From 16d0b5c228dd8d981a0d79944c70248ea813d63b Mon Sep 17 00:00:00 2001 From: ementalo Date: Wed, 27 Jun 2012 13:35:39 +0100 Subject: package name change to net.ess3 --- .../src/com/earth2me/essentials/Console.java | 33 - .../src/com/earth2me/essentials/Essentials.java | 532 ------------ .../com/earth2me/essentials/EssentialsTimer.java | 114 --- Essentials/src/com/earth2me/essentials/I18n.java | 178 ---- Essentials/src/com/earth2me/essentials/ItemDb.java | 153 ---- Essentials/src/com/earth2me/essentials/Jails.java | 353 -------- Essentials/src/com/earth2me/essentials/Kits.java | 139 --- .../src/com/earth2me/essentials/Teleport.java | 309 ------- Essentials/src/com/earth2me/essentials/Warps.java | 152 ---- .../earth2me/essentials/api/ChargeException.java | 15 - .../src/com/earth2me/essentials/api/IBackup.java | 7 - .../earth2me/essentials/api/ICommandHandler.java | 20 - .../src/com/earth2me/essentials/api/IEconomy.java | 21 - .../com/earth2me/essentials/api/IEssentials.java | 72 -- .../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 | 20 - .../src/com/earth2me/essentials/api/IKits.java | 21 - .../com/earth2me/essentials/api/IPermission.java | 17 - .../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 | 129 --- .../src/com/earth2me/essentials/api/IUserMap.java | 23 - .../src/com/earth2me/essentials/api/IWarp.java | 9 - .../src/com/earth2me/essentials/api/IWarps.java | 21 - .../src/com/earth2me/essentials/api/IWorth.java | 11 - .../essentials/api/InvalidNameException.java | 10 - .../essentials/api/NoLoanPermittedException.java | 12 - .../essentials/api/UserDoesNotExistException.java | 12 - .../essentials/api/server/IPermission.java | 5 - .../essentials/api/server/IPermissionsManager.java | 8 - .../earth2me/essentials/api/server/IPlayer.java | 5 - .../earth2me/essentials/api/server/IServer.java | 5 - .../src/com/earth2me/essentials/backup/Backup.java | 153 ---- .../earth2me/essentials/bukkit/Enchantments.java | 134 --- .../essentials/bukkit/EssentialsPlugin.java | 7 - .../src/com/earth2me/essentials/bukkit/Mob.java | 120 --- .../src/com/earth2me/essentials/bukkit/Server.java | 9 - .../earth2me/essentials/commands/Commandafk.java | 56 -- .../essentials/commands/Commandantioch.java | 23 - .../earth2me/essentials/commands/Commandback.java | 27 - .../essentials/commands/Commandbackup.java | 32 - .../essentials/commands/Commandbalance.java | 31 - .../essentials/commands/Commandbalancetop.java | 179 ---- .../earth2me/essentials/commands/Commandban.java | 69 -- .../earth2me/essentials/commands/Commandbanip.java | 39 - .../essentials/commands/Commandbigtree.java | 45 - .../earth2me/essentials/commands/Commandbreak.java | 46 - .../essentials/commands/Commandbroadcast.java | 19 - .../earth2me/essentials/commands/Commandburn.java | 24 - .../essentials/commands/Commandclearinventory.java | 93 --- .../essentials/commands/Commandcompass.java | 52 -- .../essentials/commands/Commanddelhome.java | 59 -- .../essentials/commands/Commanddeljail.java | 19 - .../essentials/commands/Commanddelwarp.java | 19 - .../earth2me/essentials/commands/Commanddepth.java | 26 - .../earth2me/essentials/commands/Commandeco.java | 119 --- .../essentials/commands/Commandenchant.java | 94 --- .../essentials/commands/Commandessentials.java | 199 ----- .../earth2me/essentials/commands/Commandexp.java | 139 --- .../earth2me/essentials/commands/Commandext.java | 43 - .../earth2me/essentials/commands/Commandfeed.java | 47 -- .../essentials/commands/Commandfireball.java | 23 - .../earth2me/essentials/commands/Commandfly.java | 72 -- .../essentials/commands/Commandgamemode.java | 66 -- .../earth2me/essentials/commands/Commandgc.java | 42 - .../essentials/commands/Commandgetpos.java | 53 -- .../earth2me/essentials/commands/Commandgive.java | 81 -- .../earth2me/essentials/commands/Commandgod.java | 67 -- .../earth2me/essentials/commands/Commandhat.java | 57 -- .../earth2me/essentials/commands/Commandheal.java | 64 -- .../earth2me/essentials/commands/Commandhelp.java | 57 -- .../essentials/commands/Commandhelpop.java | 33 - .../earth2me/essentials/commands/Commandhome.java | 108 --- .../essentials/commands/Commandignore.java | 42 - .../earth2me/essentials/commands/Commandinfo.java | 20 - .../essentials/commands/Commandinvsee.java | 19 - .../earth2me/essentials/commands/Commanditem.java | 82 -- .../essentials/commands/Commanditemdb.java | 44 - .../earth2me/essentials/commands/Commandjails.java | 14 - .../earth2me/essentials/commands/Commandjump.java | 36 - .../earth2me/essentials/commands/Commandkick.java | 39 - .../essentials/commands/Commandkickall.java | 26 - .../earth2me/essentials/commands/Commandkill.java | 32 - .../essentials/commands/Commandkillall.java | 151 ---- .../earth2me/essentials/commands/Commandkit.java | 101 --- .../essentials/commands/Commandkittycannon.java | 39 - .../essentials/commands/Commandlightning.java | 64 -- .../earth2me/essentials/commands/Commandlist.java | 166 ---- .../earth2me/essentials/commands/Commandmail.java | 165 ---- .../earth2me/essentials/commands/Commandme.java | 37 - .../earth2me/essentials/commands/Commandmore.java | 56 -- .../earth2me/essentials/commands/Commandmotd.java | 20 - .../earth2me/essentials/commands/Commandmsg.java | 98 --- .../earth2me/essentials/commands/Commandmute.java | 57 -- .../earth2me/essentials/commands/Commandnear.java | 111 --- .../earth2me/essentials/commands/Commandnick.java | 129 --- .../earth2me/essentials/commands/Commandnuke.java | 54 -- .../earth2me/essentials/commands/Commandpay.java | 44 - .../earth2me/essentials/commands/Commandping.java | 22 - .../essentials/commands/Commandpowertool.java | 109 --- .../commands/Commandpowertooltoggle.java | 23 - .../earth2me/essentials/commands/Commandptime.java | 228 ----- .../com/earth2me/essentials/commands/Commandr.java | 85 -- .../essentials/commands/Commandrealname.java | 44 - .../essentials/commands/Commandremove.java | 155 ---- .../essentials/commands/Commandrepair.java | 140 ---- .../earth2me/essentials/commands/Commandrules.java | 20 - .../earth2me/essentials/commands/Commandseen.java | 69 -- .../earth2me/essentials/commands/Commandsell.java | 152 ---- .../essentials/commands/Commandsethome.java | 95 --- .../essentials/commands/Commandsetjail.java | 21 - .../essentials/commands/Commandsetspawn.java | 17 - .../essentials/commands/Commandsetwarp.java | 50 -- .../essentials/commands/Commandsetworth.java | 50 -- .../essentials/commands/Commandsocialspy.java | 14 - .../earth2me/essentials/commands/Commandspawn.java | 55 -- .../essentials/commands/Commandspawner.java | 70 -- .../essentials/commands/Commandspawnmob.java | 297 ------- .../earth2me/essentials/commands/Commandsudo.java | 43 - .../essentials/commands/Commandsuicide.java | 20 - .../essentials/commands/Commandtempban.java | 62 -- .../essentials/commands/Commandthunder.java | 35 - .../earth2me/essentials/commands/Commandtime.java | 157 ---- .../essentials/commands/Commandtogglejail.java | 106 --- .../earth2me/essentials/commands/Commandtop.java | 21 - .../earth2me/essentials/commands/Commandtp.java | 93 --- .../earth2me/essentials/commands/Commandtpa.java | 50 -- .../essentials/commands/Commandtpaall.java | 73 -- .../essentials/commands/Commandtpaccept.java | 62 -- .../essentials/commands/Commandtpahere.java | 48 -- .../earth2me/essentials/commands/Commandtpall.java | 62 -- .../essentials/commands/Commandtpdeny.java | 22 - .../essentials/commands/Commandtphere.java | 37 - .../earth2me/essentials/commands/Commandtpo.java | 67 -- .../essentials/commands/Commandtpohere.java | 52 -- .../earth2me/essentials/commands/Commandtppos.java | 65 -- .../essentials/commands/Commandtptoggle.java | 16 - .../earth2me/essentials/commands/Commandtree.java | 69 -- .../earth2me/essentials/commands/Commandunban.java | 33 - .../essentials/commands/Commandunbanip.java | 31 - .../essentials/commands/Commandunlimited.java | 112 --- .../essentials/commands/Commandvanish.java | 37 - .../earth2me/essentials/commands/Commandwarp.java | 126 --- .../essentials/commands/Commandweather.java | 72 -- .../earth2me/essentials/commands/Commandwhois.java | 98 --- .../earth2me/essentials/commands/Commandworld.java | 81 -- .../earth2me/essentials/commands/Commandworth.java | 102 --- .../essentials/commands/EssentialsCommand.java | 132 --- .../commands/EssentialsCommandHandler.java | 316 ------- .../essentials/commands/IEssentialsCommand.java | 22 - .../essentials/commands/NoChargeException.java | 10 - .../commands/NotEnoughArgumentsException.java | 20 - .../essentials/commands/WarpNotFoundException.java | 18 - .../essentials/craftbukkit/FakeInventory.java | 243 ------ .../craftbukkit/InventoryWorkaround.java | 322 ------- .../earth2me/essentials/craftbukkit/SetExpFix.java | 65 -- .../com/earth2me/essentials/economy/Economy.java | 207 ----- .../src/com/earth2me/essentials/economy/Money.java | 17 - .../earth2me/essentials/economy/MoneyHolder.java | 36 - .../src/com/earth2me/essentials/economy/Trade.java | 357 -------- .../src/com/earth2me/essentials/economy/Worth.java | 33 - .../earth2me/essentials/economy/WorthHolder.java | 100 --- .../essentials/economy/register/Method.java | 217 ----- .../essentials/economy/register/Methods.java | 296 ------- .../essentials/economy/register/methods/BOSE6.java | 334 -------- .../essentials/economy/register/methods/BOSE7.java | 323 ------- .../essentials/economy/register/methods/MCUR.java | 195 ----- .../economy/register/methods/VaultEco.java | 347 -------- .../essentials/economy/register/methods/iCo4.java | 256 ------ .../essentials/economy/register/methods/iCo5.java | 376 --------- .../essentials/economy/register/methods/iCo6.java | 242 ------ .../listener/EssentialsBlockListener.java | 50 -- .../listener/EssentialsEntityListener.java | 176 ---- .../listener/EssentialsPlayerListener.java | 490 ----------- .../listener/EssentialsPluginListener.java | 110 --- .../essentials/listener/TntExplodeListener.java | 62 -- .../com/earth2me/essentials/metrics/Metrics.java | 625 -------------- .../essentials/metrics/MetricsListener.java | 40 - .../essentials/metrics/MetricsStarter.java | 237 ------ .../permissions/AbstractSuperpermsPermission.java | 42 - .../essentials/permissions/BasePermission.java | 16 - .../essentials/permissions/EnchantPermissions.java | 23 - .../essentials/permissions/GivePermissions.java | 30 - .../essentials/permissions/GroupsPermissions.java | 23 - .../essentials/permissions/HelpPermissions.java | 23 - .../essentials/permissions/ItemPermissions.java | 32 - .../essentials/permissions/KitPermissions.java | 31 - .../permissions/NoCommandCostPermissions.java | 23 - .../essentials/permissions/Permissions.java | 138 --- .../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 | 207 ----- .../com/earth2me/essentials/ranks/VaultGroups.java | 124 --- .../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 | 106 --- .../com/earth2me/essentials/settings/Jails.java | 18 - .../src/com/earth2me/essentials/settings/Kit.java | 20 - .../src/com/earth2me/essentials/settings/Kits.java | 28 - .../com/earth2me/essentials/settings/Settings.java | 72 -- .../essentials/settings/SettingsHolder.java | 76 -- .../com/earth2me/essentials/settings/Spawns.java | 40 - .../earth2me/essentials/settings/SpawnsHolder.java | 320 ------- .../src/com/earth2me/essentials/settings/Warp.java | 14 - .../earth2me/essentials/settings/WarpHolder.java | 48 -- .../earth2me/essentials/settings/WorldOptions.java | 16 - .../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 | 51 -- .../essentials/settings/protect/Protect.java | 52 -- .../essentials/settings/protect/SignsAndRails.java | 26 - .../storage/AbstractDelayedYamlFileReader.java | 100 --- .../storage/AbstractDelayedYamlFileWriter.java | 84 -- .../storage/AsyncStorageObjectHolder.java | 191 ----- .../essentials/storage/BukkitConstructor.java | 441 ---------- .../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 - .../com/earth2me/essentials/storage/Location.java | 115 --- .../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 | 138 --- .../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 | 20 - .../com/earth2me/essentials/user/IOfflineUser.java | 9 - .../com/earth2me/essentials/user/Inventory.java | 58 -- .../src/com/earth2me/essentials/user/User.java | 778 ----------------- .../src/com/earth2me/essentials/user/UserBase.java | 458 ---------- .../src/com/earth2me/essentials/user/UserData.java | 109 --- .../src/com/earth2me/essentials/user/UserMap.java | 97 --- .../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 | 447 ---------- .../utils/gnu/inet/encoding/Punycode.java | 321 ------- .../utils/gnu/inet/encoding/PunycodeException.java | 45 - .../utils/textreader/ArrayListInput.java | 31 - .../essentials/utils/textreader/HelpInput.java | 179 ---- .../essentials/utils/textreader/IText.java | 14 - .../utils/textreader/KeywordReplacer.java | 157 ---- .../utils/textreader/SimpleTextInput.java | 35 - .../utils/textreader/SimpleTextPager.java | 31 - .../essentials/utils/textreader/TextInput.java | 149 ---- .../essentials/utils/textreader/TextPager.java | 199 ----- Essentials/src/net/ess3/Console.java | 33 + Essentials/src/net/ess3/Essentials.java | 531 ++++++++++++ Essentials/src/net/ess3/EssentialsTimer.java | 113 +++ Essentials/src/net/ess3/I18n.java | 178 ++++ Essentials/src/net/ess3/ItemDb.java | 153 ++++ Essentials/src/net/ess3/Jails.java | 353 ++++++++ Essentials/src/net/ess3/Kits.java | 139 +++ Essentials/src/net/ess3/Teleport.java | 309 +++++++ Essentials/src/net/ess3/Warps.java | 152 ++++ Essentials/src/net/ess3/api/ChargeException.java | 15 + Essentials/src/net/ess3/api/IBackup.java | 7 + Essentials/src/net/ess3/api/ICommandHandler.java | 20 + Essentials/src/net/ess3/api/IEconomy.java | 21 + Essentials/src/net/ess3/api/IEssentials.java | 73 ++ 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 | 20 + Essentials/src/net/ess3/api/IKits.java | 21 + Essentials/src/net/ess3/api/IPermission.java | 17 + 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 | 129 +++ Essentials/src/net/ess3/api/IUserMap.java | 23 + Essentials/src/net/ess3/api/IWarp.java | 9 + Essentials/src/net/ess3/api/IWarps.java | 21 + Essentials/src/net/ess3/api/IWorth.java | 11 + .../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/IPermission.java | 5 + .../net/ess3/api/server/IPermissionsManager.java | 8 + Essentials/src/net/ess3/api/server/IPlayer.java | 5 + Essentials/src/net/ess3/api/server/IServer.java | 5 + Essentials/src/net/ess3/backup/Backup.java | 153 ++++ Essentials/src/net/ess3/bukkit/Enchantments.java | 134 +++ .../src/net/ess3/bukkit/EssentialsPlugin.java | 7 + Essentials/src/net/ess3/bukkit/Mob.java | 120 +++ Essentials/src/net/ess3/bukkit/Server.java | 9 + Essentials/src/net/ess3/commands/Commandafk.java | 56 ++ .../src/net/ess3/commands/Commandantioch.java | 23 + Essentials/src/net/ess3/commands/Commandback.java | 27 + .../src/net/ess3/commands/Commandbackup.java | 32 + .../src/net/ess3/commands/Commandbalance.java | 31 + .../src/net/ess3/commands/Commandbalancetop.java | 179 ++++ Essentials/src/net/ess3/commands/Commandban.java | 68 ++ Essentials/src/net/ess3/commands/Commandbanip.java | 39 + .../src/net/ess3/commands/Commandbigtree.java | 45 + Essentials/src/net/ess3/commands/Commandbreak.java | 44 + .../src/net/ess3/commands/Commandbroadcast.java | 19 + 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 | 59 ++ .../src/net/ess3/commands/Commanddeljail.java | 19 + .../src/net/ess3/commands/Commanddelwarp.java | 19 + Essentials/src/net/ess3/commands/Commanddepth.java | 26 + Essentials/src/net/ess3/commands/Commandeco.java | 119 +++ .../src/net/ess3/commands/Commandenchant.java | 94 +++ .../src/net/ess3/commands/Commandessentials.java | 198 +++++ Essentials/src/net/ess3/commands/Commandexp.java | 139 +++ Essentials/src/net/ess3/commands/Commandext.java | 43 + Essentials/src/net/ess3/commands/Commandfeed.java | 47 ++ .../src/net/ess3/commands/Commandfireball.java | 23 + Essentials/src/net/ess3/commands/Commandfly.java | 72 ++ .../src/net/ess3/commands/Commandgamemode.java | 66 ++ Essentials/src/net/ess3/commands/Commandgc.java | 41 + .../src/net/ess3/commands/Commandgetpos.java | 53 ++ Essentials/src/net/ess3/commands/Commandgive.java | 81 ++ Essentials/src/net/ess3/commands/Commandgod.java | 67 ++ Essentials/src/net/ess3/commands/Commandhat.java | 57 ++ Essentials/src/net/ess3/commands/Commandheal.java | 64 ++ Essentials/src/net/ess3/commands/Commandhelp.java | 57 ++ .../src/net/ess3/commands/Commandhelpop.java | 33 + Essentials/src/net/ess3/commands/Commandhome.java | 108 +++ .../src/net/ess3/commands/Commandignore.java | 42 + Essentials/src/net/ess3/commands/Commandinfo.java | 20 + .../src/net/ess3/commands/Commandinvsee.java | 19 + Essentials/src/net/ess3/commands/Commanditem.java | 82 ++ .../src/net/ess3/commands/Commanditemdb.java | 44 + Essentials/src/net/ess3/commands/Commandjails.java | 14 + Essentials/src/net/ess3/commands/Commandjump.java | 36 + Essentials/src/net/ess3/commands/Commandkick.java | 40 + .../src/net/ess3/commands/Commandkickall.java | 26 + Essentials/src/net/ess3/commands/Commandkill.java | 32 + .../src/net/ess3/commands/Commandkillall.java | 151 ++++ Essentials/src/net/ess3/commands/Commandkit.java | 99 +++ .../src/net/ess3/commands/Commandkittycannon.java | 39 + .../src/net/ess3/commands/Commandlightning.java | 64 ++ Essentials/src/net/ess3/commands/Commandlist.java | 166 ++++ Essentials/src/net/ess3/commands/Commandmail.java | 165 ++++ Essentials/src/net/ess3/commands/Commandme.java | 37 + Essentials/src/net/ess3/commands/Commandmore.java | 56 ++ Essentials/src/net/ess3/commands/Commandmotd.java | 20 + Essentials/src/net/ess3/commands/Commandmsg.java | 98 +++ Essentials/src/net/ess3/commands/Commandmute.java | 57 ++ Essentials/src/net/ess3/commands/Commandnear.java | 111 +++ Essentials/src/net/ess3/commands/Commandnick.java | 129 +++ 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 | 109 +++ .../net/ess3/commands/Commandpowertooltoggle.java | 23 + Essentials/src/net/ess3/commands/Commandptime.java | 228 +++++ Essentials/src/net/ess3/commands/Commandr.java | 85 ++ .../src/net/ess3/commands/Commandrealname.java | 44 + .../src/net/ess3/commands/Commandremove.java | 155 ++++ .../src/net/ess3/commands/Commandrepair.java | 140 ++++ Essentials/src/net/ess3/commands/Commandrules.java | 20 + Essentials/src/net/ess3/commands/Commandseen.java | 69 ++ Essentials/src/net/ess3/commands/Commandsell.java | 152 ++++ .../src/net/ess3/commands/Commandsethome.java | 95 +++ .../src/net/ess3/commands/Commandsetjail.java | 21 + .../src/net/ess3/commands/Commandsetspawn.java | 17 + .../src/net/ess3/commands/Commandsetwarp.java | 50 ++ .../src/net/ess3/commands/Commandsetworth.java | 49 ++ .../src/net/ess3/commands/Commandsocialspy.java | 14 + Essentials/src/net/ess3/commands/Commandspawn.java | 55 ++ .../src/net/ess3/commands/Commandspawner.java | 68 ++ .../src/net/ess3/commands/Commandspawnmob.java | 297 +++++++ Essentials/src/net/ess3/commands/Commandsudo.java | 43 + .../src/net/ess3/commands/Commandsuicide.java | 20 + .../src/net/ess3/commands/Commandtempban.java | 61 ++ .../src/net/ess3/commands/Commandthunder.java | 35 + Essentials/src/net/ess3/commands/Commandtime.java | 157 ++++ .../src/net/ess3/commands/Commandtogglejail.java | 105 +++ Essentials/src/net/ess3/commands/Commandtop.java | 21 + Essentials/src/net/ess3/commands/Commandtp.java | 93 +++ Essentials/src/net/ess3/commands/Commandtpa.java | 50 ++ .../src/net/ess3/commands/Commandtpaall.java | 73 ++ .../src/net/ess3/commands/Commandtpaccept.java | 62 ++ .../src/net/ess3/commands/Commandtpahere.java | 48 ++ Essentials/src/net/ess3/commands/Commandtpall.java | 62 ++ .../src/net/ess3/commands/Commandtpdeny.java | 22 + .../src/net/ess3/commands/Commandtphere.java | 37 + Essentials/src/net/ess3/commands/Commandtpo.java | 67 ++ .../src/net/ess3/commands/Commandtpohere.java | 52 ++ Essentials/src/net/ess3/commands/Commandtppos.java | 65 ++ .../src/net/ess3/commands/Commandtptoggle.java | 16 + Essentials/src/net/ess3/commands/Commandtree.java | 69 ++ Essentials/src/net/ess3/commands/Commandunban.java | 33 + .../src/net/ess3/commands/Commandunbanip.java | 31 + .../src/net/ess3/commands/Commandunlimited.java | 112 +++ .../src/net/ess3/commands/Commandvanish.java | 37 + Essentials/src/net/ess3/commands/Commandwarp.java | 126 +++ .../src/net/ess3/commands/Commandweather.java | 72 ++ Essentials/src/net/ess3/commands/Commandwhois.java | 98 +++ Essentials/src/net/ess3/commands/Commandworld.java | 81 ++ Essentials/src/net/ess3/commands/Commandworth.java | 102 +++ .../src/net/ess3/commands/EssentialsCommand.java | 132 +++ .../ess3/commands/EssentialsCommandHandler.java | 313 +++++++ .../src/net/ess3/commands/IEssentialsCommand.java | 22 + .../src/net/ess3/commands/NoChargeException.java | 10 + .../ess3/commands/NotEnoughArgumentsException.java | 20 + .../net/ess3/commands/WarpNotFoundException.java | 18 + .../src/net/ess3/craftbukkit/FakeInventory.java | 243 ++++++ .../net/ess3/craftbukkit/InventoryWorkaround.java | 322 +++++++ Essentials/src/net/ess3/craftbukkit/SetExpFix.java | 65 ++ Essentials/src/net/ess3/economy/Economy.java | 207 +++++ Essentials/src/net/ess3/economy/Money.java | 17 + Essentials/src/net/ess3/economy/MoneyHolder.java | 36 + Essentials/src/net/ess3/economy/Trade.java | 357 ++++++++ Essentials/src/net/ess3/economy/Worth.java | 33 + Essentials/src/net/ess3/economy/WorthHolder.java | 100 +++ .../src/net/ess3/economy/register/Method.java | 217 +++++ .../src/net/ess3/economy/register/Methods.java | 296 +++++++ .../net/ess3/economy/register/methods/BOSE6.java | 334 ++++++++ .../net/ess3/economy/register/methods/BOSE7.java | 323 +++++++ .../net/ess3/economy/register/methods/MCUR.java | 195 +++++ .../ess3/economy/register/methods/VaultEco.java | 347 ++++++++ .../net/ess3/economy/register/methods/iCo4.java | 256 ++++++ .../net/ess3/economy/register/methods/iCo5.java | 376 +++++++++ .../net/ess3/economy/register/methods/iCo6.java | 242 ++++++ .../net/ess3/listener/EssentialsBlockListener.java | 50 ++ .../ess3/listener/EssentialsEntityListener.java | 175 ++++ .../ess3/listener/EssentialsPlayerListener.java | 490 +++++++++++ .../ess3/listener/EssentialsPluginListener.java | 110 +++ .../src/net/ess3/listener/TntExplodeListener.java | 62 ++ Essentials/src/net/ess3/metrics/Metrics.java | 625 ++++++++++++++ .../src/net/ess3/metrics/MetricsListener.java | 37 + .../src/net/ess3/metrics/MetricsStarter.java | 237 ++++++ .../permissions/AbstractSuperpermsPermission.java | 42 + .../src/net/ess3/permissions/BasePermission.java | 16 + .../net/ess3/permissions/EnchantPermissions.java | 23 + .../src/net/ess3/permissions/GivePermissions.java | 30 + .../net/ess3/permissions/GroupsPermissions.java | 23 + .../src/net/ess3/permissions/HelpPermissions.java | 23 + .../src/net/ess3/permissions/ItemPermissions.java | 32 + .../src/net/ess3/permissions/KitPermissions.java | 31 + .../ess3/permissions/NoCommandCostPermissions.java | 23 + .../src/net/ess3/permissions/Permissions.java | 138 +++ .../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 | 207 +++++ Essentials/src/net/ess3/ranks/VaultGroups.java | 124 +++ 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 | 106 +++ Essentials/src/net/ess3/settings/Jails.java | 18 + Essentials/src/net/ess3/settings/Kit.java | 20 + Essentials/src/net/ess3/settings/Kits.java | 28 + Essentials/src/net/ess3/settings/Settings.java | 72 ++ .../src/net/ess3/settings/SettingsHolder.java | 76 ++ Essentials/src/net/ess3/settings/Spawns.java | 40 + Essentials/src/net/ess3/settings/SpawnsHolder.java | 320 +++++++ Essentials/src/net/ess3/settings/Warp.java | 14 + Essentials/src/net/ess3/settings/WarpHolder.java | 48 ++ Essentials/src/net/ess3/settings/WorldOptions.java | 16 + 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 | 51 ++ .../src/net/ess3/settings/protect/Protect.java | 52 ++ .../net/ess3/settings/protect/SignsAndRails.java | 26 + .../storage/AbstractDelayedYamlFileReader.java | 100 +++ .../storage/AbstractDelayedYamlFileWriter.java | 85 ++ .../net/ess3/storage/AsyncStorageObjectHolder.java | 191 +++++ .../src/net/ess3/storage/BukkitConstructor.java | 442 ++++++++++ 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/Location.java | 115 +++ 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 | 138 +++ .../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 | 20 + Essentials/src/net/ess3/user/IOfflineUser.java | 9 + Essentials/src/net/ess3/user/Inventory.java | 58 ++ Essentials/src/net/ess3/user/User.java | 778 +++++++++++++++++ Essentials/src/net/ess3/user/UserBase.java | 458 ++++++++++ Essentials/src/net/ess3/user/UserData.java | 109 +++ Essentials/src/net/ess3/user/UserMap.java | 97 +++ 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 | 442 ++++++++++ .../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 | 179 ++++ .../src/net/ess3/utils/textreader/IText.java | 14 + .../net/ess3/utils/textreader/KeywordReplacer.java | 157 ++++ .../net/ess3/utils/textreader/SimpleTextInput.java | 35 + .../net/ess3/utils/textreader/SimpleTextPager.java | 31 + .../src/net/ess3/utils/textreader/TextInput.java | 149 ++++ .../src/net/ess3/utils/textreader/TextPager.java | 200 +++++ Essentials/src/plugin.yml | 2 +- .../test/com/earth2me/essentials/EconomyTest.java | 116 --- .../com/earth2me/essentials/FakeOfflinePlayer.java | 100 --- .../test/com/earth2me/essentials/FakeServer.java | 928 --------------------- .../test/com/earth2me/essentials/FakeWorld.java | 678 --------------- .../test/com/earth2me/essentials/StorageTest.java | 162 ---- .../test/com/earth2me/essentials/UserTest.java | 93 --- .../test/com/earth2me/essentials/UtilTest.java | 201 ----- Essentials/test/net/ess3/EconomyTest.java | 116 +++ Essentials/test/net/ess3/FakeOfflinePlayer.java | 100 +++ Essentials/test/net/ess3/FakeServer.java | 928 +++++++++++++++++++++ Essentials/test/net/ess3/FakeWorld.java | 678 +++++++++++++++ Essentials/test/net/ess3/StorageTest.java | 162 ++++ Essentials/test/net/ess3/UserTest.java | 93 +++ Essentials/test/net/ess3/UtilTest.java | 201 +++++ .../src/com/earth2me/essentials/Economy.java | 245 ++++++ .../com/earth2me/essentials/EssentialsConf.java | 2 +- .../com/earth2me/essentials/EssentialsUpgrade.java | 17 +- .../src/com/earth2me/essentials/api/Economy.java | 242 ------ Essentials2Compat/src/plugin.yml | 2 +- .../earth2me/essentials/chat/ChatPermissions.java | 24 - .../com/earth2me/essentials/chat/ChatStore.java | 40 - .../earth2me/essentials/chat/EssentialsChat.java | 48 -- .../essentials/chat/EssentialsChatPlayer.java | 159 ---- .../essentials/chat/EssentialsLocalChatEvent.java | 111 --- .../chat/EssentialsLocalChatEventListener.java | 68 -- .../EssentialsChatPlayerListenerHighest.java | 33 - .../EssentialsChatPlayerListenerLowest.java | 36 - .../EssentialsChatPlayerListenerNormal.java | 33 - .../src/net/ess3/chat/ChatPermissions.java | 24 + EssentialsChat/src/net/ess3/chat/ChatStore.java | 40 + .../src/net/ess3/chat/EssentialsChat.java | 48 ++ .../src/net/ess3/chat/EssentialsChatPlayer.java | 159 ++++ .../net/ess3/chat/EssentialsLocalChatEvent.java | 111 +++ .../chat/EssentialsLocalChatEventListener.java | 68 ++ .../EssentialsChatPlayerListenerHighest.java | 34 + .../EssentialsChatPlayerListenerLowest.java | 38 + .../EssentialsChatPlayerListenerNormal.java | 33 + EssentialsChat/src/plugin.yml | 2 +- .../earth2me/essentials/geoip/ConfigHolder.java | 37 - .../earth2me/essentials/geoip/EssentialsGeoIP.java | 32 - .../geoip/EssentialsGeoIPPlayerListener.java | 225 ----- .../src/net/ess3/geoip/ConfigHolder.java | 37 + .../src/net/ess3/geoip/EssentialsGeoIP.java | 32 + .../ess3/geoip/EssentialsGeoIPPlayerListener.java | 225 +++++ EssentialsGeoIP/src/plugin.yml | 2 +- .../essentials/protect/BlockBreakPermissions.java | 46 - .../essentials/protect/BlockPlacePermissions.java | 46 - .../essentials/protect/EmergencyListener.java | 58 -- .../essentials/protect/EssentialsConnect.java | 124 --- .../essentials/protect/EssentialsProtect.java | 156 ---- .../protect/EssentialsProtectBlockListener.java | 514 ------------ .../protect/EssentialsProtectEntityListener.java | 322 ------- .../protect/EssentialsProtectPlayerListener.java | 97 --- .../protect/EssentialsProtectWeatherListener.java | 78 -- .../com/earth2me/essentials/protect/IProtect.java | 24 - .../essentials/protect/ItemUsePermissions.java | 45 - .../earth2me/essentials/protect/Permissions.java | 81 -- .../earth2me/essentials/protect/ProtectConfig.java | 121 --- .../earth2me/essentials/protect/ProtectHolder.java | 32 - .../essentials/protect/data/IProtectedBlock.java | 24 - .../essentials/protect/data/OwnedBlock.java | 20 - .../protect/data/ProtectedBlockJDBC.java | 434 ---------- .../protect/data/ProtectedBlockMemory.java | 258 ------ .../protect/data/ProtectedBlockMySQL.java | 160 ---- .../protect/data/ProtectedBlockSQLite.java | 108 --- .../net/ess3/protect/BlockBreakPermissions.java | 46 + .../net/ess3/protect/BlockPlacePermissions.java | 46 + .../src/net/ess3/protect/EmergencyListener.java | 58 ++ .../src/net/ess3/protect/EssentialsConnect.java | 124 +++ .../src/net/ess3/protect/EssentialsProtect.java | 157 ++++ .../protect/EssentialsProtectBlockListener.java | 515 ++++++++++++ .../protect/EssentialsProtectEntityListener.java | 322 +++++++ .../protect/EssentialsProtectPlayerListener.java | 97 +++ .../protect/EssentialsProtectWeatherListener.java | 78 ++ .../src/net/ess3/protect/IProtect.java | 24 + .../src/net/ess3/protect/ItemUsePermissions.java | 45 + .../src/net/ess3/protect/Permissions.java | 81 ++ .../src/net/ess3/protect/ProtectHolder.java | 32 + .../src/net/ess3/protect/data/IProtectedBlock.java | 24 + .../src/net/ess3/protect/data/OwnedBlock.java | 20 + .../net/ess3/protect/data/ProtectedBlockJDBC.java | 434 ++++++++++ .../ess3/protect/data/ProtectedBlockMemory.java | 258 ++++++ .../net/ess3/protect/data/ProtectedBlockMySQL.java | 160 ++++ .../ess3/protect/data/ProtectedBlockSQLite.java | 108 +++ EssentialsProtect/src/plugin.yml | 2 +- .../earth2me/essentials/signs/EssentialsSign.java | 516 ------------ .../essentials/signs/EssentialsSignsPlugin.java | 54 -- .../earth2me/essentials/signs/ISignsPlugin.java | 9 - .../com/earth2me/essentials/signs/SignBalance.java | 22 - .../essentials/signs/SignBlockListener.java | 264 ------ .../src/com/earth2me/essentials/signs/SignBuy.java | 38 - .../earth2me/essentials/signs/SignDisposal.java | 23 - .../com/earth2me/essentials/signs/SignEnchant.java | 119 --- .../essentials/signs/SignEntityListener.java | 80 -- .../earth2me/essentials/signs/SignException.java | 15 - .../com/earth2me/essentials/signs/SignFree.java | 47 -- .../earth2me/essentials/signs/SignGameMode.java | 37 - .../com/earth2me/essentials/signs/SignHeal.java | 36 - .../src/com/earth2me/essentials/signs/SignKit.java | 75 -- .../com/earth2me/essentials/signs/SignMail.java | 41 - .../essentials/signs/SignPlayerListener.java | 65 -- .../earth2me/essentials/signs/SignProtection.java | 350 -------- .../com/earth2me/essentials/signs/SignSell.java | 35 - .../earth2me/essentials/signs/SignSpawnmob.java | 48 -- .../com/earth2me/essentials/signs/SignTime.java | 57 -- .../com/earth2me/essentials/signs/SignTrade.java | 361 -------- .../com/earth2me/essentials/signs/SignWarp.java | 70 -- .../com/earth2me/essentials/signs/SignWeather.java | 55 -- .../src/com/earth2me/essentials/signs/Signs.java | 33 - .../com/earth2me/essentials/signs/SignsConfig.java | 21 - .../essentials/signs/SignsConfigHolder.java | 85 -- .../essentials/signs/SignsPermissions.java | 51 -- .../src/net/ess3/signs/EssentialsSign.java | 516 ++++++++++++ .../src/net/ess3/signs/EssentialsSignsPlugin.java | 54 ++ .../src/net/ess3/signs/ISignsPlugin.java | 9 + .../src/net/ess3/signs/SignBalance.java | 22 + .../src/net/ess3/signs/SignBlockListener.java | 264 ++++++ EssentialsSigns/src/net/ess3/signs/SignBuy.java | 38 + .../src/net/ess3/signs/SignDisposal.java | 23 + .../src/net/ess3/signs/SignEnchant.java | 119 +++ .../src/net/ess3/signs/SignEntityListener.java | 80 ++ .../src/net/ess3/signs/SignException.java | 15 + EssentialsSigns/src/net/ess3/signs/SignFree.java | 47 ++ .../src/net/ess3/signs/SignGameMode.java | 37 + EssentialsSigns/src/net/ess3/signs/SignHeal.java | 36 + EssentialsSigns/src/net/ess3/signs/SignKit.java | 75 ++ EssentialsSigns/src/net/ess3/signs/SignMail.java | 41 + .../src/net/ess3/signs/SignPlayerListener.java | 65 ++ .../src/net/ess3/signs/SignProtection.java | 350 ++++++++ EssentialsSigns/src/net/ess3/signs/SignSell.java | 35 + .../src/net/ess3/signs/SignSpawnmob.java | 48 ++ EssentialsSigns/src/net/ess3/signs/SignTime.java | 57 ++ EssentialsSigns/src/net/ess3/signs/SignTrade.java | 361 ++++++++ EssentialsSigns/src/net/ess3/signs/SignWarp.java | 70 ++ .../src/net/ess3/signs/SignWeather.java | 55 ++ EssentialsSigns/src/net/ess3/signs/Signs.java | 33 + .../src/net/ess3/signs/SignsConfig.java | 21 + .../src/net/ess3/signs/SignsConfigHolder.java | 85 ++ .../src/net/ess3/signs/SignsPermissions.java | 51 ++ EssentialsSigns/src/plugin.yml | 2 +- .../essentials/update/AbstractWorkListener.java | 39 - .../earth2me/essentials/update/EssentialsHelp.java | 171 ---- .../essentials/update/EssentialsUpdate.java | 59 -- .../com/earth2me/essentials/update/GetFile.java | 113 --- .../com/earth2me/essentials/update/ModuleInfo.java | 35 - .../earth2me/essentials/update/PastieUpload.java | 40 - .../com/earth2me/essentials/update/PostToUrl.java | 66 -- .../earth2me/essentials/update/UpdateCheck.java | 202 ----- .../com/earth2me/essentials/update/UpdateFile.java | 204 ----- .../earth2me/essentials/update/UpdateProcess.java | 199 ----- .../com/earth2me/essentials/update/Version.java | 173 ---- .../earth2me/essentials/update/VersionInfo.java | 49 -- .../update/chat/AbstractFileCommand.java | 73 -- .../earth2me/essentials/update/chat/Command.java | 9 - .../essentials/update/chat/ConfigCommand.java | 65 -- .../essentials/update/chat/ErrorsCommand.java | 71 -- .../essentials/update/chat/HelpCommand.java | 18 - .../earth2me/essentials/update/chat/IrcBot.java | 197 ----- .../essentials/update/chat/ListCommand.java | 32 - .../essentials/update/chat/StartupCommand.java | 77 -- .../essentials/update/chat/UsernameUtil.java | 124 --- .../essentials/update/states/AbstractState.java | 114 --- .../update/states/AbstractYesNoState.java | 57 -- .../essentials/update/states/AdvancedMode.java | 20 - .../essentials/update/states/Changelog.java | 91 -- .../essentials/update/states/EssentialsChat.java | 47 -- .../update/states/EssentialsChatSettings.java | 29 - .../essentials/update/states/EssentialsGeoIP.java | 47 -- .../update/states/EssentialsProtect.java | 47 -- .../update/states/InstallationFinishedEvent.java | 21 - .../essentials/update/states/StateMachine.java | 183 ---- .../essentials/update/states/StateMap.java | 12 - .../update/states/UpdateOrInstallation.java | 60 -- .../essentials/update/tasks/InstallModule.java | 61 -- .../essentials/update/tasks/SelfUpdate.java | 55 -- .../com/earth2me/essentials/update/tasks/Task.java | 7 - .../src/net/ess3/update/AbstractWorkListener.java | 39 + .../src/net/ess3/update/EssentialsHelp.java | 171 ++++ .../src/net/ess3/update/EssentialsUpdate.java | 59 ++ EssentialsUpdate/src/net/ess3/update/GetFile.java | 113 +++ .../src/net/ess3/update/ModuleInfo.java | 35 + .../src/net/ess3/update/PastieUpload.java | 40 + .../src/net/ess3/update/PostToUrl.java | 66 ++ .../src/net/ess3/update/UpdateCheck.java | 202 +++++ .../src/net/ess3/update/UpdateFile.java | 204 +++++ .../src/net/ess3/update/UpdateProcess.java | 199 +++++ EssentialsUpdate/src/net/ess3/update/Version.java | 173 ++++ .../src/net/ess3/update/VersionInfo.java | 49 ++ .../net/ess3/update/chat/AbstractFileCommand.java | 75 ++ .../src/net/ess3/update/chat/Command.java | 9 + .../src/net/ess3/update/chat/ConfigCommand.java | 65 ++ .../src/net/ess3/update/chat/ErrorsCommand.java | 71 ++ .../src/net/ess3/update/chat/HelpCommand.java | 18 + .../src/net/ess3/update/chat/IrcBot.java | 197 +++++ .../src/net/ess3/update/chat/ListCommand.java | 32 + .../src/net/ess3/update/chat/StartupCommand.java | 77 ++ .../src/net/ess3/update/chat/UsernameUtil.java | 124 +++ .../src/net/ess3/update/states/AbstractState.java | 115 +++ .../net/ess3/update/states/AbstractYesNoState.java | 57 ++ .../src/net/ess3/update/states/AdvancedMode.java | 20 + .../src/net/ess3/update/states/Changelog.java | 91 ++ .../src/net/ess3/update/states/EssentialsChat.java | 47 ++ .../ess3/update/states/EssentialsChatSettings.java | 29 + .../net/ess3/update/states/EssentialsGeoIP.java | 48 ++ .../net/ess3/update/states/EssentialsProtect.java | 48 ++ .../update/states/InstallationFinishedEvent.java | 21 + .../src/net/ess3/update/states/StateMachine.java | 185 ++++ .../src/net/ess3/update/states/StateMap.java | 12 + .../ess3/update/states/UpdateOrInstallation.java | 61 ++ .../src/net/ess3/update/tasks/InstallModule.java | 65 ++ .../src/net/ess3/update/tasks/SelfUpdate.java | 56 ++ .../src/net/ess3/update/tasks/Task.java | 7 + EssentialsUpdate/src/plugin.yml | 2 +- .../com/earth2me/essentials/update/UploadTest.java | 27 - .../earth2me/essentials/update/VersionTest.java | 86 -- .../test/com/ess3/update/UploadTest.java | 28 + .../test/com/ess3/update/VersionTest.java | 87 ++ .../earth2me/essentials/xmpp/Commandsetxmpp.java | 21 - .../com/earth2me/essentials/xmpp/Commandxmpp.java | 36 - .../earth2me/essentials/xmpp/Commandxmppspy.java | 40 - .../earth2me/essentials/xmpp/EssentialsXMPP.java | 150 ---- .../xmpp/EssentialsXMPPPlayerListener.java | 58 -- .../earth2me/essentials/xmpp/IEssentialsXMPP.java | 28 - .../com/earth2me/essentials/xmpp/UserManager.java | 100 --- .../com/earth2me/essentials/xmpp/XMPPManager.java | 375 --------- .../src/net/ess3/xmpp/Commandsetxmpp.java | 21 + EssentialsXMPP/src/net/ess3/xmpp/Commandxmpp.java | 36 + .../src/net/ess3/xmpp/Commandxmppspy.java | 40 + .../src/net/ess3/xmpp/EssentialsXMPP.java | 150 ++++ .../ess3/xmpp/EssentialsXMPPPlayerListener.java | 58 ++ .../src/net/ess3/xmpp/IEssentialsXMPP.java | 28 + EssentialsXMPP/src/net/ess3/xmpp/UserManager.java | 100 +++ EssentialsXMPP/src/net/ess3/xmpp/XMPPManager.java | 375 +++++++++ EssentialsXMPP/src/plugin.yml | 4 +- 791 files changed, 37243 insertions(+), 37361 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/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/IPermission.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/server/IPermissionsManager.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/server/IPlayer.java delete mode 100644 Essentials/src/com/earth2me/essentials/api/server/IServer.java delete mode 100644 Essentials/src/com/earth2me/essentials/backup/Backup.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/Mob.java delete mode 100644 Essentials/src/com/earth2me/essentials/bukkit/Server.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/Commandexp.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/Commandfly.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/Commandhat.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/Commandvanish.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/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/metrics/Metrics.java delete mode 100644 Essentials/src/com/earth2me/essentials/metrics/MetricsListener.java delete mode 100644 Essentials/src/com/earth2me/essentials/metrics/MetricsStarter.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/Location.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/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/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/IBackup.java create mode 100644 Essentials/src/net/ess3/api/ICommandHandler.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/IPermission.java create mode 100644 Essentials/src/net/ess3/api/server/IPermissionsManager.java create mode 100644 Essentials/src/net/ess3/api/server/IPlayer.java create mode 100644 Essentials/src/net/ess3/api/server/IServer.java create mode 100644 Essentials/src/net/ess3/backup/Backup.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/Mob.java create mode 100644 Essentials/src/net/ess3/bukkit/Server.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/Commandexp.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/Commandfly.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/Commandhat.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/Commandvanish.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/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/metrics/Metrics.java create mode 100644 Essentials/src/net/ess3/metrics/MetricsListener.java create mode 100644 Essentials/src/net/ess3/metrics/MetricsStarter.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/Location.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/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/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 Essentials/test/com/earth2me/essentials/EconomyTest.java delete mode 100644 Essentials/test/com/earth2me/essentials/FakeOfflinePlayer.java delete mode 100644 Essentials/test/com/earth2me/essentials/FakeServer.java delete mode 100644 Essentials/test/com/earth2me/essentials/FakeWorld.java delete mode 100644 Essentials/test/com/earth2me/essentials/StorageTest.java delete mode 100644 Essentials/test/com/earth2me/essentials/UserTest.java delete mode 100644 Essentials/test/com/earth2me/essentials/UtilTest.java create mode 100644 Essentials/test/net/ess3/EconomyTest.java create mode 100644 Essentials/test/net/ess3/FakeOfflinePlayer.java create mode 100644 Essentials/test/net/ess3/FakeServer.java create mode 100644 Essentials/test/net/ess3/FakeWorld.java create mode 100644 Essentials/test/net/ess3/StorageTest.java create mode 100644 Essentials/test/net/ess3/UserTest.java create mode 100644 Essentials/test/net/ess3/UtilTest.java create mode 100644 Essentials2Compat/src/com/earth2me/essentials/Economy.java delete mode 100644 Essentials2Compat/src/com/earth2me/essentials/api/Economy.java delete mode 100644 EssentialsChat/src/com/earth2me/essentials/chat/ChatPermissions.java delete mode 100644 EssentialsChat/src/com/earth2me/essentials/chat/ChatStore.java delete mode 100644 EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChat.java delete mode 100644 EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayer.java delete mode 100644 EssentialsChat/src/com/earth2me/essentials/chat/EssentialsLocalChatEvent.java delete mode 100644 EssentialsChat/src/com/earth2me/essentials/chat/EssentialsLocalChatEventListener.java delete mode 100644 EssentialsChat/src/com/earth2me/essentials/chat/listenerlevel/EssentialsChatPlayerListenerHighest.java delete mode 100644 EssentialsChat/src/com/earth2me/essentials/chat/listenerlevel/EssentialsChatPlayerListenerLowest.java delete mode 100644 EssentialsChat/src/com/earth2me/essentials/chat/listenerlevel/EssentialsChatPlayerListenerNormal.java create mode 100644 EssentialsChat/src/net/ess3/chat/ChatPermissions.java create mode 100644 EssentialsChat/src/net/ess3/chat/ChatStore.java create mode 100644 EssentialsChat/src/net/ess3/chat/EssentialsChat.java create mode 100644 EssentialsChat/src/net/ess3/chat/EssentialsChatPlayer.java create mode 100644 EssentialsChat/src/net/ess3/chat/EssentialsLocalChatEvent.java create mode 100644 EssentialsChat/src/net/ess3/chat/EssentialsLocalChatEventListener.java create mode 100644 EssentialsChat/src/net/ess3/chat/listenerlevel/EssentialsChatPlayerListenerHighest.java create mode 100644 EssentialsChat/src/net/ess3/chat/listenerlevel/EssentialsChatPlayerListenerLowest.java create mode 100644 EssentialsChat/src/net/ess3/chat/listenerlevel/EssentialsChatPlayerListenerNormal.java delete mode 100644 EssentialsGeoIP/src/com/earth2me/essentials/geoip/ConfigHolder.java delete mode 100644 EssentialsGeoIP/src/com/earth2me/essentials/geoip/EssentialsGeoIP.java delete mode 100644 EssentialsGeoIP/src/com/earth2me/essentials/geoip/EssentialsGeoIPPlayerListener.java create mode 100644 EssentialsGeoIP/src/net/ess3/geoip/ConfigHolder.java create mode 100644 EssentialsGeoIP/src/net/ess3/geoip/EssentialsGeoIP.java create mode 100644 EssentialsGeoIP/src/net/ess3/geoip/EssentialsGeoIPPlayerListener.java delete mode 100644 EssentialsProtect/src/com/earth2me/essentials/protect/BlockBreakPermissions.java delete mode 100644 EssentialsProtect/src/com/earth2me/essentials/protect/BlockPlacePermissions.java delete mode 100644 EssentialsProtect/src/com/earth2me/essentials/protect/EmergencyListener.java delete mode 100644 EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsConnect.java delete mode 100644 EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtect.java delete mode 100644 EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectBlockListener.java delete mode 100644 EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectEntityListener.java delete mode 100644 EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectPlayerListener.java delete mode 100644 EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectWeatherListener.java delete mode 100644 EssentialsProtect/src/com/earth2me/essentials/protect/IProtect.java delete mode 100644 EssentialsProtect/src/com/earth2me/essentials/protect/ItemUsePermissions.java delete mode 100644 EssentialsProtect/src/com/earth2me/essentials/protect/Permissions.java delete mode 100644 EssentialsProtect/src/com/earth2me/essentials/protect/ProtectConfig.java delete mode 100644 EssentialsProtect/src/com/earth2me/essentials/protect/ProtectHolder.java delete mode 100644 EssentialsProtect/src/com/earth2me/essentials/protect/data/IProtectedBlock.java delete mode 100644 EssentialsProtect/src/com/earth2me/essentials/protect/data/OwnedBlock.java delete mode 100644 EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockJDBC.java delete mode 100644 EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockMemory.java delete mode 100644 EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockMySQL.java delete mode 100644 EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockSQLite.java create mode 100644 EssentialsProtect/src/net/ess3/protect/BlockBreakPermissions.java create mode 100644 EssentialsProtect/src/net/ess3/protect/BlockPlacePermissions.java create mode 100644 EssentialsProtect/src/net/ess3/protect/EmergencyListener.java create mode 100644 EssentialsProtect/src/net/ess3/protect/EssentialsConnect.java create mode 100644 EssentialsProtect/src/net/ess3/protect/EssentialsProtect.java create mode 100644 EssentialsProtect/src/net/ess3/protect/EssentialsProtectBlockListener.java create mode 100644 EssentialsProtect/src/net/ess3/protect/EssentialsProtectEntityListener.java create mode 100644 EssentialsProtect/src/net/ess3/protect/EssentialsProtectPlayerListener.java create mode 100644 EssentialsProtect/src/net/ess3/protect/EssentialsProtectWeatherListener.java create mode 100644 EssentialsProtect/src/net/ess3/protect/IProtect.java create mode 100644 EssentialsProtect/src/net/ess3/protect/ItemUsePermissions.java create mode 100644 EssentialsProtect/src/net/ess3/protect/Permissions.java create mode 100644 EssentialsProtect/src/net/ess3/protect/ProtectHolder.java create mode 100644 EssentialsProtect/src/net/ess3/protect/data/IProtectedBlock.java create mode 100644 EssentialsProtect/src/net/ess3/protect/data/OwnedBlock.java create mode 100644 EssentialsProtect/src/net/ess3/protect/data/ProtectedBlockJDBC.java create mode 100644 EssentialsProtect/src/net/ess3/protect/data/ProtectedBlockMemory.java create mode 100644 EssentialsProtect/src/net/ess3/protect/data/ProtectedBlockMySQL.java create mode 100644 EssentialsProtect/src/net/ess3/protect/data/ProtectedBlockSQLite.java delete mode 100644 EssentialsSigns/src/com/earth2me/essentials/signs/EssentialsSign.java delete mode 100644 EssentialsSigns/src/com/earth2me/essentials/signs/EssentialsSignsPlugin.java delete mode 100644 EssentialsSigns/src/com/earth2me/essentials/signs/ISignsPlugin.java delete mode 100644 EssentialsSigns/src/com/earth2me/essentials/signs/SignBalance.java delete mode 100644 EssentialsSigns/src/com/earth2me/essentials/signs/SignBlockListener.java delete mode 100644 EssentialsSigns/src/com/earth2me/essentials/signs/SignBuy.java delete mode 100644 EssentialsSigns/src/com/earth2me/essentials/signs/SignDisposal.java delete mode 100644 EssentialsSigns/src/com/earth2me/essentials/signs/SignEnchant.java delete mode 100644 EssentialsSigns/src/com/earth2me/essentials/signs/SignEntityListener.java delete mode 100644 EssentialsSigns/src/com/earth2me/essentials/signs/SignException.java delete mode 100644 EssentialsSigns/src/com/earth2me/essentials/signs/SignFree.java delete mode 100644 EssentialsSigns/src/com/earth2me/essentials/signs/SignGameMode.java delete mode 100644 EssentialsSigns/src/com/earth2me/essentials/signs/SignHeal.java delete mode 100644 EssentialsSigns/src/com/earth2me/essentials/signs/SignKit.java delete mode 100644 EssentialsSigns/src/com/earth2me/essentials/signs/SignMail.java delete mode 100644 EssentialsSigns/src/com/earth2me/essentials/signs/SignPlayerListener.java delete mode 100644 EssentialsSigns/src/com/earth2me/essentials/signs/SignProtection.java delete mode 100644 EssentialsSigns/src/com/earth2me/essentials/signs/SignSell.java delete mode 100644 EssentialsSigns/src/com/earth2me/essentials/signs/SignSpawnmob.java delete mode 100644 EssentialsSigns/src/com/earth2me/essentials/signs/SignTime.java delete mode 100644 EssentialsSigns/src/com/earth2me/essentials/signs/SignTrade.java delete mode 100644 EssentialsSigns/src/com/earth2me/essentials/signs/SignWarp.java delete mode 100644 EssentialsSigns/src/com/earth2me/essentials/signs/SignWeather.java delete mode 100644 EssentialsSigns/src/com/earth2me/essentials/signs/Signs.java delete mode 100644 EssentialsSigns/src/com/earth2me/essentials/signs/SignsConfig.java delete mode 100644 EssentialsSigns/src/com/earth2me/essentials/signs/SignsConfigHolder.java delete mode 100644 EssentialsSigns/src/com/earth2me/essentials/signs/SignsPermissions.java create mode 100644 EssentialsSigns/src/net/ess3/signs/EssentialsSign.java create mode 100644 EssentialsSigns/src/net/ess3/signs/EssentialsSignsPlugin.java create mode 100644 EssentialsSigns/src/net/ess3/signs/ISignsPlugin.java create mode 100644 EssentialsSigns/src/net/ess3/signs/SignBalance.java create mode 100644 EssentialsSigns/src/net/ess3/signs/SignBlockListener.java create mode 100644 EssentialsSigns/src/net/ess3/signs/SignBuy.java create mode 100644 EssentialsSigns/src/net/ess3/signs/SignDisposal.java create mode 100644 EssentialsSigns/src/net/ess3/signs/SignEnchant.java create mode 100644 EssentialsSigns/src/net/ess3/signs/SignEntityListener.java create mode 100644 EssentialsSigns/src/net/ess3/signs/SignException.java create mode 100644 EssentialsSigns/src/net/ess3/signs/SignFree.java create mode 100644 EssentialsSigns/src/net/ess3/signs/SignGameMode.java create mode 100644 EssentialsSigns/src/net/ess3/signs/SignHeal.java create mode 100644 EssentialsSigns/src/net/ess3/signs/SignKit.java create mode 100644 EssentialsSigns/src/net/ess3/signs/SignMail.java create mode 100644 EssentialsSigns/src/net/ess3/signs/SignPlayerListener.java create mode 100644 EssentialsSigns/src/net/ess3/signs/SignProtection.java create mode 100644 EssentialsSigns/src/net/ess3/signs/SignSell.java create mode 100644 EssentialsSigns/src/net/ess3/signs/SignSpawnmob.java create mode 100644 EssentialsSigns/src/net/ess3/signs/SignTime.java create mode 100644 EssentialsSigns/src/net/ess3/signs/SignTrade.java create mode 100644 EssentialsSigns/src/net/ess3/signs/SignWarp.java create mode 100644 EssentialsSigns/src/net/ess3/signs/SignWeather.java create mode 100644 EssentialsSigns/src/net/ess3/signs/Signs.java create mode 100644 EssentialsSigns/src/net/ess3/signs/SignsConfig.java create mode 100644 EssentialsSigns/src/net/ess3/signs/SignsConfigHolder.java create mode 100644 EssentialsSigns/src/net/ess3/signs/SignsPermissions.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/AbstractWorkListener.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/EssentialsHelp.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/EssentialsUpdate.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/GetFile.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/ModuleInfo.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/PastieUpload.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/PostToUrl.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/UpdateCheck.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/UpdateFile.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/UpdateProcess.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/Version.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/VersionInfo.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/chat/AbstractFileCommand.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/chat/Command.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/chat/ConfigCommand.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/chat/ErrorsCommand.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/chat/HelpCommand.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/chat/IrcBot.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/chat/ListCommand.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/chat/StartupCommand.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/chat/UsernameUtil.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/states/AbstractState.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/states/AbstractYesNoState.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/states/AdvancedMode.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/states/Changelog.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/states/EssentialsChat.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/states/EssentialsChatSettings.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/states/EssentialsGeoIP.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/states/EssentialsProtect.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/states/InstallationFinishedEvent.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/states/StateMachine.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/states/StateMap.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/states/UpdateOrInstallation.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/tasks/InstallModule.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/tasks/SelfUpdate.java delete mode 100644 EssentialsUpdate/src/com/earth2me/essentials/update/tasks/Task.java create mode 100644 EssentialsUpdate/src/net/ess3/update/AbstractWorkListener.java create mode 100644 EssentialsUpdate/src/net/ess3/update/EssentialsHelp.java create mode 100644 EssentialsUpdate/src/net/ess3/update/EssentialsUpdate.java create mode 100644 EssentialsUpdate/src/net/ess3/update/GetFile.java create mode 100644 EssentialsUpdate/src/net/ess3/update/ModuleInfo.java create mode 100644 EssentialsUpdate/src/net/ess3/update/PastieUpload.java create mode 100644 EssentialsUpdate/src/net/ess3/update/PostToUrl.java create mode 100644 EssentialsUpdate/src/net/ess3/update/UpdateCheck.java create mode 100644 EssentialsUpdate/src/net/ess3/update/UpdateFile.java create mode 100644 EssentialsUpdate/src/net/ess3/update/UpdateProcess.java create mode 100644 EssentialsUpdate/src/net/ess3/update/Version.java create mode 100644 EssentialsUpdate/src/net/ess3/update/VersionInfo.java create mode 100644 EssentialsUpdate/src/net/ess3/update/chat/AbstractFileCommand.java create mode 100644 EssentialsUpdate/src/net/ess3/update/chat/Command.java create mode 100644 EssentialsUpdate/src/net/ess3/update/chat/ConfigCommand.java create mode 100644 EssentialsUpdate/src/net/ess3/update/chat/ErrorsCommand.java create mode 100644 EssentialsUpdate/src/net/ess3/update/chat/HelpCommand.java create mode 100644 EssentialsUpdate/src/net/ess3/update/chat/IrcBot.java create mode 100644 EssentialsUpdate/src/net/ess3/update/chat/ListCommand.java create mode 100644 EssentialsUpdate/src/net/ess3/update/chat/StartupCommand.java create mode 100644 EssentialsUpdate/src/net/ess3/update/chat/UsernameUtil.java create mode 100644 EssentialsUpdate/src/net/ess3/update/states/AbstractState.java create mode 100644 EssentialsUpdate/src/net/ess3/update/states/AbstractYesNoState.java create mode 100644 EssentialsUpdate/src/net/ess3/update/states/AdvancedMode.java create mode 100644 EssentialsUpdate/src/net/ess3/update/states/Changelog.java create mode 100644 EssentialsUpdate/src/net/ess3/update/states/EssentialsChat.java create mode 100644 EssentialsUpdate/src/net/ess3/update/states/EssentialsChatSettings.java create mode 100644 EssentialsUpdate/src/net/ess3/update/states/EssentialsGeoIP.java create mode 100644 EssentialsUpdate/src/net/ess3/update/states/EssentialsProtect.java create mode 100644 EssentialsUpdate/src/net/ess3/update/states/InstallationFinishedEvent.java create mode 100644 EssentialsUpdate/src/net/ess3/update/states/StateMachine.java create mode 100644 EssentialsUpdate/src/net/ess3/update/states/StateMap.java create mode 100644 EssentialsUpdate/src/net/ess3/update/states/UpdateOrInstallation.java create mode 100644 EssentialsUpdate/src/net/ess3/update/tasks/InstallModule.java create mode 100644 EssentialsUpdate/src/net/ess3/update/tasks/SelfUpdate.java create mode 100644 EssentialsUpdate/src/net/ess3/update/tasks/Task.java delete mode 100644 EssentialsUpdate/test/com/earth2me/essentials/update/UploadTest.java delete mode 100644 EssentialsUpdate/test/com/earth2me/essentials/update/VersionTest.java create mode 100644 EssentialsUpdate/test/com/ess3/update/UploadTest.java create mode 100644 EssentialsUpdate/test/com/ess3/update/VersionTest.java delete mode 100644 EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandsetxmpp.java delete mode 100644 EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandxmpp.java delete mode 100644 EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandxmppspy.java delete mode 100644 EssentialsXMPP/src/com/earth2me/essentials/xmpp/EssentialsXMPP.java delete mode 100644 EssentialsXMPP/src/com/earth2me/essentials/xmpp/EssentialsXMPPPlayerListener.java delete mode 100644 EssentialsXMPP/src/com/earth2me/essentials/xmpp/IEssentialsXMPP.java delete mode 100644 EssentialsXMPP/src/com/earth2me/essentials/xmpp/UserManager.java delete mode 100644 EssentialsXMPP/src/com/earth2me/essentials/xmpp/XMPPManager.java create mode 100644 EssentialsXMPP/src/net/ess3/xmpp/Commandsetxmpp.java create mode 100644 EssentialsXMPP/src/net/ess3/xmpp/Commandxmpp.java create mode 100644 EssentialsXMPP/src/net/ess3/xmpp/Commandxmppspy.java create mode 100644 EssentialsXMPP/src/net/ess3/xmpp/EssentialsXMPP.java create mode 100644 EssentialsXMPP/src/net/ess3/xmpp/EssentialsXMPPPlayerListener.java create mode 100644 EssentialsXMPP/src/net/ess3/xmpp/IEssentialsXMPP.java create mode 100644 EssentialsXMPP/src/net/ess3/xmpp/UserManager.java create mode 100644 EssentialsXMPP/src/net/ess3/xmpp/XMPPManager.java diff --git a/Essentials/src/com/earth2me/essentials/Console.java b/Essentials/src/com/earth2me/essentials/Console.java deleted file mode 100644 index 2e43883cf..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 org.bukkit.command.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 1095443c5..000000000 --- a/Essentials/src/com/earth2me/essentials/Essentials.java +++ /dev/null @@ -1,532 +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.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.metrics.Metrics; -import com.earth2me.essentials.metrics.MetricsListener; -import com.earth2me.essentials.metrics.MetricsStarter; -import com.earth2me.essentials.ranks.RanksStorage; -import com.earth2me.essentials.settings.SettingsHolder; -import com.earth2me.essentials.settings.SpawnsHolder; -import com.earth2me.essentials.user.IOfflinePlayer; -import com.earth2me.essentials.user.User; -import com.earth2me.essentials.user.UserMap; -import com.earth2me.essentials.utils.ExecuteTimer; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import lombok.Getter; -import org.bukkit.Server; -import org.bukkit.World; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -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.InvalidDescriptionException; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginDescriptionFile; -import org.bukkit.plugin.PluginManager; -import org.bukkit.plugin.java.JavaPlugin; -import org.yaml.snakeyaml.error.YAMLException; - - -public class Essentials extends JavaPlugin implements IEssentials -{ - public static final int BUKKIT_VERSION = 2149; - private static final Logger LOGGER = Logger.getLogger("Minecraft"); - 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; - private transient I18n i18n; - private transient ICommandHandler commandHandler; - private transient Economy economy; - public transient boolean testing; - private transient Metrics metrics; - @Getter - private transient EssentialsTimer timer; - @Getter - private transient List vanishedPlayers = new ArrayList(); - - @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(); - } - i18n = new I18n(this); - i18n.onEnable(); - 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(); - i18n = new I18n(this); - i18n.onEnable(); - execTimer.mark("I18n1"); - final PluginManager pm = getServer().getPluginManager(); - for (Plugin plugin : pm.getPlugins()) - { - if (plugin.getDescription().getName().startsWith("Essentials") - && !plugin.getDescription().getVersion().equals(this.getDescription().getVersion()) - && !plugin.getDescription().getName().equals("EssentialsAntiCheat")) - { - LOGGER.log(Level.WARNING, _("versionMismatch", plugin.getDescription().getName())); - } - } - final Matcher versionMatch = Pattern.compile("git-Bukkit-(?:(?:[0-9]+)\\.)+[0-9]+-R[\\.0-9]+-(?:[0-9]+-g[0-9a-f]+-)?b([0-9]+)jnks.*").matcher(getServer().getVersion()); - if (versionMatch.matches()) - { - final int versionNumber = Integer.parseInt(versionMatch.group(1)); - if (versionNumber < BUKKIT_VERSION && versionNumber > 100) - { - LOGGER.log(Level.SEVERE, " * ! * ! * ! * ! * ! * ! * ! * ! * ! * ! * ! * ! *"); - LOGGER.log(Level.SEVERE, _("notRecommendedBukkit")); - LOGGER.log(Level.SEVERE, _("requiredBukkit", Integer.toString(BUKKIT_VERSION))); - LOGGER.log(Level.SEVERE, " * ! * ! * ! * ! * ! * ! * ! * ! * ! * ! * ! * ! *"); - this.setEnabled(false); - return; - } - } - else - { - LOGGER.log(Level.INFO, _("bukkitFormatChanged")); - LOGGER.log(Level.INFO, getServer().getVersion()); - LOGGER.log(Level.INFO, getServer().getBukkitVersion()); - } - 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); - reload(); - } - 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); - - - timer = new EssentialsTimer(this); - getServer().getScheduler().scheduleSyncRepeatingTask(this, timer, 1, 100); - execTimer.mark("RegListeners"); - - final MetricsStarter metricsStarter = new MetricsStarter(this); - if (metricsStarter.getStart() != null && metricsStarter.getStart() == true) - { - getServer().getScheduler().scheduleAsyncDelayedTask(this, metricsStarter, 1); - } - else if (metricsStarter.getStart() != null && metricsStarter.getStart() == false) - { - final MetricsListener metricsListener = new MetricsListener(this, metricsStarter); - pm.registerEvents(metricsListener, this); - } - - final String timeroutput = execTimer.end(); - if (getSettings().isDebug()) - { - LOGGER.log(Level.INFO, "Essentials load {0}", timeroutput); - } - } - - @Override - public void onDisable() - { - for (Player p : getServer().getOnlinePlayers()) - { - IUser user = getUser(p); - if (user.isVanished()) - { - user.toggleVanished(); - p.sendMessage(_("unvanishedReload")); - } - } - i18n.onDisable(); - Trade.closeLog(); - } - - @Override - public void reload() - { - Trade.closeLog(); - - for (IReload iReload : reloadList) - { - iReload.onReload(); - execTimer.mark("Reload(" + iReload.getClass().getSimpleName() + ")"); - } - - i18n.updateLocale(settings.getLocale()); - } - - @Override - public boolean onCommand(final CommandSender sender, final Command command, final String commandLabel, final String[] args) - { - return commandHandler.handleCommand(sender, command, commandLabel, args); - //return onCommandEssentials(sender, command, commandLabel, args, Essentials.class.getClassLoader(), "com.earth2me.essentials.commands.Command", "essentials.", null); - } - - @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; - } - - public Metrics getMetrics() - { - return metrics; - } - - public void setMetrics(Metrics metrics) - { - this.metrics = metrics; - } - - @Override - public IUser getUser(final Object base) - { - if (base instanceof Player) - { - return getUser((Player)base); - } - if (base instanceof String) - { - final IUser user = userMap.getUser((String)base); - if (user != null && user.getBase() instanceof IOfflinePlayer) - { - ((IOfflinePlayer)user.getBase()).setName((String)base); - } - return user; - } - return null; - } - - private IUser getUser(final T base) - { - if (base == null) - { - return null; - } - - if (base instanceof IUser) - { - return (IUser)base; - } - IUser user = userMap.getUser(base.getName()); - - if (user == null) - { - user = new User(base, this); - } - else - { - //todo - fix this - user.update(base); - } - return user; - } - - /*@Override - public IUser getUser(final Player player) - { - return userMap.getUser(player); - } - - @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; - } - final Player[] players = getServer().getOnlinePlayers(); - - for (Player player : players) - { - final IUser user = getUser(player); - if (!user.isIgnoringPlayer(sender)) - { - player.sendMessage(message); - } - } - - return players.length; - } - - @Override - public int scheduleAsyncDelayedTask(final Runnable run) - { - return this.getServer().getScheduler().scheduleAsyncDelayedTask(this, run); - } - - @Override - public int scheduleSyncDelayedTask(final Runnable run) - { - return this.getServer().getScheduler().scheduleSyncDelayedTask(this, run); - } - - @Override - public int scheduleSyncDelayedTask(final Runnable run, final long delay) - { - return this.getServer().getScheduler().scheduleSyncDelayedTask(this, run, delay); - } - - @Override - public int scheduleSyncRepeatingTask(final Runnable run, final long delay, final long period) - { - return this.getServer().getScheduler().scheduleSyncRepeatingTask(this, run, delay, period); - } - - @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 I18n getI18n() - { - return i18n; - } - - @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 6874c069c..000000000 --- a/Essentials/src/com/earth2me/essentials/EssentialsTimer.java +++ /dev/null @@ -1,114 +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.permissions.Permissions; -import com.earth2me.essentials.user.UserData.TimestampType; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -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(); - private transient long lastPoll = System.currentTimeMillis(); - private final transient LinkedList history = new LinkedList(); - - EssentialsTimer(final IEssentials ess) - { - this.ess = ess; - } - - @Override - public void run() - { - final long currentTime = System.currentTimeMillis(); - long timeSpent = (currentTime - lastPoll) / 1000; - if (timeSpent == 0) - { - timeSpent = 1; - } - if (history.size() > 10) - { - history.remove(); - } - float tps = 100f / timeSpent; - if (tps <= 20) - { - history.add(tps); - } - lastPoll = currentTime; - for (Player player : ess.getServer().getOnlinePlayers()) - { - - try - { - final IUser user = ess.getUser(player); - 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); - user.resetInvulnerabilityAfterTeleport(); - } - } - - public float getAverageTPS() - { - float avg = 0; - for (Float f : history) - { - if (f != null) - { - avg += f; - } - } - return avg / history.size(); - } -} diff --git a/Essentials/src/com/earth2me/essentials/I18n.java b/Essentials/src/com/earth2me/essentials/I18n.java deleted file mode 100644 index de4afec94..000000000 --- a/Essentials/src/com/earth2me/essentials/I18n.java +++ /dev/null @@ -1,178 +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]); - } - ResourceBundle.clearCache(); - 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.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 cfcc00dd2..000000000 --- a/Essentials/src/com/earth2me/essentials/ItemDb.java +++ /dev/null @@ -1,153 +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.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; -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; - - -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.getMaterial(itemname) != null) - { - itemid = Material.getMaterial(itemname).getId(); - metaData = 0; - } - else - { - throw new Exception(_("unknownItemName", id)); - } - } - - final Material mat = Material.getMaterial(itemid); - if (mat == null) - { - throw new Exception(_("unknownItemId", itemid)); - } - final ItemStack retval = new ItemStack(mat); - retval.setAmount(mat.getMaxStackSize()); - retval.setDurability(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 b23e1bb10..000000000 --- a/Essentials/src/com/earth2me/essentials/Jails.java +++ /dev/null @@ -1,353 +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.entity.Entity; -import org.bukkit.entity.EntityType; -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.entity.EntityDamageByEntityEvent; -import org.bukkit.event.entity.EntityDamageEvent.DamageCause; -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(); - private static transient boolean enabled = false; - - public Jails(final IEssentials ess) - { - super(ess, com.earth2me.essentials.settings.Jails.class); - onReload(); - } - - private void registerListeners() - { - enabled = true; - final PluginManager pluginManager = ess.getServer().getPluginManager(); - final JailListener blockListener = new JailListener(); - pluginManager.registerEvents(blockListener, ess); - } - - @Override - public File getStorageFile() - { - return new File(ess.getDataFolder(), "jail.yml"); - } - - @Override - public void finishRead() - { - if (enabled == false && getCount() > 0) - { - registerListeners(); - } - } - - @Override - public void finishWrite() - { - if (enabled == false) - { - registerListeners(); - } - } - - @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)).getBukkitLocation(); - 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.Location(loc)); - } - finally - { - unlock(); - } - } - - @Override - public int getCount() - { - try - { - return getList().size(); - } - catch (Exception ex) - { - return 0; - } - } - - - private class JailListener 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); - } - } - - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onEntityDamageByEntity(final EntityDamageByEntityEvent event) - { - if (event.getCause() != DamageCause.ENTITY_ATTACK || event.getEntity().getType() != EntityType.PLAYER) - { - return; - } - final Entity damager = event.getDamager(); - if (damager.getType() == EntityType.PLAYER) - { - final IUser user = ess.getUser(damager); - if (user != null && 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 806266d32..000000000 --- a/Essentials/src/com/earth2me/essentials/Kits.java +++ /dev/null @@ -1,139 +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.commands.NoChargeException; -import com.earth2me.essentials.settings.Kit; -import com.earth2me.essentials.storage.AsyncStorageObjectHolder; -import com.earth2me.essentials.user.UserData.TimestampType; -import com.earth2me.essentials.utils.DateUtil; -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.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(); - } - - @Override - public void finishRead() - { - } - - @Override - public void finishWrite() - { - } - - @Override - public void checkTime(final IUser user, Kit kit) throws NoChargeException - { - final Calendar time = new GregorianCalendar(); - // Take the current time, and remove the delay from it. - final double delay = kit.getDelay(); - final Calendar earliestTime = new GregorianCalendar(); - earliestTime.add(Calendar.SECOND, -(int)delay); - earliestTime.add(Calendar.MILLISECOND, -(int)((delay * 1000.0) % 1000.0)); - - // This value contains the most recent time a kit could have been used that would allow another use. - - final long earliestLong = earliestTime.getTimeInMillis(); - - // When was the last kit used? - final Long lastTime = user.getTimestamp(TimestampType.KIT); - if (lastTime == null || lastTime < earliestLong) - { - user.setTimestamp(TimestampType.KIT, time.getTimeInMillis()); - } - else if (lastTime > time.getTimeInMillis()) - { - // This is to make sure time didn't get messed up on last kit use. - // If this happens, let's give the user the benifit of the doubt. - user.setTimestamp(TimestampType.KIT, time.getTimeInMillis()); - } - else - { - time.setTimeInMillis(lastTime); - time.add(Calendar.SECOND, (int)delay); - time.add(Calendar.MILLISECOND, (int)((delay * 1000.0) % 1000.0)); - user.sendMessage(_("kitTimed", DateUtil.formatDateDiff(time.getTimeInMillis()))); - throw new NoChargeException(); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/Teleport.java b/Essentials/src/com/earth2me/essentials/Teleport.java deleted file mode 100644 index 0a97fbc5b..000000000 --- a/Essentials/src/com/earth2me/essentials/Teleport.java +++ /dev/null @@ -1,309 +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.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.Location; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.player.PlayerRespawnEvent; -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 Entity entity; - - public Target(Location location) - { - this.location = location; - this.entity = null; - } - - public Target(Entity 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.getBase(), "teleport", ex); - } - } - catch (Exception ex) - { - user.sendMessage(_("cooldownWithMessage", ex.getMessage())); - } - } - } - - public Teleport(IUser user, IEssentials ess) - { - this.user = user; - this.ess = ess; - } - - @Override - public void respawn(final Trade chargeFor, TeleportCause cause) throws Exception - { - final Player player = user.getBase(); - final Location bed = player.getBedSpawnLocation(); - final PlayerRespawnEvent pre = new PlayerRespawnEvent(player, bed == null ? player.getWorld().getSpawnLocation() : bed, bed != null); - ess.getServer().getPluginManager().callEvent(pre); - teleport(new Target(pre.getRespawnLocation()), chargeFor, cause); - } - - @Override - 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.getServer().getScheduler().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); - } - - @Override - public void teleport(Location loc, Trade chargeFor, TeleportCause cause) throws Exception - { - teleport(new Target(loc), chargeFor, cause); - } - - @Override - public void teleport(Entity 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 tDelay = ess.getRanks().getTeleportDelay(user); - - if (chargeFor != null) - { - chargeFor.isAffordableFor(user); - } - cooldown(true); - if (tDelay <= 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)tDelay); - c.add(Calendar.MILLISECOND, (int)((tDelay * 1000.0) % 1000.0)); - user.sendMessage(_("dontMoveMessage", DateUtil.formatDateDiff(c.getTimeInMillis()))); - initTimer((long)(tDelay * 1000.0), target, chargeFor, cause); - - teleTimer = ess.scheduleSyncRepeatingTask(this, 10, 10); - } - - private void now(Target target, TeleportCause cause) throws Exception - { - cancel(); - user.setLastLocation(); - user.getBase().teleport(LocationUtil.getSafeDestination(target.getLocation()), cause); - } - - @Override - 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); - } - - @Override - public void now(Entity entity, boolean cooldown, TeleportCause cause) throws Exception - { - if (cooldown) - { - cooldown(false); - } - now(new Target(entity), cause); - } - - @Override - public void back(Trade chargeFor) throws Exception - { - user.acquireReadLock(); - try - { - teleport(new Target(user.getData().getLastLocation().getBukkitLocation()), chargeFor, TeleportCause.COMMAND); - } - finally - { - user.unlock(); - } - } - - @Override - public void back() throws Exception - { - user.acquireReadLock(); - try - { - now(new Target(user.getData().getLastLocation().getBukkitLocation()), TeleportCause.COMMAND); - } - finally - { - user.unlock(); - } - } - - @Override - public void home(Location loc, Trade chargeFor) throws Exception - { - 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 bbf01678b..000000000 --- a/Essentials/src/com/earth2me/essentials/Warps.java +++ /dev/null @@ -1,152 +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.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; -import org.bukkit.Bukkit; -import org.bukkit.Location; - - -public class Warps extends StorageObjectMap implements IWarps -{ - private static final Logger logger = Bukkit.getLogger(); - - 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().getBukkitLocation(); - } - finally - { - warp.unlock(); - } - } - - @Override - public void setWarp(final String name, final Location loc) throws Exception - { - setWarp(name, new com.earth2me.essentials.storage.Location(loc)); - } - - public void setWarp(final String name, final com.earth2me.essentials.storage.Location 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 f756c16c4..000000000 --- a/Essentials/src/com/earth2me/essentials/api/ICommandHandler.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.earth2me.essentials.api; - -import java.util.Map; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -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/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 488b1aceb..000000000 --- a/Essentials/src/com/earth2me/essentials/api/IEssentials.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.earth2me.essentials.api; - -import com.earth2me.essentials.EssentialsTimer; -import com.earth2me.essentials.economy.register.Methods; -import com.earth2me.essentials.listener.TntExplodeListener; -import com.earth2me.essentials.metrics.Metrics; -import java.util.List; -import org.bukkit.World; -import org.bukkit.plugin.Plugin; - - -public interface IEssentials extends Plugin -{ - void addReloadListener(IReload listener); - - IUser getUser(final Object base); - - 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(); - - List getVanishedPlayers(); - - EssentialsTimer getTimer(); - - Metrics getMetrics(); - - void setMetrics(Metrics metrics); -} 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 29f97488c..000000000 --- a/Essentials/src/com/earth2me/essentials/api/IItemDb.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.earth2me.essentials.api; - -import org.bukkit.inventory.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 fb8d2f090..000000000 --- a/Essentials/src/com/earth2me/essentials/api/IJails.java +++ /dev/null @@ -1,20 +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; - - int getCount(); - - 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 33d0de153..000000000 --- a/Essentials/src/com/earth2me/essentials/api/IKits.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.earth2me.essentials.api; - -import com.earth2me.essentials.commands.NoChargeException; -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(); - - void checkTime(final IUser user, Kit kit) throws NoChargeException; -} 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 d388bff47..000000000 --- a/Essentials/src/com/earth2me/essentials/api/IPermission.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.earth2me.essentials.api; - -import org.bukkit.command.CommandSender; -import org.bukkit.permissions.Permission; -import org.bukkit.permissions.PermissionDefault; - - -public interface IPermission -{ - String getPermission(); - - boolean isAuthorized(CommandSender sender); - - Permission getBukkitPermission(); - - PermissionDefault 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 3003ca3df..000000000 --- a/Essentials/src/com/earth2me/essentials/api/IReplyTo.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.earth2me.essentials.api; - -import org.bukkit.command.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 16c05a917..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(Location loc, Trade chargeFor) 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 fa54ffd21..000000000 --- a/Essentials/src/com/earth2me/essentials/api/IUser.java +++ /dev/null @@ -1,129 +0,0 @@ -package com.earth2me.essentials.api; - -import com.earth2me.essentials.storage.IStorageObjectHolder; -import com.earth2me.essentials.user.CooldownException; -import com.earth2me.essentials.user.UserData; -import java.util.List; -import org.bukkit.Location; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - - -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(); - - void setDisplayNick(); - - 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(IUser user); - - void setIgnoredPlayer(IUser user, boolean set); - - Location getAfkPosition(); - - void dispose(); - - void updateCompass(); - - List getHomes(); - - void addMail(String string); - - void setMuted(boolean mute); - - boolean toggleSocialSpy(); - - void requestTeleport(IUser user, boolean b); - - boolean isTpRequestHere(); - - 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); - - boolean isVanished(); - - void resetInvulnerabilityAfterTeleport(); - - void toggleVanished(); - - boolean isInvSee(); - - void setInvSee(boolean invsee); - - boolean hasInvulnerabilityAfterTeleport(); - - void update(final Player base); - - void setGodModeEnabled(boolean set); - - void setVanished(boolean set); - -} 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 fbe6cfa0e..000000000 --- a/Essentials/src/com/earth2me/essentials/api/IUserMap.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.earth2me.essentials.api; - -import java.io.File; -import java.util.Set; -import org.bukkit.entity.Player; - - -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; -} 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 2a98ecc64..000000000 --- a/Essentials/src/com/earth2me/essentials/api/IWarps.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.earth2me.essentials.api; - -import java.io.File; -import java.util.Collection; -import org.bukkit.Location; - - -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 4add98771..000000000 --- a/Essentials/src/com/earth2me/essentials/api/IWorth.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.earth2me.essentials.api; - -import org.bukkit.inventory.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/IPermission.java b/Essentials/src/com/earth2me/essentials/api/server/IPermission.java deleted file mode 100644 index 3b5cf2eb4..000000000 --- a/Essentials/src/com/earth2me/essentials/api/server/IPermission.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.earth2me.essentials.api.server; - -public interface IPermission { - -} diff --git a/Essentials/src/com/earth2me/essentials/api/server/IPermissionsManager.java b/Essentials/src/com/earth2me/essentials/api/server/IPermissionsManager.java deleted file mode 100644 index d8f017e20..000000000 --- a/Essentials/src/com/earth2me/essentials/api/server/IPermissionsManager.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.earth2me.essentials.api.server; - -public interface IPermissionsManager { - - IPermission registerPermission(); - - boolean checkPermission(IPlayer player, IPermission perm); -} diff --git a/Essentials/src/com/earth2me/essentials/api/server/IPlayer.java b/Essentials/src/com/earth2me/essentials/api/server/IPlayer.java deleted file mode 100644 index 7d0899e81..000000000 --- a/Essentials/src/com/earth2me/essentials/api/server/IPlayer.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.earth2me.essentials.api.server; - -public interface IPlayer { - -} 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 2c267b6cb..000000000 --- a/Essentials/src/com/earth2me/essentials/api/server/IServer.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.earth2me.essentials.api.server; - -public interface IServer { - -} 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 2da391af9..000000000 --- a/Essentials/src/com/earth2me/essentials/backup/Backup.java +++ /dev/null @@ -1,153 +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 java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.logging.Level; -import java.util.logging.Logger; -import lombok.Cleanup; -import org.bukkit.Bukkit; -import org.bukkit.Server; -import org.bukkit.command.CommandSender; - - -public class Backup implements Runnable, IBackup -{ - private static final Logger LOGGER = Bukkit.getLogger(); - private transient final Server 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().length > 0) - { - 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.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; - } - LOGGER.log(Level.INFO, _("backupStarted")); - final CommandSender consoleSender = server.getConsoleSender(); - server.dispatchCommand(consoleSender, "save-all"); - server.dispatchCommand(consoleSender, "save-off"); - - ess.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.getDataFolder().getParentFile().getParentFile()); - 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) - { - LOGGER.log(Level.INFO, line); - } - } - while (line != null); - } - finally - { - reader.close(); - } - } - catch (InterruptedException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - catch (IOException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - finally - { - ess.scheduleSyncDelayedTask(new EnableSavingRunner()); - } - } - } - - - private class EnableSavingRunner implements Runnable - { - @Override - public void run() - { - server.dispatchCommand(server.getConsoleSender(), "save-on"); - if (server.getOnlinePlayers().length == 0) - { - running.set(false); - if (taskId != -1) - { - server.getScheduler().cancelTask(taskId); - } - } - - active.set(false); - LOGGER.log(Level.INFO, _("backupFinished")); - } - } -} 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 5cbff9919..000000000 --- a/Essentials/src/com/earth2me/essentials/bukkit/Enchantments.java +++ /dev/null @@ -1,134 +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("sharp", Enchantment.DAMAGE_ALL); - - ENCHANTMENTS.put("arthropodsdamage", Enchantment.DAMAGE_ARTHROPODS); - ENCHANTMENTS.put("ardmg", Enchantment.DAMAGE_ARTHROPODS); - ENCHANTMENTS.put("baneofarthropods", Enchantment.DAMAGE_ARTHROPODS); - ENCHANTMENTS.put("baneofarthropod", Enchantment.DAMAGE_ARTHROPODS); - ENCHANTMENTS.put("arthropod", 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("minespeed", Enchantment.DIG_SPEED); - ENCHANTMENTS.put("cutspeed", 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("meleefire", Enchantment.FIRE_ASPECT); - ENCHANTMENTS.put("meleeflame", 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("breathing", Enchantment.OXYGEN); - ENCHANTMENTS.put("breath", Enchantment.OXYGEN); - - ENCHANTMENTS.put("protection", Enchantment.PROTECTION_ENVIRONMENTAL); - ENCHANTMENTS.put("prot", Enchantment.PROTECTION_ENVIRONMENTAL); - ENCHANTMENTS.put("protect", Enchantment.PROTECTION_ENVIRONMENTAL); - - ENCHANTMENTS.put("explosionsprotection", Enchantment.PROTECTION_EXPLOSIONS); - ENCHANTMENTS.put("explosionprotection", Enchantment.PROTECTION_EXPLOSIONS); - ENCHANTMENTS.put("expprot", Enchantment.PROTECTION_EXPLOSIONS); - ENCHANTMENTS.put("blastprotection", Enchantment.PROTECTION_EXPLOSIONS); - ENCHANTMENTS.put("blastprotect", Enchantment.PROTECTION_EXPLOSIONS); - - ENCHANTMENTS.put("fallprotection", Enchantment.PROTECTION_FALL); - ENCHANTMENTS.put("fallprot", Enchantment.PROTECTION_FALL); - ENCHANTMENTS.put("featherfall", Enchantment.PROTECTION_FALL); - ENCHANTMENTS.put("featherfalling", Enchantment.PROTECTION_FALL); - - ENCHANTMENTS.put("fireprotection", Enchantment.PROTECTION_FIRE); - ENCHANTMENTS.put("flameprotection", Enchantment.PROTECTION_FIRE); - ENCHANTMENTS.put("fireprotect", Enchantment.PROTECTION_FIRE); - ENCHANTMENTS.put("flameprotect", Enchantment.PROTECTION_FIRE); - - ENCHANTMENTS.put("projectileprotection", Enchantment.PROTECTION_PROJECTILE); - ENCHANTMENTS.put("projprot", Enchantment.PROTECTION_PROJECTILE); - - ENCHANTMENTS.put("silktouch", Enchantment.SILK_TOUCH); - ENCHANTMENTS.put("softtouch", Enchantment.SILK_TOUCH); - - ENCHANTMENTS.put("waterworker", Enchantment.WATER_WORKER); - ENCHANTMENTS.put("aquaaffinity", Enchantment.WATER_WORKER); - - ENCHANTMENTS.put("firearrow", Enchantment.ARROW_FIRE); - ENCHANTMENTS.put("flame", Enchantment.ARROW_FIRE); - ENCHANTMENTS.put("flamearrow", Enchantment.ARROW_FIRE); - - ENCHANTMENTS.put("arrowdamage", Enchantment.ARROW_DAMAGE); - ENCHANTMENTS.put("power", Enchantment.ARROW_DAMAGE); - ENCHANTMENTS.put("arrowpower", Enchantment.ARROW_DAMAGE); - - ENCHANTMENTS.put("arrowknockback", Enchantment.ARROW_KNOCKBACK); - ENCHANTMENTS.put("arrowkb", Enchantment.ARROW_KNOCKBACK); - ENCHANTMENTS.put("punch", Enchantment.ARROW_KNOCKBACK); - ENCHANTMENTS.put("arrowpunch", Enchantment.ARROW_KNOCKBACK); - - ENCHANTMENTS.put("infinitearrows", Enchantment.ARROW_INFINITE); - ENCHANTMENTS.put("infarrows", Enchantment.ARROW_INFINITE); - ENCHANTMENTS.put("infinity", Enchantment.ARROW_INFINITE); - ENCHANTMENTS.put("infinite", Enchantment.ARROW_INFINITE); - ENCHANTMENTS.put("unlimited", Enchantment.ARROW_INFINITE); - ENCHANTMENTS.put("unlimitedarrows", 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 f58f2e5b6..000000000 --- a/Essentials/src/com/earth2me/essentials/bukkit/EssentialsPlugin.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.earth2me.essentials.bukkit; - -import org.bukkit.plugin.java.JavaPlugin; - -public class EssentialsPlugin extends JavaPlugin { - //TODO -} 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/Server.java b/Essentials/src/com/earth2me/essentials/bukkit/Server.java deleted file mode 100644 index 1c10d9a7b..000000000 --- a/Essentials/src/com/earth2me/essentials/bukkit/Server.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.earth2me.essentials.bukkit; - -import com.earth2me.essentials.api.server.IServer; -import lombok.Delegate; - -public class Server implements IServer { - @Delegate - private org.bukkit.Server server; -} 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 a571ec652..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandafk.java +++ /dev/null @@ -1,56 +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) - { - user.setDisplayNick(); - 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 d325b7f6a..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandback.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.economy.Trade; -import com.earth2me.essentials.permissions.WorldPermissions; - - -public class Commandback extends EssentialsCommand -{ - @Override - protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - final String worldName = user.getData().getLastLocation().getWorldName(); - if (user.getWorld() != user.getData().getLastLocation().getBukkitLocation().getWorld() && ess.getSettings().getData().getGeneral().isWorldTeleportPermissions() - && WorldPermissions.getPermission(worldName).isAuthorized(user)) - { - throw new Exception(_("noPerm", "essentials.world." + worldName)); - } - //tod - verify - final Trade charge = new Trade(this.toString(), 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 6ea8aec87..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbackup.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IBackup; -import com.earth2me.essentials.api.ISettings; -import lombok.Cleanup; -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(); - if (backup == null) - { - throw new Exception(_("backupDisabled")); - } - - @Cleanup - ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - final String command = settings.getData().getGeneral().getBackup().getCommand(); - if (command == null || "".equals(command) || "save-all".equalsIgnoreCase(command)) - { - throw new Exception(_("backupDisabled")); - } - 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 c8491a2c0..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbalance.java +++ /dev/null @@ -1,31 +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 com.earth2me.essentials.utils.Util; -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 1508a134f..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbalancetop.java +++ /dev/null @@ -1,179 +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.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.scheduleAsyncDelayedTask(new Viewer(sender, page, force)); - } - else - { - if (ess.getUserMap().getUniqueUsers() > MINUSERS) - { - sender.sendMessage(_("orderBalances", ess.getUserMap().getUniqueUsers())); - } - ess.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.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.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 1bf3bded2..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandban.java +++ /dev/null @@ -1,69 +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 org.bukkit.Server; -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 - public 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 (sender instanceof Player && Permissions.BAN_OFFLINE.isAuthorized(user)) - { - sender.sendMessage(_("banExempt")); - return; - } - } - else - { - if (Permissions.BAN_EXEMPT.isAuthorized(sender)) - { - sender.sendMessage(_("banExempt")); - return; - } - } - - user.acquireWriteLock(); - final String senderName = sender instanceof Player ? ((Player)sender).getDisplayName() : Console.NAME; - String banReason; - user.getData().setBan(new Ban()); - if (args.length > 1) - { - - banReason = _("banFormat", getFinalArg(args, 1), senderName); - user.getData().getBan().setReason(banReason); - } - else - { - banReason = _("banFormat", _("defaultBanReason"), senderName); - user.getData().getBan().setReason(""); - } - - user.setBanned(true); - user.kickPlayer(banReason); - 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/Commandbanip.java b/Essentials/src/com/earth2me/essentials/commands/Commandbanip.java deleted file mode 100644 index c9d4caa89..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbanip.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 lombok.Cleanup; -import org.bukkit.command.CommandSender; - - -public class Commandbanip extends EssentialsCommand -{ - @Override - public 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 aa5645c85..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbigtree.java +++ /dev/null @@ -1,45 +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 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 if (args.length > 0 && args[0].equalsIgnoreCase("jungle")) - { - tree = TreeType.JUNGLE; - } - 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 6d2d7bb04..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbreak.java +++ /dev/null @@ -1,46 +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 java.util.ArrayList; -import java.util.List; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.inventory.ItemStack; - - -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 List list = (List)block.getDrops(); - //final BlockBreakEvent event = new BlockBreakEvent(block, user.getBase(), list); - 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 df2c5e114..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbroadcast.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.utils.Util; -import org.bukkit.command.CommandSender; - - -public class Commandbroadcast extends EssentialsCommand -{ - @Override - public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - ess.broadcastMessage(null, _("broadcast", Util.replaceFormat(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 08b8739b5..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 org.bukkit.command.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 fea6c024f..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.permissions.Permissions; -import java.util.List; -import org.bukkit.command.CommandSender; -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 629d00592..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commanddelhome.java +++ /dev/null @@ -1,59 +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.Locale; -import lombok.Cleanup; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - - -public class Commanddelhome extends EssentialsCommand -{ - @Override - public 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 9daae2fad..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commanddeljail.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -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 482652b15..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commanddelwarp.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import org.bukkit.command.CommandSender; - - -public class Commanddelwarp extends EssentialsCommand -{ - @Override - public 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 3269d2114..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandeco.java +++ /dev/null @@ -1,119 +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 java.util.Locale; -import lombok.Cleanup; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - - -public class Commandeco extends EssentialsCommand -{ - @Override - public 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 = ess.getUser(onlinePlayer); - 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 c6b0967c0..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandessentials.java +++ /dev/null @@ -1,199 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.metrics.Metrics; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.command.CommandSender; -import org.bukkit.command.ConsoleCommandSender; -import org.bukkit.entity.Player; - - -public class Commandessentials extends EssentialsCommand -{ - private transient int taskid; - private final transient Map noteBlocks = new HashMap(); - - @Override - public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length == 0) { - run_disabled(sender, commandLabel, args); - } - else if (args[0].equalsIgnoreCase("debug")) - { - run_debug(sender, commandLabel, args); - } - else if (args[0].equalsIgnoreCase("nya")) - { - run_nya(sender, commandLabel, args); - } - else if (args[0].equalsIgnoreCase("moo")) - { - run_moo(sender, commandLabel, args); - } - else if (args[0].equalsIgnoreCase("opt-out")) - { - run_optout(sender, commandLabel, args); - } - else { - run_reload(sender, commandLabel, args); - } - } - - private void run_disabled(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - sender.sendMessage("Essentials " + ess.getDescription().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()); - } - - if (disabledCommands.length() > 0) { - sender.sendMessage(_("blockList")); - sender.sendMessage(disabledCommands.toString()); - } - } - - private void run_debug(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - ess.getSettings().setDebug(!ess.getSettings().isDebug()); - sender.sendMessage("Essentials " + ess.getDescription().getVersion() + " debug mode " + (ess.getSettings().isDebug() ? "enabled" : "disabled")); - } - - private void run_reload(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - ess.reload(); - sender.sendMessage(_("essentialsReload", ess.getDescription().getVersion())); - } - - private void run_nya(final CommandSender sender, final String commandLabel, 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()); - loc.getBlock().setType(Material.NOTE_BLOCK); - } - } - taskid = ess.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() - { - server.getScheduler().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 command, final String args[]) - { - if(sender instanceof ConsoleCommandSender) - sender.sendMessage(new String[]{" (__)", " (oo)", " /------\\/", " / | ||", " * /\\---/\\", " ~~ ~~", "....\"Have you mooed today?\"..." } ); - else - sender.sendMessage(new String[]{" (__)", " (oo)", " /------\\/", " / | | |", " * /\\---/\\", " ~~ ~~", "....\"Have you mooed today?\"..." } ); - } - - private void run_optout(final CommandSender sender, final String command, final String args[]) - { - final Metrics metrics = ess.getMetrics(); - try - { - sender.sendMessage("Essentials collects simple metrics to highlight which features to concentrate work on in the future."); - if (metrics.isOptOut()) { - metrics.enable(); - } else { - metrics.disable(); - } - sender.sendMessage("Anonymous Metrics are now: " + (metrics.isOptOut() ? "disabled" : "enabled")); - } - catch (IOException ex) - { - sender.sendMessage("Unable to modify 'plugins/PluginMetrics/config.yml': " + ex.getMessage()); - } - } -} \ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandexp.java b/Essentials/src/com/earth2me/essentials/commands/Commandexp.java deleted file mode 100644 index 081ef6bc3..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandexp.java +++ /dev/null @@ -1,139 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.craftbukkit.SetExpFix; -import com.earth2me.essentials.permissions.Permissions; -import com.earth2me.essentials.utils.Util; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - - -public class Commandexp extends EssentialsCommand -{ - @Override - public void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - - if (args.length == 0) - { - showExp(user, user); - } - else if (args[0].equalsIgnoreCase("set") && Permissions.EXP_SET.isAuthorized(user)) - { - if (args.length == 3 && Permissions.EXP_SET_OTHERS.isAuthorized(user)) - { - expMatch(user, args[1], args[2], false); - } - else - { - setExp(user, user, args[1], false); - } - } - else if (args[0].equalsIgnoreCase("give") && Permissions.EXP_GIVE.isAuthorized(user)) - { - if (args.length == 3 && Permissions.EXP_GIVE_OTHERS.isAuthorized(user)) - { - expMatch(user, args[1], args[2], true); - } - else - { - setExp(user, user, args[1], true); - } - } - else - { - String match = args[0].trim(); - if (args.length == 2) - { - match = args[1].trim(); - } - if (match.equalsIgnoreCase("show") || !Permissions.EXP_OTHERS.isAuthorized(user)) - { - showExp(user, user); - } - else - { - showMatch(user, match); - } - } - } - - - public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - else if (args.length > 2 && args[0].equalsIgnoreCase("set")) - { - expMatch(sender, args[1], args[2], false); - } - else if (args.length > 2 && args[0].equalsIgnoreCase("give")) - { - expMatch(sender, args[1], args[2], true); - } - else - { - String match = args[0].trim(); - if (args.length == 2) - { - match = args[1].trim(); - } - showMatch(sender, match); - } - } - - private void showMatch(final CommandSender sender, final String match) throws NotEnoughArgumentsException - { - boolean foundUser = false; - for (Player matchPlayer : server.matchPlayer(match)) - { - foundUser = true; - final IUser target = ess.getUser(matchPlayer); - showExp(sender, target); - } - if (!foundUser) - { - throw new NotEnoughArgumentsException(_("playerNotFound")); - } - } - - private void expMatch(final CommandSender sender, final String match, final String amount, final boolean toggle) throws NotEnoughArgumentsException - { - boolean foundUser = false; - for (Player matchPlayer : server.matchPlayer(match)) - { - final IUser target = ess.getUser(matchPlayer); - setExp(sender, target, amount, toggle); - foundUser = true; - } - if (!foundUser) - { - throw new NotEnoughArgumentsException(_("playerNotFound")); - } - } - - private void showExp(final CommandSender sender, final IUser target) - { - final int totalExp = SetExpFix.getTotalExperience(target); - final int expLeft = (int)Util.roundDouble(((((3.5 * target.getLevel()) + 6.7) - (totalExp - ((1.75 * (target.getLevel() * target.getLevel())) + (5.00 * target.getLevel())))) + 1)); - sender.sendMessage(_("exp", target.getDisplayName(), SetExpFix.getTotalExperience(target), target.getLevel(), expLeft)); - } - - private void setExp(final CommandSender sender, final IUser target, final String strAmount, final boolean give) - { - Long amount = Long.parseLong(strAmount); - if (give) - { - amount += SetExpFix.getTotalExperience(target); - } - if (amount > Integer.MAX_VALUE) - { - amount = (long)Integer.MAX_VALUE; - } - SetExpFix.setTotalExperience(target, amount.intValue()); - sender.sendMessage(_("expSet", target.getDisplayName(), amount)); - } -} \ No newline at end of file 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 8e689506a..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 org.bukkit.command.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 e7c8f9fe4..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandfeed.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.permissions.Permissions; -import java.util.List; -import org.bukkit.command.CommandSender; -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 CommandSender 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/Commandfly.java b/Essentials/src/com/earth2me/essentials/commands/Commandfly.java deleted file mode 100644 index 93498e2d6..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandfly.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.permissions.Permissions; -import org.bukkit.Server; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - - -public class Commandfly extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - - flyOtherPlayers(server, sender, args); - } - - @Override - protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length > 0 && args[0].trim().length() > 2 && Permissions.FLY_OTHERS.isAuthorized(user)) - { - flyOtherPlayers(server, user, args); - return; - } - user.setAllowFlight(!user.getAllowFlight()); - if (!user.getAllowFlight()) - { - user.setFlying(false); - } - user.sendMessage(_("flyMode", _(user.getAllowFlight() ? "enabled" : "disabled"), user.getDisplayName())); - } - - private void flyOtherPlayers(final Server server, final CommandSender sender, final String[] args) - { - for (Player matchPlayer : server.matchPlayer(args[0])) - { - final IUser player = ess.getUser(matchPlayer); - if (player.isHidden()) - { - continue; - } - if (args.length > 1) - { - if (args[1].contains("on") || args[1].contains("ena") || args[1].equalsIgnoreCase("1")) - { - player.setAllowFlight(true); - } - else - { - player.setAllowFlight(false); - } - } - else - { - player.setAllowFlight(!player.getAllowFlight()); - } - - if (!player.getAllowFlight()) - { - player.setFlying(false); - } - sender.sendMessage(_("flyMode", _(player.getAllowFlight() ? "enabled" : "disabled"), player.getDisplayName())); - } - } -} 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 83a2577d6..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandgamemode.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.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); - } - - @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); - 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 args[]) - { - for (Player matchPlayer : server.matchPlayer(args[0])) - { - final IUser player = ess.getUser(matchPlayer); - if (player.isHidden()) - { - continue; - } - - if (args.length > 1) - { - if (args[1].contains("creat") || args[1].equalsIgnoreCase("1")) - { - player.setGameMode(GameMode.CREATIVE); - } - else - { - player.setGameMode(GameMode.SURVIVAL); - } - } - else - { - 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 4097c5e83..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandgc.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import org.bukkit.ChatColor; -import org.bukkit.Server; -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 - { - float tps = ess.getTimer().getAverageTPS(); - ChatColor color; - if (tps >= 18) - { - color = ChatColor.GREEN; - } - else if (tps >= 15) - { - color = ChatColor.YELLOW; - } - else - { - color = ChatColor.RED; - } - sender.sendMessage(_("tps", "" + color + tps)); - 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 c31c76d3c..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandgetpos.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.earth2me.essentials.commands; - -import com.earth2me.essentials.api.IUser; -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)) - { - //todo permissions - final IUser otherUser = getPlayer(args, 0); - if (!otherUser.isHidden() || Permissions.LIST_HIDDEN.isAuthorized(user)) - { - outputPosition(user, otherUser.getLocation(), user.getLocation()); - return; - } - - } - 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 f0f0380ac..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandgive.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.permissions.GivePermissions; -import com.earth2me.essentials.utils.Util; -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 -{ - @Override - public 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 > 3 && Util.isInt(args[2]) && Util.isInt(args[3])) - { - stack.setAmount(Integer.parseInt(args[2])); - stack.setDurability(Short.parseShort(args[3])); - } - else if (args.length > 2 && Integer.parseInt(args[2]) > 0) - { - stack.setAmount(Integer.parseInt(args[2])); - } - - if (args.length > 3) - { - for (int i = Util.isInt(args[3]) ? 4 : 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); - - //TODO: TL this. - 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 e23553036..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandgod.java +++ /dev/null @@ -1,67 +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.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); - } - - @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); - return; - } - - user.setGodModeEnabled(!user.isGodModeEnabled()); - user.sendMessage(_("godMode", (user.isGodModeEnabled() ? _("enabled") : _("disabled")))); - } - - private void godOtherPlayers(final CommandSender sender, final String[] args) - { - for (Player matchPlayer : server.matchPlayer(args[0])) - { - final IUser player = ess.getUser(matchPlayer); - if (player.isHidden()) - { - continue; - } - - if (args.length > 1) - { - if (args[1].contains("on") || args[1].contains("ena") || args[1].equalsIgnoreCase("1")) - { - player.setGodModeEnabled(true); - } - else - { - player.setGodModeEnabled(false); - } - } - else - { - player.setGodModeEnabled(!player.isGodModeEnabled()); - } - - final boolean enabled = player.isGodModeEnabled(); - player.sendMessage(_("godMode", (enabled ? _("enabled") : _("disabled")))); - sender.sendMessage(_("godMode", _(enabled ? "godEnabledFor" : "godDisabledFor", matchPlayer.getDisplayName()))); - } - } -} diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandhat.java b/Essentials/src/com/earth2me/essentials/commands/Commandhat.java deleted file mode 100644 index 91108225c..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandhat.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.craftbukkit.InventoryWorkaround; -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.PlayerInventory; - - -public class Commandhat extends EssentialsCommand -{ - @Override - protected void run(IUser user, String commandLabel, String[] args) throws Exception - { - if (args.length > 0 && (args[0].contains("rem") || args[0].contains("off") || args[0].equalsIgnoreCase("0"))) - { - final PlayerInventory inv = user.getInventory(); - final ItemStack head = inv.getHelmet(); - if (head == null || head.getType() == Material.AIR) - { - user.sendMessage(_("hatEmpty")); - } - else - { - final ItemStack air = new ItemStack(Material.AIR); - inv.setHelmet(air); - InventoryWorkaround.addItem(user.getInventory(), true, head); - user.sendMessage(_("hatRemoved")); - } - } - else - { - if (user.getItemInHand().getType() != Material.AIR) - { - final ItemStack hand = user.getItemInHand(); - if (hand.getType().getMaxDurability() == 0) - { - final PlayerInventory inv = user.getInventory(); - final ItemStack head = inv.getHelmet(); - inv.removeItem(hand); - inv.setHelmet(hand); - inv.setItemInHand(head); - user.sendMessage(_("hatPlaced")); - } - else - { - user.sendMessage(_("hatArmor")); - } - } - else - { - user.sendMessage(_("hatFail")); - } - } - } -} 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 fe620b390..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.permissions.Permissions; -import com.earth2me.essentials.user.UserData.TimestampType; -import java.util.List; -import org.bukkit.command.CommandSender; -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 - public 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 b9989ddd5..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandhelp.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.Util; -import com.earth2me.essentials.utils.textreader.HelpInput; -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 java.util.Locale; -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; - String command = commandLabel; - 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 - { - if (pageStr.length() > 26) - { - pageStr = pageStr.substring(0, 25); - } - output = new HelpInput(user, pageStr.toLowerCase(Locale.ENGLISH), ess); - command = command.concat(" ").concat(pageStr); - pageStr = chapterPageStr; - } - chapterPageStr = null; - } - else - { - output = new KeywordReplacer(input, user, ess); - } - final TextPager pager = new TextPager(output); - pager.showPage(pageStr, chapterPageStr, command, 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 42a69b4b1..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandhelpop.java +++ /dev/null @@ -1,33 +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.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(); - } - user.setDisplayNick(); - final String message = _("helpOp", user.getDisplayName(), Util.stripFormat(getFinalArg(args, 0))); - logger.log(Level.INFO, message); - for (Player onlinePlayer : server.getOnlinePlayers()) - { - final IUser player = ess.getUser(onlinePlayer); - 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 cb3220479..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandhome.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.economy.Trade; -import com.earth2me.essentials.permissions.Permissions; -import com.earth2me.essentials.permissions.WorldPermissions; -import com.earth2me.essentials.utils.Util; -import de.bananaco.permissions.worlds.WorldPermissionSet; -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(); - } - } - goHome(user, 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)) - { - goHome(user, player, homes.get(0), charge); - } - else - { - if (bed != null) - { - homes.add("bed"); - } - user.sendMessage(_("homes", Util.joinList(homes))); - } - } - throw new NoChargeException(); - } - - private void goHome(final IUser user, final IUser player, final String home, final Trade charge) throws Exception - { - final Location loc = player.getHome(home); - if (loc == null) - { - throw new NotEnoughArgumentsException(); - } - if (user.getWorld() != loc.getWorld() && ess.getSettings().getData().getGeneral().isWorldHomePermissions() - && !WorldPermissions.getPermission(loc.getWorld().getName()).isAuthorized(user)) - { - throw new Exception(_("noPerm", "essentials.world." + loc.getWorld().getName())); - } - user.getTeleport().home(loc, charge); - } -} 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 9b06cfa64..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")); - } - - user.acquireWriteLock(); - if (user.isIgnoringPlayer(player)) - { - user.setIgnoredPlayer(player, false); - user.sendMessage(_("unignorePlayer", player.getName())); - } - else - { - user.setIgnoredPlayer(player, 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 924e0a74a..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandinfo.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.earth2me.essentials.commands; - -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 349caaf63..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandinvsee.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.earth2me.essentials.commands; - -import com.earth2me.essentials.api.IUser; - - -public class Commandinvsee extends EssentialsCommand -{ - @Override - protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - final IUser invUser = getPlayer(args, 0); - user.setInvSee(true); - user.openInventory(invUser.getInventory()); - } -} 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 0dae772cc..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commanditem.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.permissions.ItemPermissions; -import com.earth2me.essentials.permissions.Permissions; -import java.util.Locale; -import org.bukkit.Material; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.ItemStack; - - -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)); - } - - try - { - if (args.length > 1 && Integer.parseInt(args[1]) > 0) - { - stack.setAmount(Integer.parseInt(args[1])); - } - else if (ess.getSettings().getData().getGeneral().getDefaultStacksize() > 0) - { - stack.setAmount(ess.getSettings().getData().getGeneral().getDefaultStacksize()); - } - else if (ess.getSettings().getData().getGeneral().getOversizedStacksize()> 0 && Permissions.OVERSIZEDSTACKS.isAuthorized(user)) - { - stack.setAmount(ess.getSettings().getData().getGeneral().getOversizedStacksize()); - } - 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); - } - } - } - catch (NumberFormatException e) - { - throw new NotEnoughArgumentsException(); - } - - if (stack.getType() == Material.AIR) - { - 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 fe1177fa2..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commanditemdb.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import org.bukkit.Material; -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())); - - - if (itemStack.getType() != Material.AIR) - { - int maxuses = itemStack.getType().getMaxDurability(); - int durability = ((maxuses + 1) - itemStack.getDurability()); - if (maxuses != 0) - { - sender.sendMessage(_("durability", Integer.toString(durability))); - } - } - } -} 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 7e50c78e2..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandjails.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.earth2me.essentials.commands; - -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 4d4388b84..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.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 Location 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); - throw new NoChargeException(); - } -} 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 fe11efcea..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandkick.java +++ /dev/null @@ -1,39 +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.permissions.Permissions; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - - -public class Commandkick extends EssentialsCommand -{ - @Override - public 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 = ess.getUser(onlinePlayer); - 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 bd22d30c9..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandkickall.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - - -public class Commandkickall extends EssentialsCommand -{ - @Override - public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - for (Player onlinePlayer : server.getOnlinePlayers()) - { - if (sender instanceof Player && onlinePlayer.getName().equalsIgnoreCase(((Player)sender).getName())) - { - continue; - } - else - { - onlinePlayer.kickPlayer(args.length > 0 ? getFinalArg(args, 0) : _("kickDefault")); - } - } - sender.sendMessage(_("kickedAll")); - } -} 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 81e998b34..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandkill.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.event.entity.EntityDamageEvent; - - -public class Commandkill extends EssentialsCommand -{ - @Override - public 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, Short.MAX_VALUE); - server.getPluginManager().callEvent(ede); - if (ede.isCancelled() && !sender.hasPermission("essentials.kill.force")) - { - continue; - } - - matchPlayer.damage(Short.MAX_VALUE); - 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 d8868e2c4..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandkillall.java +++ /dev/null @@ -1,151 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -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 - public 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"), e); - } - } - } - 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(entity instanceof Ocelot) - { - if (((Ocelot)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 4130429f8..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandkit.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.economy.Trade; -import com.earth2me.essentials.permissions.KitPermissions; -import com.earth2me.essentials.settings.Kit; -import com.earth2me.essentials.utils.Util; -import java.util.Collection; -import java.util.List; -import java.util.Locale; -import org.bukkit.command.CommandSender; -import org.bukkit.inventory.ItemStack; - - -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 if (args.length > 1 && KitPermissions.getPermission("others").isAuthorized(user)) - { - final IUser userTo = getPlayer(args, 1, true); - final String kitName = Util.sanitizeString(args[0].toLowerCase(Locale.ENGLISH)); - giveKit(userTo, user, kitName); - - } - else - { - final String kitName = Util.sanitizeString(args[0].toLowerCase(Locale.ENGLISH)); - giveKit(user, user, kitName); - - } - } - - @Override - public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 2) - { - listKits(sender); - throw new NoChargeException(); - } - { - final IUser userTo = getPlayer(args, 1, true); - final String kitName = args[0].toLowerCase(Locale.ENGLISH); - final Kit kit = ess.getKits().getKit(kitName); - ess.getKits().sendKit(userTo, kit); - sender.sendMessage(_("kitGive", kitName)); - } - } - - private void listKits(CommandSender sender) throws Exception - { - Collection kitList = ess.getKits().getList(); - if (kitList.isEmpty()) - { - sender.sendMessage(_("kits", kitList)); - } - else - { - sender.sendMessage(_("kits", Util.joinList(kitList))); - } - } - - private void giveKit(IUser userTo, IUser userFrom, String kitName) throws Exception - { - if (!KitPermissions.getPermission(kitName).isAuthorized(userFrom)) - { - throw new Exception(_("noKitPermission", "essentials.kit." + kitName)); - } - final Kit kit = ess.getKits().getKit(kitName); - ess.getKits().checkTime(userFrom, kit); - final Trade charge = new Trade("kit-" + kitName, ess); - charge.isAffordableFor(userFrom); - ess.getKits().sendKit(userTo, kit); - charge.charge(userFrom); - userTo.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 99a6aa0f3..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandkittycannon.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.earth2me.essentials.commands; - - -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.bukkit.Mob; -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.scheduleSyncDelayedTask(new Runnable() - { - @Override - public void run() - { - final Location loc = ocelot.getLocation(); - ocelot.remove(); - loc.getWorld().createExplosion(loc, 0F); - } - }, 20); - } -} \ No newline at end of file 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 b4dab9691..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandlightning.java +++ /dev/null @@ -1,64 +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.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 - public 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 = 5; - 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())); - final LightningStrike strike = matchPlayer.getWorld().strikeLightningEffect(matchPlayer.getLocation()); - if (!ess.getUser(matchPlayer).isGodModeEnabled()) - { - matchPlayer.damage(power, strike); - } - @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 db8ec5aea..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.api.ISettings; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.permissions.Permissions; -import com.earth2me.essentials.utils.Util; -import java.util.*; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - - -public class Commandlist extends EssentialsCommand -{ - @Override - public 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 (ess.getUser(onlinePlayer).isHidden()) - { - playerHidden++; - } - } - - String online; - if (showhidden && playerHidden > 0) - { - online = _("listAmountHidden", server.getOnlinePlayers().length - playerHidden, playerHidden, server.getMaxPlayers()); - } - else - { - online = _("listAmount", server.getOnlinePlayers().length - 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 = ess.getUser(OnlinePlayer); - 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.replaceFormat(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")); - } - user.setDisplayNick(); - 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 = ess.getUser(OnlinePlayer); - 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")); - } - user.setDisplayNick(); - 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 1454345da..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandmail.java +++ /dev/null @@ -1,165 +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.List; -import org.bukkit.Server; -import org.bukkit.command.CommandSender; -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)) - { - final String mail = Util.sanitizeString(Util.stripFormat(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.scheduleAsyncDelayedTask(new SendAll(user.getName() + ": " + Util.stripFormat(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.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 c420195cc..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandme.java +++ /dev/null @@ -1,37 +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.replaceFormat(message); - } - else { - message = Util.stripColor(message); - } - - - user.setDisplayNick(); - 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 bbf9ede4c..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandmore.java +++ /dev/null @@ -1,56 +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.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 c1d1e92bf..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandmotd.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.earth2me.essentials.commands; - -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 - public 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 7da2b9675..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandmsg.java +++ /dev/null @@ -1,98 +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.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 - public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 2 || args[0].trim().length() < 3 || 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.replaceFormat(message); - } - else - { - message = Util.stripColor(message); - } - } - else - { - message = Util.replaceFormat(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(ess.getUser(sender)) || 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 e6873df03..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandmute.java +++ /dev/null @@ -1,57 +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 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 - public 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) - { - final String time = getFinalArg(args, 1); - muteTimestamp = DateUtil.parseDateDiff(time, true); - player.setMuted(true); - } - else - { - player.setMuted(!player.getData().isMuted()); - } - player.setTimestamp(TimestampType.MUTE, muteTimestamp); - final boolean muted = player.getData().isMuted(); - 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 fc1450445..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandnear.java +++ /dev/null @@ -1,111 +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.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 edbefafaf..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandnick.java +++ /dev/null @@ -1,129 +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.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 - public 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 Util.replaceFormat(nick); - } - else - { - return Util.formatString(user, "essentials.nick", 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 4f6e3933a..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandnuke.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -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 1299aa6e3..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].trim().length() < 3) - { - 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) - { - 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 8c253e183..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.api.IUser; -import com.earth2me.essentials.utils.Util; - - -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.replaceFormat(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 6cf391bf7..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandpowertool.java +++ /dev/null @@ -1,109 +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 com.earth2me.essentials.utils.Util; -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("_", " "); - user.acquireReadLock(); - 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)); - } - throw new NoChargeException(); - } - if (command.startsWith("r:")) - { - command = command.substring(2); - if (!powertools.contains(command)) - { - throw new Exception(_("powerToolNoSuchCommandAssigned", command, itemName)); - } - - powertools.remove(command); - user.sendMessage(_("powerToolRemove", command, itemName)); - } - 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)); - } - - if (!user.getData().isPowerToolsEnabled()) - { - user.getData().setPowerToolsEnabled(true); - user.sendMessage(_("powerToolsEnabled")); - } - 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 e7e887189..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandptime.java +++ /dev/null @@ -1,228 +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.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 - public 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(e); - } - } - - 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 1d7100649..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandr.java +++ /dev/null @@ -1,85 +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.permissions.Permissions; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - - -public class Commandr extends EssentialsCommand -{ - @Override - public 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.replaceFormat(message); - } - else - { - message = Util.replaceFormat(message); - } - replyTo = user; - senderName = user.getDisplayName(); - } - else - { - message = Util.replaceFormat(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 (sender instanceof Player && player.isIgnoringPlayer(ess.getUser(sender))) - { - 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 getPermission() - { - 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 9d69d2ad6..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 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; - } - u.setDisplayNick(); - final String displayName = Util.stripFormat(u.getDisplayName()).toLowerCase(Locale.ENGLISH); - settings.acquireReadLock(); - if (!whois.equals(displayName) - && !displayName.equals(Util.stripFormat(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 988a1f47f..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandremove.java +++ /dev/null @@ -1,155 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import java.util.Locale; -import org.bukkit.Chunk; -import org.bukkit.World; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.*; - -//Todo: Fix this up -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"), e); - } - } - - try - { - toRemove = ToRemove.valueOf(args[0].toUpperCase(Locale.ENGLISH)); - } - catch (IllegalArgumentException e) - { - throw new NotEnoughArgumentsException(e); //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(e); //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.MINECARTS) - { - 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 05715b515..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandrepair.java +++ /dev/null @@ -1,140 +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 Trade charge = new Trade("repair-all", ess); - charge.isAffordableFor(user); - 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))); - } - charge.charge(user); - - } - 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('_', '-'), "repair-item", 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 da0a3eaec..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandrules.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.earth2me.essentials.commands; - -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 - public 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 d9f456a0d..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandseen.java +++ /dev/null @@ -1,69 +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 com.earth2me.essentials.storage.Location; -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, true); - } - - @Override - protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception - { - seen(user,args,Permissions.SEEN_BANREASON.isAuthorized(user), Permissions.SEEN_EXTRA.isAuthorized(user)); - } - - protected void seen (final CommandSender sender, final String[] args, final boolean showBan, final boolean extra) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - try - { - IUser player = getPlayer(args, 0); - player.setDisplayNick(); - sender.sendMessage(_("seenOnline", player.getDisplayName(), DateUtil.formatDateDiff(player.getTimestamp(TimestampType.LOGIN)))); - if (extra) - { - sender.sendMessage(_("whoisIPAddress", player.getAddress().getAddress().toString())); - } - } - catch (NoSuchFieldException e) - { - @Cleanup - IUser player = ess.getUser(args[0]); - player.acquireReadLock(); - if (player == null) - { - throw new Exception(_("playerNotFound")); - } - player.setDisplayNick(); - sender.sendMessage(_("seenOffline", player.getName(), DateUtil.formatDateDiff(player.getTimestamp(TimestampType.LOGOUT)))); - if (player.isBanned()) - { - sender.sendMessage(_("whoisBanned", showBan ? player.getData().getBan().getReason() : _("true"))); - } - if (extra) - { - sender.sendMessage(_("whoisIPAddress", player.getData().getIpAddress())); - final Location loc = player.getData().getLastLocation(); - if (loc != null) { - sender.sendMessage(_("whoisLocation", loc.getWorldName(), loc.getX(), loc.getY(), loc.getZ())); - } - } - } - } -} 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 5ef850264..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsethome.java +++ /dev/null @@ -1,95 +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.Location(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.Location(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.Location(user.getLocation())); - } - user.sendMessage(_("homeSet", user.getLocation().getWorld().getName(), user.getLocation().getBlockX(), user.getLocation().getBlockY(), user.getLocation().getBlockZ())); - - } -} 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 0b4c7f3ff..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsetjail.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.utils.Util; - - -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", Util.sanitizeString(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 8a1797f81..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsetwarp.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.IWarps; -import com.earth2me.essentials.permissions.WarpPermissions; -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) - { - } - - //todo permissions - if (warpLoc == null || WarpPermissions.getPermission("overwrite." + args[0]).isAuthorized(user)) - - { - 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 8bb06e48d..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 org.bukkit.command.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 - public 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 0edcf870c..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandspawn.java +++ /dev/null @@ -1,55 +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.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 81ae6a659..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandspawner.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.earth2me.essentials.commands; - -import com.earth2me.essentials.*; -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.ISettings; -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 lombok.Cleanup; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.CreatureSpawner; -import org.bukkit.entity.EntityType; - - -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")); - } - - String name = args[0]; - - Mob mob = null; - mob = Mob.fromName(name); - if (mob == null) - { - throw new Exception(_("invalidMob")); - } - @Cleanup - ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - if (settings.getData().getGeneral().getPreventSpawn(mob.getType().toString().toLowerCase(Locale.ENGLISH))) - { - throw new Exception(_("disabledToSpawnMob")); - } - if (!SpawnerPermissions.getPermission(mob.name.toLowerCase(Locale.ENGLISH)).isAuthorized(user)) - { - throw new Exception(_("noPermToSpawnMob")); - } - final Trade charge = new Trade("spawner-" + mob.name.toLowerCase(Locale.ENGLISH), ess); - charge.isAffordableFor(user); - try - { - ((CreatureSpawner)target.getBlock().getState()).setSpawnedType(mob.getType()); - - } - catch (Throwable ex) - { - throw new Exception(_("mobSpawnError"), ex); - } - charge.charge(user); - user.sendMessage(_("setSpawner", mob.name)); - - } -} 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 c9c8a2a4b..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandspawnmob.java +++ /dev/null @@ -1,297 +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.*; -import org.bukkit.DyeColor; -import org.bukkit.Location; -import org.bukkit.block.Block; -import org.bukkit.entity.*; -import org.bukkit.entity.Villager.Profession; -import org.bukkit.material.Colorable; - - -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"), e); - } - - 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"), e); - } - 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"), e); - } - 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 (spawned instanceof Slime) - { - try - { - ((Slime)spawned).setSize(Integer.parseInt(data)); - } - catch (Exception e) - { - throw new Exception(_("slimeMalformedSize"), e); - } - } - if (spawned instanceof Ageable && data.contains("baby")) - { - ((Ageable)spawned).setBaby(); - return; - } - if (spawned instanceof Colorable) - { - final String color = data.toUpperCase(Locale.ENGLISH).replace("BABY", ""); - try - { - if (color.equals("RANDOM")) - { - final Random rand = new Random(); - ((Colorable)spawned).setColor(DyeColor.values()[rand.nextInt(DyeColor.values().length)]); - } - else - { - ((Colorable)spawned).setColor(DyeColor.valueOf(color)); - } - } - catch (Exception e) - { - throw new Exception(_("sheepMalformedColor"), e); - } - } - if (spawned instanceof Tameable && 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); - } - else if (data.contains("red")) - { - ((Ocelot)spawned).setCatType(Ocelot.Type.RED_CAT); - } - else if (data.contains("black")) - { - ((Ocelot)spawned).setCatType(Ocelot.Type.BLACK_CAT); - } - } - if (type == EntityType.VILLAGER) - { - for (Profession prof : Villager.Profession.values()) - { - if (data.contains(prof.toString().toLowerCase(Locale.ENGLISH))) - { - ((Villager)spawned).setProfession(prof); - } - } - } - 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 9d94bef89..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsudo.java +++ /dev/null @@ -1,43 +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 com.earth2me.essentials.utils.Util; -import org.bukkit.command.CommandSender; -import org.bukkit.command.PluginCommand; - - -public class Commandsudo extends EssentialsCommand -{ - @Override - public 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))); - - 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 1c6b99c32..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsuicide.java +++ /dev/null @@ -1,20 +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 - { - EntityDamageEvent ede = new EntityDamageEvent(user.getBase(), EntityDamageEvent.DamageCause.SUICIDE, 1000); - server.getPluginManager().callEvent(ede); - user.damage(Short.MAX_VALUE); - user.sendMessage(_("suicideMessage")); - user.setDisplayNick(); - 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 4068f8d18..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtempban.java +++ /dev/null @@ -1,62 +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.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 - public 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 35ba8dedc..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtime.java +++ /dev/null @@ -1,157 +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 com.earth2me.essentials.utils.DescParseTickFormat; -import com.earth2me.essentials.utils.Util; -import java.util.*; -import org.bukkit.World; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - - -public class Commandtime extends EssentialsCommand -{ - @Override - public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - final List argList = new ArrayList(Arrays.asList(args)); - if ((argList.remove("set") || argList.remove("add")) && Util.isInt(argList.get(0))) - { - ess.getLogger().info("debug edited 0" + argList.get(0).toString()); - } - final String[] validArgs = argList.toArray(new String[0]); - - // Which World(s) are we interested in? - String worldSelector = null; - if (validArgs.length == 2) - { - worldSelector = validArgs[1]; - } - final Set worlds = getWorlds(sender, worldSelector); - - // If no arguments we are reading the time - if (validArgs.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(validArgs[0]); - } - catch (NumberFormatException e) - { - throw new NotEnoughArgumentsException(e); - } - - 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 856a32153..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtogglejail.java +++ /dev/null @@ -1,106 +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 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 - public 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 93b0277e1..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtp.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.earth2me.essentials.commands; - -import com.earth2me.essentials.Console; -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.ISettings; -import com.earth2me.essentials.economy.Trade; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.permissions.Permissions; -import com.earth2me.essentials.permissions.WorldPermissions; -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 - { - @Cleanup - ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - 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())); - } - if (user.getWorld() != player.getWorld() && settings.getData().getGeneral().isWorldTeleportPermissions() - && !WorldPermissions.getPermission(player.getWorld().getName()).isAuthorized(user)) - { - throw new Exception(_("noPerm", "essentials.world." + player.getWorld().getName())); - } - 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")); - @Cleanup - final IUser target = getPlayer(args, 0); - @Cleanup - final IUser toPlayer = getPlayer(args, 1); - target.acquireReadLock(); - toPlayer.acquireReadLock(); - - if (!target.getData().isTeleportEnabled()) - { - throw new Exception(_("teleportDisabled", target.getDisplayName())); - } - if (!toPlayer.getData().isTeleportEnabled()) - { - throw new Exception(_("teleportDisabled", toPlayer.getDisplayName())); - } - if (target.getWorld() != toPlayer.getWorld() && settings.getData().getGeneral().isWorldTeleportPermissions() - && !WorldPermissions.getPermission(toPlayer.getWorld().getName()).isAuthorized(user)) - { - throw new Exception(_("noPerm", "essentials.world." + toPlayer.getWorld().getName())); - } - target.getTeleport().now(toPlayer, false, TeleportCause.COMMAND); - target.sendMessage(_("teleportAtoB", user.getDisplayName(), toPlayer.getDisplayName())); - break; - } - } - - @Override - public 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 f6003316d..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpa.java +++ /dev/null @@ -1,50 +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.permissions.WorldPermissions; -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())); - } - @Cleanup - ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - if (user.getWorld() != player.getWorld() && ess.getSettings().getData().getGeneral().isWorldTeleportPermissions() - && !WorldPermissions.getPermission(user.getWorld().getName()).isAuthorized(user)) - { - throw new Exception(_("noPerm", "essentials.world." + player.getWorld().getName())); - } - if (!player.isIgnoringPlayer(user)) - { - player.requestTeleport(user, false); - player.sendMessage(_("teleportRequest", user.getDisplayName())); - player.sendMessage(_("typeTpaccept")); - player.sendMessage(_("typeTpdeny")); - int tpaAcceptCancellation = 0; - tpaAcceptCancellation = settings.getData().getCommands().getTpa().getTimeout(); - 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 b5b889c30..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpaall.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.permissions.WorldPermissions; -import lombok.Cleanup; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - - -public class Commandtpaall extends EssentialsCommand -{ - @Override - public 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; - } - @Cleanup - ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - if (user.getWorld() != player.getWorld() && settings.getData().getGeneral().isWorldTeleportPermissions() - && !WorldPermissions.getPermission(user.getWorld().getName()).isAuthorized(user)) - { - continue; - } - try - { - player.requestTeleport(user, true); - player.sendMessage(_("teleportHereRequest", user.getDisplayName())); - player.sendMessage(_("typeTpaccept")); - int tpaAcceptCancellation = 0; - tpaAcceptCancellation = settings.getData().getCommands().getTpa().getTimeout(); - 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 e0f3b7d0c..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java +++ /dev/null @@ -1,62 +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.economy.Trade; -import com.earth2me.essentials.permissions.Permissions; -import com.earth2me.essentials.permissions.WorldPermissions; -import lombok.Cleanup; -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 - { - final IUser target = user.getTeleportRequester(); - @Cleanup - ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - if (target == null || !target.isOnline() - || (args.length > 0 && !target.getName().contains(args[0])) - || (user.isTpRequestHere() && !Permissions.TPAHERE.isAuthorized(target)) - || (!user.isTpRequestHere() && ((!Permissions.TPA.isAuthorized(target) && !Permissions.TPAALL.isAuthorized(target)) - || (user.getWorld() != target.getWorld() - && settings.getData().getGeneral().isWorldTeleportPermissions() - && !WorldPermissions.getPermission(user.getWorld().getName()).isAuthorized(user))))) - { - throw new Exception(_("noPendingRequest")); - } - - long timeout = settings.getData().getCommands().getTpa().getTimeout(); - if (timeout != 0 && (System.currentTimeMillis() - user.getTeleportRequestTime()) / 1000 > timeout) - { - user.requestTeleport(null, false); - throw new Exception(_("requestTimedOut")); - } - - final Trade charge = new Trade(this.commandName, ess); - if (user.isTpRequestHere()) - { - charge.isAffordableFor(user); - } - else - { - charge.isAffordableFor(target); - } - user.sendMessage(_("requestAccepted")); - target.sendMessage(_("requestAcceptedFrom", user.getDisplayName())); - - if (user.isTpRequestHere()) - { - 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 3de6c0ba8..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpahere.java +++ /dev/null @@ -1,48 +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.permissions.WorldPermissions; -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())); - } - @Cleanup - ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - if (user.getWorld() != player.getWorld() && settings.getData().getGeneral().isWorldTeleportPermissions() - && !WorldPermissions.getPermission(user.getWorld().getName()).isAuthorized(user)) - { - throw new Exception(_("noPerm", "essentials.world." + user.getWorld().getName())); - } - player.requestTeleport(user, true); - player.sendMessage(_("teleportHereRequest", user.getDisplayName())); - player.sendMessage(_("typeTpaccept")); - int tpaAcceptCancellation = 0; - { - tpaAcceptCancellation = settings.getData().getCommands().getTpa().getTimeout(); - } - 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 e9f7419c3..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpall.java +++ /dev/null @@ -1,62 +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.permissions.WorldPermissions; -import lombok.Cleanup; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; - - -public class Commandtpall extends EssentialsCommand -{ - @Override - public 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; - } - @Cleanup - ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - - if (user.getWorld() != player.getWorld() && settings.getData().getGeneral().isWorldTeleportPermissions() - && !WorldPermissions.getPermission(user.getWorld().getName()).isAuthorized(user)) - { - continue; - } - try - { - player.getTeleport().now(user, false, TeleportCause.COMMAND); - } - catch (Exception ex) - { - ess.getCommandHandler().showCommandError(sender, commandName, ex); - } - - } - } -} \ No newline at end of file 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 1954b0874..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtphere.java +++ /dev/null @@ -1,37 +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.economy.Trade; -import com.earth2me.essentials.permissions.WorldPermissions; -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())); - } - @Cleanup - ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - if (user.getWorld() != player.getWorld() && settings.getData().getGeneral().isWorldTeleportPermissions() - && !WorldPermissions.getPermission(user.getWorld().getName()).isAuthorized(user)) - { - throw new Exception(_("noPerm", "essentials.world." + user.getWorld().getName())); - } - player.getTeleport().teleport(user, new Trade(this.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 006812e48..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpo.java +++ /dev/null @@ -1,67 +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.permissions.Permissions; -import com.earth2me.essentials.permissions.WorldPermissions; -import lombok.Cleanup; -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 - { - @Cleanup - ISettings settings = ess.getSettings(); - switch (args.length) - { - case 0: - throw new NotEnoughArgumentsException(); - - case 1: - final IUser player = getPlayer(args, 0, true); - if (!player.isOnline() || (player.isHidden() && !Permissions.TELEPORT_HIDDEN.isAuthorized(player))) - { - throw new NoSuchFieldException(_("playerNotFound")); - } - settings.acquireReadLock(); - if (user.getWorld() != player.getWorld() && settings.getData().getGeneral().isWorldTeleportPermissions() - && !WorldPermissions.getPermission(player.getWorld().getName()).isAuthorized(player)) - { - throw new Exception(_("noPerm", "essentials.world." + player.getWorld().getName())); - } - - user.sendMessage(_("teleporting")); - user.getTeleport().now(player, false, TeleportCause.COMMAND); - break; - - default: - if (!Permissions.TELEPORT_OTHERS.isAuthorized(user)) - { - throw new Exception(_("noPerm", "essentials.tp.others")); - } - user.sendMessage(_("teleporting")); - final IUser target = getPlayer(args, 0, true); - final IUser toPlayer = getPlayer(args, 1, true); - - if (!target.isOnline() || !toPlayer.isOnline() - || ((target.isHidden() || toPlayer.isHidden()) && !Permissions.TELEPORT_HIDDEN.isAuthorized(user))) - { - throw new NoSuchFieldException(_("playerNotFound")); - } - settings.acquireReadLock(); - if (target.getWorld() != toPlayer.getWorld() && settings.getData().getGeneral().isWorldTeleportPermissions() - && !WorldPermissions.getPermission(toPlayer.getWorld().getName()).isAuthorized(user)) - { - throw new Exception(_("noPerm", "essentials.world." + toPlayer.getWorld().getName())); - } - - target.getTeleport().now(toPlayer, false, TeleportCause.COMMAND); - target.sendMessage(_("teleportAtoB", user.getDisplayName(), toPlayer.getDisplayName())); - break; - } - } -} 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 c108f56f8..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpohere.java +++ /dev/null @@ -1,52 +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.permissions.Permissions; -import com.earth2me.essentials.permissions.WorldPermissions; -import lombok.Cleanup; -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")); - } - @Cleanup - ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - //todo - common method - if (user.getWorld() != player.getWorld() && settings.getData().getGeneral().isWorldTeleportPermissions() - && !WorldPermissions.getPermission(user.getWorld().getName()).isAuthorized(player)) - { - throw new Exception(_("noPerm", "essentials.world." + user.getWorld().getName())); - } - - - // 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 80daf2b16..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtppos.java +++ /dev/null @@ -1,65 +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.command.CommandSender; -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(); - } - - @Override - public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 4) - { - throw new NotEnoughArgumentsException(); - } - - IUser user = ess.getUser(server.getPlayer(args[0])); - final int x = Integer.parseInt(args[1]); - final int y = Integer.parseInt(args[2]); - final int z = Integer.parseInt(args[3]); - final Location location = new Location(user.getWorld(), x, y, z); - if (args.length > 4) - { - location.setYaw((Float.parseFloat(args[4]) + 180 + 360) % 360); - } - if (args.length > 5) - { - location.setPitch(Float.parseFloat(args[5])); - } - sender.sendMessage(_("teleporting")); - user.sendMessage(_("teleporting")); - user.getTeleport().teleport(location, null, TeleportCause.COMMAND); - } -} \ 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 79bbecd29..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtree.java +++ /dev/null @@ -1,69 +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 if (args[0].equalsIgnoreCase("jungle")) - { - tree = TreeType.SMALL_JUNGLE; - } - else if (args[0].equalsIgnoreCase("junglebush")) - { - tree = TreeType.JUNGLE_BUSH; - } - else if (args[0].equalsIgnoreCase("swamp")) - { - tree = TreeType.SWAMP; - } - 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 101e09691..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandunban.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import lombok.Cleanup; -import org.bukkit.command.CommandSender; - - -public class Commandunban extends EssentialsCommand -{ - @Override - public 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"), e); - } - } -} 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 14d2c8ae6..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandunbanip.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; -import lombok.Cleanup; -import org.bukkit.command.CommandSender; - - -public class Commandunbanip extends EssentialsCommand -{ - @Override - public 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 632a8567a..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.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; -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; - - -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.name()); - - } - } - 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.name().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 (!InventoryWorkaround.containsItem(target.getInventory(), 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/Commandvanish.java b/Essentials/src/com/earth2me/essentials/commands/Commandvanish.java deleted file mode 100644 index 9e8997a7c..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandvanish.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IUser; - - -public class Commandvanish extends EssentialsCommand -{ - @Override - protected void run(IUser user, String commandLabel, String[] args) throws Exception - { - if (args.length < 1) - { - user.toggleVanished(); - if (user.isVanished()) - { - user.sendMessage(_("vanished")); - } - else - { - user.sendMessage(_("unvanished")); - } - } - else - { - if (args[0].contains("on") || args[0].contains("ena") || args[0].equalsIgnoreCase("1")) - { - user.setVanished(true); - } - else - { - user.setVanished(false); - } - user.sendMessage(user.isVanished() ? _("vanished") : _("unvanished")); - } - } -} 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 db146a107..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandwarp.java +++ /dev/null @@ -1,126 +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.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 - public 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 chargeWarp = new Trade("warp-" + name.toLowerCase(Locale.ENGLISH).replace('_', '-'), ess); - final Trade chargeCmd = new Trade(this.commandName, ess); - final double fullCharge = chargeWarp.getCommandCost(user) + chargeCmd.getCommandCost(user); - final Trade charge = new Trade(fullCharge, 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 2df5b1eac..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 org.bukkit.World; -import org.bukkit.command.CommandSender; - - -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 858e601f5..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandwhois.java +++ /dev/null @@ -1,98 +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.permissions.Permissions; -import com.earth2me.essentials.user.UserData; -import com.earth2me.essentials.utils.DateUtil; -import com.earth2me.essentials.craftbukkit.SetExpFix; -import java.util.Locale; -import lombok.Cleanup; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - - -public class Commandwhois extends EssentialsCommand -{ - @Override - public 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(); - boolean foundPlayer = false; - for (Player onlinePlayer : server.getOnlinePlayers()) - { - @Cleanup - final IUser user = ess.getUser(onlinePlayer); - - if (user.isHidden() && !showhidden) - { - continue; - } - user.acquireReadLock(); - final String nickName = Util.stripFormat(user.getData().getNickname()); - if (!whois.equalsIgnoreCase(nickName) - && !whois.substring(prefixLength).equalsIgnoreCase(nickName) - && !whois.equalsIgnoreCase(user.getName())) - { - continue; - } - foundPlayer = true; - sender.sendMessage(_("whoisTop", user.getName())); - user.setDisplayNick(); - sender.sendMessage(_("whoisIs", user.getDisplayName(), user.getName())); - sender.sendMessage(_("whoisHealth", user.getHealth())); - sender.sendMessage(_("whoisExp", SetExpFix.getTotalExperience(user), user.getLevel())); - 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(_("whoisIPAddress", user.getAddress().getAddress().toString())); - final String location = user.getData().getGeolocation(); - if (location != null - && Permissions.GEOIP_SHOW.isAuthorized(sender)) - { - sender.sendMessage(_("whoisGeoLocation", location)); - } - sender.sendMessage(_("whoisGamemode", _(user.getGameMode().toString().toLowerCase(Locale.ENGLISH)))); - sender.sendMessage(_("whoisGod", (user.isGodModeEnabled() ? _("true") : _("false")))); - sender.sendMessage(_("whoisOP", (user.isOp() ? _("true") : _("false")))); - sender.sendMessage(_("whoisFly", user.getAllowFlight() ? _("true") : _("false"), user.isFlying() ? _("flying") : _("notFlying"))); - sender.sendMessage(_("whoisAFK", (user.getData().isAfk() ? _("true") : _("false")))); - sender.sendMessage(_("whoisJail", (user.getData().isJailed() - ? user.getTimestamp(UserData.TimestampType.JAIL) > 0 - ? DateUtil.formatDateDiff(user.getTimestamp(UserData.TimestampType.JAIL)) - : _("true") - : _("false")))); - sender.sendMessage(_("whoisMute", (user.getData().isMuted() - ? user.getTimestamp(UserData.TimestampType.MUTE) > 0 - ? DateUtil.formatDateDiff(user.getTimestamp(UserData.TimestampType.MUTE)) - : _("true") - : _("false")))); - - if (!foundPlayer) - { - throw new NoSuchFieldException(_("playerNotFound")); - } - } - } -} 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 9e2c1b08d..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.permissions.WorldPermissions; -import java.util.List; -import org.bukkit.Location; -import org.bukkit.World; -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 = new Location(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 0e1ec1dc1..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/Commandworth.java +++ /dev/null @@ -1,102 +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 java.util.Locale; -import org.bukkit.command.CommandSender; -import org.bukkit.inventory.ItemStack; - - -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.getInventory().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 e3b25177a..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java +++ /dev/null @@ -1,132 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.economy.Trade; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IEssentialsModule; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.permissions.AbstractSuperpermsPermission; -import java.util.List; -import java.util.logging.Logger; -import org.bukkit.Server; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.permissions.Permission; - - -public abstract class EssentialsCommand extends AbstractSuperpermsPermission implements IEssentialsCommand -{ - protected transient String commandName; - protected transient IEssentials ess; - protected transient IEssentialsModule module; - protected transient Server server; - protected transient Logger logger; - private transient String permission; - private transient Permission bukkitPerm; - - 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 = ess.getUser(player); - if (userMatch.getDisplayName().startsWith(args[pos]) && (getOffline || !userMatch.isHidden())) - { - return userMatch; - } - } - final IUser userMatch = ess.getUser(matches.get(0)); - 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.getBase(), 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 getPermission() - { - 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 f45a55a3f..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/EssentialsCommandHandler.java +++ /dev/null @@ -1,316 +0,0 @@ -package com.earth2me.essentials.commands; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.*; -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 b4c1b40f8..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 org.bukkit.command.Command; -import org.bukkit.command.CommandSender; - - -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 c2e9c5c44..000000000 --- a/Essentials/src/com/earth2me/essentials/commands/WarpNotFoundException.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n._; - - -public class WarpNotFoundException extends Exception -{ - public WarpNotFoundException() - { - super(_("warpNotExist")); - } - - public WarpNotFoundException(String message) - { - super(message); - } -} - - 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 8456c956e..000000000 --- a/Essentials/src/com/earth2me/essentials/craftbukkit/FakeInventory.java +++ /dev/null @@ -1,243 +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."); - } - - @Override - public int getMaxStackSize() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setMaxStackSize(int size) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public ListIterator iterator(int index) - { - 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 fc9cbb74b..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 enforceDurability, final boolean enforceAmount, final boolean enforceEnchantments) - { - return next(inventory, item, 0, enforceDurability, enforceAmount, enforceEnchantments); - } - - public static int next(final Inventory cinventory, final ItemStack item, final int start, final boolean enforceDurability, final boolean enforceAmount, final boolean enforceEnchantments) - { - 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() && (!enforceAmount || item.getAmount() == cItem.getAmount()) && (!enforceDurability || cItem.getDurability() == item.getDurability()) && (!enforceEnchantments || cItem.getEnchantments().equals(item.getEnchantments()))) - { - return i; - } - } - return -1; - } - - public static int firstPartial(final Inventory cinventory, final ItemStack item, final boolean enforceDurability) - { - return firstPartial(cinventory, item, enforceDurability, item.getType().getMaxStackSize()); - } - - public static int firstPartial(final Inventory cinventory, final ItemStack item, final boolean enforceDurability, 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 && (!enforceDurability || cItem.getDurability() == item.getDurability()) && cItem.getEnchantments().equals(item.getEnchantments())) - { - return i; - } - } - return -1; - } - - public static boolean addAllItems(final Inventory cinventory, final boolean enforceDurability, final ItemStack... items) - { - final Inventory fake = new FakeInventory(cinventory.getContents()); - if (addItem(fake, enforceDurability, items).isEmpty()) - { - addItem(cinventory, enforceDurability, 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 enforceDurability, 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() && (!enforceDurability || 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, enforceDurability, 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 enforceDurability, final boolean enforceEnchantments, 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, enforceDurability, false, enforceEnchantments); - - // 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 enforceDurability, final boolean enforceEnchantments, 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() && (!enforceDurability || combined[j].getDurability() == items[i].getDurability()) && (!enforceEnchantments || 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, enforceDurability, false, enforceEnchantments); - - // 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 b788fa7ee..000000000 --- a/Essentials/src/com/earth2me/essentials/craftbukkit/SetExpFix.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.earth2me.essentials.craftbukkit; - -import org.bukkit.entity.Player; - - -public class SetExpFix -{ - //This method is used to update both the recorded total experience and displayed total experience. - //We reset both types to prevent issues. - public static void setTotalExperience(final Player player, final int exp) - { - if (exp < 0) - { - throw new IllegalArgumentException("Experience is negative!"); - } - player.setExp(0); - player.setLevel(0); - player.setTotalExperience(0); - - //This following code is technically redundant now, as bukkit now calulcates levels more or less correctly - //At larger numbers however... player.getExp(3000), only seems to give 2999, putting the below calculations off. - 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 Player player) - { - return getExpToLevel(player.getLevel()); - } - - private static int getExpToLevel(final int level) - { - return 7 + (level * 7 >> 1); - } - - //This method is required because the bukkit player.getTotalExperience() method, shows exp that has been 'spent'. - //Without this people would be able to use exp and then still sell it. - public static int getTotalExperience(final Player player) - { - int exp = (int)Math.round(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 3ecf6b2d0..000000000 --- a/Essentials/src/com/earth2me/essentials/economy/MoneyHolder.java +++ /dev/null @@ -1,36 +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 -{ - - @Override - public void finishRead() - { - - } - - @Override - public void finishWrite() - { - - } - - - public MoneyHolder(IEssentials ess) - { - super(ess, Money.class); - onReload(); - } - - @Override - public File getStorageFile() throws IOException - { - return new File(ess.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 c9304d1bb..000000000 --- a/Essentials/src/com/earth2me/essentials/economy/Trade.java +++ /dev/null @@ -1,357 +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.craftbukkit.InventoryWorkaround; -import com.earth2me.essentials.craftbukkit.SetExpFix; -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; -import org.bukkit.Location; -import org.bukkit.entity.Item; -import org.bukkit.inventory.ItemStack; - - -public class Trade -{ - private final transient String command; - private final transient String fallbackCommand; - 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, null, ess); - } - - public Trade(final String command, final String fallback, final IEssentials ess) - { - this(command, fallback, null, null, null, ess); - } - - public Trade(final double money, final IEssentials ess) - { - this(null, null, money, null, null, ess); - } - - public Trade(final ItemStack items, final IEssentials ess) - { - this(null, null, null, items, null, ess); - } - - public Trade(final int exp, final IEssentials ess) - { - this(null, null, null, null, exp, ess); - } - - private Trade(final String command, final String fallback, final Double money, final ItemStack item, final Integer exp, final IEssentials ess) - { - this.command = command; - this.fallbackCommand = fallback; - this.money = money; - this.itemStack = item; - this.exp = exp; - this.ess = ess; - } - - public void isAffordableFor(final IUser user) throws ChargeException - { - if (getMoney() != null - && getMoney() > 0 - && !Permissions.ECO_LOAN.isAuthorized(user) - && !user.canAfford(getMoney())) - { - throw new ChargeException(_("notEnoughMoney")); - } - - if (getItemStack() != null - && !InventoryWorkaround.containsItem(user.getInventory(), 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) - && money < 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 - && SetExpFix.getTotalExperience(user) < 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 = InventoryWorkaround.addItem(user.getInventory(), 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 Item[] itemStacks = new Item[stacks + (leftover > 0 ? 1 : 0)]; - for (int i = 0; i < stacks; i++) - { - final ItemStack stack = dropStack.clone(); - stack.setAmount(maxStackSize); - itemStacks[i] = loc.getWorld().dropItem(loc, stack); - } - if (leftover > 0) - { - final ItemStack stack = dropStack.clone(); - stack.setAmount(leftover); - itemStacks[stacks] = loc.getWorld().dropItem(loc, stack); - } - } - } - else - { - success = InventoryWorkaround.addAllItems(user.getInventory(), true, getItemStack()); - } - user.updateInventory(); - } - if (getExperience() != null) - { - SetExpFix.setTotalExperience(user, SetExpFix.getTotalExperience(user) + 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 (!InventoryWorkaround.containsItem(user.getInventory(), true, true, itemStack)) - { - throw new ChargeException(_("missingItems", getItemStack().getAmount(), getItemStack().getType().toString().toLowerCase(Locale.ENGLISH).replace("_", " "))); - } - InventoryWorkaround.removeItem(user.getInventory(), 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 = SetExpFix.getTotalExperience(user); - if (experience < getExperience() && getExperience() > 0) - { - throw new ChargeException(_("notEnoughExperience")); - } - SetExpFix.setTotalExperience(user, experience - getExperience()); - } - } - - public Double getMoney() - { - return money; - } - - public ItemStack getItemStack() - { - return itemStack; - } - - public Integer getExperience() - { - return exp; - } - - public Double getCommandCost(final IUser user) - { - double cost = 0d; - if (command != null && !command.isEmpty() - && !NoCommandCostPermissions.getPermission("all").isAuthorized(user) - && !NoCommandCostPermissions.getPermission(command).isAuthorized(user)) - { - cost = ess.getSettings().getData().getEconomy().getCommandCost(command.charAt(0) == '/' ? command.substring(1) : command); - if (cost == 0.0 && fallbackCommand != null && !fallbackCommand.isEmpty()) - { - cost = ess.getSettings().getData().getEconomy().getCommandCost(fallbackCommand.charAt(0) == '/' ? fallbackCommand.substring(1) : fallbackCommand); - } - } - return cost; - } - private static FileWriter fw = null; - - public static void log(String type, String subtype, String event, String sender, Trade charge, String receiver, Trade pay, Location loc, IEssentials ess) - { - @Cleanup - final ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - if (!settings.getData().getEconomy().isLogEnabled()) - { - return; - } - if (fw == null) - { - try - { - fw = new FileWriter(new File(ess.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 d514c9797..000000000 --- a/Essentials/src/com/earth2me/essentials/economy/WorthHolder.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.earth2me.essentials.economy; - -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IWorth; -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.inventory.ItemStack; -import org.bukkit.material.MaterialData; - - -public class WorthHolder extends AsyncStorageObjectHolder implements IWorth -{ - - @Override - public void finishRead() - { - - } - - @Override - public void finishWrite() - { - - } - - - 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.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 5866066eb..000000000 --- a/Essentials/src/com/earth2me/essentials/economy/register/Method.java +++ /dev/null @@ -1,217 +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 reported name of this method. - * - * @return String Plugin name. - */ - public String getLongName(); - - /** - * 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 688e68332..000000000 --- a/Essentials/src/com/earth2me/essentials/economy/register/methods/BOSE6.java +++ /dev/null @@ -1,334 +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 getLongName() - { - return getName(); - } - - @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 53dd43d87..000000000 --- a/Essentials/src/com/earth2me/essentials/economy/register/methods/BOSE7.java +++ /dev/null @@ -1,323 +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 getLongName() - { - return getName(); - } - - @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 d2cb57a8d..000000000 --- a/Essentials/src/com/earth2me/essentials/economy/register/methods/MCUR.java +++ /dev/null @@ -1,195 +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 getLongName() - { - return getName(); - } - - @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 43beb84f4..000000000 --- a/Essentials/src/com/earth2me/essentials/economy/register/methods/VaultEco.java +++ /dev/null @@ -1,347 +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(); - } - - public String getEconomy() - { - return economy == null ? "NoEco" : economy.getName(); - } - - @Override - public String getLongName() - { - return getName().concat(" - Economy: ").concat(getEconomy()); - } - - @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 b033ba9cc..000000000 --- a/Essentials/src/com/earth2me/essentials/economy/register/methods/iCo4.java +++ /dev/null @@ -1,256 +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 getLongName() - { - return getName(); - } - - @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 137772ebc..000000000 --- a/Essentials/src/com/earth2me/essentials/economy/register/methods/iCo5.java +++ /dev/null @@ -1,376 +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 getLongName() - { - return getName(); - } - - @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 ead4ebeb3..000000000 --- a/Essentials/src/com/earth2me/essentials/economy/register/methods/iCo6.java +++ /dev/null @@ -1,242 +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 getLongName() - { - return getName(); - } - - @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 49fff3de3..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.LOW, 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.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 53055a265..000000000 --- a/Essentials/src/com/earth2me/essentials/listener/EssentialsEntityListener.java +++ /dev/null @@ -1,176 +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.user.UserData.TimestampType; -import java.util.List; -import lombok.Cleanup; -import org.bukkit.Material; -import org.bukkit.entity.Ageable; -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.LOW) - 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); - @Cleanup - final IUser defender = ess.getUser((Player)eDefend); - @Cleanup - ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - attacker.acquireReadLock(); - defender.acquireReadLock(); - - attacker.updateActivity(true); - if (settings.getData().getGeneral().getLoginAttackDelay() > 0 && !Permissions.PVPDELAY_EXEMPT.isAuthorized(attacker) - && (System.currentTimeMillis() < (attacker.getTimestamp(TimestampType.LOGIN) + settings.getData().getGeneral().getLoginAttackDelay()))) - { - event.setCancelled(true); - } - if (attacker.hasInvulnerabilityAfterTeleport() || defender.hasInvulnerabilityAfterTeleport()) - { - event.setCancelled(true); - } - final ItemStack itemstack = attacker.getItemInHand(); - final List commandList = attacker.getData().getPowertool(itemstack.getType()); - if (commandList != null && !commandList.isEmpty()) - { - for (final String command : commandList) - { - if (command != null && !command.isEmpty()) - { - ess.scheduleSyncDelayedTask( - new Runnable() - { - @Override - public void run() - { - attacker.getServer().dispatchCommand(attacker.getBase(), command.replaceAll("\\{player\\}", defender.getName())); - } - }); - event.setCancelled(true); - return; - } - } - } - } - else if (eDefend instanceof Ageable && eAttack instanceof Player) - { - final Player player = (Player)eAttack; - final ItemStack hand = player.getItemInHand(); - if (hand != null && hand.getType() == Material.MILK_BUCKET) - { - ((Ageable)eDefend).setBaby(); - hand.setType(Material.BUCKET); - player.setItemInHand(hand); - player.updateInventory(); - event.setCancelled(true); - } - } - } - - @EventHandler(priority = EventPriority.LOW, 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.LOW, 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.LOW) - public void onPlayerDeathExpEvent(final PlayerDeathEvent event) - { - final IUser user = ess.getUser(event.getEntity()); - if (Permissions.KEEPXP.isAuthorized(user)) - { - event.setKeepLevel(true); - event.setDroppedExp(0); - } - } - - @EventHandler(priority = EventPriority.LOW, 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.LOW, 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 d6f539f70..000000000 --- a/Essentials/src/com/earth2me/essentials/listener/EssentialsPlayerListener.java +++ /dev/null @@ -1,490 +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.user.UserData.TimestampType; -import com.earth2me.essentials.utils.LocationUtil; -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 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.HumanEntity; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.event.inventory.InventoryCloseEvent; -import org.bukkit.event.inventory.InventoryType; -import org.bukkit.event.player.*; -import org.bukkit.event.player.PlayerLoginEvent.Result; -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; -import org.bukkit.inventory.InventoryHolder; -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)) - { - 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.setGodModeEnabled(false); - } - if (user.isVanished()) - { - user.toggleVanished(); - } - 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) - { - if (!event.getPlayer().isOnline()) - { - return; - } - 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); - - for (String p : ess.getVanishedPlayers()) - { - if (!Permissions.VANISH_SEE_OTHERS.isAuthorized(user)) - { - user.hidePlayer(ess.getUser(p).getBase()); - } - } - - 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); - } - } - - @EventHandler(priority = EventPriority.LOWEST) - public void onInventoryClickEvent(final InventoryClickEvent event) - { - if (event.getView().getTopInventory().getType() == InventoryType.PLAYER) - { - final IUser user = ess.getUser(event.getWhoClicked()); - final InventoryHolder invHolder = event.getView().getTopInventory().getHolder(); - if (invHolder != null && invHolder instanceof HumanEntity) - { - final IUser invOwner = ess.getUser((HumanEntity)invHolder); - if (user.isInvSee() && (!Permissions.INVSEE_MODIFY.isAuthorized(user) - || Permissions.INVSEE_PREVENT_MODIFY.isAuthorized(invOwner) - || !invOwner.isOnline())) - { - event.setCancelled(true); - } - } - } - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onInventoryCloseEvent(final InventoryCloseEvent event) - { - if (event.getView().getTopInventory().getType() == InventoryType.PLAYER) - { - final IUser user = ess.getUser(event.getPlayer()); - user.setInvSee(false); - } - } -} 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 778469605..000000000 --- a/Essentials/src/com/earth2me/essentials/listener/TntExplodeListener.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.earth2me.essentials.listener; - -import com.earth2me.essentials.api.IEssentials; -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; - } - if (event.blockList().size() < 1) - { - return; - } - event.setCancelled(true); - event.getLocation().getWorld().createExplosion(event.getLocation(), 0F); - } - - @Override - public void run() - { - enabled.set(false); - } -} diff --git a/Essentials/src/com/earth2me/essentials/metrics/Metrics.java b/Essentials/src/com/earth2me/essentials/metrics/Metrics.java deleted file mode 100644 index f361e4f50..000000000 --- a/Essentials/src/com/earth2me/essentials/metrics/Metrics.java +++ /dev/null @@ -1,625 +0,0 @@ -package com.earth2me.essentials.metrics; - -/* - * Copyright 2011 Tyler Blair. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the - * following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following - * disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the - * following disclaimer in the documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED - * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL - * THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; - * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR - * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - * - * The views and conclusions contained in the software and documentation are those of the authors and contributors and - * should not be interpreted as representing official policies, either expressed or implied, of anybody else. - */ -import java.io.*; -import java.net.Proxy; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLEncoder; -import java.util.*; -import java.util.logging.Level; -import org.bukkit.Bukkit; -import org.bukkit.configuration.InvalidConfigurationException; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginDescriptionFile; - - -/** - *

The metrics class obtains data about a plugin and submits statistics about it to the metrics backend.

- * Public methods provided by this class:

- * - * Graph createGraph(String name);
- * void addCustomData(Metrics.Plotter plotter);
- * void start();
- *
- */ -public class Metrics -{ - /** - * The current revision number - */ - private final static int REVISION = 5; - /** - * The base url of the metrics domain - */ - private static final String BASE_URL = "http://metrics.essentials3.net"; - /** - * The url used to report a server's status - */ - private static final String REPORT_URL = "/report/%s"; - /** - * The file where guid and opt out is stored in - */ - private static final String CONFIG_FILE = "plugins/PluginMetrics/config.yml"; - /** - * The separator to use for custom data. This MUST NOT change unless you are hosting your own version of metrics and - * want to change it. - */ - private static final String CUSTOM_DATA_SEPARATOR = "~~"; - /** - * Interval of time to ping (in minutes) - */ - private static final int PING_INTERVAL = 10; - /** - * The plugin this metrics submits for - */ - private final Plugin plugin; - /** - * All of the custom graphs to submit to metrics - */ - private final Set graphs = Collections.synchronizedSet(new HashSet()); - /** - * The default graph, used for addCustomData when you don't want a specific graph - */ - private final Graph defaultGraph = new Graph("Default"); - /** - * The plugin configuration file - */ - private final YamlConfiguration configuration; - /** - * The plugin configuration file - */ - private final File configurationFile; - /** - * Unique server id - */ - private final String guid; - /** - * Lock for synchronization - */ - private final Object optOutLock = new Object(); - /** - * Id of the scheduled task - */ - private volatile int taskId = -1; - - public Metrics(final Plugin plugin) throws IOException - { - if (plugin == null) - { - throw new IllegalArgumentException("Plugin cannot be null"); - } - - this.plugin = plugin; - - // load the config - configurationFile = new File(CONFIG_FILE); - configuration = YamlConfiguration.loadConfiguration(configurationFile); - - // add some defaults - configuration.addDefault("opt-out", false); - configuration.addDefault("guid", UUID.randomUUID().toString()); - - // Do we need to create the file? - if (configuration.get("guid", null) == null) - { - configuration.options().header("http://metrics.griefcraft.com").copyDefaults(true); - configuration.save(configurationFile); - } - - // Load the guid then - guid = configuration.getString("guid"); - } - - /** - * Construct and create a Graph that can be used to separate specific plotters to their own graphs on the metrics - * website. Plotters can be added to the graph object returned. - * - * @param name - * @return Graph object created. Will never return NULL under normal circumstances unless bad parameters are given - */ - public Graph createGraph(final String name) - { - if (name == null) - { - throw new IllegalArgumentException("Graph name cannot be null"); - } - - // Construct the graph object - final Graph graph = new Graph(name); - - // Now we can add our graph - graphs.add(graph); - - // and return back - return graph; - } - - /** - * Adds a custom data plotter to the default graph - * - * @param plotter - */ - public void addCustomData(final Plotter plotter) - { - if (plotter == null) - { - throw new IllegalArgumentException("Plotter cannot be null"); - } - - // Add the plotter to the graph o/ - defaultGraph.addPlotter(plotter); - - // Ensure the default graph is included in the submitted graphs - graphs.add(defaultGraph); - } - - /** - * Start measuring statistics. This will immediately create an async repeating task as the plugin and send the - * initial data to the metrics backend, and then after that it will post in increments of PING_INTERVAL * 1200 - * ticks. - */ - public void start() - { - synchronized (optOutLock) - { - // Did we opt out? - if (isOptOut()) - { - return; - } - - // Begin hitting the server with glorious data - taskId = plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable() - { - private boolean firstPost = true; - - public void run() - { - try - { - // This has to be synchronized or it can collide with the disable method. - synchronized (optOutLock) - { - // Disable Task, if it is running and the server owner decided to opt-out - if (isOptOut() && taskId > 0) - { - plugin.getServer().getScheduler().cancelTask(taskId); - taskId = -1; - } - } - - // We use the inverse of firstPost because if it is the first time we are posting, - // it is not a interval ping, so it evaluates to FALSE - // Each time thereafter it will evaluate to TRUE, i.e PING! - postPlugin(!firstPost); - - // After the first post we set firstPost to false - // Each post thereafter will be a ping - firstPost = false; - } - catch (IOException e) - { - Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage()); - } - } - }, 0, PING_INTERVAL * 1200); - } - } - - /** - * Has the server owner denied plugin metrics? - * - * @return - */ - public boolean isOptOut() - { - synchronized (optOutLock) - { - try - { - // Reload the metrics file - configuration.load(CONFIG_FILE); - } - catch (IOException ex) - { - Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); - return true; - } - catch (InvalidConfigurationException ex) - { - Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); - return true; - } - return configuration.getBoolean("opt-out", false); - } - } - - /** - * Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task. - * - * @throws IOException - */ - public void enable() throws IOException - { - // This has to be synchronized or it can collide with the check in the task. - synchronized (optOutLock) - { - // Check if the server owner has already set opt-out, if not, set it. - if (isOptOut()) - { - configuration.set("opt-out", false); - configuration.save(configurationFile); - } - - // Enable Task, if it is not running - if (taskId < 0) - { - start(); - } - } - } - - /** - * Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task. - * - * @throws IOException - */ - public void disable() throws IOException - { - // This has to be synchronized or it can collide with the check in the task. - synchronized (optOutLock) - { - // Check if the server owner has already set opt-out, if not, set it. - if (!isOptOut()) - { - configuration.set("opt-out", true); - final File file = new File(CONFIG_FILE); - configuration.save(file); - } - - // Disable Task, if it is running - if (taskId >= 0) - { - this.plugin.getServer().getScheduler().cancelTask(taskId); - taskId = -1; - } - } - } - - /** - * Generic method that posts a plugin to the metrics website - */ - private void postPlugin(final boolean isPing) throws IOException - { - // The plugin's description file containg all of the plugin data such as name, version, author, etc - final PluginDescriptionFile description = plugin.getDescription(); - - // Construct the post data - final StringBuilder data = new StringBuilder(); - data.append(encode("guid")).append('=').append(encode(guid)); - encodeDataPair(data, "version", description.getVersion()); - encodeDataPair(data, "server", Bukkit.getVersion()); - encodeDataPair(data, "players", Integer.toString(Bukkit.getServer().getOnlinePlayers().length)); - encodeDataPair(data, "revision", String.valueOf(REVISION)); - - // If we're pinging, append it - if (isPing) - { - encodeDataPair(data, "ping", "true"); - } - - // Acquire a lock on the graphs, which lets us make the assumption we also lock everything - // inside of the graph (e.g plotters) - synchronized (graphs) - { - final Iterator iter = graphs.iterator(); - - while (iter.hasNext()) - { - final Graph graph = iter.next(); - - // Because we have a lock on the graphs set already, it is reasonable to assume - // that our lock transcends down to the individual plotters in the graphs also. - // Because our methods are private, no one but us can reasonably access this list - // without reflection so this is a safe assumption without adding more code. - for (Plotter plotter : graph.getPlotters()) - { - // The key name to send to the metrics server - // The format is C-GRAPHNAME-PLOTTERNAME where separator - is defined at the top - // Legacy (R4) submitters use the format Custom%s, or CustomPLOTTERNAME - final String key = String.format("C%s%s%s%s", CUSTOM_DATA_SEPARATOR, graph.getName(), CUSTOM_DATA_SEPARATOR, plotter.getColumnName()); - - // The value to send, which for the foreseeable future is just the string - // value of plotter.getValue() - final String value = Integer.toString(plotter.getValue()); - - // Add it to the http post data :) - encodeDataPair(data, key, value); - } - } - } - - // Create the url - final URL url = new URL(BASE_URL + String.format(REPORT_URL, description.getName())); - - // Connect to the website - URLConnection connection; - - // Mineshafter creates a socks proxy, so we can safely bypass it - // It does not reroute POST requests so we need to go around it - if (isMineshafterPresent()) - { - connection = url.openConnection(Proxy.NO_PROXY); - } - else - { - connection = url.openConnection(); - } - - connection.setDoOutput(true); - - // Write the data - final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); - writer.write(data.toString()); - writer.flush(); - - // Now read the response - final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); - final String response = reader.readLine(); - - // close resources - writer.close(); - reader.close(); - - if (response == null || response.startsWith("ERR")) - { - throw new IOException(response); //Throw the exception - } - else - { - // Is this the first update this hour? - if (response.contains("OK This is your first update this hour")) - { - synchronized (graphs) - { - final Iterator iter = graphs.iterator(); - - while (iter.hasNext()) - { - final Graph graph = iter.next(); - - for (Plotter plotter : graph.getPlotters()) - { - plotter.reset(); - } - } - } - } - } - //if (response.startsWith("OK")) - We should get "OK" followed by an optional description if everything goes right - } - - /** - * Check if mineshafter is present. If it is, we need to bypass it to send POST requests - * - * @return - */ - private boolean isMineshafterPresent() - { - try - { - Class.forName("mineshafter.MineServer"); - return true; - } - catch (Exception e) - { - return false; - } - } - - /** - *

Encode a key/value data pair to be used in a HTTP post request. This INCLUDES a & so the first key/value pair - * MUST be included manually, e.g:

- * - * StringBuffer data = new StringBuffer(); - * data.append(encode("guid")).append('=').append(encode(guid)); - * encodeDataPair(data, "version", description.getVersion()); - * - * - * @param buffer - * @param key - * @param value - * @return - */ - private static void encodeDataPair(final StringBuilder buffer, final String key, final String value) throws UnsupportedEncodingException - { - buffer.append('&').append(encode(key)).append('=').append(encode(value)); - } - - /** - * Encode text as UTF-8 - * - * @param text - * @return - */ - private static String encode(final String text) throws UnsupportedEncodingException - { - return URLEncoder.encode(text, "UTF-8"); - } - - - /** - * Represents a custom graph on the website - */ - public static class Graph - { - /** - * The graph's name, alphanumeric and spaces only :) If it does not comply to the above when submitted, it is - * rejected - */ - private final String name; - /** - * The set of plotters that are contained within this graph - */ - private final Set plotters = new LinkedHashSet(); - - private Graph(final String name) - { - this.name = name; - } - - /** - * Gets the graph's name - * - * @return - */ - public String getName() - { - return name; - } - - /** - * Add a plotter to the graph, which will be used to plot entries - * - * @param plotter - */ - public void addPlotter(final Plotter plotter) - { - plotters.add(plotter); - } - - /** - * Remove a plotter from the graph - * - * @param plotter - */ - public void removePlotter(final Plotter plotter) - { - plotters.remove(plotter); - } - - /** - * Gets an unmodifiable set of the plotter objects in the graph - * - * @return - */ - public Set getPlotters() - { - return Collections.unmodifiableSet(plotters); - } - - @Override - public int hashCode() - { - return name.hashCode(); - } - - @Override - public boolean equals(final Object object) - { - if (!(object instanceof Graph)) - { - return false; - } - - final Graph graph = (Graph)object; - return graph.name.equals(name); - } - } - - - /** - * Interface used to collect custom data for a plugin - */ - public static abstract class Plotter - { - /** - * The plot's name - */ - private final String name; - - /** - * Construct a plotter with the default plot name - */ - public Plotter() - { - this("Default"); - } - - /** - * Construct a plotter with a specific plot name - * - * @param name - */ - public Plotter(final String name) - { - this.name = name; - } - - /** - * Get the current value for the plotted point - * - * @return - */ - public abstract int getValue(); - - /** - * Get the column name for the plotted point - * - * @return the plotted point's column name - */ - public String getColumnName() - { - return name; - } - - /** - * Called after the website graphs have been updated - */ - public void reset() - { - } - - @Override - public int hashCode() - { - return getColumnName().hashCode() + getValue(); - } - - @Override - public boolean equals(final Object object) - { - if (!(object instanceof Plotter)) - { - return false; - } - - final Plotter plotter = (Plotter)object; - return plotter.name.equals(name) && plotter.getValue() == getValue(); - } - } -} \ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/metrics/MetricsListener.java b/Essentials/src/com/earth2me/essentials/metrics/MetricsListener.java deleted file mode 100644 index 77af2b5da..000000000 --- a/Essentials/src/com/earth2me/essentials/metrics/MetricsListener.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.earth2me.essentials.metrics; - -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IUser; -import java.util.logging.Level; -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.PlayerJoinEvent; - - -public class MetricsListener implements Listener -{ - private final transient Server server; - private final transient IEssentials ess; - private final transient MetricsStarter starter; - - public MetricsListener(final IEssentials parent, final MetricsStarter starter) - { - this.ess = parent; - this.server = parent.getServer(); - this.starter = starter; - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onPlayerJoin(final PlayerJoinEvent event) - { - /*final IUser player = ess.getUser(event.getPlayer()); - if (ess.getSettings().isMetricsEnabled() == false && (player.isAuthorized("essentials.essentials") || player.isAuthorized("bukkit.broadcast.admin"))) - { - player.sendMessage("PluginMetrics collects minimal statistic data, starting in about 5 minutes."); - player.sendMessage("To opt out, run /essentials opt-out"); - ess.getLogger().log(Level.INFO, "[Metrics] Admin join - Starting 5 minute opt-out period."); - ess.getSettings().setMetricsEnabled(true); - ess.getScheduler().scheduleAsyncDelayedTask(ess, starter, 5 * 1200); - }*/ - } -} diff --git a/Essentials/src/com/earth2me/essentials/metrics/MetricsStarter.java b/Essentials/src/com/earth2me/essentials/metrics/MetricsStarter.java deleted file mode 100644 index 82bab0047..000000000 --- a/Essentials/src/com/earth2me/essentials/metrics/MetricsStarter.java +++ /dev/null @@ -1,237 +0,0 @@ -package com.earth2me.essentials.metrics; - -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.ISettings; -import com.earth2me.essentials.economy.register.Method; -import com.earth2me.essentials.economy.register.methods.VaultEco; -import com.earth2me.essentials.metrics.Metrics.Graph; -import com.earth2me.essentials.metrics.Metrics.Plotter; -//import com.earth2me.essentials.register.payment.Method; -//import com.earth2me.essentials.register.payment.methods.VaultEco; -import com.nijikokun.bukkit.Permissions.Permissions; -import java.util.Locale; -import java.util.logging.Level; -import java.util.logging.Logger; -import lombok.Cleanup; - - -public class MetricsStarter implements Runnable -{ - private final IEssentials ess; - private transient Boolean start; - - - private enum Modules - { - Essentials, - EssentialsAntiCheat, - EssentialsChat, - EssentialsSpawn, - EssentialsProtect, - EssentialsGeoIP, - EssentialsXMPP - }; - - public MetricsStarter(final IEssentials plugin) - { - ess = plugin; - /* - try - { - - final Metrics metrics = new Metrics(ess); - ess.setMetrics(metrics); - - @Cleanup - ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - if (!metrics.isOptOut()) - { - if (settings.getData().getGeneral().isMetricsEnabled()) - { - start = true; - } - else - { - ess.getLogger().info("This plugin collects minimal statistic data and sends it to http://metrics.essentials3.net."); - ess.getLogger().info("You can opt out by running /essentials opt-out"); - ess.getLogger().info("This will start 5 minutes after the first admin/op joins."); - start = false; - } - return; - } - } - catch (Exception ex) - { - metricsError(ex); - }*/ - } - - @Override - public void run() - { - try - { - final Metrics metrics = ess.getMetrics(); - - final Graph moduleGraph = metrics.createGraph("Modules Used"); - for (Modules module : Modules.values()) - { - final String moduleName = module.toString(); - if (ess.getServer().getPluginManager().isPluginEnabled(moduleName)) - { - moduleGraph.addPlotter(new SimplePlotter(moduleName)); - } - } - - final Graph localeGraph = metrics.createGraph("Locale"); - localeGraph.addPlotter(new SimplePlotter(ess.getI18n().getCurrentLocale().getDisplayLanguage(Locale.ENGLISH))); - - final Graph featureGraph = metrics.createGraph("Features"); - featureGraph.addPlotter(new Plotter("Unique Accounts") - { - @Override - public int getValue() - { - return ess.getUserMap().getUniqueUsers(); - } - }); - featureGraph.addPlotter(new Plotter("Jails") - { - @Override - public int getValue() - { - return ess.getJails().getCount(); - } - }); - featureGraph.addPlotter(new Plotter("Kits") - { - @Override - public int getValue() - { - int size = 0; - try - { - size = ess.getKits().getList().size(); - } - catch (Exception ex) - { - } - return size; - - } - }); - featureGraph.addPlotter(new Plotter("Warps") - { - @Override - public int getValue() - { - return ess.getWarps().getList().size(); - } - }); - - final Graph enabledGraph = metrics.createGraph("EnabledFeatures"); - enabledGraph.addPlotter(new SimplePlotter("Total")); - @Cleanup - ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - final String BKcommand = settings.getData().getGeneral().getBackup().getCommand();; - if (BKcommand != null && !"".equals(BKcommand)) - { - enabledGraph.addPlotter(new SimplePlotter("Backup")); - } - if (ess.getJails().getCount() > 0) - { - enabledGraph.addPlotter(new SimplePlotter("Jails")); - } - if (ess.getKits().getList().size() > 0) - { - enabledGraph.addPlotter(new SimplePlotter("Kits")); - } - if (ess.getWarps().getList().size() > 0) - { - enabledGraph.addPlotter(new SimplePlotter("Warps")); - } - //todo - enable once settings are in - /* - if (!ess.getSettings().areSignsDisabled()) - { - enabledGraph.addPlotter(new SimplePlotter("Signs")); - } - if (ess.getSettings().getAutoAfk() > 0) - { - enabledGraph.addPlotter(new SimplePlotter("AutoAFK")); - } - if (ess.getSettings().changeDisplayName()) - { - enabledGraph.addPlotter(new SimplePlotter("DisplayName")); - } - if (ess.getSettings().getChatRadius() >= 1) - { - enabledGraph.addPlotter(new SimplePlotter("LocalChat")); - } - */ - final Graph depGraph = metrics.createGraph("Dependencies"); - final Method method = ess.getPaymentMethod().getMethod(); - if (method != null) - { - String version; - if (method instanceof VaultEco) - { - version = ((VaultEco)method).getEconomy(); - } - else - { - version = method.getVersion(); - final int dashPosition = version.indexOf('-'); - if (dashPosition > 0) - { - version = version.substring(0, dashPosition); - } - } - depGraph.addPlotter(new SimplePlotter(method.getName() + " " + version)); - } - //todo - verify - depGraph.addPlotter(new SimplePlotter(Permissions.getInstance().getName())); - - metrics.start(); - - } - catch (Exception ex) - { - metricsError(ex); - } - } - - public void metricsError(final Exception ex) - { - if (ess.getSettings().isDebug()) - { - ess.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage(), ex); - } - else - { - ess.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); - } - } - - public Boolean getStart() - { - return start; - } - - - private class SimplePlotter extends Plotter - { - public SimplePlotter(final String name) - { - super(name); - } - - @Override - public int getValue() - { - return 1; - } - } -} \ No newline at end of file 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 4819f5ced..000000000 --- a/Essentials/src/com/earth2me/essentials/permissions/AbstractSuperpermsPermission.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.earth2me.essentials.permissions; - -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.IPermission; -import org.bukkit.command.CommandSender; -import org.bukkit.permissions.Permission; -import org.bukkit.permissions.PermissionDefault; - - -public abstract class AbstractSuperpermsPermission implements IPermission -{ - protected Permission bukkitPerm; - - @Override - public Permission getBukkitPermission() - { - if (bukkitPerm != null) - { - return bukkitPerm; - } - else - { - return Util.registerPermission(getPermission(), getPermissionDefault()); - } - } - - /** - * PermissionDefault is OP, if the method is not overwritten. - * @return - */ - @Override - public PermissionDefault getPermissionDefault() - { - return PermissionDefault.OP; - } - - @Override - public boolean isAuthorized(final CommandSender sender) - { - return sender.hasPermission(getBukkitPermission()); - } -} 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 3c033913f..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 getPermission() - { - 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 162ec46c0..000000000 --- a/Essentials/src/com/earth2me/essentials/permissions/GivePermissions.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.earth2me.essentials.permissions; - -import com.earth2me.essentials.api.IPermission; -import java.util.EnumMap; -import java.util.Locale; -import java.util.Map; -import org.bukkit.Material; -import org.bukkit.permissions.PermissionDefault; - -public class GivePermissions { - private static Map permissions = new EnumMap(Material.class); - - 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 PermissionDefault getPermissionDefault() - { - return PermissionDefault.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 980af104f..000000000 --- a/Essentials/src/com/earth2me/essentials/permissions/ItemPermissions.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.earth2me.essentials.permissions; - -import com.earth2me.essentials.api.IPermission; -import java.util.EnumMap; -import java.util.Locale; -import java.util.Map; -import org.bukkit.Material; -import org.bukkit.permissions.PermissionDefault; - - -public class ItemPermissions -{ - private static Map permissions = new EnumMap(Material.class); - - 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 PermissionDefault getPermissionDefault() - { - return PermissionDefault.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 b21e0712d..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 java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import org.bukkit.permissions.PermissionDefault; - - -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 PermissionDefault getPermissionDefault() - { - return PermissionDefault.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 80437fed4..000000000 --- a/Essentials/src/com/earth2me/essentials/permissions/Permissions.java +++ /dev/null @@ -1,138 +0,0 @@ -package com.earth2me.essentials.permissions; - -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.IPermission; -import java.util.Locale; -import org.bukkit.command.CommandSender; -import org.bukkit.permissions.Permission; -import org.bukkit.permissions.PermissionDefault; - - -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_IGNORE_EXEMPT, - CHAT_SPY, - CLEARINVENTORY_OTHERS, - DELHOME_OTHERS, - ECO_LOAN(PermissionDefault.FALSE), - EXP_GIVE, - EXP_GIVE_OTHERS, - EXP_SET, - EXP_SET_OTHERS, - EXP_OTHERS, - FEED_OTHERS, - FLY_OTHERS, - GAMEMODE_OTHERS, - GEOIP_HIDE(PermissionDefault.FALSE), - GEOIP_SHOW(PermissionDefault.TRUE), - GETPOS_OTHERS, - GOD_OTHERS, - HEAL_COOLDOWN_BYPASS, - HEAL_OTHERS, - HELPOP_RECEIVE, - HOME_OTHERS, - JAIL_EXEMPT, - JOINFULLSERVER, - INVSEE_MODIFY, - INVSEE_PREVENT_MODIFY, - KEEPXP, - 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(PermissionDefault.FALSE), - POWERTOOL_APPEND, - PTIME_OTHERS, - PVPDELAY_EXEMPT, - REPAIR_ARMOR, - REPAIR_ENCHANTED, - SEEN_BANREASON, - SEEN_EXTRA, - SETHOME_MULTIPLE, - SETHOME_OTHERS, - SLEEPINGIGNORED, - SPAWN_OTHERS, - SUDO_EXEMPT, - TELEPORT_COOLDOWN_BYPASS, - TELEPORT_HIDDEN, - TELEPORT_OTHERS, - TELEPORT_TIMER_BYPASS, - TEMPBAN_EXEMPT, - TEMPBAN_OFFLINE, - TIME_SET, - TOGGLEJAIL_OFFLINE, - TPA, - TPAALL, - TPAHERE, - TPOHERE, - UNLIMITED_OTHERS, - WARP_LIST(PermissionDefault.TRUE), - WARP_OTHERS, - VANISH_SEE_OTHERS; - private static final String base = "essentials."; - private final String permission; - private final PermissionDefault defaultPerm; - private transient Permission bukkitPerm = null; - - private Permissions() - { - this(PermissionDefault.OP); - } - - private Permissions(final PermissionDefault defaultPerm) - { - permission = base + toString().toLowerCase(Locale.ENGLISH).replace('_', '.'); - this.defaultPerm = defaultPerm; - } - - @Override - public String getPermission() - { - return permission; - } - - @Override - public Permission getBukkitPermission() - { - if (bukkitPerm != null) - { - return bukkitPerm; - } - else - { - return Util.registerPermission(getPermission(), getPermissionDefault()); - } - } - - @Override - public PermissionDefault getPermissionDefault() - { - return this.defaultPerm; - } - - @Override - public boolean isAuthorized(CommandSender sender) - { - return sender.hasPermission(getBukkitPermission()); - } -} 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 dbe7df95b..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 java.util.EnumMap; -import java.util.Locale; -import java.util.Map; -import org.bukkit.Material; - -public class UnlimitedItemPermissions -{ - private static Map permissions = new EnumMap(Material.class); - - 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 7f08ad3a2..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 java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import org.bukkit.permissions.PermissionDefault; - - -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 PermissionDefault getPermissionDefault() - { - return PermissionDefault.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 512df1e0d..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.replaceFormat(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 7e3eac946..000000000 --- a/Essentials/src/com/earth2me/essentials/ranks/RanksStorage.java +++ /dev/null @@ -1,207 +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 -{ - - @Override - public void finishRead() - { - - } - - @Override - public void finishWrite() - { - - } - public RanksStorage(final IEssentials ess) - { - super(ess, Ranks.class); - onReload(); - } - - @Override - public File getStorageFile() - { - return new File(ess.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.replaceFormat(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 36c9742cf..000000000 --- a/Essentials/src/com/earth2me/essentials/ranks/VaultGroups.java +++ /dev/null @@ -1,124 +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) - { - RegisteredServiceProvider rsp = ess.getServer().getServicesManager().getRegistration(Chat.class); - Chat chat = rsp.getProvider(); - return chat.getPlayerInfoDouble(player.getBase(), "healcooldown", 0); - } - - @Override - public double getTeleportCooldown(IUser player) - { - RegisteredServiceProvider rsp = ess.getServer().getServicesManager().getRegistration(Chat.class); - Chat chat = rsp.getProvider(); - return chat.getPlayerInfoDouble(player.getBase(), "teleportcooldown", 0); - } - - @Override - public double getTeleportDelay(IUser player) - { - RegisteredServiceProvider rsp = ess.getServer().getServicesManager().getRegistration(Chat.class); - Chat chat = rsp.getProvider(); - return chat.getPlayerInfoDouble(player.getBase(), "teleportdelay", 0); - } - - @Override - public String getPrefix(IUser player) - { - RegisteredServiceProvider rsp = ess.getServer().getServicesManager().getRegistration(Chat.class); - Chat chat = rsp.getProvider(); - return chat.getPlayerPrefix(player.getBase()); - } - - @Override - public String getSuffix(IUser player) - { - RegisteredServiceProvider rsp = ess.getServer().getServicesManager().getRegistration(Chat.class); - Chat chat = rsp.getProvider(); - return chat.getPlayerSuffix(player.getBase()); - } - - @Override - public int getHomeLimit(IUser player) - { - RegisteredServiceProvider rsp = ess.getServer().getServicesManager().getRegistration(Chat.class); - Chat chat = rsp.getProvider(); - return chat.getPlayerInfoInteger(player.getBase(), "homes", 0); - } - - @Override - public MessageFormat getChatFormat(final IUser player) - { - String format = getRawChatFormat(player); - format = Util.replaceFormat(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) - { - RegisteredServiceProvider rsp = ess.getServer().getServicesManager().getRegistration(Chat.class); - Chat chat = rsp.getProvider(); - 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) - { - RegisteredServiceProvider rsp = ess.getServer().getServicesManager().getRegistration(Chat.class); - Chat chat = rsp.getProvider(); - return chat.getPrimaryGroup(player.getBase()); - } - - @Override - public boolean inGroup(IUser player, String groupname) - { - RegisteredServiceProvider rsp = ess.getServer().getServicesManager().getRegistration(Chat.class); - Chat chat = rsp.getProvider(); - 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 9647d3bed..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/General.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.earth2me.essentials.settings; - -import com.earth2me.essentials.storage.Comment; -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 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; - @Comment( - - { - "The delay, in seconds, a player can't be attacked by other players after he has been teleported by a command", - "This will also prevent that the player can attack other players" - }) - private long teleportInvulnerability = 0; - - public long getTeleportInvulnerability() - { - return teleportInvulnerability * 1000; - } - - @Comment( - { - "Set to true to enable per-world permissions for teleporting between worlds with essentials commands", - "This applies to /world, /back, /tp[a|o][here|all], but not warps.", - "Give someone permission to teleport to a world with essentials.world." - }) - private boolean worldTeleportPermissions = false; - private boolean worldHomePermissions = false; - - - @Comment("Prevent creatures spawning") - private Map creatureSpawn = new HashMap(); - - public boolean getPreventSpawn(String creatureName) - { - if (creatureSpawn == null) - { - return false; - } - return creatureSpawn.get(creatureName); - } - - @Comment("Delay to wait before people can cause attack damage after logging in ") - private long loginAttackDelay = 0; - - public long getLoginAttackDelay() - { - return loginAttackDelay * 1000; - } -} 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 3adb4ec1e..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.Location; -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(Location.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 ea0631124..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/Kit.java +++ /dev/null @@ -1,20 +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 2554ba9e8..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/SettingsHolder.java +++ /dev/null @@ -1,76 +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 -{ - - @Override - public void finishRead() - { - - } - - @Override - public void finishWrite() - { - - } - 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.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 451ef49b1..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.Location; -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(Location.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 816262a8e..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/SpawnsHolder.java +++ /dev/null @@ -1,320 +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.Location.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 -{ - - @Override - public void finishRead() - { - - } - - @Override - public void finishWrite() - { - - } - - public SpawnsHolder(final IEssentials ess) - { - super(ess, Spawns.class); - onReload(); - registerListeners(); - } - - @Override - public File getStorageFile() - { - return new File(ess.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.Location(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).getBukkitLocation(); - } - 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.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 f9c506b58..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.Location; -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 Location 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 a14db0339..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/WarpHolder.java +++ /dev/null @@ -1,48 +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 -{ - - @Override - public void finishRead() - { - - } - - @Override - public void finishWrite() - { - - } - - 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 95228684b..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/WorldOptions.java +++ /dev/null @@ -1,16 +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 2060e08e0..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 -{ - private boolean showCities = false; - private boolean downloadIfMissing = true; - private String downloadUrlCity = "http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz"; - private 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 5942b678f..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(); - private boolean showOnWhois = true; - private 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 446b6e138..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/protect/Prevent.java +++ /dev/null @@ -1,51 +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.EntityType; - - -@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(EntityType.class) - @MapValueType(Boolean.class) - private Map spawn = new HashMap(); - - public Prevent() - { - spawn.put(EntityType.PIG, false); - pistonPush.add(Material.GLASS); - } -} \ 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 70a137f90..000000000 --- a/Essentials/src/com/earth2me/essentials/settings/protect/Protect.java +++ /dev/null @@ -1,52 +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(); - - public Protect() - { - alertOnPlacement.add(Material.LAVA); - alertOnUse.add(Material.LAVA_BUCKET); - alertOnBreak.add(Material.GLASS); - } -} 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 037fa4292..000000000 --- a/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileReader.java +++ /dev/null @@ -1,100 +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; - - -public abstract class AbstractDelayedYamlFileReader implements Runnable -{ - - private final transient Class clazz; - protected final transient IEssentials plugin; - private final transient ReentrantLock lock = new ReentrantLock(); - - public AbstractDelayedYamlFileReader(final IEssentials ess, final Class clazz) - { - this.clazz = clazz; - this.plugin = ess; - } - - public void schedule(boolean instant) - { - if (instant || ((Essentials)plugin).testing) - { - run(); - } - else - { - plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, this); - } - } - - public abstract File onStart() throws IOException; - - @Override - public void run() - { - File file = null; - lock.lock(); - try - { - file = onStart(); - try - { - final FileReader reader = new FileReader(file); - try - { - final T object = new YamlStorageReader(reader, plugin).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) - { - onException(ex); - if (plugin.getSettings() == null || plugin.getSettings().isDebug()) - { - Bukkit.getLogger().log(Level.INFO, "File not found: " + file.toString()); - } - } - 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 d3289310e..000000000 --- a/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileWriter.java +++ /dev/null @@ -1,84 +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 Plugin plugin; - private final transient ReentrantLock lock = new ReentrantLock(); - - public AbstractDelayedYamlFileWriter(final IEssentials ess) - { - this.plugin = ess; - } - - public void schedule() - { - if (((Essentials)plugin).testing) - { - run(); - } - else - { - plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, 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 ea48dc269..000000000 --- a/Essentials/src/com/earth2me/essentials/storage/AsyncStorageObjectHolder.java +++ /dev/null @@ -1,191 +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 void finishRead(); - - public abstract void finishWrite(); - - 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(); - finishWrite(); - } - } - - - 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 93412be56..000000000 --- a/Essentials/src/com/earth2me/essentials/storage/BukkitConstructor.java +++ /dev/null @@ -1,441 +0,0 @@ -package com.earth2me.essentials.storage; - -import com.earth2me.essentials.Essentials; -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.Material; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.ItemStack; -import org.bukkit.material.MaterialData; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.java.JavaPluginLoader; -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 Plugin plugin; - - public BukkitConstructor(final Class clazz, final Plugin 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.getMaterial(typeId); - } - else - { - mat = Material.matchMaterial(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(Location.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 Location(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 (plugin == null || (plugin instanceof Essentials && ((Essentials)plugin).testing)) - { - clazz = super.getClassForNode(node); - } - else - { - final JavaPluginLoader jpl = (JavaPluginLoader)plugin.getPluginLoader(); - clazz = jpl.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/Location.java b/Essentials/src/com/earth2me/essentials/storage/Location.java deleted file mode 100644 index 6778027d7..000000000 --- a/Essentials/src/com/earth2me/essentials/storage/Location.java +++ /dev/null @@ -1,115 +0,0 @@ -package com.earth2me.essentials.storage; - -import java.lang.ref.WeakReference; -import java.util.UUID; -import org.bukkit.Bukkit; -import org.bukkit.World; - - -public class Location -{ - 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 Location(org.bukkit.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 Location(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 Location(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 org.bukkit.Location getBukkitLocation() throws WorldNotLoadedException - { - - org.bukkit.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 = new org.bukkit.Location(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/ManagedFile.java b/Essentials/src/com/earth2me/essentials/storage/ManagedFile.java deleted file mode 100644 index 509783955..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.getDataFolder(), filename); - - if (file.exists()) - { - try - { - if (checkForVersion(file, ess.getDescription().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 d3d118483..000000000 --- a/Essentials/src/com/earth2me/essentials/storage/StorageObjectMap.java +++ /dev/null @@ -1,138 +0,0 @@ -package com.earth2me.essentials.storage; - -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.InvalidNameException; -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; -import org.bukkit.Bukkit; - - -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.getDataFolder(), folderName); - if (!folder.exists()) - { - folder.mkdirs(); - } - loadAllObjectsAsync(); - } - - private void loadAllObjectsAsync() - { - ess.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) - { - Bukkit.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/YamlStorageReader.java b/Essentials/src/com/earth2me/essentials/storage/YamlStorageReader.java deleted file mode 100644 index ee7aa45cd..000000000 --- a/Essentials/src/com/earth2me/essentials/storage/YamlStorageReader.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.earth2me.essentials.storage; - -import java.io.Reader; -import java.lang.reflect.Field; -import java.util.*; -import java.util.concurrent.locks.ReentrantLock; -import org.bukkit.plugin.Plugin; -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 Plugin plugin; - - public YamlStorageReader(final Reader reader, final Plugin 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 6e641db69..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 Location) - { - writeLocation((Location)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 Location) - { - writeLocation((Location)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 Location) - { - writeLocation((Location)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 Location 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 18667c8ca..000000000 --- a/Essentials/src/com/earth2me/essentials/user/IOfflinePlayer.java +++ /dev/null @@ -1,20 +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); - - void setName(final String name); -} \ 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 d6266df49..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/User.java b/Essentials/src/com/earth2me/essentials/user/User.java deleted file mode 100644 index bedfd44f2..000000000 --- a/Essentials/src/com/earth2me/essentials/user/User.java +++ /dev/null @@ -1,778 +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.craftbukkit.InventoryWorkaround; -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 java.util.logging.Logger; -import lombok.Cleanup; -import lombok.Getter; -import lombok.Setter; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.OfflinePlayer; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - - -public class User extends UserBase implements IUser -{ - private CommandSender replyTo = null; - @Getter - private transient IUser teleportRequester; - @Getter - private transient boolean tpRequestHere; - @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; - @Getter - private transient boolean vanished; - @Getter - @Setter - private boolean invSee = false; - private transient Location afkPosition; - private static final Logger logger = Bukkit.getLogger(); - private AtomicBoolean gotMailInfo = new AtomicBoolean(false); - - public User(final Player base, final IEssentials ess) - { - super(base, ess); - teleport = new Teleport(this, ess); - } - - public User(final OfflinePlayer offlinePlayer, final IEssentials ess) - { - super(offlinePlayer, 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 finishRead() - { - } - - @Override - public void finishWrite() - { - } - - @Override - public void update(final Player base) - { - super.update(base); - } - - @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.Location(getLocation())); - } - finally - { - unlock(); - } - } - 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) - { - logger.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 (isOnlineUser() && 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 - @Override - 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 - @Override - 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(); - } - } - - @Override - 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(); - } - } - - @Override - 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 (Player player : ess.getServer().getOnlinePlayers()) - { - final IUser user = ess.getUser(player); - 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(); - } - } - - @Override - public Location getAfkPosition() - { - return afkPosition; - } - - @Override - 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 player, boolean here) - { - teleportRequestTime = System.currentTimeMillis(); - teleportRequester = player; - tpRequestHere = here; - } - - @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.getType() == Material.AIR) - { - 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 = InventoryWorkaround.addItem(getInventory(), true, oversizedStackSize, itemStack); - } - else - { - overfilled = InventoryWorkaround.addItem(getInventory(), 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; - } - - @Override - public void updateMoneyCache(double userMoney) - { - if (super.getMoney() != userMoney) - { - super.setMoney(userMoney); - } - } - - @Override - public boolean canAfford(double amount, boolean b) - { - return true; - } - private transient long teleportInvulnerabilityTimestamp = 0; - - public void enableInvulnerabilityAfterTeleport() - { - @Cleanup - final ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - - final long time = settings.getData().getGeneral().getTeleportInvulnerability(); - if (time > 0) - { - teleportInvulnerabilityTimestamp = System.currentTimeMillis() + time; - } - } - - @Override - public void resetInvulnerabilityAfterTeleport() - { - if (teleportInvulnerabilityTimestamp != 0 - && teleportInvulnerabilityTimestamp < System.currentTimeMillis()) - { - teleportInvulnerabilityTimestamp = 0; - } - } - - @Override - public boolean hasInvulnerabilityAfterTeleport() - { - return teleportInvulnerabilityTimestamp != 0 && teleportInvulnerabilityTimestamp >= System.currentTimeMillis(); - } - - @Override - public void setVanished(boolean set) - { - vanished = set; - if (set) - { - for (Player p : ess.getServer().getOnlinePlayers()) - { - if (!Permissions.VANISH_SEE_OTHERS.isAuthorized(ess.getUser(p))) - { - p.hidePlayer(getBase()); - } - } - setHidden(true); - ess.getVanishedPlayers().add(getName()); - } - else - { - for (Player p : ess.getServer().getOnlinePlayers()) - { - p.showPlayer(getBase()); - } - setHidden(false); - ess.getVanishedPlayers().remove(getName()); - } - } - - @Override - public void setName(String name) - { - //todo - //throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void toggleVanished() - { - final boolean set = !vanished; - this.setVanished(set); - } -} 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 436a9c76f..000000000 --- a/Essentials/src/com/earth2me/essentials/user/UserBase.java +++ /dev/null @@ -1,458 +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.IUser; -import com.earth2me.essentials.api.InvalidNameException; -import com.earth2me.essentials.permissions.Permissions; -import com.earth2me.essentials.storage.AsyncStorageObjectHolder; -import com.earth2me.essentials.storage.Location.WorldNotLoadedException; -import java.io.File; -import java.io.IOException; -import java.util.*; -import lombok.Cleanup; -import lombok.Delegate; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.OfflinePlayer; -import org.bukkit.command.CommandSender; -import org.bukkit.configuration.serialization.ConfigurationSerializable; -import org.bukkit.entity.Entity; -import org.bukkit.entity.HumanEntity; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; -import org.bukkit.permissions.Permissible; -import org.bukkit.permissions.Permission; -import org.bukkit.permissions.ServerOperator; - - -public abstract class UserBase extends AsyncStorageObjectHolder implements Player, IOfflineUser -{ - @Delegate(types = - { - Player.class, Entity.class, CommandSender.class, ServerOperator.class, - HumanEntity.class, ConfigurationSerializable.class, LivingEntity.class, - Permissible.class - }, excludes = - { - IOfflinePlayer.class - }) - protected Player base; - protected transient OfflinePlayer offlinePlayer; - - public UserBase(final Player base, final IEssentials ess) - { - super(ess, UserData.class); - this.base = base; - onReload(); - } - - public UserBase(final OfflinePlayer offlinePlayer, final IEssentials ess) - { - super(ess, UserData.class); - this.offlinePlayer = offlinePlayer; - 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 update(final OfflinePlayer offlinePlayer) - { - this.offlinePlayer = offlinePlayer; - } - - public void dispose() - { - this.offlinePlayer = Bukkit.getOfflinePlayer(base.getName()); - this.base = null; - } - - public boolean isOnlineUser() - { - return base != null; - } - - @Override - public String getName() - { - if (isOnlineUser()) - { - return base.getName(); - } - else - { - return offlinePlayer.getName(); - } - } - - @Override - public String getDisplayName() - { - if (isOnlineUser()) - { - return base.getDisplayName(); - } - else - { - return offlinePlayer.getName(); - } - } - - @Override - public Location getBedSpawnLocation() - { - return base.getBedSpawnLocation(); - } - - @Override - public void setBanned(boolean bln) - { - if (isOnlineUser()) - { - base.setBanned(bln); - } - else - { - offlinePlayer.setBanned(bln); - } - } - - @Override - public boolean hasPermission(Permission prmsn) - { - if (isOnlineUser()) - { - return base.hasPermission(prmsn); - } - else - { - return false; - } - } - - @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.Location(loc)); - } - finally - { - unlock(); - } - } - - public boolean toggleAfk() - { - acquireWriteLock(); - try - { - boolean ret = !getData().isAfk(); - getData().setAfk(ret); - return ret; - } - finally - { - unlock(); - } - } - - public void setGodModeEnabled(boolean set) - { - acquireWriteLock(); - try - { - getData().setGodmode(set); - } - finally - { - unlock(); - } - } - - public void setMuted(boolean mute) - { - acquireWriteLock(); - try - { - getData().setMuted(mute); - } - 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 IUser user) - { - acquireReadLock(); - try - { - return getData().getIgnore() == null ? false : getData().getIgnore().contains(user.getName().toLowerCase(Locale.ENGLISH)) && Permissions.CHAT_IGNORE_EXEMPT.isAuthorized(user); - } - finally - { - unlock(); - } - } - - public void setIgnoredPlayer(final IUser user, final boolean set) - { - acquireWriteLock(); - try - { - if (getData().getIgnore() == null) - { - getData().setIgnore(new HashSet()); - } - if (set) - { - getData().getIgnore().add(user.getName().toLowerCase(Locale.ENGLISH)); - } - else - { - getData().getIgnore().remove(user.getName().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.Location location : getData().getHomes().values()) - { - if (location.getWorldName().equals(loc.getWorld().getName())) - { - try - { - worldHomes.add(location.getBukkitLocation()); - } - 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 b181a5f24..000000000 --- a/Essentials/src/com/earth2me/essentials/user/UserData.java +++ /dev/null @@ -1,109 +0,0 @@ -package com.earth2me.essentials.user; - -import com.earth2me.essentials.storage.*; -import java.util.*; -import lombok.Data; -import lombok.EqualsAndHashCode; -import org.bukkit.Material; - - -@Data -@EqualsAndHashCode(callSuper = false) -public class UserData implements StorageObject -{ - public enum TimestampType - { - JAIL, MUTE, LASTHEAL, LASTTELEPORT, LOGIN, LOGOUT, KIT - } - private String nickname; - private Double money; - @MapValueType(Location.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 Location 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() - { - unlimited.add(Material.AIR); - unlimited.add(Material.ARROW); - unlimited.add(Material.APPLE); - powerTools.put(Material.DEAD_BUSH, Collections.singletonList("test")); - 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 96744da1d..000000000 --- a/Essentials/src/com/earth2me/essentials/user/UserMap.java +++ /dev/null @@ -1,97 +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.storage.StorageObjectMap; -import java.io.File; -import java.util.Locale; -import java.util.Set; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - - -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; - } -} 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 e553bc80c..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); - String parsetime = desc.replaceAll("[^0-9]", ""); - - if (parsetime.length() > 4) - { - throw new NumberFormatException(); - } - - if (parsetime.length() == 4) - { - hours += Integer.parseInt(parsetime.substring(0, 2)); - minutes += Integer.parseInt(parsetime.substring(2, 4)); - } - else if (parsetime.length() == 3) - { - hours += Integer.parseInt(parsetime.substring(0, 1)); - minutes += Integer.parseInt(parsetime.substring(1, 3)); - } - else if (parsetime.length() == 2) - { - hours += Integer.parseInt(parsetime.substring(0, 2)); - } - else if (parsetime.length() == 1) - { - hours += Integer.parseInt(parsetime.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 fbfed3f67..000000000 --- a/Essentials/src/com/earth2me/essentials/utils/Util.java +++ /dev/null @@ -1,447 +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.IUser; -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 de.bananaco.bpermissions.imp.Permissions; -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 URL_PATTERN = Pattern.compile("((?:(?:https?)://)?[\\w-_\\.]{2,})\\.([a-z]{2,3}(?:/\\S+)?)"); - private static transient final Pattern VANILLA_PATTERN = Pattern.compile("\u00A7+[0-9A-FK-ORa-fk-or]"); - private static transient final Pattern REPLACE_PATTERN = Pattern.compile("&([0-9a-fk-or])"); - private static transient final Pattern VANILLA_COLOR_PATTERN = Pattern.compile("\u00A7+[0-9A-Fa-f]"); - private static transient final Pattern VANILLA_MAGIC_PATTERN = Pattern.compile("\u00A7+[Kk]"); - private static transient final Pattern VANILLA_FORMAT_PATTERN = Pattern.compile("\u00A7+[L-ORl-or]"); - private static transient final Pattern REPLACE_COLOR_PATTERN = Pattern.compile("&([0-9a-f])"); - private static transient final Pattern REPLACE_MAGIC_PATTERN = Pattern.compile("&(k)"); - private static transient final Pattern REPLACE_FORMAT_PATTERN = Pattern.compile("&([l-or])"); - - public static String stripFormat(final String input) - { - if (input == null) - { - return null; - } - return VANILLA_PATTERN.matcher(input).replaceAll(""); - } - - public static String replaceFormat(final String input) - { - if (input == null) - { - return null; - } - return REPLACE_PATTERN.matcher(input).replaceAll("\u00a7$1"); - } - - public static String blockURL(final String input) - { - if (input == null) - { - return null; - } - String text = URL_PATTERN.matcher(input).replaceAll("$1 $2"); - while (URL_PATTERN.matcher(text).find()) - { - text = URL_PATTERN.matcher(text).replaceAll("$1 $2"); - } - return text; - } - - public static String formatString(final IUser user, final String permBase, final String input) - { - if (input == null) - { - return null; - } - String message; - if (Permissions.hasPermission(user.getBase(), permBase + ".color")) - { - message = Util.replaceColor(input, REPLACE_COLOR_PATTERN); - } - else - { - message = Util.stripColor(input, VANILLA_COLOR_PATTERN); - } - if (Permissions.hasPermission(user.getBase(), permBase + ".magic")) - { - message = Util.replaceColor(message, REPLACE_MAGIC_PATTERN); - } - else - { - message = Util.stripColor(message, VANILLA_MAGIC_PATTERN); - } - if (Permissions.hasPermission(user.getBase(), permBase + ".format")) - { - message = Util.replaceColor(message, REPLACE_FORMAT_PATTERN); - } - else - { - message = Util.stripColor(message, VANILLA_FORMAT_PATTERN); - } - return message; - } - - public static String formatMessage(final IUser user, final String permBase, final String input) - { - if (input == null) - { - return null; - } - String message = formatString(user, permBase, input); - if (!Permissions.hasPermission(user.getBase(), permBase + ".url")) - { - message = Util.blockURL(message); - } - return message; - } - - public static String stripColor(final String input) - { - if (input == null) - { - return null; - } - - return VANILLA_COLOR_PATTERN.matcher(input).replaceAll(""); - } - - private static String stripColor(final String input, final Pattern pattern) - { - return pattern.matcher(input).replaceAll(""); - } - - private static String replaceColor(final String input, final Pattern pattern) - { - return 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 cb3be1be4..000000000 --- a/Essentials/src/com/earth2me/essentials/utils/textreader/HelpInput.java +++ /dev/null @@ -1,179 +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; - final List newLines = new ArrayList(); - String pluginName = ""; - String pluginNameLow = ""; - if (!match.equalsIgnoreCase("")) - { - lines.add(_("helpMatching", match)); - } - - for (Plugin p : ess.getServer().getPluginManager().getPlugins()) - { - try - { - final List pluginLines = new ArrayList(); - final PluginDescriptionFile desc = p.getDescription(); - final Map> cmds = desc.getCommands(); - pluginName = p.getDescription().getName(); - pluginNameLow = pluginName.toLowerCase(Locale.ENGLISH); - if (pluginNameLow.equals(match)) - { - lines.clear(); - newLines.clear(); - lines.add(_("helpFrom", p.getDescription().getName())); - } - - for (Map.Entry> k : cmds.entrySet()) - { - try - { - if (!match.equalsIgnoreCase("") && (!pluginNameLow.contains(match)) && (!k.getKey().toLowerCase(Locale.ENGLISH).contains(match)) - && (!(k.getValue().get(DESCRIPTION) instanceof String - && ((String)k.getValue().get(DESCRIPTION)).toLowerCase(Locale.ENGLISH).contains(match)))) - { - continue; - } - - if (pluginNameLow.contains("essentials")) - { - final String node = "essentials." + k.getKey(); - if (!settings.getData().getCommands().isDisabled(k.getKey()) && user.hasPermission(node)) - { - pluginLines.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(pluginNameLow).isAuthorized(user)) - { - pluginLines.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) - { - pluginLines.add(_("helpLine", k.getKey(), value.get(DESCRIPTION))); - } - } - else if (permissions instanceof String && !"".equals(permissions)) - { - if (user.hasPermission(permissions.toString())) - { - pluginLines.add(_("helpLine", k.getKey(), value.get(DESCRIPTION))); - } - } - else - { - if (!settings.getData().getCommands().getHelp().isHidePermissionlessCommands()) - { - pluginLines.add(_("helpLine", k.getKey(), value.get(DESCRIPTION))); - } - } - } - } - } - catch (NullPointerException ex) - { - continue; - } - } - if (!pluginLines.isEmpty()) - { - newLines.addAll(pluginLines); - if (pluginNameLow.equals(match)) - { - break; - } - if (match.equalsIgnoreCase("")) - { - lines.add(_("helpPlugin", pluginName, pluginNameLow)); - } - } - } - catch (NullPointerException ex) - { - continue; - } - catch (Exception ex) - { - if (!reported) - { - logger.log(Level.WARNING, _("commandHelpFailedForPlugin", pluginNameLow), ex); - } - reported = true; - continue; - } - } - lines.addAll(newLines); - } - - @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 b9c67fa77..000000000 --- a/Essentials/src/com/earth2me/essentials/utils/textreader/KeywordReplacer.java +++ /dev/null @@ -1,157 +0,0 @@ -package com.earth2me.essentials.utils.textreader; - -import com.earth2me.essentials.utils.DescParseTickFormat; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IUser; -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.World; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -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 instanceof Player) - { - @Cleanup - final IUser user = ess.getUser((Player)sender); - user.acquireReadLock(); - user.setDisplayNick(); - 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() == null || user.getLocation().getWorld() == null ? "" : user.getLocation().getWorld().getName(); - worldTime12 = DescParseTickFormat.format12(user.getWorld() == null ? 0 : user.getWorld().getTime()); - worldTime24 = DescParseTickFormat.format24(user.getWorld() == null ? 0 : user.getWorld().getTime()); - worldDate = DateFormat.getDateInstance(DateFormat.MEDIUM, ess.getI18n().getCurrentLocale()).format(DescParseTickFormat.ticksToDate(user.getWorld() == null ? 0 : user.getWorld().getFullTime())); - } - else - { - displayName = ipAddress = balance = mails = world = worldTime12 = worldTime24 = worldDate = ""; - } - - int playerHidden = 0; - for (Player p : ess.getServer().getOnlinePlayers()) - { - if (ess.getUser(p).isHidden()) - { - playerHidden++; - } - } - online = Integer.toString(ess.getServer().getOnlinePlayers().length - 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 (ess.getUser(p).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 570feaa36..000000000 --- a/Essentials/src/com/earth2me/essentials/utils/textreader/TextInput.java +++ /dev/null @@ -1,149 +0,0 @@ -package com.earth2me.essentials.utils.textreader; - -import com.earth2me.essentials.utils.Util; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.api.InvalidNameException; -import java.io.*; -import java.lang.ref.SoftReference; -import java.util.*; -import java.util.logging.Level; -import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - - -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 instanceof Player) - { - try - { - final IUser user = ess.getUser((Player)sender); - file = new File(ess.getDataFolder(), filename + "_" + Util.sanitizeFileName(user.getName()) + ".txt"); - if (!file.exists()) - { - file = new File(ess.getDataFolder(), filename + "_" + Util.sanitizeFileName(ess.getRanks().getMainGroup(user)) + ".txt"); - } - } - catch (InvalidNameException ex) - { - Bukkit.getLogger().log(Level.WARNING, ex.getMessage(), ex); - } - } - if (file == null || !file.exists()) - { - file = new File(ess.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-fk]", ""), 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.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 - { - if(output != null) - output.close(); - if(input != null) - 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 cac760441..000000000 --- a/Essentials/src/com/earth2me/essentials/utils/textreader/TextPager.java +++ /dev/null @@ -1,199 +0,0 @@ -package com.earth2me.essentials.utils.textreader; - -import com.earth2me.essentials.I18n; -import static com.earth2me.essentials.I18n._; -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) - { - StringBuilder content = new StringBuilder(); - final String[] title = commandName.split(" ", 2); - if (title.length > 1) - { - content.append(I18n.capitalCase(title[0])).append(": "); - content.append(title[1]); - } - else if (chapterPageStr != null) - { - content.append(I18n.capitalCase(commandName)).append(": "); - content.append(chapterPageStr); - } - else - { - content.append(I18n.capitalCase(commandName)); - } - sender.sendMessage(_("infoPages", page, pages, content)); - } - 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, I18n.capitalCase(commandName))); - } - 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..93c638a77 --- /dev/null +++ b/Essentials/src/net/ess3/Console.java @@ -0,0 +1,33 @@ +package net.ess3; + +import net.ess3.api.IReplyTo; +import org.bukkit.command.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..a13e8e4e6 --- /dev/null +++ b/Essentials/src/net/ess3/Essentials.java @@ -0,0 +1,531 @@ +/* + * 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.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.metrics.Metrics; +import net.ess3.metrics.MetricsListener; +import net.ess3.metrics.MetricsStarter; +import net.ess3.ranks.RanksStorage; +import net.ess3.settings.SettingsHolder; +import net.ess3.settings.SpawnsHolder; +import net.ess3.user.IOfflinePlayer; +import net.ess3.user.User; +import net.ess3.user.UserMap; +import net.ess3.utils.ExecuteTimer; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import lombok.Getter; +import org.bukkit.Server; +import org.bukkit.World; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +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.InvalidDescriptionException; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginDescriptionFile; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; +import org.yaml.snakeyaml.error.YAMLException; + + +public class Essentials extends JavaPlugin implements IEssentials +{ + public static final int BUKKIT_VERSION = 2149; + private static final Logger LOGGER = Logger.getLogger("Minecraft"); + 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; + private transient I18n i18n; + private transient ICommandHandler commandHandler; + private transient Economy economy; + public transient boolean testing; + private transient Metrics metrics; + @Getter + private transient EssentialsTimer timer; + @Getter + private transient List vanishedPlayers = new ArrayList(); + + @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(); + } + i18n = new I18n(this); + i18n.onEnable(); + 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(); + i18n = new I18n(this); + i18n.onEnable(); + execTimer.mark("I18n1"); + final PluginManager pm = getServer().getPluginManager(); + for (Plugin plugin : pm.getPlugins()) + { + if (plugin.getDescription().getName().startsWith("Essentials") + && !plugin.getDescription().getVersion().equals(this.getDescription().getVersion()) + && !plugin.getDescription().getName().equals("EssentialsAntiCheat")) + { + LOGGER.log(Level.WARNING, I18n._("versionMismatch", plugin.getDescription().getName())); + } + } + final Matcher versionMatch = Pattern.compile("git-Bukkit-(?:(?:[0-9]+)\\.)+[0-9]+-R[\\.0-9]+-(?:[0-9]+-g[0-9a-f]+-)?b([0-9]+)jnks.*").matcher(getServer().getVersion()); + if (versionMatch.matches()) + { + final int versionNumber = Integer.parseInt(versionMatch.group(1)); + if (versionNumber < BUKKIT_VERSION && versionNumber > 100) + { + LOGGER.log(Level.SEVERE, " * ! * ! * ! * ! * ! * ! * ! * ! * ! * ! * ! * ! *"); + LOGGER.log(Level.SEVERE, I18n._("notRecommendedBukkit")); + LOGGER.log(Level.SEVERE, I18n._("requiredBukkit", Integer.toString(BUKKIT_VERSION))); + LOGGER.log(Level.SEVERE, " * ! * ! * ! * ! * ! * ! * ! * ! * ! * ! * ! * ! *"); + this.setEnabled(false); + return; + } + } + else + { + LOGGER.log(Level.INFO, I18n._("bukkitFormatChanged")); + LOGGER.log(Level.INFO, getServer().getVersion()); + LOGGER.log(Level.INFO, getServer().getBukkitVersion()); + } + 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); + reload(); + } + 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); + + + timer = new EssentialsTimer(this); + getServer().getScheduler().scheduleSyncRepeatingTask(this, timer, 1, 100); + execTimer.mark("RegListeners"); + + final MetricsStarter metricsStarter = new MetricsStarter(this); + if (metricsStarter.getStart() != null && metricsStarter.getStart() == true) + { + getServer().getScheduler().scheduleAsyncDelayedTask(this, metricsStarter, 1); + } + else if (metricsStarter.getStart() != null && metricsStarter.getStart() == false) + { + final MetricsListener metricsListener = new MetricsListener(this, metricsStarter); + pm.registerEvents(metricsListener, this); + } + + final String timeroutput = execTimer.end(); + if (getSettings().isDebug()) + { + LOGGER.log(Level.INFO, "Essentials load {0}", timeroutput); + } + } + + @Override + public void onDisable() + { + for (Player p : getServer().getOnlinePlayers()) + { + IUser user = getUser(p); + if (user.isVanished()) + { + user.toggleVanished(); + p.sendMessage(I18n._("unvanishedReload")); + } + } + i18n.onDisable(); + Trade.closeLog(); + } + + @Override + public void reload() + { + Trade.closeLog(); + + for (IReload iReload : reloadList) + { + iReload.onReload(); + execTimer.mark("Reload(" + iReload.getClass().getSimpleName() + ")"); + } + + i18n.updateLocale(settings.getLocale()); + } + + @Override + public boolean onCommand(final CommandSender sender, final Command command, final String commandLabel, final String[] args) + { + return commandHandler.handleCommand(sender, command, commandLabel, args); + //return onCommandEssentials(sender, command, commandLabel, args, Essentials.class.getClassLoader(), "net.ess3.commands.Command", "essentials.", null); + } + + @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; + } + + public Metrics getMetrics() + { + return metrics; + } + + public void setMetrics(Metrics metrics) + { + this.metrics = metrics; + } + + @Override + public IUser getUser(final Object base) + { + if (base instanceof Player) + { + return getUser((Player)base); + } + if (base instanceof String) + { + final IUser user = userMap.getUser((String)base); + if (user != null && user.getBase() instanceof IOfflinePlayer) + { + ((IOfflinePlayer)user.getBase()).setName((String)base); + } + return user; + } + return null; + } + + private IUser getUser(final T base) + { + if (base == null) + { + return null; + } + + if (base instanceof IUser) + { + return (IUser)base; + } + IUser user = userMap.getUser(base.getName()); + + if (user == null) + { + user = new User(base, this); + } + else + { + //todo - fix this + user.update(base); + } + return user; + } + + /*@Override + public IUser getUser(final Player player) + { + return userMap.getUser(player); + } + + @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; + } + final Player[] players = getServer().getOnlinePlayers(); + + for (Player player : players) + { + final IUser user = getUser(player); + if (!user.isIgnoringPlayer(sender)) + { + player.sendMessage(message); + } + } + + return players.length; + } + + @Override + public int scheduleAsyncDelayedTask(final Runnable run) + { + return this.getServer().getScheduler().scheduleAsyncDelayedTask(this, run); + } + + @Override + public int scheduleSyncDelayedTask(final Runnable run) + { + return this.getServer().getScheduler().scheduleSyncDelayedTask(this, run); + } + + @Override + public int scheduleSyncDelayedTask(final Runnable run, final long delay) + { + return this.getServer().getScheduler().scheduleSyncDelayedTask(this, run, delay); + } + + @Override + public int scheduleSyncRepeatingTask(final Runnable run, final long delay, final long period) + { + return this.getServer().getScheduler().scheduleSyncRepeatingTask(this, run, delay, period); + } + + @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 I18n getI18n() + { + return i18n; + } + + @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..f2ec6c441 --- /dev/null +++ b/Essentials/src/net/ess3/EssentialsTimer.java @@ -0,0 +1,113 @@ +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.LinkedList; +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(); + private transient long lastPoll = System.currentTimeMillis(); + private final transient LinkedList history = new LinkedList(); + + EssentialsTimer(final IEssentials ess) + { + this.ess = ess; + } + + @Override + public void run() + { + final long currentTime = System.currentTimeMillis(); + long timeSpent = (currentTime - lastPoll) / 1000; + if (timeSpent == 0) + { + timeSpent = 1; + } + if (history.size() > 10) + { + history.remove(); + } + float tps = 100f / timeSpent; + if (tps <= 20) + { + history.add(tps); + } + lastPoll = currentTime; + for (Player player : ess.getServer().getOnlinePlayers()) + { + + try + { + final IUser user = ess.getUser(player); + 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); + user.resetInvulnerabilityAfterTeleport(); + } + } + + public float getAverageTPS() + { + float avg = 0; + for (Float f : history) + { + if (f != null) + { + avg += f; + } + } + return avg / history.size(); + } +} diff --git a/Essentials/src/net/ess3/I18n.java b/Essentials/src/net/ess3/I18n.java new file mode 100644 index 000000000..0086576a8 --- /dev/null +++ b/Essentials/src/net/ess3/I18n.java @@ -0,0 +1,178 @@ +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]); + } + ResourceBundle.clearCache(); + 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.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..448eb7baa --- /dev/null +++ b/Essentials/src/net/ess3/ItemDb.java @@ -0,0 +1,153 @@ +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.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; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + + +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.getMaterial(itemname) != null) + { + itemid = Material.getMaterial(itemname).getId(); + metaData = 0; + } + else + { + throw new Exception(_("unknownItemName", id)); + } + } + + final Material mat = Material.getMaterial(itemid); + if (mat == null) + { + throw new Exception(_("unknownItemId", itemid)); + } + final ItemStack retval = new ItemStack(mat); + retval.setAmount(mat.getMaxStackSize()); + retval.setDurability(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..244d40853 --- /dev/null +++ b/Essentials/src/net/ess3/Jails.java @@ -0,0 +1,353 @@ +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.entity.Entity; +import org.bukkit.entity.EntityType; +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.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDamageEvent.DamageCause; +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(); + private static transient boolean enabled = false; + + public Jails(final IEssentials ess) + { + super(ess, net.ess3.settings.Jails.class); + onReload(); + } + + private void registerListeners() + { + enabled = true; + final PluginManager pluginManager = ess.getServer().getPluginManager(); + final JailListener blockListener = new JailListener(); + pluginManager.registerEvents(blockListener, ess); + } + + @Override + public File getStorageFile() + { + return new File(ess.getDataFolder(), "jail.yml"); + } + + @Override + public void finishRead() + { + if (enabled == false && getCount() > 0) + { + registerListeners(); + } + } + + @Override + public void finishWrite() + { + if (enabled == false) + { + registerListeners(); + } + } + + @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)).getBukkitLocation(); + 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.Location(loc)); + } + finally + { + unlock(); + } + } + + @Override + public int getCount() + { + try + { + return getList().size(); + } + catch (Exception ex) + { + return 0; + } + } + + + private class JailListener 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); + } + } + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onEntityDamageByEntity(final EntityDamageByEntityEvent event) + { + if (event.getCause() != DamageCause.ENTITY_ATTACK || event.getEntity().getType() != EntityType.PLAYER) + { + return; + } + final Entity damager = event.getDamager(); + if (damager.getType() == EntityType.PLAYER) + { + final IUser user = ess.getUser(damager); + if (user != null && 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..fe9c55851 --- /dev/null +++ b/Essentials/src/net/ess3/Kits.java @@ -0,0 +1,139 @@ +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.commands.NoChargeException; +import net.ess3.settings.Kit; +import net.ess3.storage.AsyncStorageObjectHolder; +import net.ess3.user.UserData.TimestampType; +import net.ess3.utils.DateUtil; +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.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(); + } + + @Override + public void finishRead() + { + } + + @Override + public void finishWrite() + { + } + + @Override + public void checkTime(final IUser user, Kit kit) throws NoChargeException + { + final Calendar time = new GregorianCalendar(); + // Take the current time, and remove the delay from it. + final double delay = kit.getDelay(); + final Calendar earliestTime = new GregorianCalendar(); + earliestTime.add(Calendar.SECOND, -(int)delay); + earliestTime.add(Calendar.MILLISECOND, -(int)((delay * 1000.0) % 1000.0)); + + // This value contains the most recent time a kit could have been used that would allow another use. + + final long earliestLong = earliestTime.getTimeInMillis(); + + // When was the last kit used? + final Long lastTime = user.getTimestamp(TimestampType.KIT); + if (lastTime == null || lastTime < earliestLong) + { + user.setTimestamp(TimestampType.KIT, time.getTimeInMillis()); + } + else if (lastTime > time.getTimeInMillis()) + { + // This is to make sure time didn't get messed up on last kit use. + // If this happens, let's give the user the benifit of the doubt. + user.setTimestamp(TimestampType.KIT, time.getTimeInMillis()); + } + else + { + time.setTimeInMillis(lastTime); + time.add(Calendar.SECOND, (int)delay); + time.add(Calendar.MILLISECOND, (int)((delay * 1000.0) % 1000.0)); + user.sendMessage(_("kitTimed", DateUtil.formatDateDiff(time.getTimeInMillis()))); + throw new NoChargeException(); + } + } +} diff --git a/Essentials/src/net/ess3/Teleport.java b/Essentials/src/net/ess3/Teleport.java new file mode 100644 index 000000000..e703679cc --- /dev/null +++ b/Essentials/src/net/ess3/Teleport.java @@ -0,0 +1,309 @@ +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.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.Location; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.player.PlayerRespawnEvent; +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 Entity entity; + + public Target(Location location) + { + this.location = location; + this.entity = null; + } + + public Target(Entity 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.getBase(), "teleport", ex); + } + } + catch (Exception ex) + { + user.sendMessage(_("cooldownWithMessage", ex.getMessage())); + } + } + } + + public Teleport(IUser user, IEssentials ess) + { + this.user = user; + this.ess = ess; + } + + @Override + public void respawn(final Trade chargeFor, TeleportCause cause) throws Exception + { + final Player player = user.getBase(); + final Location bed = player.getBedSpawnLocation(); + final PlayerRespawnEvent pre = new PlayerRespawnEvent(player, bed == null ? player.getWorld().getSpawnLocation() : bed, bed != null); + ess.getServer().getPluginManager().callEvent(pre); + teleport(new Target(pre.getRespawnLocation()), chargeFor, cause); + } + + @Override + 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.getServer().getScheduler().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); + } + + @Override + public void teleport(Location loc, Trade chargeFor, TeleportCause cause) throws Exception + { + teleport(new Target(loc), chargeFor, cause); + } + + @Override + public void teleport(Entity 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 tDelay = ess.getRanks().getTeleportDelay(user); + + if (chargeFor != null) + { + chargeFor.isAffordableFor(user); + } + cooldown(true); + if (tDelay <= 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)tDelay); + c.add(Calendar.MILLISECOND, (int)((tDelay * 1000.0) % 1000.0)); + user.sendMessage(_("dontMoveMessage", DateUtil.formatDateDiff(c.getTimeInMillis()))); + initTimer((long)(tDelay * 1000.0), target, chargeFor, cause); + + teleTimer = ess.scheduleSyncRepeatingTask(this, 10, 10); + } + + private void now(Target target, TeleportCause cause) throws Exception + { + cancel(); + user.setLastLocation(); + user.getBase().teleport(LocationUtil.getSafeDestination(target.getLocation()), cause); + } + + @Override + 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); + } + + @Override + public void now(Entity entity, boolean cooldown, TeleportCause cause) throws Exception + { + if (cooldown) + { + cooldown(false); + } + now(new Target(entity), cause); + } + + @Override + public void back(Trade chargeFor) throws Exception + { + user.acquireReadLock(); + try + { + teleport(new Target(user.getData().getLastLocation().getBukkitLocation()), chargeFor, TeleportCause.COMMAND); + } + finally + { + user.unlock(); + } + } + + @Override + public void back() throws Exception + { + user.acquireReadLock(); + try + { + now(new Target(user.getData().getLastLocation().getBukkitLocation()), TeleportCause.COMMAND); + } + finally + { + user.unlock(); + } + } + + @Override + public void home(Location loc, Trade chargeFor) throws Exception + { + 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..751b762ce --- /dev/null +++ b/Essentials/src/net/ess3/Warps.java @@ -0,0 +1,152 @@ +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.commands.WarpNotFoundException; +import net.ess3.settings.WarpHolder; +import net.ess3.storage.StorageObjectMap; +import java.io.File; +import java.util.*; +import java.util.logging.Logger; +import org.bukkit.Bukkit; +import org.bukkit.Location; + + +public class Warps extends StorageObjectMap implements IWarps +{ + private static final Logger logger = Bukkit.getLogger(); + + 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().getBukkitLocation(); + } + finally + { + warp.unlock(); + } + } + + @Override + public void setWarp(final String name, final Location loc) throws Exception + { + setWarp(name, new net.ess3.storage.Location(loc)); + } + + public void setWarp(final String name, final net.ess3.storage.Location 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/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..33093d4bd --- /dev/null +++ b/Essentials/src/net/ess3/api/ICommandHandler.java @@ -0,0 +1,20 @@ +package net.ess3.api; + +import java.util.Map; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +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/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..7a8c3ccaf --- /dev/null +++ b/Essentials/src/net/ess3/api/IEssentials.java @@ -0,0 +1,73 @@ +package net.ess3.api; + +import net.ess3.EssentialsTimer; +import net.ess3.economy.register.Methods; +import net.ess3.listener.TntExplodeListener; +import net.ess3.metrics.Metrics; +import java.util.List; + +import org.bukkit.World; +import org.bukkit.plugin.Plugin; + + +public interface IEssentials extends Plugin +{ + void addReloadListener(IReload listener); + + IUser getUser(final Object base); + + 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(); + + List getVanishedPlayers(); + + EssentialsTimer getTimer(); + + Metrics getMetrics(); + + void setMetrics(Metrics metrics); +} 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..8a20c85a1 --- /dev/null +++ b/Essentials/src/net/ess3/api/IItemDb.java @@ -0,0 +1,13 @@ +package net.ess3.api; + +import org.bukkit.inventory.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..bf616d7ec --- /dev/null +++ b/Essentials/src/net/ess3/api/IJails.java @@ -0,0 +1,20 @@ +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; + + int getCount(); + + 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..62ad57321 --- /dev/null +++ b/Essentials/src/net/ess3/api/IKits.java @@ -0,0 +1,21 @@ +package net.ess3.api; + +import net.ess3.commands.NoChargeException; +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(); + + void checkTime(final IUser user, Kit kit) throws NoChargeException; +} diff --git a/Essentials/src/net/ess3/api/IPermission.java b/Essentials/src/net/ess3/api/IPermission.java new file mode 100644 index 000000000..987f0b481 --- /dev/null +++ b/Essentials/src/net/ess3/api/IPermission.java @@ -0,0 +1,17 @@ +package net.ess3.api; + +import org.bukkit.command.CommandSender; +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionDefault; + + +public interface IPermission +{ + String getPermission(); + + boolean isAuthorized(CommandSender sender); + + Permission getBukkitPermission(); + + PermissionDefault 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..b1393d22f --- /dev/null +++ b/Essentials/src/net/ess3/api/IReplyTo.java @@ -0,0 +1,11 @@ +package net.ess3.api; + +import org.bukkit.command.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..afec3e213 --- /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(Location loc, Trade chargeFor) 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..cad866601 --- /dev/null +++ b/Essentials/src/net/ess3/api/IUser.java @@ -0,0 +1,129 @@ +package net.ess3.api; + +import net.ess3.storage.IStorageObjectHolder; +import net.ess3.user.CooldownException; +import net.ess3.user.UserData; +import java.util.List; +import org.bukkit.Location; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + + +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(); + + void setDisplayNick(); + + 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(IUser user); + + void setIgnoredPlayer(IUser user, boolean set); + + Location getAfkPosition(); + + void dispose(); + + void updateCompass(); + + List getHomes(); + + void addMail(String string); + + void setMuted(boolean mute); + + boolean toggleSocialSpy(); + + void requestTeleport(IUser user, boolean b); + + boolean isTpRequestHere(); + + 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); + + boolean isVanished(); + + void resetInvulnerabilityAfterTeleport(); + + void toggleVanished(); + + boolean isInvSee(); + + void setInvSee(boolean invsee); + + boolean hasInvulnerabilityAfterTeleport(); + + void update(final Player base); + + void setGodModeEnabled(boolean set); + + void setVanished(boolean set); + +} diff --git a/Essentials/src/net/ess3/api/IUserMap.java b/Essentials/src/net/ess3/api/IUserMap.java new file mode 100644 index 000000000..1184bd1c5 --- /dev/null +++ b/Essentials/src/net/ess3/api/IUserMap.java @@ -0,0 +1,23 @@ +package net.ess3.api; + +import java.io.File; +import java.util.Set; +import org.bukkit.entity.Player; + + +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; +} 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..908994486 --- /dev/null +++ b/Essentials/src/net/ess3/api/IWarps.java @@ -0,0 +1,21 @@ +package net.ess3.api; + +import java.io.File; +import java.util.Collection; +import org.bukkit.Location; + + +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..ffc38a203 --- /dev/null +++ b/Essentials/src/net/ess3/api/IWorth.java @@ -0,0 +1,11 @@ +package net.ess3.api; + +import org.bukkit.inventory.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/IPermission.java b/Essentials/src/net/ess3/api/server/IPermission.java new file mode 100644 index 000000000..23fee3a03 --- /dev/null +++ b/Essentials/src/net/ess3/api/server/IPermission.java @@ -0,0 +1,5 @@ +package net.ess3.api.server; + +public interface IPermission { + +} diff --git a/Essentials/src/net/ess3/api/server/IPermissionsManager.java b/Essentials/src/net/ess3/api/server/IPermissionsManager.java new file mode 100644 index 000000000..d422868b4 --- /dev/null +++ b/Essentials/src/net/ess3/api/server/IPermissionsManager.java @@ -0,0 +1,8 @@ +package net.ess3.api.server; + +public interface IPermissionsManager { + + IPermission registerPermission(); + + boolean checkPermission(IPlayer player, IPermission perm); +} diff --git a/Essentials/src/net/ess3/api/server/IPlayer.java b/Essentials/src/net/ess3/api/server/IPlayer.java new file mode 100644 index 000000000..4ae44a480 --- /dev/null +++ b/Essentials/src/net/ess3/api/server/IPlayer.java @@ -0,0 +1,5 @@ +package net.ess3.api.server; + +public interface IPlayer { + +} 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..efb5d1415 --- /dev/null +++ b/Essentials/src/net/ess3/api/server/IServer.java @@ -0,0 +1,5 @@ +package net.ess3.api.server; + +public interface IServer { + +} diff --git a/Essentials/src/net/ess3/backup/Backup.java b/Essentials/src/net/ess3/backup/Backup.java new file mode 100644 index 000000000..454ad127f --- /dev/null +++ b/Essentials/src/net/ess3/backup/Backup.java @@ -0,0 +1,153 @@ +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 java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.logging.Level; +import java.util.logging.Logger; +import lombok.Cleanup; +import org.bukkit.Bukkit; +import org.bukkit.Server; +import org.bukkit.command.CommandSender; + + +public class Backup implements Runnable, IBackup +{ + private static final Logger LOGGER = Bukkit.getLogger(); + private transient final Server 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().length > 0) + { + 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.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; + } + LOGGER.log(Level.INFO, _("backupStarted")); + final CommandSender consoleSender = server.getConsoleSender(); + server.dispatchCommand(consoleSender, "save-all"); + server.dispatchCommand(consoleSender, "save-off"); + + ess.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.getDataFolder().getParentFile().getParentFile()); + 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) + { + LOGGER.log(Level.INFO, line); + } + } + while (line != null); + } + finally + { + reader.close(); + } + } + catch (InterruptedException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + catch (IOException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + finally + { + ess.scheduleSyncDelayedTask(new EnableSavingRunner()); + } + } + } + + + private class EnableSavingRunner implements Runnable + { + @Override + public void run() + { + server.dispatchCommand(server.getConsoleSender(), "save-on"); + if (server.getOnlinePlayers().length == 0) + { + running.set(false); + if (taskId != -1) + { + server.getScheduler().cancelTask(taskId); + } + } + + active.set(false); + LOGGER.log(Level.INFO, _("backupFinished")); + } + } +} diff --git a/Essentials/src/net/ess3/bukkit/Enchantments.java b/Essentials/src/net/ess3/bukkit/Enchantments.java new file mode 100644 index 000000000..b577f06e3 --- /dev/null +++ b/Essentials/src/net/ess3/bukkit/Enchantments.java @@ -0,0 +1,134 @@ +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("sharp", Enchantment.DAMAGE_ALL); + + ENCHANTMENTS.put("arthropodsdamage", Enchantment.DAMAGE_ARTHROPODS); + ENCHANTMENTS.put("ardmg", Enchantment.DAMAGE_ARTHROPODS); + ENCHANTMENTS.put("baneofarthropods", Enchantment.DAMAGE_ARTHROPODS); + ENCHANTMENTS.put("baneofarthropod", Enchantment.DAMAGE_ARTHROPODS); + ENCHANTMENTS.put("arthropod", 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("minespeed", Enchantment.DIG_SPEED); + ENCHANTMENTS.put("cutspeed", 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("meleefire", Enchantment.FIRE_ASPECT); + ENCHANTMENTS.put("meleeflame", 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("breathing", Enchantment.OXYGEN); + ENCHANTMENTS.put("breath", Enchantment.OXYGEN); + + ENCHANTMENTS.put("protection", Enchantment.PROTECTION_ENVIRONMENTAL); + ENCHANTMENTS.put("prot", Enchantment.PROTECTION_ENVIRONMENTAL); + ENCHANTMENTS.put("protect", Enchantment.PROTECTION_ENVIRONMENTAL); + + ENCHANTMENTS.put("explosionsprotection", Enchantment.PROTECTION_EXPLOSIONS); + ENCHANTMENTS.put("explosionprotection", Enchantment.PROTECTION_EXPLOSIONS); + ENCHANTMENTS.put("expprot", Enchantment.PROTECTION_EXPLOSIONS); + ENCHANTMENTS.put("blastprotection", Enchantment.PROTECTION_EXPLOSIONS); + ENCHANTMENTS.put("blastprotect", Enchantment.PROTECTION_EXPLOSIONS); + + ENCHANTMENTS.put("fallprotection", Enchantment.PROTECTION_FALL); + ENCHANTMENTS.put("fallprot", Enchantment.PROTECTION_FALL); + ENCHANTMENTS.put("featherfall", Enchantment.PROTECTION_FALL); + ENCHANTMENTS.put("featherfalling", Enchantment.PROTECTION_FALL); + + ENCHANTMENTS.put("fireprotection", Enchantment.PROTECTION_FIRE); + ENCHANTMENTS.put("flameprotection", Enchantment.PROTECTION_FIRE); + ENCHANTMENTS.put("fireprotect", Enchantment.PROTECTION_FIRE); + ENCHANTMENTS.put("flameprotect", Enchantment.PROTECTION_FIRE); + + ENCHANTMENTS.put("projectileprotection", Enchantment.PROTECTION_PROJECTILE); + ENCHANTMENTS.put("projprot", Enchantment.PROTECTION_PROJECTILE); + + ENCHANTMENTS.put("silktouch", Enchantment.SILK_TOUCH); + ENCHANTMENTS.put("softtouch", Enchantment.SILK_TOUCH); + + ENCHANTMENTS.put("waterworker", Enchantment.WATER_WORKER); + ENCHANTMENTS.put("aquaaffinity", Enchantment.WATER_WORKER); + + ENCHANTMENTS.put("firearrow", Enchantment.ARROW_FIRE); + ENCHANTMENTS.put("flame", Enchantment.ARROW_FIRE); + ENCHANTMENTS.put("flamearrow", Enchantment.ARROW_FIRE); + + ENCHANTMENTS.put("arrowdamage", Enchantment.ARROW_DAMAGE); + ENCHANTMENTS.put("power", Enchantment.ARROW_DAMAGE); + ENCHANTMENTS.put("arrowpower", Enchantment.ARROW_DAMAGE); + + ENCHANTMENTS.put("arrowknockback", Enchantment.ARROW_KNOCKBACK); + ENCHANTMENTS.put("arrowkb", Enchantment.ARROW_KNOCKBACK); + ENCHANTMENTS.put("punch", Enchantment.ARROW_KNOCKBACK); + ENCHANTMENTS.put("arrowpunch", Enchantment.ARROW_KNOCKBACK); + + ENCHANTMENTS.put("infinitearrows", Enchantment.ARROW_INFINITE); + ENCHANTMENTS.put("infarrows", Enchantment.ARROW_INFINITE); + ENCHANTMENTS.put("infinity", Enchantment.ARROW_INFINITE); + ENCHANTMENTS.put("infinite", Enchantment.ARROW_INFINITE); + ENCHANTMENTS.put("unlimited", Enchantment.ARROW_INFINITE); + ENCHANTMENTS.put("unlimitedarrows", 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..44d821bf1 --- /dev/null +++ b/Essentials/src/net/ess3/bukkit/EssentialsPlugin.java @@ -0,0 +1,7 @@ +package net.ess3.bukkit; + +import org.bukkit.plugin.java.JavaPlugin; + +public class EssentialsPlugin extends JavaPlugin { + //TODO +} 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/Server.java b/Essentials/src/net/ess3/bukkit/Server.java new file mode 100644 index 000000000..2491a4952 --- /dev/null +++ b/Essentials/src/net/ess3/bukkit/Server.java @@ -0,0 +1,9 @@ +package net.ess3.bukkit; + +import net.ess3.api.server.IServer; +import lombok.Delegate; + +public class Server implements IServer { + @Delegate + private org.bukkit.Server server; +} diff --git a/Essentials/src/net/ess3/commands/Commandafk.java b/Essentials/src/net/ess3/commands/Commandafk.java new file mode 100644 index 000000000..97f7b247b --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandafk.java @@ -0,0 +1,56 @@ +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) + { + user.setDisplayNick(); + 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..ef785b11a --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandback.java @@ -0,0 +1,27 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.economy.Trade; +import net.ess3.permissions.WorldPermissions; + + +public class Commandback extends EssentialsCommand +{ + @Override + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + final String worldName = user.getData().getLastLocation().getWorldName(); + if (user.getWorld() != user.getData().getLastLocation().getBukkitLocation().getWorld() && ess.getSettings().getData().getGeneral().isWorldTeleportPermissions() + && WorldPermissions.getPermission(worldName).isAuthorized(user)) + { + throw new Exception(_("noPerm", "essentials.world." + worldName)); + } + //tod - verify + final Trade charge = new Trade(this.toString(), 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..2b1e68750 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandbackup.java @@ -0,0 +1,32 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IBackup; +import net.ess3.api.ISettings; +import lombok.Cleanup; +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(); + if (backup == null) + { + throw new Exception(_("backupDisabled")); + } + + @Cleanup + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + final String command = settings.getData().getGeneral().getBackup().getCommand(); + if (command == null || "".equals(command) || "save-all".equalsIgnoreCase(command)) + { + throw new Exception(_("backupDisabled")); + } + 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..401323d48 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandbalance.java @@ -0,0 +1,31 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import net.ess3.utils.Util; +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/net/ess3/commands/Commandbalancetop.java b/Essentials/src/net/ess3/commands/Commandbalancetop.java new file mode 100644 index 000000000..98c3d3d90 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandbalancetop.java @@ -0,0 +1,179 @@ +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; +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.scheduleAsyncDelayedTask(new Viewer(sender, page, force)); + } + else + { + if (ess.getUserMap().getUniqueUsers() > MINUSERS) + { + sender.sendMessage(_("orderBalances", ess.getUserMap().getUniqueUsers())); + } + ess.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.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.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..98d970987 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandban.java @@ -0,0 +1,68 @@ +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; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + + +public class Commandban extends EssentialsCommand +{ + @Override + public 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 (sender instanceof Player && Permissions.BAN_OFFLINE.isAuthorized(user)) + { + sender.sendMessage(_("banExempt")); + return; + } + } + else + { + if (Permissions.BAN_EXEMPT.isAuthorized(sender)) + { + sender.sendMessage(_("banExempt")); + return; + } + } + + user.acquireWriteLock(); + final String senderName = sender instanceof Player ? ((Player)sender).getDisplayName() : Console.NAME; + String banReason; + user.getData().setBan(new Ban()); + if (args.length > 1) + { + + banReason = _("banFormat", getFinalArg(args, 1), senderName); + user.getData().getBan().setReason(banReason); + } + else + { + banReason = _("banFormat", _("defaultBanReason"), senderName); + user.getData().getBan().setReason(""); + } + + user.setBanned(true); + user.kickPlayer(banReason); + 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/Commandbanip.java b/Essentials/src/net/ess3/commands/Commandbanip.java new file mode 100644 index 000000000..c55e57440 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandbanip.java @@ -0,0 +1,39 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import lombok.Cleanup; +import org.bukkit.command.CommandSender; + + +public class Commandbanip extends EssentialsCommand +{ + @Override + public 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..fda8b8fb5 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandbigtree.java @@ -0,0 +1,45 @@ +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 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 if (args.length > 0 && args[0].equalsIgnoreCase("jungle")) + { + tree = TreeType.JUNGLE; + } + 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..8c90f0571 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandbreak.java @@ -0,0 +1,44 @@ +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 List list = (List)block.getDrops(); + //final BlockBreakEvent event = new BlockBreakEvent(block, user.getBase(), list); + 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..d4fb48c4e --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandbroadcast.java @@ -0,0 +1,19 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.utils.Util; +import org.bukkit.command.CommandSender; + + +public class Commandbroadcast extends EssentialsCommand +{ + @Override + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + ess.broadcastMessage(null, _("broadcast", Util.replaceFormat(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..af0b91599 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandburn.java @@ -0,0 +1,24 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import org.bukkit.command.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..c46eb7206 --- /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.permissions.Permissions; +import java.util.List; +import org.bukkit.command.CommandSender; +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..b7606def6 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commanddelhome.java @@ -0,0 +1,59 @@ +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.command.CommandSender; +import org.bukkit.entity.Player; + + +public class Commanddelhome extends EssentialsCommand +{ + @Override + public 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..4aa7c479e --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commanddeljail.java @@ -0,0 +1,19 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +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/net/ess3/commands/Commanddelwarp.java b/Essentials/src/net/ess3/commands/Commanddelwarp.java new file mode 100644 index 000000000..a97514886 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commanddelwarp.java @@ -0,0 +1,19 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import org.bukkit.command.CommandSender; + + +public class Commanddelwarp extends EssentialsCommand +{ + @Override + public 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..680e5d1b4 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandeco.java @@ -0,0 +1,119 @@ +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; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + + +public class Commandeco extends EssentialsCommand +{ + @Override + public 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 = ess.getUser(onlinePlayer); + 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..a3dad9d19 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandessentials.java @@ -0,0 +1,198 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.metrics.Metrics; +import java.io.IOException; +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; +import org.bukkit.entity.Player; + + +public class Commandessentials extends EssentialsCommand +{ + private transient int taskid; + private final transient Map noteBlocks = new HashMap(); + + @Override + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length == 0) { + run_disabled(sender, commandLabel, args); + } + else if (args[0].equalsIgnoreCase("debug")) + { + run_debug(sender, commandLabel, args); + } + else if (args[0].equalsIgnoreCase("nya")) + { + run_nya(sender, commandLabel, args); + } + else if (args[0].equalsIgnoreCase("moo")) + { + run_moo(sender, commandLabel, args); + } + else if (args[0].equalsIgnoreCase("opt-out")) + { + run_optout(sender, commandLabel, args); + } + else { + run_reload(sender, commandLabel, args); + } + } + + private void run_disabled(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + sender.sendMessage("Essentials " + ess.getDescription().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()); + } + + if (disabledCommands.length() > 0) { + sender.sendMessage(_("blockList")); + sender.sendMessage(disabledCommands.toString()); + } + } + + private void run_debug(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + ess.getSettings().setDebug(!ess.getSettings().isDebug()); + sender.sendMessage("Essentials " + ess.getDescription().getVersion() + " debug mode " + (ess.getSettings().isDebug() ? "enabled" : "disabled")); + } + + private void run_reload(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + ess.reload(); + sender.sendMessage(_("essentialsReload", ess.getDescription().getVersion())); + } + + private void run_nya(final CommandSender sender, final String commandLabel, 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()); + loc.getBlock().setType(Material.NOTE_BLOCK); + } + } + taskid = ess.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() + { + server.getScheduler().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 command, final String args[]) + { + if(sender instanceof ConsoleCommandSender) + sender.sendMessage(new String[]{" (__)", " (oo)", " /------\\/", " / | ||", " * /\\---/\\", " ~~ ~~", "....\"Have you mooed today?\"..." } ); + else + sender.sendMessage(new String[]{" (__)", " (oo)", " /------\\/", " / | | |", " * /\\---/\\", " ~~ ~~", "....\"Have you mooed today?\"..." } ); + } + + private void run_optout(final CommandSender sender, final String command, final String args[]) + { + final Metrics metrics = ess.getMetrics(); + try + { + sender.sendMessage("Essentials collects simple metrics to highlight which features to concentrate work on in the future."); + if (metrics.isOptOut()) { + metrics.enable(); + } else { + metrics.disable(); + } + sender.sendMessage("Anonymous Metrics are now: " + (metrics.isOptOut() ? "disabled" : "enabled")); + } + catch (IOException ex) + { + sender.sendMessage("Unable to modify 'plugins/PluginMetrics/config.yml': " + ex.getMessage()); + } + } +} \ No newline at end of file diff --git a/Essentials/src/net/ess3/commands/Commandexp.java b/Essentials/src/net/ess3/commands/Commandexp.java new file mode 100644 index 000000000..104a294e5 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandexp.java @@ -0,0 +1,139 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.craftbukkit.SetExpFix; +import net.ess3.permissions.Permissions; +import net.ess3.utils.Util; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + + +public class Commandexp extends EssentialsCommand +{ + @Override + public void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + + if (args.length == 0) + { + showExp(user, user); + } + else if (args[0].equalsIgnoreCase("set") && Permissions.EXP_SET.isAuthorized(user)) + { + if (args.length == 3 && Permissions.EXP_SET_OTHERS.isAuthorized(user)) + { + expMatch(user, args[1], args[2], false); + } + else + { + setExp(user, user, args[1], false); + } + } + else if (args[0].equalsIgnoreCase("give") && Permissions.EXP_GIVE.isAuthorized(user)) + { + if (args.length == 3 && Permissions.EXP_GIVE_OTHERS.isAuthorized(user)) + { + expMatch(user, args[1], args[2], true); + } + else + { + setExp(user, user, args[1], true); + } + } + else + { + String match = args[0].trim(); + if (args.length == 2) + { + match = args[1].trim(); + } + if (match.equalsIgnoreCase("show") || !Permissions.EXP_OTHERS.isAuthorized(user)) + { + showExp(user, user); + } + else + { + showMatch(user, match); + } + } + } + + + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + else if (args.length > 2 && args[0].equalsIgnoreCase("set")) + { + expMatch(sender, args[1], args[2], false); + } + else if (args.length > 2 && args[0].equalsIgnoreCase("give")) + { + expMatch(sender, args[1], args[2], true); + } + else + { + String match = args[0].trim(); + if (args.length == 2) + { + match = args[1].trim(); + } + showMatch(sender, match); + } + } + + private void showMatch(final CommandSender sender, final String match) throws NotEnoughArgumentsException + { + boolean foundUser = false; + for (Player matchPlayer : server.matchPlayer(match)) + { + foundUser = true; + final IUser target = ess.getUser(matchPlayer); + showExp(sender, target); + } + if (!foundUser) + { + throw new NotEnoughArgumentsException(_("playerNotFound")); + } + } + + private void expMatch(final CommandSender sender, final String match, final String amount, final boolean toggle) throws NotEnoughArgumentsException + { + boolean foundUser = false; + for (Player matchPlayer : server.matchPlayer(match)) + { + final IUser target = ess.getUser(matchPlayer); + setExp(sender, target, amount, toggle); + foundUser = true; + } + if (!foundUser) + { + throw new NotEnoughArgumentsException(_("playerNotFound")); + } + } + + private void showExp(final CommandSender sender, final IUser target) + { + final int totalExp = SetExpFix.getTotalExperience(target); + final int expLeft = (int)Util.roundDouble(((((3.5 * target.getLevel()) + 6.7) - (totalExp - ((1.75 * (target.getLevel() * target.getLevel())) + (5.00 * target.getLevel())))) + 1)); + sender.sendMessage(_("exp", target.getDisplayName(), SetExpFix.getTotalExperience(target), target.getLevel(), expLeft)); + } + + private void setExp(final CommandSender sender, final IUser target, final String strAmount, final boolean give) + { + Long amount = Long.parseLong(strAmount); + if (give) + { + amount += SetExpFix.getTotalExperience(target); + } + if (amount > Integer.MAX_VALUE) + { + amount = (long)Integer.MAX_VALUE; + } + SetExpFix.setTotalExperience(target, amount.intValue()); + sender.sendMessage(_("expSet", target.getDisplayName(), amount)); + } +} \ No newline at end of file diff --git a/Essentials/src/net/ess3/commands/Commandext.java b/Essentials/src/net/ess3/commands/Commandext.java new file mode 100644 index 000000000..f3413f0fd --- /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 org.bukkit.command.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..55bca0932 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandfeed.java @@ -0,0 +1,47 @@ +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.command.CommandSender; +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 CommandSender 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/Commandfly.java b/Essentials/src/net/ess3/commands/Commandfly.java new file mode 100644 index 000000000..d36923764 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandfly.java @@ -0,0 +1,72 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + + +public class Commandfly extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + + flyOtherPlayers(server, sender, args); + } + + @Override + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length > 0 && args[0].trim().length() > 2 && Permissions.FLY_OTHERS.isAuthorized(user)) + { + flyOtherPlayers(server, user, args); + return; + } + user.setAllowFlight(!user.getAllowFlight()); + if (!user.getAllowFlight()) + { + user.setFlying(false); + } + user.sendMessage(_("flyMode", _(user.getAllowFlight() ? "enabled" : "disabled"), user.getDisplayName())); + } + + private void flyOtherPlayers(final Server server, final CommandSender sender, final String[] args) + { + for (Player matchPlayer : server.matchPlayer(args[0])) + { + final IUser player = ess.getUser(matchPlayer); + if (player.isHidden()) + { + continue; + } + if (args.length > 1) + { + if (args[1].contains("on") || args[1].contains("ena") || args[1].equalsIgnoreCase("1")) + { + player.setAllowFlight(true); + } + else + { + player.setAllowFlight(false); + } + } + else + { + player.setAllowFlight(!player.getAllowFlight()); + } + + if (!player.getAllowFlight()) + { + player.setFlying(false); + } + sender.sendMessage(_("flyMode", _(player.getAllowFlight() ? "enabled" : "disabled"), player.getDisplayName())); + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandgamemode.java b/Essentials/src/net/ess3/commands/Commandgamemode.java new file mode 100644 index 000000000..535afeb77 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandgamemode.java @@ -0,0 +1,66 @@ +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.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); + } + + @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); + 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 args[]) + { + for (Player matchPlayer : server.matchPlayer(args[0])) + { + final IUser player = ess.getUser(matchPlayer); + if (player.isHidden()) + { + continue; + } + + if (args.length > 1) + { + if (args[1].contains("creat") || args[1].equalsIgnoreCase("1")) + { + player.setGameMode(GameMode.CREATIVE); + } + else + { + player.setGameMode(GameMode.SURVIVAL); + } + } + else + { + 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..dfb2917c7 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandgc.java @@ -0,0 +1,41 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import org.bukkit.ChatColor; +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 + { + float tps = ess.getTimer().getAverageTPS(); + ChatColor color; + if (tps >= 18) + { + color = ChatColor.GREEN; + } + else if (tps >= 15) + { + color = ChatColor.YELLOW; + } + else + { + color = ChatColor.RED; + } + sender.sendMessage(_("tps", "" + color + tps)); + 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..e4ac2b4fe --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandgetpos.java @@ -0,0 +1,53 @@ +package net.ess3.commands; + +import net.ess3.api.IUser; +import net.ess3.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)) + { + //todo permissions + final IUser otherUser = getPlayer(args, 0); + if (!otherUser.isHidden() || Permissions.LIST_HIDDEN.isAuthorized(user)) + { + outputPosition(user, otherUser.getLocation(), user.getLocation()); + return; + } + + } + 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..13f5572c4 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandgive.java @@ -0,0 +1,81 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.permissions.GivePermissions; +import net.ess3.utils.Util; +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 +{ + @Override + public 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 > 3 && Util.isInt(args[2]) && Util.isInt(args[3])) + { + stack.setAmount(Integer.parseInt(args[2])); + stack.setDurability(Short.parseShort(args[3])); + } + else if (args.length > 2 && Integer.parseInt(args[2]) > 0) + { + stack.setAmount(Integer.parseInt(args[2])); + } + + if (args.length > 3) + { + for (int i = Util.isInt(args[3]) ? 4 : 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); + + //TODO: TL this. + 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..7cb424d81 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandgod.java @@ -0,0 +1,67 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.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); + } + + @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); + return; + } + + user.setGodModeEnabled(!user.isGodModeEnabled()); + user.sendMessage(_("godMode", (user.isGodModeEnabled() ? _("enabled") : _("disabled")))); + } + + private void godOtherPlayers(final CommandSender sender, final String[] args) + { + for (Player matchPlayer : server.matchPlayer(args[0])) + { + final IUser player = ess.getUser(matchPlayer); + if (player.isHidden()) + { + continue; + } + + if (args.length > 1) + { + if (args[1].contains("on") || args[1].contains("ena") || args[1].equalsIgnoreCase("1")) + { + player.setGodModeEnabled(true); + } + else + { + player.setGodModeEnabled(false); + } + } + else + { + player.setGodModeEnabled(!player.isGodModeEnabled()); + } + + final boolean enabled = player.isGodModeEnabled(); + player.sendMessage(_("godMode", (enabled ? _("enabled") : _("disabled")))); + sender.sendMessage(_("godMode", _(enabled ? "godEnabledFor" : "godDisabledFor", matchPlayer.getDisplayName()))); + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandhat.java b/Essentials/src/net/ess3/commands/Commandhat.java new file mode 100644 index 000000000..18fb73cca --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandhat.java @@ -0,0 +1,57 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.craftbukkit.InventoryWorkaround; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.PlayerInventory; + + +public class Commandhat extends EssentialsCommand +{ + @Override + protected void run(IUser user, String commandLabel, String[] args) throws Exception + { + if (args.length > 0 && (args[0].contains("rem") || args[0].contains("off") || args[0].equalsIgnoreCase("0"))) + { + final PlayerInventory inv = user.getInventory(); + final ItemStack head = inv.getHelmet(); + if (head == null || head.getType() == Material.AIR) + { + user.sendMessage(_("hatEmpty")); + } + else + { + final ItemStack air = new ItemStack(Material.AIR); + inv.setHelmet(air); + InventoryWorkaround.addItem(user.getInventory(), true, head); + user.sendMessage(_("hatRemoved")); + } + } + else + { + if (user.getItemInHand().getType() != Material.AIR) + { + final ItemStack hand = user.getItemInHand(); + if (hand.getType().getMaxDurability() == 0) + { + final PlayerInventory inv = user.getInventory(); + final ItemStack head = inv.getHelmet(); + inv.removeItem(hand); + inv.setHelmet(hand); + inv.setItemInHand(head); + user.sendMessage(_("hatPlaced")); + } + else + { + user.sendMessage(_("hatArmor")); + } + } + else + { + user.sendMessage(_("hatFail")); + } + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandheal.java b/Essentials/src/net/ess3/commands/Commandheal.java new file mode 100644 index 000000000..d529a56ef --- /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.permissions.Permissions; +import net.ess3.user.UserData.TimestampType; +import java.util.List; +import org.bukkit.command.CommandSender; +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 + public 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..7c2248e49 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandhelp.java @@ -0,0 +1,57 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.utils.Util; +import net.ess3.utils.textreader.HelpInput; +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 java.util.Locale; +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; + String command = commandLabel; + 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 + { + if (pageStr.length() > 26) + { + pageStr = pageStr.substring(0, 25); + } + output = new HelpInput(user, pageStr.toLowerCase(Locale.ENGLISH), ess); + command = command.concat(" ").concat(pageStr); + pageStr = chapterPageStr; + } + chapterPageStr = null; + } + else + { + output = new KeywordReplacer(input, user, ess); + } + final TextPager pager = new TextPager(output); + pager.showPage(pageStr, chapterPageStr, command, 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..b720ab590 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandhelpop.java @@ -0,0 +1,33 @@ +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; +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(); + } + user.setDisplayNick(); + final String message = _("helpOp", user.getDisplayName(), Util.stripFormat(getFinalArg(args, 0))); + logger.log(Level.INFO, message); + for (Player onlinePlayer : server.getOnlinePlayers()) + { + final IUser player = ess.getUser(onlinePlayer); + 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..4d3ddd0c1 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandhome.java @@ -0,0 +1,108 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.economy.Trade; +import net.ess3.permissions.Permissions; +import net.ess3.permissions.WorldPermissions; +import net.ess3.utils.Util; + +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(); + } + } + goHome(user, 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)) + { + goHome(user, player, homes.get(0), charge); + } + else + { + if (bed != null) + { + homes.add("bed"); + } + user.sendMessage(_("homes", Util.joinList(homes))); + } + } + throw new NoChargeException(); + } + + private void goHome(final IUser user, final IUser player, final String home, final Trade charge) throws Exception + { + final Location loc = player.getHome(home); + if (loc == null) + { + throw new NotEnoughArgumentsException(); + } + if (user.getWorld() != loc.getWorld() && ess.getSettings().getData().getGeneral().isWorldHomePermissions() + && !WorldPermissions.getPermission(loc.getWorld().getName()).isAuthorized(user)) + { + throw new Exception(_("noPerm", "essentials.world." + loc.getWorld().getName())); + } + user.getTeleport().home(loc, charge); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandignore.java b/Essentials/src/net/ess3/commands/Commandignore.java new file mode 100644 index 000000000..af9f2b710 --- /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")); + } + + user.acquireWriteLock(); + if (user.isIgnoringPlayer(player)) + { + user.setIgnoredPlayer(player, false); + user.sendMessage(_("unignorePlayer", player.getName())); + } + else + { + user.setIgnoredPlayer(player, 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..cf8d90818 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandinfo.java @@ -0,0 +1,20 @@ +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; +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/net/ess3/commands/Commandinvsee.java b/Essentials/src/net/ess3/commands/Commandinvsee.java new file mode 100644 index 000000000..cf0b18ea6 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandinvsee.java @@ -0,0 +1,19 @@ +package net.ess3.commands; + +import net.ess3.api.IUser; + + +public class Commandinvsee extends EssentialsCommand +{ + @Override + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + final IUser invUser = getPlayer(args, 0); + user.setInvSee(true); + user.openInventory(invUser.getInventory()); + } +} diff --git a/Essentials/src/net/ess3/commands/Commanditem.java b/Essentials/src/net/ess3/commands/Commanditem.java new file mode 100644 index 000000000..df371a752 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commanditem.java @@ -0,0 +1,82 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.permissions.ItemPermissions; +import net.ess3.permissions.Permissions; +import java.util.Locale; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemStack; + + +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)); + } + + try + { + if (args.length > 1 && Integer.parseInt(args[1]) > 0) + { + stack.setAmount(Integer.parseInt(args[1])); + } + else if (ess.getSettings().getData().getGeneral().getDefaultStacksize() > 0) + { + stack.setAmount(ess.getSettings().getData().getGeneral().getDefaultStacksize()); + } + else if (ess.getSettings().getData().getGeneral().getOversizedStacksize()> 0 && Permissions.OVERSIZEDSTACKS.isAuthorized(user)) + { + stack.setAmount(ess.getSettings().getData().getGeneral().getOversizedStacksize()); + } + 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); + } + } + } + catch (NumberFormatException e) + { + throw new NotEnoughArgumentsException(); + } + + if (stack.getType() == Material.AIR) + { + 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..ca869e61d --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commanditemdb.java @@ -0,0 +1,44 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import org.bukkit.Material; +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())); + + + if (itemStack.getType() != Material.AIR) + { + int maxuses = itemStack.getType().getMaxDurability(); + int durability = ((maxuses + 1) - itemStack.getDurability()); + if (maxuses != 0) + { + sender.sendMessage(_("durability", Integer.toString(durability))); + } + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandjails.java b/Essentials/src/net/ess3/commands/Commandjails.java new file mode 100644 index 000000000..6a68c1e91 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandjails.java @@ -0,0 +1,14 @@ +package net.ess3.commands; + +import net.ess3.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/net/ess3/commands/Commandjump.java b/Essentials/src/net/ess3/commands/Commandjump.java new file mode 100644 index 000000000..de5a1c0d3 --- /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.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 Location 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); + throw new NoChargeException(); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandkick.java b/Essentials/src/net/ess3/commands/Commandkick.java new file mode 100644 index 000000000..d6703aa19 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandkick.java @@ -0,0 +1,40 @@ +package net.ess3.commands; + +import net.ess3.Console; +import static net.ess3.I18n._; + +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + + +public class Commandkick extends EssentialsCommand +{ + @Override + public 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 = ess.getUser(onlinePlayer); + 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..3de05b71f --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandkickall.java @@ -0,0 +1,26 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + + +public class Commandkickall extends EssentialsCommand +{ + @Override + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + for (Player onlinePlayer : server.getOnlinePlayers()) + { + if (sender instanceof Player && onlinePlayer.getName().equalsIgnoreCase(((Player)sender).getName())) + { + continue; + } + else + { + onlinePlayer.kickPlayer(args.length > 0 ? getFinalArg(args, 0) : _("kickDefault")); + } + } + sender.sendMessage(_("kickedAll")); + } +} diff --git a/Essentials/src/net/ess3/commands/Commandkill.java b/Essentials/src/net/ess3/commands/Commandkill.java new file mode 100644 index 000000000..6f5560b1e --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandkill.java @@ -0,0 +1,32 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.EntityDamageEvent; + + +public class Commandkill extends EssentialsCommand +{ + @Override + public 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, Short.MAX_VALUE); + server.getPluginManager().callEvent(ede); + if (ede.isCancelled() && !sender.hasPermission("essentials.kill.force")) + { + continue; + } + + matchPlayer.damage(Short.MAX_VALUE); + 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..5388af0c6 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandkillall.java @@ -0,0 +1,151 @@ +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.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 + public 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"), e); + } + } + } + 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(entity instanceof Ocelot) + { + if (((Ocelot)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..ca620165a --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandkit.java @@ -0,0 +1,99 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.economy.Trade; +import net.ess3.permissions.KitPermissions; +import net.ess3.settings.Kit; +import net.ess3.utils.Util; +import java.util.Collection; +import java.util.Locale; +import org.bukkit.command.CommandSender; + + +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 if (args.length > 1 && KitPermissions.getPermission("others").isAuthorized(user)) + { + final IUser userTo = getPlayer(args, 1, true); + final String kitName = Util.sanitizeString(args[0].toLowerCase(Locale.ENGLISH)); + giveKit(userTo, user, kitName); + + } + else + { + final String kitName = Util.sanitizeString(args[0].toLowerCase(Locale.ENGLISH)); + giveKit(user, user, kitName); + + } + } + + @Override + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 2) + { + listKits(sender); + throw new NoChargeException(); + } + { + final IUser userTo = getPlayer(args, 1, true); + final String kitName = args[0].toLowerCase(Locale.ENGLISH); + final Kit kit = ess.getKits().getKit(kitName); + ess.getKits().sendKit(userTo, kit); + sender.sendMessage(_("kitGive", kitName)); + } + } + + private void listKits(CommandSender sender) throws Exception + { + Collection kitList = ess.getKits().getList(); + if (kitList.isEmpty()) + { + sender.sendMessage(_("kits", kitList)); + } + else + { + sender.sendMessage(_("kits", Util.joinList(kitList))); + } + } + + private void giveKit(IUser userTo, IUser userFrom, String kitName) throws Exception + { + if (!KitPermissions.getPermission(kitName).isAuthorized(userFrom)) + { + throw new Exception(_("noKitPermission", "essentials.kit." + kitName)); + } + final Kit kit = ess.getKits().getKit(kitName); + ess.getKits().checkTime(userFrom, kit); + final Trade charge = new Trade("kit-" + kitName, ess); + charge.isAffordableFor(userFrom); + ess.getKits().sendKit(userTo, kit); + charge.charge(userFrom); + userTo.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..74a3e7935 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandkittycannon.java @@ -0,0 +1,39 @@ +package net.ess3.commands; + + +import net.ess3.api.IUser; +import net.ess3.bukkit.Mob; +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.scheduleSyncDelayedTask(new Runnable() + { + @Override + public void run() + { + final Location loc = ocelot.getLocation(); + ocelot.remove(); + loc.getWorld().createExplosion(loc, 0F); + } + }, 20); + } +} \ No newline at end of file diff --git a/Essentials/src/net/ess3/commands/Commandlightning.java b/Essentials/src/net/ess3/commands/Commandlightning.java new file mode 100644 index 000000000..3ac1b0494 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandlightning.java @@ -0,0 +1,64 @@ +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.command.CommandSender; +import org.bukkit.entity.LightningStrike; +import org.bukkit.entity.Player; + + +public class Commandlightning extends EssentialsCommand +{ + @Override + public 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 = 5; + 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())); + final LightningStrike strike = matchPlayer.getWorld().strikeLightningEffect(matchPlayer.getLocation()); + if (!ess.getUser(matchPlayer).isGodModeEnabled()) + { + matchPlayer.damage(power, strike); + } + @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..5221ecad8 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandlist.java @@ -0,0 +1,166 @@ +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 net.ess3.utils.Util; +import java.util.*; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + + +public class Commandlist extends EssentialsCommand +{ + @Override + public 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 (ess.getUser(onlinePlayer).isHidden()) + { + playerHidden++; + } + } + + String online; + if (showhidden && playerHidden > 0) + { + online = _("listAmountHidden", server.getOnlinePlayers().length - playerHidden, playerHidden, server.getMaxPlayers()); + } + else + { + online = _("listAmount", server.getOnlinePlayers().length - 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 = ess.getUser(OnlinePlayer); + 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.replaceFormat(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")); + } + user.setDisplayNick(); + 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 = ess.getUser(OnlinePlayer); + 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")); + } + user.setDisplayNick(); + 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..722f61403 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandmail.java @@ -0,0 +1,165 @@ +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.List; + +import org.bukkit.command.CommandSender; +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)) + { + final String mail = Util.sanitizeString(Util.stripFormat(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.scheduleAsyncDelayedTask(new SendAll(user.getName() + ": " + Util.stripFormat(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.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..fb62ec234 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandme.java @@ -0,0 +1,37 @@ +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.replaceFormat(message); + } + else { + message = Util.stripColor(message); + } + + + user.setDisplayNick(); + 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..fc2d2de00 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandmore.java @@ -0,0 +1,56 @@ +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; +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/net/ess3/commands/Commandmotd.java b/Essentials/src/net/ess3/commands/Commandmotd.java new file mode 100644 index 000000000..907a41b34 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandmotd.java @@ -0,0 +1,20 @@ +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; +import org.bukkit.command.CommandSender; + + +public class Commandmotd extends EssentialsCommand +{ + @Override + public 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..e4052de89 --- /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.command.CommandSender; +import org.bukkit.entity.Player; + + +public class Commandmsg extends EssentialsCommand +{ + @Override + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 2 || args[0].trim().length() < 3 || 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.replaceFormat(message); + } + else + { + message = Util.stripColor(message); + } + } + else + { + message = Util.replaceFormat(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(ess.getUser(sender)) || 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..78d13d077 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandmute.java @@ -0,0 +1,57 @@ +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; +import org.bukkit.command.CommandSender; + + +public class Commandmute extends EssentialsCommand +{ + @Override + public 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) + { + final String time = getFinalArg(args, 1); + muteTimestamp = DateUtil.parseDateDiff(time, true); + player.setMuted(true); + } + else + { + player.setMuted(!player.getData().isMuted()); + } + player.setTimestamp(TimestampType.MUTE, muteTimestamp); + final boolean muted = player.getData().isMuted(); + 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..248adfa7f --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandnear.java @@ -0,0 +1,111 @@ +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.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/net/ess3/commands/Commandnick.java b/Essentials/src/net/ess3/commands/Commandnick.java new file mode 100644 index 000000000..e6e3df7f1 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandnick.java @@ -0,0 +1,129 @@ +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.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 + public 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 Util.replaceFormat(nick); + } + else + { + return Util.formatString(user, "essentials.nick", 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..9d39b6dca --- /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.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/net/ess3/commands/Commandpay.java b/Essentials/src/net/ess3/commands/Commandpay.java new file mode 100644 index 000000000..d60f6ea18 --- /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].trim().length() < 3) + { + 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) + { + 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..13e99b912 --- /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.api.IUser; +import net.ess3.utils.Util; + + +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.replaceFormat(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..cd8fe57b7 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandpowertool.java @@ -0,0 +1,109 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import net.ess3.utils.Util; +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("_", " "); + user.acquireReadLock(); + 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)); + } + throw new NoChargeException(); + } + if (command.startsWith("r:")) + { + command = command.substring(2); + if (!powertools.contains(command)) + { + throw new Exception(_("powerToolNoSuchCommandAssigned", command, itemName)); + } + + powertools.remove(command); + user.sendMessage(_("powerToolRemove", command, itemName)); + } + 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)); + } + + if (!user.getData().isPowerToolsEnabled()) + { + user.getData().setPowerToolsEnabled(true); + user.sendMessage(_("powerToolsEnabled")); + } + 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..51cd0485f --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandptime.java @@ -0,0 +1,228 @@ +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.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 + public 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(e); + } + } + + 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..6dbebde81 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandr.java @@ -0,0 +1,85 @@ +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.command.CommandSender; +import org.bukkit.entity.Player; + + +public class Commandr extends EssentialsCommand +{ + @Override + public 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.replaceFormat(message); + } + else + { + message = Util.replaceFormat(message); + } + replyTo = user; + senderName = user.getDisplayName(); + } + else + { + message = Util.replaceFormat(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 (sender instanceof Player && player.isIgnoringPlayer(ess.getUser(sender))) + { + 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 getPermission() + { + 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..0a5e7c783 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandrealname.java @@ -0,0 +1,44 @@ +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.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; + } + u.setDisplayNick(); + final String displayName = Util.stripFormat(u.getDisplayName()).toLowerCase(Locale.ENGLISH); + settings.acquireReadLock(); + if (!whois.equals(displayName) + && !displayName.equals(Util.stripFormat(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..af8a97d4c --- /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.command.CommandSender; +import org.bukkit.entity.*; + +//Todo: Fix this up +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"), e); + } + } + + try + { + toRemove = ToRemove.valueOf(args[0].toUpperCase(Locale.ENGLISH)); + } + catch (IllegalArgumentException e) + { + throw new NotEnoughArgumentsException(e); //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(e); //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.MINECARTS) + { + 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..b523f076b --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandrepair.java @@ -0,0 +1,140 @@ +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 Trade charge = new Trade("repair-all", ess); + charge.isAffordableFor(user); + 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))); + } + charge.charge(user); + + } + 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('_', '-'), "repair-item", 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..1e15a6097 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandrules.java @@ -0,0 +1,20 @@ +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; +import org.bukkit.command.CommandSender; + + +public class Commandrules extends EssentialsCommand +{ + @Override + public 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..315fef9c0 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandseen.java @@ -0,0 +1,69 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; + +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import net.ess3.storage.Location; +import net.ess3.user.UserData.TimestampType; +import net.ess3.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, true); + } + + @Override + protected void run(final IUser user, final String commandLabel, final String[] args) throws Exception + { + seen(user,args,Permissions.SEEN_BANREASON.isAuthorized(user), Permissions.SEEN_EXTRA.isAuthorized(user)); + } + + protected void seen (final CommandSender sender, final String[] args, final boolean showBan, final boolean extra) throws Exception + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + try + { + IUser player = getPlayer(args, 0); + player.setDisplayNick(); + sender.sendMessage(_("seenOnline", player.getDisplayName(), DateUtil.formatDateDiff(player.getTimestamp(TimestampType.LOGIN)))); + if (extra) + { + sender.sendMessage(_("whoisIPAddress", player.getAddress().getAddress().toString())); + } + } + catch (NoSuchFieldException e) + { + @Cleanup + IUser player = ess.getUser(args[0]); + player.acquireReadLock(); + if (player == null) + { + throw new Exception(_("playerNotFound")); + } + player.setDisplayNick(); + sender.sendMessage(_("seenOffline", player.getName(), DateUtil.formatDateDiff(player.getTimestamp(TimestampType.LOGOUT)))); + if (player.isBanned()) + { + sender.sendMessage(_("whoisBanned", showBan ? player.getData().getBan().getReason() : _("true"))); + } + if (extra) + { + sender.sendMessage(_("whoisIPAddress", player.getData().getIpAddress())); + final Location loc = player.getData().getLastLocation(); + if (loc != null) { + sender.sendMessage(_("whoisLocation", loc.getWorldName(), loc.getX(), loc.getY(), loc.getZ())); + } + } + } + } +} 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..ed2a3cb16 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandsethome.java @@ -0,0 +1,95 @@ +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.Location(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.Location(user.getLocation())); + } + } + } + else + { + user.acquireWriteLock(); + if (user.getData().getHomes() == null) + { + user.getData().setHomes(new HashMap()); + } + user.getData().getHomes().put("home", new net.ess3.storage.Location(user.getLocation())); + } + user.sendMessage(_("homeSet", user.getLocation().getWorld().getName(), user.getLocation().getBlockX(), user.getLocation().getBlockY(), user.getLocation().getBlockZ())); + + } +} diff --git a/Essentials/src/net/ess3/commands/Commandsetjail.java b/Essentials/src/net/ess3/commands/Commandsetjail.java new file mode 100644 index 000000000..9938b025c --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandsetjail.java @@ -0,0 +1,21 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.utils.Util; + + +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", Util.sanitizeString(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..18f0a9701 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandsetwarp.java @@ -0,0 +1,50 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.api.IWarps; +import net.ess3.permissions.WarpPermissions; +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) + { + } + + //todo permissions + if (warpLoc == null || WarpPermissions.getPermission("overwrite." + args[0]).isAuthorized(user)) + + { + 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..68fb2481e --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandsetworth.java @@ -0,0 +1,49 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +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 + public 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..1f1b4a023 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandspawn.java @@ -0,0 +1,55 @@ +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.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/net/ess3/commands/Commandspawner.java b/Essentials/src/net/ess3/commands/Commandspawner.java new file mode 100644 index 000000000..ee8b6f1d1 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandspawner.java @@ -0,0 +1,68 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.ISettings; +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 lombok.Cleanup; +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")); + } + + String name = args[0]; + + Mob mob = null; + mob = Mob.fromName(name); + if (mob == null) + { + throw new Exception(_("invalidMob")); + } + @Cleanup + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (settings.getData().getGeneral().getPreventSpawn(mob.getType().toString().toLowerCase(Locale.ENGLISH))) + { + throw new Exception(_("disabledToSpawnMob")); + } + if (!SpawnerPermissions.getPermission(mob.name.toLowerCase(Locale.ENGLISH)).isAuthorized(user)) + { + throw new Exception(_("noPermToSpawnMob")); + } + final Trade charge = new Trade("spawner-" + mob.name.toLowerCase(Locale.ENGLISH), ess); + charge.isAffordableFor(user); + try + { + ((CreatureSpawner)target.getBlock().getState()).setSpawnedType(mob.getType()); + + } + catch (Throwable ex) + { + throw new Exception(_("mobSpawnError"), ex); + } + charge.charge(user); + user.sendMessage(_("setSpawner", mob.name)); + + } +} diff --git a/Essentials/src/net/ess3/commands/Commandspawnmob.java b/Essentials/src/net/ess3/commands/Commandspawnmob.java new file mode 100644 index 000000000..d5b0ed5e2 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandspawnmob.java @@ -0,0 +1,297 @@ +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.*; +import org.bukkit.DyeColor; +import org.bukkit.Location; +import org.bukkit.block.Block; +import org.bukkit.entity.*; +import org.bukkit.entity.Villager.Profession; +import org.bukkit.material.Colorable; + + +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"), e); + } + + 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"), e); + } + 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"), e); + } + 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 (spawned instanceof Slime) + { + try + { + ((Slime)spawned).setSize(Integer.parseInt(data)); + } + catch (Exception e) + { + throw new Exception(_("slimeMalformedSize"), e); + } + } + if (spawned instanceof Ageable && data.contains("baby")) + { + ((Ageable)spawned).setBaby(); + return; + } + if (spawned instanceof Colorable) + { + final String color = data.toUpperCase(Locale.ENGLISH).replace("BABY", ""); + try + { + if (color.equals("RANDOM")) + { + final Random rand = new Random(); + ((Colorable)spawned).setColor(DyeColor.values()[rand.nextInt(DyeColor.values().length)]); + } + else + { + ((Colorable)spawned).setColor(DyeColor.valueOf(color)); + } + } + catch (Exception e) + { + throw new Exception(_("sheepMalformedColor"), e); + } + } + if (spawned instanceof Tameable && 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); + } + else if (data.contains("red")) + { + ((Ocelot)spawned).setCatType(Ocelot.Type.RED_CAT); + } + else if (data.contains("black")) + { + ((Ocelot)spawned).setCatType(Ocelot.Type.BLACK_CAT); + } + } + if (type == EntityType.VILLAGER) + { + for (Profession prof : Villager.Profession.values()) + { + if (data.contains(prof.toString().toLowerCase(Locale.ENGLISH))) + { + ((Villager)spawned).setProfession(prof); + } + } + } + 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..15489a184 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandsudo.java @@ -0,0 +1,43 @@ +package net.ess3.commands; + +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import static net.ess3.I18n._; + +import org.bukkit.command.CommandSender; +import org.bukkit.command.PluginCommand; + + +public class Commandsudo extends EssentialsCommand +{ + @Override + public 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))); + + 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..979341053 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandsuicide.java @@ -0,0 +1,20 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.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 + { + EntityDamageEvent ede = new EntityDamageEvent(user.getBase(), EntityDamageEvent.DamageCause.SUICIDE, 1000); + server.getPluginManager().callEvent(ede); + user.damage(Short.MAX_VALUE); + user.sendMessage(_("suicideMessage")); + user.setDisplayNick(); + 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..fb3918231 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandtempban.java @@ -0,0 +1,61 @@ +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.command.CommandSender; +import org.bukkit.entity.Player; + + +public class Commandtempban extends EssentialsCommand +{ + @Override + public 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..48b322e31 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandtime.java @@ -0,0 +1,157 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import net.ess3.utils.DescParseTickFormat; +import net.ess3.utils.Util; +import java.util.*; +import org.bukkit.World; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + + +public class Commandtime extends EssentialsCommand +{ + @Override + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + final List argList = new ArrayList(Arrays.asList(args)); + if ((argList.remove("set") || argList.remove("add")) && Util.isInt(argList.get(0))) + { + ess.getLogger().info("debug edited 0" + argList.get(0).toString()); + } + final String[] validArgs = argList.toArray(new String[0]); + + // Which World(s) are we interested in? + String worldSelector = null; + if (validArgs.length == 2) + { + worldSelector = validArgs[1]; + } + final Set worlds = getWorlds(sender, worldSelector); + + // If no arguments we are reading the time + if (validArgs.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(validArgs[0]); + } + catch (NumberFormatException e) + { + throw new NotEnoughArgumentsException(e); + } + + 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..1f2d52c49 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandtogglejail.java @@ -0,0 +1,105 @@ +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; +import org.bukkit.command.CommandSender; + + +public class Commandtogglejail extends EssentialsCommand +{ + @Override + public 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..103202a24 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandtp.java @@ -0,0 +1,93 @@ +package net.ess3.commands; + +import net.ess3.Console; +import static net.ess3.I18n._; +import net.ess3.api.ISettings; +import net.ess3.economy.Trade; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import net.ess3.permissions.WorldPermissions; +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 + { + @Cleanup + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + 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())); + } + if (user.getWorld() != player.getWorld() && settings.getData().getGeneral().isWorldTeleportPermissions() + && !WorldPermissions.getPermission(player.getWorld().getName()).isAuthorized(user)) + { + throw new Exception(_("noPerm", "essentials.world." + player.getWorld().getName())); + } + 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")); + @Cleanup + final IUser target = getPlayer(args, 0); + @Cleanup + final IUser toPlayer = getPlayer(args, 1); + target.acquireReadLock(); + toPlayer.acquireReadLock(); + + if (!target.getData().isTeleportEnabled()) + { + throw new Exception(_("teleportDisabled", target.getDisplayName())); + } + if (!toPlayer.getData().isTeleportEnabled()) + { + throw new Exception(_("teleportDisabled", toPlayer.getDisplayName())); + } + if (target.getWorld() != toPlayer.getWorld() && settings.getData().getGeneral().isWorldTeleportPermissions() + && !WorldPermissions.getPermission(toPlayer.getWorld().getName()).isAuthorized(user)) + { + throw new Exception(_("noPerm", "essentials.world." + toPlayer.getWorld().getName())); + } + target.getTeleport().now(toPlayer, false, TeleportCause.COMMAND); + target.sendMessage(_("teleportAtoB", user.getDisplayName(), toPlayer.getDisplayName())); + break; + } + } + + @Override + public 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..48f17f28d --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandtpa.java @@ -0,0 +1,50 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.ISettings; +import net.ess3.api.IUser; +import net.ess3.permissions.WorldPermissions; +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())); + } + @Cleanup + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (user.getWorld() != player.getWorld() && ess.getSettings().getData().getGeneral().isWorldTeleportPermissions() + && !WorldPermissions.getPermission(user.getWorld().getName()).isAuthorized(user)) + { + throw new Exception(_("noPerm", "essentials.world." + player.getWorld().getName())); + } + if (!player.isIgnoringPlayer(user)) + { + player.requestTeleport(user, false); + player.sendMessage(_("teleportRequest", user.getDisplayName())); + player.sendMessage(_("typeTpaccept")); + player.sendMessage(_("typeTpdeny")); + int tpaAcceptCancellation = 0; + tpaAcceptCancellation = settings.getData().getCommands().getTpa().getTimeout(); + 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..36bfd4086 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandtpaall.java @@ -0,0 +1,73 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.ISettings; +import net.ess3.api.IUser; +import net.ess3.permissions.WorldPermissions; +import lombok.Cleanup; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + + +public class Commandtpaall extends EssentialsCommand +{ + @Override + public 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; + } + @Cleanup + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (user.getWorld() != player.getWorld() && settings.getData().getGeneral().isWorldTeleportPermissions() + && !WorldPermissions.getPermission(user.getWorld().getName()).isAuthorized(user)) + { + continue; + } + try + { + player.requestTeleport(user, true); + player.sendMessage(_("teleportHereRequest", user.getDisplayName())); + player.sendMessage(_("typeTpaccept")); + int tpaAcceptCancellation = 0; + tpaAcceptCancellation = settings.getData().getCommands().getTpa().getTimeout(); + 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..e2a86f5bc --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandtpaccept.java @@ -0,0 +1,62 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.ISettings; +import net.ess3.api.IUser; +import net.ess3.economy.Trade; +import net.ess3.permissions.Permissions; +import net.ess3.permissions.WorldPermissions; +import lombok.Cleanup; +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 + { + final IUser target = user.getTeleportRequester(); + @Cleanup + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (target == null || !target.isOnline() + || (args.length > 0 && !target.getName().contains(args[0])) + || (user.isTpRequestHere() && !Permissions.TPAHERE.isAuthorized(target)) + || (!user.isTpRequestHere() && ((!Permissions.TPA.isAuthorized(target) && !Permissions.TPAALL.isAuthorized(target)) + || (user.getWorld() != target.getWorld() + && settings.getData().getGeneral().isWorldTeleportPermissions() + && !WorldPermissions.getPermission(user.getWorld().getName()).isAuthorized(user))))) + { + throw new Exception(_("noPendingRequest")); + } + + long timeout = settings.getData().getCommands().getTpa().getTimeout(); + if (timeout != 0 && (System.currentTimeMillis() - user.getTeleportRequestTime()) / 1000 > timeout) + { + user.requestTeleport(null, false); + throw new Exception(_("requestTimedOut")); + } + + final Trade charge = new Trade(this.commandName, ess); + if (user.isTpRequestHere()) + { + charge.isAffordableFor(user); + } + else + { + charge.isAffordableFor(target); + } + user.sendMessage(_("requestAccepted")); + target.sendMessage(_("requestAcceptedFrom", user.getDisplayName())); + + if (user.isTpRequestHere()) + { + 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..efff0cb50 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandtpahere.java @@ -0,0 +1,48 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.ISettings; +import net.ess3.api.IUser; +import net.ess3.permissions.WorldPermissions; +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())); + } + @Cleanup + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (user.getWorld() != player.getWorld() && settings.getData().getGeneral().isWorldTeleportPermissions() + && !WorldPermissions.getPermission(user.getWorld().getName()).isAuthorized(user)) + { + throw new Exception(_("noPerm", "essentials.world." + user.getWorld().getName())); + } + player.requestTeleport(user, true); + player.sendMessage(_("teleportHereRequest", user.getDisplayName())); + player.sendMessage(_("typeTpaccept")); + int tpaAcceptCancellation = 0; + { + tpaAcceptCancellation = settings.getData().getCommands().getTpa().getTimeout(); + } + 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..15d59f1d4 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandtpall.java @@ -0,0 +1,62 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.ISettings; +import net.ess3.api.IUser; +import net.ess3.permissions.WorldPermissions; +import lombok.Cleanup; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; + + +public class Commandtpall extends EssentialsCommand +{ + @Override + public 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; + } + @Cleanup + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + + if (user.getWorld() != player.getWorld() && settings.getData().getGeneral().isWorldTeleportPermissions() + && !WorldPermissions.getPermission(user.getWorld().getName()).isAuthorized(user)) + { + continue; + } + try + { + player.getTeleport().now(user, false, TeleportCause.COMMAND); + } + catch (Exception ex) + { + ess.getCommandHandler().showCommandError(sender, commandName, ex); + } + + } + } +} \ No newline at end of file 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..856cab2d4 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandtphere.java @@ -0,0 +1,37 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.ISettings; +import net.ess3.api.IUser; +import net.ess3.economy.Trade; +import net.ess3.permissions.WorldPermissions; +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())); + } + @Cleanup + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (user.getWorld() != player.getWorld() && settings.getData().getGeneral().isWorldTeleportPermissions() + && !WorldPermissions.getPermission(user.getWorld().getName()).isAuthorized(user)) + { + throw new Exception(_("noPerm", "essentials.world." + user.getWorld().getName())); + } + player.getTeleport().teleport(user, new Trade(this.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..b7fdce113 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandtpo.java @@ -0,0 +1,67 @@ +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 net.ess3.permissions.WorldPermissions; +import lombok.Cleanup; +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 + { + @Cleanup + ISettings settings = ess.getSettings(); + switch (args.length) + { + case 0: + throw new NotEnoughArgumentsException(); + + case 1: + final IUser player = getPlayer(args, 0, true); + if (!player.isOnline() || (player.isHidden() && !Permissions.TELEPORT_HIDDEN.isAuthorized(player))) + { + throw new NoSuchFieldException(_("playerNotFound")); + } + settings.acquireReadLock(); + if (user.getWorld() != player.getWorld() && settings.getData().getGeneral().isWorldTeleportPermissions() + && !WorldPermissions.getPermission(player.getWorld().getName()).isAuthorized(player)) + { + throw new Exception(_("noPerm", "essentials.world." + player.getWorld().getName())); + } + + user.sendMessage(_("teleporting")); + user.getTeleport().now(player, false, TeleportCause.COMMAND); + break; + + default: + if (!Permissions.TELEPORT_OTHERS.isAuthorized(user)) + { + throw new Exception(_("noPerm", "essentials.tp.others")); + } + user.sendMessage(_("teleporting")); + final IUser target = getPlayer(args, 0, true); + final IUser toPlayer = getPlayer(args, 1, true); + + if (!target.isOnline() || !toPlayer.isOnline() + || ((target.isHidden() || toPlayer.isHidden()) && !Permissions.TELEPORT_HIDDEN.isAuthorized(user))) + { + throw new NoSuchFieldException(_("playerNotFound")); + } + settings.acquireReadLock(); + if (target.getWorld() != toPlayer.getWorld() && settings.getData().getGeneral().isWorldTeleportPermissions() + && !WorldPermissions.getPermission(toPlayer.getWorld().getName()).isAuthorized(user)) + { + throw new Exception(_("noPerm", "essentials.world." + toPlayer.getWorld().getName())); + } + + target.getTeleport().now(toPlayer, false, TeleportCause.COMMAND); + target.sendMessage(_("teleportAtoB", user.getDisplayName(), toPlayer.getDisplayName())); + break; + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandtpohere.java b/Essentials/src/net/ess3/commands/Commandtpohere.java new file mode 100644 index 000000000..734ba32a5 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandtpohere.java @@ -0,0 +1,52 @@ +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 net.ess3.permissions.WorldPermissions; +import lombok.Cleanup; +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")); + } + @Cleanup + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + //todo - common method + if (user.getWorld() != player.getWorld() && settings.getData().getGeneral().isWorldTeleportPermissions() + && !WorldPermissions.getPermission(user.getWorld().getName()).isAuthorized(player)) + { + throw new Exception(_("noPerm", "essentials.world." + user.getWorld().getName())); + } + + + // 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..946bf9cbc --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandtppos.java @@ -0,0 +1,65 @@ +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.command.CommandSender; +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(); + } + + @Override + public void run(final CommandSender sender, final String commandLabel, final String[] args) throws Exception + { + if (args.length < 4) + { + throw new NotEnoughArgumentsException(); + } + + IUser user = ess.getUser(server.getPlayer(args[0])); + final int x = Integer.parseInt(args[1]); + final int y = Integer.parseInt(args[2]); + final int z = Integer.parseInt(args[3]); + final Location location = new Location(user.getWorld(), x, y, z); + if (args.length > 4) + { + location.setYaw((Float.parseFloat(args[4]) + 180 + 360) % 360); + } + if (args.length > 5) + { + location.setPitch(Float.parseFloat(args[5])); + } + sender.sendMessage(_("teleporting")); + user.sendMessage(_("teleporting")); + user.getTeleport().teleport(location, null, TeleportCause.COMMAND); + } +} \ 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..991e86380 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandtree.java @@ -0,0 +1,69 @@ +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 if (args[0].equalsIgnoreCase("jungle")) + { + tree = TreeType.SMALL_JUNGLE; + } + else if (args[0].equalsIgnoreCase("junglebush")) + { + tree = TreeType.JUNGLE_BUSH; + } + else if (args[0].equalsIgnoreCase("swamp")) + { + tree = TreeType.SWAMP; + } + 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..c3c6f71a1 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandunban.java @@ -0,0 +1,33 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import lombok.Cleanup; +import org.bukkit.command.CommandSender; + + +public class Commandunban extends EssentialsCommand +{ + @Override + public 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"), e); + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandunbanip.java b/Essentials/src/net/ess3/commands/Commandunbanip.java new file mode 100644 index 000000000..95c5f2e98 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandunbanip.java @@ -0,0 +1,31 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import lombok.Cleanup; +import org.bukkit.command.CommandSender; + + +public class Commandunbanip extends EssentialsCommand +{ + @Override + public 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..74a25d638 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandunlimited.java @@ -0,0 +1,112 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; +import net.ess3.craftbukkit.InventoryWorkaround; +import net.ess3.permissions.Permissions; +import net.ess3.permissions.UnlimitedItemPermissions; +import java.util.Locale; +import java.util.Set; +import lombok.Cleanup; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + + +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.name()); + + } + } + 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.name().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 (!InventoryWorkaround.containsItem(target.getInventory(), 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/Commandvanish.java b/Essentials/src/net/ess3/commands/Commandvanish.java new file mode 100644 index 000000000..16cab5a51 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandvanish.java @@ -0,0 +1,37 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.api.IUser; + + +public class Commandvanish extends EssentialsCommand +{ + @Override + protected void run(IUser user, String commandLabel, String[] args) throws Exception + { + if (args.length < 1) + { + user.toggleVanished(); + if (user.isVanished()) + { + user.sendMessage(_("vanished")); + } + else + { + user.sendMessage(_("unvanished")); + } + } + else + { + if (args[0].contains("on") || args[0].contains("ena") || args[0].equalsIgnoreCase("1")) + { + user.setVanished(true); + } + else + { + user.setVanished(false); + } + user.sendMessage(user.isVanished() ? _("vanished") : _("unvanished")); + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandwarp.java b/Essentials/src/net/ess3/commands/Commandwarp.java new file mode 100644 index 000000000..a6383df43 --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandwarp.java @@ -0,0 +1,126 @@ +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.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 + public 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 chargeWarp = new Trade("warp-" + name.toLowerCase(Locale.ENGLISH).replace('_', '-'), ess); + final Trade chargeCmd = new Trade(this.commandName, ess); + final double fullCharge = chargeWarp.getCommandCost(user) + chargeCmd.getCommandCost(user); + final Trade charge = new Trade(fullCharge, 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..eb4f2b707 --- /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 org.bukkit.World; +import org.bukkit.command.CommandSender; + + +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..18924ac9a --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandwhois.java @@ -0,0 +1,98 @@ +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 net.ess3.user.UserData; +import net.ess3.utils.DateUtil; +import net.ess3.craftbukkit.SetExpFix; +import java.util.Locale; +import lombok.Cleanup; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + + +public class Commandwhois extends EssentialsCommand +{ + @Override + public 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(); + boolean foundPlayer = false; + for (Player onlinePlayer : server.getOnlinePlayers()) + { + @Cleanup + final IUser user = ess.getUser(onlinePlayer); + + if (user.isHidden() && !showhidden) + { + continue; + } + user.acquireReadLock(); + final String nickName = Util.stripFormat(user.getData().getNickname()); + if (!whois.equalsIgnoreCase(nickName) + && !whois.substring(prefixLength).equalsIgnoreCase(nickName) + && !whois.equalsIgnoreCase(user.getName())) + { + continue; + } + foundPlayer = true; + sender.sendMessage(_("whoisTop", user.getName())); + user.setDisplayNick(); + sender.sendMessage(_("whoisIs", user.getDisplayName(), user.getName())); + sender.sendMessage(_("whoisHealth", user.getHealth())); + sender.sendMessage(_("whoisExp", SetExpFix.getTotalExperience(user), user.getLevel())); + 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(_("whoisIPAddress", user.getAddress().getAddress().toString())); + final String location = user.getData().getGeolocation(); + if (location != null + && Permissions.GEOIP_SHOW.isAuthorized(sender)) + { + sender.sendMessage(_("whoisGeoLocation", location)); + } + sender.sendMessage(_("whoisGamemode", _(user.getGameMode().toString().toLowerCase(Locale.ENGLISH)))); + sender.sendMessage(_("whoisGod", (user.isGodModeEnabled() ? _("true") : _("false")))); + sender.sendMessage(_("whoisOP", (user.isOp() ? _("true") : _("false")))); + sender.sendMessage(_("whoisFly", user.getAllowFlight() ? _("true") : _("false"), user.isFlying() ? _("flying") : _("notFlying"))); + sender.sendMessage(_("whoisAFK", (user.getData().isAfk() ? _("true") : _("false")))); + sender.sendMessage(_("whoisJail", (user.getData().isJailed() + ? user.getTimestamp(UserData.TimestampType.JAIL) > 0 + ? DateUtil.formatDateDiff(user.getTimestamp(UserData.TimestampType.JAIL)) + : _("true") + : _("false")))); + sender.sendMessage(_("whoisMute", (user.getData().isMuted() + ? user.getTimestamp(UserData.TimestampType.MUTE) > 0 + ? DateUtil.formatDateDiff(user.getTimestamp(UserData.TimestampType.MUTE)) + : _("true") + : _("false")))); + + if (!foundPlayer) + { + throw new NoSuchFieldException(_("playerNotFound")); + } + } + } +} diff --git a/Essentials/src/net/ess3/commands/Commandworld.java b/Essentials/src/net/ess3/commands/Commandworld.java new file mode 100644 index 000000000..d5e3bd58a --- /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.permissions.WorldPermissions; +import java.util.List; +import org.bukkit.Location; +import org.bukkit.World; +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 = new Location(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..211460cae --- /dev/null +++ b/Essentials/src/net/ess3/commands/Commandworth.java @@ -0,0 +1,102 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.utils.Util; +import net.ess3.api.IUser; +import java.util.Locale; +import org.bukkit.command.CommandSender; +import org.bukkit.inventory.ItemStack; + + +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.getInventory().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..73215060a --- /dev/null +++ b/Essentials/src/net/ess3/commands/EssentialsCommand.java @@ -0,0 +1,132 @@ +package net.ess3.commands; + +import static net.ess3.I18n._; +import net.ess3.economy.Trade; +import net.ess3.api.IEssentials; +import net.ess3.api.IEssentialsModule; +import net.ess3.api.IUser; +import net.ess3.permissions.AbstractSuperpermsPermission; +import java.util.List; +import java.util.logging.Logger; +import org.bukkit.Server; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.permissions.Permission; + + +public abstract class EssentialsCommand extends AbstractSuperpermsPermission implements IEssentialsCommand +{ + protected transient String commandName; + protected transient IEssentials ess; + protected transient IEssentialsModule module; + protected transient Server server; + protected transient Logger logger; + private transient String permission; + private transient Permission bukkitPerm; + + 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 = ess.getUser(player); + if (userMatch.getDisplayName().startsWith(args[pos]) && (getOffline || !userMatch.isHidden())) + { + return userMatch; + } + } + final IUser userMatch = ess.getUser(matches.get(0)); + 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.getBase(), 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 getPermission() + { + 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..ff4150c99 --- /dev/null +++ b/Essentials/src/net/ess3/commands/EssentialsCommandHandler.java @@ -0,0 +1,313 @@ +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.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("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..34f1ba020 --- /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 org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + + +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..eef5db914 --- /dev/null +++ b/Essentials/src/net/ess3/commands/WarpNotFoundException.java @@ -0,0 +1,18 @@ +package net.ess3.commands; +import static net.ess3.I18n._; + + +public class WarpNotFoundException extends Exception +{ + public WarpNotFoundException() + { + super(_("warpNotExist")); + } + + public WarpNotFoundException(String message) + { + super(message); + } +} + + diff --git a/Essentials/src/net/ess3/craftbukkit/FakeInventory.java b/Essentials/src/net/ess3/craftbukkit/FakeInventory.java new file mode 100644 index 000000000..7db0a1a7b --- /dev/null +++ b/Essentials/src/net/ess3/craftbukkit/FakeInventory.java @@ -0,0 +1,243 @@ +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."); + } + + @Override + public int getMaxStackSize() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setMaxStackSize(int size) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public ListIterator iterator(int index) + { + 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..f816026b9 --- /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 enforceDurability, final boolean enforceAmount, final boolean enforceEnchantments) + { + return next(inventory, item, 0, enforceDurability, enforceAmount, enforceEnchantments); + } + + public static int next(final Inventory cinventory, final ItemStack item, final int start, final boolean enforceDurability, final boolean enforceAmount, final boolean enforceEnchantments) + { + 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() && (!enforceAmount || item.getAmount() == cItem.getAmount()) && (!enforceDurability || cItem.getDurability() == item.getDurability()) && (!enforceEnchantments || cItem.getEnchantments().equals(item.getEnchantments()))) + { + return i; + } + } + return -1; + } + + public static int firstPartial(final Inventory cinventory, final ItemStack item, final boolean enforceDurability) + { + return firstPartial(cinventory, item, enforceDurability, item.getType().getMaxStackSize()); + } + + public static int firstPartial(final Inventory cinventory, final ItemStack item, final boolean enforceDurability, 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 && (!enforceDurability || cItem.getDurability() == item.getDurability()) && cItem.getEnchantments().equals(item.getEnchantments())) + { + return i; + } + } + return -1; + } + + public static boolean addAllItems(final Inventory cinventory, final boolean enforceDurability, final ItemStack... items) + { + final Inventory fake = new FakeInventory(cinventory.getContents()); + if (addItem(fake, enforceDurability, items).isEmpty()) + { + addItem(cinventory, enforceDurability, 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 enforceDurability, 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() && (!enforceDurability || 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, enforceDurability, 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 enforceDurability, final boolean enforceEnchantments, 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, enforceDurability, false, enforceEnchantments); + + // 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 enforceDurability, final boolean enforceEnchantments, 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() && (!enforceDurability || combined[j].getDurability() == items[i].getDurability()) && (!enforceEnchantments || 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, enforceDurability, false, enforceEnchantments); + + // 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..17efe7514 --- /dev/null +++ b/Essentials/src/net/ess3/craftbukkit/SetExpFix.java @@ -0,0 +1,65 @@ +package net.ess3.craftbukkit; + +import org.bukkit.entity.Player; + + +public class SetExpFix +{ + //This method is used to update both the recorded total experience and displayed total experience. + //We reset both types to prevent issues. + public static void setTotalExperience(final Player player, final int exp) + { + if (exp < 0) + { + throw new IllegalArgumentException("Experience is negative!"); + } + player.setExp(0); + player.setLevel(0); + player.setTotalExperience(0); + + //This following code is technically redundant now, as bukkit now calulcates levels more or less correctly + //At larger numbers however... player.getExp(3000), only seems to give 2999, putting the below calculations off. + 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 Player player) + { + return getExpToLevel(player.getLevel()); + } + + private static int getExpToLevel(final int level) + { + return 7 + (level * 7 >> 1); + } + + //This method is required because the bukkit player.getTotalExperience() method, shows exp that has been 'spent'. + //Without this people would be able to use exp and then still sell it. + public static int getTotalExperience(final Player player) + { + int exp = (int)Math.round(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..a17fdb01f --- /dev/null +++ b/Essentials/src/net/ess3/economy/MoneyHolder.java @@ -0,0 +1,36 @@ +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 +{ + + @Override + public void finishRead() + { + + } + + @Override + public void finishWrite() + { + + } + + + public MoneyHolder(IEssentials ess) + { + super(ess, Money.class); + onReload(); + } + + @Override + public File getStorageFile() throws IOException + { + return new File(ess.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..a5225a13a --- /dev/null +++ b/Essentials/src/net/ess3/economy/Trade.java @@ -0,0 +1,357 @@ +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.craftbukkit.InventoryWorkaround; +import net.ess3.craftbukkit.SetExpFix; +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; +import org.bukkit.Location; +import org.bukkit.entity.Item; +import org.bukkit.inventory.ItemStack; + + +public class Trade +{ + private final transient String command; + private final transient String fallbackCommand; + 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, null, ess); + } + + public Trade(final String command, final String fallback, final IEssentials ess) + { + this(command, fallback, null, null, null, ess); + } + + public Trade(final double money, final IEssentials ess) + { + this(null, null, money, null, null, ess); + } + + public Trade(final ItemStack items, final IEssentials ess) + { + this(null, null, null, items, null, ess); + } + + public Trade(final int exp, final IEssentials ess) + { + this(null, null, null, null, exp, ess); + } + + private Trade(final String command, final String fallback, final Double money, final ItemStack item, final Integer exp, final IEssentials ess) + { + this.command = command; + this.fallbackCommand = fallback; + this.money = money; + this.itemStack = item; + this.exp = exp; + this.ess = ess; + } + + public void isAffordableFor(final IUser user) throws ChargeException + { + if (getMoney() != null + && getMoney() > 0 + && !Permissions.ECO_LOAN.isAuthorized(user) + && !user.canAfford(getMoney())) + { + throw new ChargeException(_("notEnoughMoney")); + } + + if (getItemStack() != null + && !InventoryWorkaround.containsItem(user.getInventory(), 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) + && money < 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 + && SetExpFix.getTotalExperience(user) < 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 = InventoryWorkaround.addItem(user.getInventory(), 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 Item[] itemStacks = new Item[stacks + (leftover > 0 ? 1 : 0)]; + for (int i = 0; i < stacks; i++) + { + final ItemStack stack = dropStack.clone(); + stack.setAmount(maxStackSize); + itemStacks[i] = loc.getWorld().dropItem(loc, stack); + } + if (leftover > 0) + { + final ItemStack stack = dropStack.clone(); + stack.setAmount(leftover); + itemStacks[stacks] = loc.getWorld().dropItem(loc, stack); + } + } + } + else + { + success = InventoryWorkaround.addAllItems(user.getInventory(), true, getItemStack()); + } + user.updateInventory(); + } + if (getExperience() != null) + { + SetExpFix.setTotalExperience(user, SetExpFix.getTotalExperience(user) + 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 (!InventoryWorkaround.containsItem(user.getInventory(), true, true, itemStack)) + { + throw new ChargeException(_("missingItems", getItemStack().getAmount(), getItemStack().getType().toString().toLowerCase(Locale.ENGLISH).replace("_", " "))); + } + InventoryWorkaround.removeItem(user.getInventory(), 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 = SetExpFix.getTotalExperience(user); + if (experience < getExperience() && getExperience() > 0) + { + throw new ChargeException(_("notEnoughExperience")); + } + SetExpFix.setTotalExperience(user, experience - getExperience()); + } + } + + public Double getMoney() + { + return money; + } + + public ItemStack getItemStack() + { + return itemStack; + } + + public Integer getExperience() + { + return exp; + } + + public Double getCommandCost(final IUser user) + { + double cost = 0d; + if (command != null && !command.isEmpty() + && !NoCommandCostPermissions.getPermission("all").isAuthorized(user) + && !NoCommandCostPermissions.getPermission(command).isAuthorized(user)) + { + cost = ess.getSettings().getData().getEconomy().getCommandCost(command.charAt(0) == '/' ? command.substring(1) : command); + if (cost == 0.0 && fallbackCommand != null && !fallbackCommand.isEmpty()) + { + cost = ess.getSettings().getData().getEconomy().getCommandCost(fallbackCommand.charAt(0) == '/' ? fallbackCommand.substring(1) : fallbackCommand); + } + } + return cost; + } + private static FileWriter fw = null; + + public static void log(String type, String subtype, String event, String sender, Trade charge, String receiver, Trade pay, Location loc, IEssentials ess) + { + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (!settings.getData().getEconomy().isLogEnabled()) + { + return; + } + if (fw == null) + { + try + { + fw = new FileWriter(new File(ess.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..59074c77f --- /dev/null +++ b/Essentials/src/net/ess3/economy/WorthHolder.java @@ -0,0 +1,100 @@ +package net.ess3.economy; + +import net.ess3.api.IEssentials; +import net.ess3.api.IWorth; +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.inventory.ItemStack; +import org.bukkit.material.MaterialData; + + +public class WorthHolder extends AsyncStorageObjectHolder implements IWorth +{ + + @Override + public void finishRead() + { + + } + + @Override + public void finishWrite() + { + + } + + + 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.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..c01e46476 --- /dev/null +++ b/Essentials/src/net/ess3/economy/register/Method.java @@ -0,0 +1,217 @@ +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 reported name of this method. + * + * @return String Plugin name. + */ + public String getLongName(); + + /** + * 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..200e8573c --- /dev/null +++ b/Essentials/src/net/ess3/economy/register/methods/BOSE6.java @@ -0,0 +1,334 @@ +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 getLongName() + { + return getName(); + } + + @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..f9092c350 --- /dev/null +++ b/Essentials/src/net/ess3/economy/register/methods/BOSE7.java @@ -0,0 +1,323 @@ +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 getLongName() + { + return getName(); + } + + @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..77fed351b --- /dev/null +++ b/Essentials/src/net/ess3/economy/register/methods/MCUR.java @@ -0,0 +1,195 @@ +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 getLongName() + { + return getName(); + } + + @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..5281c5b2f --- /dev/null +++ b/Essentials/src/net/ess3/economy/register/methods/VaultEco.java @@ -0,0 +1,347 @@ +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(); + } + + public String getEconomy() + { + return economy == null ? "NoEco" : economy.getName(); + } + + @Override + public String getLongName() + { + return getName().concat(" - Economy: ").concat(getEconomy()); + } + + @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..3972b2432 --- /dev/null +++ b/Essentials/src/net/ess3/economy/register/methods/iCo4.java @@ -0,0 +1,256 @@ +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 getLongName() + { + return getName(); + } + + @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..171abfc7c --- /dev/null +++ b/Essentials/src/net/ess3/economy/register/methods/iCo5.java @@ -0,0 +1,376 @@ +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 getLongName() + { + return getName(); + } + + @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..4944a91a9 --- /dev/null +++ b/Essentials/src/net/ess3/economy/register/methods/iCo6.java @@ -0,0 +1,242 @@ +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 getLongName() + { + return getName(); + } + + @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..e23702135 --- /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.LOW, 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.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..828bb3925 --- /dev/null +++ b/Essentials/src/net/ess3/listener/EssentialsEntityListener.java @@ -0,0 +1,175 @@ +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.user.UserData.TimestampType; +import java.util.List; +import lombok.Cleanup; +import org.bukkit.Material; +import org.bukkit.entity.Ageable; +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.LOW) + 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); + @Cleanup + final IUser defender = ess.getUser((Player)eDefend); + @Cleanup + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + attacker.acquireReadLock(); + defender.acquireReadLock(); + + attacker.updateActivity(true); + if (settings.getData().getGeneral().getLoginAttackDelay() > 0 && !Permissions.PVPDELAY_EXEMPT.isAuthorized(attacker) + && (System.currentTimeMillis() < (attacker.getTimestamp(TimestampType.LOGIN) + settings.getData().getGeneral().getLoginAttackDelay()))) + { + event.setCancelled(true); + } + if (attacker.hasInvulnerabilityAfterTeleport() || defender.hasInvulnerabilityAfterTeleport()) + { + event.setCancelled(true); + } + final ItemStack itemstack = attacker.getItemInHand(); + final List commandList = attacker.getData().getPowertool(itemstack.getType()); + if (commandList != null && !commandList.isEmpty()) + { + for (final String command : commandList) + { + if (command != null && !command.isEmpty()) + { + ess.scheduleSyncDelayedTask( + new Runnable() + { + @Override + public void run() + { + attacker.getServer().dispatchCommand(attacker.getBase(), command.replaceAll("\\{player\\}", defender.getName())); + } + }); + event.setCancelled(true); + return; + } + } + } + } + else if (eDefend instanceof Ageable && eAttack instanceof Player) + { + final Player player = (Player)eAttack; + final ItemStack hand = player.getItemInHand(); + if (hand != null && hand.getType() == Material.MILK_BUCKET) + { + ((Ageable)eDefend).setBaby(); + hand.setType(Material.BUCKET); + player.setItemInHand(hand); + player.updateInventory(); + event.setCancelled(true); + } + } + } + + @EventHandler(priority = EventPriority.LOW, 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.LOW, 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.LOW) + public void onPlayerDeathExpEvent(final PlayerDeathEvent event) + { + final IUser user = ess.getUser(event.getEntity()); + if (Permissions.KEEPXP.isAuthorized(user)) + { + event.setKeepLevel(true); + event.setDroppedExp(0); + } + } + + @EventHandler(priority = EventPriority.LOW, 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.LOW, 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..3baaa6898 --- /dev/null +++ b/Essentials/src/net/ess3/listener/EssentialsPlayerListener.java @@ -0,0 +1,490 @@ +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.user.UserData.TimestampType; +import net.ess3.utils.LocationUtil; +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 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.HumanEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.event.player.*; +import org.bukkit.event.player.PlayerLoginEvent.Result; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; +import org.bukkit.inventory.InventoryHolder; +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)) + { + 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.setGodModeEnabled(false); + } + if (user.isVanished()) + { + user.toggleVanished(); + } + 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) + { + if (!event.getPlayer().isOnline()) + { + return; + } + 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); + + for (String p : ess.getVanishedPlayers()) + { + if (!Permissions.VANISH_SEE_OTHERS.isAuthorized(user)) + { + user.hidePlayer(ess.getUser(p).getBase()); + } + } + + 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); + } + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onInventoryClickEvent(final InventoryClickEvent event) + { + if (event.getView().getTopInventory().getType() == InventoryType.PLAYER) + { + final IUser user = ess.getUser(event.getWhoClicked()); + final InventoryHolder invHolder = event.getView().getTopInventory().getHolder(); + if (invHolder != null && invHolder instanceof HumanEntity) + { + final IUser invOwner = ess.getUser((HumanEntity)invHolder); + if (user.isInvSee() && (!Permissions.INVSEE_MODIFY.isAuthorized(user) + || Permissions.INVSEE_PREVENT_MODIFY.isAuthorized(invOwner) + || !invOwner.isOnline())) + { + event.setCancelled(true); + } + } + } + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onInventoryCloseEvent(final InventoryCloseEvent event) + { + if (event.getView().getTopInventory().getType() == InventoryType.PLAYER) + { + final IUser user = ess.getUser(event.getPlayer()); + user.setInvSee(false); + } + } +} 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..fc4609d05 --- /dev/null +++ b/Essentials/src/net/ess3/listener/TntExplodeListener.java @@ -0,0 +1,62 @@ +package net.ess3.listener; + +import net.ess3.api.IEssentials; +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; + } + if (event.blockList().size() < 1) + { + return; + } + event.setCancelled(true); + event.getLocation().getWorld().createExplosion(event.getLocation(), 0F); + } + + @Override + public void run() + { + enabled.set(false); + } +} diff --git a/Essentials/src/net/ess3/metrics/Metrics.java b/Essentials/src/net/ess3/metrics/Metrics.java new file mode 100644 index 000000000..415938dea --- /dev/null +++ b/Essentials/src/net/ess3/metrics/Metrics.java @@ -0,0 +1,625 @@ +package net.ess3.metrics; + +/* + * Copyright 2011 Tyler Blair. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the + * following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following + * disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the + * following disclaimer in the documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL + * THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the authors and contributors and + * should not be interpreted as representing official policies, either expressed or implied, of anybody else. + */ +import java.io.*; +import java.net.Proxy; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLEncoder; +import java.util.*; +import java.util.logging.Level; +import org.bukkit.Bukkit; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginDescriptionFile; + + +/** + *

The metrics class obtains data about a plugin and submits statistics about it to the metrics backend.

+ * Public methods provided by this class:

+ * + * Graph createGraph(String name);
+ * void addCustomData(Metrics.Plotter plotter);
+ * void start();
+ *
+ */ +public class Metrics +{ + /** + * The current revision number + */ + private final static int REVISION = 5; + /** + * The base url of the metrics domain + */ + private static final String BASE_URL = "http://metrics.essentials3.net"; + /** + * The url used to report a server's status + */ + private static final String REPORT_URL = "/report/%s"; + /** + * The file where guid and opt out is stored in + */ + private static final String CONFIG_FILE = "plugins/PluginMetrics/config.yml"; + /** + * The separator to use for custom data. This MUST NOT change unless you are hosting your own version of metrics and + * want to change it. + */ + private static final String CUSTOM_DATA_SEPARATOR = "~~"; + /** + * Interval of time to ping (in minutes) + */ + private static final int PING_INTERVAL = 10; + /** + * The plugin this metrics submits for + */ + private final Plugin plugin; + /** + * All of the custom graphs to submit to metrics + */ + private final Set graphs = Collections.synchronizedSet(new HashSet()); + /** + * The default graph, used for addCustomData when you don't want a specific graph + */ + private final Graph defaultGraph = new Graph("Default"); + /** + * The plugin configuration file + */ + private final YamlConfiguration configuration; + /** + * The plugin configuration file + */ + private final File configurationFile; + /** + * Unique server id + */ + private final String guid; + /** + * Lock for synchronization + */ + private final Object optOutLock = new Object(); + /** + * Id of the scheduled task + */ + private volatile int taskId = -1; + + public Metrics(final Plugin plugin) throws IOException + { + if (plugin == null) + { + throw new IllegalArgumentException("Plugin cannot be null"); + } + + this.plugin = plugin; + + // load the config + configurationFile = new File(CONFIG_FILE); + configuration = YamlConfiguration.loadConfiguration(configurationFile); + + // add some defaults + configuration.addDefault("opt-out", false); + configuration.addDefault("guid", UUID.randomUUID().toString()); + + // Do we need to create the file? + if (configuration.get("guid", null) == null) + { + configuration.options().header("http://metrics.griefcraft.com").copyDefaults(true); + configuration.save(configurationFile); + } + + // Load the guid then + guid = configuration.getString("guid"); + } + + /** + * Construct and create a Graph that can be used to separate specific plotters to their own graphs on the metrics + * website. Plotters can be added to the graph object returned. + * + * @param name + * @return Graph object created. Will never return NULL under normal circumstances unless bad parameters are given + */ + public Graph createGraph(final String name) + { + if (name == null) + { + throw new IllegalArgumentException("Graph name cannot be null"); + } + + // Construct the graph object + final Graph graph = new Graph(name); + + // Now we can add our graph + graphs.add(graph); + + // and return back + return graph; + } + + /** + * Adds a custom data plotter to the default graph + * + * @param plotter + */ + public void addCustomData(final Plotter plotter) + { + if (plotter == null) + { + throw new IllegalArgumentException("Plotter cannot be null"); + } + + // Add the plotter to the graph o/ + defaultGraph.addPlotter(plotter); + + // Ensure the default graph is included in the submitted graphs + graphs.add(defaultGraph); + } + + /** + * Start measuring statistics. This will immediately create an async repeating task as the plugin and send the + * initial data to the metrics backend, and then after that it will post in increments of PING_INTERVAL * 1200 + * ticks. + */ + public void start() + { + synchronized (optOutLock) + { + // Did we opt out? + if (isOptOut()) + { + return; + } + + // Begin hitting the server with glorious data + taskId = plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable() + { + private boolean firstPost = true; + + public void run() + { + try + { + // This has to be synchronized or it can collide with the disable method. + synchronized (optOutLock) + { + // Disable Task, if it is running and the server owner decided to opt-out + if (isOptOut() && taskId > 0) + { + plugin.getServer().getScheduler().cancelTask(taskId); + taskId = -1; + } + } + + // We use the inverse of firstPost because if it is the first time we are posting, + // it is not a interval ping, so it evaluates to FALSE + // Each time thereafter it will evaluate to TRUE, i.e PING! + postPlugin(!firstPost); + + // After the first post we set firstPost to false + // Each post thereafter will be a ping + firstPost = false; + } + catch (IOException e) + { + Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage()); + } + } + }, 0, PING_INTERVAL * 1200); + } + } + + /** + * Has the server owner denied plugin metrics? + * + * @return + */ + public boolean isOptOut() + { + synchronized (optOutLock) + { + try + { + // Reload the metrics file + configuration.load(CONFIG_FILE); + } + catch (IOException ex) + { + Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); + return true; + } + catch (InvalidConfigurationException ex) + { + Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); + return true; + } + return configuration.getBoolean("opt-out", false); + } + } + + /** + * Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task. + * + * @throws IOException + */ + public void enable() throws IOException + { + // This has to be synchronized or it can collide with the check in the task. + synchronized (optOutLock) + { + // Check if the server owner has already set opt-out, if not, set it. + if (isOptOut()) + { + configuration.set("opt-out", false); + configuration.save(configurationFile); + } + + // Enable Task, if it is not running + if (taskId < 0) + { + start(); + } + } + } + + /** + * Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task. + * + * @throws IOException + */ + public void disable() throws IOException + { + // This has to be synchronized or it can collide with the check in the task. + synchronized (optOutLock) + { + // Check if the server owner has already set opt-out, if not, set it. + if (!isOptOut()) + { + configuration.set("opt-out", true); + final File file = new File(CONFIG_FILE); + configuration.save(file); + } + + // Disable Task, if it is running + if (taskId >= 0) + { + this.plugin.getServer().getScheduler().cancelTask(taskId); + taskId = -1; + } + } + } + + /** + * Generic method that posts a plugin to the metrics website + */ + private void postPlugin(final boolean isPing) throws IOException + { + // The plugin's description file containg all of the plugin data such as name, version, author, etc + final PluginDescriptionFile description = plugin.getDescription(); + + // Construct the post data + final StringBuilder data = new StringBuilder(); + data.append(encode("guid")).append('=').append(encode(guid)); + encodeDataPair(data, "version", description.getVersion()); + encodeDataPair(data, "server", Bukkit.getVersion()); + encodeDataPair(data, "players", Integer.toString(Bukkit.getServer().getOnlinePlayers().length)); + encodeDataPair(data, "revision", String.valueOf(REVISION)); + + // If we're pinging, append it + if (isPing) + { + encodeDataPair(data, "ping", "true"); + } + + // Acquire a lock on the graphs, which lets us make the assumption we also lock everything + // inside of the graph (e.g plotters) + synchronized (graphs) + { + final Iterator iter = graphs.iterator(); + + while (iter.hasNext()) + { + final Graph graph = iter.next(); + + // Because we have a lock on the graphs set already, it is reasonable to assume + // that our lock transcends down to the individual plotters in the graphs also. + // Because our methods are private, no one but us can reasonably access this list + // without reflection so this is a safe assumption without adding more code. + for (Plotter plotter : graph.getPlotters()) + { + // The key name to send to the metrics server + // The format is C-GRAPHNAME-PLOTTERNAME where separator - is defined at the top + // Legacy (R4) submitters use the format Custom%s, or CustomPLOTTERNAME + final String key = String.format("C%s%s%s%s", CUSTOM_DATA_SEPARATOR, graph.getName(), CUSTOM_DATA_SEPARATOR, plotter.getColumnName()); + + // The value to send, which for the foreseeable future is just the string + // value of plotter.getValue() + final String value = Integer.toString(plotter.getValue()); + + // Add it to the http post data :) + encodeDataPair(data, key, value); + } + } + } + + // Create the url + final URL url = new URL(BASE_URL + String.format(REPORT_URL, description.getName())); + + // Connect to the website + URLConnection connection; + + // Mineshafter creates a socks proxy, so we can safely bypass it + // It does not reroute POST requests so we need to go around it + if (isMineshafterPresent()) + { + connection = url.openConnection(Proxy.NO_PROXY); + } + else + { + connection = url.openConnection(); + } + + connection.setDoOutput(true); + + // Write the data + final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); + writer.write(data.toString()); + writer.flush(); + + // Now read the response + final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); + final String response = reader.readLine(); + + // close resources + writer.close(); + reader.close(); + + if (response == null || response.startsWith("ERR")) + { + throw new IOException(response); //Throw the exception + } + else + { + // Is this the first update this hour? + if (response.contains("OK This is your first update this hour")) + { + synchronized (graphs) + { + final Iterator iter = graphs.iterator(); + + while (iter.hasNext()) + { + final Graph graph = iter.next(); + + for (Plotter plotter : graph.getPlotters()) + { + plotter.reset(); + } + } + } + } + } + //if (response.startsWith("OK")) - We should get "OK" followed by an optional description if everything goes right + } + + /** + * Check if mineshafter is present. If it is, we need to bypass it to send POST requests + * + * @return + */ + private boolean isMineshafterPresent() + { + try + { + Class.forName("mineshafter.MineServer"); + return true; + } + catch (Exception e) + { + return false; + } + } + + /** + *

Encode a key/value data pair to be used in a HTTP post request. This INCLUDES a & so the first key/value pair + * MUST be included manually, e.g:

+ * + * StringBuffer data = new StringBuffer(); + * data.append(encode("guid")).append('=').append(encode(guid)); + * encodeDataPair(data, "version", description.getVersion()); + * + * + * @param buffer + * @param key + * @param value + * @return + */ + private static void encodeDataPair(final StringBuilder buffer, final String key, final String value) throws UnsupportedEncodingException + { + buffer.append('&').append(encode(key)).append('=').append(encode(value)); + } + + /** + * Encode text as UTF-8 + * + * @param text + * @return + */ + private static String encode(final String text) throws UnsupportedEncodingException + { + return URLEncoder.encode(text, "UTF-8"); + } + + + /** + * Represents a custom graph on the website + */ + public static class Graph + { + /** + * The graph's name, alphanumeric and spaces only :) If it does not comply to the above when submitted, it is + * rejected + */ + private final String name; + /** + * The set of plotters that are contained within this graph + */ + private final Set plotters = new LinkedHashSet(); + + private Graph(final String name) + { + this.name = name; + } + + /** + * Gets the graph's name + * + * @return + */ + public String getName() + { + return name; + } + + /** + * Add a plotter to the graph, which will be used to plot entries + * + * @param plotter + */ + public void addPlotter(final Plotter plotter) + { + plotters.add(plotter); + } + + /** + * Remove a plotter from the graph + * + * @param plotter + */ + public void removePlotter(final Plotter plotter) + { + plotters.remove(plotter); + } + + /** + * Gets an unmodifiable set of the plotter objects in the graph + * + * @return + */ + public Set getPlotters() + { + return Collections.unmodifiableSet(plotters); + } + + @Override + public int hashCode() + { + return name.hashCode(); + } + + @Override + public boolean equals(final Object object) + { + if (!(object instanceof Graph)) + { + return false; + } + + final Graph graph = (Graph)object; + return graph.name.equals(name); + } + } + + + /** + * Interface used to collect custom data for a plugin + */ + public static abstract class Plotter + { + /** + * The plot's name + */ + private final String name; + + /** + * Construct a plotter with the default plot name + */ + public Plotter() + { + this("Default"); + } + + /** + * Construct a plotter with a specific plot name + * + * @param name + */ + public Plotter(final String name) + { + this.name = name; + } + + /** + * Get the current value for the plotted point + * + * @return + */ + public abstract int getValue(); + + /** + * Get the column name for the plotted point + * + * @return the plotted point's column name + */ + public String getColumnName() + { + return name; + } + + /** + * Called after the website graphs have been updated + */ + public void reset() + { + } + + @Override + public int hashCode() + { + return getColumnName().hashCode() + getValue(); + } + + @Override + public boolean equals(final Object object) + { + if (!(object instanceof Plotter)) + { + return false; + } + + final Plotter plotter = (Plotter)object; + return plotter.name.equals(name) && plotter.getValue() == getValue(); + } + } +} \ No newline at end of file diff --git a/Essentials/src/net/ess3/metrics/MetricsListener.java b/Essentials/src/net/ess3/metrics/MetricsListener.java new file mode 100644 index 000000000..1db463a46 --- /dev/null +++ b/Essentials/src/net/ess3/metrics/MetricsListener.java @@ -0,0 +1,37 @@ +package net.ess3.metrics; + +import net.ess3.api.IEssentials; +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; + + +public class MetricsListener implements Listener +{ + private final transient Server server; + private final transient IEssentials ess; + private final transient MetricsStarter starter; + + public MetricsListener(final IEssentials parent, final MetricsStarter starter) + { + this.ess = parent; + this.server = parent.getServer(); + this.starter = starter; + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerJoin(final PlayerJoinEvent event) + { + /*final IUser player = ess.getUser(event.getPlayer()); + if (ess.getSettings().isMetricsEnabled() == false && (player.isAuthorized("essentials.essentials") || player.isAuthorized("bukkit.broadcast.admin"))) + { + player.sendMessage("PluginMetrics collects minimal statistic data, starting in about 5 minutes."); + player.sendMessage("To opt out, run /essentials opt-out"); + ess.getLogger().log(Level.INFO, "[Metrics] Admin join - Starting 5 minute opt-out period."); + ess.getSettings().setMetricsEnabled(true); + ess.getScheduler().scheduleAsyncDelayedTask(ess, starter, 5 * 1200); + }*/ + } +} diff --git a/Essentials/src/net/ess3/metrics/MetricsStarter.java b/Essentials/src/net/ess3/metrics/MetricsStarter.java new file mode 100644 index 000000000..46b1651aa --- /dev/null +++ b/Essentials/src/net/ess3/metrics/MetricsStarter.java @@ -0,0 +1,237 @@ +package net.ess3.metrics; + +import net.ess3.api.IEssentials; +import net.ess3.api.ISettings; +import net.ess3.economy.register.Method; +import net.ess3.economy.register.methods.VaultEco; +import net.ess3.metrics.Metrics.Graph; +import net.ess3.metrics.Metrics.Plotter; +//import com.earth2me.essentials.register.payment.Method; +//import com.earth2me.essentials.register.payment.methods.VaultEco; +import com.nijikokun.bukkit.Permissions.Permissions; +import java.util.Locale; +import java.util.logging.Level; + +import lombok.Cleanup; + + +public class MetricsStarter implements Runnable +{ + private final IEssentials ess; + private transient Boolean start; + + + private enum Modules + { + Essentials, + EssentialsAntiCheat, + EssentialsChat, + EssentialsSpawn, + EssentialsProtect, + EssentialsGeoIP, + EssentialsXMPP + }; + + public MetricsStarter(final IEssentials plugin) + { + ess = plugin; + /* + try + { + + final Metrics metrics = new Metrics(ess); + ess.setMetrics(metrics); + + @Cleanup + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (!metrics.isOptOut()) + { + if (settings.getData().getGeneral().isMetricsEnabled()) + { + start = true; + } + else + { + ess.getLogger().info("This plugin collects minimal statistic data and sends it to http://metrics.essentials3.net."); + ess.getLogger().info("You can opt out by running /essentials opt-out"); + ess.getLogger().info("This will start 5 minutes after the first admin/op joins."); + start = false; + } + return; + } + } + catch (Exception ex) + { + metricsError(ex); + }*/ + } + + @Override + public void run() + { + try + { + final Metrics metrics = ess.getMetrics(); + + final Graph moduleGraph = metrics.createGraph("Modules Used"); + for (Modules module : Modules.values()) + { + final String moduleName = module.toString(); + if (ess.getServer().getPluginManager().isPluginEnabled(moduleName)) + { + moduleGraph.addPlotter(new SimplePlotter(moduleName)); + } + } + + final Graph localeGraph = metrics.createGraph("Locale"); + localeGraph.addPlotter(new SimplePlotter(ess.getI18n().getCurrentLocale().getDisplayLanguage(Locale.ENGLISH))); + + final Graph featureGraph = metrics.createGraph("Features"); + featureGraph.addPlotter(new Plotter("Unique Accounts") + { + @Override + public int getValue() + { + return ess.getUserMap().getUniqueUsers(); + } + }); + featureGraph.addPlotter(new Plotter("Jails") + { + @Override + public int getValue() + { + return ess.getJails().getCount(); + } + }); + featureGraph.addPlotter(new Plotter("Kits") + { + @Override + public int getValue() + { + int size = 0; + try + { + size = ess.getKits().getList().size(); + } + catch (Exception ex) + { + } + return size; + + } + }); + featureGraph.addPlotter(new Plotter("Warps") + { + @Override + public int getValue() + { + return ess.getWarps().getList().size(); + } + }); + + final Graph enabledGraph = metrics.createGraph("EnabledFeatures"); + enabledGraph.addPlotter(new SimplePlotter("Total")); + @Cleanup + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + final String BKcommand = settings.getData().getGeneral().getBackup().getCommand();; + if (BKcommand != null && !"".equals(BKcommand)) + { + enabledGraph.addPlotter(new SimplePlotter("Backup")); + } + if (ess.getJails().getCount() > 0) + { + enabledGraph.addPlotter(new SimplePlotter("Jails")); + } + if (ess.getKits().getList().size() > 0) + { + enabledGraph.addPlotter(new SimplePlotter("Kits")); + } + if (ess.getWarps().getList().size() > 0) + { + enabledGraph.addPlotter(new SimplePlotter("Warps")); + } + //todo - enable once settings are in + /* + if (!ess.getSettings().areSignsDisabled()) + { + enabledGraph.addPlotter(new SimplePlotter("Signs")); + } + if (ess.getSettings().getAutoAfk() > 0) + { + enabledGraph.addPlotter(new SimplePlotter("AutoAFK")); + } + if (ess.getSettings().changeDisplayName()) + { + enabledGraph.addPlotter(new SimplePlotter("DisplayName")); + } + if (ess.getSettings().getChatRadius() >= 1) + { + enabledGraph.addPlotter(new SimplePlotter("LocalChat")); + } + */ + final Graph depGraph = metrics.createGraph("Dependencies"); + final Method method = ess.getPaymentMethod().getMethod(); + if (method != null) + { + String version; + if (method instanceof VaultEco) + { + version = ((VaultEco)method).getEconomy(); + } + else + { + version = method.getVersion(); + final int dashPosition = version.indexOf('-'); + if (dashPosition > 0) + { + version = version.substring(0, dashPosition); + } + } + depGraph.addPlotter(new SimplePlotter(method.getName() + " " + version)); + } + //todo - verify + depGraph.addPlotter(new SimplePlotter(Permissions.getInstance().getName())); + + metrics.start(); + + } + catch (Exception ex) + { + metricsError(ex); + } + } + + public void metricsError(final Exception ex) + { + if (ess.getSettings().isDebug()) + { + ess.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage(), ex); + } + else + { + ess.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); + } + } + + public Boolean getStart() + { + return start; + } + + + private class SimplePlotter extends Plotter + { + public SimplePlotter(final String name) + { + super(name); + } + + @Override + public int getValue() + { + return 1; + } + } +} \ No newline at end of file diff --git a/Essentials/src/net/ess3/permissions/AbstractSuperpermsPermission.java b/Essentials/src/net/ess3/permissions/AbstractSuperpermsPermission.java new file mode 100644 index 000000000..ca6c33cfa --- /dev/null +++ b/Essentials/src/net/ess3/permissions/AbstractSuperpermsPermission.java @@ -0,0 +1,42 @@ +package net.ess3.permissions; + +import net.ess3.utils.Util; +import net.ess3.api.IPermission; +import org.bukkit.command.CommandSender; +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionDefault; + + +public abstract class AbstractSuperpermsPermission implements IPermission +{ + protected Permission bukkitPerm; + + @Override + public Permission getBukkitPermission() + { + if (bukkitPerm != null) + { + return bukkitPerm; + } + else + { + return Util.registerPermission(getPermission(), getPermissionDefault()); + } + } + + /** + * PermissionDefault is OP, if the method is not overwritten. + * @return + */ + @Override + public PermissionDefault getPermissionDefault() + { + return PermissionDefault.OP; + } + + @Override + public boolean isAuthorized(final CommandSender sender) + { + return sender.hasPermission(getBukkitPermission()); + } +} diff --git a/Essentials/src/net/ess3/permissions/BasePermission.java b/Essentials/src/net/ess3/permissions/BasePermission.java new file mode 100644 index 000000000..71b18c034 --- /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 getPermission() + { + 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..231acb8b7 --- /dev/null +++ b/Essentials/src/net/ess3/permissions/GivePermissions.java @@ -0,0 +1,30 @@ +package net.ess3.permissions; + +import net.ess3.api.IPermission; +import java.util.EnumMap; +import java.util.Locale; +import java.util.Map; +import org.bukkit.Material; +import org.bukkit.permissions.PermissionDefault; + +public class GivePermissions { + private static Map permissions = new EnumMap(Material.class); + + 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 PermissionDefault getPermissionDefault() + { + return PermissionDefault.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..53ff48ae6 --- /dev/null +++ b/Essentials/src/net/ess3/permissions/ItemPermissions.java @@ -0,0 +1,32 @@ +package net.ess3.permissions; + +import net.ess3.api.IPermission; +import java.util.EnumMap; +import java.util.Locale; +import java.util.Map; +import org.bukkit.Material; +import org.bukkit.permissions.PermissionDefault; + + +public class ItemPermissions +{ + private static Map permissions = new EnumMap(Material.class); + + 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 PermissionDefault getPermissionDefault() + { + return PermissionDefault.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..c01768fa6 --- /dev/null +++ b/Essentials/src/net/ess3/permissions/KitPermissions.java @@ -0,0 +1,31 @@ +package net.ess3.permissions; + +import net.ess3.api.IPermission; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import org.bukkit.permissions.PermissionDefault; + + +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 PermissionDefault getPermissionDefault() + { + return PermissionDefault.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..3d2ac9160 --- /dev/null +++ b/Essentials/src/net/ess3/permissions/Permissions.java @@ -0,0 +1,138 @@ +package net.ess3.permissions; + +import net.ess3.utils.Util; +import net.ess3.api.IPermission; +import java.util.Locale; +import org.bukkit.command.CommandSender; +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionDefault; + + +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_IGNORE_EXEMPT, + CHAT_SPY, + CLEARINVENTORY_OTHERS, + DELHOME_OTHERS, + ECO_LOAN(PermissionDefault.FALSE), + EXP_GIVE, + EXP_GIVE_OTHERS, + EXP_SET, + EXP_SET_OTHERS, + EXP_OTHERS, + FEED_OTHERS, + FLY_OTHERS, + GAMEMODE_OTHERS, + GEOIP_HIDE(PermissionDefault.FALSE), + GEOIP_SHOW(PermissionDefault.TRUE), + GETPOS_OTHERS, + GOD_OTHERS, + HEAL_COOLDOWN_BYPASS, + HEAL_OTHERS, + HELPOP_RECEIVE, + HOME_OTHERS, + JAIL_EXEMPT, + JOINFULLSERVER, + INVSEE_MODIFY, + INVSEE_PREVENT_MODIFY, + KEEPXP, + 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(PermissionDefault.FALSE), + POWERTOOL_APPEND, + PTIME_OTHERS, + PVPDELAY_EXEMPT, + REPAIR_ARMOR, + REPAIR_ENCHANTED, + SEEN_BANREASON, + SEEN_EXTRA, + SETHOME_MULTIPLE, + SETHOME_OTHERS, + SLEEPINGIGNORED, + SPAWN_OTHERS, + SUDO_EXEMPT, + TELEPORT_COOLDOWN_BYPASS, + TELEPORT_HIDDEN, + TELEPORT_OTHERS, + TELEPORT_TIMER_BYPASS, + TEMPBAN_EXEMPT, + TEMPBAN_OFFLINE, + TIME_SET, + TOGGLEJAIL_OFFLINE, + TPA, + TPAALL, + TPAHERE, + TPOHERE, + UNLIMITED_OTHERS, + WARP_LIST(PermissionDefault.TRUE), + WARP_OTHERS, + VANISH_SEE_OTHERS; + private static final String base = "essentials."; + private final String permission; + private final PermissionDefault defaultPerm; + private transient Permission bukkitPerm = null; + + private Permissions() + { + this(PermissionDefault.OP); + } + + private Permissions(final PermissionDefault defaultPerm) + { + permission = base + toString().toLowerCase(Locale.ENGLISH).replace('_', '.'); + this.defaultPerm = defaultPerm; + } + + @Override + public String getPermission() + { + return permission; + } + + @Override + public Permission getBukkitPermission() + { + if (bukkitPerm != null) + { + return bukkitPerm; + } + else + { + return Util.registerPermission(getPermission(), getPermissionDefault()); + } + } + + @Override + public PermissionDefault getPermissionDefault() + { + return this.defaultPerm; + } + + @Override + public boolean isAuthorized(CommandSender sender) + { + return sender.hasPermission(getBukkitPermission()); + } +} 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..02d6ec9b0 --- /dev/null +++ b/Essentials/src/net/ess3/permissions/UnlimitedItemPermissions.java @@ -0,0 +1,23 @@ +package net.ess3.permissions; + +import net.ess3.api.IPermission; +import java.util.EnumMap; +import java.util.Locale; +import java.util.Map; +import org.bukkit.Material; + +public class UnlimitedItemPermissions +{ + private static Map permissions = new EnumMap(Material.class); + + 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..f8d146b61 --- /dev/null +++ b/Essentials/src/net/ess3/permissions/WarpPermissions.java @@ -0,0 +1,31 @@ +package net.ess3.permissions; + +import net.ess3.api.IPermission; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import org.bukkit.permissions.PermissionDefault; + + +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 PermissionDefault getPermissionDefault() + { + return PermissionDefault.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..8c07555e3 --- /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.replaceFormat(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..85d5743b5 --- /dev/null +++ b/Essentials/src/net/ess3/ranks/RanksStorage.java @@ -0,0 +1,207 @@ +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 +{ + + @Override + public void finishRead() + { + + } + + @Override + public void finishWrite() + { + + } + public RanksStorage(final IEssentials ess) + { + super(ess, Ranks.class); + onReload(); + } + + @Override + public File getStorageFile() + { + return new File(ess.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.replaceFormat(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..30f526686 --- /dev/null +++ b/Essentials/src/net/ess3/ranks/VaultGroups.java @@ -0,0 +1,124 @@ +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; +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) + { + RegisteredServiceProvider rsp = ess.getServer().getServicesManager().getRegistration(Chat.class); + Chat chat = rsp.getProvider(); + return chat.getPlayerInfoDouble(player.getBase(), "healcooldown", 0); + } + + @Override + public double getTeleportCooldown(IUser player) + { + RegisteredServiceProvider rsp = ess.getServer().getServicesManager().getRegistration(Chat.class); + Chat chat = rsp.getProvider(); + return chat.getPlayerInfoDouble(player.getBase(), "teleportcooldown", 0); + } + + @Override + public double getTeleportDelay(IUser player) + { + RegisteredServiceProvider rsp = ess.getServer().getServicesManager().getRegistration(Chat.class); + Chat chat = rsp.getProvider(); + return chat.getPlayerInfoDouble(player.getBase(), "teleportdelay", 0); + } + + @Override + public String getPrefix(IUser player) + { + RegisteredServiceProvider rsp = ess.getServer().getServicesManager().getRegistration(Chat.class); + Chat chat = rsp.getProvider(); + return chat.getPlayerPrefix(player.getBase()); + } + + @Override + public String getSuffix(IUser player) + { + RegisteredServiceProvider rsp = ess.getServer().getServicesManager().getRegistration(Chat.class); + Chat chat = rsp.getProvider(); + return chat.getPlayerSuffix(player.getBase()); + } + + @Override + public int getHomeLimit(IUser player) + { + RegisteredServiceProvider rsp = ess.getServer().getServicesManager().getRegistration(Chat.class); + Chat chat = rsp.getProvider(); + return chat.getPlayerInfoInteger(player.getBase(), "homes", 0); + } + + @Override + public MessageFormat getChatFormat(final IUser player) + { + String format = getRawChatFormat(player); + format = Util.replaceFormat(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) + { + RegisteredServiceProvider rsp = ess.getServer().getServicesManager().getRegistration(Chat.class); + Chat chat = rsp.getProvider(); + 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) + { + RegisteredServiceProvider rsp = ess.getServer().getServicesManager().getRegistration(Chat.class); + Chat chat = rsp.getProvider(); + return chat.getPrimaryGroup(player.getBase()); + } + + @Override + public boolean inGroup(IUser player, String groupname) + { + RegisteredServiceProvider rsp = ess.getServer().getServicesManager().getRegistration(Chat.class); + Chat chat = rsp.getProvider(); + 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..831f2c869 --- /dev/null +++ b/Essentials/src/net/ess3/settings/General.java @@ -0,0 +1,106 @@ +package net.ess3.settings; + +import net.ess3.storage.Comment; +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 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; + @Comment( + + { + "The delay, in seconds, a player can't be attacked by other players after he has been teleported by a command", + "This will also prevent that the player can attack other players" + }) + private long teleportInvulnerability = 0; + + public long getTeleportInvulnerability() + { + return teleportInvulnerability * 1000; + } + + @Comment( + { + "Set to true to enable per-world permissions for teleporting between worlds with essentials commands", + "This applies to /world, /back, /tp[a|o][here|all], but not warps.", + "Give someone permission to teleport to a world with essentials.world." + }) + private boolean worldTeleportPermissions = false; + private boolean worldHomePermissions = false; + + + @Comment("Prevent creatures spawning") + private Map creatureSpawn = new HashMap(); + + public boolean getPreventSpawn(String creatureName) + { + if (creatureSpawn == null) + { + return false; + } + return creatureSpawn.get(creatureName); + } + + @Comment("Delay to wait before people can cause attack damage after logging in ") + private long loginAttackDelay = 0; + + public long getLoginAttackDelay() + { + return loginAttackDelay * 1000; + } +} diff --git a/Essentials/src/net/ess3/settings/Jails.java b/Essentials/src/net/ess3/settings/Jails.java new file mode 100644 index 000000000..a6e1f5c82 --- /dev/null +++ b/Essentials/src/net/ess3/settings/Jails.java @@ -0,0 +1,18 @@ +package net.ess3.settings; + +import net.ess3.storage.Location; +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(Location.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..0ffff6759 --- /dev/null +++ b/Essentials/src/net/ess3/settings/Kit.java @@ -0,0 +1,20 @@ +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..b0c0a9121 --- /dev/null +++ b/Essentials/src/net/ess3/settings/SettingsHolder.java @@ -0,0 +1,76 @@ +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 +{ + + @Override + public void finishRead() + { + + } + + @Override + public void finishWrite() + { + + } + 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.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..15ee73fe6 --- /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.Location; +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(Location.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..fd545705d --- /dev/null +++ b/Essentials/src/net/ess3/settings/SpawnsHolder.java @@ -0,0 +1,320 @@ +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.Location.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 +{ + + @Override + public void finishRead() + { + + } + + @Override + public void finishWrite() + { + + } + + public SpawnsHolder(final IEssentials ess) + { + super(ess, Spawns.class); + onReload(); + registerListeners(); + } + + @Override + public File getStorageFile() + { + return new File(ess.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.Location(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).getBukkitLocation(); + } + 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.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..7b5a2f597 --- /dev/null +++ b/Essentials/src/net/ess3/settings/Warp.java @@ -0,0 +1,14 @@ +package net.ess3.settings; + +import net.ess3.storage.Location; +import net.ess3.storage.StorageObject; +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Data +@EqualsAndHashCode(callSuper = false) +public class Warp implements StorageObject +{ + private String name; + private Location 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..eaef24b6d --- /dev/null +++ b/Essentials/src/net/ess3/settings/WarpHolder.java @@ -0,0 +1,48 @@ +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 +{ + + @Override + public void finishRead() + { + + } + + @Override + public void finishWrite() + { + + } + + 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..4b667c25e --- /dev/null +++ b/Essentials/src/net/ess3/settings/WorldOptions.java @@ -0,0 +1,16 @@ +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..089477b25 --- /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 +{ + private boolean showCities = false; + private boolean downloadIfMissing = true; + private String downloadUrlCity = "http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz"; + private 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..cae4a4df0 --- /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(); + private boolean showOnWhois = true; + private 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..b2c571f1a --- /dev/null +++ b/Essentials/src/net/ess3/settings/protect/Prevent.java @@ -0,0 +1,51 @@ +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.EntityType; + + +@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(EntityType.class) + @MapValueType(Boolean.class) + private Map spawn = new HashMap(); + + public Prevent() + { + spawn.put(EntityType.PIG, false); + pistonPush.add(Material.GLASS); + } +} \ 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..ab5a061fd --- /dev/null +++ b/Essentials/src/net/ess3/settings/protect/Protect.java @@ -0,0 +1,52 @@ +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(); + + public Protect() + { + alertOnPlacement.add(Material.LAVA); + alertOnUse.add(Material.LAVA_BUCKET); + alertOnBreak.add(Material.GLASS); + } +} 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..d87f421f2 --- /dev/null +++ b/Essentials/src/net/ess3/storage/AbstractDelayedYamlFileReader.java @@ -0,0 +1,100 @@ +package net.ess3.storage; + +import net.ess3.Essentials; +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; + protected final transient IEssentials plugin; + private final transient ReentrantLock lock = new ReentrantLock(); + + public AbstractDelayedYamlFileReader(final IEssentials ess, final Class clazz) + { + this.clazz = clazz; + this.plugin = ess; + } + + public void schedule(boolean instant) + { + if (instant || ((Essentials)plugin).testing) + { + run(); + } + else + { + plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, this); + } + } + + public abstract File onStart() throws IOException; + + @Override + public void run() + { + File file = null; + lock.lock(); + try + { + file = onStart(); + try + { + final FileReader reader = new FileReader(file); + try + { + final T object = new YamlStorageReader(reader, plugin).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) + { + onException(ex); + if (plugin.getSettings() == null || plugin.getSettings().isDebug()) + { + Bukkit.getLogger().log(Level.INFO, "File not found: " + file.toString()); + } + } + 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..19f40cd68 --- /dev/null +++ b/Essentials/src/net/ess3/storage/AbstractDelayedYamlFileWriter.java @@ -0,0 +1,85 @@ +package net.ess3.storage; + +import net.ess3.Essentials; +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; +import org.bukkit.plugin.Plugin; + + +public abstract class AbstractDelayedYamlFileWriter implements Runnable +{ + private final transient Plugin plugin; + private final transient ReentrantLock lock = new ReentrantLock(); + + public AbstractDelayedYamlFileWriter(final IEssentials ess) + { + this.plugin = ess; + } + + public void schedule() + { + if (((Essentials)plugin).testing) + { + run(); + } + else + { + plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, 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..9b7f25827 --- /dev/null +++ b/Essentials/src/net/ess3/storage/AsyncStorageObjectHolder.java @@ -0,0 +1,191 @@ +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 void finishRead(); + + public abstract void finishWrite(); + + 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(); + finishWrite(); + } + } + + + 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..aae975d27 --- /dev/null +++ b/Essentials/src/net/ess3/storage/BukkitConstructor.java @@ -0,0 +1,442 @@ +package net.ess3.storage; + +import net.ess3.Essentials; +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.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemStack; +import org.bukkit.material.MaterialData; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.java.JavaPluginLoader; +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 Plugin plugin; + + public BukkitConstructor(final Class clazz, final Plugin 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.getMaterial(typeId); + } + else + { + mat = Material.matchMaterial(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(Location.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 Location(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 (plugin == null || (plugin instanceof Essentials && ((Essentials)plugin).testing)) + { + clazz = super.getClassForNode(node); + } + else + { + final JavaPluginLoader jpl = (JavaPluginLoader)plugin.getPluginLoader(); + clazz = jpl.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/Location.java b/Essentials/src/net/ess3/storage/Location.java new file mode 100644 index 000000000..06210504b --- /dev/null +++ b/Essentials/src/net/ess3/storage/Location.java @@ -0,0 +1,115 @@ +package net.ess3.storage; + +import java.lang.ref.WeakReference; +import java.util.UUID; +import org.bukkit.Bukkit; +import org.bukkit.World; + + +public class Location +{ + 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 Location(org.bukkit.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 Location(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 Location(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 org.bukkit.Location getBukkitLocation() throws WorldNotLoadedException + { + + org.bukkit.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 = new org.bukkit.Location(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/ManagedFile.java b/Essentials/src/net/ess3/storage/ManagedFile.java new file mode 100644 index 000000000..216e21f17 --- /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.getDataFolder(), filename); + + if (file.exists()) + { + try + { + if (checkForVersion(file, ess.getDescription().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..d8bf49d9c --- /dev/null +++ b/Essentials/src/net/ess3/storage/StorageObjectMap.java @@ -0,0 +1,138 @@ +package net.ess3.storage; + +import net.ess3.utils.Util; +import net.ess3.api.IEssentials; +import net.ess3.api.InvalidNameException; +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; +import org.bukkit.Bukkit; + + +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.getDataFolder(), folderName); + if (!folder.exists()) + { + folder.mkdirs(); + } + loadAllObjectsAsync(); + } + + private void loadAllObjectsAsync() + { + ess.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) + { + Bukkit.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/YamlStorageReader.java b/Essentials/src/net/ess3/storage/YamlStorageReader.java new file mode 100644 index 000000000..957902ee6 --- /dev/null +++ b/Essentials/src/net/ess3/storage/YamlStorageReader.java @@ -0,0 +1,120 @@ +package net.ess3.storage; + +import java.io.Reader; +import java.lang.reflect.Field; +import java.util.*; +import java.util.concurrent.locks.ReentrantLock; +import org.bukkit.plugin.Plugin; +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 Plugin plugin; + + public YamlStorageReader(final Reader reader, final Plugin 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..66c9dc852 --- /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 Location) + { + writeLocation((Location)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 Location) + { + writeLocation((Location)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 Location) + { + writeLocation((Location)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 Location 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..dc1ae0979 --- /dev/null +++ b/Essentials/src/net/ess3/user/IOfflinePlayer.java @@ -0,0 +1,20 @@ +package net.ess3.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); + + void setName(final String name); +} \ 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..60756957c --- /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/User.java b/Essentials/src/net/ess3/user/User.java new file mode 100644 index 000000000..54f16f1cf --- /dev/null +++ b/Essentials/src/net/ess3/user/User.java @@ -0,0 +1,778 @@ +package net.ess3.user; + +import net.ess3.Console; +import static net.ess3.I18n._; +import net.ess3.Teleport; +import net.ess3.api.*; +import net.ess3.craftbukkit.InventoryWorkaround; +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 java.util.logging.Logger; +import lombok.Cleanup; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + + +public class User extends UserBase implements IUser +{ + private CommandSender replyTo = null; + @Getter + private transient IUser teleportRequester; + @Getter + private transient boolean tpRequestHere; + @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; + @Getter + private transient boolean vanished; + @Getter + @Setter + private boolean invSee = false; + private transient Location afkPosition; + private static final Logger logger = Bukkit.getLogger(); + private AtomicBoolean gotMailInfo = new AtomicBoolean(false); + + public User(final Player base, final IEssentials ess) + { + super(base, ess); + teleport = new Teleport(this, ess); + } + + public User(final OfflinePlayer offlinePlayer, final IEssentials ess) + { + super(offlinePlayer, 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 finishRead() + { + } + + @Override + public void finishWrite() + { + } + + @Override + public void update(final Player base) + { + super.update(base); + } + + @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.Location(getLocation())); + } + finally + { + unlock(); + } + } + 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) + { + logger.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 (isOnlineUser() && 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 + @Override + 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 + @Override + 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(); + } + } + + @Override + 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(); + } + } + + @Override + 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 (Player player : ess.getServer().getOnlinePlayers()) + { + final IUser user = ess.getUser(player); + 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(); + } + } + + @Override + public Location getAfkPosition() + { + return afkPosition; + } + + @Override + 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 player, boolean here) + { + teleportRequestTime = System.currentTimeMillis(); + teleportRequester = player; + tpRequestHere = here; + } + + @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.getType() == Material.AIR) + { + 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 = InventoryWorkaround.addItem(getInventory(), true, oversizedStackSize, itemStack); + } + else + { + overfilled = InventoryWorkaround.addItem(getInventory(), 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; + } + + @Override + public void updateMoneyCache(double userMoney) + { + if (super.getMoney() != userMoney) + { + super.setMoney(userMoney); + } + } + + @Override + public boolean canAfford(double amount, boolean b) + { + return true; + } + private transient long teleportInvulnerabilityTimestamp = 0; + + public void enableInvulnerabilityAfterTeleport() + { + @Cleanup + final ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + + final long time = settings.getData().getGeneral().getTeleportInvulnerability(); + if (time > 0) + { + teleportInvulnerabilityTimestamp = System.currentTimeMillis() + time; + } + } + + @Override + public void resetInvulnerabilityAfterTeleport() + { + if (teleportInvulnerabilityTimestamp != 0 + && teleportInvulnerabilityTimestamp < System.currentTimeMillis()) + { + teleportInvulnerabilityTimestamp = 0; + } + } + + @Override + public boolean hasInvulnerabilityAfterTeleport() + { + return teleportInvulnerabilityTimestamp != 0 && teleportInvulnerabilityTimestamp >= System.currentTimeMillis(); + } + + @Override + public void setVanished(boolean set) + { + vanished = set; + if (set) + { + for (Player p : ess.getServer().getOnlinePlayers()) + { + if (!Permissions.VANISH_SEE_OTHERS.isAuthorized(ess.getUser(p))) + { + p.hidePlayer(getBase()); + } + } + setHidden(true); + ess.getVanishedPlayers().add(getName()); + } + else + { + for (Player p : ess.getServer().getOnlinePlayers()) + { + p.showPlayer(getBase()); + } + setHidden(false); + ess.getVanishedPlayers().remove(getName()); + } + } + + @Override + public void setName(String name) + { + //todo + //throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void toggleVanished() + { + final boolean set = !vanished; + this.setVanished(set); + } +} diff --git a/Essentials/src/net/ess3/user/UserBase.java b/Essentials/src/net/ess3/user/UserBase.java new file mode 100644 index 000000000..73c151b00 --- /dev/null +++ b/Essentials/src/net/ess3/user/UserBase.java @@ -0,0 +1,458 @@ +package net.ess3.user; + +import net.ess3.utils.Util; +import net.ess3.api.IEssentials; +import net.ess3.api.ISettings; +import net.ess3.api.IUser; +import net.ess3.api.InvalidNameException; +import net.ess3.permissions.Permissions; +import net.ess3.storage.AsyncStorageObjectHolder; +import net.ess3.storage.Location.WorldNotLoadedException; +import java.io.File; +import java.io.IOException; +import java.util.*; +import lombok.Cleanup; +import lombok.Delegate; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.serialization.ConfigurationSerializable; +import org.bukkit.entity.Entity; +import org.bukkit.entity.HumanEntity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.permissions.Permissible; +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.ServerOperator; + + +public abstract class UserBase extends AsyncStorageObjectHolder implements Player, IOfflineUser +{ + @Delegate(types = + { + Player.class, Entity.class, CommandSender.class, ServerOperator.class, + HumanEntity.class, ConfigurationSerializable.class, LivingEntity.class, + Permissible.class + }, excludes = + { + IOfflinePlayer.class + }) + protected Player base; + protected transient OfflinePlayer offlinePlayer; + + public UserBase(final Player base, final IEssentials ess) + { + super(ess, UserData.class); + this.base = base; + onReload(); + } + + public UserBase(final OfflinePlayer offlinePlayer, final IEssentials ess) + { + super(ess, UserData.class); + this.offlinePlayer = offlinePlayer; + 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 update(final OfflinePlayer offlinePlayer) + { + this.offlinePlayer = offlinePlayer; + } + + public void dispose() + { + this.offlinePlayer = Bukkit.getOfflinePlayer(base.getName()); + this.base = null; + } + + public boolean isOnlineUser() + { + return base != null; + } + + @Override + public String getName() + { + if (isOnlineUser()) + { + return base.getName(); + } + else + { + return offlinePlayer.getName(); + } + } + + @Override + public String getDisplayName() + { + if (isOnlineUser()) + { + return base.getDisplayName(); + } + else + { + return offlinePlayer.getName(); + } + } + + @Override + public Location getBedSpawnLocation() + { + return base.getBedSpawnLocation(); + } + + @Override + public void setBanned(boolean bln) + { + if (isOnlineUser()) + { + base.setBanned(bln); + } + else + { + offlinePlayer.setBanned(bln); + } + } + + @Override + public boolean hasPermission(Permission prmsn) + { + if (isOnlineUser()) + { + return base.hasPermission(prmsn); + } + else + { + return false; + } + } + + @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.Location(loc)); + } + finally + { + unlock(); + } + } + + public boolean toggleAfk() + { + acquireWriteLock(); + try + { + boolean ret = !getData().isAfk(); + getData().setAfk(ret); + return ret; + } + finally + { + unlock(); + } + } + + public void setGodModeEnabled(boolean set) + { + acquireWriteLock(); + try + { + getData().setGodmode(set); + } + finally + { + unlock(); + } + } + + public void setMuted(boolean mute) + { + acquireWriteLock(); + try + { + getData().setMuted(mute); + } + 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 IUser user) + { + acquireReadLock(); + try + { + return getData().getIgnore() == null ? false : getData().getIgnore().contains(user.getName().toLowerCase(Locale.ENGLISH)) && Permissions.CHAT_IGNORE_EXEMPT.isAuthorized(user); + } + finally + { + unlock(); + } + } + + public void setIgnoredPlayer(final IUser user, final boolean set) + { + acquireWriteLock(); + try + { + if (getData().getIgnore() == null) + { + getData().setIgnore(new HashSet()); + } + if (set) + { + getData().getIgnore().add(user.getName().toLowerCase(Locale.ENGLISH)); + } + else + { + getData().getIgnore().remove(user.getName().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.Location location : getData().getHomes().values()) + { + if (location.getWorldName().equals(loc.getWorld().getName())) + { + try + { + worldHomes.add(location.getBukkitLocation()); + } + 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..702fecf03 --- /dev/null +++ b/Essentials/src/net/ess3/user/UserData.java @@ -0,0 +1,109 @@ +package net.ess3.user; + +import net.ess3.storage.*; +import java.util.*; +import lombok.Data; +import lombok.EqualsAndHashCode; +import org.bukkit.Material; + + +@Data +@EqualsAndHashCode(callSuper = false) +public class UserData implements StorageObject +{ + public enum TimestampType + { + JAIL, MUTE, LASTHEAL, LASTTELEPORT, LOGIN, LOGOUT, KIT + } + private String nickname; + private Double money; + @MapValueType(Location.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 Location 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() + { + unlimited.add(Material.AIR); + unlimited.add(Material.ARROW); + unlimited.add(Material.APPLE); + powerTools.put(Material.DEAD_BUSH, Collections.singletonList("test")); + 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..a0e6aee44 --- /dev/null +++ b/Essentials/src/net/ess3/user/UserMap.java @@ -0,0 +1,97 @@ +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.storage.StorageObjectMap; +import java.io.File; +import java.util.Locale; +import java.util.Set; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + + +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; + } +} 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..bf7d95c23 --- /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); + String parsetime = desc.replaceAll("[^0-9]", ""); + + if (parsetime.length() > 4) + { + throw new NumberFormatException(); + } + + if (parsetime.length() == 4) + { + hours += Integer.parseInt(parsetime.substring(0, 2)); + minutes += Integer.parseInt(parsetime.substring(2, 4)); + } + else if (parsetime.length() == 3) + { + hours += Integer.parseInt(parsetime.substring(0, 1)); + minutes += Integer.parseInt(parsetime.substring(1, 3)); + } + else if (parsetime.length() == 2) + { + hours += Integer.parseInt(parsetime.substring(0, 2)); + } + else if (parsetime.length() == 1) + { + hours += Integer.parseInt(parsetime.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..8121f8ff8 --- /dev/null +++ b/Essentials/src/net/ess3/utils/Util.java @@ -0,0 +1,442 @@ +package net.ess3.utils; + +import static net.ess3.I18n._; +import net.ess3.api.IEssentials; +import net.ess3.api.ISettings; +import net.ess3.api.IUser; +import net.ess3.api.InvalidNameException; +import net.ess3.utils.gnu.inet.encoding.Punycode; +import net.ess3.utils.gnu.inet.encoding.PunycodeException; +import de.bananaco.bpermissions.imp.Permissions; +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 URL_PATTERN = Pattern.compile("((?:(?:https?)://)?[\\w-_\\.]{2,})\\.([a-z]{2,3}(?:/\\S+)?)"); + private static transient final Pattern VANILLA_PATTERN = Pattern.compile("\u00A7+[0-9A-FK-ORa-fk-or]"); + private static transient final Pattern REPLACE_PATTERN = Pattern.compile("&([0-9a-fk-or])"); + private static transient final Pattern VANILLA_COLOR_PATTERN = Pattern.compile("\u00A7+[0-9A-Fa-f]"); + private static transient final Pattern VANILLA_MAGIC_PATTERN = Pattern.compile("\u00A7+[Kk]"); + private static transient final Pattern VANILLA_FORMAT_PATTERN = Pattern.compile("\u00A7+[L-ORl-or]"); + private static transient final Pattern REPLACE_COLOR_PATTERN = Pattern.compile("&([0-9a-f])"); + private static transient final Pattern REPLACE_MAGIC_PATTERN = Pattern.compile("&(k)"); + private static transient final Pattern REPLACE_FORMAT_PATTERN = Pattern.compile("&([l-or])"); + + public static String stripFormat(final String input) + { + if (input == null) + { + return null; + } + return VANILLA_PATTERN.matcher(input).replaceAll(""); + } + + public static String replaceFormat(final String input) + { + if (input == null) + { + return null; + } + return REPLACE_PATTERN.matcher(input).replaceAll("\u00a7$1"); + } + + public static String blockURL(final String input) + { + if (input == null) + { + return null; + } + String text = URL_PATTERN.matcher(input).replaceAll("$1 $2"); + while (URL_PATTERN.matcher(text).find()) + { + text = URL_PATTERN.matcher(text).replaceAll("$1 $2"); + } + return text; + } + + public static String formatString(final IUser user, final String permBase, final String input) + { + if (input == null) + { + return null; + } + String message; + if (Permissions.hasPermission(user.getBase(), permBase + ".color")) + { + message = Util.replaceColor(input, REPLACE_COLOR_PATTERN); + } + else + { + message = Util.stripColor(input, VANILLA_COLOR_PATTERN); + } + if (Permissions.hasPermission(user.getBase(), permBase + ".magic")) + { + message = Util.replaceColor(message, REPLACE_MAGIC_PATTERN); + } + else + { + message = Util.stripColor(message, VANILLA_MAGIC_PATTERN); + } + if (Permissions.hasPermission(user.getBase(), permBase + ".format")) + { + message = Util.replaceColor(message, REPLACE_FORMAT_PATTERN); + } + else + { + message = Util.stripColor(message, VANILLA_FORMAT_PATTERN); + } + return message; + } + + public static String formatMessage(final IUser user, final String permBase, final String input) + { + if (input == null) + { + return null; + } + String message = formatString(user, permBase, input); + if (!Permissions.hasPermission(user.getBase(), permBase + ".url")) + { + message = Util.blockURL(message); + } + return message; + } + + public static String stripColor(final String input) + { + if (input == null) + { + return null; + } + + return VANILLA_COLOR_PATTERN.matcher(input).replaceAll(""); + } + + private static String stripColor(final String input, final Pattern pattern) + { + return pattern.matcher(input).replaceAll(""); + } + + private static String replaceColor(final String input, final Pattern pattern) + { + return 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..109cc3702 --- /dev/null +++ b/Essentials/src/net/ess3/utils/textreader/HelpInput.java @@ -0,0 +1,179 @@ +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; + final List newLines = new ArrayList(); + String pluginName = ""; + String pluginNameLow = ""; + if (!match.equalsIgnoreCase("")) + { + lines.add(_("helpMatching", match)); + } + + for (Plugin p : ess.getServer().getPluginManager().getPlugins()) + { + try + { + final List pluginLines = new ArrayList(); + final PluginDescriptionFile desc = p.getDescription(); + final Map> cmds = desc.getCommands(); + pluginName = p.getDescription().getName(); + pluginNameLow = pluginName.toLowerCase(Locale.ENGLISH); + if (pluginNameLow.equals(match)) + { + lines.clear(); + newLines.clear(); + lines.add(_("helpFrom", p.getDescription().getName())); + } + + for (Map.Entry> k : cmds.entrySet()) + { + try + { + if (!match.equalsIgnoreCase("") && (!pluginNameLow.contains(match)) && (!k.getKey().toLowerCase(Locale.ENGLISH).contains(match)) + && (!(k.getValue().get(DESCRIPTION) instanceof String + && ((String)k.getValue().get(DESCRIPTION)).toLowerCase(Locale.ENGLISH).contains(match)))) + { + continue; + } + + if (pluginNameLow.contains("essentials")) + { + final String node = "essentials." + k.getKey(); + if (!settings.getData().getCommands().isDisabled(k.getKey()) && user.hasPermission(node)) + { + pluginLines.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(pluginNameLow).isAuthorized(user)) + { + pluginLines.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) + { + pluginLines.add(_("helpLine", k.getKey(), value.get(DESCRIPTION))); + } + } + else if (permissions instanceof String && !"".equals(permissions)) + { + if (user.hasPermission(permissions.toString())) + { + pluginLines.add(_("helpLine", k.getKey(), value.get(DESCRIPTION))); + } + } + else + { + if (!settings.getData().getCommands().getHelp().isHidePermissionlessCommands()) + { + pluginLines.add(_("helpLine", k.getKey(), value.get(DESCRIPTION))); + } + } + } + } + } + catch (NullPointerException ex) + { + continue; + } + } + if (!pluginLines.isEmpty()) + { + newLines.addAll(pluginLines); + if (pluginNameLow.equals(match)) + { + break; + } + if (match.equalsIgnoreCase("")) + { + lines.add(_("helpPlugin", pluginName, pluginNameLow)); + } + } + } + catch (NullPointerException ex) + { + continue; + } + catch (Exception ex) + { + if (!reported) + { + logger.log(Level.WARNING, _("commandHelpFailedForPlugin", pluginNameLow), ex); + } + reported = true; + continue; + } + } + lines.addAll(newLines); + } + + @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..3ec331d7a --- /dev/null +++ b/Essentials/src/net/ess3/utils/textreader/KeywordReplacer.java @@ -0,0 +1,157 @@ +package net.ess3.utils.textreader; + +import net.ess3.utils.DescParseTickFormat; +import net.ess3.api.IEssentials; +import net.ess3.api.IUser; +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.World; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +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 instanceof Player) + { + @Cleanup + final IUser user = ess.getUser((Player)sender); + user.acquireReadLock(); + user.setDisplayNick(); + 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() == null || user.getLocation().getWorld() == null ? "" : user.getLocation().getWorld().getName(); + worldTime12 = DescParseTickFormat.format12(user.getWorld() == null ? 0 : user.getWorld().getTime()); + worldTime24 = DescParseTickFormat.format24(user.getWorld() == null ? 0 : user.getWorld().getTime()); + worldDate = DateFormat.getDateInstance(DateFormat.MEDIUM, ess.getI18n().getCurrentLocale()).format(DescParseTickFormat.ticksToDate(user.getWorld() == null ? 0 : user.getWorld().getFullTime())); + } + else + { + displayName = ipAddress = balance = mails = world = worldTime12 = worldTime24 = worldDate = ""; + } + + int playerHidden = 0; + for (Player p : ess.getServer().getOnlinePlayers()) + { + if (ess.getUser(p).isHidden()) + { + playerHidden++; + } + } + online = Integer.toString(ess.getServer().getOnlinePlayers().length - 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 (ess.getUser(p).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..20fecc255 --- /dev/null +++ b/Essentials/src/net/ess3/utils/textreader/TextInput.java @@ -0,0 +1,149 @@ +package net.ess3.utils.textreader; + +import net.ess3.utils.Util; +import net.ess3.api.IEssentials; +import net.ess3.api.IUser; +import net.ess3.api.InvalidNameException; +import java.io.*; +import java.lang.ref.SoftReference; +import java.util.*; +import java.util.logging.Level; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + + +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 instanceof Player) + { + try + { + final IUser user = ess.getUser((Player)sender); + file = new File(ess.getDataFolder(), filename + "_" + Util.sanitizeFileName(user.getName()) + ".txt"); + if (!file.exists()) + { + file = new File(ess.getDataFolder(), filename + "_" + Util.sanitizeFileName(ess.getRanks().getMainGroup(user)) + ".txt"); + } + } + catch (InvalidNameException ex) + { + Bukkit.getLogger().log(Level.WARNING, ex.getMessage(), ex); + } + } + if (file == null || !file.exists()) + { + file = new File(ess.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-fk]", ""), 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.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 + { + if(output != null) + output.close(); + if(input != null) + 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..18b662be5 --- /dev/null +++ b/Essentials/src/net/ess3/utils/textreader/TextPager.java @@ -0,0 +1,200 @@ +package net.ess3.utils.textreader; + +import net.ess3.I18n; +import static net.ess3.I18n._; +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) + { + StringBuilder content = new StringBuilder(); + final String[] title = commandName.split(" ", 2); + if (title.length > 1) + { + content.append(I18n.capitalCase(title[0])).append(": "); + content.append(title[1]); + } + else if (chapterPageStr != null) + { + content.append(I18n.capitalCase(commandName)).append(": "); + content.append(chapterPageStr); + } + else + { + content.append(I18n.capitalCase(commandName)); + } + sender.sendMessage(_("infoPages", page, pages, content)); + } + 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, I18n.capitalCase(commandName))); + } + 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/plugin.yml b/Essentials/src/plugin.yml index 0f203b705..76d930a5c 100644 --- a/Essentials/src/plugin.yml +++ b/Essentials/src/plugin.yml @@ -1,6 +1,6 @@ # This determines the command prefix when there are conflicts (/name:home, /name:help, etc.) name: Essentials-3 -main: com.earth2me.essentials.Essentials +main: net.ess3.Essentials # Note to developers: This next line cannot change, or the automatic versioning system will break. version: ${build.number} website: http://tiny.cc/EssentialsWiki diff --git a/Essentials/test/com/earth2me/essentials/EconomyTest.java b/Essentials/test/com/earth2me/essentials/EconomyTest.java deleted file mode 100644 index 44d388c3b..000000000 --- a/Essentials/test/com/earth2me/essentials/EconomyTest.java +++ /dev/null @@ -1,116 +0,0 @@ -package com.earth2me.essentials; - -import com.earth2me.essentials.api.NoLoanPermittedException; -import com.earth2me.essentials.api.UserDoesNotExistException; -import com.earth2me.essentials.user.User; -import java.io.IOException; -import junit.framework.TestCase; -import org.bukkit.World.Environment; -import org.bukkit.plugin.InvalidDescriptionException; -import org.junit.Test; - - -public class EconomyTest extends TestCase -{ - private final transient Essentials ess; - private final static String NPCNAME = "npc1"; - private final static String PLAYERNAME = "TestPlayer1"; - - public EconomyTest(final String testName) - { - super(testName); - ess = new Essentials(); - final FakeServer server = new FakeServer(); - server.createWorld("testWorld", Environment.NORMAL); - try - { - ess.setupForTesting(server); - } - catch (InvalidDescriptionException ex) - { - fail("InvalidDescriptionException"); - } - catch (IOException ex) - { - fail("IOException"); - } - server.addPlayer(new User(new FakeOfflinePlayer(PLAYERNAME), ess)); - } - - // only one big test, since we use static instances - @Test - public void testEconomy() - { - // test NPC - assertFalse("NPC does not exists", ess.getEconomy().playerExists(NPCNAME)); - assertTrue("Create NPC", ess.getEconomy().createNPC(NPCNAME)); - assertTrue("NPC exists", ess.getEconomy().playerExists(NPCNAME)); - assertNull("NPC can not be accessed", ess.getUser(NPCNAME)); - try - { - ess.getEconomy().removeNPC(NPCNAME); - } - catch (UserDoesNotExistException ex) - { - fail(ex.getMessage()); - } - assertFalse("NPC can be removed",ess.getEconomy().playerExists(NPCNAME)); - - //test Math - try - { - - assertTrue("Player exists", ess.getEconomy().playerExists(PLAYERNAME)); - ess.getEconomy().resetBalance(PLAYERNAME); - assertEquals("Player has no money", 0.0, ess.getEconomy().getMoney(PLAYERNAME)); - ess.getEconomy().setMoney(PLAYERNAME, 10.0); - assertEquals("Set money", 10.0, ess.getEconomy().getMoney(PLAYERNAME)); - } - catch (NoLoanPermittedException ex) - { - fail(ex.getMessage()); - } - catch (UserDoesNotExistException ex) - { - fail(ex.getMessage()); - } - - //test Format - assertEquals("Format $1000", "$1000", ess.getEconomy().format(1000.0)); - assertEquals("Format $10", "$10", ess.getEconomy().format(10.0)); - assertEquals("Format $10.10", "$10.10", ess.getEconomy().format(10.10)); - assertEquals("Format $10.10", "$10.10", ess.getEconomy().format(10.102)); - assertEquals("Format $10.11", "$10.11", ess.getEconomy().format(10.109)); - - - //test Exceptions - try - { - assertTrue("Player exists", ess.getEconomy().playerExists(PLAYERNAME)); - ess.getEconomy().resetBalance(PLAYERNAME); - assertEquals("Reset balance", 0.0, ess.getEconomy().getMoney(PLAYERNAME)); - ess.getEconomy().setMoney(PLAYERNAME, -5.0); - fail("Did not throw exception"); - } - catch (NoLoanPermittedException ex) - { - } - catch (UserDoesNotExistException ex) - { - fail(ex.getMessage()); - } - - try - { - ess.getEconomy().resetBalance("UnknownPlayer"); - fail("Did not throw exception"); - } - catch (NoLoanPermittedException ex) - { - fail(ex.getMessage()); - } - catch (UserDoesNotExistException ex) - { - } - } -} diff --git a/Essentials/test/com/earth2me/essentials/FakeOfflinePlayer.java b/Essentials/test/com/earth2me/essentials/FakeOfflinePlayer.java deleted file mode 100644 index 01dd470ca..000000000 --- a/Essentials/test/com/earth2me/essentials/FakeOfflinePlayer.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.earth2me.essentials; - -import java.util.Map; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.OfflinePlayer; -import org.bukkit.entity.Player; - - -public class FakeOfflinePlayer implements OfflinePlayer -{ - private final transient String name; - - public FakeOfflinePlayer(String name) - { - this.name = name; - } - - @Override - public boolean isOnline() - { - return false; - } - - @Override - public String getName() - { - return name; - } - - @Override - public boolean isBanned() - { - return false; - } - - @Override - public void setBanned(boolean bln) - { - } - - @Override - public boolean isWhitelisted() - { - return false; - } - - @Override - public void setWhitelisted(boolean bln) - { - } - - @Override - public Player getPlayer() - { - return Bukkit.getPlayerExact(name); - } - - @Override - public long getFirstPlayed() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public long getLastPlayed() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean hasPlayedBefore() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isOp() - { - return false; - } - - @Override - public void setOp(boolean bln) - { - } - - @Override - public Map serialize() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Location getBedSpawnLocation() - { - throw new UnsupportedOperationException("Not supported yet."); - } - -} diff --git a/Essentials/test/com/earth2me/essentials/FakeServer.java b/Essentials/test/com/earth2me/essentials/FakeServer.java deleted file mode 100644 index 552c0c419..000000000 --- a/Essentials/test/com/earth2me/essentials/FakeServer.java +++ /dev/null @@ -1,928 +0,0 @@ -package com.earth2me.essentials; - -import com.avaje.ebean.config.ServerConfig; -import java.io.File; -import java.util.*; -import java.util.concurrent.Callable; -import java.util.concurrent.Future; -import java.util.logging.Logger; -import org.bukkit.*; -import org.bukkit.World.Environment; -import org.bukkit.command.CommandSender; -import org.bukkit.command.ConsoleCommandSender; -import org.bukkit.command.PluginCommand; -import org.bukkit.entity.Player; -import org.bukkit.event.Event; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.inventory.InventoryType; -import org.bukkit.help.HelpMap; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.InventoryHolder; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.Recipe; -import org.bukkit.map.MapView; -import org.bukkit.permissions.Permissible; -import org.bukkit.permissions.Permission; -import org.bukkit.plugin.*; -import org.bukkit.plugin.messaging.Messenger; -import org.bukkit.scheduler.BukkitScheduler; -import org.bukkit.scheduler.BukkitTask; -import org.bukkit.scheduler.BukkitWorker; - - -public class FakeServer implements Server -{ - private List players = new ArrayList(); - private final List worlds = new ArrayList(); - - public FakeServer() - { - if (Bukkit.getServer() == null) - { - Bukkit.setServer(this); - } - } - - public String getName() - { - return "Essentials Fake Server"; - } - - public String getVersion() - { - return "1.0"; - } - - @Override - public Player[] getOnlinePlayers() - { - return players.toArray(new Player[0]); - } - - public void setOnlinePlayers(List players) - { - this.players = players; - } - - @Override - public int getMaxPlayers() - { - return 100; - } - - @Override - public int getPort() - { - return 25565; - } - - @Override - public String getIp() - { - return "127.0.0.1"; - } - - @Override - public String getServerName() - { - return "Test Server"; - } - - @Override - public String getServerId() - { - return "Test Server"; - } - - @Override - public int broadcastMessage(String string) - { - int i = 0; - for (Player player : players) - { - player.sendMessage(string); - i++; - } - return i; - } - - @Override - public String getUpdateFolder() - { - return "update"; - } - - @Override - public File getUpdateFolderFile() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Player getPlayer(String string) - { - for (Player player : players) - { - if (player.getName().equalsIgnoreCase(string)) - { - return player; - } - } - return null; - } - - @Override - public List matchPlayer(String string) - { - List matches = new ArrayList(); - for (Player player : players) - { - if (player.getName().substring(0, Math.min(player.getName().length(), string.length())).equalsIgnoreCase(string)) - { - matches.add(player); - } - } - return matches; - } - private PluginManager pManager = new PluginManager() - { - private Set permissions = new HashSet(); - - @Override - public void registerInterface(Class type) throws IllegalArgumentException - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Plugin getPlugin(String string) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Plugin[] getPlugins() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isPluginEnabled(String string) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isPluginEnabled(Plugin plugin) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Plugin loadPlugin(File file) throws InvalidPluginException, InvalidDescriptionException, UnknownDependencyException - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Plugin[] loadPlugins(File file) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void disablePlugins() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void clearPlugins() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void callEvent(Event event) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void registerEvents(Listener ll, Plugin plugin) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void registerEvent(Class type, Listener ll, EventPriority ep, EventExecutor ee, Plugin plugin) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void enablePlugin(Plugin plugin) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void disablePlugin(Plugin plugin) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Permission getPermission(String string) - { - for (Permission permission : permissions) - { - if (permission.getName().equals(string)) - { - return permission; - } - } - return null; - } - - @Override - public void addPermission(Permission prmsn) - { - permissions.add(prmsn); - } - - @Override - public void removePermission(Permission prmsn) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void removePermission(String string) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Set getDefaultPermissions(boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void recalculatePermissionDefaults(Permission prmsn) - { - } - - @Override - public void subscribeToPermission(String string, Permissible prmsbl) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void unsubscribeFromPermission(String string, Permissible prmsbl) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Set getPermissionSubscriptions(String string) - { - return Collections.emptySet(); - } - - @Override - public void subscribeToDefaultPerms(boolean bln, Permissible prmsbl) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void unsubscribeFromDefaultPerms(boolean bln, Permissible prmsbl) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Set getDefaultPermSubscriptions(boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Set getPermissions() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean useTimings() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void registerEvent(Class type, Listener ll, EventPriority ep, EventExecutor ee, Plugin plugin, boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - }; - - @Override - public PluginManager getPluginManager() - { - return pManager; - } - - @Override - public BukkitScheduler getScheduler() - { - return new BukkitScheduler() - { - @Override - public int scheduleSyncDelayedTask(Plugin plugin, Runnable r, long l) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int scheduleSyncDelayedTask(Plugin plugin, Runnable r) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int scheduleSyncRepeatingTask(Plugin plugin, Runnable r, long l, long l1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int scheduleAsyncDelayedTask(Plugin plugin, Runnable r, long l) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int scheduleAsyncDelayedTask(Plugin plugin, Runnable r) - { - r.run(); - return 0; - } - - @Override - public int scheduleAsyncRepeatingTask(Plugin plugin, Runnable r, long l, long l1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Future callSyncMethod(Plugin plugin, Callable clbl) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void cancelTask(int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void cancelTasks(Plugin plugin) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void cancelAllTasks() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isCurrentlyRunning(int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isQueued(int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public List getActiveWorkers() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public List getPendingTasks() - { - throw new UnsupportedOperationException("Not supported yet."); - } - }; - } - - @Override - public ServicesManager getServicesManager() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public List getWorlds() - { - return worlds; - } - - public World createWorld(String string, Environment e) - { - World w = new FakeWorld(string, e); - worlds.add(w); - return w; - } - - public World createWorld(String string, Environment e, long l) - { - World w = new FakeWorld(string, e); - worlds.add(w); - return w; - } - - @Override - public World getWorld(String string) - { - for (World world : worlds) - { - if (world.getName().equalsIgnoreCase(string)) - { - return world; - } - } - return null; - } - - @Override - public void reload() - { - } - - @Override - public Logger getLogger() - { - return Logger.getLogger("Minecraft"); - } - - @Override - public PluginCommand getPluginCommand(String string) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void savePlayers() - { - } - - @Override - public boolean dispatchCommand(CommandSender cs, String string) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void configureDbConfig(ServerConfig sc) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean addRecipe(Recipe recipe) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - public void addPlayer(Player base1) - { - players.add(base1); - } - - @Override - public World createWorld(WorldCreator creator) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean unloadWorld(String string, boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean unloadWorld(World world, boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Map getCommandAliases() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getSpawnRadius() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setSpawnRadius(int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean getOnlineMode() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - public World getWorld(long l) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public World getWorld(UUID uuid) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getViewDistance() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean getAllowNether() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean hasWhitelist() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public MapView getMap(short s) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public MapView createMap(World world) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean getAllowFlight() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setWhitelist(boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Set getWhitelistedPlayers() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void reloadWhitelist() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Player getPlayerExact(String string) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void shutdown() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int broadcast(String string, String string1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public org.bukkit.OfflinePlayer getOfflinePlayer(final String string) - { - return new org.bukkit.OfflinePlayer() - { - @Override - public boolean isOnline() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public String getName() - { - return string; - } - - @Override - public boolean isBanned() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setBanned(boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isWhitelisted() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setWhitelisted(boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Player getPlayer() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isOp() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setOp(boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Map serialize() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public long getFirstPlayed() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public long getLastPlayed() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean hasPlayedBefore() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Location getBedSpawnLocation() - { - throw new UnsupportedOperationException("Not supported yet."); - } - }; - } - - @Override - public Set getIPBans() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void banIP(String string) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void unbanIP(String string) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Set getBannedPlayers() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public GameMode getDefaultGameMode() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setDefaultGameMode(GameMode gamemode) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public ConsoleCommandSender getConsoleSender() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Set getOperators() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public String getBukkitVersion() - { - return "Essentials Fake-Server"; - } - - @Override - public File getWorldContainer() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public OfflinePlayer[] getOfflinePlayers() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean getAllowEnd() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Messenger getMessenger() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void sendPluginMessage(Plugin plugin, String string, byte[] bytes) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Set getListeningPluginChannels() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean useExactLoginLocation() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getTicksPerAnimalSpawns() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getTicksPerMonsterSpawns() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public List getRecipesFor(ItemStack is) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Iterator recipeIterator() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void clearRecipes() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void resetRecipes() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public HelpMap getHelpMap() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Inventory createInventory(InventoryHolder ih, InventoryType it) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Inventory createInventory(InventoryHolder ih, int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Inventory createInventory(InventoryHolder ih, int i, String string) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public String getWorldType() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean getGenerateStructures() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public long getConnectionThrottle() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getMonsterSpawnLimit() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getAnimalSpawnLimit() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getWaterAnimalSpawnLimit() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isPrimaryThread() - { - throw new UnsupportedOperationException("Not supported yet."); - } -} diff --git a/Essentials/test/com/earth2me/essentials/FakeWorld.java b/Essentials/test/com/earth2me/essentials/FakeWorld.java deleted file mode 100644 index c389a3f37..000000000 --- a/Essentials/test/com/earth2me/essentials/FakeWorld.java +++ /dev/null @@ -1,678 +0,0 @@ -package com.earth2me.essentials; - -import java.io.File; -import java.util.Collection; -import java.util.List; -import java.util.Set; -import java.util.UUID; -import org.bukkit.*; -import org.bukkit.block.Biome; -import org.bukkit.block.Block; -import org.bukkit.entity.*; -import org.bukkit.generator.BlockPopulator; -import org.bukkit.generator.ChunkGenerator; -import org.bukkit.inventory.ItemStack; -import org.bukkit.metadata.MetadataValue; -import org.bukkit.plugin.Plugin; -import org.bukkit.util.Vector; - - -public class FakeWorld implements World -{ - private final String name; - private final Environment env; - - public FakeWorld(String string, Environment environment) - { - this.name = string; - this.env = environment; - } - - @Override - public Block getBlockAt(int i, int i1, int i2) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Block getBlockAt(Location lctn) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getBlockTypeIdAt(int i, int i1, int i2) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getBlockTypeIdAt(Location lctn) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getHighestBlockYAt(int i, int i1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getHighestBlockYAt(Location lctn) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Chunk getChunkAt(int i, int i1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Chunk getChunkAt(Location lctn) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Chunk getChunkAt(Block block) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isChunkLoaded(Chunk chunk) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Chunk[] getLoadedChunks() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void loadChunk(Chunk chunk) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isChunkLoaded(int i, int i1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void loadChunk(int i, int i1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean loadChunk(int i, int i1, boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean unloadChunk(int i, int i1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean unloadChunk(int i, int i1, boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean unloadChunk(int i, int i1, boolean bln, boolean bln1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean unloadChunkRequest(int i, int i1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean unloadChunkRequest(int i, int i1, boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean regenerateChunk(int i, int i1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean refreshChunk(int i, int i1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Item dropItem(Location lctn, ItemStack is) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Item dropItemNaturally(Location lctn, ItemStack is) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Arrow spawnArrow(Location lctn, Vector vector, float f, float f1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean generateTree(Location lctn, TreeType tt) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean generateTree(Location lctn, TreeType tt, BlockChangeDelegate bcd) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public LivingEntity spawnCreature(Location lctn, CreatureType ct) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public LightningStrike strikeLightning(Location lctn) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public LightningStrike strikeLightningEffect(Location lctn) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public List getEntities() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public List getLivingEntities() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public List getPlayers() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public String getName() - { - return name; - } - - @Override - public Location getSpawnLocation() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean setSpawnLocation(int i, int i1, int i2) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public long getTime() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setTime(long l) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public long getFullTime() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setFullTime(long l) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean hasStorm() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setStorm(boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getWeatherDuration() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setWeatherDuration(int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isThundering() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setThundering(boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getThunderDuration() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setThunderDuration(int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Environment getEnvironment() - { - return env; - } - - @Override - public long getSeed() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean getPVP() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setPVP(boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void save() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean createExplosion(double d, double d1, double d2, float f) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean createExplosion(Location lctn, float f) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public ChunkGenerator getGenerator() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public List getPopulators() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void playEffect(Location lctn, Effect effect, int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void playEffect(Location lctn, Effect effect, int i, int i1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean createExplosion(double d, double d1, double d2, float f, boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean createExplosion(Location lctn, float f, boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public T spawn(Location lctn, Class type) throws IllegalArgumentException - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public ChunkSnapshot getEmptyChunkSnapshot(int i, int i1, boolean bln, boolean bln1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setSpawnFlags(boolean bln, boolean bln1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean getAllowAnimals() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean getAllowMonsters() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public UUID getUID() - { - return UUID.randomUUID(); - } - - @Override - public Block getHighestBlockAt(int i, int i1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Block getHighestBlockAt(Location lctn) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Biome getBiome(int i, int i1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public double getTemperature(int i, int i1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public double getHumidity(int i, int i1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean unloadChunk(Chunk chunk) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getMaxHeight() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean getKeepSpawnInMemory() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setKeepSpawnInMemory(boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isAutoSave() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setAutoSave(boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Difficulty getDifficulty() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setDifficulty(Difficulty difficulty) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getSeaLevel() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public File getWorldFolder() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Collection getEntitiesByClass(Class... types) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public WorldType getWorldType() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void sendPluginMessage(Plugin plugin, String string, byte[] bytes) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Set getListeningPluginChannels() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean canGenerateStructures() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public long getTicksPerAnimalSpawns() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setTicksPerAnimalSpawns(int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public long getTicksPerMonsterSpawns() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setTicksPerMonsterSpawns(int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Collection getEntitiesByClass(Class type) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Collection getEntitiesByClasses(Class... types) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public LivingEntity spawnCreature(Location arg0, EntityType arg1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void playEffect(Location lctn, Effect effect, T t) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void playEffect(Location lctn, Effect effect, T t, int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setMetadata(String string, MetadataValue mv) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public List getMetadata(String string) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean hasMetadata(String string) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void removeMetadata(String string, Plugin plugin) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setBiome(int arg0, int arg1, Biome arg2) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getMonsterSpawnLimit() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setMonsterSpawnLimit(int arg0) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getAnimalSpawnLimit() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setAnimalSpawnLimit(int arg0) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getWaterAnimalSpawnLimit() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setWaterAnimalSpawnLimit(int arg0) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Entity spawnEntity(Location loc, EntityType type) - { - throw new UnsupportedOperationException("Not supported yet."); - } -} diff --git a/Essentials/test/com/earth2me/essentials/StorageTest.java b/Essentials/test/com/earth2me/essentials/StorageTest.java deleted file mode 100644 index 5a5e12250..000000000 --- a/Essentials/test/com/earth2me/essentials/StorageTest.java +++ /dev/null @@ -1,162 +0,0 @@ -package com.earth2me.essentials; - -import com.earth2me.essentials.utils.ExecuteTimer; -import com.earth2me.essentials.settings.Settings; -import com.earth2me.essentials.storage.ObjectLoadException; -import com.earth2me.essentials.storage.StorageObject; -import com.earth2me.essentials.storage.YamlStorageReader; -import com.earth2me.essentials.storage.YamlStorageWriter; -import java.io.*; -import junit.framework.TestCase; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.World.Environment; -import org.bukkit.plugin.InvalidDescriptionException; -import org.junit.Test; - - -public class StorageTest extends TestCase -{ - Essentials ess; - FakeServer server; - World world; - - public StorageTest() - { - ess = new Essentials(); - server = new FakeServer(); - world = server.createWorld("testWorld", Environment.NORMAL); - try - { - ess.setupForTesting(server); - } - catch (InvalidDescriptionException ex) - { - fail("InvalidDescriptionException"); - } - catch (IOException ex) - { - fail("IOException"); - } - } - - @Test - public void testSettings() - { - try - { - assertTrue(StorageObject.class.isAssignableFrom(Settings.class)); - ExecuteTimer ext = new ExecuteTimer(); - ext.start(); - final ByteArrayInputStream bais = new ByteArrayInputStream(new byte[0]); - final Reader reader = new InputStreamReader(bais); - final Settings settings = new YamlStorageReader(reader, null).load(Settings.class); - ext.mark("load empty settings"); - final ByteArrayInputStream bais3 = new ByteArrayInputStream(new byte[0]); - final Reader reader3 = new InputStreamReader(bais3); - final Settings settings3 = new YamlStorageReader(reader3, null).load(Settings.class); - ext.mark("load empty settings (class cached)"); - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - final PrintWriter writer = new PrintWriter(baos); - new YamlStorageWriter(writer).save(settings); - writer.close(); - ext.mark("write settings"); - byte[] written = baos.toByteArray(); - System.out.println(new String(written)); - final ByteArrayInputStream bais2 = new ByteArrayInputStream(written); - final Reader reader2 = new InputStreamReader(bais2); - final Settings settings2 = new YamlStorageReader(reader2, null).load(Settings.class); - System.out.println(settings.toString()); - System.out.println(settings2.toString()); - ext.mark("reload settings"); - System.out.println(ext.end()); - //assertEquals("Default and rewritten config should be equal", settings, settings2); - //that assertion fails, because empty list and maps return as null - } - catch (ObjectLoadException ex) - { - fail(ex.getMessage()); - } - } - - @Test - public void testUserdata() - { - try - { - FakeServer server = new FakeServer(); - World world = server.createWorld("testWorld", Environment.NORMAL); - ExecuteTimer ext = new ExecuteTimer(); - ext.start(); - final ByteArrayInputStream bais = new ByteArrayInputStream(new byte[0]); - final Reader reader = new InputStreamReader(bais); - final com.earth2me.essentials.user.UserData userdata = new YamlStorageReader(reader, null).load(com.earth2me.essentials.user.UserData.class); - ext.mark("load empty user"); - final ByteArrayInputStream bais3 = new ByteArrayInputStream(new byte[0]); - final Reader reader3 = new InputStreamReader(bais3); - final com.earth2me.essentials.user.UserData userdata3 = new YamlStorageReader(reader3, null).load(com.earth2me.essentials.user.UserData.class); - ext.mark("load empty user (class cached)"); - - for (int j = 0; j < 10000; j++) - { - userdata.getHomes().put("home", new com.earth2me.essentials.storage.Location(new Location(world, j, j, j))); - } - ext.mark("change home 10000 times"); - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - final PrintWriter writer = new PrintWriter(baos); - new YamlStorageWriter(writer).save(userdata); - writer.close(); - ext.mark("write user"); - final ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); - final PrintWriter writer2 = new PrintWriter(baos2); - new YamlStorageWriter(writer2).save(userdata); - writer2.close(); - ext.mark("write user (cached)"); - byte[] written = baos.toByteArray(); - System.out.println(new String(written)); - ext.mark("debug output"); - final ByteArrayInputStream bais2 = new ByteArrayInputStream(written); - final Reader reader2 = new InputStreamReader(bais2); - final com.earth2me.essentials.user.UserData userdata2 = new YamlStorageReader(reader2, null).load(com.earth2me.essentials.user.UserData.class); - ext.mark("reload file"); - final ByteArrayInputStream bais4 = new ByteArrayInputStream(written); - final Reader reader4 = new InputStreamReader(bais4); - final com.earth2me.essentials.user.UserData userdata4 = new YamlStorageReader(reader4, null).load(com.earth2me.essentials.user.UserData.class); - ext.mark("reload file (cached)"); - System.out.println(userdata.toString()); - System.out.println(userdata2.toString()); - System.out.println(ext.end()); - } - catch (ObjectLoadException ex) - { - fail(ex.getMessage()); - } - - } - - /*@Test - public void testOldUserdata() - { - ExecuteTimer ext = new ExecuteTimer(); - ext.start(); - OfflinePlayer base1 = server.createPlayer("testPlayer1", ess); - server.addPlayer(base1); - ext.mark("fake user created"); - UserData user = (UserData)ess.getUser(base1); - ext.mark("load empty user"); - for (int j = 0; j < 1; j++) - { - user.setHome("home", new Location(world, j, j, j)); - } - ext.mark("change home 1 times"); - user.save(); - ext.mark("write user"); - user.save(); - ext.mark("write user (cached)"); - user.reloadConfig(); - ext.mark("reloaded file"); - user.reloadConfig(); - ext.mark("reloaded file (cached)"); - System.out.println(ext.end()); - }*/ -} diff --git a/Essentials/test/com/earth2me/essentials/UserTest.java b/Essentials/test/com/earth2me/essentials/UserTest.java deleted file mode 100644 index 6cffcb4f3..000000000 --- a/Essentials/test/com/earth2me/essentials/UserTest.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.earth2me.essentials; - -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.user.User; -import java.io.IOException; -import junit.framework.TestCase; -import org.bukkit.World.Environment; -import org.bukkit.plugin.InvalidDescriptionException; - - -public class UserTest extends TestCase -{ - private final IUser base1; - private final Essentials ess; - private final FakeServer server; - - public UserTest(String testName) - { - super(testName); - ess = new Essentials(); - server = new FakeServer(); - server.createWorld("testWorld", Environment.NORMAL); - try - { - ess.setupForTesting(server); - } - catch (InvalidDescriptionException ex) - { - fail("InvalidDescriptionException"); - } - catch (IOException ex) - { - fail("IOException"); - } - base1 = new User(new FakeOfflinePlayer("testPlayer1"), ess); - server.addPlayer(base1); - ess.getUser(base1); - } - - private void should(String what) - { - System.out.println(getName() + " should " + what); - } - - /*public void testUpdate() - { - OfflinePlayer base1alt = server.createPlayer(base1.getName(), ess); - assertEquals(base1alt, ess.getUser(base1alt).getBase()); - } - - public void testHome() - { - IUser user = ess.getUser(base1); - Location loc = base1.getLocation(); - user.setHome(); - OfflinePlayer base2 = server.createPlayer(base1.getName(), ess); - IUser user2 = ess.getUser(base2); - - Location home = user2.getHome(loc); - assertNotNull(home); - assertEquals(loc.getWorld().getName(), home.getWorld().getName()); - assertEquals(loc.getX(), home.getX()); - assertEquals(loc.getY(), home.getY()); - assertEquals(loc.getZ(), home.getZ()); - assertEquals(loc.getYaw(), home.getYaw()); - assertEquals(loc.getPitch(), home.getPitch()); - }*/ - - /*public void testMoney() - { - should("properly set, take, give, and get money"); - IUser user = ess.getUser(base1); - double i; - user.setMoney(i = 100.5); - user.takeMoney(50); - i -= 50; - user.giveMoney(25); - i += 25; - assertEquals(user.getMoney(), i); - }*/ - - /*public void testGetGroup() - { - should("return the default group"); - IUser user = ess.getUser(base1); - //assertEquals(user.getGroup(), "default"); - }*/ - - public void testNoop() - { - assertTrue(true); - } -} diff --git a/Essentials/test/com/earth2me/essentials/UtilTest.java b/Essentials/test/com/earth2me/essentials/UtilTest.java deleted file mode 100644 index 94cd2877d..000000000 --- a/Essentials/test/com/earth2me/essentials/UtilTest.java +++ /dev/null @@ -1,201 +0,0 @@ -package com.earth2me.essentials; - -import com.earth2me.essentials.api.InvalidNameException; -import com.earth2me.essentials.utils.DateUtil; -import com.earth2me.essentials.utils.Util; -import java.io.IOException; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.logging.Level; -import java.util.logging.Logger; -import junit.framework.TestCase; -import org.bukkit.World.Environment; -import org.bukkit.plugin.InvalidDescriptionException; - - -public class UtilTest extends TestCase -{ - private final Essentials ess; - private final FakeServer server; - - public UtilTest() - { - ess = new Essentials(); - server = new FakeServer(); - server.createWorld("testWorld", Environment.NORMAL); - try - { - ess.setupForTesting(server); - } - catch (InvalidDescriptionException ex) - { - fail("InvalidDescriptionException"); - } - catch (IOException ex) - { - fail("IOException"); - } - } - - public void testFDDnow() - { - Calendar c = new GregorianCalendar(); - String resp = DateUtil.formatDateDiff(c, c); - assertEquals("now", resp); - } - - public void testFDDfuture() - { - Calendar a, b; - a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); - b = new GregorianCalendar(2010, 1, 1, 10, 0, 1); - assertEquals(" 1 second", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); - b = new GregorianCalendar(2010, 1, 1, 10, 0, 2); - assertEquals(" 2 seconds", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); - b = new GregorianCalendar(2010, 1, 1, 10, 0, 3); - assertEquals(" 3 seconds", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); - b = new GregorianCalendar(2010, 1, 1, 10, 1, 0); - assertEquals(" 1 minute", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); - b = new GregorianCalendar(2010, 1, 1, 10, 2, 0); - assertEquals(" 2 minutes", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); - b = new GregorianCalendar(2010, 1, 1, 10, 3, 0); - assertEquals(" 3 minutes", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); - b = new GregorianCalendar(2010, 1, 1, 11, 0, 0); - assertEquals(" 1 hour", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); - b = new GregorianCalendar(2010, 1, 1, 12, 0, 0); - assertEquals(" 2 hours", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); - b = new GregorianCalendar(2010, 1, 1, 13, 0, 0); - assertEquals(" 3 hours", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); - b = new GregorianCalendar(2010, 1, 2, 10, 0, 0); - assertEquals(" 1 day", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); - b = new GregorianCalendar(2010, 1, 3, 10, 0, 0); - assertEquals(" 2 days", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); - b = new GregorianCalendar(2010, 1, 4, 10, 0, 0); - assertEquals(" 3 days", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); - b = new GregorianCalendar(2010, 2, 1, 10, 0, 0); - assertEquals(" 1 month", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); - b = new GregorianCalendar(2010, 3, 1, 10, 0, 0); - assertEquals(" 2 months", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); - b = new GregorianCalendar(2010, 4, 1, 10, 0, 0); - assertEquals(" 3 months", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); - b = new GregorianCalendar(2011, 1, 1, 10, 0, 0); - assertEquals(" 1 year", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); - b = new GregorianCalendar(2012, 1, 1, 10, 0, 0); - assertEquals(" 2 years", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); - b = new GregorianCalendar(2013, 1, 1, 10, 0, 0); - assertEquals(" 3 years", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); - b = new GregorianCalendar(2011, 4, 5, 23, 38, 12); - assertEquals(" 1 year 3 months 4 days 13 hours 38 minutes 12 seconds", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 9, 17, 23, 45, 45); - b = new GregorianCalendar(2015, 3, 7, 10, 0, 0); - assertEquals(" 4 years 5 months 20 days 10 hours 14 minutes 15 seconds", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2011, 4, 31, 10, 0, 0); - b = new GregorianCalendar(2011, 4, 31, 10, 5, 0); - assertEquals(" 5 minutes", DateUtil.formatDateDiff(a, b)); - } - - public void testFDDpast() - { - Calendar a, b; - a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); - b = new GregorianCalendar(2010, 1, 1, 9, 59, 59); - assertEquals(" 1 second", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); - b = new GregorianCalendar(2010, 1, 1, 9, 59, 58); - assertEquals(" 2 seconds", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); - b = new GregorianCalendar(2010, 1, 1, 9, 59, 57); - assertEquals(" 3 seconds", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); - b = new GregorianCalendar(2010, 1, 1, 9, 59, 0); - assertEquals(" 1 minute", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); - b = new GregorianCalendar(2010, 1, 1, 9, 58, 0); - assertEquals(" 2 minutes", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); - b = new GregorianCalendar(2010, 1, 1, 9, 57, 0); - assertEquals(" 3 minutes", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); - b = new GregorianCalendar(2010, 1, 1, 9, 0, 0); - assertEquals(" 1 hour", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); - b = new GregorianCalendar(2010, 1, 1, 8, 0, 0); - assertEquals(" 2 hours", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); - b = new GregorianCalendar(2010, 1, 1, 7, 0, 0); - assertEquals(" 3 hours", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 1, 5, 10, 0, 0); - b = new GregorianCalendar(2010, 1, 4, 10, 0, 0); - assertEquals(" 1 day", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 1, 5, 10, 0, 0); - b = new GregorianCalendar(2010, 1, 3, 10, 0, 0); - assertEquals(" 2 days", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 1, 5, 10, 0, 0); - b = new GregorianCalendar(2010, 1, 2, 10, 0, 0); - assertEquals(" 3 days", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 5, 1, 10, 0, 0); - b = new GregorianCalendar(2010, 4, 1, 10, 0, 0); - assertEquals(" 1 month", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 5, 1, 10, 0, 0); - b = new GregorianCalendar(2010, 3, 1, 10, 0, 0); - assertEquals(" 2 months", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 5, 1, 10, 0, 0); - b = new GregorianCalendar(2010, 2, 1, 10, 0, 0); - assertEquals(" 3 months", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); - b = new GregorianCalendar(2009, 1, 1, 10, 0, 0); - assertEquals(" 1 year", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); - b = new GregorianCalendar(2008, 1, 1, 10, 0, 0); - assertEquals(" 2 years", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); - b = new GregorianCalendar(2007, 1, 1, 10, 0, 0); - assertEquals(" 3 years", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); - b = new GregorianCalendar(2009, 4, 5, 23, 38, 12); - assertEquals(" 8 months 26 days 10 hours 21 minutes 48 seconds", DateUtil.formatDateDiff(a, b)); - a = new GregorianCalendar(2010, 9, 17, 23, 45, 45); - b = new GregorianCalendar(2000, 3, 7, 10, 0, 0); - assertEquals(" 10 years 6 months 10 days 13 hours 45 minutes 45 seconds", DateUtil.formatDateDiff(a, b)); - } - - public void filenameTest() { - try - { - assertEquals("_-", Util.sanitizeFileName("\u0000")); - assertEquals("_-", Util.sanitizeFileName("\u0001")); - assertEquals("_-", Util.sanitizeFileName("\u001f")); - assertEquals(" -", Util.sanitizeFileName(" ")); - assertEquals("_-", Util.sanitizeFileName("..")); - assertEquals("_-", Util.sanitizeFileName("..\\")); - assertEquals("_-", Util.sanitizeFileName("../")); - assertEquals("_-", Util.sanitizeFileName("\"")); - assertEquals("_-", Util.sanitizeFileName("<>?:*.")); - assertEquals("a-0fa", Util.sanitizeFileName("aä")); - - } - catch (InvalidNameException ex) - { - Logger.getLogger(UtilTest.class.getName()).log(Level.SEVERE, null, ex); - } - - } -} diff --git a/Essentials/test/net/ess3/EconomyTest.java b/Essentials/test/net/ess3/EconomyTest.java new file mode 100644 index 000000000..978f35fc6 --- /dev/null +++ b/Essentials/test/net/ess3/EconomyTest.java @@ -0,0 +1,116 @@ +package net.ess3; + +import net.ess3.api.NoLoanPermittedException; +import net.ess3.api.UserDoesNotExistException; +import net.ess3.user.User; +import java.io.IOException; +import junit.framework.TestCase; +import org.bukkit.World.Environment; +import org.bukkit.plugin.InvalidDescriptionException; +import org.junit.Test; + + +public class EconomyTest extends TestCase +{ + private final transient Essentials ess; + private final static String NPCNAME = "npc1"; + private final static String PLAYERNAME = "TestPlayer1"; + + public EconomyTest(final String testName) + { + super(testName); + ess = new Essentials(); + final FakeServer server = new FakeServer(); + server.createWorld("testWorld", Environment.NORMAL); + try + { + ess.setupForTesting(server); + } + catch (InvalidDescriptionException ex) + { + fail("InvalidDescriptionException"); + } + catch (IOException ex) + { + fail("IOException"); + } + server.addPlayer(new User(new FakeOfflinePlayer(PLAYERNAME), ess)); + } + + // only one big test, since we use static instances + @Test + public void testEconomy() + { + // test NPC + assertFalse("NPC does not exists", ess.getEconomy().playerExists(NPCNAME)); + assertTrue("Create NPC", ess.getEconomy().createNPC(NPCNAME)); + assertTrue("NPC exists", ess.getEconomy().playerExists(NPCNAME)); + assertNull("NPC can not be accessed", ess.getUser(NPCNAME)); + try + { + ess.getEconomy().removeNPC(NPCNAME); + } + catch (UserDoesNotExistException ex) + { + fail(ex.getMessage()); + } + assertFalse("NPC can be removed",ess.getEconomy().playerExists(NPCNAME)); + + //test Math + try + { + + assertTrue("Player exists", ess.getEconomy().playerExists(PLAYERNAME)); + ess.getEconomy().resetBalance(PLAYERNAME); + assertEquals("Player has no money", 0.0, ess.getEconomy().getMoney(PLAYERNAME)); + ess.getEconomy().setMoney(PLAYERNAME, 10.0); + assertEquals("Set money", 10.0, ess.getEconomy().getMoney(PLAYERNAME)); + } + catch (NoLoanPermittedException ex) + { + fail(ex.getMessage()); + } + catch (UserDoesNotExistException ex) + { + fail(ex.getMessage()); + } + + //test Format + assertEquals("Format $1000", "$1000", ess.getEconomy().format(1000.0)); + assertEquals("Format $10", "$10", ess.getEconomy().format(10.0)); + assertEquals("Format $10.10", "$10.10", ess.getEconomy().format(10.10)); + assertEquals("Format $10.10", "$10.10", ess.getEconomy().format(10.102)); + assertEquals("Format $10.11", "$10.11", ess.getEconomy().format(10.109)); + + + //test Exceptions + try + { + assertTrue("Player exists", ess.getEconomy().playerExists(PLAYERNAME)); + ess.getEconomy().resetBalance(PLAYERNAME); + assertEquals("Reset balance", 0.0, ess.getEconomy().getMoney(PLAYERNAME)); + ess.getEconomy().setMoney(PLAYERNAME, -5.0); + fail("Did not throw exception"); + } + catch (NoLoanPermittedException ex) + { + } + catch (UserDoesNotExistException ex) + { + fail(ex.getMessage()); + } + + try + { + ess.getEconomy().resetBalance("UnknownPlayer"); + fail("Did not throw exception"); + } + catch (NoLoanPermittedException ex) + { + fail(ex.getMessage()); + } + catch (UserDoesNotExistException ex) + { + } + } +} diff --git a/Essentials/test/net/ess3/FakeOfflinePlayer.java b/Essentials/test/net/ess3/FakeOfflinePlayer.java new file mode 100644 index 000000000..de1f9064e --- /dev/null +++ b/Essentials/test/net/ess3/FakeOfflinePlayer.java @@ -0,0 +1,100 @@ +package net.ess3; + +import java.util.Map; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; + + +public class FakeOfflinePlayer implements OfflinePlayer +{ + private final transient String name; + + public FakeOfflinePlayer(String name) + { + this.name = name; + } + + @Override + public boolean isOnline() + { + return false; + } + + @Override + public String getName() + { + return name; + } + + @Override + public boolean isBanned() + { + return false; + } + + @Override + public void setBanned(boolean bln) + { + } + + @Override + public boolean isWhitelisted() + { + return false; + } + + @Override + public void setWhitelisted(boolean bln) + { + } + + @Override + public Player getPlayer() + { + return Bukkit.getPlayerExact(name); + } + + @Override + public long getFirstPlayed() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public long getLastPlayed() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean hasPlayedBefore() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isOp() + { + return false; + } + + @Override + public void setOp(boolean bln) + { + } + + @Override + public Map serialize() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Location getBedSpawnLocation() + { + throw new UnsupportedOperationException("Not supported yet."); + } + +} diff --git a/Essentials/test/net/ess3/FakeServer.java b/Essentials/test/net/ess3/FakeServer.java new file mode 100644 index 000000000..26437ddc0 --- /dev/null +++ b/Essentials/test/net/ess3/FakeServer.java @@ -0,0 +1,928 @@ +package net.ess3; + +import com.avaje.ebean.config.ServerConfig; +import java.io.File; +import java.util.*; +import java.util.concurrent.Callable; +import java.util.concurrent.Future; +import java.util.logging.Logger; +import org.bukkit.*; +import org.bukkit.World.Environment; +import org.bukkit.command.CommandSender; +import org.bukkit.command.ConsoleCommandSender; +import org.bukkit.command.PluginCommand; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.help.HelpMap; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.Recipe; +import org.bukkit.map.MapView; +import org.bukkit.permissions.Permissible; +import org.bukkit.permissions.Permission; +import org.bukkit.plugin.*; +import org.bukkit.plugin.messaging.Messenger; +import org.bukkit.scheduler.BukkitScheduler; +import org.bukkit.scheduler.BukkitTask; +import org.bukkit.scheduler.BukkitWorker; + + +public class FakeServer implements Server +{ + private List players = new ArrayList(); + private final List worlds = new ArrayList(); + + public FakeServer() + { + if (Bukkit.getServer() == null) + { + Bukkit.setServer(this); + } + } + + public String getName() + { + return "Essentials Fake Server"; + } + + public String getVersion() + { + return "1.0"; + } + + @Override + public Player[] getOnlinePlayers() + { + return players.toArray(new Player[0]); + } + + public void setOnlinePlayers(List players) + { + this.players = players; + } + + @Override + public int getMaxPlayers() + { + return 100; + } + + @Override + public int getPort() + { + return 25565; + } + + @Override + public String getIp() + { + return "127.0.0.1"; + } + + @Override + public String getServerName() + { + return "Test Server"; + } + + @Override + public String getServerId() + { + return "Test Server"; + } + + @Override + public int broadcastMessage(String string) + { + int i = 0; + for (Player player : players) + { + player.sendMessage(string); + i++; + } + return i; + } + + @Override + public String getUpdateFolder() + { + return "update"; + } + + @Override + public File getUpdateFolderFile() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Player getPlayer(String string) + { + for (Player player : players) + { + if (player.getName().equalsIgnoreCase(string)) + { + return player; + } + } + return null; + } + + @Override + public List matchPlayer(String string) + { + List matches = new ArrayList(); + for (Player player : players) + { + if (player.getName().substring(0, Math.min(player.getName().length(), string.length())).equalsIgnoreCase(string)) + { + matches.add(player); + } + } + return matches; + } + private PluginManager pManager = new PluginManager() + { + private Set permissions = new HashSet(); + + @Override + public void registerInterface(Class type) throws IllegalArgumentException + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Plugin getPlugin(String string) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Plugin[] getPlugins() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isPluginEnabled(String string) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isPluginEnabled(Plugin plugin) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Plugin loadPlugin(File file) throws InvalidPluginException, InvalidDescriptionException, UnknownDependencyException + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Plugin[] loadPlugins(File file) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void disablePlugins() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void clearPlugins() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void callEvent(Event event) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void registerEvents(Listener ll, Plugin plugin) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void registerEvent(Class type, Listener ll, EventPriority ep, EventExecutor ee, Plugin plugin) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void enablePlugin(Plugin plugin) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void disablePlugin(Plugin plugin) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Permission getPermission(String string) + { + for (Permission permission : permissions) + { + if (permission.getName().equals(string)) + { + return permission; + } + } + return null; + } + + @Override + public void addPermission(Permission prmsn) + { + permissions.add(prmsn); + } + + @Override + public void removePermission(Permission prmsn) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void removePermission(String string) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Set getDefaultPermissions(boolean bln) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void recalculatePermissionDefaults(Permission prmsn) + { + } + + @Override + public void subscribeToPermission(String string, Permissible prmsbl) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void unsubscribeFromPermission(String string, Permissible prmsbl) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Set getPermissionSubscriptions(String string) + { + return Collections.emptySet(); + } + + @Override + public void subscribeToDefaultPerms(boolean bln, Permissible prmsbl) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void unsubscribeFromDefaultPerms(boolean bln, Permissible prmsbl) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Set getDefaultPermSubscriptions(boolean bln) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Set getPermissions() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean useTimings() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void registerEvent(Class type, Listener ll, EventPriority ep, EventExecutor ee, Plugin plugin, boolean bln) + { + throw new UnsupportedOperationException("Not supported yet."); + } + }; + + @Override + public PluginManager getPluginManager() + { + return pManager; + } + + @Override + public BukkitScheduler getScheduler() + { + return new BukkitScheduler() + { + @Override + public int scheduleSyncDelayedTask(Plugin plugin, Runnable r, long l) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int scheduleSyncDelayedTask(Plugin plugin, Runnable r) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int scheduleSyncRepeatingTask(Plugin plugin, Runnable r, long l, long l1) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int scheduleAsyncDelayedTask(Plugin plugin, Runnable r, long l) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int scheduleAsyncDelayedTask(Plugin plugin, Runnable r) + { + r.run(); + return 0; + } + + @Override + public int scheduleAsyncRepeatingTask(Plugin plugin, Runnable r, long l, long l1) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Future callSyncMethod(Plugin plugin, Callable clbl) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void cancelTask(int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void cancelTasks(Plugin plugin) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void cancelAllTasks() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isCurrentlyRunning(int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isQueued(int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public List getActiveWorkers() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public List getPendingTasks() + { + throw new UnsupportedOperationException("Not supported yet."); + } + }; + } + + @Override + public ServicesManager getServicesManager() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public List getWorlds() + { + return worlds; + } + + public World createWorld(String string, Environment e) + { + World w = new FakeWorld(string, e); + worlds.add(w); + return w; + } + + public World createWorld(String string, Environment e, long l) + { + World w = new FakeWorld(string, e); + worlds.add(w); + return w; + } + + @Override + public World getWorld(String string) + { + for (World world : worlds) + { + if (world.getName().equalsIgnoreCase(string)) + { + return world; + } + } + return null; + } + + @Override + public void reload() + { + } + + @Override + public Logger getLogger() + { + return Logger.getLogger("Minecraft"); + } + + @Override + public PluginCommand getPluginCommand(String string) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void savePlayers() + { + } + + @Override + public boolean dispatchCommand(CommandSender cs, String string) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void configureDbConfig(ServerConfig sc) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean addRecipe(Recipe recipe) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public void addPlayer(Player base1) + { + players.add(base1); + } + + @Override + public World createWorld(WorldCreator creator) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean unloadWorld(String string, boolean bln) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean unloadWorld(World world, boolean bln) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Map getCommandAliases() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int getSpawnRadius() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setSpawnRadius(int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean getOnlineMode() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + public World getWorld(long l) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public World getWorld(UUID uuid) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int getViewDistance() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean getAllowNether() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean hasWhitelist() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public MapView getMap(short s) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public MapView createMap(World world) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean getAllowFlight() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setWhitelist(boolean bln) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Set getWhitelistedPlayers() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void reloadWhitelist() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Player getPlayerExact(String string) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void shutdown() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int broadcast(String string, String string1) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public org.bukkit.OfflinePlayer getOfflinePlayer(final String string) + { + return new org.bukkit.OfflinePlayer() + { + @Override + public boolean isOnline() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public String getName() + { + return string; + } + + @Override + public boolean isBanned() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setBanned(boolean bln) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isWhitelisted() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setWhitelisted(boolean bln) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Player getPlayer() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isOp() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setOp(boolean bln) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Map serialize() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public long getFirstPlayed() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public long getLastPlayed() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean hasPlayedBefore() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Location getBedSpawnLocation() + { + throw new UnsupportedOperationException("Not supported yet."); + } + }; + } + + @Override + public Set getIPBans() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void banIP(String string) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void unbanIP(String string) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Set getBannedPlayers() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public GameMode getDefaultGameMode() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setDefaultGameMode(GameMode gamemode) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public ConsoleCommandSender getConsoleSender() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Set getOperators() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public String getBukkitVersion() + { + return "Essentials Fake-Server"; + } + + @Override + public File getWorldContainer() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public OfflinePlayer[] getOfflinePlayers() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean getAllowEnd() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Messenger getMessenger() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void sendPluginMessage(Plugin plugin, String string, byte[] bytes) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Set getListeningPluginChannels() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean useExactLoginLocation() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int getTicksPerAnimalSpawns() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int getTicksPerMonsterSpawns() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public List getRecipesFor(ItemStack is) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Iterator recipeIterator() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void clearRecipes() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void resetRecipes() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public HelpMap getHelpMap() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Inventory createInventory(InventoryHolder ih, InventoryType it) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Inventory createInventory(InventoryHolder ih, int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Inventory createInventory(InventoryHolder ih, int i, String string) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public String getWorldType() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean getGenerateStructures() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public long getConnectionThrottle() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int getMonsterSpawnLimit() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int getAnimalSpawnLimit() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int getWaterAnimalSpawnLimit() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isPrimaryThread() + { + throw new UnsupportedOperationException("Not supported yet."); + } +} diff --git a/Essentials/test/net/ess3/FakeWorld.java b/Essentials/test/net/ess3/FakeWorld.java new file mode 100644 index 000000000..fb617d98b --- /dev/null +++ b/Essentials/test/net/ess3/FakeWorld.java @@ -0,0 +1,678 @@ +package net.ess3; + +import java.io.File; +import java.util.Collection; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import org.bukkit.*; +import org.bukkit.block.Biome; +import org.bukkit.block.Block; +import org.bukkit.entity.*; +import org.bukkit.generator.BlockPopulator; +import org.bukkit.generator.ChunkGenerator; +import org.bukkit.inventory.ItemStack; +import org.bukkit.metadata.MetadataValue; +import org.bukkit.plugin.Plugin; +import org.bukkit.util.Vector; + + +public class FakeWorld implements World +{ + private final String name; + private final Environment env; + + public FakeWorld(String string, Environment environment) + { + this.name = string; + this.env = environment; + } + + @Override + public Block getBlockAt(int i, int i1, int i2) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Block getBlockAt(Location lctn) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int getBlockTypeIdAt(int i, int i1, int i2) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int getBlockTypeIdAt(Location lctn) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int getHighestBlockYAt(int i, int i1) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int getHighestBlockYAt(Location lctn) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Chunk getChunkAt(int i, int i1) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Chunk getChunkAt(Location lctn) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Chunk getChunkAt(Block block) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isChunkLoaded(Chunk chunk) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Chunk[] getLoadedChunks() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void loadChunk(Chunk chunk) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isChunkLoaded(int i, int i1) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void loadChunk(int i, int i1) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean loadChunk(int i, int i1, boolean bln) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean unloadChunk(int i, int i1) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean unloadChunk(int i, int i1, boolean bln) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean unloadChunk(int i, int i1, boolean bln, boolean bln1) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean unloadChunkRequest(int i, int i1) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean unloadChunkRequest(int i, int i1, boolean bln) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean regenerateChunk(int i, int i1) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean refreshChunk(int i, int i1) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Item dropItem(Location lctn, ItemStack is) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Item dropItemNaturally(Location lctn, ItemStack is) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Arrow spawnArrow(Location lctn, Vector vector, float f, float f1) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean generateTree(Location lctn, TreeType tt) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean generateTree(Location lctn, TreeType tt, BlockChangeDelegate bcd) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public LivingEntity spawnCreature(Location lctn, CreatureType ct) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public LightningStrike strikeLightning(Location lctn) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public LightningStrike strikeLightningEffect(Location lctn) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public List getEntities() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public List getLivingEntities() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public List getPlayers() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public String getName() + { + return name; + } + + @Override + public Location getSpawnLocation() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean setSpawnLocation(int i, int i1, int i2) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public long getTime() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setTime(long l) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public long getFullTime() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setFullTime(long l) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean hasStorm() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setStorm(boolean bln) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int getWeatherDuration() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setWeatherDuration(int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isThundering() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setThundering(boolean bln) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int getThunderDuration() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setThunderDuration(int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Environment getEnvironment() + { + return env; + } + + @Override + public long getSeed() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean getPVP() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setPVP(boolean bln) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void save() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean createExplosion(double d, double d1, double d2, float f) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean createExplosion(Location lctn, float f) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public ChunkGenerator getGenerator() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public List getPopulators() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void playEffect(Location lctn, Effect effect, int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void playEffect(Location lctn, Effect effect, int i, int i1) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean createExplosion(double d, double d1, double d2, float f, boolean bln) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean createExplosion(Location lctn, float f, boolean bln) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public T spawn(Location lctn, Class type) throws IllegalArgumentException + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public ChunkSnapshot getEmptyChunkSnapshot(int i, int i1, boolean bln, boolean bln1) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setSpawnFlags(boolean bln, boolean bln1) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean getAllowAnimals() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean getAllowMonsters() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public UUID getUID() + { + return UUID.randomUUID(); + } + + @Override + public Block getHighestBlockAt(int i, int i1) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Block getHighestBlockAt(Location lctn) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Biome getBiome(int i, int i1) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public double getTemperature(int i, int i1) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public double getHumidity(int i, int i1) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean unloadChunk(Chunk chunk) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int getMaxHeight() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean getKeepSpawnInMemory() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setKeepSpawnInMemory(boolean bln) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isAutoSave() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setAutoSave(boolean bln) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Difficulty getDifficulty() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setDifficulty(Difficulty difficulty) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int getSeaLevel() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public File getWorldFolder() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Collection getEntitiesByClass(Class... types) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public WorldType getWorldType() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void sendPluginMessage(Plugin plugin, String string, byte[] bytes) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Set getListeningPluginChannels() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean canGenerateStructures() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public long getTicksPerAnimalSpawns() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setTicksPerAnimalSpawns(int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public long getTicksPerMonsterSpawns() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setTicksPerMonsterSpawns(int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Collection getEntitiesByClass(Class type) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Collection getEntitiesByClasses(Class... types) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public LivingEntity spawnCreature(Location arg0, EntityType arg1) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void playEffect(Location lctn, Effect effect, T t) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void playEffect(Location lctn, Effect effect, T t, int i) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setMetadata(String string, MetadataValue mv) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public List getMetadata(String string) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean hasMetadata(String string) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void removeMetadata(String string, Plugin plugin) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setBiome(int arg0, int arg1, Biome arg2) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int getMonsterSpawnLimit() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setMonsterSpawnLimit(int arg0) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int getAnimalSpawnLimit() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setAnimalSpawnLimit(int arg0) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int getWaterAnimalSpawnLimit() + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setWaterAnimalSpawnLimit(int arg0) + { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Entity spawnEntity(Location loc, EntityType type) + { + throw new UnsupportedOperationException("Not supported yet."); + } +} diff --git a/Essentials/test/net/ess3/StorageTest.java b/Essentials/test/net/ess3/StorageTest.java new file mode 100644 index 000000000..429844e76 --- /dev/null +++ b/Essentials/test/net/ess3/StorageTest.java @@ -0,0 +1,162 @@ +package net.ess3; + +import net.ess3.utils.ExecuteTimer; +import net.ess3.settings.Settings; +import net.ess3.storage.ObjectLoadException; +import net.ess3.storage.StorageObject; +import net.ess3.storage.YamlStorageReader; +import net.ess3.storage.YamlStorageWriter; +import java.io.*; +import junit.framework.TestCase; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.World.Environment; +import org.bukkit.plugin.InvalidDescriptionException; +import org.junit.Test; + + +public class StorageTest extends TestCase +{ + Essentials ess; + FakeServer server; + World world; + + public StorageTest() + { + ess = new Essentials(); + server = new FakeServer(); + world = server.createWorld("testWorld", Environment.NORMAL); + try + { + ess.setupForTesting(server); + } + catch (InvalidDescriptionException ex) + { + fail("InvalidDescriptionException"); + } + catch (IOException ex) + { + fail("IOException"); + } + } + + @Test + public void testSettings() + { + try + { + assertTrue(StorageObject.class.isAssignableFrom(Settings.class)); + ExecuteTimer ext = new ExecuteTimer(); + ext.start(); + final ByteArrayInputStream bais = new ByteArrayInputStream(new byte[0]); + final Reader reader = new InputStreamReader(bais); + final Settings settings = new YamlStorageReader(reader, null).load(Settings.class); + ext.mark("load empty settings"); + final ByteArrayInputStream bais3 = new ByteArrayInputStream(new byte[0]); + final Reader reader3 = new InputStreamReader(bais3); + final Settings settings3 = new YamlStorageReader(reader3, null).load(Settings.class); + ext.mark("load empty settings (class cached)"); + final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + final PrintWriter writer = new PrintWriter(baos); + new YamlStorageWriter(writer).save(settings); + writer.close(); + ext.mark("write settings"); + byte[] written = baos.toByteArray(); + System.out.println(new String(written)); + final ByteArrayInputStream bais2 = new ByteArrayInputStream(written); + final Reader reader2 = new InputStreamReader(bais2); + final Settings settings2 = new YamlStorageReader(reader2, null).load(Settings.class); + System.out.println(settings.toString()); + System.out.println(settings2.toString()); + ext.mark("reload settings"); + System.out.println(ext.end()); + //assertEquals("Default and rewritten config should be equal", settings, settings2); + //that assertion fails, because empty list and maps return as null + } + catch (ObjectLoadException ex) + { + fail(ex.getMessage()); + } + } + + @Test + public void testUserdata() + { + try + { + FakeServer server = new FakeServer(); + World world = server.createWorld("testWorld", Environment.NORMAL); + ExecuteTimer ext = new ExecuteTimer(); + ext.start(); + final ByteArrayInputStream bais = new ByteArrayInputStream(new byte[0]); + final Reader reader = new InputStreamReader(bais); + final net.ess3.user.UserData userdata = new YamlStorageReader(reader, null).load(net.ess3.user.UserData.class); + ext.mark("load empty user"); + final ByteArrayInputStream bais3 = new ByteArrayInputStream(new byte[0]); + final Reader reader3 = new InputStreamReader(bais3); + final net.ess3.user.UserData userdata3 = new YamlStorageReader(reader3, null).load(net.ess3.user.UserData.class); + ext.mark("load empty user (class cached)"); + + for (int j = 0; j < 10000; j++) + { + userdata.getHomes().put("home", new net.ess3.storage.Location(new Location(world, j, j, j))); + } + ext.mark("change home 10000 times"); + final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + final PrintWriter writer = new PrintWriter(baos); + new YamlStorageWriter(writer).save(userdata); + writer.close(); + ext.mark("write user"); + final ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); + final PrintWriter writer2 = new PrintWriter(baos2); + new YamlStorageWriter(writer2).save(userdata); + writer2.close(); + ext.mark("write user (cached)"); + byte[] written = baos.toByteArray(); + System.out.println(new String(written)); + ext.mark("debug output"); + final ByteArrayInputStream bais2 = new ByteArrayInputStream(written); + final Reader reader2 = new InputStreamReader(bais2); + final net.ess3.user.UserData userdata2 = new YamlStorageReader(reader2, null).load(net.ess3.user.UserData.class); + ext.mark("reload file"); + final ByteArrayInputStream bais4 = new ByteArrayInputStream(written); + final Reader reader4 = new InputStreamReader(bais4); + final net.ess3.user.UserData userdata4 = new YamlStorageReader(reader4, null).load(net.ess3.user.UserData.class); + ext.mark("reload file (cached)"); + System.out.println(userdata.toString()); + System.out.println(userdata2.toString()); + System.out.println(ext.end()); + } + catch (ObjectLoadException ex) + { + fail(ex.getMessage()); + } + + } + + /*@Test + public void testOldUserdata() + { + ExecuteTimer ext = new ExecuteTimer(); + ext.start(); + OfflinePlayer base1 = server.createPlayer("testPlayer1", ess); + server.addPlayer(base1); + ext.mark("fake user created"); + UserData user = (UserData)ess.getUser(base1); + ext.mark("load empty user"); + for (int j = 0; j < 1; j++) + { + user.setHome("home", new Location(world, j, j, j)); + } + ext.mark("change home 1 times"); + user.save(); + ext.mark("write user"); + user.save(); + ext.mark("write user (cached)"); + user.reloadConfig(); + ext.mark("reloaded file"); + user.reloadConfig(); + ext.mark("reloaded file (cached)"); + System.out.println(ext.end()); + }*/ +} diff --git a/Essentials/test/net/ess3/UserTest.java b/Essentials/test/net/ess3/UserTest.java new file mode 100644 index 000000000..e834e0175 --- /dev/null +++ b/Essentials/test/net/ess3/UserTest.java @@ -0,0 +1,93 @@ +package net.ess3; + +import net.ess3.api.IUser; +import net.ess3.user.User; +import java.io.IOException; +import junit.framework.TestCase; +import org.bukkit.World.Environment; +import org.bukkit.plugin.InvalidDescriptionException; + + +public class UserTest extends TestCase +{ + private final IUser base1; + private final Essentials ess; + private final FakeServer server; + + public UserTest(String testName) + { + super(testName); + ess = new Essentials(); + server = new FakeServer(); + server.createWorld("testWorld", Environment.NORMAL); + try + { + ess.setupForTesting(server); + } + catch (InvalidDescriptionException ex) + { + fail("InvalidDescriptionException"); + } + catch (IOException ex) + { + fail("IOException"); + } + base1 = new User(new FakeOfflinePlayer("testPlayer1"), ess); + server.addPlayer(base1); + ess.getUser(base1); + } + + private void should(String what) + { + System.out.println(getName() + " should " + what); + } + + /*public void testUpdate() + { + OfflinePlayer base1alt = server.createPlayer(base1.getName(), ess); + assertEquals(base1alt, ess.getUser(base1alt).getBase()); + } + + public void testHome() + { + IUser user = ess.getUser(base1); + Location loc = base1.getLocation(); + user.setHome(); + OfflinePlayer base2 = server.createPlayer(base1.getName(), ess); + IUser user2 = ess.getUser(base2); + + Location home = user2.getHome(loc); + assertNotNull(home); + assertEquals(loc.getWorld().getName(), home.getWorld().getName()); + assertEquals(loc.getX(), home.getX()); + assertEquals(loc.getY(), home.getY()); + assertEquals(loc.getZ(), home.getZ()); + assertEquals(loc.getYaw(), home.getYaw()); + assertEquals(loc.getPitch(), home.getPitch()); + }*/ + + /*public void testMoney() + { + should("properly set, take, give, and get money"); + IUser user = ess.getUser(base1); + double i; + user.setMoney(i = 100.5); + user.takeMoney(50); + i -= 50; + user.giveMoney(25); + i += 25; + assertEquals(user.getMoney(), i); + }*/ + + /*public void testGetGroup() + { + should("return the default group"); + IUser user = ess.getUser(base1); + //assertEquals(user.getGroup(), "default"); + }*/ + + public void testNoop() + { + assertTrue(true); + } +} diff --git a/Essentials/test/net/ess3/UtilTest.java b/Essentials/test/net/ess3/UtilTest.java new file mode 100644 index 000000000..6ab863fc2 --- /dev/null +++ b/Essentials/test/net/ess3/UtilTest.java @@ -0,0 +1,201 @@ +package net.ess3; + +import net.ess3.api.InvalidNameException; +import net.ess3.utils.DateUtil; +import net.ess3.utils.Util; +import java.io.IOException; +import java.util.Calendar; +import java.util.GregorianCalendar; +import java.util.logging.Level; +import java.util.logging.Logger; +import junit.framework.TestCase; +import org.bukkit.World.Environment; +import org.bukkit.plugin.InvalidDescriptionException; + + +public class UtilTest extends TestCase +{ + private final Essentials ess; + private final FakeServer server; + + public UtilTest() + { + ess = new Essentials(); + server = new FakeServer(); + server.createWorld("testWorld", Environment.NORMAL); + try + { + ess.setupForTesting(server); + } + catch (InvalidDescriptionException ex) + { + fail("InvalidDescriptionException"); + } + catch (IOException ex) + { + fail("IOException"); + } + } + + public void testFDDnow() + { + Calendar c = new GregorianCalendar(); + String resp = DateUtil.formatDateDiff(c, c); + assertEquals("now", resp); + } + + public void testFDDfuture() + { + Calendar a, b; + a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); + b = new GregorianCalendar(2010, 1, 1, 10, 0, 1); + assertEquals(" 1 second", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); + b = new GregorianCalendar(2010, 1, 1, 10, 0, 2); + assertEquals(" 2 seconds", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); + b = new GregorianCalendar(2010, 1, 1, 10, 0, 3); + assertEquals(" 3 seconds", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); + b = new GregorianCalendar(2010, 1, 1, 10, 1, 0); + assertEquals(" 1 minute", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); + b = new GregorianCalendar(2010, 1, 1, 10, 2, 0); + assertEquals(" 2 minutes", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); + b = new GregorianCalendar(2010, 1, 1, 10, 3, 0); + assertEquals(" 3 minutes", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); + b = new GregorianCalendar(2010, 1, 1, 11, 0, 0); + assertEquals(" 1 hour", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); + b = new GregorianCalendar(2010, 1, 1, 12, 0, 0); + assertEquals(" 2 hours", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); + b = new GregorianCalendar(2010, 1, 1, 13, 0, 0); + assertEquals(" 3 hours", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); + b = new GregorianCalendar(2010, 1, 2, 10, 0, 0); + assertEquals(" 1 day", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); + b = new GregorianCalendar(2010, 1, 3, 10, 0, 0); + assertEquals(" 2 days", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); + b = new GregorianCalendar(2010, 1, 4, 10, 0, 0); + assertEquals(" 3 days", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); + b = new GregorianCalendar(2010, 2, 1, 10, 0, 0); + assertEquals(" 1 month", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); + b = new GregorianCalendar(2010, 3, 1, 10, 0, 0); + assertEquals(" 2 months", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); + b = new GregorianCalendar(2010, 4, 1, 10, 0, 0); + assertEquals(" 3 months", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); + b = new GregorianCalendar(2011, 1, 1, 10, 0, 0); + assertEquals(" 1 year", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); + b = new GregorianCalendar(2012, 1, 1, 10, 0, 0); + assertEquals(" 2 years", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); + b = new GregorianCalendar(2013, 1, 1, 10, 0, 0); + assertEquals(" 3 years", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); + b = new GregorianCalendar(2011, 4, 5, 23, 38, 12); + assertEquals(" 1 year 3 months 4 days 13 hours 38 minutes 12 seconds", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 9, 17, 23, 45, 45); + b = new GregorianCalendar(2015, 3, 7, 10, 0, 0); + assertEquals(" 4 years 5 months 20 days 10 hours 14 minutes 15 seconds", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2011, 4, 31, 10, 0, 0); + b = new GregorianCalendar(2011, 4, 31, 10, 5, 0); + assertEquals(" 5 minutes", DateUtil.formatDateDiff(a, b)); + } + + public void testFDDpast() + { + Calendar a, b; + a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); + b = new GregorianCalendar(2010, 1, 1, 9, 59, 59); + assertEquals(" 1 second", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); + b = new GregorianCalendar(2010, 1, 1, 9, 59, 58); + assertEquals(" 2 seconds", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); + b = new GregorianCalendar(2010, 1, 1, 9, 59, 57); + assertEquals(" 3 seconds", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); + b = new GregorianCalendar(2010, 1, 1, 9, 59, 0); + assertEquals(" 1 minute", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); + b = new GregorianCalendar(2010, 1, 1, 9, 58, 0); + assertEquals(" 2 minutes", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); + b = new GregorianCalendar(2010, 1, 1, 9, 57, 0); + assertEquals(" 3 minutes", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); + b = new GregorianCalendar(2010, 1, 1, 9, 0, 0); + assertEquals(" 1 hour", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); + b = new GregorianCalendar(2010, 1, 1, 8, 0, 0); + assertEquals(" 2 hours", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); + b = new GregorianCalendar(2010, 1, 1, 7, 0, 0); + assertEquals(" 3 hours", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 1, 5, 10, 0, 0); + b = new GregorianCalendar(2010, 1, 4, 10, 0, 0); + assertEquals(" 1 day", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 1, 5, 10, 0, 0); + b = new GregorianCalendar(2010, 1, 3, 10, 0, 0); + assertEquals(" 2 days", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 1, 5, 10, 0, 0); + b = new GregorianCalendar(2010, 1, 2, 10, 0, 0); + assertEquals(" 3 days", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 5, 1, 10, 0, 0); + b = new GregorianCalendar(2010, 4, 1, 10, 0, 0); + assertEquals(" 1 month", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 5, 1, 10, 0, 0); + b = new GregorianCalendar(2010, 3, 1, 10, 0, 0); + assertEquals(" 2 months", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 5, 1, 10, 0, 0); + b = new GregorianCalendar(2010, 2, 1, 10, 0, 0); + assertEquals(" 3 months", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); + b = new GregorianCalendar(2009, 1, 1, 10, 0, 0); + assertEquals(" 1 year", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); + b = new GregorianCalendar(2008, 1, 1, 10, 0, 0); + assertEquals(" 2 years", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); + b = new GregorianCalendar(2007, 1, 1, 10, 0, 0); + assertEquals(" 3 years", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 1, 1, 10, 0, 0); + b = new GregorianCalendar(2009, 4, 5, 23, 38, 12); + assertEquals(" 8 months 26 days 10 hours 21 minutes 48 seconds", DateUtil.formatDateDiff(a, b)); + a = new GregorianCalendar(2010, 9, 17, 23, 45, 45); + b = new GregorianCalendar(2000, 3, 7, 10, 0, 0); + assertEquals(" 10 years 6 months 10 days 13 hours 45 minutes 45 seconds", DateUtil.formatDateDiff(a, b)); + } + + public void filenameTest() { + try + { + assertEquals("_-", Util.sanitizeFileName("\u0000")); + assertEquals("_-", Util.sanitizeFileName("\u0001")); + assertEquals("_-", Util.sanitizeFileName("\u001f")); + assertEquals(" -", Util.sanitizeFileName(" ")); + assertEquals("_-", Util.sanitizeFileName("..")); + assertEquals("_-", Util.sanitizeFileName("..\\")); + assertEquals("_-", Util.sanitizeFileName("../")); + assertEquals("_-", Util.sanitizeFileName("\"")); + assertEquals("_-", Util.sanitizeFileName("<>?:*.")); + assertEquals("a-0fa", Util.sanitizeFileName("aä")); + + } + catch (InvalidNameException ex) + { + Logger.getLogger(UtilTest.class.getName()).log(Level.SEVERE, null, ex); + } + + } +} diff --git a/Essentials2Compat/src/com/earth2me/essentials/Economy.java b/Essentials2Compat/src/com/earth2me/essentials/Economy.java new file mode 100644 index 000000000..bf1c9a61d --- /dev/null +++ b/Essentials2Compat/src/com/earth2me/essentials/Economy.java @@ -0,0 +1,245 @@ +package com.earth2me.essentials; + +import net.ess3.api.IEssentials; +import net.ess3.api.NoLoanPermittedException; +import net.ess3.api.UserDoesNotExistException; +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 net.ess3.api.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 net.ess3.api.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/Essentials2Compat/src/com/earth2me/essentials/EssentialsConf.java b/Essentials2Compat/src/com/earth2me/essentials/EssentialsConf.java index 0dc36e262..cbc51eddd 100644 --- a/Essentials2Compat/src/com/earth2me/essentials/EssentialsConf.java +++ b/Essentials2Compat/src/com/earth2me/essentials/EssentialsConf.java @@ -1,6 +1,6 @@ package com.earth2me.essentials; -import static com.earth2me.essentials.I18n._; +import static net.ess3.I18n._; import com.google.common.io.Files; import java.io.*; import java.nio.ByteBuffer; diff --git a/Essentials2Compat/src/com/earth2me/essentials/EssentialsUpgrade.java b/Essentials2Compat/src/com/earth2me/essentials/EssentialsUpgrade.java index d912caf7e..cbc6f5982 100644 --- a/Essentials2Compat/src/com/earth2me/essentials/EssentialsUpgrade.java +++ b/Essentials2Compat/src/com/earth2me/essentials/EssentialsUpgrade.java @@ -1,12 +1,13 @@ package com.earth2me.essentials; -import com.earth2me.essentials.economy.WorthHolder; -import com.earth2me.essentials.storage.ManagedFile; -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.settings.Spawns; -import com.earth2me.essentials.storage.Location; -import com.earth2me.essentials.storage.YamlStorageWriter; +import net.ess3.economy.WorthHolder; +import net.ess3.Warps; +import net.ess3.storage.ManagedFile; +import static net.ess3.I18n._; +import net.ess3.api.IEssentials; +import net.ess3.settings.Spawns; +import net.ess3.storage.Location; +import net.ess3.storage.YamlStorageWriter; import java.io.*; import java.math.BigInteger; import java.security.DigestInputStream; @@ -658,7 +659,7 @@ public class EssentialsUpgrade config.load(); if (!config.hasProperty("jails")) { - final com.earth2me.essentials.settings.Jails jails = new com.earth2me.essentials.settings.Jails(); + final net.ess3.settings.Jails jails = new net.ess3.settings.Jails(); Set keys = config.getKeys(false); for (String jailName : keys) { 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 663c451c6..000000000 --- a/Essentials2Compat/src/com/earth2me/essentials/api/Economy.java +++ /dev/null @@ -1,242 +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); - } -} diff --git a/Essentials2Compat/src/plugin.yml b/Essentials2Compat/src/plugin.yml index 5610b82a4..bc721f650 100644 --- a/Essentials2Compat/src/plugin.yml +++ b/Essentials2Compat/src/plugin.yml @@ -1,5 +1,5 @@ name: Essentials -main: com.earth2me.essentials.Essentials +main: net.ess3.Essentials version: 2.9 website: http://tiny.cc/EssentialsWiki description: Compatibility plugin for older plugins diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/ChatPermissions.java b/EssentialsChat/src/com/earth2me/essentials/chat/ChatPermissions.java deleted file mode 100644 index 43142915f..000000000 --- a/EssentialsChat/src/com/earth2me/essentials/chat/ChatPermissions.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.earth2me.essentials.chat; - -import com.earth2me.essentials.api.IPermission; -import com.earth2me.essentials.permissions.BasePermission; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - - -public class ChatPermissions -{ - 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.chat.", groupName.toLowerCase(Locale.ENGLISH)); - permissions.put(groupName, perm); - } - return perm; - } -} diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/ChatStore.java b/EssentialsChat/src/com/earth2me/essentials/chat/ChatStore.java deleted file mode 100644 index f01ada07b..000000000 --- a/EssentialsChat/src/com/earth2me/essentials/chat/ChatStore.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.earth2me.essentials.chat; - -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.economy.Trade; - - -public class ChatStore -{ - private final transient IUser user; - private final transient String type; - private final transient Trade charge; - - public ChatStore(final IEssentials ess, final IUser user, final String type) - { - this.user = user; - this.type = type; - this.charge = new Trade(getLongType(), ess); - } - - public IUser getUser() - { - return user; - } - - public Trade getCharge() - { - return charge; - } - - public String getType() - { - return type; - } - - public final String getLongType() - { - return type.length() == 0 ? "chat" : "chat-" + type; - } -} diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChat.java b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChat.java deleted file mode 100644 index 1ff0d6f41..000000000 --- a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChat.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.earth2me.essentials.chat; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.chat.listenerlevel.EssentialsChatPlayerListenerHighest; -import com.earth2me.essentials.chat.listenerlevel.EssentialsChatPlayerListenerLowest; -import com.earth2me.essentials.chat.listenerlevel.EssentialsChatPlayerListenerNormal; -import java.util.HashMap; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.bukkit.event.player.PlayerChatEvent; -import org.bukkit.plugin.PluginManager; -import org.bukkit.plugin.java.JavaPlugin; - - -public class EssentialsChat extends JavaPlugin -{ - private static final Logger LOGGER = Logger.getLogger("Minecraft"); - - @Override - public void onEnable() - { - final PluginManager pluginManager = getServer().getPluginManager(); - final IEssentials ess = (IEssentials)pluginManager.getPlugin("Essentials3"); - if (!this.getDescription().getVersion().equals(ess.getDescription().getVersion())) - { - LOGGER.log(Level.WARNING, _("versionMismatchAll")); - } - if (!ess.isEnabled()) - { - this.setEnabled(false); - return; - } - - final Map chatStore = new HashMap(); - - final EssentialsChatPlayerListenerLowest playerListenerLowest = new EssentialsChatPlayerListenerLowest(getServer(), ess, chatStore); - final EssentialsChatPlayerListenerNormal playerListenerNormal = new EssentialsChatPlayerListenerNormal(getServer(), ess, chatStore); - final EssentialsChatPlayerListenerHighest playerListenerHighest = new EssentialsChatPlayerListenerHighest(getServer(), ess, chatStore); - pluginManager.registerEvents(playerListenerLowest, this); - pluginManager.registerEvents(playerListenerNormal, this); - pluginManager.registerEvents(playerListenerHighest, this); - - final EssentialsLocalChatEventListener localChatListener = new EssentialsLocalChatEventListener(getServer(), ess); - pluginManager.registerEvents(localChatListener, this); - } -} diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayer.java b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayer.java deleted file mode 100644 index fcd9d7e01..000000000 --- a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayer.java +++ /dev/null @@ -1,159 +0,0 @@ -package com.earth2me.essentials.chat; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.ChargeException; -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.economy.Trade; -import com.earth2me.essentials.permissions.Permissions; -import com.earth2me.essentials.utils.Util; -import java.util.Locale; -import java.util.Map; -import java.util.logging.Logger; -import org.bukkit.Server; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerChatEvent; - -//TODO: Translate the local/spy tags -public abstract class EssentialsChatPlayer implements Listener -{ - protected transient IEssentials ess; - protected final static Logger LOGGER = Logger.getLogger("Minecraft"); - protected final transient Server server; - protected final transient Map chatStorage; - - public EssentialsChatPlayer(final Server server, - final IEssentials ess, - final Map chatStorage) - { - this.ess = ess; - this.server = server; - this.chatStorage = chatStorage; - } - - public void onPlayerChat(final PlayerChatEvent event) - { - } - - public ChatStore getChatStore(final PlayerChatEvent event) - { - return chatStorage.get(event); - } - - public void setChatStore(final PlayerChatEvent event, final ChatStore chatStore) - { - chatStorage.put(event, chatStore); - } - - public ChatStore delChatStore(final PlayerChatEvent event) - { - return chatStorage.remove(event); - } - - protected void chargeChat(final PlayerChatEvent event, final ChatStore chatStore) - { - try - { - charge(chatStore.getUser(), chatStore.getCharge()); - } - catch (ChargeException e) - { - ess.getCommandHandler().showCommandError(chatStore.getUser(), chatStore.getLongType(), e); - event.setCancelled(true); - } - } - - protected void charge(final CommandSender sender, final Trade charge) throws ChargeException - { - if (sender instanceof Player) - { - charge.charge(ess.getUser((Player)sender)); - } - } - - protected void formatChat(final PlayerChatEvent event, final ChatStore chatStore) - { - final IUser user = chatStore.getUser(); - if (Permissions.CHAT_COLOR.isAuthorized(user)) - { - event.setMessage(Util.stripColor(event.getMessage())); - } - String group = ess.getRanks().getMainGroup(user); - String world = user.getWorld().getName(); - - IRanks groupSettings = ess.getRanks(); - event.setFormat(groupSettings.getChatFormat(user).format(new Object[] - { - group, world, world.substring(0, 1).toUpperCase(Locale.ENGLISH) - })); - - } - - //TODO: Flesh this out - '?' trigger is too easily accidentally triggered - protected String getChatType(final String message) - { - switch (message.charAt(0)) - { - case '!': - return "shout"; - //case '?': - //return "question"; - //case '@': - // return "admin"; - default: - return ""; - } - } - - protected void handleLocalChat(final PlayerChatEvent event, final ChatStore chatStore) - { - - long radius = 0; - ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - try - { - radius = settings.getData().getChat().getLocalRadius(); - } - finally - { - settings.unlock(); - } - - if (radius < 1) - { - return; - } - - radius *= radius; - - final IUser user = chatStore.getUser(); - - if (event.getMessage().length() > 1 && chatStore.getType().length() > 0) - { - if (ChatPermissions.getPermission(chatStore.getType()).isAuthorized(user)) - { - final StringBuilder format = new StringBuilder(); - format.append(chatStore.getType()).append("Format"); - event.setMessage(event.getMessage().substring(1)); - event.setFormat(_(format.toString(), event.getFormat())); - return; - } - - final StringBuilder errorMsg = new StringBuilder(); - errorMsg.append("notAllowedTo").append(chatStore.getType().substring(0, 1).toUpperCase(Locale.ENGLISH)).append(chatStore.getType().substring(1)); - - user.sendMessage(_(errorMsg.toString())); - event.setCancelled(true); - return; - } - - event.setCancelled(true); - final EssentialsLocalChatEvent localChat = new EssentialsLocalChatEvent(event, radius); - ess.getServer().getPluginManager().callEvent(localChat); - } -} diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsLocalChatEvent.java b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsLocalChatEvent.java deleted file mode 100644 index 4ca1a4496..000000000 --- a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsLocalChatEvent.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.earth2me.essentials.chat; - -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerChatEvent; - - -public class EssentialsLocalChatEvent extends Event implements Cancellable -{ - private Player player; - private String message; - private String format = "<%1$s> %2$s"; - private long radius; - private boolean cancelled = false; - private PlayerChatEvent parentEvent = null; - private static final HandlerList handlers = new HandlerList(); - - public EssentialsLocalChatEvent(final Player player, final String message, final String format, final long radius) - { - this.player = player; - this.message = message; - this.format = format; - this.radius = radius; - } - - public EssentialsLocalChatEvent(final PlayerChatEvent event, final long radius) - { - this(event.getPlayer(), event.getMessage(), event.getFormat(), radius); - this.parentEvent = event; - } - - @Override - public boolean isCancelled() - { - return cancelled; - } - - @Override - public void setCancelled(final boolean cancel) - { - this.cancelled = cancel; - } - - public String getMessage() - { - return message; - } - - public void setMessage(final String message) - { - this.message = message; - } - - public void setPlayer(final Player player) - { - this.player = player; - } - - public Player getPlayer() - { - return player; - } - - public String getFormat() - { - return format; - } - - public void setFormat(final String format) - { - // Oh for a better way to do this! - try - { - String.format(format, player, message); - } - catch (RuntimeException ex) - { - ex.fillInStackTrace(); - throw ex; - } - this.format = format; - } - - public long getRadius() - { - return radius; - } - - public void setRadius(final long radius) - { - this.radius = radius; - } - - public PlayerChatEvent getParentEvent() - { - return parentEvent; - } - - @Override - public HandlerList getHandlers() - { - return handlers; - } - - public static HandlerList getHandlerList() - { - return handlers; - } -} diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsLocalChatEventListener.java b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsLocalChatEventListener.java deleted file mode 100644 index db596b15f..000000000 --- a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsLocalChatEventListener.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.earth2me.essentials.chat; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IUser; -import org.bukkit.Location; -import org.bukkit.Server; -import org.bukkit.World; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; - - -public class EssentialsLocalChatEventListener implements Listener -{ - protected transient IEssentials ess; - protected final transient Server server; - - public EssentialsLocalChatEventListener(final Server server, final IEssentials ess) - { - this.ess = ess; - this.server = server; - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onLocalChat(final EssentialsLocalChatEvent event) - { - final Player sender = event.getPlayer(); - final Location loc = sender.getLocation(); - final World world = loc.getWorld(); - - for (Player onlinePlayer : server.getOnlinePlayers()) - { - String type = _("chatTypeLocal"); - final IUser user = ess.getUser(onlinePlayer); - if (user.isIgnoringPlayer(ess.getUser(sender))) - { - continue; - } - if (!user.equals(sender)) - { - boolean abort = false; - final Location playerLoc = user.getLocation(); - if (playerLoc.getWorld() != world) - { - abort = true; - } - final double delta = playerLoc.distanceSquared(loc); - - if (delta > event.getRadius()) - { - abort = true; - } - - if (abort) - { - if (ChatPermissions.getPermission("spy").isAuthorized(user)) - { - type = type.concat(_("chatTypeSpy")); - } - } - } - final String message = type.concat(String.format(event.getFormat(), sender.getDisplayName(), event.getMessage())); - user.sendMessage(message); - } - } -} diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/listenerlevel/EssentialsChatPlayerListenerHighest.java b/EssentialsChat/src/com/earth2me/essentials/chat/listenerlevel/EssentialsChatPlayerListenerHighest.java deleted file mode 100644 index 576c93e6f..000000000 --- a/EssentialsChat/src/com/earth2me/essentials/chat/listenerlevel/EssentialsChatPlayerListenerHighest.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.earth2me.essentials.chat.listenerlevel; - -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.chat.ChatStore; -import com.earth2me.essentials.chat.EssentialsChatPlayer; -import java.util.Map; -import org.bukkit.Server; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.player.PlayerChatEvent; - - -public class EssentialsChatPlayerListenerHighest extends EssentialsChatPlayer -{ - public EssentialsChatPlayerListenerHighest(final Server server, - final IEssentials ess, - final Map chatStorage) - { - super(server, ess, chatStorage); - } - - @EventHandler(priority = EventPriority.HIGHEST) - @Override - public void onPlayerChat(final PlayerChatEvent event) - { - final ChatStore chatStore = delChatStore(event); - if (event.isCancelled()) - { - return; - } - chargeChat(event, chatStore); - } -} diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/listenerlevel/EssentialsChatPlayerListenerLowest.java b/EssentialsChat/src/com/earth2me/essentials/chat/listenerlevel/EssentialsChatPlayerListenerLowest.java deleted file mode 100644 index 3fcff995c..000000000 --- a/EssentialsChat/src/com/earth2me/essentials/chat/listenerlevel/EssentialsChatPlayerListenerLowest.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.earth2me.essentials.chat.listenerlevel; - -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.chat.ChatStore; -import com.earth2me.essentials.chat.EssentialsChatPlayer; -import java.util.Map; -import org.bukkit.Server; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.player.PlayerChatEvent; - - -public class EssentialsChatPlayerListenerLowest extends EssentialsChatPlayer -{ - public EssentialsChatPlayerListenerLowest(final Server server, - final IEssentials ess, - final Map chatStorage) - { - super(server, ess, chatStorage); - } - - @EventHandler(priority = EventPriority.LOWEST) - @Override - public void onPlayerChat(final PlayerChatEvent event) - { - if (event.isCancelled()) - { - return; - } - final IUser user = ess.getUser(event.getPlayer()); - final ChatStore chatStore = new ChatStore(ess, user, getChatType(event.getMessage())); - setChatStore(event, chatStore); - formatChat(event, chatStore); - } -} \ No newline at end of file diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/listenerlevel/EssentialsChatPlayerListenerNormal.java b/EssentialsChat/src/com/earth2me/essentials/chat/listenerlevel/EssentialsChatPlayerListenerNormal.java deleted file mode 100644 index c456b700d..000000000 --- a/EssentialsChat/src/com/earth2me/essentials/chat/listenerlevel/EssentialsChatPlayerListenerNormal.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.earth2me.essentials.chat.listenerlevel; - -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.chat.ChatStore; -import com.earth2me.essentials.chat.EssentialsChatPlayer; -import java.util.Map; -import org.bukkit.Server; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.player.PlayerChatEvent; - - -public class EssentialsChatPlayerListenerNormal extends EssentialsChatPlayer -{ - public EssentialsChatPlayerListenerNormal(final Server server, - final IEssentials ess, - final Map chatStorage) - { - super(server, ess, chatStorage); - } - - @EventHandler(priority = EventPriority.NORMAL) - @Override - public void onPlayerChat(final PlayerChatEvent event) - { - if (event.isCancelled()) - { - return; - } - final ChatStore chatStore = getChatStore(event); - handleLocalChat(event, chatStore); - } -} diff --git a/EssentialsChat/src/net/ess3/chat/ChatPermissions.java b/EssentialsChat/src/net/ess3/chat/ChatPermissions.java new file mode 100644 index 000000000..888b85f9d --- /dev/null +++ b/EssentialsChat/src/net/ess3/chat/ChatPermissions.java @@ -0,0 +1,24 @@ +package net.ess3.chat; + +import net.ess3.api.IPermission; +import net.ess3.permissions.BasePermission; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + + +public class ChatPermissions +{ + 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.chat.", groupName.toLowerCase(Locale.ENGLISH)); + permissions.put(groupName, perm); + } + return perm; + } +} diff --git a/EssentialsChat/src/net/ess3/chat/ChatStore.java b/EssentialsChat/src/net/ess3/chat/ChatStore.java new file mode 100644 index 000000000..4d696fb36 --- /dev/null +++ b/EssentialsChat/src/net/ess3/chat/ChatStore.java @@ -0,0 +1,40 @@ +package net.ess3.chat; + +import net.ess3.api.IEssentials; +import net.ess3.api.IUser; +import net.ess3.economy.Trade; + + +public class ChatStore +{ + private final transient IUser user; + private final transient String type; + private final transient Trade charge; + + public ChatStore(final IEssentials ess, final IUser user, final String type) + { + this.user = user; + this.type = type; + this.charge = new Trade(getLongType(), ess); + } + + public IUser getUser() + { + return user; + } + + public Trade getCharge() + { + return charge; + } + + public String getType() + { + return type; + } + + public final String getLongType() + { + return type.length() == 0 ? "chat" : "chat-" + type; + } +} diff --git a/EssentialsChat/src/net/ess3/chat/EssentialsChat.java b/EssentialsChat/src/net/ess3/chat/EssentialsChat.java new file mode 100644 index 000000000..4c922c45f --- /dev/null +++ b/EssentialsChat/src/net/ess3/chat/EssentialsChat.java @@ -0,0 +1,48 @@ +package net.ess3.chat; + +import static net.ess3.I18n._; +import net.ess3.api.IEssentials; +import net.ess3.chat.listenerlevel.EssentialsChatPlayerListenerHighest; +import net.ess3.chat.listenerlevel.EssentialsChatPlayerListenerLowest; +import net.ess3.chat.listenerlevel.EssentialsChatPlayerListenerNormal; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.bukkit.event.player.PlayerChatEvent; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + + +public class EssentialsChat extends JavaPlugin +{ + private static final Logger LOGGER = Logger.getLogger("Minecraft"); + + @Override + public void onEnable() + { + final PluginManager pluginManager = getServer().getPluginManager(); + final IEssentials ess = (IEssentials)pluginManager.getPlugin("Essentials-3"); + if (!this.getDescription().getVersion().equals(ess.getDescription().getVersion())) + { + LOGGER.log(Level.WARNING, _("versionMismatchAll")); + } + if (!ess.isEnabled()) + { + this.setEnabled(false); + return; + } + + final Map chatStore = new HashMap(); + + final EssentialsChatPlayerListenerLowest playerListenerLowest = new EssentialsChatPlayerListenerLowest(getServer(), ess, chatStore); + final EssentialsChatPlayerListenerNormal playerListenerNormal = new EssentialsChatPlayerListenerNormal(getServer(), ess, chatStore); + final EssentialsChatPlayerListenerHighest playerListenerHighest = new EssentialsChatPlayerListenerHighest(getServer(), ess, chatStore); + pluginManager.registerEvents(playerListenerLowest, this); + pluginManager.registerEvents(playerListenerNormal, this); + pluginManager.registerEvents(playerListenerHighest, this); + + final EssentialsLocalChatEventListener localChatListener = new EssentialsLocalChatEventListener(getServer(), ess); + pluginManager.registerEvents(localChatListener, this); + } +} diff --git a/EssentialsChat/src/net/ess3/chat/EssentialsChatPlayer.java b/EssentialsChat/src/net/ess3/chat/EssentialsChatPlayer.java new file mode 100644 index 000000000..ae8fce4a1 --- /dev/null +++ b/EssentialsChat/src/net/ess3/chat/EssentialsChatPlayer.java @@ -0,0 +1,159 @@ +package net.ess3.chat; + +import static net.ess3.I18n._; +import net.ess3.api.ChargeException; +import net.ess3.api.IEssentials; +import net.ess3.api.IRanks; +import net.ess3.api.ISettings; +import net.ess3.api.IUser; +import net.ess3.economy.Trade; +import net.ess3.permissions.Permissions; +import net.ess3.utils.Util; +import java.util.Locale; +import java.util.Map; +import java.util.logging.Logger; +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerChatEvent; + +//TODO: Translate the local/spy tags +public abstract class EssentialsChatPlayer implements Listener +{ + protected transient IEssentials ess; + protected final static Logger LOGGER = Logger.getLogger("Minecraft"); + protected final transient Server server; + protected final transient Map chatStorage; + + public EssentialsChatPlayer(final Server server, + final IEssentials ess, + final Map chatStorage) + { + this.ess = ess; + this.server = server; + this.chatStorage = chatStorage; + } + + public void onPlayerChat(final PlayerChatEvent event) + { + } + + public ChatStore getChatStore(final PlayerChatEvent event) + { + return chatStorage.get(event); + } + + public void setChatStore(final PlayerChatEvent event, final ChatStore chatStore) + { + chatStorage.put(event, chatStore); + } + + public ChatStore delChatStore(final PlayerChatEvent event) + { + return chatStorage.remove(event); + } + + protected void chargeChat(final PlayerChatEvent event, final ChatStore chatStore) + { + try + { + charge(chatStore.getUser(), chatStore.getCharge()); + } + catch (ChargeException e) + { + ess.getCommandHandler().showCommandError(chatStore.getUser(), chatStore.getLongType(), e); + event.setCancelled(true); + } + } + + protected void charge(final CommandSender sender, final Trade charge) throws ChargeException + { + if (sender instanceof Player) + { + charge.charge(ess.getUser((Player)sender)); + } + } + + protected void formatChat(final PlayerChatEvent event, final ChatStore chatStore) + { + final IUser user = chatStore.getUser(); + if (Permissions.CHAT_COLOR.isAuthorized(user)) + { + event.setMessage(Util.stripColor(event.getMessage())); + } + String group = ess.getRanks().getMainGroup(user); + String world = user.getWorld().getName(); + + IRanks groupSettings = ess.getRanks(); + event.setFormat(groupSettings.getChatFormat(user).format(new Object[] + { + group, world, world.substring(0, 1).toUpperCase(Locale.ENGLISH) + })); + + } + + //TODO: Flesh this out - '?' trigger is too easily accidentally triggered + protected String getChatType(final String message) + { + switch (message.charAt(0)) + { + case '!': + return "shout"; + //case '?': + //return "question"; + //case '@': + // return "admin"; + default: + return ""; + } + } + + protected void handleLocalChat(final PlayerChatEvent event, final ChatStore chatStore) + { + + long radius = 0; + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + try + { + radius = settings.getData().getChat().getLocalRadius(); + } + finally + { + settings.unlock(); + } + + if (radius < 1) + { + return; + } + + radius *= radius; + + final IUser user = chatStore.getUser(); + + if (event.getMessage().length() > 1 && chatStore.getType().length() > 0) + { + if (ChatPermissions.getPermission(chatStore.getType()).isAuthorized(user)) + { + final StringBuilder format = new StringBuilder(); + format.append(chatStore.getType()).append("Format"); + event.setMessage(event.getMessage().substring(1)); + event.setFormat(_(format.toString(), event.getFormat())); + return; + } + + final StringBuilder errorMsg = new StringBuilder(); + errorMsg.append("notAllowedTo").append(chatStore.getType().substring(0, 1).toUpperCase(Locale.ENGLISH)).append(chatStore.getType().substring(1)); + + user.sendMessage(_(errorMsg.toString())); + event.setCancelled(true); + return; + } + + event.setCancelled(true); + final EssentialsLocalChatEvent localChat = new EssentialsLocalChatEvent(event, radius); + ess.getServer().getPluginManager().callEvent(localChat); + } +} diff --git a/EssentialsChat/src/net/ess3/chat/EssentialsLocalChatEvent.java b/EssentialsChat/src/net/ess3/chat/EssentialsLocalChatEvent.java new file mode 100644 index 000000000..e0ce6602d --- /dev/null +++ b/EssentialsChat/src/net/ess3/chat/EssentialsLocalChatEvent.java @@ -0,0 +1,111 @@ +package net.ess3.chat; + +import org.bukkit.entity.Player; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.bukkit.event.player.PlayerChatEvent; + + +public class EssentialsLocalChatEvent extends Event implements Cancellable +{ + private Player player; + private String message; + private String format = "<%1$s> %2$s"; + private long radius; + private boolean cancelled = false; + private PlayerChatEvent parentEvent = null; + private static final HandlerList handlers = new HandlerList(); + + public EssentialsLocalChatEvent(final Player player, final String message, final String format, final long radius) + { + this.player = player; + this.message = message; + this.format = format; + this.radius = radius; + } + + public EssentialsLocalChatEvent(final PlayerChatEvent event, final long radius) + { + this(event.getPlayer(), event.getMessage(), event.getFormat(), radius); + this.parentEvent = event; + } + + @Override + public boolean isCancelled() + { + return cancelled; + } + + @Override + public void setCancelled(final boolean cancel) + { + this.cancelled = cancel; + } + + public String getMessage() + { + return message; + } + + public void setMessage(final String message) + { + this.message = message; + } + + public void setPlayer(final Player player) + { + this.player = player; + } + + public Player getPlayer() + { + return player; + } + + public String getFormat() + { + return format; + } + + public void setFormat(final String format) + { + // Oh for a better way to do this! + try + { + String.format(format, player, message); + } + catch (RuntimeException ex) + { + ex.fillInStackTrace(); + throw ex; + } + this.format = format; + } + + public long getRadius() + { + return radius; + } + + public void setRadius(final long radius) + { + this.radius = radius; + } + + public PlayerChatEvent getParentEvent() + { + return parentEvent; + } + + @Override + public HandlerList getHandlers() + { + return handlers; + } + + public static HandlerList getHandlerList() + { + return handlers; + } +} diff --git a/EssentialsChat/src/net/ess3/chat/EssentialsLocalChatEventListener.java b/EssentialsChat/src/net/ess3/chat/EssentialsLocalChatEventListener.java new file mode 100644 index 000000000..29bd7e8e8 --- /dev/null +++ b/EssentialsChat/src/net/ess3/chat/EssentialsLocalChatEventListener.java @@ -0,0 +1,68 @@ +package net.ess3.chat; + +import static net.ess3.I18n._; +import net.ess3.api.IEssentials; +import net.ess3.api.IUser; +import org.bukkit.Location; +import org.bukkit.Server; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; + + +public class EssentialsLocalChatEventListener implements Listener +{ + protected transient IEssentials ess; + protected final transient Server server; + + public EssentialsLocalChatEventListener(final Server server, final IEssentials ess) + { + this.ess = ess; + this.server = server; + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onLocalChat(final EssentialsLocalChatEvent event) + { + final Player sender = event.getPlayer(); + final Location loc = sender.getLocation(); + final World world = loc.getWorld(); + + for (Player onlinePlayer : server.getOnlinePlayers()) + { + String type = _("chatTypeLocal"); + final IUser user = ess.getUser(onlinePlayer); + if (user.isIgnoringPlayer(ess.getUser(sender))) + { + continue; + } + if (!user.equals(sender)) + { + boolean abort = false; + final Location playerLoc = user.getLocation(); + if (playerLoc.getWorld() != world) + { + abort = true; + } + final double delta = playerLoc.distanceSquared(loc); + + if (delta > event.getRadius()) + { + abort = true; + } + + if (abort) + { + if (ChatPermissions.getPermission("spy").isAuthorized(user)) + { + type = type.concat(_("chatTypeSpy")); + } + } + } + final String message = type.concat(String.format(event.getFormat(), sender.getDisplayName(), event.getMessage())); + user.sendMessage(message); + } + } +} diff --git a/EssentialsChat/src/net/ess3/chat/listenerlevel/EssentialsChatPlayerListenerHighest.java b/EssentialsChat/src/net/ess3/chat/listenerlevel/EssentialsChatPlayerListenerHighest.java new file mode 100644 index 000000000..21f3a188e --- /dev/null +++ b/EssentialsChat/src/net/ess3/chat/listenerlevel/EssentialsChatPlayerListenerHighest.java @@ -0,0 +1,34 @@ +package net.ess3.chat.listenerlevel; + +import net.ess3.api.IEssentials; +import net.ess3.chat.ChatStore; +import net.ess3.chat.ChatStore; +import net.ess3.chat.EssentialsChatPlayer; +import java.util.Map; +import org.bukkit.Server; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.player.PlayerChatEvent; + + +public class EssentialsChatPlayerListenerHighest extends EssentialsChatPlayer +{ + public EssentialsChatPlayerListenerHighest(final Server server, + final IEssentials ess, + final Map chatStorage) + { + super(server, ess, chatStorage); + } + + @EventHandler(priority = EventPriority.HIGHEST) + @Override + public void onPlayerChat(final PlayerChatEvent event) + { + final ChatStore chatStore = delChatStore(event); + if (event.isCancelled()) + { + return; + } + chargeChat(event, chatStore); + } +} diff --git a/EssentialsChat/src/net/ess3/chat/listenerlevel/EssentialsChatPlayerListenerLowest.java b/EssentialsChat/src/net/ess3/chat/listenerlevel/EssentialsChatPlayerListenerLowest.java new file mode 100644 index 000000000..eb75e3680 --- /dev/null +++ b/EssentialsChat/src/net/ess3/chat/listenerlevel/EssentialsChatPlayerListenerLowest.java @@ -0,0 +1,38 @@ +package net.ess3.chat.listenerlevel; + +import net.ess3.api.IEssentials; +import net.ess3.api.IUser; +import net.ess3.chat.ChatStore; +import net.ess3.chat.EssentialsChatPlayer; +import java.util.Map; + +import net.ess3.chat.EssentialsChatPlayer; +import org.bukkit.Server; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.player.PlayerChatEvent; + + +public class EssentialsChatPlayerListenerLowest extends EssentialsChatPlayer +{ + public EssentialsChatPlayerListenerLowest(final Server server, + final IEssentials ess, + final Map chatStorage) + { + super(server, ess, chatStorage); + } + + @EventHandler(priority = EventPriority.LOWEST) + @Override + public void onPlayerChat(final PlayerChatEvent event) + { + if (event.isCancelled()) + { + return; + } + final IUser user = ess.getUser(event.getPlayer()); + final ChatStore chatStore = new ChatStore(ess, user, getChatType(event.getMessage())); + setChatStore(event, chatStore); + formatChat(event, chatStore); + } +} \ No newline at end of file diff --git a/EssentialsChat/src/net/ess3/chat/listenerlevel/EssentialsChatPlayerListenerNormal.java b/EssentialsChat/src/net/ess3/chat/listenerlevel/EssentialsChatPlayerListenerNormal.java new file mode 100644 index 000000000..2e3b44549 --- /dev/null +++ b/EssentialsChat/src/net/ess3/chat/listenerlevel/EssentialsChatPlayerListenerNormal.java @@ -0,0 +1,33 @@ +package net.ess3.chat.listenerlevel; + +import net.ess3.api.IEssentials; +import net.ess3.chat.ChatStore; +import net.ess3.chat.EssentialsChatPlayer; +import java.util.Map; +import org.bukkit.Server; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.player.PlayerChatEvent; + + +public class EssentialsChatPlayerListenerNormal extends EssentialsChatPlayer +{ + public EssentialsChatPlayerListenerNormal(final Server server, + final IEssentials ess, + final Map chatStorage) + { + super(server, ess, chatStorage); + } + + @EventHandler(priority = EventPriority.NORMAL) + @Override + public void onPlayerChat(final PlayerChatEvent event) + { + if (event.isCancelled()) + { + return; + } + final ChatStore chatStore = getChatStore(event); + handleLocalChat(event, chatStore); + } +} diff --git a/EssentialsChat/src/plugin.yml b/EssentialsChat/src/plugin.yml index 0d54428e3..6e314cbbb 100644 --- a/EssentialsChat/src/plugin.yml +++ b/EssentialsChat/src/plugin.yml @@ -1,6 +1,6 @@ # This determines the command prefix when there are conflicts (/name:home, /name:help, etc.) name: EssentialsChat -main: com.earth2me.essentials.chat.EssentialsChat +main: net.ess3.chat.EssentialsChat # Note to developers: This next line cannot change, or the automatic versioning system will break. version: ${build.number} website: http://tiny.cc/EssentialsWiki diff --git a/EssentialsGeoIP/src/com/earth2me/essentials/geoip/ConfigHolder.java b/EssentialsGeoIP/src/com/earth2me/essentials/geoip/ConfigHolder.java deleted file mode 100644 index 183c591ab..000000000 --- a/EssentialsGeoIP/src/com/earth2me/essentials/geoip/ConfigHolder.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.earth2me.essentials.geoip; - -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.settings.geoip.GeoIP; -import com.earth2me.essentials.storage.AsyncStorageObjectHolder; -import java.io.File; -import java.io.IOException; -import org.bukkit.plugin.Plugin; - - -public class ConfigHolder extends AsyncStorageObjectHolder -{ - private final transient Plugin geoip; - - public ConfigHolder(final IEssentials ess, final Plugin geoip) - { - super(ess, GeoIP.class); - this.geoip = geoip; - onReload(); - } - - @Override - public File getStorageFile() throws IOException - { - return new File(geoip.getDataFolder(), "config.yml"); - } - - @Override - public void finishRead() - { - } - - @Override - public void finishWrite() - { - } -} diff --git a/EssentialsGeoIP/src/com/earth2me/essentials/geoip/EssentialsGeoIP.java b/EssentialsGeoIP/src/com/earth2me/essentials/geoip/EssentialsGeoIP.java deleted file mode 100644 index 43b4959da..000000000 --- a/EssentialsGeoIP/src/com/earth2me/essentials/geoip/EssentialsGeoIP.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.earth2me.essentials.geoip; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IEssentials; -import java.util.logging.Level; -import org.bukkit.plugin.PluginManager; -import org.bukkit.plugin.java.JavaPlugin; - - -public class EssentialsGeoIP extends JavaPlugin -{ - @Override - public void onEnable() - { - final PluginManager pm = getServer().getPluginManager(); - final IEssentials ess = (IEssentials)pm.getPlugin("Essentials3"); - if (!this.getDescription().getVersion().equals(ess.getDescription().getVersion())) - { - getLogger().log(Level.WARNING, _("versionMismatchAll")); - } - if (!ess.isEnabled()) - { - this.setEnabled(false); - return; - } - final EssentialsGeoIPPlayerListener playerListener = new EssentialsGeoIPPlayerListener(this, ess); - pm.registerEvents(playerListener, this); - ess.addReloadListener(playerListener); - - getLogger().log(Level.INFO, "This product includes GeoLite data created by MaxMind, available from http://www.maxmind.com/."); - } -} diff --git a/EssentialsGeoIP/src/com/earth2me/essentials/geoip/EssentialsGeoIPPlayerListener.java b/EssentialsGeoIP/src/com/earth2me/essentials/geoip/EssentialsGeoIPPlayerListener.java deleted file mode 100644 index 158457155..000000000 --- a/EssentialsGeoIP/src/com/earth2me/essentials/geoip/EssentialsGeoIPPlayerListener.java +++ /dev/null @@ -1,225 +0,0 @@ -package com.earth2me.essentials.geoip; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IReload; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.permissions.Permissions; -import com.maxmind.geoip.Location; -import com.maxmind.geoip.LookupService; -import com.maxmind.geoip.regionName; -import java.io.*; -import java.net.InetAddress; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLConnection; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.zip.GZIPInputStream; -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.Plugin; - - -public class EssentialsGeoIPPlayerListener implements Listener, IReload -{ - private transient LookupService ls = null; - private static final Logger LOGGER = Logger.getLogger("Minecraft"); - private transient File databaseFile; - private final transient ConfigHolder config; - private final transient IEssentials ess; - private final transient Plugin geoip; - - public EssentialsGeoIPPlayerListener(final Plugin geoip, final IEssentials ess) - { - super(); - this.ess = ess; - this.geoip = geoip; - this.config = new ConfigHolder(ess, geoip); - onReload(); - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onPlayerJoin(final PlayerJoinEvent event) - { - final IUser u = ess.getUser(event.getPlayer()); - if (Permissions.GEOIP_HIDE.isAuthorized(u)) - { - return; - } - config.acquireReadLock(); - try - { - final InetAddress address = event.getPlayer().getAddress().getAddress(); - final StringBuilder builder = new StringBuilder(); - if (config.getData().getDatabase().isShowCities()) - { - final Location loc = ls.getLocation(address); - if (loc == null) - { - return; - } - if (loc.city != null) - { - builder.append(loc.city).append(", "); - } - final String region = regionName.regionNameByCode(loc.countryCode, loc.region); - if (region != null) - { - builder.append(region).append(", "); - } - builder.append(loc.countryName); - } - else - { - builder.append(ls.getCountry(address).getName()); - } - if (config.getData().isShowOnWhois()) - { - u.acquireWriteLock(); - try - { - u.getData().setGeolocation(builder.toString()); - } - finally - { - u.unlock(); - } - } - if (config.getData().isShowOnLogin() && !u.isHidden()) - { - for (Player player : event.getPlayer().getServer().getOnlinePlayers()) - { - final IUser user = ess.getUser(player); - if (Permissions.GEOIP_SHOW.isAuthorized(user)) - { - user.sendMessage(_("geoipJoinFormat", user.getDisplayName(), builder.toString())); - } - } - } - } - finally - { - config.unlock(); - } - } - - @Override - public final void onReload() - { - config.onReload(); - config.acquireReadLock(); - try - { - if (config.getData().getDatabase().isShowCities()) - { - databaseFile = new File(geoip.getDataFolder(), "GeoIPCity.dat"); - } - else - { - databaseFile = new File(geoip.getDataFolder(), "GeoIP.dat"); - } - if (!databaseFile.exists()) - { - if (config.getData().getDatabase().isDownloadIfMissing()) - { - if (config.getData().getDatabase().isShowCities()) - { - downloadDatabase(config.getData().getDatabase().getDownloadUrlCity()); - } - else - { - downloadDatabase(config.getData().getDatabase().getDownloadUrl()); - } - } - else - { - LOGGER.log(Level.SEVERE, _("cantFindGeoIpDB")); - return; - } - } - try - { - ls = new LookupService(databaseFile); - } - catch (IOException ex) - { - LOGGER.log(Level.SEVERE, _("cantReadGeoIpDB"), ex); - } - } - finally - { - config.unlock(); - } - } - - private void downloadDatabase(final String url) - { - if (url == null || url.isEmpty()) - { - LOGGER.log(Level.SEVERE, _("geoIpUrlEmpty")); - return; - } - InputStream input = null; - OutputStream output = null; - try - { - LOGGER.log(Level.INFO, _("downloadingGeoIp")); - final URL downloadUrl = new URL(url); - final URLConnection conn = downloadUrl.openConnection(); - conn.setConnectTimeout(10000); - conn.connect(); - input = conn.getInputStream(); - if (url.endsWith(".gz")) - { - input = new GZIPInputStream(input); - } - output = new FileOutputStream(databaseFile); - final byte[] buffer = new byte[2048]; - int length = input.read(buffer); - while (length >= 0) - { - output.write(buffer, 0, length); - length = input.read(buffer); - } - input.close(); - output.close(); - } - catch (MalformedURLException ex) - { - LOGGER.log(Level.SEVERE, _("geoIpUrlInvalid"), ex); - } - catch (IOException ex) - { - LOGGER.log(Level.SEVERE, _("connectionFailed"), ex); - } - finally - { - if (output != null) - { - try - { - output.close(); - } - catch (IOException ex) - { - LOGGER.log(Level.SEVERE, _("connectionFailed"), ex); - } - } - if (input != null) - { - try - { - input.close(); - } - catch (IOException ex) - { - LOGGER.log(Level.SEVERE, _("connectionFailed"), ex); - } - } - } - } -} diff --git a/EssentialsGeoIP/src/net/ess3/geoip/ConfigHolder.java b/EssentialsGeoIP/src/net/ess3/geoip/ConfigHolder.java new file mode 100644 index 000000000..068a1ba45 --- /dev/null +++ b/EssentialsGeoIP/src/net/ess3/geoip/ConfigHolder.java @@ -0,0 +1,37 @@ +package net.ess3.geoip; + +import net.ess3.api.IEssentials; +import net.ess3.settings.geoip.GeoIP; +import net.ess3.storage.AsyncStorageObjectHolder; +import java.io.File; +import java.io.IOException; +import org.bukkit.plugin.Plugin; + + +public class ConfigHolder extends AsyncStorageObjectHolder +{ + private final transient Plugin geoip; + + public ConfigHolder(final IEssentials ess, final Plugin geoip) + { + super(ess, GeoIP.class); + this.geoip = geoip; + onReload(); + } + + @Override + public File getStorageFile() throws IOException + { + return new File(geoip.getDataFolder(), "config.yml"); + } + + @Override + public void finishRead() + { + } + + @Override + public void finishWrite() + { + } +} diff --git a/EssentialsGeoIP/src/net/ess3/geoip/EssentialsGeoIP.java b/EssentialsGeoIP/src/net/ess3/geoip/EssentialsGeoIP.java new file mode 100644 index 000000000..9767f213b --- /dev/null +++ b/EssentialsGeoIP/src/net/ess3/geoip/EssentialsGeoIP.java @@ -0,0 +1,32 @@ +package net.ess3.geoip; + +import static net.ess3.I18n._; +import net.ess3.api.IEssentials; +import java.util.logging.Level; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + + +public class EssentialsGeoIP extends JavaPlugin +{ + @Override + public void onEnable() + { + final PluginManager pm = getServer().getPluginManager(); + final IEssentials ess = (IEssentials)pm.getPlugin("Essentials-3"); + if (!this.getDescription().getVersion().equals(ess.getDescription().getVersion())) + { + getLogger().log(Level.WARNING, _("versionMismatchAll")); + } + if (!ess.isEnabled()) + { + this.setEnabled(false); + return; + } + final EssentialsGeoIPPlayerListener playerListener = new EssentialsGeoIPPlayerListener(this, ess); + pm.registerEvents(playerListener, this); + ess.addReloadListener(playerListener); + + getLogger().log(Level.INFO, "This product includes GeoLite data created by MaxMind, available from http://www.maxmind.com/."); + } +} diff --git a/EssentialsGeoIP/src/net/ess3/geoip/EssentialsGeoIPPlayerListener.java b/EssentialsGeoIP/src/net/ess3/geoip/EssentialsGeoIPPlayerListener.java new file mode 100644 index 000000000..a6bbeffec --- /dev/null +++ b/EssentialsGeoIP/src/net/ess3/geoip/EssentialsGeoIPPlayerListener.java @@ -0,0 +1,225 @@ +package net.ess3.geoip; + +import static net.ess3.I18n._; +import net.ess3.api.IEssentials; +import net.ess3.api.IReload; +import net.ess3.api.IUser; +import net.ess3.permissions.Permissions; +import com.maxmind.geoip.Location; +import com.maxmind.geoip.LookupService; +import com.maxmind.geoip.regionName; +import java.io.*; +import java.net.InetAddress; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.zip.GZIPInputStream; +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.Plugin; + + +public class EssentialsGeoIPPlayerListener implements Listener, IReload +{ + private transient LookupService ls = null; + private static final Logger LOGGER = Logger.getLogger("Minecraft"); + private transient File databaseFile; + private final transient ConfigHolder config; + private final transient IEssentials ess; + private final transient Plugin geoip; + + public EssentialsGeoIPPlayerListener(final Plugin geoip, final IEssentials ess) + { + super(); + this.ess = ess; + this.geoip = geoip; + this.config = new ConfigHolder(ess, geoip); + onReload(); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerJoin(final PlayerJoinEvent event) + { + final IUser u = ess.getUser(event.getPlayer()); + if (Permissions.GEOIP_HIDE.isAuthorized(u)) + { + return; + } + config.acquireReadLock(); + try + { + final InetAddress address = event.getPlayer().getAddress().getAddress(); + final StringBuilder builder = new StringBuilder(); + if (config.getData().getDatabase().isShowCities()) + { + final Location loc = ls.getLocation(address); + if (loc == null) + { + return; + } + if (loc.city != null) + { + builder.append(loc.city).append(", "); + } + final String region = regionName.regionNameByCode(loc.countryCode, loc.region); + if (region != null) + { + builder.append(region).append(", "); + } + builder.append(loc.countryName); + } + else + { + builder.append(ls.getCountry(address).getName()); + } + if (config.getData().isShowOnWhois()) + { + u.acquireWriteLock(); + try + { + u.getData().setGeolocation(builder.toString()); + } + finally + { + u.unlock(); + } + } + if (config.getData().isShowOnLogin() && !u.isHidden()) + { + for (Player player : event.getPlayer().getServer().getOnlinePlayers()) + { + final IUser user = ess.getUser(player); + if (Permissions.GEOIP_SHOW.isAuthorized(user)) + { + user.sendMessage(_("geoipJoinFormat", user.getDisplayName(), builder.toString())); + } + } + } + } + finally + { + config.unlock(); + } + } + + @Override + public final void onReload() + { + config.onReload(); + config.acquireReadLock(); + try + { + if (config.getData().getDatabase().isShowCities()) + { + databaseFile = new File(geoip.getDataFolder(), "GeoIPCity.dat"); + } + else + { + databaseFile = new File(geoip.getDataFolder(), "GeoIP.dat"); + } + if (!databaseFile.exists()) + { + if (config.getData().getDatabase().isDownloadIfMissing()) + { + if (config.getData().getDatabase().isShowCities()) + { + downloadDatabase(config.getData().getDatabase().getDownloadUrlCity()); + } + else + { + downloadDatabase(config.getData().getDatabase().getDownloadUrl()); + } + } + else + { + LOGGER.log(Level.SEVERE, _("cantFindGeoIpDB")); + return; + } + } + try + { + ls = new LookupService(databaseFile); + } + catch (IOException ex) + { + LOGGER.log(Level.SEVERE, _("cantReadGeoIpDB"), ex); + } + } + finally + { + config.unlock(); + } + } + + private void downloadDatabase(final String url) + { + if (url == null || url.isEmpty()) + { + LOGGER.log(Level.SEVERE, _("geoIpUrlEmpty")); + return; + } + InputStream input = null; + OutputStream output = null; + try + { + LOGGER.log(Level.INFO, _("downloadingGeoIp")); + final URL downloadUrl = new URL(url); + final URLConnection conn = downloadUrl.openConnection(); + conn.setConnectTimeout(10000); + conn.connect(); + input = conn.getInputStream(); + if (url.endsWith(".gz")) + { + input = new GZIPInputStream(input); + } + output = new FileOutputStream(databaseFile); + final byte[] buffer = new byte[2048]; + int length = input.read(buffer); + while (length >= 0) + { + output.write(buffer, 0, length); + length = input.read(buffer); + } + input.close(); + output.close(); + } + catch (MalformedURLException ex) + { + LOGGER.log(Level.SEVERE, _("geoIpUrlInvalid"), ex); + } + catch (IOException ex) + { + LOGGER.log(Level.SEVERE, _("connectionFailed"), ex); + } + finally + { + if (output != null) + { + try + { + output.close(); + } + catch (IOException ex) + { + LOGGER.log(Level.SEVERE, _("connectionFailed"), ex); + } + } + if (input != null) + { + try + { + input.close(); + } + catch (IOException ex) + { + LOGGER.log(Level.SEVERE, _("connectionFailed"), ex); + } + } + } + } +} diff --git a/EssentialsGeoIP/src/plugin.yml b/EssentialsGeoIP/src/plugin.yml index bcc2aa313..709e6d92b 100644 --- a/EssentialsGeoIP/src/plugin.yml +++ b/EssentialsGeoIP/src/plugin.yml @@ -1,6 +1,6 @@ # This determines the command prefix when there are conflicts (/name:home, /name:help, etc.) name: EssentialsGeoIP -main: com.earth2me.essentials.geoip.EssentialsGeoIP +main: net.ess3.geoip.EssentialsGeoIP # Note to developers: This next line cannot change, or the automatic versioning system will break. version: ${build.number} website: http://tiny.cc/EssentialsWiki diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/BlockBreakPermissions.java b/EssentialsProtect/src/com/earth2me/essentials/protect/BlockBreakPermissions.java deleted file mode 100644 index 05a376a03..000000000 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/BlockBreakPermissions.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.earth2me.essentials.protect; - -import com.earth2me.essentials.api.IPermission; -import com.earth2me.essentials.permissions.AbstractSuperpermsPermission; -import java.util.EnumMap; -import java.util.Locale; -import java.util.Map; -import org.bukkit.Material; -import org.bukkit.permissions.PermissionDefault; - - -public final class BlockBreakPermissions extends AbstractSuperpermsPermission -{ - private static Map permissions = new EnumMap(Material.class); - private static final String base = "essentials.protect.blockbreak."; - private final String permission; - - public static IPermission getPermission(final Material mat) - { - IPermission perm = permissions.get(mat); - if (perm == null) - { - perm = new BlockBreakPermissions(mat.toString().toLowerCase(Locale.ENGLISH)); - permissions.put(mat, perm); - } - return perm; - } - - private BlockBreakPermissions(final String matName) - { - super(); - this.permission = base + matName; - } - - @Override - public String getPermission() - { - return this.permission; - } - - @Override - public PermissionDefault getPermissionDefault() - { - return PermissionDefault.TRUE; - } -} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/BlockPlacePermissions.java b/EssentialsProtect/src/com/earth2me/essentials/protect/BlockPlacePermissions.java deleted file mode 100644 index e7a4c29c5..000000000 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/BlockPlacePermissions.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.earth2me.essentials.protect; - -import com.earth2me.essentials.api.IPermission; -import com.earth2me.essentials.permissions.AbstractSuperpermsPermission; -import java.util.EnumMap; -import java.util.Locale; -import java.util.Map; -import org.bukkit.Material; -import org.bukkit.permissions.PermissionDefault; - - -public class BlockPlacePermissions extends AbstractSuperpermsPermission -{ - private static Map permissions = new EnumMap(Material.class); - private static final String base = "essentials.protect.blockplace."; - private final String permission; - - public static IPermission getPermission(final Material mat) - { - IPermission perm = permissions.get(mat); - if (perm == null) - { - perm = new BlockPlacePermissions(mat.toString().toLowerCase(Locale.ENGLISH)); - permissions.put(mat, perm); - } - return perm; - } - - private BlockPlacePermissions(final String matName) - { - super(); - this.permission = base + matName; - } - - @Override - public String getPermission() - { - return this.permission; - } - - @Override - public PermissionDefault getPermissionDefault() - { - return PermissionDefault.TRUE; - } -} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EmergencyListener.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EmergencyListener.java deleted file mode 100644 index 5f9253c55..000000000 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/EmergencyListener.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.earth2me.essentials.protect; - -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.BlockBurnEvent; -import org.bukkit.event.block.BlockFromToEvent; -import org.bukkit.event.block.BlockIgniteEvent; -import org.bukkit.event.entity.EntityDamageEvent; -import org.bukkit.event.entity.EntityExplodeEvent; -import org.bukkit.event.player.PlayerJoinEvent; - - -public class EmergencyListener implements Listener -{ - @EventHandler(priority = EventPriority.LOW) - public void onBlockBurn(final BlockBurnEvent event) - { - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onBlockIgnite(final BlockIgniteEvent event) - { - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onBlockFromTo(final BlockFromToEvent event) - { - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onBlockBreak(final BlockBreakEvent event) - { - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onPlayerJoin(final PlayerJoinEvent event) - { - event.getPlayer().sendMessage("Essentials Protect is in emergency mode. Check your log for errors."); - } - - @EventHandler(priority = EventPriority.LOW) - public void onEntityExplode(final EntityExplodeEvent event) - { - event.setCancelled(true); - } - - @EventHandler(priority = EventPriority.LOW) - public void onEntityDamage(final EntityDamageEvent event) - { - event.setCancelled(true); - } -} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsConnect.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsConnect.java deleted file mode 100644 index ceb425e6a..000000000 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsConnect.java +++ /dev/null @@ -1,124 +0,0 @@ -package com.earth2me.essentials.protect; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IReload; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.protect.data.ProtectedBlockMySQL; -import com.earth2me.essentials.protect.data.ProtectedBlockSQLite; -import java.beans.PropertyVetoException; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; - - -public class EssentialsConnect -{ - private static final Logger LOGGER = Logger.getLogger("Minecraft"); - private final transient IEssentials ess; - private final transient IProtect protect; - - public EssentialsConnect(final Plugin essPlugin, final Plugin essProtect) - { - if (!essProtect.getDescription().getVersion().equals(essPlugin.getDescription().getVersion())) - { - LOGGER.log(Level.WARNING, _("versionMismatchAll")); - } - ess = (IEssentials)essPlugin; - protect = (IProtect)essProtect; - protect.setSettings(new ProtectHolder(ess)); - final ProtectReloader pr = new ProtectReloader(); - pr.onReload(); - ess.addReloadListener(pr); - } - - public IEssentials getEssentials() - { - return ess; - } - - public void alert(final Player user, final String item, final String type) - { - final Location loc = user.getLocation(); - final String warnMessage = _("alertFormat", user.getName(), type, item, - loc.getWorld().getName() + "," + loc.getBlockX() + "," - + loc.getBlockY() + "," + loc.getBlockZ()); - LOGGER.log(Level.WARNING, warnMessage); - for (Player p : ess.getServer().getOnlinePlayers()) - { - final IUser alertUser = ess.getUser(p); - if (Permissions.ALERTS.isAuthorized(alertUser)) - { - alertUser.sendMessage(warnMessage); - } - } - } - - - private class ProtectReloader implements IReload - { - @Override - public void onReload() - { - if (protect.getStorage() != null) - { - protect.getStorage().onPluginDeactivation(); - } - - /* - * for (ProtectConfig protectConfig : ProtectConfig.values()) { if (protectConfig.isList()) { - * protect.getSettingsList().put(protectConfig, - * ess.getSettings().getProtectList(protectConfig.getConfigName())); } else if (protectConfig.isString()) { - * protect.getSettingsString().put(protectConfig, - * ess.getSettings().getProtectString(protectConfig.getConfigName())); } else { - * protect.getSettingsBoolean().put(protectConfig, - * ess.getSettings().getProtectBoolean(protectConfig.getConfigName(), - * protectConfig.getDefaultValueBoolean())); } - * - * } - */ - - final ProtectHolder settings = protect.getSettings(); - settings.acquireReadLock(); - try - { - if (settings.getData().getDbtype().equalsIgnoreCase("mysql")) - { - try - { - protect.setStorage(new ProtectedBlockMySQL( - settings.getData().getDburl(), - settings.getData().getDbuser(), - settings.getData().getDbpassword())); - } - catch (PropertyVetoException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - } - else - { - try - { - protect.setStorage(new ProtectedBlockSQLite("jdbc:sqlite:" + ess.getDataFolder() + "/EssentialsProtect.db")); - } - catch (PropertyVetoException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - } - /*if (protect.getSettingBool(ProtectConfig.memstore)) - { - protect.setStorage(new ProtectedBlockMemory(protect.getStorage(), protect)); - }*/ - - } - finally - { - settings.unlock(); - } - } - } -} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtect.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtect.java deleted file mode 100644 index fa3fff70d..000000000 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtect.java +++ /dev/null @@ -1,156 +0,0 @@ -package com.earth2me.essentials.protect; - -import com.earth2me.essentials.protect.data.IProtectedBlock; -import java.util.logging.Filter; -import java.util.logging.Level; -import java.util.logging.LogRecord; -import java.util.logging.Logger; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginManager; -import org.bukkit.plugin.java.JavaPlugin; - - -public class EssentialsProtect extends JavaPlugin implements IProtect -{ - private static final Logger LOGGER = Logger.getLogger("Minecraft"); - private static com.mchange.v2.log.MLogger C3P0logger; - //private final transient Map settingsBoolean = new EnumMap(ProtectConfig.class); - //private final transient Map settingsString = new EnumMap(ProtectConfig.class); - //private final transient Map> settingsList = new EnumMap>(ProtectConfig.class); - private transient IProtectedBlock storage = null; - private transient EssentialsConnect ess = null; - private transient ProtectHolder settings = null; - private transient com.mchange.v2.c3p0.management.ActiveManagementCoordinator temp; // leave this here for maven - - @Override - public void onLoad() - { - C3P0logger = com.mchange.v2.log.MLog.getLogger(com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.class); - C3P0logger.setFilter(new Filter() - { - public boolean isLoggable(final LogRecord lr) - { - return lr.getLevel() != Level.INFO; - } - }); - } - - @Override - public void onEnable() - { - final PluginManager pm = this.getServer().getPluginManager(); - final Plugin essPlugin = pm.getPlugin("Essentials3"); - if (essPlugin == null || !essPlugin.isEnabled()) - { - enableEmergencyMode(pm); - return; - } - ess = new EssentialsConnect(essPlugin, this); - - final EssentialsProtectPlayerListener playerListener = new EssentialsProtectPlayerListener(this); - pm.registerEvents(playerListener, this); - - final EssentialsProtectBlockListener blockListener = new EssentialsProtectBlockListener(this); - pm.registerEvents(blockListener, this); - - final EssentialsProtectEntityListener entityListener = new EssentialsProtectEntityListener(this); - pm.registerEvents(entityListener, this); - - final EssentialsProtectWeatherListener weatherListener = new EssentialsProtectWeatherListener(this); - pm.registerEvents(weatherListener, this); - } - - private void enableEmergencyMode(final PluginManager pm) - { - final EmergencyListener emListener = new EmergencyListener(); - pm.registerEvents(emListener, this); - - for (Player player : getServer().getOnlinePlayers()) - { - player.sendMessage("Essentials Protect is in emergency mode. Check your log for errors."); - } - LOGGER.log(Level.SEVERE, "Essentials not installed or failed to load. Essenials Protect is in emergency mode now."); - } - - /*@Override - public boolean checkProtectionItems(final ProtectConfig list, final int id) - { - final List itemList = settingsList.get(list); - return itemList != null && !itemList.isEmpty() && itemList.contains(id); - }*/ - @Override - public IProtectedBlock getStorage() - { - return storage; - } - - @Override - public void setStorage(final IProtectedBlock pb) - { - storage = pb; - } - - @Override - public EssentialsConnect getEssentialsConnect() - { - return ess; - } - - /*public Map getSettingsBoolean() - { - return settingsBoolean; - } - - public Map getSettingsString() - { - return settingsString; - } - - public Map> getSettingsList() - { - return settingsList; - } - - @Override - public boolean getSettingBool(final ProtectConfig protectConfig) - { - final Boolean bool = settingsBoolean.get(protectConfig); - return bool == null ? protectConfig.getDefaultValueBoolean() : bool; - } - - @Override - public String getSettingString(final ProtectConfig protectConfig) - { - final String str = settingsString.get(protectConfig); - return str == null ? protectConfig.getDefaultValueString() : str; - }*/ - @Override - public void onDisable() - { - if (storage != null) - { - storage.onPluginDeactivation(); - } - // Sleep for a second to allow the database to close. - try - { - Thread.sleep(1000); - } - catch (InterruptedException ex) - { - } - } - - @Override - public ProtectHolder getSettings() - { - return settings; - } - - @Override - public void setSettings(final ProtectHolder settings) - { - this.settings = settings; - } -} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectBlockListener.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectBlockListener.java deleted file mode 100644 index 89dcc71cb..000000000 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectBlockListener.java +++ /dev/null @@ -1,514 +0,0 @@ -package com.earth2me.essentials.protect; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.protect.data.IProtectedBlock; -import java.util.ArrayList; -import java.util.List; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.block.*; - - -public class EssentialsProtectBlockListener implements Listener -{ - final private transient IProtect prot; - - public EssentialsProtectBlockListener(final IProtect parent) - { - this.prot = parent; - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockPlace(final BlockPlaceEvent event) - { - final Player user = event.getPlayer(); - final ProtectHolder settings = prot.getSettings(); - settings.acquireReadLock(); - try - { - if (!Permissions.BUILD.isAuthorized(user)) - { - event.setCancelled(true); - return; - } - - final Block blockPlaced = event.getBlockPlaced(); - - if (!BlockPlacePermissions.getPermission(blockPlaced.getType()).isAuthorized(user)) - { - event.setCancelled(true); - return; - } - - if (!Permissions.ALERTS_NOTRIGGER.isAuthorized(user) - && settings.getData().getAlertOnPlacement().contains(blockPlaced.getType())) - { - prot.getEssentialsConnect().alert(user, blockPlaced.getType().toString(), _("alertPlaced")); - } - - final Block below = blockPlaced.getRelative(BlockFace.DOWN); - if ((below.getType() == Material.RAILS || below.getType() == Material.POWERED_RAIL || below.getType() == Material.DETECTOR_RAIL) - && settings.getData().getSignsAndRails().isPreventBlockAboveRails() - && isProtected(below, user, settings)) - { - event.setCancelled(true); - return; - } - - final List protect = new ArrayList(); - if ((blockPlaced.getType() == Material.RAILS || blockPlaced.getType() == Material.POWERED_RAIL || blockPlaced.getType() == Material.DETECTOR_RAIL) - && settings.getData().getSignsAndRails().isProtectRails() - && Permissions.RAILS.isAuthorized(user)) - { - protect.add(blockPlaced); - if (settings.getData().getSignsAndRails().isBlockBelow() - && !isProtected(blockPlaced.getRelative(BlockFace.DOWN), user, settings)) - { - protect.add(blockPlaced.getRelative(BlockFace.DOWN)); - } - } - /*if ((blockPlaced.getType() == Material.SIGN_POST || blockPlaced.getType() == Material.WALL_SIGN) - && settings.getData().getSignsAndRails().isProtectSigns() - && user.isAuthorized("essentials.protect")) - { - protect.add(blockPlaced); - if (settings.getData().getSignsAndRails().isBlockBelow() - && event.getBlockAgainst().getType() != Material.SIGN_POST - && event.getBlockAgainst().getType() != Material.WALL_SIGN - && !isProtected(event.getBlockAgainst(), user, settings)) - { - protect.add(event.getBlockAgainst()); - } - }*/ - for (Block block : protect) - { - prot.getStorage().protectBlock(block, user.getName()); - } - } - finally - { - settings.unlock(); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockIgnite(BlockIgniteEvent event) - { - final ProtectHolder settings = prot.getSettings(); - settings.acquireReadLock(); - try - { - final Block block = event.getBlock(); - if ((block.getType() == Material.RAILS || block.getType() == Material.POWERED_RAIL || block.getType() == Material.DETECTOR_RAIL) - && settings.getData().getSignsAndRails().isProtectRails()) - { - event.setCancelled(true); - return; - } - if ((block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST) - && settings.getData().getSignsAndRails().isProtectSigns()) - { - event.setCancelled(true); - return; - } - if (event.getBlock().getType() == Material.OBSIDIAN - || event.getBlock().getRelative(BlockFace.DOWN).getType() == Material.OBSIDIAN) - { - event.setCancelled(settings.getData().getPrevent().isPortalCreation()); - return; - } - - if (event.getCause().equals(BlockIgniteEvent.IgniteCause.SPREAD)) - { - event.setCancelled(settings.getData().getPrevent().isFirespread()); - return; - } - - if (event.getCause().equals(BlockIgniteEvent.IgniteCause.FLINT_AND_STEEL) && event.getPlayer() != null) - { - event.setCancelled(Permissions.USEFLINTSTEEL.isAuthorized(event.getPlayer())); - return; - } - - if (event.getCause().equals(BlockIgniteEvent.IgniteCause.LAVA)) - { - event.setCancelled(settings.getData().getPrevent().isLavaFirespread()); - return; - } - if (event.getCause().equals(BlockIgniteEvent.IgniteCause.LIGHTNING)) - { - event.setCancelled(settings.getData().getPrevent().isLightningFirespread()); - return; - } - } - finally - { - settings.unlock(); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockFromTo(final BlockFromToEvent event) - { - final ProtectHolder settings = prot.getSettings(); - settings.acquireReadLock(); - try - { - final Block toBlock = event.getToBlock(); - if ((toBlock.getType() == Material.RAILS || toBlock.getType() == Material.POWERED_RAIL || toBlock.getType() == Material.DETECTOR_RAIL) - && settings.getData().getSignsAndRails().isProtectRails()) - { - event.setCancelled(true); - return; - } - if ((toBlock.getType() == Material.WALL_SIGN || toBlock.getType() == Material.SIGN_POST) - && settings.getData().getSignsAndRails().isProtectSigns()) - { - event.setCancelled(true); - return; - } - - final Block block = event.getBlock(); - if (block.getType() == Material.WATER || block.getType() == Material.STATIONARY_WATER) - { - event.setCancelled(settings.getData().getPrevent().isWaterFlow()); - return; - } - - if (block.getType() == Material.LAVA || block.getType() == Material.STATIONARY_LAVA) - { - event.setCancelled(settings.getData().getPrevent().isLavaFlow()); - return; - } - // TODO: Test if this still works - /* - * if (block.getType() == Material.AIR) { - * event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_water_bucket_flow)); return; } - */ - } - finally - { - settings.unlock(); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockBurn(final BlockBurnEvent event) - { - final ProtectHolder settings = prot.getSettings(); - settings.acquireReadLock(); - try - { - final Block block = event.getBlock(); - if ((block.getType() == Material.RAILS || block.getType() == Material.POWERED_RAIL || block.getType() == Material.DETECTOR_RAIL) - && settings.getData().getSignsAndRails().isProtectRails()) - { - event.setCancelled(true); - return; - } - if ((block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST) - && settings.getData().getSignsAndRails().isProtectSigns()) - { - event.setCancelled(true); - return; - } - if (settings.getData().getPrevent().isFirespread()) - { - event.setCancelled(true); - return; - } - } - finally - { - settings.unlock(); - } - } - private final static BlockFace[] faces = new BlockFace[] - { - BlockFace.NORTH, - BlockFace.EAST, - BlockFace.SOUTH, - BlockFace.WEST, - BlockFace.UP, - BlockFace.DOWN, - BlockFace.SELF - }; - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockBreak(final BlockBreakEvent event) - { - final Player user = event.getPlayer(); - - if (!Permissions.BUILD.isAuthorized(user)) - { - event.setCancelled(true); - return; - } - final Block block = event.getBlock(); - - if (!BlockBreakPermissions.getPermission(block.getType()).isAuthorized(user)) - { - event.setCancelled(true); - return; - } - final ProtectHolder settings = prot.getSettings(); - settings.acquireReadLock(); - try - { - final Material type = block.getType(); - - if (!Permissions.ALERTS_NOTRIGGER.isAuthorized(user) && settings.getData().getAlertOnBreak().contains(type)) - { - prot.getEssentialsConnect().alert(user, type.toString(), _("alertBroke")); - } - final IProtectedBlock storage = prot.getStorage(); - - if (Permissions.ADMIN.isAuthorized(user)) - { - if (type == Material.WALL_SIGN || type == Material.SIGN_POST || type == Material.RAILS || type == Material.POWERED_RAIL || type == Material.DETECTOR_RAIL) - { - storage.unprotectBlock(block); - if (type == Material.RAILS || type == Material.POWERED_RAIL || type == Material.DETECTOR_RAIL || type == Material.SIGN_POST) - { - final Block below = block.getRelative(BlockFace.DOWN); - storage.unprotectBlock(below); - } - else - { - for (BlockFace blockFace : faces) - { - final Block against = block.getRelative(blockFace); - storage.unprotectBlock(against); - } - } - } - else - { - for (BlockFace blockFace : faces) - { - final Block against = block.getRelative(blockFace); - storage.unprotectBlock(against); - } - } - } - else - { - - final boolean isProtected = isProtected(block, user, settings); - if (isProtected) - { - event.setCancelled(true); - } - else - { - if (type == Material.WALL_SIGN || type == Material.SIGN_POST || type == Material.RAILS || type == Material.POWERED_RAIL || type == Material.DETECTOR_RAIL) - { - storage.unprotectBlock(block); - if (type == Material.RAILS || type == Material.POWERED_RAIL || type == Material.DETECTOR_RAIL || type == Material.SIGN_POST) - { - final Block below = block.getRelative(BlockFace.DOWN); - storage.unprotectBlock(below); - } - else - { - for (BlockFace blockFace : faces) - { - final Block against = block.getRelative(blockFace); - storage.unprotectBlock(against); - } - } - } - else - { - for (BlockFace blockFace : faces) - { - final Block against = block.getRelative(blockFace); - storage.unprotectBlock(against); - } - } - } - } - } - finally - { - settings.unlock(); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockPistonExtend(final BlockPistonExtendEvent event) - { - final ProtectHolder settings = prot.getSettings(); - settings.acquireReadLock(); - try - { - for (Block block : event.getBlocks()) - { - if (settings.getData().getPrevent().getPistonPush().contains(block.getType())) - { - event.setCancelled(true); - return; - } - if ((block.getRelative(BlockFace.UP).getType() == Material.RAILS - || block.getType() == Material.RAILS - || block.getRelative(BlockFace.UP).getType() == Material.POWERED_RAIL - || block.getType() == Material.POWERED_RAIL - || block.getRelative(BlockFace.UP).getType() == Material.DETECTOR_RAIL - || block.getType() == Material.DETECTOR_RAIL) - && settings.getData().getSignsAndRails().isProtectRails()) - { - event.setCancelled(true); - return; - } - if (settings.getData().getSignsAndRails().isProtectSigns()) - { - for (BlockFace blockFace : faces) - { - if (blockFace == BlockFace.DOWN) - { - continue; - } - final Block sign = block.getRelative(blockFace); - if ((blockFace == BlockFace.UP || blockFace == BlockFace.SELF) - && sign.getType() == Material.SIGN_POST) - { - event.setCancelled(true); - return; - } - if ((blockFace == BlockFace.NORTH || blockFace == BlockFace.EAST - || blockFace == BlockFace.SOUTH || blockFace == BlockFace.WEST - || blockFace == BlockFace.SELF) - && sign.getType() == Material.WALL_SIGN) - { - event.setCancelled(true); - return; - } - } - } - } - } - finally - { - settings.unlock(); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockPistonRetract(final BlockPistonRetractEvent event) - { - if (!event.isSticky()) - { - return; - } - final ProtectHolder settings = prot.getSettings(); - settings.acquireReadLock(); - try - { - final Block block = event.getRetractLocation().getBlock(); - if (settings.getData().getPrevent().getPistonPush().contains(block.getType())) - { - event.setCancelled(true); - return; - } - if ((block.getRelative(BlockFace.UP).getType() == Material.RAILS - || block.getType() == Material.RAILS - || block.getRelative(BlockFace.UP).getType() == Material.POWERED_RAIL - || block.getType() == Material.POWERED_RAIL - || block.getRelative(BlockFace.UP).getType() == Material.DETECTOR_RAIL - || block.getType() == Material.DETECTOR_RAIL) - && settings.getData().getSignsAndRails().isProtectRails()) - { - event.setCancelled(true); - return; - } - if (settings.getData().getSignsAndRails().isProtectSigns()) - { - for (BlockFace blockFace : faces) - { - if (blockFace == BlockFace.DOWN) - { - continue; - } - final Block sign = block.getRelative(blockFace); - if ((blockFace == BlockFace.UP || blockFace == BlockFace.SELF) - && sign.getType() == Material.SIGN_POST) - { - event.setCancelled(true); - return; - } - if ((blockFace == BlockFace.NORTH || blockFace == BlockFace.EAST - || blockFace == BlockFace.SOUTH || blockFace == BlockFace.WEST - || blockFace == BlockFace.SELF) - && sign.getType() == Material.WALL_SIGN) - { - event.setCancelled(true); - return; - } - } - } - } - finally - { - settings.unlock(); - } - } - - private boolean isProtected(final Block block, final Player user, final ProtectHolder settings) - { - final Material type = block.getType(); - if (settings.getData().getSignsAndRails().isProtectSigns()) - { - if (type == Material.WALL_SIGN || type == Material.SIGN_POST) - { - return prot.getStorage().isProtected(block, user.getName()); - } - - final Block up = block.getRelative(BlockFace.UP); - if (up != null && up.getType() == Material.SIGN_POST) - { - return prot.getStorage().isProtected(block, user.getName()); - } - final BlockFace[] directions = new BlockFace[] - { - BlockFace.NORTH, - BlockFace.EAST, - BlockFace.SOUTH, - BlockFace.WEST - }; - for (BlockFace blockFace : directions) - { - final Block signblock = block.getRelative(blockFace); - if (signblock.getType() == Material.WALL_SIGN) - { - final org.bukkit.material.Sign signMat = (org.bukkit.material.Sign)signblock.getState().getData(); - if (signMat != null && signMat.getFacing() == blockFace) - { - return prot.getStorage().isProtected(block, user.getName()); - } - } - } - - } - if (settings.getData().getSignsAndRails().isProtectRails()) - { - if (type == Material.RAILS || type == Material.POWERED_RAIL || type == Material.DETECTOR_RAIL) - { - return prot.getStorage().isProtected(block, user.getName()); - } - if (settings.getData().getSignsAndRails().isBlockBelow()) - { - final Block up = block.getRelative(BlockFace.UP); - if (up != null && (type == Material.RAILS || type == Material.POWERED_RAIL || type == Material.DETECTOR_RAIL)) - { - return prot.getStorage().isProtected(block, user.getName()); - } - } - } - return false; - } -} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectEntityListener.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectEntityListener.java deleted file mode 100644 index 8966b5336..000000000 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectEntityListener.java +++ /dev/null @@ -1,322 +0,0 @@ -package com.earth2me.essentials.protect; - -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.entity.*; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.*; -import org.bukkit.event.entity.EntityDamageEvent.DamageCause; -import org.bukkit.event.entity.EntityTargetEvent.TargetReason; - - -public class EssentialsProtectEntityListener implements Listener -{ - private final transient IProtect prot; - - public EssentialsProtectEntityListener(final IProtect prot) - { - super(); - this.prot = prot; - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onEntityDamage(final EntityDamageEvent event) - { - final ProtectHolder settings = prot.getSettings(); - settings.acquireReadLock(); - try - { - final Entity target = event.getEntity(); - - if (target instanceof Villager && settings.getData().getPrevent().isVillagerDeath()) - { - event.setCancelled(true); - return; - } - - final Player user = target instanceof Player ? (Player)target : null; - if (target instanceof Player && event instanceof EntityDamageByBlockEvent) - { - final DamageCause cause = event.getCause(); - - if (cause == DamageCause.CONTACT - && (Permissions.PREVENTDAMAGE_CONTACT.isAuthorized(user) - && !Permissions.PREVENTDAMAGE_NONE.isAuthorized(user))) - { - event.setCancelled(true); - return; - } - if (cause == DamageCause.LAVA - && (Permissions.PREVENTDAMAGE_LAVADAMAGE.isAuthorized(user) - && !Permissions.PREVENTDAMAGE_NONE.isAuthorized(user))) - { - event.setCancelled(true); - return; - } - if (cause == DamageCause.BLOCK_EXPLOSION - && (Permissions.PREVENTDAMAGE_TNT.isAuthorized(user) - && !Permissions.PREVENTDAMAGE_NONE.isAuthorized(user))) - { - event.setCancelled(true); - return; - } - } - - if (target instanceof Player && event instanceof EntityDamageByEntityEvent) - { - final EntityDamageByEntityEvent edEvent = (EntityDamageByEntityEvent)event; - final Entity eAttack = edEvent.getDamager(); - final Player attacker = eAttack instanceof Player ? (Player)eAttack : null; - - // PVP Settings - if (target instanceof Player && eAttack instanceof Player - && (!Permissions.PVP.isAuthorized(user) || !Permissions.PVP.isAuthorized(attacker))) - { - event.setCancelled(true); - return; - } - - //Creeper explode prevention - if (eAttack instanceof Creeper && settings.getData().getPrevent().isCreeperExplosion() - || (Permissions.PREVENTDAMAGE_CREEPER.isAuthorized(user) - && !Permissions.PREVENTDAMAGE_NONE.isAuthorized(user))) - { - event.setCancelled(true); - return; - } - - if ((event.getEntity() instanceof Fireball || event.getEntity() instanceof SmallFireball) - && (Permissions.PREVENTDAMAGE_FIREBALL.isAuthorized(user) - && !Permissions.PREVENTDAMAGE_NONE.isAuthorized(user))) - { - event.setCancelled(true); - return; - } - - if (eAttack instanceof TNTPrimed - && (Permissions.PREVENTDAMAGE_TNT.isAuthorized(user) - && !Permissions.PREVENTDAMAGE_NONE.isAuthorized(user))) - { - event.setCancelled(true); - return; - } - - if (edEvent.getDamager() instanceof Projectile - && ((Permissions.PREVENTDAMAGE_PROJECTILES.isAuthorized(user) - && !Permissions.PREVENTDAMAGE_NONE.isAuthorized(user)) - || (((Projectile)edEvent.getDamager()).getShooter() instanceof Player - && (!Permissions.PVP.isAuthorized(user) - || !Permissions.PVP.isAuthorized((Player)((Projectile)edEvent.getDamager()).getShooter()))))) - { - event.setCancelled(true); - return; - } - } - - final DamageCause cause = event.getCause(); - if (target instanceof Player) - { - if (cause == DamageCause.FALL - && (Permissions.PREVENTDAMAGE_FALL.isAuthorized(user) - && !Permissions.PREVENTDAMAGE_NONE.isAuthorized(user))) - { - event.setCancelled(true); - return; - } - - if (cause == DamageCause.SUFFOCATION - && (Permissions.PREVENTDAMAGE_SUFFOCATION.isAuthorized(user) - && !Permissions.PREVENTDAMAGE_NONE.isAuthorized(user))) - { - event.setCancelled(true); - return; - } - if ((cause == DamageCause.FIRE - || cause == DamageCause.FIRE_TICK) - && (Permissions.PREVENTDAMAGE_FIRE.isAuthorized(user) - && !Permissions.PREVENTDAMAGE_NONE.isAuthorized(user))) - { - event.setCancelled(true); - return; - } - if (cause == DamageCause.DROWNING - && (Permissions.PREVENTDAMAGE_DROWNING.isAuthorized(user) - && !Permissions.PREVENTDAMAGE_NONE.isAuthorized(user))) - { - event.setCancelled(true); - return; - } - if (cause == DamageCause.LIGHTNING - && (Permissions.PREVENTDAMAGE_LIGHTNING.isAuthorized(user) - && !Permissions.PREVENTDAMAGE_NONE.isAuthorized(user))) - { - event.setCancelled(true); - return; - } - } - } - finally - { - settings.unlock(); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onEntityExplode(final EntityExplodeEvent event) - { - final ProtectHolder settings = prot.getSettings(); - settings.acquireReadLock(); - try - { - final int maxHeight = settings.getData().getCreeperMaxHeight(); - - if (event.getEntity() instanceof EnderDragon - && settings.getData().getPrevent().isEnderdragonBlockdamage()) - { - event.setCancelled(true); - return; - } - else if (event.getEntity() instanceof Creeper - && (settings.getData().getPrevent().isCreeperExplosion() - || settings.getData().getPrevent().isCreeperBlockdamage() - || (maxHeight >= 0 && event.getLocation().getBlockY() > maxHeight))) - { - event.setCancelled(true); - event.getLocation().getWorld().createExplosion(event.getLocation(), 0F); - return; - } - else if (event.getEntity() instanceof TNTPrimed - && settings.getData().getPrevent().isTntExplosion()) - { - event.setCancelled(true); - return; - } - else if ((event.getEntity() instanceof Fireball || event.getEntity() instanceof SmallFireball) - && settings.getData().getPrevent().isFireballExplosion()) - { - event.setCancelled(true); - return; - } - // This code will prevent explosions near protected rails, signs or protected chests - // TODO: Use protect db instead of this code - - for (Block block : event.blockList()) - { - if ((block.getRelative(BlockFace.UP).getType() == Material.RAILS - || block.getType() == Material.RAILS - || block.getRelative(BlockFace.UP).getType() == Material.POWERED_RAIL - || block.getType() == Material.POWERED_RAIL - || block.getRelative(BlockFace.UP).getType() == Material.DETECTOR_RAIL - || block.getType() == Material.DETECTOR_RAIL) - && settings.getData().getSignsAndRails().isProtectRails()) - { - event.setCancelled(true); - return; - } - if ((block.getType() == Material.WALL_SIGN - || block.getRelative(BlockFace.NORTH).getType() == Material.WALL_SIGN - || block.getRelative(BlockFace.EAST).getType() == Material.WALL_SIGN - || block.getRelative(BlockFace.SOUTH).getType() == Material.WALL_SIGN - || block.getRelative(BlockFace.WEST).getType() == Material.WALL_SIGN - || block.getType() == Material.SIGN_POST - || block.getRelative(BlockFace.UP).getType() == Material.SIGN_POST) - && settings.getData().getSignsAndRails().isProtectSigns()) - { - event.setCancelled(true); - return; - } - } - } - finally - { - settings.unlock(); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onCreatureSpawn(final CreatureSpawnEvent event) - { - if (event.getEntity().getType() == EntityType.PLAYER) - { - return; - } - final EntityType creature = event.getEntityType(); - if (creature == null) - { - return; - } - final ProtectHolder settings = prot.getSettings(); - settings.acquireReadLock(); - try - { - final Boolean prevent = settings.getData().getPrevent().getSpawn().get(creature); - if (prevent != null && prevent) - { - event.setCancelled(true); - } - } - finally - { - settings.unlock(); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onEntityTarget(final EntityTargetEvent event) - { - if (event.getTarget().getType() == EntityType.PLAYER) - { - final Player user = (Player)event.getTarget(); - if ((event.getReason() == TargetReason.CLOSEST_PLAYER - || event.getReason() == TargetReason.TARGET_ATTACKED_ENTITY - || event.getReason() == TargetReason.PIG_ZOMBIE_TARGET - || event.getReason() == TargetReason.RANDOM_TARGET - || event.getReason() == TargetReason.TARGET_ATTACKED_OWNER - || event.getReason() == TargetReason.OWNER_ATTACKED_TARGET) - && Permissions.ENTITYTARGET.isAuthorized(user)) - { - event.setCancelled(true); - } - } - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onExplosionPrime(final ExplosionPrimeEvent event) - { - final ProtectHolder settings = prot.getSettings(); - settings.acquireReadLock(); - try - { - if ((event.getEntity() instanceof Fireball || event.getEntity() instanceof SmallFireball) - && settings.getData().getPrevent().isFireballFire()) - { - event.setFire(false); - } - } - finally - { - settings.unlock(); - } - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onEntityChangeBlock(final EntityChangeBlockEvent event) - { - final ProtectHolder settings = prot.getSettings(); - settings.acquireReadLock(); - try - { - if (event.getEntityType() == EntityType.ENDERMAN && settings.getData().getPrevent().isEndermanPickup()) - { - event.setCancelled(true); - } - } - finally - { - settings.unlock(); - } - } -} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectPlayerListener.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectPlayerListener.java deleted file mode 100644 index 9b870d383..000000000 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectPlayerListener.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.earth2me.essentials.protect; - -import static com.earth2me.essentials.I18n._; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.block.Action; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.inventory.ItemStack; - - -public class EssentialsProtectPlayerListener implements Listener -{ - private final transient IProtect prot; - - public EssentialsProtectPlayerListener(final IProtect prot) - { - this.prot = prot; - } - - @EventHandler(priority = EventPriority.LOW) - public void onPlayerInteract(final PlayerInteractEvent event) - { - // Do not return if cancelled, because the interact event has 2 cancelled states. - final Player user = event.getPlayer(); - - final ProtectHolder settings = prot.getSettings(); - settings.acquireReadLock(); - try - { - if (event.hasItem() - && (event.getItem().getType() == Material.WATER_BUCKET - || event.getItem().getType() == Material.LAVA_BUCKET) - && !Permissions.BUILD.isAuthorized(user)) - { - if (settings.getData().isWarnOnBuildDisallow()) - { - user.sendMessage(_("buildAlert")); - } - event.setCancelled(true); - return; - } - - if (!Permissions.INTERACT.isAuthorized(user)) - { - if (settings.getData().isWarnOnBuildDisallow()) - { - user.sendMessage(_("buildAlert")); - } - event.setCancelled(true); - return; - } - - final ItemStack item = event.getItem(); - if (item != null - && !ItemUsePermissions.getPermission(item.getType()).isAuthorized(user)) - { - event.setCancelled(true); - return; - } - - if (Permissions.OWNERINFO.isAuthorized(user) && event.getAction() == Action.RIGHT_CLICK_BLOCK) - { - final StringBuilder stringBuilder = new StringBuilder(); - boolean first = true; - final Block blockClicked = event.getClickedBlock(); - for (String owner : prot.getStorage().getOwners(blockClicked)) - { - if (!first) - { - stringBuilder.append(", "); - } - first = false; - stringBuilder.append(owner); - } - final String ownerNames = stringBuilder.toString(); - if (ownerNames != null && !ownerNames.isEmpty()) - { - user.sendMessage(_("protectionOwner", ownerNames)); - } - } - if (item != null - && !Permissions.ALERTS_NOTRIGGER.isAuthorized(user) - && settings.getData().getAlertOnUse().contains(item.getType())) - { - prot.getEssentialsConnect().alert(user, item.getType().toString(), _("alertUsed")); - } - } - finally - { - settings.unlock(); - } - } -} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectWeatherListener.java b/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectWeatherListener.java deleted file mode 100644 index babebac71..000000000 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/EssentialsProtectWeatherListener.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.earth2me.essentials.protect; - -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.weather.LightningStrikeEvent; -import org.bukkit.event.weather.ThunderChangeEvent; -import org.bukkit.event.weather.WeatherChangeEvent; - - -public class EssentialsProtectWeatherListener implements Listener -{ - private final transient IProtect prot; - - public EssentialsProtectWeatherListener(final IProtect prot) - { - this.prot = prot; - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onWeatherChange(final WeatherChangeEvent event) - { - final ProtectHolder settings = prot.getSettings(); - settings.acquireReadLock(); - try - { - if (!event.isCancelled() - && settings.getData().isDisableStorm() - && event.toWeatherState()) - { - event.setCancelled(true); - } - } - finally - { - settings.unlock(); - } - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onLightningStrike(final LightningStrikeEvent event) - { - final ProtectHolder settings = prot.getSettings(); - settings.acquireReadLock(); - try - { - if (!event.isCancelled() - && settings.getData().isDisableLighting()) - { - event.setCancelled(true); - } - } - finally - { - settings.unlock(); - } - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onThunderChange(final ThunderChangeEvent event) - { - final ProtectHolder settings = prot.getSettings(); - settings.acquireReadLock(); - try - { - if (!event.isCancelled() - && settings.getData().isDisableThunder() - && event.toThunderState()) - { - event.setCancelled(true); - } - } - finally - { - settings.unlock(); - } - } -} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/IProtect.java b/EssentialsProtect/src/com/earth2me/essentials/protect/IProtect.java deleted file mode 100644 index d25661bf8..000000000 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/IProtect.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.earth2me.essentials.protect; - -import com.earth2me.essentials.protect.data.IProtectedBlock; -import org.bukkit.plugin.Plugin; - - -public interface IProtect extends Plugin -{ -// boolean checkProtectionItems(final ProtectConfig list, final int id); -// boolean getSettingBool(final ProtectConfig protectConfig); -// String getSettingString(final ProtectConfig protectConfig); - IProtectedBlock getStorage(); - - void setStorage(IProtectedBlock pb); - - EssentialsConnect getEssentialsConnect(); - -// Map getSettingsBoolean(); -// Map getSettingsString(); -// Map> getSettingsList(); - ProtectHolder getSettings(); - - void setSettings(ProtectHolder settings); -} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/ItemUsePermissions.java b/EssentialsProtect/src/com/earth2me/essentials/protect/ItemUsePermissions.java deleted file mode 100644 index c4cfd617d..000000000 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/ItemUsePermissions.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.earth2me.essentials.protect; - -import com.earth2me.essentials.api.IPermission; -import com.earth2me.essentials.permissions.AbstractSuperpermsPermission; -import java.util.EnumMap; -import java.util.Locale; -import java.util.Map; -import org.bukkit.Material; -import org.bukkit.permissions.PermissionDefault; - - -public class ItemUsePermissions extends AbstractSuperpermsPermission -{ - private static Map permissions = new EnumMap(Material.class); - private static final String base = "essentials.protect.itemuse."; - private final String permission; - - public static IPermission getPermission(final Material mat) - { - IPermission perm = permissions.get(mat); - if (perm == null) - { - perm = new ItemUsePermissions(mat.toString().toLowerCase(Locale.ENGLISH)); - permissions.put(mat, perm); - } - return perm; - } - - private ItemUsePermissions(final String matName) - { - this.permission = base + matName; - } - - @Override - public String getPermission() - { - return this.permission; - } - - @Override - public PermissionDefault getPermissionDefault() - { - return PermissionDefault.TRUE; - } -} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/Permissions.java b/EssentialsProtect/src/com/earth2me/essentials/protect/Permissions.java deleted file mode 100644 index edd9a1d40..000000000 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/Permissions.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.earth2me.essentials.protect; - -import com.earth2me.essentials.api.IPermission; -import com.earth2me.essentials.utils.Util; -import java.util.Locale; -import org.bukkit.command.CommandSender; -import org.bukkit.permissions.Permission; -import org.bukkit.permissions.PermissionDefault; - - -public enum Permissions implements IPermission -{ - ALERTS, - ALERTS_NOTRIGGER, - ADMIN, - BUILD(PermissionDefault.TRUE), - ENTITYTARGET(PermissionDefault.TRUE), - INTERACT(PermissionDefault.TRUE), - OWNERINFO, - PVP(PermissionDefault.TRUE), - PREVENTDAMAGE_FALL(PermissionDefault.FALSE), - PREVENTDAMAGE_CREEPER(PermissionDefault.FALSE), - PREVENTDAMAGE_CONTACT(PermissionDefault.FALSE), - PREVENTDAMAGE_FIREBALL(PermissionDefault.FALSE), - PREVENTDAMAGE_PROJECTILES(PermissionDefault.FALSE), - PREVENTDAMAGE_LAVADAMAGE(PermissionDefault.FALSE), - PREVENTDAMAGE_TNT(PermissionDefault.FALSE), - PREVENTDAMAGE_SUFFOCATION(PermissionDefault.FALSE), - PREVENTDAMAGE_FIRE(PermissionDefault.FALSE), - PREVENTDAMAGE_DROWNING(PermissionDefault.FALSE), - PREVENTDAMAGE_LIGHTNING(PermissionDefault.FALSE), - PREVENTDAMAGE_NONE(PermissionDefault.FALSE), - RAILS(PermissionDefault.TRUE), - USEFLINTSTEEL(PermissionDefault.TRUE); - private static final String base = "essentials.protect."; - private final String permission; - private final PermissionDefault defaultPerm; - private transient Permission bukkitPerm = null; - - private Permissions() - { - this(PermissionDefault.OP); - } - - private Permissions(final PermissionDefault defaultPerm) - { - permission = base + toString().toLowerCase(Locale.ENGLISH).replace('_', '.'); - this.defaultPerm = defaultPerm; - } - - @Override - public String getPermission() - { - return permission; - } - - @Override - public Permission getBukkitPermission() - { - if (bukkitPerm != null) - { - return bukkitPerm; - } - else - { - return Util.registerPermission(getPermission(), getPermissionDefault()); - } - } - - @Override - public PermissionDefault getPermissionDefault() - { - return this.defaultPerm; - } - - @Override - public boolean isAuthorized(final CommandSender sender) - { - return sender.hasPermission(getBukkitPermission()); - } -} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/ProtectConfig.java b/EssentialsProtect/src/com/earth2me/essentials/protect/ProtectConfig.java deleted file mode 100644 index feeeb19df..000000000 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/ProtectConfig.java +++ /dev/null @@ -1,121 +0,0 @@ -package com.earth2me.essentials.protect; - - -/*public enum ProtectConfig -{ - datatype("protect.datatype", "sqlite"), - mysqlDB("protect.mysqlDb", "jdbc:mysql://localhost:3306/minecraft"), - dbUsername("protect.username", "root"), - dbPassword("protect.password", ""), - memstore("protect.memstore", false), - disable_contactdmg("protect.disable.contactdmg", false), - disable_lavadmg("protect.disable.lavadmg", false), - disable_build("protect.disable.build", true), - disable_use("protect.disable.use", true), - disable_pvp("protect.disable.pvp", false), - disable_projectiles("protect.disable.projectiles", false), - disable_fall("protect.disable.fall", false), - disable_suffocate("protect.disable.suffocate", false), - disable_firedmg("protect.disable.firedmg", false), - disable_lightning("protect.disable.lightning", false), - disable_drown("protect.disable.drown", false), - disable_weather_storm("protect.disable.weather.storm", false), - disable_weather_lightning("protect.disable.weather.lightning", false), - disable_weather_thunder("protect.disable.weather.thunder", false), - prevent_fire_spread("protect.prevent.fire-spread", true), - prevent_flint_fire("protect.prevent.flint-fire", false), - prevent_lava_fire_spread("protect.prevent.lava-fire-spread", true), - prevent_lightning_fire_spread("protect.prevent.lightning-fire-spread", true), - prevent_water_flow("protect.prevent.water-flow", false), - prevent_lava_flow("protect.prevent.lava-flow", false), - prevent_water_bucket_flow("protect.prevent.water-bucket-flow", false), - prevent_portal_creation("protect.prevent.portal-creation", false), - prevent_block_on_rail("protect.protect.prevent-block-on-rails", false), - prevent_tnt_explosion("protect.prevent.tnt-explosion", false), - prevent_tnt_playerdmg("protect.prevent.tnt-playerdamage", false), - prevent_fireball_explosion("protect.prevent.fireball-explosion", false), - prevent_fireball_fire("protect.prevent.fireball-fire", false), - prevent_fireball_playerdmg("protect.prevent.fireball-playerdamage", false), - prevent_creeper_explosion("protect.prevent.creeper-explosion", true), - prevent_creeper_playerdmg("protect.prevent.creeper-playerdamage", false), - prevent_creeper_blockdmg("protect.prevent.creeper-blockdamage", false), - prevent_enderman_pickup("protect.prevent.enderman-pickup", false), - prevent_villager_death("protect.prevent.villager-death", false), - prevent_enderdragon_blockdmg("protect.prevent.enderdragon-blockdamage", true), - prevent_entitytarget("protect.prevent.entitytarget", false), - protect_rails("protect.protect.rails", true), - protect_below_rails("protect.protect.block-below", true), - protect_signs("protect.protect.signs", true), - protect_against_signs("protect.protect.block-below", true), - enderdragon_fakeexplosions("protect.enderdragon-fakeexplosions", false), - alert_on_placement("protect.alert.on-placement"), - alert_on_use("protect.alert.on-use"), - alert_on_break("protect.alert.on-break"), - blacklist_placement("protect.blacklist.placement"), - blacklist_usage("protect.blacklist.usage"), - blacklist_break("protect.blacklist.break"), - blacklist_piston("protect.blacklist.piston"); - private final String configName; - private final String defValueString; - private final boolean defValueBoolean; - private final boolean isList; - private final boolean isString; - - private ProtectConfig(final String configName) - { - this(configName, null, false, true, false); - } - - private ProtectConfig(final String configName, final String defValueString) - { - this(configName, defValueString, false, false, true); - } - - private ProtectConfig(final String configName, final boolean defValueBoolean) - { - this(configName, null, defValueBoolean, false, false); - } - - private ProtectConfig(final String configName, final String defValueString, final boolean defValueBoolean, final boolean isList, final boolean isString) - { - this.configName = configName; - this.defValueString = defValueString; - this.defValueBoolean = defValueBoolean; - this.isList = isList; - this.isString = isString; - } - - /** - * @return the configName - *//* - public String getConfigName() - { - return configName; - } - - /** - * @return the default value String - *//* - public String getDefaultValueString() - { - return defValueString; - } - - /** - * @return the default value boolean - *//* - public boolean getDefaultValueBoolean() - { - return defValueBoolean; - } - - public boolean isString() - { - return isString; - } - - public boolean isList() - { - return isList; - } -}*/ diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/ProtectHolder.java b/EssentialsProtect/src/com/earth2me/essentials/protect/ProtectHolder.java deleted file mode 100644 index 626f82dd5..000000000 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/ProtectHolder.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.earth2me.essentials.protect; - -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.settings.protect.Protect; -import com.earth2me.essentials.storage.AsyncStorageObjectHolder; -import java.io.File; -import java.io.IOException; - - -public class ProtectHolder extends AsyncStorageObjectHolder -{ - public ProtectHolder(final IEssentials ess) - { - super(ess, Protect.class); - } - - @Override - public File getStorageFile() throws IOException - { - return new File(ess.getDataFolder(), "protect.yml"); - } - - @Override - public void finishRead() - { - } - - @Override - public void finishWrite() - { - } -} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/data/IProtectedBlock.java b/EssentialsProtect/src/com/earth2me/essentials/protect/data/IProtectedBlock.java deleted file mode 100644 index 755baface..000000000 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/data/IProtectedBlock.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.earth2me.essentials.protect.data; - -import java.util.List; -import org.bukkit.block.Block; - - -public interface IProtectedBlock -{ - public void clearProtections(); - - public void importProtections(List blocks); - - public List exportProtections(); - - public void protectBlock(Block block, String playerName); - - public boolean isProtected(Block block, String playerName); - - public List getOwners(Block block); - - public int unprotectBlock(Block block); - - public void onPluginDeactivation(); -} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/data/OwnedBlock.java b/EssentialsProtect/src/com/earth2me/essentials/protect/data/OwnedBlock.java deleted file mode 100644 index dc28feae8..000000000 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/data/OwnedBlock.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.earth2me.essentials.protect.data; - - -public class OwnedBlock -{ - final int x; - final int y; - final int z; - final String world; - final String playerName; - - public OwnedBlock(int x, int y, int z, String world, String playerName) - { - this.x = x; - this.y = y; - this.z = z; - this.world = world; - this.playerName = playerName; - } -} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockJDBC.java b/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockJDBC.java deleted file mode 100644 index 53d5de945..000000000 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockJDBC.java +++ /dev/null @@ -1,434 +0,0 @@ -package com.earth2me.essentials.protect.data; - -import com.mchange.v2.c3p0.ComboPooledDataSource; -import java.beans.PropertyVetoException; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.bukkit.block.Block; - - -public abstract class ProtectedBlockJDBC implements IProtectedBlock -{ - protected static final Logger LOGGER = Logger.getLogger("Minecraft"); - protected final transient ComboPooledDataSource cpds; - - protected abstract PreparedStatement getStatementCreateTable(Connection conn) throws SQLException; - - protected abstract PreparedStatement getStatementUpdateFrom2_0Table(Connection conn) throws SQLException; - - protected abstract PreparedStatement getStatementDeleteAll(Connection conn) throws SQLException; - - protected abstract PreparedStatement getStatementInsert(Connection conn, String world, int x, int y, int z, String playerName) throws SQLException; - - protected abstract PreparedStatement getStatementPlayerCountByLocation(Connection conn, String world, int x, int y, int z, String playerName) throws SQLException; - - protected abstract PreparedStatement getStatementPlayersByLocation(Connection conn, String name, int x, int y, int z) throws SQLException; - - protected abstract PreparedStatement getStatementDeleteByLocation(Connection conn, String world, int x, int y, int z) throws SQLException; - - protected abstract PreparedStatement getStatementAllBlocks(Connection conn) throws SQLException; - - public ProtectedBlockJDBC(final String driver, final String url) throws PropertyVetoException - { - this(driver, url, null, null); - } - - public ProtectedBlockJDBC(final String driver, final String url, final String username, final String password) throws PropertyVetoException - { - cpds = new ComboPooledDataSource(); - cpds.setDriverClass(driver); - cpds.setJdbcUrl(url); - if (username != null) - { - cpds.setUser(username); - cpds.setPassword(password); - } - cpds.setMaxStatements(20); - createAndConvertTable(); - } - - private void createAndConvertTable() - { - Connection conn = null; - PreparedStatement ps = null; - try - { - conn = cpds.getConnection(); - ps = getStatementCreateTable(conn); - ps.execute(); - ps.close(); - ps = getStatementUpdateFrom2_0Table(conn); - ps.execute(); - } - catch (SQLException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - finally - { - if (ps != null) - { - try - { - ps.close(); - } - catch (SQLException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - } - if (conn != null) - { - try - { - conn.close(); - } - catch (SQLException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - } - } - } - - @Override - public void clearProtections() - { - Connection conn = null; - PreparedStatement ps = null; - try - { - conn = cpds.getConnection(); - ps = getStatementDeleteAll(conn); - ps.executeUpdate(); - } - catch (SQLException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - finally - { - if (ps != null) - { - try - { - ps.close(); - } - catch (SQLException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - } - if (conn != null) - { - try - { - conn.close(); - } - catch (SQLException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - } - } - } - - @Override - public void importProtections(final List blocks) - { - for (OwnedBlock ownedBlock : blocks) - { - if (ownedBlock.playerName == null) - { - continue; - } - protectBlock(ownedBlock.world, ownedBlock.x, ownedBlock.y, ownedBlock.z, ownedBlock.playerName); - } - } - - @Override - public List exportProtections() - { - Connection conn = null; - PreparedStatement ps = null; - ResultSet rs = null; - List blocks = new ArrayList(); - try - { - conn = cpds.getConnection(); - ps = getStatementAllBlocks(conn); - rs = ps.executeQuery(); - while (rs.next()) - { - OwnedBlock ob = new OwnedBlock( - rs.getInt(2), - rs.getInt(3), - rs.getInt(4), - rs.getString(1), - rs.getString(5)); - blocks.add(ob); - } - return blocks; - } - catch (SQLException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - return blocks; - } - finally - { - if (rs != null) - { - try - { - rs.close(); - } - catch (SQLException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - } - if (ps != null) - { - try - { - ps.close(); - } - catch (SQLException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - } - if (conn != null) - { - try - { - conn.close(); - } - catch (SQLException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - } - } - } - - @Override - public void protectBlock(final Block block, final String playerName) - { - protectBlock(block.getWorld().getName(), block.getX(), block.getY(), block.getZ(), playerName); - } - - private void protectBlock(final String world, final int x, final int y, final int z, final String playerName) - { - Connection conn = null; - PreparedStatement ps = null; - try - { - conn = cpds.getConnection(); - ps = getStatementInsert(conn, world, x, y, z, playerName); - ps.executeUpdate(); - } - catch (SQLException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - finally - { - if (ps != null) - { - try - { - ps.close(); - } - catch (SQLException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - } - if (conn != null) - { - try - { - conn.close(); - } - catch (SQLException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - } - } - } - - @Override - public boolean isProtected(final Block block, final String playerName) - { - Connection conn = null; - PreparedStatement ps = null; - ResultSet rs = null; - try - { - conn = cpds.getConnection(); - ps = getStatementPlayerCountByLocation(conn, block.getWorld().getName(), block.getX(), block.getY(), block.getZ(), playerName); - rs = ps.executeQuery(); - return rs.next() && rs.getInt(1) > 0 && rs.getInt(2) == 0; - } - catch (SQLException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - return true; - } - finally - { - if (rs != null) - { - try - { - rs.close(); - } - catch (SQLException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - } - if (ps != null) - { - try - { - ps.close(); - } - catch (SQLException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - } - if (conn != null) - { - try - { - conn.close(); - } - catch (SQLException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - } - } - } - - @Override - public List getOwners(final Block block) - { - Connection conn = null; - PreparedStatement ps = null; - ResultSet rs = null; - List owners = new ArrayList(); - try - { - conn = cpds.getConnection(); - ps = getStatementPlayersByLocation(conn, block.getWorld().getName(), block.getX(), block.getY(), block.getZ()); - rs = ps.executeQuery(); - while (rs.next()) - { - owners.add(rs.getString(1)); - } - return owners; - } - catch (SQLException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - return owners; - } - finally - { - if (rs != null) - { - try - { - rs.close(); - } - catch (SQLException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - } - if (ps != null) - { - try - { - ps.close(); - } - catch (SQLException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - } - if (conn != null) - { - try - { - conn.close(); - } - catch (SQLException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - } - } - } - - @Override - public int unprotectBlock(final Block block) - { - Connection conn = null; - PreparedStatement ps = null; - try - { - conn = cpds.getConnection(); - ps = getStatementDeleteByLocation(conn, block.getWorld().getName(), block.getX(), block.getY(), block.getZ()); - return ps.executeUpdate(); - } - catch (SQLException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - return 0; - } - finally - { - if (ps != null) - { - try - { - ps.close(); - } - catch (SQLException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - } - if (conn != null) - { - try - { - conn.close(); - } - catch (SQLException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - } - } - } - - @Override - public void onPluginDeactivation() - { - cpds.close(); - } -} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockMemory.java b/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockMemory.java deleted file mode 100644 index 7b38d54eb..000000000 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockMemory.java +++ /dev/null @@ -1,258 +0,0 @@ -package com.earth2me.essentials.protect.data; - -import java.util.*; -import java.util.Map.Entry; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.plugin.Plugin; - - -public final class ProtectedBlockMemory implements IProtectedBlock -{ - private final transient List worlds = new ArrayList(); - private final transient List playerNames = new ArrayList(); - private final transient IProtectedBlock storage; - private final transient Plugin plugin; - - - static class ProtectedLocation - { - private final transient int x; - private final transient int y; - private final transient int z; - private final transient int w; - - public ProtectedLocation(final Block block, final int worldId) - { - this.x = block.getX(); - this.y = block.getY(); - this.z = block.getZ(); - this.w = worldId; - } - - public ProtectedLocation(final OwnedBlock ownedBlock, final int worldId) - { - this.x = ownedBlock.x; - this.y = ownedBlock.y; - this.z = ownedBlock.z; - this.w = worldId; - } - - @Override - public boolean equals(final Object object) - { - if (object instanceof ProtectedLocation) - { - final ProtectedLocation pLoc = (ProtectedLocation)object; - return x == pLoc.x && y == pLoc.y && z == pLoc.z && w == pLoc.w; - } - return false; - } - - @Override - public int hashCode() - { - return x ^ y ^ z ^ w; - } - } - - - static class ProtectedBy - { - private transient int playerId = -1; - private transient Set playerIds; - - public void add(final int playerId) - { - if (this.playerId == -1 || this.playerId == playerId) - { - this.playerId = playerId; - } - else - { - if (playerIds == null) - { - playerIds = new HashSet(4); - playerIds.add(this.playerId); - } - playerIds.add(playerId); - } - } - - public boolean contains(final int playerId) - { - if (playerIds == null) - { - return this.playerId == playerId; - } - return playerIds.contains(playerId); - } - - public List getPlayers(final List playerNames) - { - final List list = new ArrayList(2); - if (playerIds == null) - { - list.add(playerNames.get(playerId)); - } - else - { - for (Integer integer : playerIds) - { - list.add(playerNames.get(integer)); - } - } - return list; - } - - public int size() - { - if (playerIds == null) - { - return 1; - } - return playerIds.size(); - } - } - private final transient Map blocks = new HashMap(); - - public ProtectedBlockMemory(final IProtectedBlock storage, final Plugin plugin) - { - this.storage = storage; - this.plugin = plugin; - importProtections(storage.exportProtections()); - } - - @Override - public void clearProtections() - { - blocks.clear(); - } - - @Override - public void importProtections(final List blocks) - { - for (OwnedBlock ownedBlock : blocks) - { - final ProtectedLocation pl = new ProtectedLocation(ownedBlock, getWorldId(ownedBlock.world)); - if (ownedBlock.playerName == null) - { - continue; - } - protectBlock(pl, ownedBlock.playerName); - } - } - - @Override - public List exportProtections() - { - final List blockList = new ArrayList(blocks.size()); - for (Entry entry : blocks.entrySet()) - { - for (String name : entry.getValue().getPlayers(playerNames)) - { - final OwnedBlock ob = new OwnedBlock( - entry.getKey().x, - entry.getKey().y, - entry.getKey().z, - worlds.get(entry.getKey().w), - name); - blockList.add(ob); - } - } - return blockList; - } - - @Override - public void protectBlock(final Block block, final String playerName) - { - final ProtectedLocation pl = new ProtectedLocation(block, getWorldId(block.getWorld())); - protectBlock(pl, playerName); - plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, new Runnable() - { - @Override - public void run() - { - storage.protectBlock(block, playerName); - } - }); - } - - private void protectBlock(final ProtectedLocation pl, final String playerName) - { - final int playerId = getPlayerId(playerName); - ProtectedBy pb = blocks.get(pl); - if (pb == null) - { - pb = new ProtectedBy(); - blocks.put(pl, pb); - } - pb.add(playerId); - } - - @Override - public boolean isProtected(final Block block, final String playerName) - { - final int playerId = getPlayerId(playerName); - final ProtectedLocation pl = new ProtectedLocation(block, getWorldId(block.getWorld())); - final ProtectedBy pb = blocks.get(pl); - return !pb.contains(playerId); - } - - @Override - public List getOwners(final Block block) - { - ProtectedLocation pl = new ProtectedLocation(block, getWorldId(block.getWorld())); - ProtectedBy pb = blocks.get(pl); - return pb.getPlayers(playerNames); - } - - @Override - public int unprotectBlock(final Block block) - { - final ProtectedLocation pl = new ProtectedLocation(block, getWorldId(block.getWorld())); - final ProtectedBy pb = blocks.remove(pl); - plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, new Runnable() - { - @Override - public void run() - { - storage.unprotectBlock(block); - } - }); - return pb.size(); - } - - private int getPlayerId(final String playername) - { - int id = playerNames.indexOf(playername); - if (id < 0) - { - playerNames.add(playername); - id = playerNames.indexOf(playername); - } - return id; - } - - private int getWorldId(final World world) - { - return getWorldId(world.getName()); - } - - private int getWorldId(final String name) - { - int id = worlds.indexOf(name); - if (id < 0) - { - worlds.add(name); - id = worlds.indexOf(name); - } - return id; - } - - @Override - public void onPluginDeactivation() - { - storage.onPluginDeactivation(); - } -} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockMySQL.java b/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockMySQL.java deleted file mode 100644 index 39070c30c..000000000 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockMySQL.java +++ /dev/null @@ -1,160 +0,0 @@ -package com.earth2me.essentials.protect.data; - -import java.beans.PropertyVetoException; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.logging.Level; -import java.util.logging.Logger; - - -public class ProtectedBlockMySQL extends ProtectedBlockJDBC -{ - public ProtectedBlockMySQL(final String url, final String username, final String password) throws PropertyVetoException - { - super("com.mysql.jdbc.Driver", url, username, password); - } - private static final String QueryCreateTable = - "CREATE TABLE IF NOT EXISTS `EssentialsProtect` (" - + "`worldName` varchar(60) NOT NULL," - + "`x` int(11) NOT NULL, `y` int(11) NOT NULL, `z` int(11) NOT NULL," - + "`playerName` varchar(150) DEFAULT NULL," - + "KEY `pos` (`worldName`,`x`,`z`,`y`)" - + ") ENGINE=MyISAM DEFAULT CHARSET=utf8"; - - @Override - protected PreparedStatement getStatementCreateTable(final Connection conn) throws SQLException - { - return conn.prepareStatement(QueryCreateTable); - } - private static final String QueryUpdateFrom2_0TableCheck = - "SHOW COLUMNS FROM `EssentialsProtect` LIKE 'id';"; - private static final String QueryUpdateFrom2_0Table = - "ALTER TABLE `EssentialsProtect` " - + "CHARACTER SET = utf8, ENGINE = MyISAM," - + "DROP COLUMN `id`," - + "CHANGE COLUMN `playerName` `playerName` VARCHAR(150) NULL AFTER `z`," - + "CHANGE COLUMN `worldName` `worldName` VARCHAR(60) NOT NULL," - + "ADD INDEX `position` (`worldName` ASC, `x` ASC, `z` ASC, `y` ASC)," - + "DROP PRIMARY KEY ;"; - - @Override - protected PreparedStatement getStatementUpdateFrom2_0Table(final Connection conn) throws SQLException - { - PreparedStatement testPS = null; - ResultSet testRS = null; - try - { - testPS = conn.prepareStatement(QueryUpdateFrom2_0TableCheck); - testRS = testPS.executeQuery(); - if (testRS.first()) - { - return conn.prepareStatement(QueryUpdateFrom2_0Table); - } - else - { - return conn.prepareStatement("SELECT 1;"); - } - } - finally - { - if (testRS != null) - { - try - { - testRS.close(); - } - catch (SQLException ex) - { - Logger.getLogger(ProtectedBlockMySQL.class.getName()).log(Level.SEVERE, null, ex); - } - } - if (testPS != null) - { - try - { - testPS.close(); - } - catch (SQLException ex) - { - Logger.getLogger(ProtectedBlockMySQL.class.getName()).log(Level.SEVERE, null, ex); - } - } - } - } - private static final String QueryDeleteAll = "DELETE FROM EssentialsProtect;"; - - @Override - protected PreparedStatement getStatementDeleteAll(final Connection conn) throws SQLException - { - return conn.prepareStatement(QueryDeleteAll); - } - private static final String QueryInsert = - "INSERT INTO EssentialsProtect (worldName, x, y, z, playerName) VALUES (?, ?, ?, ?, ?);"; - - @Override - protected PreparedStatement getStatementInsert(final Connection conn, final String world, final int x, final int y, final int z, - final String playerName) throws SQLException - { - final PreparedStatement ps = conn.prepareStatement(QueryInsert); - ps.setString(1, world); - ps.setInt(2, x); - ps.setInt(3, y); - ps.setInt(4, z); - ps.setString(5, playerName); - return ps; - } - private static final String QueryCountByPlayer = - "SELECT COUNT(playerName), SUM(playerName = ?) FROM EssentialsProtect " - + "WHERE worldName = ? AND x = ? AND y = ? AND z = ? GROUP BY x;"; - - @Override - protected PreparedStatement getStatementPlayerCountByLocation(final Connection conn, final String world, final int x, final int y, final int z, - final String playerName) throws SQLException - { - final PreparedStatement ps = conn.prepareStatement(QueryCountByPlayer); - ps.setString(1, playerName); - ps.setString(2, world); - ps.setInt(3, x); - ps.setInt(4, y); - ps.setInt(5, z); - return ps; - } - private static final String QueryPlayersByLocation = - "SELECT playerName FROM EssentialsProtect WHERE worldname = ? AND x = ? AND y = ? AND z = ?;"; - - @Override - protected PreparedStatement getStatementPlayersByLocation(final Connection conn, final String world, - final int x, final int y, final int z) throws SQLException - { - final PreparedStatement ps = conn.prepareStatement(QueryPlayersByLocation); - ps.setString(1, world); - ps.setInt(2, x); - ps.setInt(3, y); - ps.setInt(4, z); - return ps; - } - private static final String QueryDeleteByLocation = - "DELETE FROM EssentialsProtect WHERE worldName = ? AND x = ? AND y = ? AND z = ?;"; - - @Override - protected PreparedStatement getStatementDeleteByLocation(final Connection conn, final String world, - final int x, final int y, final int z) throws SQLException - { - final PreparedStatement ps = conn.prepareStatement(QueryDeleteByLocation); - ps.setString(1, world); - ps.setInt(2, x); - ps.setInt(3, y); - ps.setInt(4, z); - return ps; - } - private static final String QueryAllBlocks = - "SELECT worldName, x, y, z, playerName FROM EssentialsProtect;"; - - @Override - protected PreparedStatement getStatementAllBlocks(final Connection conn) throws SQLException - { - return conn.prepareStatement(QueryAllBlocks); - } -} diff --git a/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockSQLite.java b/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockSQLite.java deleted file mode 100644 index 464c620fe..000000000 --- a/EssentialsProtect/src/com/earth2me/essentials/protect/data/ProtectedBlockSQLite.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.earth2me.essentials.protect.data; - -import java.beans.PropertyVetoException; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; - - -public class ProtectedBlockSQLite extends ProtectedBlockJDBC -{ - public ProtectedBlockSQLite(final String url) throws PropertyVetoException - { - super("org.sqlite.JDBC", url); - } - private static final String QueryCreateTable = - "CREATE TABLE IF NOT EXISTS EssentialsProtect (" - + "worldName TEXT ,playerName TEXT, " - + "x NUMERIC, y NUMERIC, z NUMERIC)"; - - @Override - protected PreparedStatement getStatementCreateTable(final Connection conn) throws SQLException - { - return conn.prepareStatement(QueryCreateTable); - } - private static final String QueryUpdateFrom2_0Table = - "CREATE INDEX IF NOT EXISTS position ON EssentialsProtect (" - + "worldName, x, z, y)"; - - @Override - protected PreparedStatement getStatementUpdateFrom2_0Table(final Connection conn) throws SQLException - { - return conn.prepareStatement(QueryUpdateFrom2_0Table); - } - private static final String QueryDeleteAll = "DELETE FROM EssentialsProtect;"; - - @Override - protected PreparedStatement getStatementDeleteAll(final Connection conn) throws SQLException - { - return conn.prepareStatement(QueryDeleteAll); - } - private static final String QueryInsert = - "INSERT INTO EssentialsProtect (worldName, x, y, z, playerName) VALUES (?, ?, ?, ?, ?);"; - - @Override - protected PreparedStatement getStatementInsert(final Connection conn, final String world, - final int x, final int y, final int z, final String playerName) throws SQLException - { - final PreparedStatement ps = conn.prepareStatement(QueryInsert); - ps.setString(1, world); - ps.setInt(2, x); - ps.setInt(3, y); - ps.setInt(4, z); - ps.setString(5, playerName); - return ps; - } - private static final String QueryPlayerCountByLocation = - "SELECT COUNT(playerName), SUM(playerName = ?) FROM EssentialsProtect " - + "WHERE worldName = ? AND x = ? AND y = ? AND z = ? GROUP BY x;"; - - @Override - protected PreparedStatement getStatementPlayerCountByLocation(final Connection conn, final String world, - final int x, final int y, final int z, final String playerName) throws SQLException - { - final PreparedStatement ps = conn.prepareStatement(QueryPlayerCountByLocation); - ps.setString(1, playerName); - ps.setString(2, world); - ps.setInt(3, x); - ps.setInt(4, y); - ps.setInt(5, z); - return ps; - } - private static final String QueryPlayersByLocation = - "SELECT playerName FROM EssentialsProtect WHERE worldname = ? AND x = ? AND y = ? AND z = ?;"; - - @Override - protected PreparedStatement getStatementPlayersByLocation(final Connection conn, final String world, - final int x, final int y, final int z) throws SQLException - { - final PreparedStatement ps = conn.prepareStatement(QueryPlayersByLocation); - ps.setString(1, world); - ps.setInt(2, x); - ps.setInt(3, y); - ps.setInt(4, z); - return ps; - } - private static final String QueryDeleteByLocation = - "DELETE FROM EssentialsProtect WHERE worldName = ? AND x = ? AND y = ? AND z = ?;"; - - @Override - protected PreparedStatement getStatementDeleteByLocation(final Connection conn, final String world, - final int x, final int y, final int z) throws SQLException - { - final PreparedStatement ps = conn.prepareStatement(QueryDeleteByLocation); - ps.setString(1, world); - ps.setInt(2, x); - ps.setInt(3, y); - ps.setInt(4, z); - return ps; - } - private static final String QueryAllBlocks = - "SELECT worldName, x, y, z, playerName FROM EssentialsProtect;"; - - @Override - protected PreparedStatement getStatementAllBlocks(final Connection conn) throws SQLException - { - return conn.prepareStatement(QueryAllBlocks); - } -} diff --git a/EssentialsProtect/src/net/ess3/protect/BlockBreakPermissions.java b/EssentialsProtect/src/net/ess3/protect/BlockBreakPermissions.java new file mode 100644 index 000000000..1a07588e8 --- /dev/null +++ b/EssentialsProtect/src/net/ess3/protect/BlockBreakPermissions.java @@ -0,0 +1,46 @@ +package net.ess3.protect; + +import net.ess3.api.IPermission; +import net.ess3.permissions.AbstractSuperpermsPermission; +import java.util.EnumMap; +import java.util.Locale; +import java.util.Map; +import org.bukkit.Material; +import org.bukkit.permissions.PermissionDefault; + + +public final class BlockBreakPermissions extends AbstractSuperpermsPermission +{ + private static Map permissions = new EnumMap(Material.class); + private static final String base = "essentials.protect.blockbreak."; + private final String permission; + + public static IPermission getPermission(final Material mat) + { + IPermission perm = permissions.get(mat); + if (perm == null) + { + perm = new BlockBreakPermissions(mat.toString().toLowerCase(Locale.ENGLISH)); + permissions.put(mat, perm); + } + return perm; + } + + private BlockBreakPermissions(final String matName) + { + super(); + this.permission = base + matName; + } + + @Override + public String getPermission() + { + return this.permission; + } + + @Override + public PermissionDefault getPermissionDefault() + { + return PermissionDefault.TRUE; + } +} diff --git a/EssentialsProtect/src/net/ess3/protect/BlockPlacePermissions.java b/EssentialsProtect/src/net/ess3/protect/BlockPlacePermissions.java new file mode 100644 index 000000000..87e771e73 --- /dev/null +++ b/EssentialsProtect/src/net/ess3/protect/BlockPlacePermissions.java @@ -0,0 +1,46 @@ +package net.ess3.protect; + +import net.ess3.api.IPermission; +import net.ess3.permissions.AbstractSuperpermsPermission; +import java.util.EnumMap; +import java.util.Locale; +import java.util.Map; +import org.bukkit.Material; +import org.bukkit.permissions.PermissionDefault; + + +public class BlockPlacePermissions extends AbstractSuperpermsPermission +{ + private static Map permissions = new EnumMap(Material.class); + private static final String base = "essentials.protect.blockplace."; + private final String permission; + + public static IPermission getPermission(final Material mat) + { + IPermission perm = permissions.get(mat); + if (perm == null) + { + perm = new BlockPlacePermissions(mat.toString().toLowerCase(Locale.ENGLISH)); + permissions.put(mat, perm); + } + return perm; + } + + private BlockPlacePermissions(final String matName) + { + super(); + this.permission = base + matName; + } + + @Override + public String getPermission() + { + return this.permission; + } + + @Override + public PermissionDefault getPermissionDefault() + { + return PermissionDefault.TRUE; + } +} diff --git a/EssentialsProtect/src/net/ess3/protect/EmergencyListener.java b/EssentialsProtect/src/net/ess3/protect/EmergencyListener.java new file mode 100644 index 000000000..2d70ee698 --- /dev/null +++ b/EssentialsProtect/src/net/ess3/protect/EmergencyListener.java @@ -0,0 +1,58 @@ +package net.ess3.protect; + +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.BlockBurnEvent; +import org.bukkit.event.block.BlockFromToEvent; +import org.bukkit.event.block.BlockIgniteEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.entity.EntityExplodeEvent; +import org.bukkit.event.player.PlayerJoinEvent; + + +public class EmergencyListener implements Listener +{ + @EventHandler(priority = EventPriority.LOW) + public void onBlockBurn(final BlockBurnEvent event) + { + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onBlockIgnite(final BlockIgniteEvent event) + { + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onBlockFromTo(final BlockFromToEvent event) + { + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onBlockBreak(final BlockBreakEvent event) + { + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onPlayerJoin(final PlayerJoinEvent event) + { + event.getPlayer().sendMessage("Essentials Protect is in emergency mode. Check your log for errors."); + } + + @EventHandler(priority = EventPriority.LOW) + public void onEntityExplode(final EntityExplodeEvent event) + { + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOW) + public void onEntityDamage(final EntityDamageEvent event) + { + event.setCancelled(true); + } +} diff --git a/EssentialsProtect/src/net/ess3/protect/EssentialsConnect.java b/EssentialsProtect/src/net/ess3/protect/EssentialsConnect.java new file mode 100644 index 000000000..c3fcfe441 --- /dev/null +++ b/EssentialsProtect/src/net/ess3/protect/EssentialsConnect.java @@ -0,0 +1,124 @@ +package net.ess3.protect; + +import static net.ess3.I18n._; +import net.ess3.api.IEssentials; +import net.ess3.api.IReload; +import net.ess3.api.IUser; +import net.ess3.protect.data.ProtectedBlockMySQL; +import net.ess3.protect.data.ProtectedBlockSQLite; +import java.beans.PropertyVetoException; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + + +public class EssentialsConnect +{ + private static final Logger LOGGER = Logger.getLogger("Minecraft"); + private final transient IEssentials ess; + private final transient IProtect protect; + + public EssentialsConnect(final Plugin essPlugin, final Plugin essProtect) + { + if (!essProtect.getDescription().getVersion().equals(essPlugin.getDescription().getVersion())) + { + LOGGER.log(Level.WARNING, _("versionMismatchAll")); + } + ess = (IEssentials)essPlugin; + protect = (IProtect)essProtect; + protect.setSettings(new ProtectHolder(ess)); + final ProtectReloader pr = new ProtectReloader(); + pr.onReload(); + ess.addReloadListener(pr); + } + + public IEssentials getEssentials() + { + return ess; + } + + public void alert(final Player user, final String item, final String type) + { + final Location loc = user.getLocation(); + final String warnMessage = _("alertFormat", user.getName(), type, item, + loc.getWorld().getName() + "," + loc.getBlockX() + "," + + loc.getBlockY() + "," + loc.getBlockZ()); + LOGGER.log(Level.WARNING, warnMessage); + for (Player p : ess.getServer().getOnlinePlayers()) + { + final IUser alertUser = ess.getUser(p); + if (Permissions.ALERTS.isAuthorized(alertUser)) + { + alertUser.sendMessage(warnMessage); + } + } + } + + + private class ProtectReloader implements IReload + { + @Override + public void onReload() + { + if (protect.getStorage() != null) + { + protect.getStorage().onPluginDeactivation(); + } + + /* + * for (ProtectConfig protectConfig : ProtectConfig.values()) { if (protectConfig.isList()) { + * protect.getSettingsList().put(protectConfig, + * ess.getSettings().getProtectList(protectConfig.getConfigName())); } else if (protectConfig.isString()) { + * protect.getSettingsString().put(protectConfig, + * ess.getSettings().getProtectString(protectConfig.getConfigName())); } else { + * protect.getSettingsBoolean().put(protectConfig, + * ess.getSettings().getProtectBoolean(protectConfig.getConfigName(), + * protectConfig.getDefaultValueBoolean())); } + * + * } + */ + + final ProtectHolder settings = protect.getSettings(); + settings.acquireReadLock(); + try + { + if (settings.getData().getDbtype().equalsIgnoreCase("mysql")) + { + try + { + protect.setStorage(new ProtectedBlockMySQL( + settings.getData().getDburl(), + settings.getData().getDbuser(), + settings.getData().getDbpassword())); + } + catch (PropertyVetoException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + else + { + try + { + protect.setStorage(new ProtectedBlockSQLite("jdbc:sqlite:" + ess.getDataFolder() + "/EssentialsProtect.db")); + } + catch (PropertyVetoException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + /*if (protect.getSettingBool(ProtectConfig.memstore)) + { + protect.setStorage(new ProtectedBlockMemory(protect.getStorage(), protect)); + }*/ + + } + finally + { + settings.unlock(); + } + } + } +} diff --git a/EssentialsProtect/src/net/ess3/protect/EssentialsProtect.java b/EssentialsProtect/src/net/ess3/protect/EssentialsProtect.java new file mode 100644 index 000000000..9f1e58e10 --- /dev/null +++ b/EssentialsProtect/src/net/ess3/protect/EssentialsProtect.java @@ -0,0 +1,157 @@ +package net.ess3.protect; + +import net.ess3.protect.data.IProtectedBlock; +import java.util.logging.Filter; +import java.util.logging.Level; +import java.util.logging.LogRecord; +import java.util.logging.Logger; + +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + + +public class EssentialsProtect extends JavaPlugin implements IProtect +{ + private static final Logger LOGGER = Logger.getLogger("Minecraft"); + private static com.mchange.v2.log.MLogger C3P0logger; + //private final transient Map settingsBoolean = new EnumMap(ProtectConfig.class); + //private final transient Map settingsString = new EnumMap(ProtectConfig.class); + //private final transient Map> settingsList = new EnumMap>(ProtectConfig.class); + private transient IProtectedBlock storage = null; + private transient EssentialsConnect ess = null; + private transient ProtectHolder settings = null; + private transient com.mchange.v2.c3p0.management.ActiveManagementCoordinator temp; // leave this here for maven + + @Override + public void onLoad() + { + C3P0logger = com.mchange.v2.log.MLog.getLogger(com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.class); + C3P0logger.setFilter(new Filter() + { + public boolean isLoggable(final LogRecord lr) + { + return lr.getLevel() != Level.INFO; + } + }); + } + + @Override + public void onEnable() + { + final PluginManager pm = this.getServer().getPluginManager(); + final Plugin essPlugin = pm.getPlugin("Essentials-3"); + if (essPlugin == null || !essPlugin.isEnabled()) + { + enableEmergencyMode(pm); + return; + } + ess = new EssentialsConnect(essPlugin, this); + + final EssentialsProtectPlayerListener playerListener = new EssentialsProtectPlayerListener(this); + pm.registerEvents(playerListener, this); + + final EssentialsProtectBlockListener blockListener = new EssentialsProtectBlockListener(this); + pm.registerEvents(blockListener, this); + + final EssentialsProtectEntityListener entityListener = new EssentialsProtectEntityListener(this); + pm.registerEvents(entityListener, this); + + final EssentialsProtectWeatherListener weatherListener = new EssentialsProtectWeatherListener(this); + pm.registerEvents(weatherListener, this); + } + + private void enableEmergencyMode(final PluginManager pm) + { + final EmergencyListener emListener = new EmergencyListener(); + pm.registerEvents(emListener, this); + + for (Player player : getServer().getOnlinePlayers()) + { + player.sendMessage("Essentials Protect is in emergency mode. Check your log for errors."); + } + LOGGER.log(Level.SEVERE, "Essentials not installed or failed to load. Essenials Protect is in emergency mode now."); + } + + /*@Override + public boolean checkProtectionItems(final ProtectConfig list, final int id) + { + final List itemList = settingsList.get(list); + return itemList != null && !itemList.isEmpty() && itemList.contains(id); + }*/ + @Override + public IProtectedBlock getStorage() + { + return storage; + } + + @Override + public void setStorage(final IProtectedBlock pb) + { + storage = pb; + } + + @Override + public EssentialsConnect getEssentialsConnect() + { + return ess; + } + + /*public Map getSettingsBoolean() + { + return settingsBoolean; + } + + public Map getSettingsString() + { + return settingsString; + } + + public Map> getSettingsList() + { + return settingsList; + } + + @Override + public boolean getSettingBool(final ProtectConfig protectConfig) + { + final Boolean bool = settingsBoolean.get(protectConfig); + return bool == null ? protectConfig.getDefaultValueBoolean() : bool; + } + + @Override + public String getSettingString(final ProtectConfig protectConfig) + { + final String str = settingsString.get(protectConfig); + return str == null ? protectConfig.getDefaultValueString() : str; + }*/ + @Override + public void onDisable() + { + if (storage != null) + { + storage.onPluginDeactivation(); + } + // Sleep for a second to allow the database to close. + try + { + Thread.sleep(1000); + } + catch (InterruptedException ex) + { + } + } + + @Override + public ProtectHolder getSettings() + { + return settings; + } + + @Override + public void setSettings(final ProtectHolder settings) + { + this.settings = settings; + } +} diff --git a/EssentialsProtect/src/net/ess3/protect/EssentialsProtectBlockListener.java b/EssentialsProtect/src/net/ess3/protect/EssentialsProtectBlockListener.java new file mode 100644 index 000000000..ecfee8e20 --- /dev/null +++ b/EssentialsProtect/src/net/ess3/protect/EssentialsProtectBlockListener.java @@ -0,0 +1,515 @@ +package net.ess3.protect; + +import static net.ess3.I18n._; +import net.ess3.protect.data.IProtectedBlock; +import java.util.ArrayList; +import java.util.List; + +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.*; + + +public class EssentialsProtectBlockListener implements Listener +{ + final private transient IProtect prot; + + public EssentialsProtectBlockListener(final IProtect parent) + { + this.prot = parent; + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockPlace(final BlockPlaceEvent event) + { + final Player user = event.getPlayer(); + final ProtectHolder settings = prot.getSettings(); + settings.acquireReadLock(); + try + { + if (!Permissions.BUILD.isAuthorized(user)) + { + event.setCancelled(true); + return; + } + + final Block blockPlaced = event.getBlockPlaced(); + + if (!BlockPlacePermissions.getPermission(blockPlaced.getType()).isAuthorized(user)) + { + event.setCancelled(true); + return; + } + + if (!Permissions.ALERTS_NOTRIGGER.isAuthorized(user) + && settings.getData().getAlertOnPlacement().contains(blockPlaced.getType())) + { + prot.getEssentialsConnect().alert(user, blockPlaced.getType().toString(), _("alertPlaced")); + } + + final Block below = blockPlaced.getRelative(BlockFace.DOWN); + if ((below.getType() == Material.RAILS || below.getType() == Material.POWERED_RAIL || below.getType() == Material.DETECTOR_RAIL) + && settings.getData().getSignsAndRails().isPreventBlockAboveRails() + && isProtected(below, user, settings)) + { + event.setCancelled(true); + return; + } + + final List protect = new ArrayList(); + if ((blockPlaced.getType() == Material.RAILS || blockPlaced.getType() == Material.POWERED_RAIL || blockPlaced.getType() == Material.DETECTOR_RAIL) + && settings.getData().getSignsAndRails().isProtectRails() + && Permissions.RAILS.isAuthorized(user)) + { + protect.add(blockPlaced); + if (settings.getData().getSignsAndRails().isBlockBelow() + && !isProtected(blockPlaced.getRelative(BlockFace.DOWN), user, settings)) + { + protect.add(blockPlaced.getRelative(BlockFace.DOWN)); + } + } + /*if ((blockPlaced.getType() == Material.SIGN_POST || blockPlaced.getType() == Material.WALL_SIGN) + && settings.getData().getSignsAndRails().isProtectSigns() + && user.isAuthorized("essentials.protect")) + { + protect.add(blockPlaced); + if (settings.getData().getSignsAndRails().isBlockBelow() + && event.getBlockAgainst().getType() != Material.SIGN_POST + && event.getBlockAgainst().getType() != Material.WALL_SIGN + && !isProtected(event.getBlockAgainst(), user, settings)) + { + protect.add(event.getBlockAgainst()); + } + }*/ + for (Block block : protect) + { + prot.getStorage().protectBlock(block, user.getName()); + } + } + finally + { + settings.unlock(); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockIgnite(BlockIgniteEvent event) + { + final ProtectHolder settings = prot.getSettings(); + settings.acquireReadLock(); + try + { + final Block block = event.getBlock(); + if ((block.getType() == Material.RAILS || block.getType() == Material.POWERED_RAIL || block.getType() == Material.DETECTOR_RAIL) + && settings.getData().getSignsAndRails().isProtectRails()) + { + event.setCancelled(true); + return; + } + if ((block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST) + && settings.getData().getSignsAndRails().isProtectSigns()) + { + event.setCancelled(true); + return; + } + if (event.getBlock().getType() == Material.OBSIDIAN + || event.getBlock().getRelative(BlockFace.DOWN).getType() == Material.OBSIDIAN) + { + event.setCancelled(settings.getData().getPrevent().isPortalCreation()); + return; + } + + if (event.getCause().equals(BlockIgniteEvent.IgniteCause.SPREAD)) + { + event.setCancelled(settings.getData().getPrevent().isFirespread()); + return; + } + + if (event.getCause().equals(BlockIgniteEvent.IgniteCause.FLINT_AND_STEEL) && event.getPlayer() != null) + { + event.setCancelled(Permissions.USEFLINTSTEEL.isAuthorized(event.getPlayer())); + return; + } + + if (event.getCause().equals(BlockIgniteEvent.IgniteCause.LAVA)) + { + event.setCancelled(settings.getData().getPrevent().isLavaFirespread()); + return; + } + if (event.getCause().equals(BlockIgniteEvent.IgniteCause.LIGHTNING)) + { + event.setCancelled(settings.getData().getPrevent().isLightningFirespread()); + return; + } + } + finally + { + settings.unlock(); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockFromTo(final BlockFromToEvent event) + { + final ProtectHolder settings = prot.getSettings(); + settings.acquireReadLock(); + try + { + final Block toBlock = event.getToBlock(); + if ((toBlock.getType() == Material.RAILS || toBlock.getType() == Material.POWERED_RAIL || toBlock.getType() == Material.DETECTOR_RAIL) + && settings.getData().getSignsAndRails().isProtectRails()) + { + event.setCancelled(true); + return; + } + if ((toBlock.getType() == Material.WALL_SIGN || toBlock.getType() == Material.SIGN_POST) + && settings.getData().getSignsAndRails().isProtectSigns()) + { + event.setCancelled(true); + return; + } + + final Block block = event.getBlock(); + if (block.getType() == Material.WATER || block.getType() == Material.STATIONARY_WATER) + { + event.setCancelled(settings.getData().getPrevent().isWaterFlow()); + return; + } + + if (block.getType() == Material.LAVA || block.getType() == Material.STATIONARY_LAVA) + { + event.setCancelled(settings.getData().getPrevent().isLavaFlow()); + return; + } + // TODO: Test if this still works + /* + * if (block.getType() == Material.AIR) { + * event.setCancelled(prot.getSettingBool(ProtectConfig.prevent_water_bucket_flow)); return; } + */ + } + finally + { + settings.unlock(); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockBurn(final BlockBurnEvent event) + { + final ProtectHolder settings = prot.getSettings(); + settings.acquireReadLock(); + try + { + final Block block = event.getBlock(); + if ((block.getType() == Material.RAILS || block.getType() == Material.POWERED_RAIL || block.getType() == Material.DETECTOR_RAIL) + && settings.getData().getSignsAndRails().isProtectRails()) + { + event.setCancelled(true); + return; + } + if ((block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST) + && settings.getData().getSignsAndRails().isProtectSigns()) + { + event.setCancelled(true); + return; + } + if (settings.getData().getPrevent().isFirespread()) + { + event.setCancelled(true); + return; + } + } + finally + { + settings.unlock(); + } + } + private final static BlockFace[] faces = new BlockFace[] + { + BlockFace.NORTH, + BlockFace.EAST, + BlockFace.SOUTH, + BlockFace.WEST, + BlockFace.UP, + BlockFace.DOWN, + BlockFace.SELF + }; + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockBreak(final BlockBreakEvent event) + { + final Player user = event.getPlayer(); + + if (!Permissions.BUILD.isAuthorized(user)) + { + event.setCancelled(true); + return; + } + final Block block = event.getBlock(); + + if (!BlockBreakPermissions.getPermission(block.getType()).isAuthorized(user)) + { + event.setCancelled(true); + return; + } + final ProtectHolder settings = prot.getSettings(); + settings.acquireReadLock(); + try + { + final Material type = block.getType(); + + if (!Permissions.ALERTS_NOTRIGGER.isAuthorized(user) && settings.getData().getAlertOnBreak().contains(type)) + { + prot.getEssentialsConnect().alert(user, type.toString(), _("alertBroke")); + } + final IProtectedBlock storage = prot.getStorage(); + + if (Permissions.ADMIN.isAuthorized(user)) + { + if (type == Material.WALL_SIGN || type == Material.SIGN_POST || type == Material.RAILS || type == Material.POWERED_RAIL || type == Material.DETECTOR_RAIL) + { + storage.unprotectBlock(block); + if (type == Material.RAILS || type == Material.POWERED_RAIL || type == Material.DETECTOR_RAIL || type == Material.SIGN_POST) + { + final Block below = block.getRelative(BlockFace.DOWN); + storage.unprotectBlock(below); + } + else + { + for (BlockFace blockFace : faces) + { + final Block against = block.getRelative(blockFace); + storage.unprotectBlock(against); + } + } + } + else + { + for (BlockFace blockFace : faces) + { + final Block against = block.getRelative(blockFace); + storage.unprotectBlock(against); + } + } + } + else + { + + final boolean isProtected = isProtected(block, user, settings); + if (isProtected) + { + event.setCancelled(true); + } + else + { + if (type == Material.WALL_SIGN || type == Material.SIGN_POST || type == Material.RAILS || type == Material.POWERED_RAIL || type == Material.DETECTOR_RAIL) + { + storage.unprotectBlock(block); + if (type == Material.RAILS || type == Material.POWERED_RAIL || type == Material.DETECTOR_RAIL || type == Material.SIGN_POST) + { + final Block below = block.getRelative(BlockFace.DOWN); + storage.unprotectBlock(below); + } + else + { + for (BlockFace blockFace : faces) + { + final Block against = block.getRelative(blockFace); + storage.unprotectBlock(against); + } + } + } + else + { + for (BlockFace blockFace : faces) + { + final Block against = block.getRelative(blockFace); + storage.unprotectBlock(against); + } + } + } + } + } + finally + { + settings.unlock(); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockPistonExtend(final BlockPistonExtendEvent event) + { + final ProtectHolder settings = prot.getSettings(); + settings.acquireReadLock(); + try + { + for (Block block : event.getBlocks()) + { + if (settings.getData().getPrevent().getPistonPush().contains(block.getType())) + { + event.setCancelled(true); + return; + } + if ((block.getRelative(BlockFace.UP).getType() == Material.RAILS + || block.getType() == Material.RAILS + || block.getRelative(BlockFace.UP).getType() == Material.POWERED_RAIL + || block.getType() == Material.POWERED_RAIL + || block.getRelative(BlockFace.UP).getType() == Material.DETECTOR_RAIL + || block.getType() == Material.DETECTOR_RAIL) + && settings.getData().getSignsAndRails().isProtectRails()) + { + event.setCancelled(true); + return; + } + if (settings.getData().getSignsAndRails().isProtectSigns()) + { + for (BlockFace blockFace : faces) + { + if (blockFace == BlockFace.DOWN) + { + continue; + } + final Block sign = block.getRelative(blockFace); + if ((blockFace == BlockFace.UP || blockFace == BlockFace.SELF) + && sign.getType() == Material.SIGN_POST) + { + event.setCancelled(true); + return; + } + if ((blockFace == BlockFace.NORTH || blockFace == BlockFace.EAST + || blockFace == BlockFace.SOUTH || blockFace == BlockFace.WEST + || blockFace == BlockFace.SELF) + && sign.getType() == Material.WALL_SIGN) + { + event.setCancelled(true); + return; + } + } + } + } + } + finally + { + settings.unlock(); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockPistonRetract(final BlockPistonRetractEvent event) + { + if (!event.isSticky()) + { + return; + } + final ProtectHolder settings = prot.getSettings(); + settings.acquireReadLock(); + try + { + final Block block = event.getRetractLocation().getBlock(); + if (settings.getData().getPrevent().getPistonPush().contains(block.getType())) + { + event.setCancelled(true); + return; + } + if ((block.getRelative(BlockFace.UP).getType() == Material.RAILS + || block.getType() == Material.RAILS + || block.getRelative(BlockFace.UP).getType() == Material.POWERED_RAIL + || block.getType() == Material.POWERED_RAIL + || block.getRelative(BlockFace.UP).getType() == Material.DETECTOR_RAIL + || block.getType() == Material.DETECTOR_RAIL) + && settings.getData().getSignsAndRails().isProtectRails()) + { + event.setCancelled(true); + return; + } + if (settings.getData().getSignsAndRails().isProtectSigns()) + { + for (BlockFace blockFace : faces) + { + if (blockFace == BlockFace.DOWN) + { + continue; + } + final Block sign = block.getRelative(blockFace); + if ((blockFace == BlockFace.UP || blockFace == BlockFace.SELF) + && sign.getType() == Material.SIGN_POST) + { + event.setCancelled(true); + return; + } + if ((blockFace == BlockFace.NORTH || blockFace == BlockFace.EAST + || blockFace == BlockFace.SOUTH || blockFace == BlockFace.WEST + || blockFace == BlockFace.SELF) + && sign.getType() == Material.WALL_SIGN) + { + event.setCancelled(true); + return; + } + } + } + } + finally + { + settings.unlock(); + } + } + + private boolean isProtected(final Block block, final Player user, final ProtectHolder settings) + { + final Material type = block.getType(); + if (settings.getData().getSignsAndRails().isProtectSigns()) + { + if (type == Material.WALL_SIGN || type == Material.SIGN_POST) + { + return prot.getStorage().isProtected(block, user.getName()); + } + + final Block up = block.getRelative(BlockFace.UP); + if (up != null && up.getType() == Material.SIGN_POST) + { + return prot.getStorage().isProtected(block, user.getName()); + } + final BlockFace[] directions = new BlockFace[] + { + BlockFace.NORTH, + BlockFace.EAST, + BlockFace.SOUTH, + BlockFace.WEST + }; + for (BlockFace blockFace : directions) + { + final Block signblock = block.getRelative(blockFace); + if (signblock.getType() == Material.WALL_SIGN) + { + final org.bukkit.material.Sign signMat = (org.bukkit.material.Sign)signblock.getState().getData(); + if (signMat != null && signMat.getFacing() == blockFace) + { + return prot.getStorage().isProtected(block, user.getName()); + } + } + } + + } + if (settings.getData().getSignsAndRails().isProtectRails()) + { + if (type == Material.RAILS || type == Material.POWERED_RAIL || type == Material.DETECTOR_RAIL) + { + return prot.getStorage().isProtected(block, user.getName()); + } + if (settings.getData().getSignsAndRails().isBlockBelow()) + { + final Block up = block.getRelative(BlockFace.UP); + if (up != null && (type == Material.RAILS || type == Material.POWERED_RAIL || type == Material.DETECTOR_RAIL)) + { + return prot.getStorage().isProtected(block, user.getName()); + } + } + } + return false; + } +} diff --git a/EssentialsProtect/src/net/ess3/protect/EssentialsProtectEntityListener.java b/EssentialsProtect/src/net/ess3/protect/EssentialsProtectEntityListener.java new file mode 100644 index 000000000..67df5c8c5 --- /dev/null +++ b/EssentialsProtect/src/net/ess3/protect/EssentialsProtectEntityListener.java @@ -0,0 +1,322 @@ +package net.ess3.protect; + +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.*; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.*; +import org.bukkit.event.entity.EntityDamageEvent.DamageCause; +import org.bukkit.event.entity.EntityTargetEvent.TargetReason; + + +public class EssentialsProtectEntityListener implements Listener +{ + private final transient IProtect prot; + + public EssentialsProtectEntityListener(final IProtect prot) + { + super(); + this.prot = prot; + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onEntityDamage(final EntityDamageEvent event) + { + final ProtectHolder settings = prot.getSettings(); + settings.acquireReadLock(); + try + { + final Entity target = event.getEntity(); + + if (target instanceof Villager && settings.getData().getPrevent().isVillagerDeath()) + { + event.setCancelled(true); + return; + } + + final Player user = target instanceof Player ? (Player)target : null; + if (target instanceof Player && event instanceof EntityDamageByBlockEvent) + { + final DamageCause cause = event.getCause(); + + if (cause == DamageCause.CONTACT + && (Permissions.PREVENTDAMAGE_CONTACT.isAuthorized(user) + && !Permissions.PREVENTDAMAGE_NONE.isAuthorized(user))) + { + event.setCancelled(true); + return; + } + if (cause == DamageCause.LAVA + && (Permissions.PREVENTDAMAGE_LAVADAMAGE.isAuthorized(user) + && !Permissions.PREVENTDAMAGE_NONE.isAuthorized(user))) + { + event.setCancelled(true); + return; + } + if (cause == DamageCause.BLOCK_EXPLOSION + && (Permissions.PREVENTDAMAGE_TNT.isAuthorized(user) + && !Permissions.PREVENTDAMAGE_NONE.isAuthorized(user))) + { + event.setCancelled(true); + return; + } + } + + if (target instanceof Player && event instanceof EntityDamageByEntityEvent) + { + final EntityDamageByEntityEvent edEvent = (EntityDamageByEntityEvent)event; + final Entity eAttack = edEvent.getDamager(); + final Player attacker = eAttack instanceof Player ? (Player)eAttack : null; + + // PVP Settings + if (target instanceof Player && eAttack instanceof Player + && (!Permissions.PVP.isAuthorized(user) || !Permissions.PVP.isAuthorized(attacker))) + { + event.setCancelled(true); + return; + } + + //Creeper explode prevention + if (eAttack instanceof Creeper && settings.getData().getPrevent().isCreeperExplosion() + || (Permissions.PREVENTDAMAGE_CREEPER.isAuthorized(user) + && !Permissions.PREVENTDAMAGE_NONE.isAuthorized(user))) + { + event.setCancelled(true); + return; + } + + if ((event.getEntity() instanceof Fireball || event.getEntity() instanceof SmallFireball) + && (Permissions.PREVENTDAMAGE_FIREBALL.isAuthorized(user) + && !Permissions.PREVENTDAMAGE_NONE.isAuthorized(user))) + { + event.setCancelled(true); + return; + } + + if (eAttack instanceof TNTPrimed + && (Permissions.PREVENTDAMAGE_TNT.isAuthorized(user) + && !Permissions.PREVENTDAMAGE_NONE.isAuthorized(user))) + { + event.setCancelled(true); + return; + } + + if (edEvent.getDamager() instanceof Projectile + && ((Permissions.PREVENTDAMAGE_PROJECTILES.isAuthorized(user) + && !Permissions.PREVENTDAMAGE_NONE.isAuthorized(user)) + || (((Projectile)edEvent.getDamager()).getShooter() instanceof Player + && (!Permissions.PVP.isAuthorized(user) + || !Permissions.PVP.isAuthorized((Player)((Projectile)edEvent.getDamager()).getShooter()))))) + { + event.setCancelled(true); + return; + } + } + + final DamageCause cause = event.getCause(); + if (target instanceof Player) + { + if (cause == DamageCause.FALL + && (Permissions.PREVENTDAMAGE_FALL.isAuthorized(user) + && !Permissions.PREVENTDAMAGE_NONE.isAuthorized(user))) + { + event.setCancelled(true); + return; + } + + if (cause == DamageCause.SUFFOCATION + && (Permissions.PREVENTDAMAGE_SUFFOCATION.isAuthorized(user) + && !Permissions.PREVENTDAMAGE_NONE.isAuthorized(user))) + { + event.setCancelled(true); + return; + } + if ((cause == DamageCause.FIRE + || cause == DamageCause.FIRE_TICK) + && (Permissions.PREVENTDAMAGE_FIRE.isAuthorized(user) + && !Permissions.PREVENTDAMAGE_NONE.isAuthorized(user))) + { + event.setCancelled(true); + return; + } + if (cause == DamageCause.DROWNING + && (Permissions.PREVENTDAMAGE_DROWNING.isAuthorized(user) + && !Permissions.PREVENTDAMAGE_NONE.isAuthorized(user))) + { + event.setCancelled(true); + return; + } + if (cause == DamageCause.LIGHTNING + && (Permissions.PREVENTDAMAGE_LIGHTNING.isAuthorized(user) + && !Permissions.PREVENTDAMAGE_NONE.isAuthorized(user))) + { + event.setCancelled(true); + return; + } + } + } + finally + { + settings.unlock(); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onEntityExplode(final EntityExplodeEvent event) + { + final ProtectHolder settings = prot.getSettings(); + settings.acquireReadLock(); + try + { + final int maxHeight = settings.getData().getCreeperMaxHeight(); + + if (event.getEntity() instanceof EnderDragon + && settings.getData().getPrevent().isEnderdragonBlockdamage()) + { + event.setCancelled(true); + return; + } + else if (event.getEntity() instanceof Creeper + && (settings.getData().getPrevent().isCreeperExplosion() + || settings.getData().getPrevent().isCreeperBlockdamage() + || (maxHeight >= 0 && event.getLocation().getBlockY() > maxHeight))) + { + event.setCancelled(true); + event.getLocation().getWorld().createExplosion(event.getLocation(), 0F); + return; + } + else if (event.getEntity() instanceof TNTPrimed + && settings.getData().getPrevent().isTntExplosion()) + { + event.setCancelled(true); + return; + } + else if ((event.getEntity() instanceof Fireball || event.getEntity() instanceof SmallFireball) + && settings.getData().getPrevent().isFireballExplosion()) + { + event.setCancelled(true); + return; + } + // This code will prevent explosions near protected rails, signs or protected chests + // TODO: Use protect db instead of this code + + for (Block block : event.blockList()) + { + if ((block.getRelative(BlockFace.UP).getType() == Material.RAILS + || block.getType() == Material.RAILS + || block.getRelative(BlockFace.UP).getType() == Material.POWERED_RAIL + || block.getType() == Material.POWERED_RAIL + || block.getRelative(BlockFace.UP).getType() == Material.DETECTOR_RAIL + || block.getType() == Material.DETECTOR_RAIL) + && settings.getData().getSignsAndRails().isProtectRails()) + { + event.setCancelled(true); + return; + } + if ((block.getType() == Material.WALL_SIGN + || block.getRelative(BlockFace.NORTH).getType() == Material.WALL_SIGN + || block.getRelative(BlockFace.EAST).getType() == Material.WALL_SIGN + || block.getRelative(BlockFace.SOUTH).getType() == Material.WALL_SIGN + || block.getRelative(BlockFace.WEST).getType() == Material.WALL_SIGN + || block.getType() == Material.SIGN_POST + || block.getRelative(BlockFace.UP).getType() == Material.SIGN_POST) + && settings.getData().getSignsAndRails().isProtectSigns()) + { + event.setCancelled(true); + return; + } + } + } + finally + { + settings.unlock(); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onCreatureSpawn(final CreatureSpawnEvent event) + { + if (event.getEntity().getType() == EntityType.PLAYER) + { + return; + } + final EntityType creature = event.getEntityType(); + if (creature == null) + { + return; + } + final ProtectHolder settings = prot.getSettings(); + settings.acquireReadLock(); + try + { + final Boolean prevent = settings.getData().getPrevent().getSpawn().get(creature); + if (prevent != null && prevent) + { + event.setCancelled(true); + } + } + finally + { + settings.unlock(); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onEntityTarget(final EntityTargetEvent event) + { + if (event.getTarget().getType() == EntityType.PLAYER) + { + final Player user = (Player)event.getTarget(); + if ((event.getReason() == TargetReason.CLOSEST_PLAYER + || event.getReason() == TargetReason.TARGET_ATTACKED_ENTITY + || event.getReason() == TargetReason.PIG_ZOMBIE_TARGET + || event.getReason() == TargetReason.RANDOM_TARGET + || event.getReason() == TargetReason.TARGET_ATTACKED_OWNER + || event.getReason() == TargetReason.OWNER_ATTACKED_TARGET) + && Permissions.ENTITYTARGET.isAuthorized(user)) + { + event.setCancelled(true); + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onExplosionPrime(final ExplosionPrimeEvent event) + { + final ProtectHolder settings = prot.getSettings(); + settings.acquireReadLock(); + try + { + if ((event.getEntity() instanceof Fireball || event.getEntity() instanceof SmallFireball) + && settings.getData().getPrevent().isFireballFire()) + { + event.setFire(false); + } + } + finally + { + settings.unlock(); + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onEntityChangeBlock(final EntityChangeBlockEvent event) + { + final ProtectHolder settings = prot.getSettings(); + settings.acquireReadLock(); + try + { + if (event.getEntityType() == EntityType.ENDERMAN && settings.getData().getPrevent().isEndermanPickup()) + { + event.setCancelled(true); + } + } + finally + { + settings.unlock(); + } + } +} diff --git a/EssentialsProtect/src/net/ess3/protect/EssentialsProtectPlayerListener.java b/EssentialsProtect/src/net/ess3/protect/EssentialsProtectPlayerListener.java new file mode 100644 index 000000000..64e4a529b --- /dev/null +++ b/EssentialsProtect/src/net/ess3/protect/EssentialsProtectPlayerListener.java @@ -0,0 +1,97 @@ +package net.ess3.protect; + +import static net.ess3.I18n._; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; + + +public class EssentialsProtectPlayerListener implements Listener +{ + private final transient IProtect prot; + + public EssentialsProtectPlayerListener(final IProtect prot) + { + this.prot = prot; + } + + @EventHandler(priority = EventPriority.LOW) + public void onPlayerInteract(final PlayerInteractEvent event) + { + // Do not return if cancelled, because the interact event has 2 cancelled states. + final Player user = event.getPlayer(); + + final ProtectHolder settings = prot.getSettings(); + settings.acquireReadLock(); + try + { + if (event.hasItem() + && (event.getItem().getType() == Material.WATER_BUCKET + || event.getItem().getType() == Material.LAVA_BUCKET) + && !Permissions.BUILD.isAuthorized(user)) + { + if (settings.getData().isWarnOnBuildDisallow()) + { + user.sendMessage(_("buildAlert")); + } + event.setCancelled(true); + return; + } + + if (!Permissions.INTERACT.isAuthorized(user)) + { + if (settings.getData().isWarnOnBuildDisallow()) + { + user.sendMessage(_("buildAlert")); + } + event.setCancelled(true); + return; + } + + final ItemStack item = event.getItem(); + if (item != null + && !ItemUsePermissions.getPermission(item.getType()).isAuthorized(user)) + { + event.setCancelled(true); + return; + } + + if (Permissions.OWNERINFO.isAuthorized(user) && event.getAction() == Action.RIGHT_CLICK_BLOCK) + { + final StringBuilder stringBuilder = new StringBuilder(); + boolean first = true; + final Block blockClicked = event.getClickedBlock(); + for (String owner : prot.getStorage().getOwners(blockClicked)) + { + if (!first) + { + stringBuilder.append(", "); + } + first = false; + stringBuilder.append(owner); + } + final String ownerNames = stringBuilder.toString(); + if (ownerNames != null && !ownerNames.isEmpty()) + { + user.sendMessage(_("protectionOwner", ownerNames)); + } + } + if (item != null + && !Permissions.ALERTS_NOTRIGGER.isAuthorized(user) + && settings.getData().getAlertOnUse().contains(item.getType())) + { + prot.getEssentialsConnect().alert(user, item.getType().toString(), _("alertUsed")); + } + } + finally + { + settings.unlock(); + } + } +} diff --git a/EssentialsProtect/src/net/ess3/protect/EssentialsProtectWeatherListener.java b/EssentialsProtect/src/net/ess3/protect/EssentialsProtectWeatherListener.java new file mode 100644 index 000000000..6f08bdd13 --- /dev/null +++ b/EssentialsProtect/src/net/ess3/protect/EssentialsProtectWeatherListener.java @@ -0,0 +1,78 @@ +package net.ess3.protect; + +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.weather.LightningStrikeEvent; +import org.bukkit.event.weather.ThunderChangeEvent; +import org.bukkit.event.weather.WeatherChangeEvent; + + +public class EssentialsProtectWeatherListener implements Listener +{ + private final transient IProtect prot; + + public EssentialsProtectWeatherListener(final IProtect prot) + { + this.prot = prot; + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onWeatherChange(final WeatherChangeEvent event) + { + final ProtectHolder settings = prot.getSettings(); + settings.acquireReadLock(); + try + { + if (!event.isCancelled() + && settings.getData().isDisableStorm() + && event.toWeatherState()) + { + event.setCancelled(true); + } + } + finally + { + settings.unlock(); + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onLightningStrike(final LightningStrikeEvent event) + { + final ProtectHolder settings = prot.getSettings(); + settings.acquireReadLock(); + try + { + if (!event.isCancelled() + && settings.getData().isDisableLighting()) + { + event.setCancelled(true); + } + } + finally + { + settings.unlock(); + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onThunderChange(final ThunderChangeEvent event) + { + final ProtectHolder settings = prot.getSettings(); + settings.acquireReadLock(); + try + { + if (!event.isCancelled() + && settings.getData().isDisableThunder() + && event.toThunderState()) + { + event.setCancelled(true); + } + } + finally + { + settings.unlock(); + } + } +} diff --git a/EssentialsProtect/src/net/ess3/protect/IProtect.java b/EssentialsProtect/src/net/ess3/protect/IProtect.java new file mode 100644 index 000000000..df2a454a0 --- /dev/null +++ b/EssentialsProtect/src/net/ess3/protect/IProtect.java @@ -0,0 +1,24 @@ +package net.ess3.protect; + +import net.ess3.protect.data.IProtectedBlock; +import org.bukkit.plugin.Plugin; + + +public interface IProtect extends Plugin +{ +// boolean checkProtectionItems(final ProtectConfig list, final int id); +// boolean getSettingBool(final ProtectConfig protectConfig); +// String getSettingString(final ProtectConfig protectConfig); + IProtectedBlock getStorage(); + + void setStorage(IProtectedBlock pb); + + EssentialsConnect getEssentialsConnect(); + +// Map getSettingsBoolean(); +// Map getSettingsString(); +// Map> getSettingsList(); + ProtectHolder getSettings(); + + void setSettings(ProtectHolder settings); +} diff --git a/EssentialsProtect/src/net/ess3/protect/ItemUsePermissions.java b/EssentialsProtect/src/net/ess3/protect/ItemUsePermissions.java new file mode 100644 index 000000000..d9ecf9bc0 --- /dev/null +++ b/EssentialsProtect/src/net/ess3/protect/ItemUsePermissions.java @@ -0,0 +1,45 @@ +package net.ess3.protect; + +import net.ess3.api.IPermission; +import net.ess3.permissions.AbstractSuperpermsPermission; +import java.util.EnumMap; +import java.util.Locale; +import java.util.Map; +import org.bukkit.Material; +import org.bukkit.permissions.PermissionDefault; + + +public class ItemUsePermissions extends AbstractSuperpermsPermission +{ + private static Map permissions = new EnumMap(Material.class); + private static final String base = "essentials.protect.itemuse."; + private final String permission; + + public static IPermission getPermission(final Material mat) + { + IPermission perm = permissions.get(mat); + if (perm == null) + { + perm = new ItemUsePermissions(mat.toString().toLowerCase(Locale.ENGLISH)); + permissions.put(mat, perm); + } + return perm; + } + + private ItemUsePermissions(final String matName) + { + this.permission = base + matName; + } + + @Override + public String getPermission() + { + return this.permission; + } + + @Override + public PermissionDefault getPermissionDefault() + { + return PermissionDefault.TRUE; + } +} diff --git a/EssentialsProtect/src/net/ess3/protect/Permissions.java b/EssentialsProtect/src/net/ess3/protect/Permissions.java new file mode 100644 index 000000000..37042618b --- /dev/null +++ b/EssentialsProtect/src/net/ess3/protect/Permissions.java @@ -0,0 +1,81 @@ +package net.ess3.protect; + +import net.ess3.api.IPermission; +import net.ess3.utils.Util; +import java.util.Locale; +import org.bukkit.command.CommandSender; +import org.bukkit.permissions.Permission; +import org.bukkit.permissions.PermissionDefault; + + +public enum Permissions implements IPermission +{ + ALERTS, + ALERTS_NOTRIGGER, + ADMIN, + BUILD(PermissionDefault.TRUE), + ENTITYTARGET(PermissionDefault.TRUE), + INTERACT(PermissionDefault.TRUE), + OWNERINFO, + PVP(PermissionDefault.TRUE), + PREVENTDAMAGE_FALL(PermissionDefault.FALSE), + PREVENTDAMAGE_CREEPER(PermissionDefault.FALSE), + PREVENTDAMAGE_CONTACT(PermissionDefault.FALSE), + PREVENTDAMAGE_FIREBALL(PermissionDefault.FALSE), + PREVENTDAMAGE_PROJECTILES(PermissionDefault.FALSE), + PREVENTDAMAGE_LAVADAMAGE(PermissionDefault.FALSE), + PREVENTDAMAGE_TNT(PermissionDefault.FALSE), + PREVENTDAMAGE_SUFFOCATION(PermissionDefault.FALSE), + PREVENTDAMAGE_FIRE(PermissionDefault.FALSE), + PREVENTDAMAGE_DROWNING(PermissionDefault.FALSE), + PREVENTDAMAGE_LIGHTNING(PermissionDefault.FALSE), + PREVENTDAMAGE_NONE(PermissionDefault.FALSE), + RAILS(PermissionDefault.TRUE), + USEFLINTSTEEL(PermissionDefault.TRUE); + private static final String base = "essentials.protect."; + private final String permission; + private final PermissionDefault defaultPerm; + private transient Permission bukkitPerm = null; + + private Permissions() + { + this(PermissionDefault.OP); + } + + private Permissions(final PermissionDefault defaultPerm) + { + permission = base + toString().toLowerCase(Locale.ENGLISH).replace('_', '.'); + this.defaultPerm = defaultPerm; + } + + @Override + public String getPermission() + { + return permission; + } + + @Override + public Permission getBukkitPermission() + { + if (bukkitPerm != null) + { + return bukkitPerm; + } + else + { + return Util.registerPermission(getPermission(), getPermissionDefault()); + } + } + + @Override + public PermissionDefault getPermissionDefault() + { + return this.defaultPerm; + } + + @Override + public boolean isAuthorized(final CommandSender sender) + { + return sender.hasPermission(getBukkitPermission()); + } +} diff --git a/EssentialsProtect/src/net/ess3/protect/ProtectHolder.java b/EssentialsProtect/src/net/ess3/protect/ProtectHolder.java new file mode 100644 index 000000000..145a5e97e --- /dev/null +++ b/EssentialsProtect/src/net/ess3/protect/ProtectHolder.java @@ -0,0 +1,32 @@ +package net.ess3.protect; + +import net.ess3.api.IEssentials; +import net.ess3.settings.protect.Protect; +import net.ess3.storage.AsyncStorageObjectHolder; +import java.io.File; +import java.io.IOException; + + +public class ProtectHolder extends AsyncStorageObjectHolder +{ + public ProtectHolder(final IEssentials ess) + { + super(ess, Protect.class); + } + + @Override + public File getStorageFile() throws IOException + { + return new File(ess.getDataFolder(), "protect.yml"); + } + + @Override + public void finishRead() + { + } + + @Override + public void finishWrite() + { + } +} diff --git a/EssentialsProtect/src/net/ess3/protect/data/IProtectedBlock.java b/EssentialsProtect/src/net/ess3/protect/data/IProtectedBlock.java new file mode 100644 index 000000000..a27adfb3c --- /dev/null +++ b/EssentialsProtect/src/net/ess3/protect/data/IProtectedBlock.java @@ -0,0 +1,24 @@ +package net.ess3.protect.data; + +import java.util.List; +import org.bukkit.block.Block; + + +public interface IProtectedBlock +{ + public void clearProtections(); + + public void importProtections(List blocks); + + public List exportProtections(); + + public void protectBlock(Block block, String playerName); + + public boolean isProtected(Block block, String playerName); + + public List getOwners(Block block); + + public int unprotectBlock(Block block); + + public void onPluginDeactivation(); +} diff --git a/EssentialsProtect/src/net/ess3/protect/data/OwnedBlock.java b/EssentialsProtect/src/net/ess3/protect/data/OwnedBlock.java new file mode 100644 index 000000000..cac1826e9 --- /dev/null +++ b/EssentialsProtect/src/net/ess3/protect/data/OwnedBlock.java @@ -0,0 +1,20 @@ +package net.ess3.protect.data; + + +public class OwnedBlock +{ + final int x; + final int y; + final int z; + final String world; + final String playerName; + + public OwnedBlock(int x, int y, int z, String world, String playerName) + { + this.x = x; + this.y = y; + this.z = z; + this.world = world; + this.playerName = playerName; + } +} diff --git a/EssentialsProtect/src/net/ess3/protect/data/ProtectedBlockJDBC.java b/EssentialsProtect/src/net/ess3/protect/data/ProtectedBlockJDBC.java new file mode 100644 index 000000000..70475c6f5 --- /dev/null +++ b/EssentialsProtect/src/net/ess3/protect/data/ProtectedBlockJDBC.java @@ -0,0 +1,434 @@ +package net.ess3.protect.data; + +import com.mchange.v2.c3p0.ComboPooledDataSource; +import java.beans.PropertyVetoException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.bukkit.block.Block; + + +public abstract class ProtectedBlockJDBC implements IProtectedBlock +{ + protected static final Logger LOGGER = Logger.getLogger("Minecraft"); + protected final transient ComboPooledDataSource cpds; + + protected abstract PreparedStatement getStatementCreateTable(Connection conn) throws SQLException; + + protected abstract PreparedStatement getStatementUpdateFrom2_0Table(Connection conn) throws SQLException; + + protected abstract PreparedStatement getStatementDeleteAll(Connection conn) throws SQLException; + + protected abstract PreparedStatement getStatementInsert(Connection conn, String world, int x, int y, int z, String playerName) throws SQLException; + + protected abstract PreparedStatement getStatementPlayerCountByLocation(Connection conn, String world, int x, int y, int z, String playerName) throws SQLException; + + protected abstract PreparedStatement getStatementPlayersByLocation(Connection conn, String name, int x, int y, int z) throws SQLException; + + protected abstract PreparedStatement getStatementDeleteByLocation(Connection conn, String world, int x, int y, int z) throws SQLException; + + protected abstract PreparedStatement getStatementAllBlocks(Connection conn) throws SQLException; + + public ProtectedBlockJDBC(final String driver, final String url) throws PropertyVetoException + { + this(driver, url, null, null); + } + + public ProtectedBlockJDBC(final String driver, final String url, final String username, final String password) throws PropertyVetoException + { + cpds = new ComboPooledDataSource(); + cpds.setDriverClass(driver); + cpds.setJdbcUrl(url); + if (username != null) + { + cpds.setUser(username); + cpds.setPassword(password); + } + cpds.setMaxStatements(20); + createAndConvertTable(); + } + + private void createAndConvertTable() + { + Connection conn = null; + PreparedStatement ps = null; + try + { + conn = cpds.getConnection(); + ps = getStatementCreateTable(conn); + ps.execute(); + ps.close(); + ps = getStatementUpdateFrom2_0Table(conn); + ps.execute(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + finally + { + if (ps != null) + { + try + { + ps.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + if (conn != null) + { + try + { + conn.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + } + } + + @Override + public void clearProtections() + { + Connection conn = null; + PreparedStatement ps = null; + try + { + conn = cpds.getConnection(); + ps = getStatementDeleteAll(conn); + ps.executeUpdate(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + finally + { + if (ps != null) + { + try + { + ps.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + if (conn != null) + { + try + { + conn.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + } + } + + @Override + public void importProtections(final List blocks) + { + for (OwnedBlock ownedBlock : blocks) + { + if (ownedBlock.playerName == null) + { + continue; + } + protectBlock(ownedBlock.world, ownedBlock.x, ownedBlock.y, ownedBlock.z, ownedBlock.playerName); + } + } + + @Override + public List exportProtections() + { + Connection conn = null; + PreparedStatement ps = null; + ResultSet rs = null; + List blocks = new ArrayList(); + try + { + conn = cpds.getConnection(); + ps = getStatementAllBlocks(conn); + rs = ps.executeQuery(); + while (rs.next()) + { + OwnedBlock ob = new OwnedBlock( + rs.getInt(2), + rs.getInt(3), + rs.getInt(4), + rs.getString(1), + rs.getString(5)); + blocks.add(ob); + } + return blocks; + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + return blocks; + } + finally + { + if (rs != null) + { + try + { + rs.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + if (ps != null) + { + try + { + ps.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + if (conn != null) + { + try + { + conn.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + } + } + + @Override + public void protectBlock(final Block block, final String playerName) + { + protectBlock(block.getWorld().getName(), block.getX(), block.getY(), block.getZ(), playerName); + } + + private void protectBlock(final String world, final int x, final int y, final int z, final String playerName) + { + Connection conn = null; + PreparedStatement ps = null; + try + { + conn = cpds.getConnection(); + ps = getStatementInsert(conn, world, x, y, z, playerName); + ps.executeUpdate(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + finally + { + if (ps != null) + { + try + { + ps.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + if (conn != null) + { + try + { + conn.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + } + } + + @Override + public boolean isProtected(final Block block, final String playerName) + { + Connection conn = null; + PreparedStatement ps = null; + ResultSet rs = null; + try + { + conn = cpds.getConnection(); + ps = getStatementPlayerCountByLocation(conn, block.getWorld().getName(), block.getX(), block.getY(), block.getZ(), playerName); + rs = ps.executeQuery(); + return rs.next() && rs.getInt(1) > 0 && rs.getInt(2) == 0; + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + return true; + } + finally + { + if (rs != null) + { + try + { + rs.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + if (ps != null) + { + try + { + ps.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + if (conn != null) + { + try + { + conn.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + } + } + + @Override + public List getOwners(final Block block) + { + Connection conn = null; + PreparedStatement ps = null; + ResultSet rs = null; + List owners = new ArrayList(); + try + { + conn = cpds.getConnection(); + ps = getStatementPlayersByLocation(conn, block.getWorld().getName(), block.getX(), block.getY(), block.getZ()); + rs = ps.executeQuery(); + while (rs.next()) + { + owners.add(rs.getString(1)); + } + return owners; + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + return owners; + } + finally + { + if (rs != null) + { + try + { + rs.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + if (ps != null) + { + try + { + ps.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + if (conn != null) + { + try + { + conn.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + } + } + + @Override + public int unprotectBlock(final Block block) + { + Connection conn = null; + PreparedStatement ps = null; + try + { + conn = cpds.getConnection(); + ps = getStatementDeleteByLocation(conn, block.getWorld().getName(), block.getX(), block.getY(), block.getZ()); + return ps.executeUpdate(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + return 0; + } + finally + { + if (ps != null) + { + try + { + ps.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + if (conn != null) + { + try + { + conn.close(); + } + catch (SQLException ex) + { + LOGGER.log(Level.SEVERE, null, ex); + } + } + } + } + + @Override + public void onPluginDeactivation() + { + cpds.close(); + } +} diff --git a/EssentialsProtect/src/net/ess3/protect/data/ProtectedBlockMemory.java b/EssentialsProtect/src/net/ess3/protect/data/ProtectedBlockMemory.java new file mode 100644 index 000000000..10c825154 --- /dev/null +++ b/EssentialsProtect/src/net/ess3/protect/data/ProtectedBlockMemory.java @@ -0,0 +1,258 @@ +package net.ess3.protect.data; + +import java.util.*; +import java.util.Map.Entry; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.plugin.Plugin; + + +public final class ProtectedBlockMemory implements IProtectedBlock +{ + private final transient List worlds = new ArrayList(); + private final transient List playerNames = new ArrayList(); + private final transient IProtectedBlock storage; + private final transient Plugin plugin; + + + static class ProtectedLocation + { + private final transient int x; + private final transient int y; + private final transient int z; + private final transient int w; + + public ProtectedLocation(final Block block, final int worldId) + { + this.x = block.getX(); + this.y = block.getY(); + this.z = block.getZ(); + this.w = worldId; + } + + public ProtectedLocation(final OwnedBlock ownedBlock, final int worldId) + { + this.x = ownedBlock.x; + this.y = ownedBlock.y; + this.z = ownedBlock.z; + this.w = worldId; + } + + @Override + public boolean equals(final Object object) + { + if (object instanceof ProtectedLocation) + { + final ProtectedLocation pLoc = (ProtectedLocation)object; + return x == pLoc.x && y == pLoc.y && z == pLoc.z && w == pLoc.w; + } + return false; + } + + @Override + public int hashCode() + { + return x ^ y ^ z ^ w; + } + } + + + static class ProtectedBy + { + private transient int playerId = -1; + private transient Set playerIds; + + public void add(final int playerId) + { + if (this.playerId == -1 || this.playerId == playerId) + { + this.playerId = playerId; + } + else + { + if (playerIds == null) + { + playerIds = new HashSet(4); + playerIds.add(this.playerId); + } + playerIds.add(playerId); + } + } + + public boolean contains(final int playerId) + { + if (playerIds == null) + { + return this.playerId == playerId; + } + return playerIds.contains(playerId); + } + + public List getPlayers(final List playerNames) + { + final List list = new ArrayList(2); + if (playerIds == null) + { + list.add(playerNames.get(playerId)); + } + else + { + for (Integer integer : playerIds) + { + list.add(playerNames.get(integer)); + } + } + return list; + } + + public int size() + { + if (playerIds == null) + { + return 1; + } + return playerIds.size(); + } + } + private final transient Map blocks = new HashMap(); + + public ProtectedBlockMemory(final IProtectedBlock storage, final Plugin plugin) + { + this.storage = storage; + this.plugin = plugin; + importProtections(storage.exportProtections()); + } + + @Override + public void clearProtections() + { + blocks.clear(); + } + + @Override + public void importProtections(final List blocks) + { + for (OwnedBlock ownedBlock : blocks) + { + final ProtectedLocation pl = new ProtectedLocation(ownedBlock, getWorldId(ownedBlock.world)); + if (ownedBlock.playerName == null) + { + continue; + } + protectBlock(pl, ownedBlock.playerName); + } + } + + @Override + public List exportProtections() + { + final List blockList = new ArrayList(blocks.size()); + for (Entry entry : blocks.entrySet()) + { + for (String name : entry.getValue().getPlayers(playerNames)) + { + final OwnedBlock ob = new OwnedBlock( + entry.getKey().x, + entry.getKey().y, + entry.getKey().z, + worlds.get(entry.getKey().w), + name); + blockList.add(ob); + } + } + return blockList; + } + + @Override + public void protectBlock(final Block block, final String playerName) + { + final ProtectedLocation pl = new ProtectedLocation(block, getWorldId(block.getWorld())); + protectBlock(pl, playerName); + plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, new Runnable() + { + @Override + public void run() + { + storage.protectBlock(block, playerName); + } + }); + } + + private void protectBlock(final ProtectedLocation pl, final String playerName) + { + final int playerId = getPlayerId(playerName); + ProtectedBy pb = blocks.get(pl); + if (pb == null) + { + pb = new ProtectedBy(); + blocks.put(pl, pb); + } + pb.add(playerId); + } + + @Override + public boolean isProtected(final Block block, final String playerName) + { + final int playerId = getPlayerId(playerName); + final ProtectedLocation pl = new ProtectedLocation(block, getWorldId(block.getWorld())); + final ProtectedBy pb = blocks.get(pl); + return !pb.contains(playerId); + } + + @Override + public List getOwners(final Block block) + { + ProtectedLocation pl = new ProtectedLocation(block, getWorldId(block.getWorld())); + ProtectedBy pb = blocks.get(pl); + return pb.getPlayers(playerNames); + } + + @Override + public int unprotectBlock(final Block block) + { + final ProtectedLocation pl = new ProtectedLocation(block, getWorldId(block.getWorld())); + final ProtectedBy pb = blocks.remove(pl); + plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, new Runnable() + { + @Override + public void run() + { + storage.unprotectBlock(block); + } + }); + return pb.size(); + } + + private int getPlayerId(final String playername) + { + int id = playerNames.indexOf(playername); + if (id < 0) + { + playerNames.add(playername); + id = playerNames.indexOf(playername); + } + return id; + } + + private int getWorldId(final World world) + { + return getWorldId(world.getName()); + } + + private int getWorldId(final String name) + { + int id = worlds.indexOf(name); + if (id < 0) + { + worlds.add(name); + id = worlds.indexOf(name); + } + return id; + } + + @Override + public void onPluginDeactivation() + { + storage.onPluginDeactivation(); + } +} diff --git a/EssentialsProtect/src/net/ess3/protect/data/ProtectedBlockMySQL.java b/EssentialsProtect/src/net/ess3/protect/data/ProtectedBlockMySQL.java new file mode 100644 index 000000000..9fd17d0a7 --- /dev/null +++ b/EssentialsProtect/src/net/ess3/protect/data/ProtectedBlockMySQL.java @@ -0,0 +1,160 @@ +package net.ess3.protect.data; + +import java.beans.PropertyVetoException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.logging.Level; +import java.util.logging.Logger; + + +public class ProtectedBlockMySQL extends ProtectedBlockJDBC +{ + public ProtectedBlockMySQL(final String url, final String username, final String password) throws PropertyVetoException + { + super("com.mysql.jdbc.Driver", url, username, password); + } + private static final String QueryCreateTable = + "CREATE TABLE IF NOT EXISTS `EssentialsProtect` (" + + "`worldName` varchar(60) NOT NULL," + + "`x` int(11) NOT NULL, `y` int(11) NOT NULL, `z` int(11) NOT NULL," + + "`playerName` varchar(150) DEFAULT NULL," + + "KEY `pos` (`worldName`,`x`,`z`,`y`)" + + ") ENGINE=MyISAM DEFAULT CHARSET=utf8"; + + @Override + protected PreparedStatement getStatementCreateTable(final Connection conn) throws SQLException + { + return conn.prepareStatement(QueryCreateTable); + } + private static final String QueryUpdateFrom2_0TableCheck = + "SHOW COLUMNS FROM `EssentialsProtect` LIKE 'id';"; + private static final String QueryUpdateFrom2_0Table = + "ALTER TABLE `EssentialsProtect` " + + "CHARACTER SET = utf8, ENGINE = MyISAM," + + "DROP COLUMN `id`," + + "CHANGE COLUMN `playerName` `playerName` VARCHAR(150) NULL AFTER `z`," + + "CHANGE COLUMN `worldName` `worldName` VARCHAR(60) NOT NULL," + + "ADD INDEX `position` (`worldName` ASC, `x` ASC, `z` ASC, `y` ASC)," + + "DROP PRIMARY KEY ;"; + + @Override + protected PreparedStatement getStatementUpdateFrom2_0Table(final Connection conn) throws SQLException + { + PreparedStatement testPS = null; + ResultSet testRS = null; + try + { + testPS = conn.prepareStatement(QueryUpdateFrom2_0TableCheck); + testRS = testPS.executeQuery(); + if (testRS.first()) + { + return conn.prepareStatement(QueryUpdateFrom2_0Table); + } + else + { + return conn.prepareStatement("SELECT 1;"); + } + } + finally + { + if (testRS != null) + { + try + { + testRS.close(); + } + catch (SQLException ex) + { + Logger.getLogger(ProtectedBlockMySQL.class.getName()).log(Level.SEVERE, null, ex); + } + } + if (testPS != null) + { + try + { + testPS.close(); + } + catch (SQLException ex) + { + Logger.getLogger(ProtectedBlockMySQL.class.getName()).log(Level.SEVERE, null, ex); + } + } + } + } + private static final String QueryDeleteAll = "DELETE FROM EssentialsProtect;"; + + @Override + protected PreparedStatement getStatementDeleteAll(final Connection conn) throws SQLException + { + return conn.prepareStatement(QueryDeleteAll); + } + private static final String QueryInsert = + "INSERT INTO EssentialsProtect (worldName, x, y, z, playerName) VALUES (?, ?, ?, ?, ?);"; + + @Override + protected PreparedStatement getStatementInsert(final Connection conn, final String world, final int x, final int y, final int z, + final String playerName) throws SQLException + { + final PreparedStatement ps = conn.prepareStatement(QueryInsert); + ps.setString(1, world); + ps.setInt(2, x); + ps.setInt(3, y); + ps.setInt(4, z); + ps.setString(5, playerName); + return ps; + } + private static final String QueryCountByPlayer = + "SELECT COUNT(playerName), SUM(playerName = ?) FROM EssentialsProtect " + + "WHERE worldName = ? AND x = ? AND y = ? AND z = ? GROUP BY x;"; + + @Override + protected PreparedStatement getStatementPlayerCountByLocation(final Connection conn, final String world, final int x, final int y, final int z, + final String playerName) throws SQLException + { + final PreparedStatement ps = conn.prepareStatement(QueryCountByPlayer); + ps.setString(1, playerName); + ps.setString(2, world); + ps.setInt(3, x); + ps.setInt(4, y); + ps.setInt(5, z); + return ps; + } + private static final String QueryPlayersByLocation = + "SELECT playerName FROM EssentialsProtect WHERE worldname = ? AND x = ? AND y = ? AND z = ?;"; + + @Override + protected PreparedStatement getStatementPlayersByLocation(final Connection conn, final String world, + final int x, final int y, final int z) throws SQLException + { + final PreparedStatement ps = conn.prepareStatement(QueryPlayersByLocation); + ps.setString(1, world); + ps.setInt(2, x); + ps.setInt(3, y); + ps.setInt(4, z); + return ps; + } + private static final String QueryDeleteByLocation = + "DELETE FROM EssentialsProtect WHERE worldName = ? AND x = ? AND y = ? AND z = ?;"; + + @Override + protected PreparedStatement getStatementDeleteByLocation(final Connection conn, final String world, + final int x, final int y, final int z) throws SQLException + { + final PreparedStatement ps = conn.prepareStatement(QueryDeleteByLocation); + ps.setString(1, world); + ps.setInt(2, x); + ps.setInt(3, y); + ps.setInt(4, z); + return ps; + } + private static final String QueryAllBlocks = + "SELECT worldName, x, y, z, playerName FROM EssentialsProtect;"; + + @Override + protected PreparedStatement getStatementAllBlocks(final Connection conn) throws SQLException + { + return conn.prepareStatement(QueryAllBlocks); + } +} diff --git a/EssentialsProtect/src/net/ess3/protect/data/ProtectedBlockSQLite.java b/EssentialsProtect/src/net/ess3/protect/data/ProtectedBlockSQLite.java new file mode 100644 index 000000000..65dbac213 --- /dev/null +++ b/EssentialsProtect/src/net/ess3/protect/data/ProtectedBlockSQLite.java @@ -0,0 +1,108 @@ +package net.ess3.protect.data; + +import java.beans.PropertyVetoException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; + + +public class ProtectedBlockSQLite extends ProtectedBlockJDBC +{ + public ProtectedBlockSQLite(final String url) throws PropertyVetoException + { + super("org.sqlite.JDBC", url); + } + private static final String QueryCreateTable = + "CREATE TABLE IF NOT EXISTS EssentialsProtect (" + + "worldName TEXT ,playerName TEXT, " + + "x NUMERIC, y NUMERIC, z NUMERIC)"; + + @Override + protected PreparedStatement getStatementCreateTable(final Connection conn) throws SQLException + { + return conn.prepareStatement(QueryCreateTable); + } + private static final String QueryUpdateFrom2_0Table = + "CREATE INDEX IF NOT EXISTS position ON EssentialsProtect (" + + "worldName, x, z, y)"; + + @Override + protected PreparedStatement getStatementUpdateFrom2_0Table(final Connection conn) throws SQLException + { + return conn.prepareStatement(QueryUpdateFrom2_0Table); + } + private static final String QueryDeleteAll = "DELETE FROM EssentialsProtect;"; + + @Override + protected PreparedStatement getStatementDeleteAll(final Connection conn) throws SQLException + { + return conn.prepareStatement(QueryDeleteAll); + } + private static final String QueryInsert = + "INSERT INTO EssentialsProtect (worldName, x, y, z, playerName) VALUES (?, ?, ?, ?, ?);"; + + @Override + protected PreparedStatement getStatementInsert(final Connection conn, final String world, + final int x, final int y, final int z, final String playerName) throws SQLException + { + final PreparedStatement ps = conn.prepareStatement(QueryInsert); + ps.setString(1, world); + ps.setInt(2, x); + ps.setInt(3, y); + ps.setInt(4, z); + ps.setString(5, playerName); + return ps; + } + private static final String QueryPlayerCountByLocation = + "SELECT COUNT(playerName), SUM(playerName = ?) FROM EssentialsProtect " + + "WHERE worldName = ? AND x = ? AND y = ? AND z = ? GROUP BY x;"; + + @Override + protected PreparedStatement getStatementPlayerCountByLocation(final Connection conn, final String world, + final int x, final int y, final int z, final String playerName) throws SQLException + { + final PreparedStatement ps = conn.prepareStatement(QueryPlayerCountByLocation); + ps.setString(1, playerName); + ps.setString(2, world); + ps.setInt(3, x); + ps.setInt(4, y); + ps.setInt(5, z); + return ps; + } + private static final String QueryPlayersByLocation = + "SELECT playerName FROM EssentialsProtect WHERE worldname = ? AND x = ? AND y = ? AND z = ?;"; + + @Override + protected PreparedStatement getStatementPlayersByLocation(final Connection conn, final String world, + final int x, final int y, final int z) throws SQLException + { + final PreparedStatement ps = conn.prepareStatement(QueryPlayersByLocation); + ps.setString(1, world); + ps.setInt(2, x); + ps.setInt(3, y); + ps.setInt(4, z); + return ps; + } + private static final String QueryDeleteByLocation = + "DELETE FROM EssentialsProtect WHERE worldName = ? AND x = ? AND y = ? AND z = ?;"; + + @Override + protected PreparedStatement getStatementDeleteByLocation(final Connection conn, final String world, + final int x, final int y, final int z) throws SQLException + { + final PreparedStatement ps = conn.prepareStatement(QueryDeleteByLocation); + ps.setString(1, world); + ps.setInt(2, x); + ps.setInt(3, y); + ps.setInt(4, z); + return ps; + } + private static final String QueryAllBlocks = + "SELECT worldName, x, y, z, playerName FROM EssentialsProtect;"; + + @Override + protected PreparedStatement getStatementAllBlocks(final Connection conn) throws SQLException + { + return conn.prepareStatement(QueryAllBlocks); + } +} diff --git a/EssentialsProtect/src/plugin.yml b/EssentialsProtect/src/plugin.yml index b11803595..1510a4fa1 100644 --- a/EssentialsProtect/src/plugin.yml +++ b/EssentialsProtect/src/plugin.yml @@ -1,6 +1,6 @@ # This determines the command prefix when there are conflicts (/name:home, /name:help, etc.) name: EssentialsProtect -main: com.earth2me.essentials.protect.EssentialsProtect +main: net.ess3.protect.EssentialsProtect # Note to developers: This next line cannot change, or the automatic versioning system will break. version: ${build.number} website: http://tiny.cc/EssentialsWiki diff --git a/EssentialsSigns/src/com/earth2me/essentials/signs/EssentialsSign.java b/EssentialsSigns/src/com/earth2me/essentials/signs/EssentialsSign.java deleted file mode 100644 index 8f8a4814a..000000000 --- a/EssentialsSigns/src/com/earth2me/essentials/signs/EssentialsSign.java +++ /dev/null @@ -1,516 +0,0 @@ -package com.earth2me.essentials.signs; - -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.IEssentials; -import com.earth2me.essentials.api.IUser; -import java.util.HashSet; -import java.util.Locale; -import java.util.Set; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.block.Sign; -import org.bukkit.entity.Player; -import org.bukkit.event.block.SignChangeEvent; -import org.bukkit.inventory.ItemStack; - - -public class EssentialsSign -{ - private static final Set EMPTY_SET = new HashSet(); - protected transient final String signName; - - public EssentialsSign(final String signName) - { - this.signName = signName; - } - - public final boolean onSignCreate(final SignChangeEvent event, final IEssentials ess) - { - final ISign sign = new EventSign(event); - final IUser user = ess.getUser(event.getPlayer()); - if (!SignsPermissions.getCreatePermission(signName).isAuthorized(user)) - { - // Return true, so other plugins can use the same sign title, just hope - // they won't change it to §1[Signname] - return true; - } - sign.setLine(0, _("signFormatFail", this.signName)); - try - { - final boolean ret = onSignCreate(sign, user, getUsername(user), ess); - if (ret) - { - sign.setLine(0, getSuccessName()); - } - return ret; - } - catch (ChargeException ex) - { - ess.getCommandHandler().showCommandError(user, signName, ex); - } - catch (SignException ex) - { - ess.getCommandHandler().showCommandError(user, signName, ex); - } - // Return true, so the player sees the wrong sign. - return true; - } - - public String getSuccessName() - { - return _("signFormatSuccess", this.signName); - } - - public String getTemplateName() - { - return _("signFormatTemplate", this.signName); - } - - private String getUsername(final IUser user) - { - return user.getName().substring(0, user.getName().length() > 13 ? 13 : user.getName().length()); - } - - public final boolean onSignInteract(final Block block, final Player player, final IEssentials ess) - { - final ISign sign = new BlockSign(block); - final IUser user = ess.getUser(player); - try - { - return SignsPermissions.getUsePermission(signName).isAuthorized(user) - && onSignInteract(sign, user, getUsername(user), ess); - } - catch (ChargeException ex) - { - ess.getCommandHandler().showCommandError(user, signName, ex); - return false; - } - catch (SignException ex) - { - ess.getCommandHandler().showCommandError(user, signName, ex); - return false; - } - } - - public final boolean onSignBreak(final Block block, final Player player, final IEssentials ess) - { - final ISign sign = new BlockSign(block); - final IUser user = ess.getUser(player); - try - { - return SignsPermissions.getBreakPermission(signName).isAuthorized(user) - && onSignBreak(sign, user, getUsername(user), ess); - } - catch (SignException ex) - { - ess.getCommandHandler().showCommandError(user, signName, ex); - return false; - } - } - - protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException - { - return true; - } - - protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException - { - return true; - } - - protected boolean onSignBreak(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException - { - return true; - } - - public final boolean onBlockPlace(final Block block, final Player player, final IEssentials ess) - { - final IUser user = ess.getUser(player); - try - { - return onBlockPlace(block, user, getUsername(user), ess); - } - catch (ChargeException ex) - { - ess.getCommandHandler().showCommandError(user, signName, ex); - } - catch (SignException ex) - { - ess.getCommandHandler().showCommandError(user, signName, ex); - } - return false; - } - - public final boolean onBlockInteract(final Block block, final Player player, final IEssentials ess) - { - final IUser user = ess.getUser(player); - try - { - return onBlockInteract(block, user, getUsername(user), ess); - } - catch (ChargeException ex) - { - ess.getCommandHandler().showCommandError(user, signName, ex); - } - catch (SignException ex) - { - ess.getCommandHandler().showCommandError(user, signName, ex); - } - return false; - } - - public final boolean onBlockBreak(final Block block, final Player player, final IEssentials ess) - { - final IUser user = ess.getUser(player); - try - { - return onBlockBreak(block, user, getUsername(user), ess); - } - catch (SignException ex) - { - ess.getCommandHandler().showCommandError(user, signName, ex); - } - return false; - } - - public boolean onBlockBreak(final Block block, final IEssentials ess) - { - return true; - } - - public boolean onBlockExplode(final Block block, final IEssentials ess) - { - return true; - } - - public boolean onBlockBurn(final Block block, final IEssentials ess) - { - return true; - } - - public boolean onBlockIgnite(final Block block, final IEssentials ess) - { - return true; - } - - public boolean onBlockPush(final Block block, final IEssentials ess) - { - return true; - } - - public static boolean checkIfBlockBreaksSigns(final Block block) - { - final Block sign = block.getRelative(BlockFace.UP); - if (sign.getType() == Material.SIGN_POST && isValidSign(new BlockSign(sign))) - { - return true; - } - final BlockFace[] directions = new BlockFace[] - { - BlockFace.NORTH, - BlockFace.EAST, - BlockFace.SOUTH, - BlockFace.WEST - }; - for (BlockFace blockFace : directions) - { - final Block signblock = block.getRelative(blockFace); - if (signblock.getType() == Material.WALL_SIGN) - { - final org.bukkit.material.Sign signMat = (org.bukkit.material.Sign)signblock.getState().getData(); - if (signMat != null && signMat.getFacing() == blockFace && isValidSign(new BlockSign(signblock))) - { - return true; - } - } - } - return false; - } - - public static boolean isValidSign(final ISign sign) - { - return sign.getLine(0).matches("§1\\[.*\\]"); - } - - protected boolean onBlockPlace(final Block block, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException - { - return true; - } - - protected boolean onBlockInteract(final Block block, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException - { - return true; - } - - protected boolean onBlockBreak(final Block block, final IUser player, final String username, final IEssentials ess) throws SignException - { - return true; - } - - public Set getBlocks() - { - return EMPTY_SET; - } - - protected final void validateTrade(final ISign sign, final int index, final IEssentials ess) throws SignException - { - final String line = sign.getLine(index).trim(); - if (line.isEmpty()) - { - return; - } - final Trade trade = getTrade(sign, index, 0, ess); - final Double money = trade.getMoney(); - if (money != null) - { - sign.setLine(index, Util.shortCurrency(money, ess)); - } - } - - protected final void validateTrade(final ISign sign, final int amountIndex, final int itemIndex, - final IUser player, final IEssentials ess) throws SignException - { - if (sign.getLine(itemIndex).equalsIgnoreCase("exp") || sign.getLine(itemIndex).equalsIgnoreCase("xp")) - { - int amount = getIntegerPositive(sign.getLine(amountIndex)); - sign.setLine(amountIndex, Integer.toString(amount)); - sign.setLine(itemIndex, "exp"); - return; - } - final Trade trade = getTrade(sign, amountIndex, itemIndex, player, ess); - final ItemStack item = trade.getItemStack(); - sign.setLine(amountIndex, Integer.toString(item.getAmount())); - sign.setLine(itemIndex, sign.getLine(itemIndex).trim()); - } - - protected final Trade getTrade(final ISign sign, final int amountIndex, final int itemIndex, - final IUser player, final IEssentials ess) throws SignException - { - if (sign.getLine(itemIndex).equalsIgnoreCase("exp") || sign.getLine(itemIndex).equalsIgnoreCase("xp")) - { - final int amount = getIntegerPositive(sign.getLine(amountIndex)); - return new Trade(amount, ess); - } - final ItemStack item = getItemStack(sign.getLine(itemIndex), 1, ess); - final int amount = Math.min(getIntegerPositive(sign.getLine(amountIndex)), item.getType().getMaxStackSize() * player.getInventory().getSize()); - if (item.getTypeId() == 0 || amount < 1) - { - throw new SignException(_("moreThanZero")); - } - item.setAmount(amount); - return new Trade(item, ess); - } - - protected final void validateInteger(final ISign sign, final int index) throws SignException - { - final String line = sign.getLine(index).trim(); - if (line.isEmpty()) - { - throw new SignException("Empty line " + index); - } - final int quantity = getIntegerPositive(line); - sign.setLine(index, Integer.toString(quantity)); - } - - protected final int getIntegerPositive(final String line) throws SignException - { - final int quantity = getInteger(line); - if (quantity < 1) - { - throw new SignException(_("moreThanZero")); - } - return quantity; - } - - protected final int getInteger(final String line) throws SignException - { - try - { - final int quantity = Integer.parseInt(line); - - return quantity; - } - catch (NumberFormatException ex) - { - throw new SignException("Invalid sign", ex); - } - } - - protected final ItemStack getItemStack(final String itemName, final int quantity, final IEssentials ess) throws SignException - { - try - { - final ItemStack item = ess.getItemDb().get(itemName); - item.setAmount(quantity); - return item; - } - catch (Exception ex) - { - throw new SignException(ex.getMessage(), ex); - } - } - - protected final Double getMoney(final String line) throws SignException - { - final boolean isMoney = line.matches("^[^0-9-\\.][\\.0-9]+$"); - return isMoney ? getDoublePositive(line.substring(1)) : null; - } - - protected final Double getDoublePositive(final String line) throws SignException - { - final double quantity = getDouble(line); - if (Math.round(quantity * 100.0) < 1.0) - { - throw new SignException(_("moreThanZero")); - } - return quantity; - } - - protected final Double getDouble(final String line) throws SignException - { - try - { - return Double.parseDouble(line); - } - catch (NumberFormatException ex) - { - throw new SignException(ex.getMessage(), ex); - } - } - - protected final Trade getTrade(final ISign sign, final int index, final IEssentials ess) throws SignException - { - return getTrade(sign, index, 1, ess); - } - - protected final Trade getTrade(final ISign sign, final int index, final int decrement, final IEssentials ess) throws SignException - { - final String line = sign.getLine(index).trim(); - if (line.isEmpty()) - { - return new Trade(signName.toLowerCase(Locale.ENGLISH) + "sign", ess); - } - - final Double money = getMoney(line); - if (money == null) - { - final String[] split = line.split("[ :]+", 2); - if (split.length != 2) - { - throw new SignException(_("invalidCharge")); - } - final int quantity = getIntegerPositive(split[0]); - - final String item = split[1].toLowerCase(Locale.ENGLISH); - if (item.equalsIgnoreCase("times")) - { - sign.setLine(index, (quantity - decrement) + " times"); - return new Trade(signName.toLowerCase(Locale.ENGLISH) + "sign", ess); - } - else if (item.equalsIgnoreCase("exp") || item.equalsIgnoreCase("xp")) - { - sign.setLine(index, quantity + " exp"); - return new Trade(quantity, ess); - } - else - { - final ItemStack stack = getItemStack(item, quantity, ess); - sign.setLine(index, quantity + " " + item); - return new Trade(stack, ess); - } - } - else - { - return new Trade(money, ess); - } - } - - - static class EventSign implements ISign - { - private final transient SignChangeEvent event; - private final transient Block block; - - public EventSign(final SignChangeEvent event) - { - this.event = event; - this.block = event.getBlock(); - } - - @Override - public final String getLine(final int index) - { - return event.getLine(index); - } - - @Override - public final void setLine(final int index, final String text) - { - event.setLine(index, text); - } - - @Override - public Block getBlock() - { - return block; - } - - @Override - public void updateSign() - { - } - } - - - static class BlockSign implements ISign - { - private final transient Sign sign; - private final transient Block block; - - public BlockSign(final Block block) - { - this.block = block; - this.sign = (Sign)block.getState(); - } - - @Override - public final String getLine(final int index) - { - return sign.getLine(index); - } - - @Override - public final void setLine(final int index, final String text) - { - sign.setLine(index, text); - } - - @Override - public final Block getBlock() - { - return block; - } - - @Override - public final void updateSign() - { - sign.update(); - } - } - - - public interface ISign - { - String getLine(final int index); - - void setLine(final int index, final String text); - - public Block getBlock(); - - void updateSign(); - } -} diff --git a/EssentialsSigns/src/com/earth2me/essentials/signs/EssentialsSignsPlugin.java b/EssentialsSigns/src/com/earth2me/essentials/signs/EssentialsSignsPlugin.java deleted file mode 100644 index 97146439e..000000000 --- a/EssentialsSigns/src/com/earth2me/essentials/signs/EssentialsSignsPlugin.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.earth2me.essentials.signs; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IEssentials; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.bukkit.Bukkit; -import org.bukkit.plugin.PluginManager; -import org.bukkit.plugin.java.JavaPlugin; - - -public class EssentialsSignsPlugin extends JavaPlugin implements ISignsPlugin -{ - private static final transient Logger LOGGER = Bukkit.getLogger(); - private transient SignsConfigHolder config; - - @Override - public void onEnable() - { - final PluginManager pluginManager = getServer().getPluginManager(); - final IEssentials ess = (IEssentials)pluginManager.getPlugin("Essentials3"); - if (!this.getDescription().getVersion().equals(ess.getDescription().getVersion())) - { - LOGGER.log(Level.WARNING, _("versionMismatchAll")); - } - if (!ess.isEnabled()) - { - this.setEnabled(false); - return; - } - - final SignBlockListener signBlockListener = new SignBlockListener(ess, this); - pluginManager.registerEvents(signBlockListener, this); - - final SignPlayerListener signPlayerListener = new SignPlayerListener(ess, this); - pluginManager.registerEvents(signPlayerListener, this); - - final SignEntityListener signEntityListener = new SignEntityListener(ess, this); - pluginManager.registerEvents(signEntityListener, this); - - config = new SignsConfigHolder(ess, this); - } - - @Override - public void onDisable() - { - } - - @Override - public SignsConfigHolder getSettings() - { - return config; - } -} diff --git a/EssentialsSigns/src/com/earth2me/essentials/signs/ISignsPlugin.java b/EssentialsSigns/src/com/earth2me/essentials/signs/ISignsPlugin.java deleted file mode 100644 index 2847ef87e..000000000 --- a/EssentialsSigns/src/com/earth2me/essentials/signs/ISignsPlugin.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.earth2me.essentials.signs; - -import com.earth2me.essentials.api.IEssentialsModule; - - -public interface ISignsPlugin extends IEssentialsModule -{ - SignsConfigHolder getSettings(); -} diff --git a/EssentialsSigns/src/com/earth2me/essentials/signs/SignBalance.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignBalance.java deleted file mode 100644 index cb8e568aa..000000000 --- a/EssentialsSigns/src/com/earth2me/essentials/signs/SignBalance.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.earth2me.essentials.signs; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.utils.Util; - - -public class SignBalance extends EssentialsSign -{ - public SignBalance() - { - super("Balance"); - } - - @Override - protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException - { - player.sendMessage(_("balance", Util.displayCurrency(player.getMoney(), ess))); - return true; - } -} diff --git a/EssentialsSigns/src/com/earth2me/essentials/signs/SignBlockListener.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignBlockListener.java deleted file mode 100644 index 80e603394..000000000 --- a/EssentialsSigns/src/com/earth2me/essentials/signs/SignBlockListener.java +++ /dev/null @@ -1,264 +0,0 @@ -package com.earth2me.essentials.signs; - -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.ISettings; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.utils.Util; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.Sign; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.block.*; - - -public class SignBlockListener implements Listener -{ - private final transient IEssentials ess; - private final transient ISignsPlugin plugin; - private final static Logger LOGGER = Logger.getLogger("Minecraft"); - private final static int WALL_SIGN = Material.WALL_SIGN.getId(); - private final static int SIGN_POST = Material.SIGN_POST.getId(); - - public SignBlockListener(final IEssentials ess, final ISignsPlugin plugin) - { - this.ess = ess; - this.plugin = plugin; - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockBreak(final BlockBreakEvent event) - { - ISettings settings = ess.getSettings(); - settings.acquireReadLock(); - if (plugin.getSettings().areSignsDisabled()) - { - return; - } - - if (protectSignsAndBlocks(event.getBlock(), event.getPlayer())) - { - event.setCancelled(true); - } - } - - public boolean protectSignsAndBlocks(final Block block, final Player player) - { - final int mat = block.getTypeId(); - if (mat == SIGN_POST || mat == WALL_SIGN) - { - final Sign csign = (Sign)block.getState(); - - for (EssentialsSign sign : plugin.getSettings().getEnabledSigns()) - { - if (csign.getLine(0).equalsIgnoreCase(sign.getSuccessName()) - && !sign.onSignBreak(block, player, ess)) - { - return true; - } - } - } - // prevent any signs be broken by destroying the block they are attached to - if (EssentialsSign.checkIfBlockBreaksSigns(block)) - { - LOGGER.log(Level.INFO, "Prevented that a block was broken next to a sign."); - return true; - } - for (EssentialsSign sign : plugin.getSettings().getEnabledSigns()) - { - if (sign.getBlocks().contains(block.getType()) - && !sign.onBlockBreak(block, player, ess)) - { - LOGGER.log(Level.INFO, "A block was protected by a sign."); - return true; - } - } - return false; - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onSignChange(final SignChangeEvent event) - { - if (plugin.getSettings().areSignsDisabled()) - { - return; - } - IUser user = ess.getUser(event.getPlayer()); - - for (int i = 0; i < 4; i++) - { - event.setLine(i, Util.formatString(user, "essentials.signs", event.getLine(i))); - } - - for (Signs signs : Signs.values()) - { - final EssentialsSign sign = signs.getSign(); - if (event.getLine(0).equalsIgnoreCase(sign.getSuccessName())) - { - event.setCancelled(true); - return; - } - if (event.getLine(0).equalsIgnoreCase(sign.getTemplateName()) - && !sign.onSignCreate(event, ess)) - { - event.setCancelled(true); - return; - } - } - } - - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onBlockPlace(final BlockPlaceEvent event) - { - if (plugin.getSettings().areSignsDisabled()) - { - return; - } - - final Block against = event.getBlockAgainst(); - if ((against.getTypeId() == WALL_SIGN - || against.getTypeId() == SIGN_POST) - && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(against))) - { - event.setCancelled(true); - return; - } - final Block block = event.getBlock(); - if (block.getTypeId() == WALL_SIGN - || block.getTypeId() == SIGN_POST) - { - return; - } - for (Signs signs : Signs.values()) - { - final EssentialsSign sign = signs.getSign(); - if (sign.getBlocks().contains(block.getType()) - && !sign.onBlockPlace(block, event.getPlayer(), ess)) - { - event.setCancelled(true); - return; - } - } - } - - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onBlockBurn(final BlockBurnEvent event) - { - if (plugin.getSettings().areSignsDisabled()) - { - return; - } - - final Block block = event.getBlock(); - if (((block.getTypeId() == WALL_SIGN - || block.getTypeId() == SIGN_POST) - && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(block))) - || EssentialsSign.checkIfBlockBreaksSigns(block)) - { - event.setCancelled(true); - return; - } - for (EssentialsSign sign : plugin.getSettings().getEnabledSigns()) - { - if (sign.getBlocks().contains(block.getType()) - && !sign.onBlockBurn(block, ess)) - { - event.setCancelled(true); - return; - } - } - } - - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onBlockIgnite(final BlockIgniteEvent event) - { - if (plugin.getSettings().areSignsDisabled()) - { - return; - } - - final Block block = event.getBlock(); - if (((block.getTypeId() == WALL_SIGN - || block.getTypeId() == SIGN_POST) - && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(block))) - || EssentialsSign.checkIfBlockBreaksSigns(block)) - { - event.setCancelled(true); - return; - } - for (EssentialsSign sign : plugin.getSettings().getEnabledSigns()) - { - if (sign.getBlocks().contains(block.getType()) - && !sign.onBlockIgnite(block, ess)) - { - event.setCancelled(true); - return; - } - } - } - - @EventHandler(priority = EventPriority.LOW) - public void onBlockPistonExtend(final BlockPistonExtendEvent event) - { - if (plugin.getSettings().areSignsDisabled()) - { - return; - } - - for (Block block : event.getBlocks()) - { - if (((block.getTypeId() == WALL_SIGN - || block.getTypeId() == SIGN_POST) - && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(block))) - || EssentialsSign.checkIfBlockBreaksSigns(block)) - { - event.setCancelled(true); - return; - } - for (EssentialsSign sign : plugin.getSettings().getEnabledSigns()) - { - if (sign.getBlocks().contains(block.getType()) - && !sign.onBlockPush(block, ess)) - { - event.setCancelled(true); - return; - } - } - } - } - - @EventHandler(priority = EventPriority.LOW) - public void onBlockPistonRetract(final BlockPistonRetractEvent event) - { - if (plugin.getSettings().areSignsDisabled()) - { - return; - } - - if (event.isSticky()) - { - final Block block = event.getBlock(); - if (((block.getTypeId() == WALL_SIGN - || block.getTypeId() == SIGN_POST) - && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(block))) - || EssentialsSign.checkIfBlockBreaksSigns(block)) - { - event.setCancelled(true); - return; - } - for (EssentialsSign sign : plugin.getSettings().getEnabledSigns()) - { - if (sign.getBlocks().contains(block.getType()) - && !sign.onBlockPush(block, ess)) - { - event.setCancelled(true); - return; - } - } - } - } -} diff --git a/EssentialsSigns/src/com/earth2me/essentials/signs/SignBuy.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignBuy.java deleted file mode 100644 index dcb0ec857..000000000 --- a/EssentialsSigns/src/com/earth2me/essentials/signs/SignBuy.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.earth2me.essentials.signs; - -import com.earth2me.essentials.api.ChargeException; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.economy.Trade; - - -public class SignBuy extends EssentialsSign -{ - public SignBuy() - { - super("Buy"); - } - - @Override - protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException - { - validateTrade(sign, 1, 2, player, ess); - validateTrade(sign, 3, ess); - return true; - } - - @Override - protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException - { - final Trade items = getTrade(sign, 1, 2, player, ess); - final Trade charge = getTrade(sign, 3, ess); - charge.isAffordableFor(player); - if (!items.pay(player, false)) - { - throw new ChargeException("Inventory full"); - } - charge.charge(player); - Trade.log("Sign", "Buy", "Interact", username, charge, username, items, sign.getBlock().getLocation(), ess); - return true; - } -} diff --git a/EssentialsSigns/src/com/earth2me/essentials/signs/SignDisposal.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignDisposal.java deleted file mode 100644 index 056c79e67..000000000 --- a/EssentialsSigns/src/com/earth2me/essentials/signs/SignDisposal.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.earth2me.essentials.signs; - -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IUser; - - -public class SignDisposal extends EssentialsSign -{ - public SignDisposal() - { - super("Disposal"); - } - - @Override - protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) - { - player.sendMessage("Bukkit broke this sign :("); - //TODO: wait for a fix in bukkit - //Problem: Items can be duplicated - //player.getBase().openInventory(ess.getServer().createInventory(player, 36)); - return true; - } -} diff --git a/EssentialsSigns/src/com/earth2me/essentials/signs/SignEnchant.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignEnchant.java deleted file mode 100644 index 222a04909..000000000 --- a/EssentialsSigns/src/com/earth2me/essentials/signs/SignEnchant.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.earth2me.essentials.signs; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.ChargeException; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.bukkit.Enchantments; -import com.earth2me.essentials.economy.Trade; -import java.util.Locale; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.ItemStack; - - -public class SignEnchant extends EssentialsSign -{ - public SignEnchant() - { - super("Enchant"); - } - - @Override - protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException - { - final ItemStack stack = sign.getLine(1).equals("*") || sign.getLine(1).equalsIgnoreCase("any") ? null : getItemStack(sign.getLine(1), 1, ess); - final String[] enchantLevel = sign.getLine(2).split(":"); - if (enchantLevel.length != 2) - { - throw new SignException(_("invalidSignLine", 3)); - } - final Enchantment enchantment = Enchantments.getByName(enchantLevel[0]); - if (enchantment == null) - { - throw new SignException(_("enchantmentNotFound")); - } - int level; - try - { - level = Integer.parseInt(enchantLevel[1]); - } - catch (NumberFormatException ex) - { - throw new SignException(ex.getMessage(), ex); - } - if (level < 1 || level > enchantment.getMaxLevel()) - { - level = enchantment.getMaxLevel(); - sign.setLine(2, enchantLevel[0] + ":" + level); - } - try - { - if (stack != null) - { - stack.addEnchantment(enchantment, level); - } - } - catch (Throwable ex) - { - throw new SignException(ex.getMessage(), ex); - } - getTrade(sign, 3, ess); - return true; - } - - @Override - protected boolean onSignInteract(ISign sign, IUser player, String username, IEssentials ess) throws SignException, ChargeException - { - final ItemStack search = sign.getLine(1).equals("*") || sign.getLine(1).equalsIgnoreCase("any") ? null : getItemStack(sign.getLine(1), 1, ess); - int slot = -1; - final Trade charge = getTrade(sign, 3, ess); - charge.isAffordableFor(player); - final String[] enchantLevel = sign.getLine(2).split(":"); - if (enchantLevel.length != 2) - { - throw new SignException(_("invalidSignLine", 3)); - } - final Enchantment enchantment = Enchantments.getByName(enchantLevel[0]); - if (enchantment == null) - { - throw new SignException(_("enchantmentNotFound")); - } - int level; - try - { - level = Integer.parseInt(enchantLevel[1]); - } - catch (NumberFormatException ex) - { - level = enchantment.getMaxLevel(); - } - - final ItemStack playerHand = player.getItemInHand(); - if (playerHand == null - || playerHand.getAmount() != 1 - || (playerHand.containsEnchantment(enchantment) - && playerHand.getEnchantmentLevel(enchantment) == level)) - { - throw new SignException(_("missingItems", 1, sign.getLine(1))); - } - if (search != null && playerHand.getType() != search.getType()) - { - throw new SignException(_("missingItems", 1, search.getType().toString().toLowerCase(Locale.ENGLISH).replace('_', ' '))); - } - - final ItemStack toEnchant = playerHand; - try - { - toEnchant.addEnchantment(enchantment, level); - } - catch (Exception ex) - { - throw new SignException(ex.getMessage(), ex); - } - - charge.charge(player); - Trade.log("Sign", "Enchant", "Interact", username, charge, username, charge, sign.getBlock().getLocation(), ess); - player.updateInventory(); - return true; - } -} diff --git a/EssentialsSigns/src/com/earth2me/essentials/signs/SignEntityListener.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignEntityListener.java deleted file mode 100644 index 789f9ba1f..000000000 --- a/EssentialsSigns/src/com/earth2me/essentials/signs/SignEntityListener.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.earth2me.essentials.signs; - -import com.earth2me.essentials.api.IEssentials; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityChangeBlockEvent; -import org.bukkit.event.entity.EntityExplodeEvent; - - -public class SignEntityListener implements Listener -{ - private final transient IEssentials ess; - private final transient ISignsPlugin plugin; - - public SignEntityListener(final IEssentials ess, final ISignsPlugin plugin) - { - this.ess = ess; - this.plugin = plugin; - } - - @EventHandler(priority = EventPriority.LOW) - public void onEntityExplode(final EntityExplodeEvent event) - { - if (plugin.getSettings().areSignsDisabled()) - { - return; - } - - for (Block block : event.blockList()) - { - if (((block.getTypeId() == Material.WALL_SIGN.getId() - || block.getTypeId() == Material.SIGN_POST.getId()) - && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(block))) - || EssentialsSign.checkIfBlockBreaksSigns(block)) - { - event.setCancelled(true); - return; - } - for (EssentialsSign sign : plugin.getSettings().getEnabledSigns()) - { - if (sign.getBlocks().contains(block.getType())) - { - event.setCancelled(!sign.onBlockExplode(block, ess)); - return; - } - } - } - } - - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onEntityChangeBlock(final EntityChangeBlockEvent event) - { - if (plugin.getSettings().areSignsDisabled()) - { - return; - } - - final Block block = event.getBlock(); - if (((block.getTypeId() == Material.WALL_SIGN.getId() - || block.getTypeId() == Material.SIGN_POST.getId()) - && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(block))) - || EssentialsSign.checkIfBlockBreaksSigns(block)) - { - event.setCancelled(true); - return; - } - for (EssentialsSign sign : plugin.getSettings().getEnabledSigns()) - { - if (sign.getBlocks().contains(block.getType()) - && !sign.onBlockBreak(block, ess)) - { - event.setCancelled(true); - return; - } - } - } -} diff --git a/EssentialsSigns/src/com/earth2me/essentials/signs/SignException.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignException.java deleted file mode 100644 index 9c9ab44a2..000000000 --- a/EssentialsSigns/src/com/earth2me/essentials/signs/SignException.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.earth2me.essentials.signs; - - -public class SignException extends Exception -{ - public SignException(final String message) - { - super(message); - } - - public SignException(final String message, final Throwable throwable) - { - super(message, throwable); - } -} diff --git a/EssentialsSigns/src/com/earth2me/essentials/signs/SignFree.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignFree.java deleted file mode 100644 index b5fc54e40..000000000 --- a/EssentialsSigns/src/com/earth2me/essentials/signs/SignFree.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.earth2me.essentials.signs; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.craftbukkit.InventoryWorkaround; -import com.earth2me.essentials.economy.Trade; -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; - - -public class SignFree extends EssentialsSign -{ - public SignFree() - { - super("Free"); - } - - @Override - protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException - { - getItemStack(sign.getLine(1), 1, ess); - return true; - } - - @Override - protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException - { - final ItemStack item = getItemStack(sign.getLine(1), 1, ess); - if (item.getType() == Material.AIR) - { - throw new SignException(_("cantSpawnItem", "Air")); - } - - item.setAmount(item.getType().getMaxStackSize()); - InventoryWorkaround.addItem(player.getInventory(), true, item); - player.sendMessage("Item added to your inventory."); - player.updateInventory(); - //TODO: wait for a fix in bukkit - //Problem: Items can be duplicated - //Inventory i = ess.getServer().createInventory(player, InventoryType.CHEST); - //i.addItem(item); - //player.openInventory(i); - Trade.log("Sign", "Free", "Interact", username, null, username, new Trade(item, ess), sign.getBlock().getLocation(), ess); - return true; - } -} diff --git a/EssentialsSigns/src/com/earth2me/essentials/signs/SignGameMode.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignGameMode.java deleted file mode 100644 index d9fdd2872..000000000 --- a/EssentialsSigns/src/com/earth2me/essentials/signs/SignGameMode.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.earth2me.essentials.signs; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.ChargeException; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.economy.Trade; -import java.util.Locale; -import org.bukkit.GameMode; - - -public class SignGameMode extends EssentialsSign -{ - public SignGameMode() - { - super("GameMode"); - } - - @Override - protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException - { - validateTrade(sign, 1, ess); - return true; - } - - @Override - protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException - { - final Trade charge = getTrade(sign, 1, ess); - charge.isAffordableFor(player); - - player.setGameMode(player.getGameMode() == GameMode.SURVIVAL ? GameMode.CREATIVE : GameMode.SURVIVAL); - player.sendMessage(_("gameMode", _(player.getGameMode().toString().toLowerCase(Locale.ENGLISH)), player.getDisplayName())); - charge.charge(player); - return true; - } -} diff --git a/EssentialsSigns/src/com/earth2me/essentials/signs/SignHeal.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignHeal.java deleted file mode 100644 index 2da09e521..000000000 --- a/EssentialsSigns/src/com/earth2me/essentials/signs/SignHeal.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.earth2me.essentials.signs; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.ChargeException; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.economy.Trade; - - -public class SignHeal extends EssentialsSign -{ - public SignHeal() - { - super("Heal"); - } - - @Override - protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException - { - validateTrade(sign, 1, ess); - return true; - } - - @Override - protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException - { - final Trade charge = getTrade(sign, 1, ess); - charge.isAffordableFor(player); - player.setHealth(20); - player.setFoodLevel(20); - player.setFireTicks(0); - player.sendMessage(_("youAreHealed")); - charge.charge(player); - return true; - } -} diff --git a/EssentialsSigns/src/com/earth2me/essentials/signs/SignKit.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignKit.java deleted file mode 100644 index 9ddce494f..000000000 --- a/EssentialsSigns/src/com/earth2me/essentials/signs/SignKit.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.earth2me.essentials.signs; - -import com.earth2me.essentials.api.ChargeException; -import com.earth2me.essentials.economy.Trade; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.permissions.KitPermissions; -import com.earth2me.essentials.settings.Kit; -import java.util.Locale; - - -public class SignKit extends EssentialsSign -{ - public SignKit() - { - super("Kit"); - } - - @Override - protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException - { - validateTrade(sign, 3, ess); - - final String kitName = sign.getLine(1).toLowerCase(Locale.ENGLISH); - - if (kitName.isEmpty()) - { - sign.setLine(1, "§dKit name!"); - return false; - } - else - { - try - { - ess.getKits().getKit(kitName); - } - catch (Exception ex) - { - throw new SignException(ex.getMessage(), ex); - } - final String group = sign.getLine(2); - if ("Everyone".equalsIgnoreCase(group) || "Everybody".equalsIgnoreCase(group)) - { - sign.setLine(2, "§2Everyone"); - } - return true; - } - } - - @Override - protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException - { - final String kitName = sign.getLine(1).toLowerCase(Locale.ENGLISH); - final String group = sign.getLine(2); - if ((!group.isEmpty() && ("§2Everyone".equals(group) || ess.getRanks().inGroup(player, group))) - || (group.isEmpty() && KitPermissions.getPermission(kitName).isAuthorized(player))) - { - final Trade charge = getTrade(sign, 3, ess); - charge.isAffordableFor(player); - try - {; - final Kit kit = ess.getKits().getKit(kitName); - ess.getKits().checkTime(player, kit); - ess.getKits().sendKit(player, kit); - charge.charge(player); - } - catch (Exception ex) - { - throw new SignException(ex.getMessage(), ex); - } - return true; - } - return false; - } -} diff --git a/EssentialsSigns/src/com/earth2me/essentials/signs/SignMail.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignMail.java deleted file mode 100644 index 7845c86a6..000000000 --- a/EssentialsSigns/src/com/earth2me/essentials/signs/SignMail.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.earth2me.essentials.signs; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IUser; -import java.util.List; - - -public class SignMail extends EssentialsSign -{ - public SignMail() - { - super("Mail"); - } - - @Override - protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException - { - final List mail; - player.acquireReadLock(); - try - { - mail = player.getData().getMails(); - } - finally - { - player.unlock(); - } - if (mail == null || mail.isEmpty()) - { - player.sendMessage(_("noNewMail")); - return false; - } - for (String s : mail) - { - player.sendMessage(s); - } - player.sendMessage(_("markMailAsRead")); - return true; - } -} diff --git a/EssentialsSigns/src/com/earth2me/essentials/signs/SignPlayerListener.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignPlayerListener.java deleted file mode 100644 index 9d597820f..000000000 --- a/EssentialsSigns/src/com/earth2me/essentials/signs/SignPlayerListener.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.earth2me.essentials.signs; - -import com.earth2me.essentials.api.IEssentials; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.Sign; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.block.Action; -import org.bukkit.event.player.PlayerInteractEvent; - - -public class SignPlayerListener implements Listener -{ - private final transient IEssentials ess; - private final transient ISignsPlugin plugin; - - public SignPlayerListener(final IEssentials ess, final ISignsPlugin plugin) - { - this.ess = ess; - this.plugin = plugin; - } - - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onPlayerInteract(final PlayerInteractEvent event) - { - if (plugin.getSettings().areSignsDisabled() || event.getAction() != Action.RIGHT_CLICK_BLOCK) - { - return; - } - final Block block = event.getClickedBlock(); - if (block == null) - { - return; - } - - final int mat = block.getTypeId(); - if (mat == Material.SIGN_POST.getId() || mat == Material.WALL_SIGN.getId()) - { - final Sign csign = (Sign)block.getState(); - for (EssentialsSign sign : plugin.getSettings().getEnabledSigns()) - { - if (csign.getLine(0).equalsIgnoreCase(sign.getSuccessName())) - { - sign.onSignInteract(block, event.getPlayer(), ess); - event.setCancelled(true); - return; - } - } - } - else - { - for (EssentialsSign sign : plugin.getSettings().getEnabledSigns()) - { - if (sign.getBlocks().contains(block.getType()) - && !sign.onBlockInteract(block, event.getPlayer(), ess)) - { - event.setCancelled(true); - return; - } - } - } - } -} diff --git a/EssentialsSigns/src/com/earth2me/essentials/signs/SignProtection.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignProtection.java deleted file mode 100644 index 3921ffc5e..000000000 --- a/EssentialsSigns/src/com/earth2me/essentials/signs/SignProtection.java +++ /dev/null @@ -1,350 +0,0 @@ -package com.earth2me.essentials.signs; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.ChargeException; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.economy.Trade; -import com.earth2me.essentials.utils.Util; -import java.util.*; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.block.Sign; -import org.bukkit.inventory.ItemStack; - - -public class SignProtection extends EssentialsSign -{ - private final transient Set protectedBlocks = EnumSet.noneOf(Material.class); - - public SignProtection() - { - super("Protection"); - protectedBlocks.add(Material.CHEST); - protectedBlocks.add(Material.BURNING_FURNACE); - protectedBlocks.add(Material.FURNACE); - protectedBlocks.add(Material.DISPENSER); - } - - @Override - protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException - { - sign.setLine(3, "§4" + username); - if (hasAdjacentBlock(sign.getBlock())) - { - final SignProtectionState state = isBlockProtected(sign.getBlock(), player, username, true, ess); - if (state == SignProtectionState.NOSIGN || state == SignProtectionState.OWNER - || SignsPermissions.PROTECTION_OVERRIDE.isAuthorized(player)) - { - sign.setLine(3, "§1" + username); - return true; - } - } - player.sendMessage(_("signProtectInvalidLocation")); - return false; - } - - @Override - protected boolean onSignBreak(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException - { - final SignProtectionState state = checkProtectionSign(sign, player, username, ess); - return state == SignProtectionState.OWNER; - } - - public boolean hasAdjacentBlock(final Block block, final Block... ignoredBlocks) - { - final Block[] faces = getAdjacentBlocks(block); - for (Block b : faces) - { - for (Block ignoredBlock : ignoredBlocks) - { - if (b.getLocation().equals(ignoredBlock.getLocation())) - { - continue; - } - } - if (protectedBlocks.contains(b.getType())) - { - return true; - } - } - return false; - } - - private void checkIfSignsAreBroken(final Block block, final IUser player, final String username, final IEssentials ess) - { - final Map signs = getConnectedSigns(block, player, username, false, ess); - for (Map.Entry entry : signs.entrySet()) - { - if (entry.getValue() != SignProtectionState.NOSIGN) - { - final Block sign = entry.getKey().getBlock(); - if (!hasAdjacentBlock(sign, block)) - { - block.setType(Material.AIR); - final Trade trade = new Trade(new ItemStack(Material.SIGN, 1), ess); - trade.pay(player); - } - } - } - } - - private Map getConnectedSigns(final Block block, final IUser user, final String username, boolean secure, final IEssentials ess) - { - final Map signs = new HashMap(); - getConnectedSigns(block, signs, user, username, secure ? 4 : 2, ess); - return signs; - } - - private void getConnectedSigns(final Block block, final Map signs, final IUser user, final String username, final int depth, final IEssentials ess) - { - final Block[] faces = getAdjacentBlocks(block); - for (Block b : faces) - { - final Location loc = b.getLocation(); - if (signs.containsKey(loc)) - { - continue; - } - final SignProtectionState check = checkProtectionSign(b, user, username, ess); - signs.put(loc, check); - - if (protectedBlocks.contains(b.getType()) && depth > 0) - { - getConnectedSigns(b, signs, user, username, depth - 1, ess); - } - } - } - - - public enum SignProtectionState - { - NOT_ALLOWED, ALLOWED, NOSIGN, OWNER - } - - private SignProtectionState checkProtectionSign(final Block block, final IUser user, final String username, final IEssentials ess) - { - if (block.getType() == Material.SIGN_POST || block.getType() == Material.WALL_SIGN) - { - final BlockSign sign = new BlockSign(block); - if (sign.getLine(0).equals(this.getSuccessName())) - { - return checkProtectionSign(sign, user, username, ess); - } - } - return SignProtectionState.NOSIGN; - } - - private SignProtectionState checkProtectionSign(final ISign sign, final IUser user, final String username, final IEssentials ess) - { - if (user == null || username == null) - { - return SignProtectionState.NOT_ALLOWED; - } - if (SignsPermissions.PROTECTION_OVERRIDE.isAuthorized(user)) - { - return SignProtectionState.OWNER; - } - if (Util.stripFormat(sign.getLine(3)).equalsIgnoreCase(username)) - { - return SignProtectionState.OWNER; - } - for (int i = 1; i <= 2; i++) - { - final String line = sign.getLine(i); - if (line.startsWith("(") && line.endsWith(")") && ess.getRanks().inGroup(user, line.substring(1, line.length() - 1))) - { - return SignProtectionState.ALLOWED; - } - else if (line.equalsIgnoreCase(username)) - { - return SignProtectionState.ALLOWED; - } - } - return SignProtectionState.NOT_ALLOWED; - } - - private Block[] getAdjacentBlocks(final Block block) - { - return new Block[] - { - block.getRelative(BlockFace.NORTH), - block.getRelative(BlockFace.SOUTH), - block.getRelative(BlockFace.EAST), - block.getRelative(BlockFace.WEST), - block.getRelative(BlockFace.DOWN), - block.getRelative(BlockFace.UP) - }; - } - - public SignProtectionState isBlockProtected(final Block block, final IUser user, final String username, boolean secure, final IEssentials ess) - { - final Map signs = getConnectedSigns(block, user, username, secure, ess); - SignProtectionState retstate = SignProtectionState.NOSIGN; - for (SignProtectionState state : signs.values()) - { - if (state == SignProtectionState.ALLOWED) - { - retstate = state; - } - else if (state == SignProtectionState.NOT_ALLOWED && retstate != SignProtectionState.ALLOWED) - { - retstate = state; - } - } - if (!secure || retstate == SignProtectionState.NOSIGN) - { - for (SignProtectionState state : signs.values()) - { - if (state == SignProtectionState.OWNER) - { - return state; - } - } - } - return retstate; - } - - public boolean isBlockProtected(final Block block) - { - final Block[] faces = getAdjacentBlocks(block); - for (Block b : faces) - { - if (b.getType() == Material.SIGN_POST || b.getType() == Material.WALL_SIGN) - { - final Sign sign = (Sign)b.getState(); - if (sign.getLine(0).equalsIgnoreCase("§1[Protection]")) - { - return true; - } - } - if (protectedBlocks.contains(b.getType())) - { - final Block[] faceChest = getAdjacentBlocks(b); - - for (Block a : faceChest) - { - if (a.getType() == Material.SIGN_POST || a.getType() == Material.WALL_SIGN) - { - final Sign sign = (Sign)a.getState(); - if (sign.getLine(0).equalsIgnoreCase("§1[Protection]")) - { - return true; - } - } - } - } - } - return false; - } - - @Override - public Set getBlocks() - { - return protectedBlocks; - } - - @Override - protected boolean onBlockPlace(final Block block, final IUser player, final String username, final IEssentials ess) throws SignException - { - for (Block adjBlock : getAdjacentBlocks(block)) - { - final SignProtectionState state = isBlockProtected(adjBlock, player, username, true, ess); - - if ((state == SignProtectionState.ALLOWED || state == SignProtectionState.NOT_ALLOWED) - && !SignsPermissions.PROTECTION_OVERRIDE.isAuthorized(player)) - { - player.sendMessage(_("noPlacePermission", block.getType().toString().toLowerCase(Locale.ENGLISH))); - return false; - } - } - return true; - - } - - @Override - protected boolean onBlockInteract(final Block block, final IUser player, final String username, final IEssentials ess) throws SignException - { - final SignProtectionState state = isBlockProtected(block, player, username, false, ess); - - if (state == SignProtectionState.OWNER || state == SignProtectionState.NOSIGN || state == SignProtectionState.ALLOWED) - { - return true; - } - - if (state == SignProtectionState.NOT_ALLOWED - && SignsPermissions.PROTECTION_OVERRIDE.isAuthorized(player)) - { - return true; - } - - - player.sendMessage(_("noAccessPermission", block.getType().toString().toLowerCase(Locale.ENGLISH))); - return false; - } - - @Override - protected boolean onBlockBreak(final Block block, final IUser player, final String username, final IEssentials ess) throws SignException - { - final SignProtectionState state = isBlockProtected(block, player, username, false, ess); - - if (state == SignProtectionState.OWNER || state == SignProtectionState.NOSIGN) - { - checkIfSignsAreBroken(block, player, username, ess); - return true; - } - - if ((state == SignProtectionState.ALLOWED || state == SignProtectionState.NOT_ALLOWED) - && SignsPermissions.PROTECTION_OVERRIDE.isAuthorized(player)) - { - checkIfSignsAreBroken(block, player, username, ess); - return true; - } - - - player.sendMessage(_("noDestroyPermission", block.getType().toString().toLowerCase(Locale.ENGLISH))); - return false; - } - - @Override - public boolean onBlockBreak(final Block block, final IEssentials ess) - { - final SignProtectionState state = isBlockProtected(block, null, null, false, ess); - - return state == SignProtectionState.NOSIGN; - } - - @Override - public boolean onBlockExplode(final Block block, final IEssentials ess) - { - final SignProtectionState state = isBlockProtected(block, null, null, false, ess); - - return state == SignProtectionState.NOSIGN; - } - - @Override - public boolean onBlockBurn(final Block block, final IEssentials ess) - { - final SignProtectionState state = isBlockProtected(block, null, null, false, ess); - - return state == SignProtectionState.NOSIGN; - } - - @Override - public boolean onBlockIgnite(final Block block, final IEssentials ess) - { - final SignProtectionState state = isBlockProtected(block, null, null, false, ess); - - return state == SignProtectionState.NOSIGN; - } - - @Override - public boolean onBlockPush(final Block block, final IEssentials ess) - { - final SignProtectionState state = isBlockProtected(block, null, null, false, ess); - - return state == SignProtectionState.NOSIGN; - } -} diff --git a/EssentialsSigns/src/com/earth2me/essentials/signs/SignSell.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignSell.java deleted file mode 100644 index ced0e01fa..000000000 --- a/EssentialsSigns/src/com/earth2me/essentials/signs/SignSell.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.earth2me.essentials.signs; - -import com.earth2me.essentials.api.ChargeException; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.economy.Trade; - - -public class SignSell extends EssentialsSign -{ - public SignSell() - { - super("Sell"); - } - - @Override - protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException - { - validateTrade(sign, 1, 2, player, ess); - validateTrade(sign, 3, ess); - return true; - } - - @Override - protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException - { - final Trade charge = getTrade(sign, 1, 2, player, ess); - final Trade money = getTrade(sign, 3, ess); - charge.isAffordableFor(player); - money.pay(player); - charge.charge(player); - Trade.log("Sign", "Sell", "Interact", username, charge, username, money, sign.getBlock().getLocation(), ess); - return true; - } -} diff --git a/EssentialsSigns/src/com/earth2me/essentials/signs/SignSpawnmob.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignSpawnmob.java deleted file mode 100644 index e581c8516..000000000 --- a/EssentialsSigns/src/com/earth2me/essentials/signs/SignSpawnmob.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.earth2me.essentials.signs; - -import com.earth2me.essentials.api.ChargeException; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.commands.Commandspawnmob; -import com.earth2me.essentials.economy.Trade; - - -public class SignSpawnmob extends EssentialsSign -{ - public SignSpawnmob() - { - super("Spawnmob"); - } - - @Override - protected boolean onSignCreate(ISign sign, IUser player, String username, IEssentials ess) throws SignException, ChargeException - { - validateInteger(sign, 1); - validateTrade(sign, 3, ess); - return true; - } - - //TODO: This should call a method not a command - @Override - protected boolean onSignInteract(ISign sign, IUser player, String username, IEssentials ess) throws SignException, ChargeException - { - final Trade charge = getTrade(sign, 3, ess); - charge.isAffordableFor(player); - Commandspawnmob command = new Commandspawnmob(); - command.init(ess, "spawnmob"); - String[] args = new String[] - { - sign.getLine(2), sign.getLine(1) - }; - try - { - command.run(player, "spawnmob", args); - } - catch (Exception ex) - { - throw new SignException(ex.getMessage(), ex); - } - charge.charge(player); - return true; - } -} diff --git a/EssentialsSigns/src/com/earth2me/essentials/signs/SignTime.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignTime.java deleted file mode 100644 index d09b88d70..000000000 --- a/EssentialsSigns/src/com/earth2me/essentials/signs/SignTime.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.earth2me.essentials.signs; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.ChargeException; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.economy.Trade; - - -public class SignTime extends EssentialsSign -{ - public SignTime() - { - super("Time"); - } - - @Override - protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException - { - validateTrade(sign, 2, ess); - final String timeString = sign.getLine(1); - if ("Day".equalsIgnoreCase(timeString)) - { - sign.setLine(1, "§2Day"); - return true; - } - if ("Night".equalsIgnoreCase(timeString)) - { - sign.setLine(1, "§2Night"); - return true; - } - throw new SignException(_("onlyDayNight")); - } - - @Override - protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException - { - final Trade charge = getTrade(sign, 2, ess); - charge.isAffordableFor(player); - final String timeString = sign.getLine(1); - long time = player.getWorld().getTime(); - time -= time % 24000; - if ("§2Day".equalsIgnoreCase(timeString)) - { - player.getWorld().setTime(time + 24000); - charge.charge(player); - return true; - } - if ("§2Night".equalsIgnoreCase(timeString)) - { - player.getWorld().setTime(time + 37700); - charge.charge(player); - return true; - } - throw new SignException(_("onlyDayNight")); - } -} diff --git a/EssentialsSigns/src/com/earth2me/essentials/signs/SignTrade.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignTrade.java deleted file mode 100644 index 0dcb58c95..000000000 --- a/EssentialsSigns/src/com/earth2me/essentials/signs/SignTrade.java +++ /dev/null @@ -1,361 +0,0 @@ -package com.earth2me.essentials.signs; - -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.IEssentials; -import com.earth2me.essentials.api.IUser; -import org.bukkit.inventory.ItemStack; - -//TODO: Sell Enchantment on Trade signs? -public class SignTrade extends EssentialsSign -{ - - public SignTrade() - { - super("Trade"); - } - - @Override - protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException - { - validateTrade(sign, 1, false, ess); - validateTrade(sign, 2, true, ess); - final Trade charge = getTrade(sign, 2, true, true, ess); - charge.isAffordableFor(player); - sign.setLine(3, "§8" + username); - charge.charge(player); - Trade.log("Sign", "Trade", "Create", username, charge, username, null, sign.getBlock().getLocation(), ess); - return true; - } - - @Override - protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException - { - if (sign.getLine(3).substring(2).equalsIgnoreCase(username)) - { - final Trade store = rechargeSign(sign, ess, player); - Trade stored = null; - try - { - stored = getTrade(sign, 1, true, true, ess); - subtractAmount(sign, 1, stored, ess); - stored.pay(player); - } - catch (SignException e) - { - if (store == null) - { - throw new SignException(_("tradeSignEmptyOwner"), e); - } - } - Trade.log("Sign", "Trade", "OwnerInteract", username, store, username, stored, sign.getBlock().getLocation(), ess); - } - else - { - final Trade charge = getTrade(sign, 1, false, false, ess); - final Trade trade = getTrade(sign, 2, false, true, ess); - charge.isAffordableFor(player); - addAmount(sign, 1, charge, ess); - subtractAmount(sign, 2, trade, ess); - if (!trade.pay(player, false)) - { - subtractAmount(sign, 1, charge, ess); - addAmount(sign, 2, trade, ess); - throw new ChargeException("Full inventory"); - } - charge.charge(player); - Trade.log("Sign", "Trade", "Interact", sign.getLine(3), charge, username, trade, sign.getBlock().getLocation(), ess); - } - sign.updateSign(); - return true; - } - - private Trade rechargeSign(final ISign sign, final IEssentials ess, final IUser player) throws SignException, ChargeException - { - final Trade trade = getTrade(sign, 2, false, false, ess); - if (trade.getItemStack() != null && player.getItemInHand() != null - && trade.getItemStack().getTypeId() == player.getItemInHand().getTypeId() - && trade.getItemStack().getDurability() == player.getItemInHand().getDurability() - && trade.getItemStack().getEnchantments().equals(player.getItemInHand().getEnchantments())) - { - int amount = player.getItemInHand().getAmount(); - amount -= amount % trade.getItemStack().getAmount(); - if (amount > 0) - { - final ItemStack stack = player.getItemInHand().clone(); - stack.setAmount(amount); - final Trade store = new Trade(stack, ess); - addAmount(sign, 2, store, ess); - store.charge(player); - return store; - } - } - return null; - } - - @Override - protected boolean onSignBreak(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException - { - if ((sign.getLine(3).length() > 3 && sign.getLine(3).substring(2).equalsIgnoreCase(username)) - || SignsPermissions.TRADE_OVERRIDE.isAuthorized(player)) - { - try - { - final Trade stored1 = getTrade(sign, 1, true, false, ess); - final Trade stored2 = getTrade(sign, 2, true, false, ess); - stored1.pay(player); - stored2.pay(player); - Trade.log("Sign", "Trade", "Break", username, stored2, username, stored1, sign.getBlock().getLocation(), ess); - } - catch (SignException e) - { - if (SignsPermissions.TRADE_OVERRIDE.isAuthorized(player)) - { - return true; - } - throw e; - } - return true; - } - else - { - return false; - } - } - - protected final void validateTrade(final ISign sign, final int index, final boolean amountNeeded, final IEssentials ess) throws SignException - { - final String line = sign.getLine(index).trim(); - if (line.isEmpty()) - { - throw new SignException("Empty line"); - } - final String[] split = line.split("[ :]+"); - - if (split.length == 1 && !amountNeeded) - { - final Double money = getMoney(split[0]); - if (money != null) - { - if (Util.shortCurrency(money, ess).length() * 2 > 15) - { - throw new SignException("Line can be too long!"); - } - sign.setLine(index, Util.shortCurrency(money, ess) + ":0"); - return; - } - } - - if (split.length == 2 && amountNeeded) - { - final Double money = getMoney(split[0]); - Double amount = getDoublePositive(split[1]); - if (money != null && amount != null) - { - amount -= amount % money; - if (amount < 0.01 || money < 0.01) - { - throw new SignException(_("moreThanZero")); - } - sign.setLine(index, Util.shortCurrency(money, ess) + ":" + Util.shortCurrency(amount, ess).substring(1)); - return; - } - } - - if (split.length == 2 && !amountNeeded) - { - final int amount = getIntegerPositive(split[0]); - - if (amount < 1) - { - throw new SignException(_("moreThanZero")); - } - if (!(split[1].equalsIgnoreCase("exp") || split[1].equalsIgnoreCase("xp")) - && getItemStack(split[1], amount, ess).getTypeId() == 0) - { - throw new SignException(_("moreThanZero")); - } - String newline = amount + " " + split[1] + ":0"; - if ((newline + amount).length() > 15) - { - throw new SignException("Line can be too long!"); - } - sign.setLine(index, newline); - return; - } - - if (split.length == 3 && amountNeeded) - { - final int stackamount = getIntegerPositive(split[0]); - int amount = getIntegerPositive(split[2]); - amount -= amount % stackamount; - if (amount < 1 || stackamount < 1) - { - throw new SignException(_("moreThanZero")); - } - if (!(split[1].equalsIgnoreCase("exp") || split[1].equalsIgnoreCase("xp")) - && getItemStack(split[1], stackamount, ess).getTypeId() == 0) - { - throw new SignException(_("moreThanZero")); - } - sign.setLine(index, stackamount + " " + split[1] + ":" + amount); - return; - } - throw new SignException(_("invalidSignLine", index + 1)); - } - - protected final Trade getTrade(final ISign sign, final int index, final boolean fullAmount, final boolean notEmpty, final IEssentials ess) throws SignException - { - final String line = sign.getLine(index).trim(); - if (line.isEmpty()) - { - throw new SignException("Empty line"); - } - final String[] split = line.split("[ :]+"); - - if (split.length == 2) - { - try - { - final Double money = getMoney(split[0]); - final Double amount = notEmpty ? getDoublePositive(split[1]) : getDouble(split[1]); - if (money != null && amount != null) - { - return new Trade(fullAmount ? amount : money, ess); - } - } - catch (SignException e) - { - throw new SignException(_("tradeSignEmpty"), e); - } - } - - if (split.length == 3) - { - if (split[1].equalsIgnoreCase("exp") || split[1].equalsIgnoreCase("xp")) - { - final int stackamount = getIntegerPositive(split[0]); - int amount = getInteger(split[2]); - amount -= amount % stackamount; - if (notEmpty && (amount < 1 || stackamount < 1)) - { - throw new SignException(_("tradeSignEmpty")); - } - return new Trade(fullAmount ? amount : stackamount, ess); - } - else - { - final int stackamount = getIntegerPositive(split[0]); - final ItemStack item = getItemStack(split[1], stackamount, ess); - int amount = getInteger(split[2]); - amount -= amount % stackamount; - if (notEmpty && (amount < 1 || stackamount < 1 || item.getTypeId() == 0)) - { - throw new SignException(_("tradeSignEmpty")); - } - item.setAmount(fullAmount ? amount : stackamount); - return new Trade(item, ess); - } - } - throw new SignException(_("invalidSignLine", index + 1)); - } - - protected final void subtractAmount(final ISign sign, final int index, final Trade trade, final IEssentials ess) throws SignException - { - final Double money = trade.getMoney(); - if (money != null) - { - changeAmount(sign, index, -money, ess); - } - final ItemStack item = trade.getItemStack(); - if (item != null) - { - changeAmount(sign, index, -item.getAmount(), ess); - } - final Integer exp = trade.getExperience(); - if (exp != null) - { - changeAmount(sign, index, -exp.intValue(), ess); - } - } - - protected final void addAmount(final ISign sign, final int index, final Trade trade, final IEssentials ess) throws SignException - { - final Double money = trade.getMoney(); - if (money != null) - { - changeAmount(sign, index, money, ess); - } - final ItemStack item = trade.getItemStack(); - if (item != null) - { - changeAmount(sign, index, item.getAmount(), ess); - } - final Integer exp = trade.getExperience(); - if (exp != null) - { - changeAmount(sign, index, exp.intValue(), ess); - } - } - - //TODO: Translate these exceptions. - private void changeAmount(final ISign sign, final int index, final double value, final IEssentials ess) throws SignException - { - - final String line = sign.getLine(index).trim(); - if (line.isEmpty()) - { - throw new SignException("Empty line"); - } - final String[] split = line.split("[ :]+"); - - if (split.length == 2) - { - final Double money = getMoney(split[0]); - final Double amount = getDouble(split[1]); - if (money != null && amount != null) - { - final String newline = Util.shortCurrency(money, ess) + ":" + Util.shortCurrency(amount + value, ess).substring(1); - if (newline.length() > 15) - { - throw new SignException("This sign is full: Line too long!"); - } - sign.setLine(index, newline); - return; - } - } - - if (split.length == 3) - { - if (split[1].equalsIgnoreCase("exp") || split[1].equalsIgnoreCase("xp")) - { - final int stackamount = getIntegerPositive(split[0]); - final int amount = getInteger(split[2]); - final String newline = stackamount + " " + split[1] + ":" + (amount + Math.round(value)); - if (newline.length() > 15) - { - throw new SignException("This sign is full: Line too long!"); - } - sign.setLine(index, newline); - return; - } - else - { - final int stackamount = getIntegerPositive(split[0]); - //TODO: Unused local variable - final ItemStack item = getItemStack(split[1], stackamount, ess); - final int amount = getInteger(split[2]); - final String newline = stackamount + " " + split[1] + ":" + (amount + Math.round(value)); - if (newline.length() > 15) - { - throw new SignException("This sign is full: Line too long!"); - } - sign.setLine(index, newline); - return; - } - } - throw new SignException(_("invalidSignLine", index + 1)); - } -} diff --git a/EssentialsSigns/src/com/earth2me/essentials/signs/SignWarp.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignWarp.java deleted file mode 100644 index 12deb86de..000000000 --- a/EssentialsSigns/src/com/earth2me/essentials/signs/SignWarp.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.earth2me.essentials.signs; - -import com.earth2me.essentials.api.ChargeException; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.economy.Trade; -import com.earth2me.essentials.permissions.WarpPermissions; -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; - - -public class SignWarp extends EssentialsSign -{ - public SignWarp() - { - super("Warp"); - } - - @Override - protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException - { - validateTrade(sign, 3, ess); - final String warpName = sign.getLine(1); - - if (warpName.isEmpty()) - { - sign.setLine(1, "§dWarp name!"); - return false; - } - else - { - try - { - ess.getWarps().getWarp(warpName); - } - catch (Exception ex) - { - throw new SignException(ex.getMessage(), ex); - } - final String group = sign.getLine(2); - if ("Everyone".equalsIgnoreCase(group) || "Everybody".equalsIgnoreCase(group)) - { - sign.setLine(2, "§2Everyone"); - } - return true; - } - } - - @Override - protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException - { - final String warpName = sign.getLine(1); - final String group = sign.getLine(2); - - if ((!group.isEmpty() && ("§2Everyone".equals(group) || ess.getRanks().inGroup(player, group))) - || (group.isEmpty() && WarpPermissions.getPermission(warpName).isAuthorized(player))) - { - final Trade charge = getTrade(sign, 3, ess); - try - { - player.getTeleport().warp(warpName, charge, TeleportCause.PLUGIN); - } - catch (Exception ex) - { - throw new SignException(ex.getMessage(), ex); - } - return true; - } - return false; - } -} diff --git a/EssentialsSigns/src/com/earth2me/essentials/signs/SignWeather.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignWeather.java deleted file mode 100644 index 70b5d0079..000000000 --- a/EssentialsSigns/src/com/earth2me/essentials/signs/SignWeather.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.earth2me.essentials.signs; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.ChargeException; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.economy.Trade; - - -public class SignWeather extends EssentialsSign -{ - public SignWeather() - { - super("Weather"); - } - - @Override - protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException - { - validateTrade(sign, 2, ess); - final String timeString = sign.getLine(1); - if ("Sun".equalsIgnoreCase(timeString)) - { - sign.setLine(1, "§2Sun"); - return true; - } - if ("Storm".equalsIgnoreCase(timeString)) - { - sign.setLine(1, "§2Storm"); - return true; - } - throw new SignException(_("onlySunStorm")); - } - - @Override - protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException - { - final Trade charge = getTrade(sign, 2, ess); - charge.isAffordableFor(player); - final String weatherString = sign.getLine(1); - if ("§2Sun".equalsIgnoreCase(weatherString)) - { - player.getWorld().setStorm(false); - charge.charge(player); - return true; - } - if ("§2Storm".equalsIgnoreCase(weatherString)) - { - player.getWorld().setStorm(true); - charge.charge(player); - return true; - } - throw new SignException(_("onlySunStorm")); - } -} diff --git a/EssentialsSigns/src/com/earth2me/essentials/signs/Signs.java b/EssentialsSigns/src/com/earth2me/essentials/signs/Signs.java deleted file mode 100644 index e29d45ad4..000000000 --- a/EssentialsSigns/src/com/earth2me/essentials/signs/Signs.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.earth2me.essentials.signs; - - -public enum Signs -{ - BALANCE(new SignBalance()), - BUY(new SignBuy()), - DISPOSAL(new SignDisposal()), - ENCHANT(new SignEnchant()), - FREE(new SignFree()), - GAMEMODE(new SignGameMode()), - HEAL(new SignHeal()), - KIT(new SignKit()), - MAIL(new SignMail()), - PROTECTION(new SignProtection()), - SELL(new SignSell()), - SPAWNMOB(new SignSpawnmob()), - TIME(new SignTime()), - TRADE(new SignTrade()), - WARP(new SignWarp()), - WEATHER(new SignWeather()); - private final EssentialsSign sign; - - private Signs(final EssentialsSign sign) - { - this.sign = sign; - } - - public EssentialsSign getSign() - { - return sign; - } -} diff --git a/EssentialsSigns/src/com/earth2me/essentials/signs/SignsConfig.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignsConfig.java deleted file mode 100644 index c9b4ccc83..000000000 --- a/EssentialsSigns/src/com/earth2me/essentials/signs/SignsConfig.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.earth2me.essentials.signs; - -import com.earth2me.essentials.storage.StorageObject; -import java.util.HashMap; -import java.util.Map; - - -public class SignsConfig implements StorageObject -{ - private Map signs = new HashMap(); - - public Map getSigns() - { - return signs; - } - - public void setSigns(final Map signs) - { - this.signs = signs; - } -} diff --git a/EssentialsSigns/src/com/earth2me/essentials/signs/SignsConfigHolder.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignsConfigHolder.java deleted file mode 100644 index 4ebbb1260..000000000 --- a/EssentialsSigns/src/com/earth2me/essentials/signs/SignsConfigHolder.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.earth2me.essentials.signs; - -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.storage.AsyncStorageObjectHolder; -import java.io.File; -import java.io.IOException; -import java.util.*; -import org.bukkit.plugin.Plugin; - - -public class SignsConfigHolder extends AsyncStorageObjectHolder -{ - private final transient Plugin plugin; - private Set enabledSigns = new HashSet(); - private boolean signsEnabled = false; - - public SignsConfigHolder(final IEssentials ess, final Plugin plugin) - { - super(ess, SignsConfig.class); - this.plugin = plugin; - onReload(); - acquireReadLock(); - try - { - final Map signs = getData().getSigns(); - for (Map.Entry entry : signs.entrySet()) - { - if (entry.getKey().trim().toUpperCase(Locale.ENGLISH).equals("COLOR") || entry.getKey().trim().toUpperCase(Locale.ENGLISH).equals("COLOUR")) - { - signsEnabled = true; - continue; - } - final Signs sign = Signs.valueOf(entry.getKey().toUpperCase(Locale.ENGLISH)); - if (sign != null && entry.getValue()) - { - enabledSigns.add(sign.getSign()); - } - } - } - finally - { - unlock(); - } - acquireWriteLock(); - try - { - final Map signs = new HashMap(); - for (Signs sign : Signs.values()) - { - signs.put(sign.toString(), enabledSigns.contains(sign.getSign())); - } - getData().setSigns(signs); - } - finally - { - unlock(); - } - } - - @Override - public File getStorageFile() throws IOException - { - return new File(plugin.getDataFolder(), "config.yml"); - } - - public Set getEnabledSigns() - { - return enabledSigns; - } - - public boolean areSignsDisabled() - { - return !signsEnabled; - } - - @Override - public void finishRead() - { - } - - @Override - public void finishWrite() - { - } -} diff --git a/EssentialsSigns/src/com/earth2me/essentials/signs/SignsPermissions.java b/EssentialsSigns/src/com/earth2me/essentials/signs/SignsPermissions.java deleted file mode 100644 index eb8025f5b..000000000 --- a/EssentialsSigns/src/com/earth2me/essentials/signs/SignsPermissions.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.earth2me.essentials.signs; - -import com.earth2me.essentials.api.IPermission; -import com.earth2me.essentials.permissions.BasePermission; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - - -public class SignsPermissions -{ - public static final IPermission COLOR = new BasePermission("essentials.signs.", "color"); - public static final IPermission PROTECTION_OVERRIDE = new BasePermission("essentials.signs.protection.", "override"); - public static final IPermission TRADE_OVERRIDE = new BasePermission("essentials.signs.trade.", "override"); - private static Map createpermissions = new HashMap(); - - public static IPermission getCreatePermission(final String signName) - { - IPermission perm = createpermissions.get(signName); - if (perm == null) - { - perm = new BasePermission("essentials.signs.create.", signName.toLowerCase(Locale.ENGLISH)); - createpermissions.put(signName, perm); - } - return perm; - } - private static Map usepermissions = new HashMap(); - - public static IPermission getUsePermission(final String signName) - { - IPermission perm = usepermissions.get(signName); - if (perm == null) - { - perm = new BasePermission("essentials.signs.use.", signName.toLowerCase(Locale.ENGLISH)); - usepermissions.put(signName, perm); - } - return perm; - } - private static Map breakpermissions = new HashMap(); - - public static IPermission getBreakPermission(final String signName) - { - IPermission perm = breakpermissions.get(signName); - if (perm == null) - { - perm = new BasePermission("essentials.signs.break.", signName.toLowerCase(Locale.ENGLISH)); - breakpermissions.put(signName, perm); - } - return perm; - } -} diff --git a/EssentialsSigns/src/net/ess3/signs/EssentialsSign.java b/EssentialsSigns/src/net/ess3/signs/EssentialsSign.java new file mode 100644 index 000000000..272f14252 --- /dev/null +++ b/EssentialsSigns/src/net/ess3/signs/EssentialsSign.java @@ -0,0 +1,516 @@ +package net.ess3.signs; + +import net.ess3.api.ChargeException; +import static net.ess3.I18n._; +import net.ess3.economy.Trade; +import net.ess3.utils.Util; +import net.ess3.api.IEssentials; +import net.ess3.api.IUser; +import java.util.HashSet; +import java.util.Locale; +import java.util.Set; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.Sign; +import org.bukkit.entity.Player; +import org.bukkit.event.block.SignChangeEvent; +import org.bukkit.inventory.ItemStack; + + +public class EssentialsSign +{ + private static final Set EMPTY_SET = new HashSet(); + protected transient final String signName; + + public EssentialsSign(final String signName) + { + this.signName = signName; + } + + public final boolean onSignCreate(final SignChangeEvent event, final IEssentials ess) + { + final ISign sign = new EventSign(event); + final IUser user = ess.getUser(event.getPlayer()); + if (!SignsPermissions.getCreatePermission(signName).isAuthorized(user)) + { + // Return true, so other plugins can use the same sign title, just hope + // they won't change it to §1[Signname] + return true; + } + sign.setLine(0, _("signFormatFail", this.signName)); + try + { + final boolean ret = onSignCreate(sign, user, getUsername(user), ess); + if (ret) + { + sign.setLine(0, getSuccessName()); + } + return ret; + } + catch (ChargeException ex) + { + ess.getCommandHandler().showCommandError(user, signName, ex); + } + catch (SignException ex) + { + ess.getCommandHandler().showCommandError(user, signName, ex); + } + // Return true, so the player sees the wrong sign. + return true; + } + + public String getSuccessName() + { + return _("signFormatSuccess", this.signName); + } + + public String getTemplateName() + { + return _("signFormatTemplate", this.signName); + } + + private String getUsername(final IUser user) + { + return user.getName().substring(0, user.getName().length() > 13 ? 13 : user.getName().length()); + } + + public final boolean onSignInteract(final Block block, final Player player, final IEssentials ess) + { + final ISign sign = new BlockSign(block); + final IUser user = ess.getUser(player); + try + { + return SignsPermissions.getUsePermission(signName).isAuthorized(user) + && onSignInteract(sign, user, getUsername(user), ess); + } + catch (ChargeException ex) + { + ess.getCommandHandler().showCommandError(user, signName, ex); + return false; + } + catch (SignException ex) + { + ess.getCommandHandler().showCommandError(user, signName, ex); + return false; + } + } + + public final boolean onSignBreak(final Block block, final Player player, final IEssentials ess) + { + final ISign sign = new BlockSign(block); + final IUser user = ess.getUser(player); + try + { + return SignsPermissions.getBreakPermission(signName).isAuthorized(user) + && onSignBreak(sign, user, getUsername(user), ess); + } + catch (SignException ex) + { + ess.getCommandHandler().showCommandError(user, signName, ex); + return false; + } + } + + protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException + { + return true; + } + + protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException + { + return true; + } + + protected boolean onSignBreak(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException + { + return true; + } + + public final boolean onBlockPlace(final Block block, final Player player, final IEssentials ess) + { + final IUser user = ess.getUser(player); + try + { + return onBlockPlace(block, user, getUsername(user), ess); + } + catch (ChargeException ex) + { + ess.getCommandHandler().showCommandError(user, signName, ex); + } + catch (SignException ex) + { + ess.getCommandHandler().showCommandError(user, signName, ex); + } + return false; + } + + public final boolean onBlockInteract(final Block block, final Player player, final IEssentials ess) + { + final IUser user = ess.getUser(player); + try + { + return onBlockInteract(block, user, getUsername(user), ess); + } + catch (ChargeException ex) + { + ess.getCommandHandler().showCommandError(user, signName, ex); + } + catch (SignException ex) + { + ess.getCommandHandler().showCommandError(user, signName, ex); + } + return false; + } + + public final boolean onBlockBreak(final Block block, final Player player, final IEssentials ess) + { + final IUser user = ess.getUser(player); + try + { + return onBlockBreak(block, user, getUsername(user), ess); + } + catch (SignException ex) + { + ess.getCommandHandler().showCommandError(user, signName, ex); + } + return false; + } + + public boolean onBlockBreak(final Block block, final IEssentials ess) + { + return true; + } + + public boolean onBlockExplode(final Block block, final IEssentials ess) + { + return true; + } + + public boolean onBlockBurn(final Block block, final IEssentials ess) + { + return true; + } + + public boolean onBlockIgnite(final Block block, final IEssentials ess) + { + return true; + } + + public boolean onBlockPush(final Block block, final IEssentials ess) + { + return true; + } + + public static boolean checkIfBlockBreaksSigns(final Block block) + { + final Block sign = block.getRelative(BlockFace.UP); + if (sign.getType() == Material.SIGN_POST && isValidSign(new BlockSign(sign))) + { + return true; + } + final BlockFace[] directions = new BlockFace[] + { + BlockFace.NORTH, + BlockFace.EAST, + BlockFace.SOUTH, + BlockFace.WEST + }; + for (BlockFace blockFace : directions) + { + final Block signblock = block.getRelative(blockFace); + if (signblock.getType() == Material.WALL_SIGN) + { + final org.bukkit.material.Sign signMat = (org.bukkit.material.Sign)signblock.getState().getData(); + if (signMat != null && signMat.getFacing() == blockFace && isValidSign(new BlockSign(signblock))) + { + return true; + } + } + } + return false; + } + + public static boolean isValidSign(final ISign sign) + { + return sign.getLine(0).matches("§1\\[.*\\]"); + } + + protected boolean onBlockPlace(final Block block, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException + { + return true; + } + + protected boolean onBlockInteract(final Block block, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException + { + return true; + } + + protected boolean onBlockBreak(final Block block, final IUser player, final String username, final IEssentials ess) throws SignException + { + return true; + } + + public Set getBlocks() + { + return EMPTY_SET; + } + + protected final void validateTrade(final ISign sign, final int index, final IEssentials ess) throws SignException + { + final String line = sign.getLine(index).trim(); + if (line.isEmpty()) + { + return; + } + final Trade trade = getTrade(sign, index, 0, ess); + final Double money = trade.getMoney(); + if (money != null) + { + sign.setLine(index, Util.shortCurrency(money, ess)); + } + } + + protected final void validateTrade(final ISign sign, final int amountIndex, final int itemIndex, + final IUser player, final IEssentials ess) throws SignException + { + if (sign.getLine(itemIndex).equalsIgnoreCase("exp") || sign.getLine(itemIndex).equalsIgnoreCase("xp")) + { + int amount = getIntegerPositive(sign.getLine(amountIndex)); + sign.setLine(amountIndex, Integer.toString(amount)); + sign.setLine(itemIndex, "exp"); + return; + } + final Trade trade = getTrade(sign, amountIndex, itemIndex, player, ess); + final ItemStack item = trade.getItemStack(); + sign.setLine(amountIndex, Integer.toString(item.getAmount())); + sign.setLine(itemIndex, sign.getLine(itemIndex).trim()); + } + + protected final Trade getTrade(final ISign sign, final int amountIndex, final int itemIndex, + final IUser player, final IEssentials ess) throws SignException + { + if (sign.getLine(itemIndex).equalsIgnoreCase("exp") || sign.getLine(itemIndex).equalsIgnoreCase("xp")) + { + final int amount = getIntegerPositive(sign.getLine(amountIndex)); + return new Trade(amount, ess); + } + final ItemStack item = getItemStack(sign.getLine(itemIndex), 1, ess); + final int amount = Math.min(getIntegerPositive(sign.getLine(amountIndex)), item.getType().getMaxStackSize() * player.getInventory().getSize()); + if (item.getTypeId() == 0 || amount < 1) + { + throw new SignException(_("moreThanZero")); + } + item.setAmount(amount); + return new Trade(item, ess); + } + + protected final void validateInteger(final ISign sign, final int index) throws SignException + { + final String line = sign.getLine(index).trim(); + if (line.isEmpty()) + { + throw new SignException("Empty line " + index); + } + final int quantity = getIntegerPositive(line); + sign.setLine(index, Integer.toString(quantity)); + } + + protected final int getIntegerPositive(final String line) throws SignException + { + final int quantity = getInteger(line); + if (quantity < 1) + { + throw new SignException(_("moreThanZero")); + } + return quantity; + } + + protected final int getInteger(final String line) throws SignException + { + try + { + final int quantity = Integer.parseInt(line); + + return quantity; + } + catch (NumberFormatException ex) + { + throw new SignException("Invalid sign", ex); + } + } + + protected final ItemStack getItemStack(final String itemName, final int quantity, final IEssentials ess) throws SignException + { + try + { + final ItemStack item = ess.getItemDb().get(itemName); + item.setAmount(quantity); + return item; + } + catch (Exception ex) + { + throw new SignException(ex.getMessage(), ex); + } + } + + protected final Double getMoney(final String line) throws SignException + { + final boolean isMoney = line.matches("^[^0-9-\\.][\\.0-9]+$"); + return isMoney ? getDoublePositive(line.substring(1)) : null; + } + + protected final Double getDoublePositive(final String line) throws SignException + { + final double quantity = getDouble(line); + if (Math.round(quantity * 100.0) < 1.0) + { + throw new SignException(_("moreThanZero")); + } + return quantity; + } + + protected final Double getDouble(final String line) throws SignException + { + try + { + return Double.parseDouble(line); + } + catch (NumberFormatException ex) + { + throw new SignException(ex.getMessage(), ex); + } + } + + protected final Trade getTrade(final ISign sign, final int index, final IEssentials ess) throws SignException + { + return getTrade(sign, index, 1, ess); + } + + protected final Trade getTrade(final ISign sign, final int index, final int decrement, final IEssentials ess) throws SignException + { + final String line = sign.getLine(index).trim(); + if (line.isEmpty()) + { + return new Trade(signName.toLowerCase(Locale.ENGLISH) + "sign", ess); + } + + final Double money = getMoney(line); + if (money == null) + { + final String[] split = line.split("[ :]+", 2); + if (split.length != 2) + { + throw new SignException(_("invalidCharge")); + } + final int quantity = getIntegerPositive(split[0]); + + final String item = split[1].toLowerCase(Locale.ENGLISH); + if (item.equalsIgnoreCase("times")) + { + sign.setLine(index, (quantity - decrement) + " times"); + return new Trade(signName.toLowerCase(Locale.ENGLISH) + "sign", ess); + } + else if (item.equalsIgnoreCase("exp") || item.equalsIgnoreCase("xp")) + { + sign.setLine(index, quantity + " exp"); + return new Trade(quantity, ess); + } + else + { + final ItemStack stack = getItemStack(item, quantity, ess); + sign.setLine(index, quantity + " " + item); + return new Trade(stack, ess); + } + } + else + { + return new Trade(money, ess); + } + } + + + static class EventSign implements ISign + { + private final transient SignChangeEvent event; + private final transient Block block; + + public EventSign(final SignChangeEvent event) + { + this.event = event; + this.block = event.getBlock(); + } + + @Override + public final String getLine(final int index) + { + return event.getLine(index); + } + + @Override + public final void setLine(final int index, final String text) + { + event.setLine(index, text); + } + + @Override + public Block getBlock() + { + return block; + } + + @Override + public void updateSign() + { + } + } + + + static class BlockSign implements ISign + { + private final transient Sign sign; + private final transient Block block; + + public BlockSign(final Block block) + { + this.block = block; + this.sign = (Sign)block.getState(); + } + + @Override + public final String getLine(final int index) + { + return sign.getLine(index); + } + + @Override + public final void setLine(final int index, final String text) + { + sign.setLine(index, text); + } + + @Override + public final Block getBlock() + { + return block; + } + + @Override + public final void updateSign() + { + sign.update(); + } + } + + + public interface ISign + { + String getLine(final int index); + + void setLine(final int index, final String text); + + public Block getBlock(); + + void updateSign(); + } +} diff --git a/EssentialsSigns/src/net/ess3/signs/EssentialsSignsPlugin.java b/EssentialsSigns/src/net/ess3/signs/EssentialsSignsPlugin.java new file mode 100644 index 000000000..d2f615d52 --- /dev/null +++ b/EssentialsSigns/src/net/ess3/signs/EssentialsSignsPlugin.java @@ -0,0 +1,54 @@ +package net.ess3.signs; + +import static net.ess3.I18n._; +import net.ess3.api.IEssentials; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.bukkit.Bukkit; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + + +public class EssentialsSignsPlugin extends JavaPlugin implements ISignsPlugin +{ + private static final transient Logger LOGGER = Bukkit.getLogger(); + private transient SignsConfigHolder config; + + @Override + public void onEnable() + { + final PluginManager pluginManager = getServer().getPluginManager(); + final IEssentials ess = (IEssentials)pluginManager.getPlugin("Essentials-3"); + if (!this.getDescription().getVersion().equals(ess.getDescription().getVersion())) + { + LOGGER.log(Level.WARNING, _("versionMismatchAll")); + } + if (!ess.isEnabled()) + { + this.setEnabled(false); + return; + } + + final SignBlockListener signBlockListener = new SignBlockListener(ess, this); + pluginManager.registerEvents(signBlockListener, this); + + final SignPlayerListener signPlayerListener = new SignPlayerListener(ess, this); + pluginManager.registerEvents(signPlayerListener, this); + + final SignEntityListener signEntityListener = new SignEntityListener(ess, this); + pluginManager.registerEvents(signEntityListener, this); + + config = new SignsConfigHolder(ess, this); + } + + @Override + public void onDisable() + { + } + + @Override + public SignsConfigHolder getSettings() + { + return config; + } +} diff --git a/EssentialsSigns/src/net/ess3/signs/ISignsPlugin.java b/EssentialsSigns/src/net/ess3/signs/ISignsPlugin.java new file mode 100644 index 000000000..9a6d14a61 --- /dev/null +++ b/EssentialsSigns/src/net/ess3/signs/ISignsPlugin.java @@ -0,0 +1,9 @@ +package net.ess3.signs; + +import net.ess3.api.IEssentialsModule; + + +public interface ISignsPlugin extends IEssentialsModule +{ + SignsConfigHolder getSettings(); +} diff --git a/EssentialsSigns/src/net/ess3/signs/SignBalance.java b/EssentialsSigns/src/net/ess3/signs/SignBalance.java new file mode 100644 index 000000000..35a1648ae --- /dev/null +++ b/EssentialsSigns/src/net/ess3/signs/SignBalance.java @@ -0,0 +1,22 @@ +package net.ess3.signs; + +import static net.ess3.I18n._; +import net.ess3.api.IEssentials; +import net.ess3.api.IUser; +import net.ess3.utils.Util; + + +public class SignBalance extends EssentialsSign +{ + public SignBalance() + { + super("Balance"); + } + + @Override + protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException + { + player.sendMessage(_("balance", Util.displayCurrency(player.getMoney(), ess))); + return true; + } +} diff --git a/EssentialsSigns/src/net/ess3/signs/SignBlockListener.java b/EssentialsSigns/src/net/ess3/signs/SignBlockListener.java new file mode 100644 index 000000000..31cdfc970 --- /dev/null +++ b/EssentialsSigns/src/net/ess3/signs/SignBlockListener.java @@ -0,0 +1,264 @@ +package net.ess3.signs; + +import net.ess3.api.IEssentials; +import net.ess3.api.ISettings; +import net.ess3.api.IUser; +import net.ess3.utils.Util; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.Sign; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.*; + + +public class SignBlockListener implements Listener +{ + private final transient IEssentials ess; + private final transient ISignsPlugin plugin; + private final static Logger LOGGER = Logger.getLogger("Minecraft"); + private final static int WALL_SIGN = Material.WALL_SIGN.getId(); + private final static int SIGN_POST = Material.SIGN_POST.getId(); + + public SignBlockListener(final IEssentials ess, final ISignsPlugin plugin) + { + this.ess = ess; + this.plugin = plugin; + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockBreak(final BlockBreakEvent event) + { + ISettings settings = ess.getSettings(); + settings.acquireReadLock(); + if (plugin.getSettings().areSignsDisabled()) + { + return; + } + + if (protectSignsAndBlocks(event.getBlock(), event.getPlayer())) + { + event.setCancelled(true); + } + } + + public boolean protectSignsAndBlocks(final Block block, final Player player) + { + final int mat = block.getTypeId(); + if (mat == SIGN_POST || mat == WALL_SIGN) + { + final Sign csign = (Sign)block.getState(); + + for (EssentialsSign sign : plugin.getSettings().getEnabledSigns()) + { + if (csign.getLine(0).equalsIgnoreCase(sign.getSuccessName()) + && !sign.onSignBreak(block, player, ess)) + { + return true; + } + } + } + // prevent any signs be broken by destroying the block they are attached to + if (EssentialsSign.checkIfBlockBreaksSigns(block)) + { + LOGGER.log(Level.INFO, "Prevented that a block was broken next to a sign."); + return true; + } + for (EssentialsSign sign : plugin.getSettings().getEnabledSigns()) + { + if (sign.getBlocks().contains(block.getType()) + && !sign.onBlockBreak(block, player, ess)) + { + LOGGER.log(Level.INFO, "A block was protected by a sign."); + return true; + } + } + return false; + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onSignChange(final SignChangeEvent event) + { + if (plugin.getSettings().areSignsDisabled()) + { + return; + } + IUser user = ess.getUser(event.getPlayer()); + + for (int i = 0; i < 4; i++) + { + event.setLine(i, Util.formatString(user, "essentials.signs", event.getLine(i))); + } + + for (Signs signs : Signs.values()) + { + final EssentialsSign sign = signs.getSign(); + if (event.getLine(0).equalsIgnoreCase(sign.getSuccessName())) + { + event.setCancelled(true); + return; + } + if (event.getLine(0).equalsIgnoreCase(sign.getTemplateName()) + && !sign.onSignCreate(event, ess)) + { + event.setCancelled(true); + return; + } + } + } + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onBlockPlace(final BlockPlaceEvent event) + { + if (plugin.getSettings().areSignsDisabled()) + { + return; + } + + final Block against = event.getBlockAgainst(); + if ((against.getTypeId() == WALL_SIGN + || against.getTypeId() == SIGN_POST) + && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(against))) + { + event.setCancelled(true); + return; + } + final Block block = event.getBlock(); + if (block.getTypeId() == WALL_SIGN + || block.getTypeId() == SIGN_POST) + { + return; + } + for (Signs signs : Signs.values()) + { + final EssentialsSign sign = signs.getSign(); + if (sign.getBlocks().contains(block.getType()) + && !sign.onBlockPlace(block, event.getPlayer(), ess)) + { + event.setCancelled(true); + return; + } + } + } + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onBlockBurn(final BlockBurnEvent event) + { + if (plugin.getSettings().areSignsDisabled()) + { + return; + } + + final Block block = event.getBlock(); + if (((block.getTypeId() == WALL_SIGN + || block.getTypeId() == SIGN_POST) + && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(block))) + || EssentialsSign.checkIfBlockBreaksSigns(block)) + { + event.setCancelled(true); + return; + } + for (EssentialsSign sign : plugin.getSettings().getEnabledSigns()) + { + if (sign.getBlocks().contains(block.getType()) + && !sign.onBlockBurn(block, ess)) + { + event.setCancelled(true); + return; + } + } + } + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onBlockIgnite(final BlockIgniteEvent event) + { + if (plugin.getSettings().areSignsDisabled()) + { + return; + } + + final Block block = event.getBlock(); + if (((block.getTypeId() == WALL_SIGN + || block.getTypeId() == SIGN_POST) + && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(block))) + || EssentialsSign.checkIfBlockBreaksSigns(block)) + { + event.setCancelled(true); + return; + } + for (EssentialsSign sign : plugin.getSettings().getEnabledSigns()) + { + if (sign.getBlocks().contains(block.getType()) + && !sign.onBlockIgnite(block, ess)) + { + event.setCancelled(true); + return; + } + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onBlockPistonExtend(final BlockPistonExtendEvent event) + { + if (plugin.getSettings().areSignsDisabled()) + { + return; + } + + for (Block block : event.getBlocks()) + { + if (((block.getTypeId() == WALL_SIGN + || block.getTypeId() == SIGN_POST) + && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(block))) + || EssentialsSign.checkIfBlockBreaksSigns(block)) + { + event.setCancelled(true); + return; + } + for (EssentialsSign sign : plugin.getSettings().getEnabledSigns()) + { + if (sign.getBlocks().contains(block.getType()) + && !sign.onBlockPush(block, ess)) + { + event.setCancelled(true); + return; + } + } + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onBlockPistonRetract(final BlockPistonRetractEvent event) + { + if (plugin.getSettings().areSignsDisabled()) + { + return; + } + + if (event.isSticky()) + { + final Block block = event.getBlock(); + if (((block.getTypeId() == WALL_SIGN + || block.getTypeId() == SIGN_POST) + && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(block))) + || EssentialsSign.checkIfBlockBreaksSigns(block)) + { + event.setCancelled(true); + return; + } + for (EssentialsSign sign : plugin.getSettings().getEnabledSigns()) + { + if (sign.getBlocks().contains(block.getType()) + && !sign.onBlockPush(block, ess)) + { + event.setCancelled(true); + return; + } + } + } + } +} diff --git a/EssentialsSigns/src/net/ess3/signs/SignBuy.java b/EssentialsSigns/src/net/ess3/signs/SignBuy.java new file mode 100644 index 000000000..ff08cdbc1 --- /dev/null +++ b/EssentialsSigns/src/net/ess3/signs/SignBuy.java @@ -0,0 +1,38 @@ +package net.ess3.signs; + +import net.ess3.api.ChargeException; +import net.ess3.api.IEssentials; +import net.ess3.api.IUser; +import net.ess3.economy.Trade; + + +public class SignBuy extends EssentialsSign +{ + public SignBuy() + { + super("Buy"); + } + + @Override + protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException + { + validateTrade(sign, 1, 2, player, ess); + validateTrade(sign, 3, ess); + return true; + } + + @Override + protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException + { + final Trade items = getTrade(sign, 1, 2, player, ess); + final Trade charge = getTrade(sign, 3, ess); + charge.isAffordableFor(player); + if (!items.pay(player, false)) + { + throw new ChargeException("Inventory full"); + } + charge.charge(player); + Trade.log("Sign", "Buy", "Interact", username, charge, username, items, sign.getBlock().getLocation(), ess); + return true; + } +} diff --git a/EssentialsSigns/src/net/ess3/signs/SignDisposal.java b/EssentialsSigns/src/net/ess3/signs/SignDisposal.java new file mode 100644 index 000000000..01775e18c --- /dev/null +++ b/EssentialsSigns/src/net/ess3/signs/SignDisposal.java @@ -0,0 +1,23 @@ +package net.ess3.signs; + +import net.ess3.api.IEssentials; +import net.ess3.api.IUser; + + +public class SignDisposal extends EssentialsSign +{ + public SignDisposal() + { + super("Disposal"); + } + + @Override + protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) + { + player.sendMessage("Bukkit broke this sign :("); + //TODO: wait for a fix in bukkit + //Problem: Items can be duplicated + //player.getBase().openInventory(ess.getServer().createInventory(player, 36)); + return true; + } +} diff --git a/EssentialsSigns/src/net/ess3/signs/SignEnchant.java b/EssentialsSigns/src/net/ess3/signs/SignEnchant.java new file mode 100644 index 000000000..6004d9f38 --- /dev/null +++ b/EssentialsSigns/src/net/ess3/signs/SignEnchant.java @@ -0,0 +1,119 @@ +package net.ess3.signs; + +import static net.ess3.I18n._; +import net.ess3.api.ChargeException; +import net.ess3.api.IEssentials; +import net.ess3.api.IUser; +import net.ess3.bukkit.Enchantments; +import net.ess3.economy.Trade; +import java.util.Locale; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemStack; + + +public class SignEnchant extends EssentialsSign +{ + public SignEnchant() + { + super("Enchant"); + } + + @Override + protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException + { + final ItemStack stack = sign.getLine(1).equals("*") || sign.getLine(1).equalsIgnoreCase("any") ? null : getItemStack(sign.getLine(1), 1, ess); + final String[] enchantLevel = sign.getLine(2).split(":"); + if (enchantLevel.length != 2) + { + throw new SignException(_("invalidSignLine", 3)); + } + final Enchantment enchantment = Enchantments.getByName(enchantLevel[0]); + if (enchantment == null) + { + throw new SignException(_("enchantmentNotFound")); + } + int level; + try + { + level = Integer.parseInt(enchantLevel[1]); + } + catch (NumberFormatException ex) + { + throw new SignException(ex.getMessage(), ex); + } + if (level < 1 || level > enchantment.getMaxLevel()) + { + level = enchantment.getMaxLevel(); + sign.setLine(2, enchantLevel[0] + ":" + level); + } + try + { + if (stack != null) + { + stack.addEnchantment(enchantment, level); + } + } + catch (Throwable ex) + { + throw new SignException(ex.getMessage(), ex); + } + getTrade(sign, 3, ess); + return true; + } + + @Override + protected boolean onSignInteract(ISign sign, IUser player, String username, IEssentials ess) throws SignException, ChargeException + { + final ItemStack search = sign.getLine(1).equals("*") || sign.getLine(1).equalsIgnoreCase("any") ? null : getItemStack(sign.getLine(1), 1, ess); + int slot = -1; + final Trade charge = getTrade(sign, 3, ess); + charge.isAffordableFor(player); + final String[] enchantLevel = sign.getLine(2).split(":"); + if (enchantLevel.length != 2) + { + throw new SignException(_("invalidSignLine", 3)); + } + final Enchantment enchantment = Enchantments.getByName(enchantLevel[0]); + if (enchantment == null) + { + throw new SignException(_("enchantmentNotFound")); + } + int level; + try + { + level = Integer.parseInt(enchantLevel[1]); + } + catch (NumberFormatException ex) + { + level = enchantment.getMaxLevel(); + } + + final ItemStack playerHand = player.getItemInHand(); + if (playerHand == null + || playerHand.getAmount() != 1 + || (playerHand.containsEnchantment(enchantment) + && playerHand.getEnchantmentLevel(enchantment) == level)) + { + throw new SignException(_("missingItems", 1, sign.getLine(1))); + } + if (search != null && playerHand.getType() != search.getType()) + { + throw new SignException(_("missingItems", 1, search.getType().toString().toLowerCase(Locale.ENGLISH).replace('_', ' '))); + } + + final ItemStack toEnchant = playerHand; + try + { + toEnchant.addEnchantment(enchantment, level); + } + catch (Exception ex) + { + throw new SignException(ex.getMessage(), ex); + } + + charge.charge(player); + Trade.log("Sign", "Enchant", "Interact", username, charge, username, charge, sign.getBlock().getLocation(), ess); + player.updateInventory(); + return true; + } +} diff --git a/EssentialsSigns/src/net/ess3/signs/SignEntityListener.java b/EssentialsSigns/src/net/ess3/signs/SignEntityListener.java new file mode 100644 index 000000000..1c316478d --- /dev/null +++ b/EssentialsSigns/src/net/ess3/signs/SignEntityListener.java @@ -0,0 +1,80 @@ +package net.ess3.signs; + +import net.ess3.api.IEssentials; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityChangeBlockEvent; +import org.bukkit.event.entity.EntityExplodeEvent; + + +public class SignEntityListener implements Listener +{ + private final transient IEssentials ess; + private final transient ISignsPlugin plugin; + + public SignEntityListener(final IEssentials ess, final ISignsPlugin plugin) + { + this.ess = ess; + this.plugin = plugin; + } + + @EventHandler(priority = EventPriority.LOW) + public void onEntityExplode(final EntityExplodeEvent event) + { + if (plugin.getSettings().areSignsDisabled()) + { + return; + } + + for (Block block : event.blockList()) + { + if (((block.getTypeId() == Material.WALL_SIGN.getId() + || block.getTypeId() == Material.SIGN_POST.getId()) + && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(block))) + || EssentialsSign.checkIfBlockBreaksSigns(block)) + { + event.setCancelled(true); + return; + } + for (EssentialsSign sign : plugin.getSettings().getEnabledSigns()) + { + if (sign.getBlocks().contains(block.getType())) + { + event.setCancelled(!sign.onBlockExplode(block, ess)); + return; + } + } + } + } + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onEntityChangeBlock(final EntityChangeBlockEvent event) + { + if (plugin.getSettings().areSignsDisabled()) + { + return; + } + + final Block block = event.getBlock(); + if (((block.getTypeId() == Material.WALL_SIGN.getId() + || block.getTypeId() == Material.SIGN_POST.getId()) + && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(block))) + || EssentialsSign.checkIfBlockBreaksSigns(block)) + { + event.setCancelled(true); + return; + } + for (EssentialsSign sign : plugin.getSettings().getEnabledSigns()) + { + if (sign.getBlocks().contains(block.getType()) + && !sign.onBlockBreak(block, ess)) + { + event.setCancelled(true); + return; + } + } + } +} diff --git a/EssentialsSigns/src/net/ess3/signs/SignException.java b/EssentialsSigns/src/net/ess3/signs/SignException.java new file mode 100644 index 000000000..7ca73e4e5 --- /dev/null +++ b/EssentialsSigns/src/net/ess3/signs/SignException.java @@ -0,0 +1,15 @@ +package net.ess3.signs; + + +public class SignException extends Exception +{ + public SignException(final String message) + { + super(message); + } + + public SignException(final String message, final Throwable throwable) + { + super(message, throwable); + } +} diff --git a/EssentialsSigns/src/net/ess3/signs/SignFree.java b/EssentialsSigns/src/net/ess3/signs/SignFree.java new file mode 100644 index 000000000..2cf049346 --- /dev/null +++ b/EssentialsSigns/src/net/ess3/signs/SignFree.java @@ -0,0 +1,47 @@ +package net.ess3.signs; + +import static net.ess3.I18n._; +import net.ess3.api.IEssentials; +import net.ess3.api.IUser; +import net.ess3.craftbukkit.InventoryWorkaround; +import net.ess3.economy.Trade; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + + +public class SignFree extends EssentialsSign +{ + public SignFree() + { + super("Free"); + } + + @Override + protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException + { + getItemStack(sign.getLine(1), 1, ess); + return true; + } + + @Override + protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException + { + final ItemStack item = getItemStack(sign.getLine(1), 1, ess); + if (item.getType() == Material.AIR) + { + throw new SignException(_("cantSpawnItem", "Air")); + } + + item.setAmount(item.getType().getMaxStackSize()); + InventoryWorkaround.addItem(player.getInventory(), true, item); + player.sendMessage("Item added to your inventory."); + player.updateInventory(); + //TODO: wait for a fix in bukkit + //Problem: Items can be duplicated + //Inventory i = ess.getServer().createInventory(player, InventoryType.CHEST); + //i.addItem(item); + //player.openInventory(i); + Trade.log("Sign", "Free", "Interact", username, null, username, new Trade(item, ess), sign.getBlock().getLocation(), ess); + return true; + } +} diff --git a/EssentialsSigns/src/net/ess3/signs/SignGameMode.java b/EssentialsSigns/src/net/ess3/signs/SignGameMode.java new file mode 100644 index 000000000..a8ef5a881 --- /dev/null +++ b/EssentialsSigns/src/net/ess3/signs/SignGameMode.java @@ -0,0 +1,37 @@ +package net.ess3.signs; + +import static net.ess3.I18n._; +import net.ess3.api.ChargeException; +import net.ess3.api.IEssentials; +import net.ess3.api.IUser; +import net.ess3.economy.Trade; +import java.util.Locale; +import org.bukkit.GameMode; + + +public class SignGameMode extends EssentialsSign +{ + public SignGameMode() + { + super("GameMode"); + } + + @Override + protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException + { + validateTrade(sign, 1, ess); + return true; + } + + @Override + protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException + { + final Trade charge = getTrade(sign, 1, ess); + charge.isAffordableFor(player); + + player.setGameMode(player.getGameMode() == GameMode.SURVIVAL ? GameMode.CREATIVE : GameMode.SURVIVAL); + player.sendMessage(_("gameMode", _(player.getGameMode().toString().toLowerCase(Locale.ENGLISH)), player.getDisplayName())); + charge.charge(player); + return true; + } +} diff --git a/EssentialsSigns/src/net/ess3/signs/SignHeal.java b/EssentialsSigns/src/net/ess3/signs/SignHeal.java new file mode 100644 index 000000000..787e7b166 --- /dev/null +++ b/EssentialsSigns/src/net/ess3/signs/SignHeal.java @@ -0,0 +1,36 @@ +package net.ess3.signs; + +import static net.ess3.I18n._; +import net.ess3.api.ChargeException; +import net.ess3.api.IEssentials; +import net.ess3.api.IUser; +import net.ess3.economy.Trade; + + +public class SignHeal extends EssentialsSign +{ + public SignHeal() + { + super("Heal"); + } + + @Override + protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException + { + validateTrade(sign, 1, ess); + return true; + } + + @Override + protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException + { + final Trade charge = getTrade(sign, 1, ess); + charge.isAffordableFor(player); + player.setHealth(20); + player.setFoodLevel(20); + player.setFireTicks(0); + player.sendMessage(_("youAreHealed")); + charge.charge(player); + return true; + } +} diff --git a/EssentialsSigns/src/net/ess3/signs/SignKit.java b/EssentialsSigns/src/net/ess3/signs/SignKit.java new file mode 100644 index 000000000..9c478ccad --- /dev/null +++ b/EssentialsSigns/src/net/ess3/signs/SignKit.java @@ -0,0 +1,75 @@ +package net.ess3.signs; + +import net.ess3.api.ChargeException; +import net.ess3.economy.Trade; +import net.ess3.api.IEssentials; +import net.ess3.api.IUser; +import net.ess3.permissions.KitPermissions; +import net.ess3.settings.Kit; +import java.util.Locale; + + +public class SignKit extends EssentialsSign +{ + public SignKit() + { + super("Kit"); + } + + @Override + protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException + { + validateTrade(sign, 3, ess); + + final String kitName = sign.getLine(1).toLowerCase(Locale.ENGLISH); + + if (kitName.isEmpty()) + { + sign.setLine(1, "§dKit name!"); + return false; + } + else + { + try + { + ess.getKits().getKit(kitName); + } + catch (Exception ex) + { + throw new SignException(ex.getMessage(), ex); + } + final String group = sign.getLine(2); + if ("Everyone".equalsIgnoreCase(group) || "Everybody".equalsIgnoreCase(group)) + { + sign.setLine(2, "§2Everyone"); + } + return true; + } + } + + @Override + protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException + { + final String kitName = sign.getLine(1).toLowerCase(Locale.ENGLISH); + final String group = sign.getLine(2); + if ((!group.isEmpty() && ("§2Everyone".equals(group) || ess.getRanks().inGroup(player, group))) + || (group.isEmpty() && KitPermissions.getPermission(kitName).isAuthorized(player))) + { + final Trade charge = getTrade(sign, 3, ess); + charge.isAffordableFor(player); + try + {; + final Kit kit = ess.getKits().getKit(kitName); + ess.getKits().checkTime(player, kit); + ess.getKits().sendKit(player, kit); + charge.charge(player); + } + catch (Exception ex) + { + throw new SignException(ex.getMessage(), ex); + } + return true; + } + return false; + } +} diff --git a/EssentialsSigns/src/net/ess3/signs/SignMail.java b/EssentialsSigns/src/net/ess3/signs/SignMail.java new file mode 100644 index 000000000..6acf14bb1 --- /dev/null +++ b/EssentialsSigns/src/net/ess3/signs/SignMail.java @@ -0,0 +1,41 @@ +package net.ess3.signs; + +import static net.ess3.I18n._; +import net.ess3.api.IEssentials; +import net.ess3.api.IUser; +import java.util.List; + + +public class SignMail extends EssentialsSign +{ + public SignMail() + { + super("Mail"); + } + + @Override + protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException + { + final List mail; + player.acquireReadLock(); + try + { + mail = player.getData().getMails(); + } + finally + { + player.unlock(); + } + if (mail == null || mail.isEmpty()) + { + player.sendMessage(_("noNewMail")); + return false; + } + for (String s : mail) + { + player.sendMessage(s); + } + player.sendMessage(_("markMailAsRead")); + return true; + } +} diff --git a/EssentialsSigns/src/net/ess3/signs/SignPlayerListener.java b/EssentialsSigns/src/net/ess3/signs/SignPlayerListener.java new file mode 100644 index 000000000..eabf5423b --- /dev/null +++ b/EssentialsSigns/src/net/ess3/signs/SignPlayerListener.java @@ -0,0 +1,65 @@ +package net.ess3.signs; + +import net.ess3.api.IEssentials; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.Sign; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; + + +public class SignPlayerListener implements Listener +{ + private final transient IEssentials ess; + private final transient ISignsPlugin plugin; + + public SignPlayerListener(final IEssentials ess, final ISignsPlugin plugin) + { + this.ess = ess; + this.plugin = plugin; + } + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onPlayerInteract(final PlayerInteractEvent event) + { + if (plugin.getSettings().areSignsDisabled() || event.getAction() != Action.RIGHT_CLICK_BLOCK) + { + return; + } + final Block block = event.getClickedBlock(); + if (block == null) + { + return; + } + + final int mat = block.getTypeId(); + if (mat == Material.SIGN_POST.getId() || mat == Material.WALL_SIGN.getId()) + { + final Sign csign = (Sign)block.getState(); + for (EssentialsSign sign : plugin.getSettings().getEnabledSigns()) + { + if (csign.getLine(0).equalsIgnoreCase(sign.getSuccessName())) + { + sign.onSignInteract(block, event.getPlayer(), ess); + event.setCancelled(true); + return; + } + } + } + else + { + for (EssentialsSign sign : plugin.getSettings().getEnabledSigns()) + { + if (sign.getBlocks().contains(block.getType()) + && !sign.onBlockInteract(block, event.getPlayer(), ess)) + { + event.setCancelled(true); + return; + } + } + } + } +} diff --git a/EssentialsSigns/src/net/ess3/signs/SignProtection.java b/EssentialsSigns/src/net/ess3/signs/SignProtection.java new file mode 100644 index 000000000..e87002fd4 --- /dev/null +++ b/EssentialsSigns/src/net/ess3/signs/SignProtection.java @@ -0,0 +1,350 @@ +package net.ess3.signs; + +import static net.ess3.I18n._; +import net.ess3.api.ChargeException; +import net.ess3.api.IEssentials; +import net.ess3.api.IUser; +import net.ess3.economy.Trade; +import net.ess3.utils.Util; +import java.util.*; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.Sign; +import org.bukkit.inventory.ItemStack; + + +public class SignProtection extends EssentialsSign +{ + private final transient Set protectedBlocks = EnumSet.noneOf(Material.class); + + public SignProtection() + { + super("Protection"); + protectedBlocks.add(Material.CHEST); + protectedBlocks.add(Material.BURNING_FURNACE); + protectedBlocks.add(Material.FURNACE); + protectedBlocks.add(Material.DISPENSER); + } + + @Override + protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException + { + sign.setLine(3, "§4" + username); + if (hasAdjacentBlock(sign.getBlock())) + { + final SignProtectionState state = isBlockProtected(sign.getBlock(), player, username, true, ess); + if (state == SignProtectionState.NOSIGN || state == SignProtectionState.OWNER + || SignsPermissions.PROTECTION_OVERRIDE.isAuthorized(player)) + { + sign.setLine(3, "§1" + username); + return true; + } + } + player.sendMessage(_("signProtectInvalidLocation")); + return false; + } + + @Override + protected boolean onSignBreak(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException + { + final SignProtectionState state = checkProtectionSign(sign, player, username, ess); + return state == SignProtectionState.OWNER; + } + + public boolean hasAdjacentBlock(final Block block, final Block... ignoredBlocks) + { + final Block[] faces = getAdjacentBlocks(block); + for (Block b : faces) + { + for (Block ignoredBlock : ignoredBlocks) + { + if (b.getLocation().equals(ignoredBlock.getLocation())) + { + continue; + } + } + if (protectedBlocks.contains(b.getType())) + { + return true; + } + } + return false; + } + + private void checkIfSignsAreBroken(final Block block, final IUser player, final String username, final IEssentials ess) + { + final Map signs = getConnectedSigns(block, player, username, false, ess); + for (Map.Entry entry : signs.entrySet()) + { + if (entry.getValue() != SignProtectionState.NOSIGN) + { + final Block sign = entry.getKey().getBlock(); + if (!hasAdjacentBlock(sign, block)) + { + block.setType(Material.AIR); + final Trade trade = new Trade(new ItemStack(Material.SIGN, 1), ess); + trade.pay(player); + } + } + } + } + + private Map getConnectedSigns(final Block block, final IUser user, final String username, boolean secure, final IEssentials ess) + { + final Map signs = new HashMap(); + getConnectedSigns(block, signs, user, username, secure ? 4 : 2, ess); + return signs; + } + + private void getConnectedSigns(final Block block, final Map signs, final IUser user, final String username, final int depth, final IEssentials ess) + { + final Block[] faces = getAdjacentBlocks(block); + for (Block b : faces) + { + final Location loc = b.getLocation(); + if (signs.containsKey(loc)) + { + continue; + } + final SignProtectionState check = checkProtectionSign(b, user, username, ess); + signs.put(loc, check); + + if (protectedBlocks.contains(b.getType()) && depth > 0) + { + getConnectedSigns(b, signs, user, username, depth - 1, ess); + } + } + } + + + public enum SignProtectionState + { + NOT_ALLOWED, ALLOWED, NOSIGN, OWNER + } + + private SignProtectionState checkProtectionSign(final Block block, final IUser user, final String username, final IEssentials ess) + { + if (block.getType() == Material.SIGN_POST || block.getType() == Material.WALL_SIGN) + { + final BlockSign sign = new BlockSign(block); + if (sign.getLine(0).equals(this.getSuccessName())) + { + return checkProtectionSign(sign, user, username, ess); + } + } + return SignProtectionState.NOSIGN; + } + + private SignProtectionState checkProtectionSign(final ISign sign, final IUser user, final String username, final IEssentials ess) + { + if (user == null || username == null) + { + return SignProtectionState.NOT_ALLOWED; + } + if (SignsPermissions.PROTECTION_OVERRIDE.isAuthorized(user)) + { + return SignProtectionState.OWNER; + } + if (Util.stripFormat(sign.getLine(3)).equalsIgnoreCase(username)) + { + return SignProtectionState.OWNER; + } + for (int i = 1; i <= 2; i++) + { + final String line = sign.getLine(i); + if (line.startsWith("(") && line.endsWith(")") && ess.getRanks().inGroup(user, line.substring(1, line.length() - 1))) + { + return SignProtectionState.ALLOWED; + } + else if (line.equalsIgnoreCase(username)) + { + return SignProtectionState.ALLOWED; + } + } + return SignProtectionState.NOT_ALLOWED; + } + + private Block[] getAdjacentBlocks(final Block block) + { + return new Block[] + { + block.getRelative(BlockFace.NORTH), + block.getRelative(BlockFace.SOUTH), + block.getRelative(BlockFace.EAST), + block.getRelative(BlockFace.WEST), + block.getRelative(BlockFace.DOWN), + block.getRelative(BlockFace.UP) + }; + } + + public SignProtectionState isBlockProtected(final Block block, final IUser user, final String username, boolean secure, final IEssentials ess) + { + final Map signs = getConnectedSigns(block, user, username, secure, ess); + SignProtectionState retstate = SignProtectionState.NOSIGN; + for (SignProtectionState state : signs.values()) + { + if (state == SignProtectionState.ALLOWED) + { + retstate = state; + } + else if (state == SignProtectionState.NOT_ALLOWED && retstate != SignProtectionState.ALLOWED) + { + retstate = state; + } + } + if (!secure || retstate == SignProtectionState.NOSIGN) + { + for (SignProtectionState state : signs.values()) + { + if (state == SignProtectionState.OWNER) + { + return state; + } + } + } + return retstate; + } + + public boolean isBlockProtected(final Block block) + { + final Block[] faces = getAdjacentBlocks(block); + for (Block b : faces) + { + if (b.getType() == Material.SIGN_POST || b.getType() == Material.WALL_SIGN) + { + final Sign sign = (Sign)b.getState(); + if (sign.getLine(0).equalsIgnoreCase("§1[Protection]")) + { + return true; + } + } + if (protectedBlocks.contains(b.getType())) + { + final Block[] faceChest = getAdjacentBlocks(b); + + for (Block a : faceChest) + { + if (a.getType() == Material.SIGN_POST || a.getType() == Material.WALL_SIGN) + { + final Sign sign = (Sign)a.getState(); + if (sign.getLine(0).equalsIgnoreCase("§1[Protection]")) + { + return true; + } + } + } + } + } + return false; + } + + @Override + public Set getBlocks() + { + return protectedBlocks; + } + + @Override + protected boolean onBlockPlace(final Block block, final IUser player, final String username, final IEssentials ess) throws SignException + { + for (Block adjBlock : getAdjacentBlocks(block)) + { + final SignProtectionState state = isBlockProtected(adjBlock, player, username, true, ess); + + if ((state == SignProtectionState.ALLOWED || state == SignProtectionState.NOT_ALLOWED) + && !SignsPermissions.PROTECTION_OVERRIDE.isAuthorized(player)) + { + player.sendMessage(_("noPlacePermission", block.getType().toString().toLowerCase(Locale.ENGLISH))); + return false; + } + } + return true; + + } + + @Override + protected boolean onBlockInteract(final Block block, final IUser player, final String username, final IEssentials ess) throws SignException + { + final SignProtectionState state = isBlockProtected(block, player, username, false, ess); + + if (state == SignProtectionState.OWNER || state == SignProtectionState.NOSIGN || state == SignProtectionState.ALLOWED) + { + return true; + } + + if (state == SignProtectionState.NOT_ALLOWED + && SignsPermissions.PROTECTION_OVERRIDE.isAuthorized(player)) + { + return true; + } + + + player.sendMessage(_("noAccessPermission", block.getType().toString().toLowerCase(Locale.ENGLISH))); + return false; + } + + @Override + protected boolean onBlockBreak(final Block block, final IUser player, final String username, final IEssentials ess) throws SignException + { + final SignProtectionState state = isBlockProtected(block, player, username, false, ess); + + if (state == SignProtectionState.OWNER || state == SignProtectionState.NOSIGN) + { + checkIfSignsAreBroken(block, player, username, ess); + return true; + } + + if ((state == SignProtectionState.ALLOWED || state == SignProtectionState.NOT_ALLOWED) + && SignsPermissions.PROTECTION_OVERRIDE.isAuthorized(player)) + { + checkIfSignsAreBroken(block, player, username, ess); + return true; + } + + + player.sendMessage(_("noDestroyPermission", block.getType().toString().toLowerCase(Locale.ENGLISH))); + return false; + } + + @Override + public boolean onBlockBreak(final Block block, final IEssentials ess) + { + final SignProtectionState state = isBlockProtected(block, null, null, false, ess); + + return state == SignProtectionState.NOSIGN; + } + + @Override + public boolean onBlockExplode(final Block block, final IEssentials ess) + { + final SignProtectionState state = isBlockProtected(block, null, null, false, ess); + + return state == SignProtectionState.NOSIGN; + } + + @Override + public boolean onBlockBurn(final Block block, final IEssentials ess) + { + final SignProtectionState state = isBlockProtected(block, null, null, false, ess); + + return state == SignProtectionState.NOSIGN; + } + + @Override + public boolean onBlockIgnite(final Block block, final IEssentials ess) + { + final SignProtectionState state = isBlockProtected(block, null, null, false, ess); + + return state == SignProtectionState.NOSIGN; + } + + @Override + public boolean onBlockPush(final Block block, final IEssentials ess) + { + final SignProtectionState state = isBlockProtected(block, null, null, false, ess); + + return state == SignProtectionState.NOSIGN; + } +} diff --git a/EssentialsSigns/src/net/ess3/signs/SignSell.java b/EssentialsSigns/src/net/ess3/signs/SignSell.java new file mode 100644 index 000000000..9a48e4948 --- /dev/null +++ b/EssentialsSigns/src/net/ess3/signs/SignSell.java @@ -0,0 +1,35 @@ +package net.ess3.signs; + +import net.ess3.api.ChargeException; +import net.ess3.api.IEssentials; +import net.ess3.api.IUser; +import net.ess3.economy.Trade; + + +public class SignSell extends EssentialsSign +{ + public SignSell() + { + super("Sell"); + } + + @Override + protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException + { + validateTrade(sign, 1, 2, player, ess); + validateTrade(sign, 3, ess); + return true; + } + + @Override + protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException + { + final Trade charge = getTrade(sign, 1, 2, player, ess); + final Trade money = getTrade(sign, 3, ess); + charge.isAffordableFor(player); + money.pay(player); + charge.charge(player); + Trade.log("Sign", "Sell", "Interact", username, charge, username, money, sign.getBlock().getLocation(), ess); + return true; + } +} diff --git a/EssentialsSigns/src/net/ess3/signs/SignSpawnmob.java b/EssentialsSigns/src/net/ess3/signs/SignSpawnmob.java new file mode 100644 index 000000000..47961a96e --- /dev/null +++ b/EssentialsSigns/src/net/ess3/signs/SignSpawnmob.java @@ -0,0 +1,48 @@ +package net.ess3.signs; + +import net.ess3.api.ChargeException; +import net.ess3.api.IEssentials; +import net.ess3.api.IUser; +import net.ess3.commands.Commandspawnmob; +import net.ess3.economy.Trade; + + +public class SignSpawnmob extends EssentialsSign +{ + public SignSpawnmob() + { + super("Spawnmob"); + } + + @Override + protected boolean onSignCreate(ISign sign, IUser player, String username, IEssentials ess) throws SignException, ChargeException + { + validateInteger(sign, 1); + validateTrade(sign, 3, ess); + return true; + } + + //TODO: This should call a method not a command + @Override + protected boolean onSignInteract(ISign sign, IUser player, String username, IEssentials ess) throws SignException, ChargeException + { + final Trade charge = getTrade(sign, 3, ess); + charge.isAffordableFor(player); + Commandspawnmob command = new Commandspawnmob(); + command.init(ess, "spawnmob"); + String[] args = new String[] + { + sign.getLine(2), sign.getLine(1) + }; + try + { + command.run(player, "spawnmob", args); + } + catch (Exception ex) + { + throw new SignException(ex.getMessage(), ex); + } + charge.charge(player); + return true; + } +} diff --git a/EssentialsSigns/src/net/ess3/signs/SignTime.java b/EssentialsSigns/src/net/ess3/signs/SignTime.java new file mode 100644 index 000000000..8ef98a4d5 --- /dev/null +++ b/EssentialsSigns/src/net/ess3/signs/SignTime.java @@ -0,0 +1,57 @@ +package net.ess3.signs; + +import static net.ess3.I18n._; +import net.ess3.api.ChargeException; +import net.ess3.api.IEssentials; +import net.ess3.api.IUser; +import net.ess3.economy.Trade; + + +public class SignTime extends EssentialsSign +{ + public SignTime() + { + super("Time"); + } + + @Override + protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException + { + validateTrade(sign, 2, ess); + final String timeString = sign.getLine(1); + if ("Day".equalsIgnoreCase(timeString)) + { + sign.setLine(1, "§2Day"); + return true; + } + if ("Night".equalsIgnoreCase(timeString)) + { + sign.setLine(1, "§2Night"); + return true; + } + throw new SignException(_("onlyDayNight")); + } + + @Override + protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException + { + final Trade charge = getTrade(sign, 2, ess); + charge.isAffordableFor(player); + final String timeString = sign.getLine(1); + long time = player.getWorld().getTime(); + time -= time % 24000; + if ("§2Day".equalsIgnoreCase(timeString)) + { + player.getWorld().setTime(time + 24000); + charge.charge(player); + return true; + } + if ("§2Night".equalsIgnoreCase(timeString)) + { + player.getWorld().setTime(time + 37700); + charge.charge(player); + return true; + } + throw new SignException(_("onlyDayNight")); + } +} diff --git a/EssentialsSigns/src/net/ess3/signs/SignTrade.java b/EssentialsSigns/src/net/ess3/signs/SignTrade.java new file mode 100644 index 000000000..c3e78e226 --- /dev/null +++ b/EssentialsSigns/src/net/ess3/signs/SignTrade.java @@ -0,0 +1,361 @@ +package net.ess3.signs; + +import net.ess3.api.ChargeException; +import static net.ess3.I18n._; +import net.ess3.economy.Trade; +import net.ess3.utils.Util; +import net.ess3.api.IEssentials; +import net.ess3.api.IUser; +import org.bukkit.inventory.ItemStack; + +//TODO: Sell Enchantment on Trade signs? +public class SignTrade extends EssentialsSign +{ + + public SignTrade() + { + super("Trade"); + } + + @Override + protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException + { + validateTrade(sign, 1, false, ess); + validateTrade(sign, 2, true, ess); + final Trade charge = getTrade(sign, 2, true, true, ess); + charge.isAffordableFor(player); + sign.setLine(3, "§8" + username); + charge.charge(player); + Trade.log("Sign", "Trade", "Create", username, charge, username, null, sign.getBlock().getLocation(), ess); + return true; + } + + @Override + protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException + { + if (sign.getLine(3).substring(2).equalsIgnoreCase(username)) + { + final Trade store = rechargeSign(sign, ess, player); + Trade stored = null; + try + { + stored = getTrade(sign, 1, true, true, ess); + subtractAmount(sign, 1, stored, ess); + stored.pay(player); + } + catch (SignException e) + { + if (store == null) + { + throw new SignException(_("tradeSignEmptyOwner"), e); + } + } + Trade.log("Sign", "Trade", "OwnerInteract", username, store, username, stored, sign.getBlock().getLocation(), ess); + } + else + { + final Trade charge = getTrade(sign, 1, false, false, ess); + final Trade trade = getTrade(sign, 2, false, true, ess); + charge.isAffordableFor(player); + addAmount(sign, 1, charge, ess); + subtractAmount(sign, 2, trade, ess); + if (!trade.pay(player, false)) + { + subtractAmount(sign, 1, charge, ess); + addAmount(sign, 2, trade, ess); + throw new ChargeException("Full inventory"); + } + charge.charge(player); + Trade.log("Sign", "Trade", "Interact", sign.getLine(3), charge, username, trade, sign.getBlock().getLocation(), ess); + } + sign.updateSign(); + return true; + } + + private Trade rechargeSign(final ISign sign, final IEssentials ess, final IUser player) throws SignException, ChargeException + { + final Trade trade = getTrade(sign, 2, false, false, ess); + if (trade.getItemStack() != null && player.getItemInHand() != null + && trade.getItemStack().getTypeId() == player.getItemInHand().getTypeId() + && trade.getItemStack().getDurability() == player.getItemInHand().getDurability() + && trade.getItemStack().getEnchantments().equals(player.getItemInHand().getEnchantments())) + { + int amount = player.getItemInHand().getAmount(); + amount -= amount % trade.getItemStack().getAmount(); + if (amount > 0) + { + final ItemStack stack = player.getItemInHand().clone(); + stack.setAmount(amount); + final Trade store = new Trade(stack, ess); + addAmount(sign, 2, store, ess); + store.charge(player); + return store; + } + } + return null; + } + + @Override + protected boolean onSignBreak(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException + { + if ((sign.getLine(3).length() > 3 && sign.getLine(3).substring(2).equalsIgnoreCase(username)) + || SignsPermissions.TRADE_OVERRIDE.isAuthorized(player)) + { + try + { + final Trade stored1 = getTrade(sign, 1, true, false, ess); + final Trade stored2 = getTrade(sign, 2, true, false, ess); + stored1.pay(player); + stored2.pay(player); + Trade.log("Sign", "Trade", "Break", username, stored2, username, stored1, sign.getBlock().getLocation(), ess); + } + catch (SignException e) + { + if (SignsPermissions.TRADE_OVERRIDE.isAuthorized(player)) + { + return true; + } + throw e; + } + return true; + } + else + { + return false; + } + } + + protected final void validateTrade(final ISign sign, final int index, final boolean amountNeeded, final IEssentials ess) throws SignException + { + final String line = sign.getLine(index).trim(); + if (line.isEmpty()) + { + throw new SignException("Empty line"); + } + final String[] split = line.split("[ :]+"); + + if (split.length == 1 && !amountNeeded) + { + final Double money = getMoney(split[0]); + if (money != null) + { + if (Util.shortCurrency(money, ess).length() * 2 > 15) + { + throw new SignException("Line can be too long!"); + } + sign.setLine(index, Util.shortCurrency(money, ess) + ":0"); + return; + } + } + + if (split.length == 2 && amountNeeded) + { + final Double money = getMoney(split[0]); + Double amount = getDoublePositive(split[1]); + if (money != null && amount != null) + { + amount -= amount % money; + if (amount < 0.01 || money < 0.01) + { + throw new SignException(_("moreThanZero")); + } + sign.setLine(index, Util.shortCurrency(money, ess) + ":" + Util.shortCurrency(amount, ess).substring(1)); + return; + } + } + + if (split.length == 2 && !amountNeeded) + { + final int amount = getIntegerPositive(split[0]); + + if (amount < 1) + { + throw new SignException(_("moreThanZero")); + } + if (!(split[1].equalsIgnoreCase("exp") || split[1].equalsIgnoreCase("xp")) + && getItemStack(split[1], amount, ess).getTypeId() == 0) + { + throw new SignException(_("moreThanZero")); + } + String newline = amount + " " + split[1] + ":0"; + if ((newline + amount).length() > 15) + { + throw new SignException("Line can be too long!"); + } + sign.setLine(index, newline); + return; + } + + if (split.length == 3 && amountNeeded) + { + final int stackamount = getIntegerPositive(split[0]); + int amount = getIntegerPositive(split[2]); + amount -= amount % stackamount; + if (amount < 1 || stackamount < 1) + { + throw new SignException(_("moreThanZero")); + } + if (!(split[1].equalsIgnoreCase("exp") || split[1].equalsIgnoreCase("xp")) + && getItemStack(split[1], stackamount, ess).getTypeId() == 0) + { + throw new SignException(_("moreThanZero")); + } + sign.setLine(index, stackamount + " " + split[1] + ":" + amount); + return; + } + throw new SignException(_("invalidSignLine", index + 1)); + } + + protected final Trade getTrade(final ISign sign, final int index, final boolean fullAmount, final boolean notEmpty, final IEssentials ess) throws SignException + { + final String line = sign.getLine(index).trim(); + if (line.isEmpty()) + { + throw new SignException("Empty line"); + } + final String[] split = line.split("[ :]+"); + + if (split.length == 2) + { + try + { + final Double money = getMoney(split[0]); + final Double amount = notEmpty ? getDoublePositive(split[1]) : getDouble(split[1]); + if (money != null && amount != null) + { + return new Trade(fullAmount ? amount : money, ess); + } + } + catch (SignException e) + { + throw new SignException(_("tradeSignEmpty"), e); + } + } + + if (split.length == 3) + { + if (split[1].equalsIgnoreCase("exp") || split[1].equalsIgnoreCase("xp")) + { + final int stackamount = getIntegerPositive(split[0]); + int amount = getInteger(split[2]); + amount -= amount % stackamount; + if (notEmpty && (amount < 1 || stackamount < 1)) + { + throw new SignException(_("tradeSignEmpty")); + } + return new Trade(fullAmount ? amount : stackamount, ess); + } + else + { + final int stackamount = getIntegerPositive(split[0]); + final ItemStack item = getItemStack(split[1], stackamount, ess); + int amount = getInteger(split[2]); + amount -= amount % stackamount; + if (notEmpty && (amount < 1 || stackamount < 1 || item.getTypeId() == 0)) + { + throw new SignException(_("tradeSignEmpty")); + } + item.setAmount(fullAmount ? amount : stackamount); + return new Trade(item, ess); + } + } + throw new SignException(_("invalidSignLine", index + 1)); + } + + protected final void subtractAmount(final ISign sign, final int index, final Trade trade, final IEssentials ess) throws SignException + { + final Double money = trade.getMoney(); + if (money != null) + { + changeAmount(sign, index, -money, ess); + } + final ItemStack item = trade.getItemStack(); + if (item != null) + { + changeAmount(sign, index, -item.getAmount(), ess); + } + final Integer exp = trade.getExperience(); + if (exp != null) + { + changeAmount(sign, index, -exp.intValue(), ess); + } + } + + protected final void addAmount(final ISign sign, final int index, final Trade trade, final IEssentials ess) throws SignException + { + final Double money = trade.getMoney(); + if (money != null) + { + changeAmount(sign, index, money, ess); + } + final ItemStack item = trade.getItemStack(); + if (item != null) + { + changeAmount(sign, index, item.getAmount(), ess); + } + final Integer exp = trade.getExperience(); + if (exp != null) + { + changeAmount(sign, index, exp.intValue(), ess); + } + } + + //TODO: Translate these exceptions. + private void changeAmount(final ISign sign, final int index, final double value, final IEssentials ess) throws SignException + { + + final String line = sign.getLine(index).trim(); + if (line.isEmpty()) + { + throw new SignException("Empty line"); + } + final String[] split = line.split("[ :]+"); + + if (split.length == 2) + { + final Double money = getMoney(split[0]); + final Double amount = getDouble(split[1]); + if (money != null && amount != null) + { + final String newline = Util.shortCurrency(money, ess) + ":" + Util.shortCurrency(amount + value, ess).substring(1); + if (newline.length() > 15) + { + throw new SignException("This sign is full: Line too long!"); + } + sign.setLine(index, newline); + return; + } + } + + if (split.length == 3) + { + if (split[1].equalsIgnoreCase("exp") || split[1].equalsIgnoreCase("xp")) + { + final int stackamount = getIntegerPositive(split[0]); + final int amount = getInteger(split[2]); + final String newline = stackamount + " " + split[1] + ":" + (amount + Math.round(value)); + if (newline.length() > 15) + { + throw new SignException("This sign is full: Line too long!"); + } + sign.setLine(index, newline); + return; + } + else + { + final int stackamount = getIntegerPositive(split[0]); + //TODO: Unused local variable + final ItemStack item = getItemStack(split[1], stackamount, ess); + final int amount = getInteger(split[2]); + final String newline = stackamount + " " + split[1] + ":" + (amount + Math.round(value)); + if (newline.length() > 15) + { + throw new SignException("This sign is full: Line too long!"); + } + sign.setLine(index, newline); + return; + } + } + throw new SignException(_("invalidSignLine", index + 1)); + } +} diff --git a/EssentialsSigns/src/net/ess3/signs/SignWarp.java b/EssentialsSigns/src/net/ess3/signs/SignWarp.java new file mode 100644 index 000000000..b6dc95d0f --- /dev/null +++ b/EssentialsSigns/src/net/ess3/signs/SignWarp.java @@ -0,0 +1,70 @@ +package net.ess3.signs; + +import net.ess3.api.ChargeException; +import net.ess3.api.IEssentials; +import net.ess3.api.IUser; +import net.ess3.economy.Trade; +import net.ess3.permissions.WarpPermissions; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; + + +public class SignWarp extends EssentialsSign +{ + public SignWarp() + { + super("Warp"); + } + + @Override + protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException + { + validateTrade(sign, 3, ess); + final String warpName = sign.getLine(1); + + if (warpName.isEmpty()) + { + sign.setLine(1, "§dWarp name!"); + return false; + } + else + { + try + { + ess.getWarps().getWarp(warpName); + } + catch (Exception ex) + { + throw new SignException(ex.getMessage(), ex); + } + final String group = sign.getLine(2); + if ("Everyone".equalsIgnoreCase(group) || "Everybody".equalsIgnoreCase(group)) + { + sign.setLine(2, "§2Everyone"); + } + return true; + } + } + + @Override + protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException + { + final String warpName = sign.getLine(1); + final String group = sign.getLine(2); + + if ((!group.isEmpty() && ("§2Everyone".equals(group) || ess.getRanks().inGroup(player, group))) + || (group.isEmpty() && WarpPermissions.getPermission(warpName).isAuthorized(player))) + { + final Trade charge = getTrade(sign, 3, ess); + try + { + player.getTeleport().warp(warpName, charge, TeleportCause.PLUGIN); + } + catch (Exception ex) + { + throw new SignException(ex.getMessage(), ex); + } + return true; + } + return false; + } +} diff --git a/EssentialsSigns/src/net/ess3/signs/SignWeather.java b/EssentialsSigns/src/net/ess3/signs/SignWeather.java new file mode 100644 index 000000000..94217aeec --- /dev/null +++ b/EssentialsSigns/src/net/ess3/signs/SignWeather.java @@ -0,0 +1,55 @@ +package net.ess3.signs; + +import static net.ess3.I18n._; +import net.ess3.api.ChargeException; +import net.ess3.api.IEssentials; +import net.ess3.api.IUser; +import net.ess3.economy.Trade; + + +public class SignWeather extends EssentialsSign +{ + public SignWeather() + { + super("Weather"); + } + + @Override + protected boolean onSignCreate(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException + { + validateTrade(sign, 2, ess); + final String timeString = sign.getLine(1); + if ("Sun".equalsIgnoreCase(timeString)) + { + sign.setLine(1, "§2Sun"); + return true; + } + if ("Storm".equalsIgnoreCase(timeString)) + { + sign.setLine(1, "§2Storm"); + return true; + } + throw new SignException(_("onlySunStorm")); + } + + @Override + protected boolean onSignInteract(final ISign sign, final IUser player, final String username, final IEssentials ess) throws SignException, ChargeException + { + final Trade charge = getTrade(sign, 2, ess); + charge.isAffordableFor(player); + final String weatherString = sign.getLine(1); + if ("§2Sun".equalsIgnoreCase(weatherString)) + { + player.getWorld().setStorm(false); + charge.charge(player); + return true; + } + if ("§2Storm".equalsIgnoreCase(weatherString)) + { + player.getWorld().setStorm(true); + charge.charge(player); + return true; + } + throw new SignException(_("onlySunStorm")); + } +} diff --git a/EssentialsSigns/src/net/ess3/signs/Signs.java b/EssentialsSigns/src/net/ess3/signs/Signs.java new file mode 100644 index 000000000..af4111dac --- /dev/null +++ b/EssentialsSigns/src/net/ess3/signs/Signs.java @@ -0,0 +1,33 @@ +package net.ess3.signs; + + +public enum Signs +{ + BALANCE(new SignBalance()), + BUY(new SignBuy()), + DISPOSAL(new SignDisposal()), + ENCHANT(new SignEnchant()), + FREE(new SignFree()), + GAMEMODE(new SignGameMode()), + HEAL(new SignHeal()), + KIT(new SignKit()), + MAIL(new SignMail()), + PROTECTION(new SignProtection()), + SELL(new SignSell()), + SPAWNMOB(new SignSpawnmob()), + TIME(new SignTime()), + TRADE(new SignTrade()), + WARP(new SignWarp()), + WEATHER(new SignWeather()); + private final EssentialsSign sign; + + private Signs(final EssentialsSign sign) + { + this.sign = sign; + } + + public EssentialsSign getSign() + { + return sign; + } +} diff --git a/EssentialsSigns/src/net/ess3/signs/SignsConfig.java b/EssentialsSigns/src/net/ess3/signs/SignsConfig.java new file mode 100644 index 000000000..70b606962 --- /dev/null +++ b/EssentialsSigns/src/net/ess3/signs/SignsConfig.java @@ -0,0 +1,21 @@ +package net.ess3.signs; + +import net.ess3.storage.StorageObject; +import java.util.HashMap; +import java.util.Map; + + +public class SignsConfig implements StorageObject +{ + private Map signs = new HashMap(); + + public Map getSigns() + { + return signs; + } + + public void setSigns(final Map signs) + { + this.signs = signs; + } +} diff --git a/EssentialsSigns/src/net/ess3/signs/SignsConfigHolder.java b/EssentialsSigns/src/net/ess3/signs/SignsConfigHolder.java new file mode 100644 index 000000000..395d0194a --- /dev/null +++ b/EssentialsSigns/src/net/ess3/signs/SignsConfigHolder.java @@ -0,0 +1,85 @@ +package net.ess3.signs; + +import net.ess3.api.IEssentials; +import net.ess3.storage.AsyncStorageObjectHolder; +import java.io.File; +import java.io.IOException; +import java.util.*; +import org.bukkit.plugin.Plugin; + + +public class SignsConfigHolder extends AsyncStorageObjectHolder +{ + private final transient Plugin plugin; + private Set enabledSigns = new HashSet(); + private boolean signsEnabled = false; + + public SignsConfigHolder(final IEssentials ess, final Plugin plugin) + { + super(ess, SignsConfig.class); + this.plugin = plugin; + onReload(); + acquireReadLock(); + try + { + final Map signs = getData().getSigns(); + for (Map.Entry entry : signs.entrySet()) + { + if (entry.getKey().trim().toUpperCase(Locale.ENGLISH).equals("COLOR") || entry.getKey().trim().toUpperCase(Locale.ENGLISH).equals("COLOUR")) + { + signsEnabled = true; + continue; + } + final Signs sign = Signs.valueOf(entry.getKey().toUpperCase(Locale.ENGLISH)); + if (sign != null && entry.getValue()) + { + enabledSigns.add(sign.getSign()); + } + } + } + finally + { + unlock(); + } + acquireWriteLock(); + try + { + final Map signs = new HashMap(); + for (Signs sign : Signs.values()) + { + signs.put(sign.toString(), enabledSigns.contains(sign.getSign())); + } + getData().setSigns(signs); + } + finally + { + unlock(); + } + } + + @Override + public File getStorageFile() throws IOException + { + return new File(plugin.getDataFolder(), "config.yml"); + } + + public Set getEnabledSigns() + { + return enabledSigns; + } + + public boolean areSignsDisabled() + { + return !signsEnabled; + } + + @Override + public void finishRead() + { + } + + @Override + public void finishWrite() + { + } +} diff --git a/EssentialsSigns/src/net/ess3/signs/SignsPermissions.java b/EssentialsSigns/src/net/ess3/signs/SignsPermissions.java new file mode 100644 index 000000000..21c736b7d --- /dev/null +++ b/EssentialsSigns/src/net/ess3/signs/SignsPermissions.java @@ -0,0 +1,51 @@ +package net.ess3.signs; + +import net.ess3.api.IPermission; +import net.ess3.permissions.BasePermission; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + + +public class SignsPermissions +{ + public static final IPermission COLOR = new BasePermission("essentials.signs.", "color"); + public static final IPermission PROTECTION_OVERRIDE = new BasePermission("essentials.signs.protection.", "override"); + public static final IPermission TRADE_OVERRIDE = new BasePermission("essentials.signs.trade.", "override"); + private static Map createpermissions = new HashMap(); + + public static IPermission getCreatePermission(final String signName) + { + IPermission perm = createpermissions.get(signName); + if (perm == null) + { + perm = new BasePermission("essentials.signs.create.", signName.toLowerCase(Locale.ENGLISH)); + createpermissions.put(signName, perm); + } + return perm; + } + private static Map usepermissions = new HashMap(); + + public static IPermission getUsePermission(final String signName) + { + IPermission perm = usepermissions.get(signName); + if (perm == null) + { + perm = new BasePermission("essentials.signs.use.", signName.toLowerCase(Locale.ENGLISH)); + usepermissions.put(signName, perm); + } + return perm; + } + private static Map breakpermissions = new HashMap(); + + public static IPermission getBreakPermission(final String signName) + { + IPermission perm = breakpermissions.get(signName); + if (perm == null) + { + perm = new BasePermission("essentials.signs.break.", signName.toLowerCase(Locale.ENGLISH)); + breakpermissions.put(signName, perm); + } + return perm; + } +} diff --git a/EssentialsSigns/src/plugin.yml b/EssentialsSigns/src/plugin.yml index ef71c54ef..a58338c86 100644 --- a/EssentialsSigns/src/plugin.yml +++ b/EssentialsSigns/src/plugin.yml @@ -1,6 +1,6 @@ # This determines the command prefix when there are conflicts (/name:home, /name:help, etc.) name: EssentialsSigns -main: com.earth2me.essentials.signs.EssentialsSignsPlugin +main: net.ess3.signs.EssentialsSignsPlugin # Note to developers: This next line cannot change, or the automatic versioning system will break. version: ${build.number} website: http://tiny.cc/EssentialsWiki diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/AbstractWorkListener.java b/EssentialsUpdate/src/com/earth2me/essentials/update/AbstractWorkListener.java deleted file mode 100644 index d2cbb8a64..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/AbstractWorkListener.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.earth2me.essentials.update; - -import org.bukkit.plugin.Plugin; - - -public abstract class AbstractWorkListener -{ - public AbstractWorkListener(final Plugin plugin, final VersionInfo newVersionInfo) - { - this.plugin = plugin; - this.newVersionInfo = newVersionInfo; - } - private final transient Plugin plugin; - private final transient VersionInfo newVersionInfo; - - public final void onWorkAbort() - { - onWorkAbort(null); - } - - public abstract void onWorkAbort(String message); - - public final void onWorkDone() - { - onWorkDone(null); - } - - public abstract void onWorkDone(String message); - - public VersionInfo getNewVersionInfo() - { - return newVersionInfo; - } - - public Plugin getPlugin() - { - return plugin; - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/EssentialsHelp.java b/EssentialsUpdate/src/com/earth2me/essentials/update/EssentialsHelp.java deleted file mode 100644 index 7dd46451a..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/EssentialsHelp.java +++ /dev/null @@ -1,171 +0,0 @@ -package com.earth2me.essentials.update; - -import com.earth2me.essentials.update.chat.*; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import org.bukkit.Server; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerChatEvent; -import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginManager; - - -public class EssentialsHelp implements Listener -{ - private transient Player chatUser; - private final transient Server server; - private final transient Plugin plugin; - private transient IrcBot ircBot; - private final transient Map commands = new HashMap(); - - public EssentialsHelp(final Plugin plugin) - { - super(); - this.plugin = plugin; - this.server = plugin.getServer(); - commands.put("!help", new HelpCommand()); - commands.put("!list", new ListCommand()); - commands.put("!startup", new StartupCommand(plugin)); - commands.put("!errors", new ErrorsCommand(plugin)); - commands.put("!config", new ConfigCommand(plugin)); - } - - public void registerEvents() - { - final PluginManager pluginManager = server.getPluginManager(); - pluginManager.registerEvents(this, plugin); - } - - public void onCommand(final CommandSender sender) - { - if (sender instanceof Player && sender.hasPermission("essentials.helpchat")) - { - if (chatUser == null) - { - chatUser = (Player)sender; - ircBot = null; - sender.sendMessage("You will be connected to the Essentials Help Chat."); - sender.sendMessage("All your chat messages will be forwarded to the channel. You can't chat with other players on your server while in help chat, but you can use commands."); - sender.sendMessage("Please be patient, if noone is available, check back later."); - sender.sendMessage("Type !help to get a list of all commands."); - sender.sendMessage("Type !quit to leave the channel."); - sender.sendMessage("Do you want to join the channel now? (yes/no)"); - } - if (!chatUser.equals(sender)) - { - sender.sendMessage("The player " + chatUser.getDisplayName() + " is already using the essentialshelp."); - } - } - else - { - sender.sendMessage("Please run the command as op from in game."); - } - } - - public void onDisable() - { - closeConnection(); - } - - private boolean sendChatMessage(final Player player, final String message) - { - final String messageCleaned = message.trim(); - if (messageCleaned.isEmpty()) - { - return false; - } - if (ircBot == null) - { - return handleAnswer(messageCleaned, player); - } - else - { - if (ircBot.isKicked()) - { - closeConnection(); - return false; - } - final String lowMessage = messageCleaned.toLowerCase(Locale.ENGLISH); - if (lowMessage.startsWith("!quit")) - { - closeConnection(); - player.sendMessage("Connection closed."); - return true; - } - if (!ircBot.isConnected() || ircBot.getChannels().length == 0) - { - return false; - } - if (handleCommands(lowMessage, player)) - { - return true; - } - ircBot.sendMessage(messageCleaned); - chatUser.sendMessage("§6" + ircBot.getNick() + ": §7" + messageCleaned); - return true; - } - } - - private void closeConnection() - { - chatUser = null; - if (ircBot != null) - { - ircBot.quit(); - ircBot = null; - } - } - - private boolean handleAnswer(final String message, final Player player) - { - if (message.equalsIgnoreCase("yes")) - { - player.sendMessage("Connecting..."); - connectToIRC(player); - return true; - } - if (message.equalsIgnoreCase("no") || message.equalsIgnoreCase("!quit")) - { - chatUser = null; - return true; - } - return false; - } - - private boolean handleCommands(final String lowMessage, final Player player) - { - final String[] parts = lowMessage.split(" "); - if (commands.containsKey(parts[0])) - { - commands.get(parts[0]).run(ircBot, player); - return true; - } - return false; - } - - private void connectToIRC(final Player player) - { - ircBot = new IrcBot(player, "Ess_" + player.getName(), UsernameUtil.createUsername(player)); - } - - @EventHandler - public void onPlayerChat(final PlayerChatEvent event) - { - if (event.getPlayer() == chatUser) - { - final boolean success = sendChatMessage(event.getPlayer(), event.getMessage()); - event.setCancelled(success); - } - } - - @EventHandler - public void onPlayerQuit(final PlayerQuitEvent event) - { - closeConnection(); - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/EssentialsUpdate.java b/EssentialsUpdate/src/com/earth2me/essentials/update/EssentialsUpdate.java deleted file mode 100644 index 0a3143a72..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/EssentialsUpdate.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.earth2me.essentials.update; - -import java.util.logging.Level; -import org.bukkit.Bukkit; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.plugin.java.JavaPlugin; - - -public class EssentialsUpdate extends JavaPlugin -{ - private transient EssentialsHelp essentialsHelp; - private transient UpdateProcess updateProcess; - - @Override - public void onEnable() - { - if (!getDataFolder().exists() && !getDataFolder().mkdirs()) - { - Bukkit.getLogger().log(Level.SEVERE, "Could not create data folder: {0}", getDataFolder().getPath()); - } - essentialsHelp = new EssentialsHelp(this); - essentialsHelp.registerEvents(); - - final UpdateCheck updateCheck = new UpdateCheck(this); - updateCheck.checkForUpdates(); - updateProcess = new UpdateProcess(this, updateCheck); - updateProcess.registerEvents(); - - if (updateCheck.isEssentialsInstalled()) - { - updateCheck.scheduleUpdateTask(); - } - else - { - Bukkit.getLogger().info("Essentials is ready for installation. Join the game and follow the instructions."); - } - } - - @Override - public void onDisable() - { - essentialsHelp.onDisable(); - } - - @Override - public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) - { - if (command.getName().equalsIgnoreCase("essentialsupdate")) - { - updateProcess.onCommand(sender); - } - if (command.getName().equalsIgnoreCase("essentialshelp")) - { - essentialsHelp.onCommand(sender); - } - return true; - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/GetFile.java b/EssentialsUpdate/src/com/earth2me/essentials/update/GetFile.java deleted file mode 100644 index 06b414e93..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/GetFile.java +++ /dev/null @@ -1,113 +0,0 @@ -package com.earth2me.essentials.update; - -import java.io.*; -import java.math.BigInteger; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLConnection; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.logging.Level; -import org.bukkit.Bukkit; - - -public class GetFile -{ - private transient URLConnection connection; - private transient MessageDigest digest; - - public GetFile(final String urlString) throws MalformedURLException, IOException - { - this(new URL(urlString)); - } - - public GetFile(final URL url) throws IOException - { - this.connection = url.openConnection(); - this.connection.setConnectTimeout(1000); - this.connection.setReadTimeout(5000); - this.connection.setUseCaches(false); - this.connection.connect(); - final int respCode = ((HttpURLConnection)this.connection).getResponseCode(); - if (respCode >= 300 && respCode < 400 && this.connection.getHeaderField("Location") != null) - { - connection.getInputStream().close(); - final URL redirect = new URL(this.connection.getHeaderField("Location")); - this.connection = redirect.openConnection(); - this.connection.setConnectTimeout(1000); - this.connection.setReadTimeout(5000); - this.connection.setUseCaches(false); - this.connection.connect(); - } - } - - public void saveTo(final File file) throws IOException - { - try - { - saveTo(file, null); - } - catch (NoSuchAlgorithmException ex) - { - throw new RuntimeException(ex); - } - } - - public void saveTo(final File file, final String key) throws IOException, NoSuchAlgorithmException - { - if (key != null) - { - digest = MessageDigest.getInstance("SHA256"); - } - final byte[] buffer = new byte[1024 * 8]; - boolean brokenFile = false; - final BufferedInputStream input = new BufferedInputStream(connection.getInputStream()); - try - { - final BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(file)); - try - { - int length; - do - { - length = input.read(buffer); - if (length >= 0) - { - if (key != null) - { - digest.update(buffer, 0, length); - } - output.write(buffer, 0, length); - } - } - while (length >= 0); - if (key != null) - { - final byte[] checksum = digest.digest(); - final String checksumString = new BigInteger(checksum).toString(36); - if (!checksumString.equals(key)) - { - brokenFile = true; - } - } - } - finally - { - output.close(); - } - if (brokenFile && !file.delete()) - { - Bukkit.getLogger().log(Level.SEVERE, "Could not delete file {0}", file.getPath()); - } - } - finally - { - input.close(); - } - if (brokenFile) - { - throw new IOException("Checksum check failed."); - } - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/ModuleInfo.java b/EssentialsUpdate/src/com/earth2me/essentials/update/ModuleInfo.java deleted file mode 100644 index 722fca3e1..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/ModuleInfo.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.earth2me.essentials.update; - -import java.net.MalformedURLException; -import java.net.URL; -import org.bukkit.configuration.Configuration; - - -public class ModuleInfo -{ - private final transient String url; - private final transient String version; - private final transient String hash; - - public ModuleInfo(final Configuration updateConfig, final String path) - { - url = updateConfig.getString(path + ".url", null); - version = updateConfig.getString(path + ".version", null); - hash = updateConfig.getString(path + ".hash", null); - } - - public URL getUrl() throws MalformedURLException - { - return new URL(url); - } - - public String getVersion() - { - return version; - } - - public String getHash() - { - return hash; - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/PastieUpload.java b/EssentialsUpdate/src/com/earth2me/essentials/update/PastieUpload.java deleted file mode 100644 index 489c2163d..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/PastieUpload.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.earth2me.essentials.update; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.HashMap; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - - -public class PastieUpload -{ - private final transient PostToUrl connection; - - public PastieUpload() throws MalformedURLException - { - connection = new PostToUrl(new URL("http://pastie.org/pastes")); - } - - public String send(final String data) throws IOException - { - final Map map = new HashMap(); - map.put("paste[parser_id]", "19"); - map.put("paste[authorization]", "burger"); - map.put("paste[body]", data); - map.put("paste[restricted]", "1"); - final String html = connection.send(map); - final Matcher matcher = Pattern.compile("(?s).*\\?key=([a-z0-9]+).*").matcher(html); - if (matcher.matches()) - { - final String key = matcher.group(1); - return "http://pastie.org/private/" + key; - } - else - { - throw new IOException("Failed to upload to pastie.org"); - } - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/PostToUrl.java b/EssentialsUpdate/src/com/earth2me/essentials/update/PostToUrl.java deleted file mode 100644 index c8978961b..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/PostToUrl.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.earth2me.essentials.update; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.math.BigInteger; -import java.net.URL; -import java.net.URLConnection; -import java.nio.charset.Charset; -import java.util.Map; -import java.util.Random; - - -public class PostToUrl -{ - private final transient URL url; - private final transient String boundary; - private final transient Random random = new Random(); - private final static String CRLF = "\r\n"; - private final static Charset UTF8 = Charset.forName("utf-8"); - - public PostToUrl(final URL url) - { - this.url = url; - final byte[] bytes = new byte[32]; - random.nextBytes(bytes); - this.boundary = "----------" + new BigInteger(bytes).toString(Character.MAX_RADIX) + "_$"; - } - - public String send(final Map data) throws IOException - { - final URLConnection connection = url.openConnection(); - connection.setRequestProperty("content-type", "multipart/form-data; boundary=" + boundary); - final StringBuilder dataBuilder = new StringBuilder(); - for (Map.Entry entry : data.entrySet()) - { - if (entry.getValue() instanceof String) - { - dataBuilder.append("--").append(boundary).append(CRLF); - dataBuilder.append("Content-Disposition: form-data; name=\"").append(entry.getKey()).append('"').append(CRLF); - dataBuilder.append(CRLF); - dataBuilder.append(entry.getValue()).append(CRLF); - } - // TODO: Add support for file upload - } - dataBuilder.append("--").append(boundary).append("--").append(CRLF); - dataBuilder.append(CRLF); - connection.setDoOutput(true); - final byte[] message = dataBuilder.toString().getBytes(UTF8); - connection.setRequestProperty("content-length", Integer.toString(message.length)); - connection.connect(); - final OutputStream stream = connection.getOutputStream(); - stream.write(message); - stream.close(); - final BufferedReader page = new BufferedReader(new InputStreamReader(connection.getInputStream(), UTF8)); - final StringBuilder input = new StringBuilder(); - String line; - while ((line = page.readLine()) != null) - { - input.append(line).append("\n"); - } - page.close(); - return input.toString(); - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/UpdateCheck.java b/EssentialsUpdate/src/com/earth2me/essentials/update/UpdateCheck.java deleted file mode 100644 index 1f69ebde1..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/UpdateCheck.java +++ /dev/null @@ -1,202 +0,0 @@ -package com.earth2me.essentials.update; - -import java.io.File; -import java.util.Map; -import java.util.Map.Entry; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import org.bukkit.Bukkit; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginManager; - - -public class UpdateCheck -{ - private transient CheckResult result = CheckResult.UNKNOWN; - private transient Version currentVersion; - private transient Version newVersion = null; - private transient int bukkitResult = 0; - private transient UpdateFile updateFile; - private final static int CHECK_INTERVAL = 20 * 60 * 60 * 6; - private final transient Plugin plugin; - private transient boolean essentialsInstalled; - - public UpdateCheck(final Plugin plugin) - { - this.plugin = plugin; - updateFile = new UpdateFile(plugin); - checkForEssentials(); - } - - private void checkForEssentials() - { - final PluginManager pluginManager = plugin.getServer().getPluginManager(); - final Plugin essentials = pluginManager.getPlugin("Essentials-3"); - essentialsInstalled = essentials != null; - if (essentialsInstalled) - { - currentVersion = new Version(essentials.getDescription().getVersion()); - } - else - { - if (new File(plugin.getDataFolder().getParentFile(), "Essentials.jar").exists()) - { - Bukkit.getLogger().severe("Essentials.jar found, but not recognized by Bukkit. Broken download?"); - } - } - } - - public void scheduleUpdateTask() - { - plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable() - { - @Override - public void run() - { - updateFile = new UpdateFile(plugin); - checkForUpdates(); - } - }, CHECK_INTERVAL, CHECK_INTERVAL); - } - - public boolean isEssentialsInstalled() - { - return essentialsInstalled; - } - - public CheckResult getResult() - { - return result; - } - - public int getNewBukkitVersion() - { - return bukkitResult; - } - - public VersionInfo getNewVersionInfo() - { - return updateFile.getVersions().get(newVersion); - } - - - public enum CheckResult - { - NEW_ESS, NEW_ESS_BUKKIT, NEW_BUKKIT, OK, UNKNOWN - } - - public void checkForUpdates() - { - if (currentVersion == null) - { - return; - } - final Map versions = updateFile.getVersions(); - final int bukkitVersion = getBukkitVersion(); - Version higher = null; - Version found = null; - Version lower = null; - int bukkitHigher = 0; - int bukkitLower = 0; - for (Entry entry : versions.entrySet()) - { - final int minBukkit = entry.getValue().getMinBukkit(); - final int maxBukkit = entry.getValue().getMaxBukkit(); - if (minBukkit == 0 || maxBukkit == 0) - { - continue; - } - if (bukkitVersion <= maxBukkit) - { - if (bukkitVersion < minBukkit) - { - if (higher == null || higher.compareTo(entry.getKey()) < 0) - { - - higher = entry.getKey(); - bukkitHigher = minBukkit; - } - } - else - { - if (found == null || found.compareTo(entry.getKey()) < 0) - { - found = entry.getKey(); - } - } - } - else - { - if (lower == null || lower.compareTo(entry.getKey()) < 0) - { - lower = entry.getKey(); - bukkitLower = minBukkit; - } - } - } - if (found != null) - { - if (found.compareTo(currentVersion) > 0) - { - result = CheckResult.NEW_ESS; - newVersion = found; - } - else - { - result = CheckResult.OK; - } - } - else if (higher != null) - { - if (higher.compareTo(currentVersion) > 0) - { - newVersion = higher; - result = CheckResult.NEW_ESS_BUKKIT; - bukkitResult = bukkitHigher; - } - else if (higher.compareTo(currentVersion) < 0) - { - result = CheckResult.UNKNOWN; - } - else - { - result = CheckResult.NEW_BUKKIT; - bukkitResult = bukkitHigher; - } - } - else if (lower != null) - { - if (lower.compareTo(currentVersion) > 0) - { - result = CheckResult.NEW_ESS_BUKKIT; - newVersion = lower; - bukkitResult = bukkitLower; - } - else if (lower.compareTo(currentVersion) < 0) - { - result = CheckResult.UNKNOWN; - } - else - { - result = CheckResult.NEW_BUKKIT; - bukkitResult = bukkitLower; - } - } - - } - - private int getBukkitVersion() - { - final Matcher versionMatch = Pattern.compile("git-Bukkit-(?:(?:[0-9]+)\\.)+[0-9]+-R[\\.0-9]+-(?:[0-9]+-g[0-9a-f]+-)?b([0-9]+)jnks.*").matcher(plugin.getServer().getVersion()); - if (versionMatch.matches()) - { - return Integer.parseInt(versionMatch.group(1)); - } - throw new NumberFormatException("Bukkit Version changed!"); - } - - public Version getNewVersion() - { - return newVersion; - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/UpdateFile.java b/EssentialsUpdate/src/com/earth2me/essentials/update/UpdateFile.java deleted file mode 100644 index 0659f7dbb..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/UpdateFile.java +++ /dev/null @@ -1,204 +0,0 @@ -package com.earth2me.essentials.update; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.math.BigInteger; -import java.security.KeyFactory; -import java.security.PublicKey; -import java.security.Signature; -import java.security.spec.X509EncodedKeySpec; -import java.util.Collections; -import java.util.Map; -import java.util.TreeMap; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.bukkit.Bukkit; -import org.bukkit.configuration.InvalidConfigurationException; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.plugin.Plugin; - - -public class UpdateFile -{ - private final static Logger LOGGER = Bukkit.getLogger(); - private final static String UPDATE_URL = "http://goo.gl/67jev"; - private final static BigInteger PUBLIC_KEY = new BigInteger("5ha6a2d4qdy17ttkg8evh74sl5a87djojwenu12k1lvy8ui6003e6l06rntczpoh99mhc3txj8mqlxw111oyy9yl7s7qpyluyzix3j1odxrxx4u52gxvyu6qiteapczkzvi7rxgeqsozz7b19rdx73a7quo9ybwpz1cr82r7x5k0pg2a73pjjsv2j1awr13azo7klrcxp9y5xxwf5qv1s3tw4zqftli18u0ek5qkbzfbgk1v5n2f11pkwwk6p0mibrn26wnjbv11vyiqgu95o7busmt6vf5q7grpcenl637w83mbin56s3asj1131b2mscj9xep3cbj7la9tgsxl5bj87vzy8sk2d34kzwqdqgh9nry43nqqus12l1stmiv184r8r3jcy8w43e8h1u1mzklldb5eytkuhayqik8l3ns04hwt8sgacvw534be8sx26qrn5s1", 36); - private final transient File file; - private final transient Plugin plugin; - private final transient TreeMap versions = new TreeMap(); - - public UpdateFile(final Plugin plugin) - { - this.plugin = plugin; - final long lastUpdate = Long.parseLong(plugin.getConfig().getString("lastupdate", "0")); - file = new File(plugin.getDataFolder(), "update.yml"); - if (lastUpdate < System.currentTimeMillis() - 1000 * 60 * 60 * 6 || !file.exists()) - { - if (file.exists() && !file.delete()) - { - LOGGER.log(Level.SEVERE, "Could not delete file update.yml!"); - return; - } - if (!downloadFile() || !checkFile()) - { - LOGGER.log(Level.SEVERE, "Could not download and verify file update.yml!"); - return; - } - } - try - { - readVersions(); - } - catch (Exception ex) - { - LOGGER.log(Level.SEVERE, "Could not load update.yml!"); - return; - } - } - - private boolean downloadFile() - { - GetFile getFile; - try - { - getFile = new GetFile(UPDATE_URL); - getFile.saveTo(file); - plugin.getConfig().set("lastupdate", System.currentTimeMillis()); - plugin.getConfig().save(new File(plugin.getDataFolder(), "config.yml")); - return true; - } - catch (IOException ex) - { - LOGGER.log(Level.SEVERE, "Error while downloading update.yml", ex); - return false; - } - } - - private boolean checkFile() - { - BufferedInputStream bis = null; - try - { - bis = new BufferedInputStream(new FileInputStream(file)); - if (bis.read() != '#') - { - throw new IOException("File has to start with #"); - } - final StringBuilder length = new StringBuilder(); - final StringBuilder signature = new StringBuilder(); - boolean isSignature = false; - do - { - final int cur = bis.read(); - if (cur == -1) - { - break; - } - if (cur == ':') - { - isSignature = true; - } - else if (cur == '\n') - { - break; - } - else if ((cur >= '0' && cur <= '9') - || (cur >= 'a' && cur <= 'z')) - { - if (isSignature) - { - signature.append((char)cur); - } - else - { - length.append((char)cur); - } - } - else - { - throw new IOException("Illegal character in signature!"); - } - } - while (true); - if (length.length() == 0 || signature.length() == 0) - { - throw new IOException("Broken signature!"); - } - final int sigLength = new BigInteger(length.toString(), 36).intValue(); - if (sigLength < 0 || sigLength > 2048) - { - throw new IOException("Invalid signature length!"); - } - final byte[] sigBytes = new BigInteger(signature.toString(), 36).toByteArray(); - if (sigLength < sigBytes.length) - { - throw new IOException("Length is less then available bytes."); - } - byte[] realBytes; - if (sigLength == sigBytes.length) - { - realBytes = sigBytes; - } - else - { - realBytes = new byte[sigLength]; - System.arraycopy(sigBytes, 0, realBytes, sigLength - sigBytes.length, sigBytes.length); - } - final X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(PUBLIC_KEY.toByteArray()); - final KeyFactory keyFactory = KeyFactory.getInstance("RSA"); - final PublicKey pubKey = keyFactory.generatePublic(pubKeySpec); - final Signature rsa = Signature.getInstance("SHA256withRSA"); - rsa.initVerify(pubKey); - final byte[] buffer = new byte[2048]; - int readLength; - do - { - readLength = bis.read(buffer); - if (readLength >= 0) - { - rsa.update(buffer, 0, readLength); - } - } - while (readLength >= 0); - return rsa.verify(realBytes); - } - catch (Exception ex) - { - LOGGER.log(Level.SEVERE, ex.getMessage(), ex); - } - finally - { - try - { - if (bis != null) - { - bis.close(); - } - } - catch (IOException ex) - { - LOGGER.log(Level.SEVERE, ex.getMessage(), ex); - } - } - return false; - } - - private void readVersions() throws FileNotFoundException, InvalidConfigurationException, IOException - { - final YamlConfiguration updateConfig = new YamlConfiguration(); - updateConfig.load(file); - versions.clear(); - for (String versionString : updateConfig.getKeys(false)) - { - versions.put(new Version(versionString), new VersionInfo(updateConfig, versionString)); - } - } - - public Map getVersions() - { - return Collections.unmodifiableMap(versions.descendingMap()); - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/UpdateProcess.java b/EssentialsUpdate/src/com/earth2me/essentials/update/UpdateProcess.java deleted file mode 100644 index 3a8139840..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/UpdateProcess.java +++ /dev/null @@ -1,199 +0,0 @@ -package com.earth2me.essentials.update; - -import com.earth2me.essentials.update.states.InstallationFinishedEvent; -import com.earth2me.essentials.update.states.StateMachine; -import com.earth2me.essentials.update.tasks.SelfUpdate; -import java.util.logging.Level; -import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; -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.PlayerChatEvent; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.plugin.Plugin; - -// TODO: This whole thing should make use of the conversations api -public class UpdateProcess implements Listener -{ - private transient Player currentPlayer; - private final transient Plugin plugin; - private final transient UpdateCheck updateCheck; - private transient StateMachine stateMachine; - - public UpdateProcess(final Plugin plugin, final UpdateCheck updateCheck) - { - super(); - this.plugin = plugin; - this.updateCheck = updateCheck; - } - - public void registerEvents() - { - plugin.getServer().getPluginManager().registerEvents(this, plugin); - } - - public boolean selfUpdate() - { - if (new Version(plugin.getDescription().getVersion()).compareTo(updateCheck.getNewVersion()) < 0) - { - if (currentPlayer != null) - { - currentPlayer.sendMessage("A newer version of EssentialsUpdate is found. Downloading new file and reloading server."); - } - Bukkit.getLogger().log(Level.INFO, "A newer version of EssentialsUpdate is found. Downloading new file and reloading server."); - new SelfUpdate(new AbstractWorkListener(plugin, updateCheck.getNewVersionInfo()) - { - @Override - public void onWorkAbort(final String message) - { - if (message != null && !message.isEmpty() - && UpdateProcess.this.currentPlayer != null - && UpdateProcess.this.currentPlayer.isOnline()) - { - UpdateProcess.this.currentPlayer.sendMessage(message); - } - if (message != null && !message.isEmpty()) - { - Bukkit.getLogger().log(Level.SEVERE, message); - } - UpdateProcess.this.currentPlayer = null; - } - - @Override - public void onWorkDone(final String message) - { - if (message != null && !message.isEmpty() - && UpdateProcess.this.currentPlayer != null - && UpdateProcess.this.currentPlayer.isOnline()) - { - UpdateProcess.this.currentPlayer.sendMessage(message); - } - if (message != null && !message.isEmpty()) - { - Bukkit.getLogger().log(Level.INFO, message); - } - UpdateProcess.this.currentPlayer = null; - } - }).start(); - return true; - } - if (updateCheck.getResult() == UpdateCheck.CheckResult.NEW_ESS_BUKKIT) - { - final String message = "Please update bukkit to version " + updateCheck.getNewBukkitVersion() + " before updating Essentials."; - if (currentPlayer != null) - { - currentPlayer.sendMessage(message); - } - Bukkit.getLogger().log(Level.INFO, message); - currentPlayer = null; - return true; - } - return false; - } - - @EventHandler - public void onInstallationFinished(final InstallationFinishedEvent event) - { - UpdateProcess.this.currentPlayer = null; - } - - @EventHandler(priority = EventPriority.LOWEST) - public void onPlayerChat(final PlayerChatEvent event) - { - if (event.getPlayer() == currentPlayer) - { - final StateMachine.MachineResult result = stateMachine.reactOnMessage(event.getMessage()); - if (result == StateMachine.MachineResult.ABORT) - { - currentPlayer.sendMessage("Installation wizard aborted. You can restart it using /essentialsupdate."); - currentPlayer = null; - } - if (result == StateMachine.MachineResult.DONE) - { - startWork(); - } - event.setCancelled(true); - return; - } - } - - @EventHandler - public void onPlayerJoin(final PlayerJoinEvent event) - { - final Player player = event.getPlayer(); - if (currentPlayer != null && currentPlayer.getName().equals(player.getName())) - { - currentPlayer = player; - player.sendMessage("You quit the game, while the installation wizard was running."); - player.sendMessage("The installation wizard will now resume."); - player.sendMessage("You can exit the wizard by typing quit into the chat."); - stateMachine.resumeInstallation(player); - } - if (player.hasPermission("essentials.update") && !updateCheck.isEssentialsInstalled()) - { - player.sendMessage("Hello " + player.getDisplayName()); - player.sendMessage("Please type /essentialsupdate into the chat to start the installation of Essentials."); - } - if (player.hasPermission("essentials.update")) - { - final UpdateCheck.CheckResult result = updateCheck.getResult(); - switch (result) - { - case NEW_ESS: - player.sendMessage("The new version " + updateCheck.getNewVersion().toString() + " for Essentials is available. Please type /essentialsupdate to update."); - break; - case NEW_BUKKIT: - player.sendMessage("Your bukkit version is not the recommended build for Essentials, please update to version " + updateCheck.getNewBukkitVersion() + "."); - break; - case NEW_ESS_BUKKIT: - player.sendMessage("There is a new version " + updateCheck.getNewVersion().toString() + " of Essentials for Bukkit " + updateCheck.getNewBukkitVersion()); - break; - default: - } - } - } - - public void onCommand(final CommandSender sender) - { - if (sender instanceof Player && sender.hasPermission("essentials.update")) - { - if (currentPlayer == null) - { - currentPlayer = (Player)sender; - if (selfUpdate()) - { - return; - } - stateMachine = new StateMachine(plugin, currentPlayer, updateCheck); - final StateMachine.MachineResult result = stateMachine.askQuestion(); - if (result == StateMachine.MachineResult.DONE) - { - startWork(); - } - } - if (!currentPlayer.equals(sender)) - { - sender.sendMessage("The player " + currentPlayer.getDisplayName() + " is already using the wizard."); - } - } - else - { - sender.sendMessage("Please run the command as op from in game."); - } - } - - private void startWork() - { - currentPlayer.sendMessage("Installation wizard done. Starting installation."); - Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() - { - @Override - public void run() - { - stateMachine.startWork(); - } - }); - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/Version.java b/EssentialsUpdate/src/com/earth2me/essentials/update/Version.java deleted file mode 100644 index a82f49abf..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/Version.java +++ /dev/null @@ -1,173 +0,0 @@ -package com.earth2me.essentials.update; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - - -public class Version implements Comparable -{ - public enum Type - { - STABLE, PREVIEW, DEVELOPER - } - - public int getMajor() - { - return major; - } - - public int getMinor() - { - return minor; - } - - public int getBuild() - { - return build; - } - - public Type getType() - { - return type; - } - private final transient int major; - private final transient int minor; - private final transient int build; - private final transient Type type; - - public Version(final String versionString) - { - final Matcher matcher = Pattern.compile("(Pre|Dev)?([0-9]+)[_\\.]([0-9]+)[_\\.]([0-9]+).*").matcher(versionString); - if (!matcher.matches() || matcher.groupCount() < 4) - { - type = Type.DEVELOPER; - major = 99; - minor = build = 0; - return; - } - if (versionString.startsWith("Pre")) - { - type = Type.PREVIEW; - } - else if (versionString.startsWith("Dev")) - { - type = Type.DEVELOPER; - } - else - { - type = Type.STABLE; - } - major = Integer.parseInt(matcher.group(2)); - minor = Integer.parseInt(matcher.group(3)); - build = Integer.parseInt(matcher.group(4)); - } - - @Override - public int compareTo(final Version other) - { - int ret = 0; - if (other.getType() == Type.DEVELOPER && getType() != Type.DEVELOPER) - { - ret = -1; - } - else if (getType() == Type.DEVELOPER && other.getType() != Type.DEVELOPER) - { - ret = 1; - } - else if (other.getMajor() > getMajor()) - { - ret = -1; - } - else if (getMajor() > other.getMajor()) - { - ret = 1; - } - else if (other.getMinor() > getMinor()) - { - ret = -1; - } - else if (getMinor() > other.getMinor()) - { - ret = 1; - } - else if (other.getBuild() > getBuild()) - { - ret = -1; - } - else if (getBuild() > other.getBuild()) - { - ret = 1; - } - else if (other.getType() == Type.STABLE && getType() == Type.PREVIEW) - { - ret = -1; - } - else if (getType() == Type.STABLE && other.getType() == Type.PREVIEW) - { - ret = 1; - } - return ret; - } - - @Override - public boolean equals(final Object obj) - { - if (obj == null) - { - return false; - } - if (getClass() != obj.getClass()) - { - return false; - } - final Version other = (Version)obj; - if (this.major != other.major) - { - return false; - } - if (this.minor != other.minor) - { - return false; - } - if (this.build != other.build) - { - return false; - } - if (this.type != other.type) - { - return false; - } - return true; - } - - @Override - public int hashCode() - { - int hash = 5; - hash = 71 * hash + this.major; - hash = 71 * hash + this.minor; - hash = 71 * hash + this.build; - hash = 71 * hash + (this.type == null ? 0 : this.type.hashCode()); - return hash; - } - - @Override - public String toString() - { - final StringBuilder builder = new StringBuilder(); - if (type == Type.DEVELOPER) - { - builder.append("Dev"); - } - if (type == Type.PREVIEW) - { - builder.append("Pre"); - } - builder.append(major); - builder.append('.'); - builder.append(minor); - builder.append('.'); - builder.append(build); - return builder.toString(); - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/VersionInfo.java b/EssentialsUpdate/src/com/earth2me/essentials/update/VersionInfo.java deleted file mode 100644 index c06aa2e64..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/VersionInfo.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.earth2me.essentials.update; - -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.bukkit.configuration.Configuration; - - -public class VersionInfo -{ - private final transient List changelog; - private final transient int minBukkit; - private final transient int maxBukkit; - private final transient Map modules; - - public VersionInfo(final Configuration updateConfig, final String path) - { - changelog = updateConfig.getStringList(path + ".changelog"); - minBukkit = updateConfig.getInt(path + ".min-bukkit", 0); - maxBukkit = updateConfig.getInt(path + ".max-bukkit", 0); - modules = new HashMap(); - final String modulesPath = path + ".modules"; - for (String module : updateConfig.getKeys(false)) - { - modules.put(module, new ModuleInfo(updateConfig, modulesPath + module)); - } - } - - public List getChangelog() - { - return Collections.unmodifiableList(changelog); - } - - public int getMinBukkit() - { - return minBukkit; - } - - public int getMaxBukkit() - { - return maxBukkit; - } - - public Map getModules() - { - return Collections.unmodifiableMap(modules); - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/chat/AbstractFileCommand.java b/EssentialsUpdate/src/com/earth2me/essentials/update/chat/AbstractFileCommand.java deleted file mode 100644 index 7c99d28f6..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/chat/AbstractFileCommand.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.earth2me.essentials.update.chat; - -import com.earth2me.essentials.update.PastieUpload; -import java.io.*; -import java.nio.charset.Charset; -import org.bukkit.plugin.Plugin; - - -public abstract class AbstractFileCommand implements Command -{ - private final transient Plugin plugin; - private final static Charset UTF8 = Charset.forName("utf-8"); - - public AbstractFileCommand(final Plugin plugin) - { - this.plugin = plugin; - } - - protected BufferedReader getServerLogReader() throws IOException - { - final File bukkitFolder = plugin.getDataFolder().getAbsoluteFile().getParentFile().getParentFile(); - if (bukkitFolder == null || !bukkitFolder.exists()) - { - throw new IOException("Bukkit folder not found."); - } - final File logFile = new File(bukkitFolder, "server.log"); - if (!logFile.exists()) - { - throw new IOException("Server log not found."); - } - final FileInputStream fis = new FileInputStream(logFile); - try - { - if (logFile.length() > 1000000) - { - fis.skip(logFile.length() - 1000000); - } - return new BufferedReader(new InputStreamReader(fis)); - } - catch (IOException ex) - { - fis.close(); - throw ex; - } - } - - protected BufferedReader getPluginConfig(final String pluginName, final String fileName) throws IOException - { - final File configFolder = new File(plugin.getDataFolder().getAbsoluteFile().getParentFile(), pluginName); - if (!configFolder.exists()) - { - throw new IOException(pluginName + " plugin folder not found."); - } - final File configFile = new File(configFolder, fileName); - if (!configFile.exists()) - { - throw new IOException(pluginName + " plugin file " + fileName + " not found."); - } - return new BufferedReader(new InputStreamReader(new FileInputStream(configFile), UTF8)); - - } - - protected String uploadToPastie(final StringBuilder input) throws IOException - { - if (input.length() > 15000) - { - input.delete(0, input.length() - 15000); - input.append("## Cropped after 15000 bytes"); - } - final PastieUpload pastie = new PastieUpload(); - return pastie.send(input.toString()); - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/chat/Command.java b/EssentialsUpdate/src/com/earth2me/essentials/update/chat/Command.java deleted file mode 100644 index ad4c75e43..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/chat/Command.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.earth2me.essentials.update.chat; - -import org.bukkit.entity.Player; - - -public interface Command -{ - void run(final IrcBot ircBot, final Player player); -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/chat/ConfigCommand.java b/EssentialsUpdate/src/com/earth2me/essentials/update/chat/ConfigCommand.java deleted file mode 100644 index 78563a950..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/chat/ConfigCommand.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.earth2me.essentials.update.chat; - -import java.io.BufferedReader; -import java.io.IOException; -import java.util.logging.Level; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; - - -public class ConfigCommand extends AbstractFileCommand implements Command -{ - public ConfigCommand(final Plugin plugin) - { - super(plugin); - } - - @Override - public void run(final IrcBot ircBot, final Player player) - { - BufferedReader page = null; - try - { - page = getPluginConfig("Essentials-3", "config.yml"); - final StringBuilder input = new StringBuilder(); - do - { - final String line = page.readLine(); - if (line == null) - { - break; - } - else - { - input.append(line).append("\n"); - } - } - while (true); - page.close(); - final String message = "Essentials config.yml: " + uploadToPastie(input); - player.sendMessage("§6" + ircBot.getNick() + ": §7" + message); - ircBot.sendMessage(message); - } - catch (IOException ex) - { - Bukkit.getLogger().log(Level.SEVERE, null, ex); - player.sendMessage(ex.getMessage()); - } - finally - { - try - { - if (page != null) - { - page.close(); - } - } - catch (IOException ex) - { - Bukkit.getLogger().log(Level.SEVERE, null, ex); - player.sendMessage(ex.getMessage()); - } - } - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/chat/ErrorsCommand.java b/EssentialsUpdate/src/com/earth2me/essentials/update/chat/ErrorsCommand.java deleted file mode 100644 index 41aa551c4..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/chat/ErrorsCommand.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.earth2me.essentials.update.chat; - -import java.io.BufferedReader; -import java.io.IOException; -import java.util.logging.Level; -import java.util.regex.Pattern; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; - - -public class ErrorsCommand extends AbstractFileCommand implements Command -{ - private final transient Pattern pattern = Pattern.compile("^[0-9 :-]+\\[INFO\\].*"); - - public ErrorsCommand(final Plugin plugin) - { - super(plugin); - } - - @Override - public void run(final IrcBot ircBot, final Player player) - { - BufferedReader page = null; - try - { - page = getServerLogReader(); - final StringBuilder input = new StringBuilder(); - do - { - final String line = page.readLine(); - if (line == null) - { - break; - } - else - { - if (!pattern.matcher(line).matches()) - { - input.append(line).append("\n"); - } - } - } - while (true); - page.close(); - final String message = "Errors: " + uploadToPastie(input); - player.sendMessage("§6" + ircBot.getNick() + ": §7" + message); - ircBot.sendMessage(message); - } - catch (IOException ex) - { - Bukkit.getLogger().log(Level.SEVERE, null, ex); - player.sendMessage(ex.getMessage()); - } - finally - { - try - { - if (page != null) - { - page.close(); - } - } - catch (IOException ex) - { - Bukkit.getLogger().log(Level.SEVERE, null, ex); - player.sendMessage(ex.getMessage()); - } - } - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/chat/HelpCommand.java b/EssentialsUpdate/src/com/earth2me/essentials/update/chat/HelpCommand.java deleted file mode 100644 index a6f76cece..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/chat/HelpCommand.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.earth2me.essentials.update.chat; - -import org.bukkit.entity.Player; - - -public class HelpCommand implements Command -{ - @Override - public void run(final IrcBot ircBot, final Player player) - { - player.sendMessage("Commands: (Note: Files send to the chat will be public viewable.)"); - player.sendMessage("!errors - Send the last server errors to the chat."); - player.sendMessage("!startup - Send the last startup messages to the chat."); - player.sendMessage("!config - Sends your Essentials config to the chat."); - player.sendMessage("!list - List all players in chat."); - player.sendMessage("!quit - Leave chat."); - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/chat/IrcBot.java b/EssentialsUpdate/src/com/earth2me/essentials/update/chat/IrcBot.java deleted file mode 100644 index c2cc209e6..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/chat/IrcBot.java +++ /dev/null @@ -1,197 +0,0 @@ -package com.earth2me.essentials.update.chat; - -import java.io.IOException; -import java.util.logging.Level; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.jibble.pircbot.Colors; -import org.jibble.pircbot.IrcException; -import org.jibble.pircbot.PircBot; -import org.jibble.pircbot.User; - - -public class IrcBot extends PircBot -{ - private static final String CHANNEL = "#essentials"; - private static final int PORT = 6667; - private static final String SERVER = "irc.esper.net"; - private transient boolean reconnect = true; - private final transient Player player; - private transient boolean kicked = false; - - public IrcBot(final Player player, final String nickName, final String versionString) - { - super(); - this.player = player; - setName(nickName); - setLogin("esshelp"); - setVersion(versionString); - connect(); - joinChannel(CHANNEL); - } - - private void connect() - { - try - { - connect(SERVER, PORT); - } - catch (IOException ex) - { - Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); - } - catch (IrcException ex) - { - Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); - } - } - - public void quit() - { - reconnect = false; - disconnect(); - } - - @Override - protected void onConnect() - { - reconnect = true; - } - - @Override - protected void onDisconnect() - { - if (reconnect) - { - int tries = 10; - while (!isConnected()) - { - try - { - tries--; - reconnect(); - } - catch (Exception e) - { - Bukkit.getLogger().log(Level.WARNING, e.getMessage(), e); - try - { - Thread.sleep(10000); - } - catch (InterruptedException ex) - { - Bukkit.getLogger().log(Level.WARNING, e.getMessage(), e); - } - } - if (tries <= 0) - { - player.sendMessage("Connection lost to server."); - kicked = true; - break; - } - } - } - } - - @Override - protected void onKick(final String channel, final String kickerNick, - final String kickerLogin, final String kickerHostname, - final String recipientNick, final String reason) - { - if (recipientNick.equals(getNick())) - { - player.sendMessage("You have been kicked from the channel: " + reason); - quit(); - kicked = true; - } - } - - public boolean isKicked() - { - return kicked; - } - - @Override - protected void onMessage(final String channel, final String sender, - final String login, final String hostname, - final String message) - { - player.sendMessage(formatChatMessage(sender, message, false)); - } - - @Override - protected void onAction(final String sender, final String login, - final String hostname, final String target, - final String action) - { - player.sendMessage(formatChatMessage(sender, action, true)); - } - - @Override - protected void onNotice(final String sourceNick, final String sourceLogin, - final String sourceHostname, final String target, - final String notice) - { - player.sendMessage(formatChatMessage(sourceNick, notice, false)); - } - - @Override - protected void onTopic(final String channel, final String topic, - final String setBy, final long date, - final boolean changed) - { - player.sendMessage(formatChatMessage(channel, topic, false)); - } - - public String formatChatMessage(final String nick, final String message, final boolean action) - { - final StringBuilder builder = new StringBuilder(); - builder.append("§6"); - if (action) - { - builder.append('*'); - } - builder.append(nick); - if (!action) - { - builder.append(':'); - } - builder.append(" §7"); - builder.append(replaceColors(message)); - return builder.toString(); - } - - private String replaceColors(final String message) - { - String m = Colors.removeFormatting(message); - m = m.replaceAll("\u000310(,(0?[0-9]|1[0-5]))?", "§b"); - m = m.replaceAll("\u000311(,(0?[0-9]|1[0-5]))?", "§f"); - m = m.replaceAll("\u000312(,(0?[0-9]|1[0-5]))?", "§9"); - m = m.replaceAll("\u000313(,(0?[0-9]|1[0-5]))?", "§d"); - m = m.replaceAll("\u000314(,(0?[0-9]|1[0-5]))?", "§8"); - m = m.replaceAll("\u000315(,(0?[0-9]|1[0-5]))?", "§7"); - m = m.replaceAll("\u00030?1(,(0?[0-9]|1[0-5]))?", "§0"); - m = m.replaceAll("\u00030?2(,(0?[0-9]|1[0-5]))?", "§1"); - m = m.replaceAll("\u00030?3(,(0?[0-9]|1[0-5]))?", "§2"); - m = m.replaceAll("\u00030?4(,(0?[0-9]|1[0-5]))?", "§c"); - m = m.replaceAll("\u00030?5(,(0?[0-9]|1[0-5]))?", "§4"); - m = m.replaceAll("\u00030?6(,(0?[0-9]|1[0-5]))?", "§5"); - m = m.replaceAll("\u00030?7(,(0?[0-9]|1[0-5]))?", "§6"); - m = m.replaceAll("\u00030?8(,(0?[0-9]|1[0-5]))?", "§e"); - m = m.replaceAll("\u00030?9(,(0?[0-9]|1[0-5]))?", "§a"); - m = m.replaceAll("\u00030?0(,(0?[0-9]|1[0-5]))?", "§f"); - m = m.replace("\u000f", "§7"); - m = Colors.removeColors(m); - return m; - } - - public void sendMessage(final String message) - { - sendMessage(CHANNEL, message); - } - - public User[] getUsers() - { - return getUsers(CHANNEL); - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/chat/ListCommand.java b/EssentialsUpdate/src/com/earth2me/essentials/update/chat/ListCommand.java deleted file mode 100644 index 9aa932efa..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/chat/ListCommand.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.earth2me.essentials.update.chat; - -import org.bukkit.entity.Player; -import org.jibble.pircbot.User; - - -public class ListCommand implements Command -{ - @Override - public void run(final IrcBot ircBot, final Player player) - { - final User[] members = ircBot.getUsers(); - final StringBuilder message = new StringBuilder(); - for (User user : members) - { - if (message.length() > 0) - { - message.append("§f, "); - } - if (user.isOp() || user.hasVoice()) - { - message.append("§6"); - } - else - { - message.append("§7"); - } - message.append(user.getPrefix()).append(user.getNick()); - } - player.sendMessage(message.toString()); - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/chat/StartupCommand.java b/EssentialsUpdate/src/com/earth2me/essentials/update/chat/StartupCommand.java deleted file mode 100644 index f244d6e3a..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/chat/StartupCommand.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.earth2me.essentials.update.chat; - -import java.io.BufferedReader; -import java.io.IOException; -import java.util.logging.Level; -import java.util.regex.Pattern; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; - - -public class StartupCommand extends AbstractFileCommand implements Command -{ - private final transient Pattern patternStart = Pattern.compile("^[0-9 :-]+\\[INFO\\] Starting minecraft server version.*"); - private final transient Pattern patternEnd = Pattern.compile("^[0-9 :-]+\\[INFO\\] Done \\([0-9.,]+s\\)! For help, type \"help\".*"); - - public StartupCommand(final Plugin plugin) - { - super(plugin); - } - - @Override - public void run(final IrcBot ircBot, final Player player) - { - BufferedReader page = null; - try - { - page = getServerLogReader(); - final StringBuilder input = new StringBuilder(); - String line; - boolean log = false; - while ((line = page.readLine()) != null) - { - if (patternStart.matcher(line).matches()) - { - if (input.length() > 0) - { - input.delete(0, input.length()); - } - log = true; - } - if (log) - { - input.append(line).append("\n"); - } - if (patternEnd.matcher(line).matches()) - { - log = false; - } - } - page.close(); - final String message = "Startup: " + uploadToPastie(input); - player.sendMessage("§6" + ircBot.getNick() + ": §7" + message); - ircBot.sendMessage(message); - } - catch (IOException ex) - { - Bukkit.getLogger().log(Level.SEVERE, null, ex); - player.sendMessage(ex.getMessage()); - } - finally - { - try - { - if (page != null) - { - page.close(); - } - } - catch (IOException ex) - { - Bukkit.getLogger().log(Level.SEVERE, null, ex); - player.sendMessage(ex.getMessage()); - } - } - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/chat/UsernameUtil.java b/EssentialsUpdate/src/com/earth2me/essentials/update/chat/UsernameUtil.java deleted file mode 100644 index 2fd9a38b6..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/chat/UsernameUtil.java +++ /dev/null @@ -1,124 +0,0 @@ -package com.earth2me.essentials.update.chat; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import org.bukkit.Bukkit; -import org.bukkit.Server; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; - - -public final class UsernameUtil -{ - private static final Pattern CB_PATTERN = Pattern.compile("git-Bukkit-([0-9]+).([0-9]+).([0-9]+)-[0-9]+-[0-9a-z]+-b([0-9]+)jnks.*"); - - private UsernameUtil() - { - } - - public static String createUsername(final Player player) - { - final StringBuilder nameBuilder = new StringBuilder(); - final Server server = Bukkit.getServer(); - nameBuilder.append(player.getName()); - - addCraftBukkitVersion(server, nameBuilder); - addEssentialsVersion(server, nameBuilder); - addGroupManagerVersion(server, nameBuilder); - addPermissionsExVersion(server, nameBuilder); - addPermissionsBukkitVersion(server, nameBuilder); - addBPermissionsVersion(server, nameBuilder); - addPermissionsVersion(server, nameBuilder); - - return nameBuilder.toString(); - } - - private static void addPermissionsVersion(final Server server, final StringBuilder nameBuilder) - { - final Plugin perm = server.getPluginManager().getPlugin("Permissions"); - if (perm != null) - { - nameBuilder.append(" P"); - if (!perm.isEnabled()) - { - nameBuilder.append('!'); - } - nameBuilder.append(perm.getDescription().getVersion()); - } - } - - private static void addBPermissionsVersion(final Server server, final StringBuilder nameBuilder) - { - final Plugin bperm = server.getPluginManager().getPlugin("bPermissions"); - if (bperm != null) - { - nameBuilder.append(" BP"); - if (!bperm.isEnabled()) - { - nameBuilder.append('!'); - } - nameBuilder.append(bperm.getDescription().getVersion()); - } - } - - private static void addPermissionsBukkitVersion(final Server server, final StringBuilder nameBuilder) - { - final Plugin permb = server.getPluginManager().getPlugin("PermissionsBukkit"); - if (permb != null) - { - nameBuilder.append(" PB"); - if (!permb.isEnabled()) - { - nameBuilder.append('!'); - } - nameBuilder.append(permb.getDescription().getVersion()); - } - } - - private static void addPermissionsExVersion(final Server server, final StringBuilder nameBuilder) - { - final Plugin pex = server.getPluginManager().getPlugin("PermissionsEx"); - if (pex != null) - { - nameBuilder.append(" PEX"); - if (!pex.isEnabled()) - { - nameBuilder.append('!'); - } - nameBuilder.append(pex.getDescription().getVersion()); - } - } - - private static void addGroupManagerVersion(final Server server, final StringBuilder nameBuilder) - { - final Plugin groupManager = server.getPluginManager().getPlugin("GroupManager"); - if (groupManager != null) - { - nameBuilder.append(" GM"); - if (!groupManager.isEnabled()) - { - nameBuilder.append('!'); - } - } - } - - private static void addEssentialsVersion(final Server server, final StringBuilder nameBuilder) - { - final Plugin essentials = server.getPluginManager().getPlugin("Essentials-3"); - if (essentials != null) - { - nameBuilder.append(" ESS"); - nameBuilder.append(essentials.getDescription().getVersion()); - } - } - - private static void addCraftBukkitVersion(final Server server, final StringBuilder nameBuilder) - { - final Matcher versionMatch = CB_PATTERN.matcher(server.getVersion()); - if (versionMatch.matches()) - { - nameBuilder.append(" CB"); - nameBuilder.append(versionMatch.group(4)); - } - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/states/AbstractState.java b/EssentialsUpdate/src/com/earth2me/essentials/update/states/AbstractState.java deleted file mode 100644 index 9d3279439..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/states/AbstractState.java +++ /dev/null @@ -1,114 +0,0 @@ -package com.earth2me.essentials.update.states; - -import com.earth2me.essentials.update.AbstractWorkListener; -import org.bukkit.entity.Player; - - -public abstract class AbstractState -{ - private transient boolean abortion = false; - private final transient StateMap stateMap; - - public AbstractState(final StateMap stateMap) - { - this.stateMap = stateMap; - } - - public T getState(final Class stateClass) - { - if (!stateMap.containsKey(stateClass)) - { - try - { - final AbstractState state = stateClass.getConstructor(StateMap.class).newInstance(stateMap); - stateMap.put(stateClass, state); - } - catch (Exception ex) - { - /* - * This should never happen. All states, that are added to the map automatically, have to have a - * Constructor that accepts the StateMap. - */ - throw new RuntimeException(ex); - } - } - return (T)stateMap.get(stateClass); - } - - public abstract AbstractState getNextState(); - - /** - * Check if we already know the answer, so the user does not have to answer the question. - * - * @return true, if the answer could be guessed. - */ - public boolean guessAnswer() - { - return false; - } - - /** - * Ask the user the question. - * - * @param sender - */ - public abstract void askQuestion(Player sender); - - /** - * React on the answer and set internal variables - * - * @param answer - * @return true, if the answer could be recognized as a valid answer - */ - public abstract boolean reactOnAnswer(String answer); - - public final AbstractState reactOnAnswer(final Player sender, final String answer) - { - final String trimmedAnswer = answer.trim(); - if (trimmedAnswer.equalsIgnoreCase("quit") - || trimmedAnswer.equalsIgnoreCase("bye") - || trimmedAnswer.equalsIgnoreCase("abort") - || trimmedAnswer.equalsIgnoreCase("cancel") - || trimmedAnswer.equalsIgnoreCase("exit")) - { - abort(); - return null; - } - try - { - final boolean found = reactOnAnswer(trimmedAnswer); - if (found) - { - return getNextState(); - } - else - { - sender.sendMessage("Answer not recognized."); - return this; - } - } - catch (RuntimeException ex) - { - sender.sendMessage(ex.toString()); - return this; - } - } - - /** - * Do something based on the answer, that the user gave. - */ - public void doWork(final AbstractWorkListener listener) - { - listener.onWorkDone(); - } - - public boolean isAbortion() - { - return abortion; - } - - protected void abort() - { - abortion = true; - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/states/AbstractYesNoState.java b/EssentialsUpdate/src/com/earth2me/essentials/update/states/AbstractYesNoState.java deleted file mode 100644 index 67baf6bb6..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/states/AbstractYesNoState.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.earth2me.essentials.update.states; - - -public abstract class AbstractYesNoState extends AbstractState -{ - private boolean answer = false; - private final transient Class yesState; - private final transient Class noState; - - public AbstractYesNoState(final StateMap states, final Class nextState) - { - this(states, nextState, nextState); - } - - public AbstractYesNoState(final StateMap states, final Class yesState, final Class noState) - { - super(states); - this.yesState = yesState; - this.noState = noState; - } - - @Override - public AbstractState getNextState() - { - return answer - ? (yesState == null ? null : getState(yesState)) - : (noState == null ? null : getState(noState)); - } - - @Override - public boolean reactOnAnswer(final String answer) - { - if (answer.equalsIgnoreCase("yes") - || answer.equalsIgnoreCase("y")) - { - this.answer = true; - return true; - } - if (answer.equalsIgnoreCase("no") - || answer.equalsIgnoreCase("n")) - { - this.answer = false; - return true; - } - return false; - } - - public boolean getAnswer() - { - return answer; - } - - protected void setAnswer(final boolean answer) - { - this.answer = answer; - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/states/AdvancedMode.java b/EssentialsUpdate/src/com/earth2me/essentials/update/states/AdvancedMode.java deleted file mode 100644 index 88d9efc4a..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/states/AdvancedMode.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.earth2me.essentials.update.states; - -import org.bukkit.entity.Player; - - -public class AdvancedMode extends AbstractYesNoState -{ - public AdvancedMode(final StateMap states) - { - super(states, EssentialsChat.class); - } - - @Override - public void askQuestion(final Player sender) - { - sender.sendMessage("This installation mode has a lot of options."); - sender.sendMessage("Do you want use the advanced mode to see all questions?"); - sender.sendMessage("Otherwise the default values will be used."); - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/states/Changelog.java b/EssentialsUpdate/src/com/earth2me/essentials/update/states/Changelog.java deleted file mode 100644 index 10a4f33c5..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/states/Changelog.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.earth2me.essentials.update.states; - -import com.earth2me.essentials.update.UpdateCheck; -import com.earth2me.essentials.update.VersionInfo; -import java.util.List; -import org.bukkit.entity.Player; - - -public class Changelog extends AbstractState -{ - private static final int CHANGES_PER_PAGE = 5; - private transient int page = 0; - private transient boolean confirmed = false; - private transient final List changes; - private transient final int pages; - - public Changelog(final StateMap stateMap) - { - super(stateMap); - changes = getChanges(); - pages = changes.size() / CHANGES_PER_PAGE + (changes.size() % CHANGES_PER_PAGE > 0 ? 1 : 0); - } - - @Override - public AbstractState getNextState() - { - return confirmed ? getState(EssentialsChat.class) : this; - } - - @Override - public boolean guessAnswer() - { - if (pages == 0) - { - confirmed = true; - } - return confirmed; - } - - private List getChanges() - { - final UpdateCheck updateCheck = getState(UpdateOrInstallation.class).getUpdateCheck(); - final VersionInfo versionInfo = updateCheck.getNewVersionInfo(); - return versionInfo.getChangelog(); - } - - @Override - public void askQuestion(final Player sender) - { - if (pages > 1) - { - sender.sendMessage("Changelog, page " + page + " of " + pages + ":"); - } - else - { - sender.sendMessage("Changelog:"); - } - for (int i = page * CHANGES_PER_PAGE; i < Math.min(page * CHANGES_PER_PAGE + CHANGES_PER_PAGE, changes.size()); i++) - { - sender.sendMessage(changes.get(i)); - } - if (pages > 1) - { - sender.sendMessage("Select a page by typing the numbers 1 to " + pages + " to view all changes and then type confirm or abort."); - } - else - { - sender.sendMessage("Type confirm to update Essentials or abort to cancel the update."); - } - } - - @Override - public boolean reactOnAnswer(final String answer) - { - if (answer.equalsIgnoreCase("confirm")) - { - confirmed = true; - return true; - } - if (answer.matches("[0-9]+")) - { - final int page = Integer.parseInt(answer); - if (page <= pages && page > 0) - { - this.page = page - 1; - return true; - } - } - return false; - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/states/EssentialsChat.java b/EssentialsUpdate/src/com/earth2me/essentials/update/states/EssentialsChat.java deleted file mode 100644 index 7253f0d80..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/states/EssentialsChat.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.earth2me.essentials.update.states; - -import com.earth2me.essentials.update.AbstractWorkListener; -import com.earth2me.essentials.update.tasks.InstallModule; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; - - -public class EssentialsChat extends AbstractYesNoState -{ - public EssentialsChat(final StateMap states) - { - super(states, EssentialsChatSettings.class); - } - - @Override - public boolean guessAnswer() - { - final Plugin plugin = Bukkit.getPluginManager().getPlugin("EssentialsChat"); - if (plugin != null) - { - setAnswer(true); - return true; - } - return false; - } - - @Override - public void askQuestion(final Player sender) - { - sender.sendMessage("Do you want to install EssentialsChat? (yes/no)"); - sender.sendMessage("EssentialsChat is a simple chat formatting plugin"); - sender.sendMessage("It allows you to make user prefixes and coloured text."); - } - - @Override - public void doWork(final AbstractWorkListener listener) - { - if (getAnswer()) - { - new InstallModule(listener, "EssentialsChat").start(); - return; - } - listener.onWorkDone(); - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/states/EssentialsChatSettings.java b/EssentialsUpdate/src/com/earth2me/essentials/update/states/EssentialsChatSettings.java deleted file mode 100644 index bb53bc86b..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/states/EssentialsChatSettings.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.earth2me.essentials.update.states; - -import org.bukkit.entity.Player; - - -public class EssentialsChatSettings extends AbstractYesNoState -{ - public EssentialsChatSettings(final StateMap states) - { - super(states, null); - } - - @Override - public boolean guessAnswer() - { - if (getState(AdvancedMode.class).getAnswer()) - { - setAnswer(false); - return true; - } - return false; - } - - @Override - public void askQuestion(final Player sender) - { - sender.sendMessage("Would you like to configure EssentialsChat to prefix ingame messages with their group?"); - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/states/EssentialsGeoIP.java b/EssentialsUpdate/src/com/earth2me/essentials/update/states/EssentialsGeoIP.java deleted file mode 100644 index 6924a5445..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/states/EssentialsGeoIP.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.earth2me.essentials.update.states; - -import com.earth2me.essentials.update.AbstractWorkListener; -import com.earth2me.essentials.update.tasks.InstallModule; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; - - -public class EssentialsGeoIP extends AbstractYesNoState -{ - public EssentialsGeoIP(final StateMap states) - { - super(states, null); - } - - @Override - public boolean guessAnswer() - { - final Plugin plugin = Bukkit.getPluginManager().getPlugin("EssentialsGeoIP"); - if (plugin != null) - { - setAnswer(true); - return true; - } - return false; - } - - @Override - public void askQuestion(final Player sender) - { - sender.sendMessage("Do you want to install EssentialsGeoIP? (yes/no)"); - sender.sendMessage("EssentialsGeoIP performs a IP lookup on joining players"); - sender.sendMessage("It allows you get a rough idea of where a player is from."); - } - - @Override - public void doWork(final AbstractWorkListener listener) - { - if (getAnswer()) - { - new InstallModule(listener, "EssentialsGeoIP").start(); - return; - } - listener.onWorkDone(); - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/states/EssentialsProtect.java b/EssentialsUpdate/src/com/earth2me/essentials/update/states/EssentialsProtect.java deleted file mode 100644 index 925d28315..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/states/EssentialsProtect.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.earth2me.essentials.update.states; - -import com.earth2me.essentials.update.AbstractWorkListener; -import com.earth2me.essentials.update.tasks.InstallModule; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; - - -public class EssentialsProtect extends AbstractYesNoState -{ - public EssentialsProtect(final StateMap states) - { - super(states, null); - } - - @Override - public boolean guessAnswer() - { - final Plugin plugin = Bukkit.getPluginManager().getPlugin("EssentialsProtect"); - if (plugin != null) - { - setAnswer(true); - return true; - } - return false; - } - - @Override - public void askQuestion(final Player sender) - { - sender.sendMessage("Do you want to install EssentialsProtect? (yes/no)"); - sender.sendMessage("EssentialsProtect is a basic world protection system"); - sender.sendMessage("It allows you to set server wide rules, such as disabling creeper explosions, and preventing fire spread."); - } - - @Override - public void doWork(final AbstractWorkListener listener) - { - if (getAnswer()) - { - new InstallModule(listener, "EssentialsProtect").start(); - return; - } - listener.onWorkDone(); - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/states/InstallationFinishedEvent.java b/EssentialsUpdate/src/com/earth2me/essentials/update/states/InstallationFinishedEvent.java deleted file mode 100644 index 4c3fd8f0a..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/states/InstallationFinishedEvent.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.earth2me.essentials.update.states; - -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; - - -public class InstallationFinishedEvent extends Event -{ - private static final HandlerList handlers = new HandlerList(); - - @Override - public HandlerList getHandlers() - { - return handlers; - } - - public static HandlerList getHandlerList() - { - return handlers; - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/states/StateMachine.java b/EssentialsUpdate/src/com/earth2me/essentials/update/states/StateMachine.java deleted file mode 100644 index 6ce926f92..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/states/StateMachine.java +++ /dev/null @@ -1,183 +0,0 @@ -package com.earth2me.essentials.update.states; - -import com.earth2me.essentials.update.AbstractWorkListener; -import com.earth2me.essentials.update.UpdateCheck; -import java.util.Iterator; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; - - -public class StateMachine extends AbstractWorkListener implements Runnable -{ - public enum MachineResult - { - ABORT, WAIT, DONE, NONE - } - private final transient StateMap states = new StateMap(); - private transient AbstractState current; - private transient Player player; - private transient MachineResult result = MachineResult.NONE; - - public StateMachine(final Plugin plugin, final Player player, final UpdateCheck updateCheck) - { - super(plugin, updateCheck.getNewVersionInfo()); - this.player = player; - states.clear(); - final UpdateOrInstallation state = new UpdateOrInstallation(states, updateCheck); - current = states.put(UpdateOrInstallation.class, state); - } - - public MachineResult askQuestion() - { - try - { - while (current.guessAnswer()) - { - current = current.getNextState(); - if (current == null) - { - result = MachineResult.DONE; - break; - } - } - if (current != null) - { - if (player.isOnline()) - { - current.askQuestion(player); - } - result = MachineResult.WAIT; - } - } - catch (RuntimeException ex) - { - player.sendMessage(ex.getMessage()); - finish(); - result = MachineResult.ABORT; - } - return result; - } - - public MachineResult reactOnMessage(final String message) - { - result = MachineResult.NONE; - final AbstractState next = current.reactOnAnswer(player, message); - if (next == null) - { - if (current.isAbortion()) - { - finish(); - result = MachineResult.ABORT; - } - else - { - result = MachineResult.DONE; - } - } - else - { - current = next; - askQuestion(); - } - return result; - } - private transient Iterator iterator; - - public void startWork() - { - iterator = states.values().iterator(); - Bukkit.getScheduler().scheduleAsyncDelayedTask(getPlugin(), this); - } - - @Override - public void run() - { - if (!iterator.hasNext()) - { - Bukkit.getScheduler().scheduleSyncDelayedTask(getPlugin(), new Runnable() - { - @Override - public void run() - { - if (StateMachine.this.player.isOnline()) - { - StateMachine.this.player.sendMessage("Installation done. Reloading server."); - } - finish(); - Bukkit.getServer().reload(); - } - }); - return; - } - final AbstractState state = iterator.next(); - state.doWork(this); - } - - @Override - public void onWorkAbort(final String message) - { - finish(); - Bukkit.getScheduler().scheduleSyncDelayedTask(getPlugin(), new Runnable() - { - @Override - public void run() - { - if (message != null && !message.isEmpty() && StateMachine.this.player.isOnline()) - { - StateMachine.this.player.sendMessage(message); - } - } - }); - } - - @Override - public void onWorkDone(final String message) - { - Bukkit.getScheduler().scheduleSyncDelayedTask(getPlugin(), new Runnable() - { - @Override - public void run() - { - if (message != null && !message.isEmpty() && StateMachine.this.player.isOnline()) - { - StateMachine.this.player.sendMessage(message); - } - Bukkit.getScheduler().scheduleAsyncDelayedTask(getPlugin(), StateMachine.this); - } - }); - } - - private void finish() - { - current = null; - iterator = null; - states.clear(); - getPlugin().getServer().getPluginManager().callEvent(new InstallationFinishedEvent()); - } - - public void resumeInstallation(final Player player) - { - this.player = player; - if (result == MachineResult.WAIT) - { - if (current == null) - { - throw new RuntimeException("State is WAIT, but current state is null!"); - } - current.askQuestion(player); - } - if (result == MachineResult.DONE && iterator != null) - { - player.sendMessage("Installation is still running."); - } - if (result == MachineResult.ABORT) - { - throw new RuntimeException("Player should not be able to resume an aborted installation."); - } - if (result == MachineResult.NONE) - { - throw new RuntimeException("State machine in an undefined state."); - } - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/states/StateMap.java b/EssentialsUpdate/src/com/earth2me/essentials/update/states/StateMap.java deleted file mode 100644 index cca4223d6..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/states/StateMap.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.earth2me.essentials.update.states; - -import java.util.LinkedHashMap; - - -public class StateMap extends LinkedHashMap, AbstractState> -{ - public StateMap() - { - super(50); - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/states/UpdateOrInstallation.java b/EssentialsUpdate/src/com/earth2me/essentials/update/states/UpdateOrInstallation.java deleted file mode 100644 index 6b48f90be..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/states/UpdateOrInstallation.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.earth2me.essentials.update.states; - -import com.earth2me.essentials.update.UpdateCheck; -import org.bukkit.entity.Player; - - -public class UpdateOrInstallation extends AbstractState -{ - private final transient UpdateCheck updateCheck; - private transient boolean update = false; - - public UpdateOrInstallation(final StateMap stateMap, final UpdateCheck updateCheck) - { - super(stateMap); - this.updateCheck = updateCheck; - } - - @Override - public boolean guessAnswer() - { - if (getUpdateCheck().isEssentialsInstalled()) - { - update = true; - } - return update; - } - - @Override - public AbstractState getNextState() - { - return update ? getState(Changelog.class) : getState(EssentialsChat.class); - } - - @Override - public void askQuestion(final Player sender) - { - sender.sendMessage("Thank you for choosing Essentials."); - sender.sendMessage("The following installation wizard will guide you through the installation of Essentials."); - sender.sendMessage("Your answers will be saved for a later update."); - sender.sendMessage("Please answer the messages with yes or no, if not otherwise stated."); - sender.sendMessage("Write bye/exit/quit if you want to exit the wizard at anytime."); - sender.sendMessage("Type ok to continue..."); - } - - @Override - public boolean reactOnAnswer(final String answer) - { - return answer.equalsIgnoreCase("ok") || answer.equalsIgnoreCase("k") || answer.equalsIgnoreCase("continue"); - } - - public UpdateCheck getUpdateCheck() - { - return updateCheck; - } - - public boolean isUpdate() - { - return update; - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/tasks/InstallModule.java b/EssentialsUpdate/src/com/earth2me/essentials/update/tasks/InstallModule.java deleted file mode 100644 index 778f5172f..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/tasks/InstallModule.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.earth2me.essentials.update.tasks; - -import com.earth2me.essentials.update.AbstractWorkListener; -import com.earth2me.essentials.update.GetFile; -import com.earth2me.essentials.update.ModuleInfo; -import com.earth2me.essentials.update.VersionInfo; -import java.io.File; -import java.net.URL; -import java.util.logging.Level; -import org.bukkit.Bukkit; - - -public class InstallModule implements Runnable, Task -{ - protected final transient AbstractWorkListener listener; - private final transient String moduleName; - private final transient String fileName; - - public InstallModule(final AbstractWorkListener listener, final String moduleName) - { - this(listener, moduleName, moduleName + ".jar"); - } - - public InstallModule(final AbstractWorkListener listener, final String moduleName, final String fileName) - { - this.listener = listener; - this.moduleName = moduleName; - this.fileName = fileName; - } - - @Override - public void start() - { - Bukkit.getScheduler().scheduleAsyncDelayedTask(listener.getPlugin(), this); - } - - @Override - public void run() - { - final VersionInfo info = listener.getNewVersionInfo(); - final ModuleInfo module = info.getModules().get(moduleName); - if (module == null) - { - listener.onWorkAbort("Module " + moduleName + " not found in VersionInfo."); - return; - } - try - { - final URL downloadUrl = module.getUrl(); - final GetFile getFile = new GetFile(downloadUrl); - getFile.saveTo(new File(listener.getPlugin().getServer().getUpdateFolderFile(), fileName), module.getHash()); - listener.onWorkDone("Module " + moduleName + " downloaded."); - } - catch (Exception ex) - { - Bukkit.getLogger().log(Level.SEVERE, "Failed to download module " + moduleName + " to " + fileName, ex); - listener.onWorkAbort("An error occured, please check your server log."); - return; - } - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/tasks/SelfUpdate.java b/EssentialsUpdate/src/com/earth2me/essentials/update/tasks/SelfUpdate.java deleted file mode 100644 index 3baf86be7..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/tasks/SelfUpdate.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.earth2me.essentials.update.tasks; - -import com.earth2me.essentials.update.AbstractWorkListener; -import org.bukkit.Bukkit; - - -public class SelfUpdate extends AbstractWorkListener implements Task, Runnable -{ - private final transient AbstractWorkListener listener; - - public SelfUpdate(final AbstractWorkListener listener) - { - super(listener.getPlugin(), listener.getNewVersionInfo()); - this.listener = listener; - } - - @Override - public void onWorkAbort(final String message) - { - listener.onWorkAbort(message); - } - - @Override - public void onWorkDone(final String message) - { - listener.onWorkDone(message); - Bukkit.getScheduler().scheduleSyncDelayedTask(getPlugin(), new Runnable() - { - @Override - public void run() - { - Bukkit.getServer().reload(); - } - }); - } - - @Override - public void start() - { - Bukkit.getScheduler().scheduleSyncDelayedTask(getPlugin(), this); - } - - @Override - public void run() - { - Bukkit.getScheduler().scheduleAsyncDelayedTask(getPlugin(), new Runnable() - { - @Override - public void run() - { - new InstallModule(SelfUpdate.this, "EssentialsUpdate").start(); - } - }); - } -} diff --git a/EssentialsUpdate/src/com/earth2me/essentials/update/tasks/Task.java b/EssentialsUpdate/src/com/earth2me/essentials/update/tasks/Task.java deleted file mode 100644 index 3f1d572ed..000000000 --- a/EssentialsUpdate/src/com/earth2me/essentials/update/tasks/Task.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.earth2me.essentials.update.tasks; - - -public interface Task -{ - void start(); -} diff --git a/EssentialsUpdate/src/net/ess3/update/AbstractWorkListener.java b/EssentialsUpdate/src/net/ess3/update/AbstractWorkListener.java new file mode 100644 index 000000000..7a927d4db --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/AbstractWorkListener.java @@ -0,0 +1,39 @@ +package net.ess3.update; + +import org.bukkit.plugin.Plugin; + + +public abstract class AbstractWorkListener +{ + public AbstractWorkListener(final Plugin plugin, final VersionInfo newVersionInfo) + { + this.plugin = plugin; + this.newVersionInfo = newVersionInfo; + } + private final transient Plugin plugin; + private final transient VersionInfo newVersionInfo; + + public final void onWorkAbort() + { + onWorkAbort(null); + } + + public abstract void onWorkAbort(String message); + + public final void onWorkDone() + { + onWorkDone(null); + } + + public abstract void onWorkDone(String message); + + public VersionInfo getNewVersionInfo() + { + return newVersionInfo; + } + + public Plugin getPlugin() + { + return plugin; + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/EssentialsHelp.java b/EssentialsUpdate/src/net/ess3/update/EssentialsHelp.java new file mode 100644 index 000000000..0d433ecc0 --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/EssentialsHelp.java @@ -0,0 +1,171 @@ +package net.ess3.update; + +import net.ess3.update.chat.*; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import org.bukkit.Server; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerChatEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginManager; + + +public class EssentialsHelp implements Listener +{ + private transient Player chatUser; + private final transient Server server; + private final transient Plugin plugin; + private transient IrcBot ircBot; + private final transient Map commands = new HashMap(); + + public EssentialsHelp(final Plugin plugin) + { + super(); + this.plugin = plugin; + this.server = plugin.getServer(); + commands.put("!help", new HelpCommand()); + commands.put("!list", new ListCommand()); + commands.put("!startup", new StartupCommand(plugin)); + commands.put("!errors", new ErrorsCommand(plugin)); + commands.put("!config", new ConfigCommand(plugin)); + } + + public void registerEvents() + { + final PluginManager pluginManager = server.getPluginManager(); + pluginManager.registerEvents(this, plugin); + } + + public void onCommand(final CommandSender sender) + { + if (sender instanceof Player && sender.hasPermission("essentials.helpchat")) + { + if (chatUser == null) + { + chatUser = (Player)sender; + ircBot = null; + sender.sendMessage("You will be connected to the Essentials Help Chat."); + sender.sendMessage("All your chat messages will be forwarded to the channel. You can't chat with other players on your server while in help chat, but you can use commands."); + sender.sendMessage("Please be patient, if noone is available, check back later."); + sender.sendMessage("Type !help to get a list of all commands."); + sender.sendMessage("Type !quit to leave the channel."); + sender.sendMessage("Do you want to join the channel now? (yes/no)"); + } + if (!chatUser.equals(sender)) + { + sender.sendMessage("The player " + chatUser.getDisplayName() + " is already using the essentialshelp."); + } + } + else + { + sender.sendMessage("Please run the command as op from in game."); + } + } + + public void onDisable() + { + closeConnection(); + } + + private boolean sendChatMessage(final Player player, final String message) + { + final String messageCleaned = message.trim(); + if (messageCleaned.isEmpty()) + { + return false; + } + if (ircBot == null) + { + return handleAnswer(messageCleaned, player); + } + else + { + if (ircBot.isKicked()) + { + closeConnection(); + return false; + } + final String lowMessage = messageCleaned.toLowerCase(Locale.ENGLISH); + if (lowMessage.startsWith("!quit")) + { + closeConnection(); + player.sendMessage("Connection closed."); + return true; + } + if (!ircBot.isConnected() || ircBot.getChannels().length == 0) + { + return false; + } + if (handleCommands(lowMessage, player)) + { + return true; + } + ircBot.sendMessage(messageCleaned); + chatUser.sendMessage("§6" + ircBot.getNick() + ": §7" + messageCleaned); + return true; + } + } + + private void closeConnection() + { + chatUser = null; + if (ircBot != null) + { + ircBot.quit(); + ircBot = null; + } + } + + private boolean handleAnswer(final String message, final Player player) + { + if (message.equalsIgnoreCase("yes")) + { + player.sendMessage("Connecting..."); + connectToIRC(player); + return true; + } + if (message.equalsIgnoreCase("no") || message.equalsIgnoreCase("!quit")) + { + chatUser = null; + return true; + } + return false; + } + + private boolean handleCommands(final String lowMessage, final Player player) + { + final String[] parts = lowMessage.split(" "); + if (commands.containsKey(parts[0])) + { + commands.get(parts[0]).run(ircBot, player); + return true; + } + return false; + } + + private void connectToIRC(final Player player) + { + ircBot = new IrcBot(player, "Ess_" + player.getName(), UsernameUtil.createUsername(player)); + } + + @EventHandler + public void onPlayerChat(final PlayerChatEvent event) + { + if (event.getPlayer() == chatUser) + { + final boolean success = sendChatMessage(event.getPlayer(), event.getMessage()); + event.setCancelled(success); + } + } + + @EventHandler + public void onPlayerQuit(final PlayerQuitEvent event) + { + closeConnection(); + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/EssentialsUpdate.java b/EssentialsUpdate/src/net/ess3/update/EssentialsUpdate.java new file mode 100644 index 000000000..33875423a --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/EssentialsUpdate.java @@ -0,0 +1,59 @@ +package net.ess3.update; + +import java.util.logging.Level; +import org.bukkit.Bukkit; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.plugin.java.JavaPlugin; + + +public class EssentialsUpdate extends JavaPlugin +{ + private transient EssentialsHelp essentialsHelp; + private transient UpdateProcess updateProcess; + + @Override + public void onEnable() + { + if (!getDataFolder().exists() && !getDataFolder().mkdirs()) + { + Bukkit.getLogger().log(Level.SEVERE, "Could not create data folder: {0}", getDataFolder().getPath()); + } + essentialsHelp = new EssentialsHelp(this); + essentialsHelp.registerEvents(); + + final UpdateCheck updateCheck = new UpdateCheck(this); + updateCheck.checkForUpdates(); + updateProcess = new UpdateProcess(this, updateCheck); + updateProcess.registerEvents(); + + if (updateCheck.isEssentialsInstalled()) + { + updateCheck.scheduleUpdateTask(); + } + else + { + Bukkit.getLogger().info("Essentials is ready for installation. Join the game and follow the instructions."); + } + } + + @Override + public void onDisable() + { + essentialsHelp.onDisable(); + } + + @Override + public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) + { + if (command.getName().equalsIgnoreCase("essentialsupdate")) + { + updateProcess.onCommand(sender); + } + if (command.getName().equalsIgnoreCase("essentialshelp")) + { + essentialsHelp.onCommand(sender); + } + return true; + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/GetFile.java b/EssentialsUpdate/src/net/ess3/update/GetFile.java new file mode 100644 index 000000000..9636e3bd1 --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/GetFile.java @@ -0,0 +1,113 @@ +package net.ess3.update; + +import java.io.*; +import java.math.BigInteger; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.logging.Level; +import org.bukkit.Bukkit; + + +public class GetFile +{ + private transient URLConnection connection; + private transient MessageDigest digest; + + public GetFile(final String urlString) throws MalformedURLException, IOException + { + this(new URL(urlString)); + } + + public GetFile(final URL url) throws IOException + { + this.connection = url.openConnection(); + this.connection.setConnectTimeout(1000); + this.connection.setReadTimeout(5000); + this.connection.setUseCaches(false); + this.connection.connect(); + final int respCode = ((HttpURLConnection)this.connection).getResponseCode(); + if (respCode >= 300 && respCode < 400 && this.connection.getHeaderField("Location") != null) + { + connection.getInputStream().close(); + final URL redirect = new URL(this.connection.getHeaderField("Location")); + this.connection = redirect.openConnection(); + this.connection.setConnectTimeout(1000); + this.connection.setReadTimeout(5000); + this.connection.setUseCaches(false); + this.connection.connect(); + } + } + + public void saveTo(final File file) throws IOException + { + try + { + saveTo(file, null); + } + catch (NoSuchAlgorithmException ex) + { + throw new RuntimeException(ex); + } + } + + public void saveTo(final File file, final String key) throws IOException, NoSuchAlgorithmException + { + if (key != null) + { + digest = MessageDigest.getInstance("SHA256"); + } + final byte[] buffer = new byte[1024 * 8]; + boolean brokenFile = false; + final BufferedInputStream input = new BufferedInputStream(connection.getInputStream()); + try + { + final BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(file)); + try + { + int length; + do + { + length = input.read(buffer); + if (length >= 0) + { + if (key != null) + { + digest.update(buffer, 0, length); + } + output.write(buffer, 0, length); + } + } + while (length >= 0); + if (key != null) + { + final byte[] checksum = digest.digest(); + final String checksumString = new BigInteger(checksum).toString(36); + if (!checksumString.equals(key)) + { + brokenFile = true; + } + } + } + finally + { + output.close(); + } + if (brokenFile && !file.delete()) + { + Bukkit.getLogger().log(Level.SEVERE, "Could not delete file {0}", file.getPath()); + } + } + finally + { + input.close(); + } + if (brokenFile) + { + throw new IOException("Checksum check failed."); + } + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/ModuleInfo.java b/EssentialsUpdate/src/net/ess3/update/ModuleInfo.java new file mode 100644 index 000000000..993575cbf --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/ModuleInfo.java @@ -0,0 +1,35 @@ +package net.ess3.update; + +import java.net.MalformedURLException; +import java.net.URL; +import org.bukkit.configuration.Configuration; + + +public class ModuleInfo +{ + private final transient String url; + private final transient String version; + private final transient String hash; + + public ModuleInfo(final Configuration updateConfig, final String path) + { + url = updateConfig.getString(path + ".url", null); + version = updateConfig.getString(path + ".version", null); + hash = updateConfig.getString(path + ".hash", null); + } + + public URL getUrl() throws MalformedURLException + { + return new URL(url); + } + + public String getVersion() + { + return version; + } + + public String getHash() + { + return hash; + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/PastieUpload.java b/EssentialsUpdate/src/net/ess3/update/PastieUpload.java new file mode 100644 index 000000000..9fba2351d --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/PastieUpload.java @@ -0,0 +1,40 @@ +package net.ess3.update; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + + +public class PastieUpload +{ + private final transient PostToUrl connection; + + public PastieUpload() throws MalformedURLException + { + connection = new PostToUrl(new URL("http://pastie.org/pastes")); + } + + public String send(final String data) throws IOException + { + final Map map = new HashMap(); + map.put("paste[parser_id]", "19"); + map.put("paste[authorization]", "burger"); + map.put("paste[body]", data); + map.put("paste[restricted]", "1"); + final String html = connection.send(map); + final Matcher matcher = Pattern.compile("(?s).*\\?key=([a-z0-9]+).*").matcher(html); + if (matcher.matches()) + { + final String key = matcher.group(1); + return "http://pastie.org/private/" + key; + } + else + { + throw new IOException("Failed to upload to pastie.org"); + } + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/PostToUrl.java b/EssentialsUpdate/src/net/ess3/update/PostToUrl.java new file mode 100644 index 000000000..28fc13c55 --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/PostToUrl.java @@ -0,0 +1,66 @@ +package net.ess3.update; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.math.BigInteger; +import java.net.URL; +import java.net.URLConnection; +import java.nio.charset.Charset; +import java.util.Map; +import java.util.Random; + + +public class PostToUrl +{ + private final transient URL url; + private final transient String boundary; + private final transient Random random = new Random(); + private final static String CRLF = "\r\n"; + private final static Charset UTF8 = Charset.forName("utf-8"); + + public PostToUrl(final URL url) + { + this.url = url; + final byte[] bytes = new byte[32]; + random.nextBytes(bytes); + this.boundary = "----------" + new BigInteger(bytes).toString(Character.MAX_RADIX) + "_$"; + } + + public String send(final Map data) throws IOException + { + final URLConnection connection = url.openConnection(); + connection.setRequestProperty("content-type", "multipart/form-data; boundary=" + boundary); + final StringBuilder dataBuilder = new StringBuilder(); + for (Map.Entry entry : data.entrySet()) + { + if (entry.getValue() instanceof String) + { + dataBuilder.append("--").append(boundary).append(CRLF); + dataBuilder.append("Content-Disposition: form-data; name=\"").append(entry.getKey()).append('"').append(CRLF); + dataBuilder.append(CRLF); + dataBuilder.append(entry.getValue()).append(CRLF); + } + // TODO: Add support for file upload + } + dataBuilder.append("--").append(boundary).append("--").append(CRLF); + dataBuilder.append(CRLF); + connection.setDoOutput(true); + final byte[] message = dataBuilder.toString().getBytes(UTF8); + connection.setRequestProperty("content-length", Integer.toString(message.length)); + connection.connect(); + final OutputStream stream = connection.getOutputStream(); + stream.write(message); + stream.close(); + final BufferedReader page = new BufferedReader(new InputStreamReader(connection.getInputStream(), UTF8)); + final StringBuilder input = new StringBuilder(); + String line; + while ((line = page.readLine()) != null) + { + input.append(line).append("\n"); + } + page.close(); + return input.toString(); + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/UpdateCheck.java b/EssentialsUpdate/src/net/ess3/update/UpdateCheck.java new file mode 100644 index 000000000..98a9983e8 --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/UpdateCheck.java @@ -0,0 +1,202 @@ +package net.ess3.update; + +import java.io.File; +import java.util.Map; +import java.util.Map.Entry; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.bukkit.Bukkit; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.PluginManager; + + +public class UpdateCheck +{ + private transient CheckResult result = CheckResult.UNKNOWN; + private transient Version currentVersion; + private transient Version newVersion = null; + private transient int bukkitResult = 0; + private transient UpdateFile updateFile; + private final static int CHECK_INTERVAL = 20 * 60 * 60 * 6; + private final transient Plugin plugin; + private transient boolean essentialsInstalled; + + public UpdateCheck(final Plugin plugin) + { + this.plugin = plugin; + updateFile = new UpdateFile(plugin); + checkForEssentials(); + } + + private void checkForEssentials() + { + final PluginManager pluginManager = plugin.getServer().getPluginManager(); + final Plugin essentials = pluginManager.getPlugin("Essentials-3"); + essentialsInstalled = essentials != null; + if (essentialsInstalled) + { + currentVersion = new Version(essentials.getDescription().getVersion()); + } + else + { + if (new File(plugin.getDataFolder().getParentFile(), "Essentials.jar").exists()) + { + Bukkit.getLogger().severe("Essentials.jar found, but not recognized by Bukkit. Broken download?"); + } + } + } + + public void scheduleUpdateTask() + { + plugin.getServer().getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable() + { + @Override + public void run() + { + updateFile = new UpdateFile(plugin); + checkForUpdates(); + } + }, CHECK_INTERVAL, CHECK_INTERVAL); + } + + public boolean isEssentialsInstalled() + { + return essentialsInstalled; + } + + public CheckResult getResult() + { + return result; + } + + public int getNewBukkitVersion() + { + return bukkitResult; + } + + public VersionInfo getNewVersionInfo() + { + return updateFile.getVersions().get(newVersion); + } + + + public enum CheckResult + { + NEW_ESS, NEW_ESS_BUKKIT, NEW_BUKKIT, OK, UNKNOWN + } + + public void checkForUpdates() + { + if (currentVersion == null) + { + return; + } + final Map versions = updateFile.getVersions(); + final int bukkitVersion = getBukkitVersion(); + Version higher = null; + Version found = null; + Version lower = null; + int bukkitHigher = 0; + int bukkitLower = 0; + for (Entry entry : versions.entrySet()) + { + final int minBukkit = entry.getValue().getMinBukkit(); + final int maxBukkit = entry.getValue().getMaxBukkit(); + if (minBukkit == 0 || maxBukkit == 0) + { + continue; + } + if (bukkitVersion <= maxBukkit) + { + if (bukkitVersion < minBukkit) + { + if (higher == null || higher.compareTo(entry.getKey()) < 0) + { + + higher = entry.getKey(); + bukkitHigher = minBukkit; + } + } + else + { + if (found == null || found.compareTo(entry.getKey()) < 0) + { + found = entry.getKey(); + } + } + } + else + { + if (lower == null || lower.compareTo(entry.getKey()) < 0) + { + lower = entry.getKey(); + bukkitLower = minBukkit; + } + } + } + if (found != null) + { + if (found.compareTo(currentVersion) > 0) + { + result = CheckResult.NEW_ESS; + newVersion = found; + } + else + { + result = CheckResult.OK; + } + } + else if (higher != null) + { + if (higher.compareTo(currentVersion) > 0) + { + newVersion = higher; + result = CheckResult.NEW_ESS_BUKKIT; + bukkitResult = bukkitHigher; + } + else if (higher.compareTo(currentVersion) < 0) + { + result = CheckResult.UNKNOWN; + } + else + { + result = CheckResult.NEW_BUKKIT; + bukkitResult = bukkitHigher; + } + } + else if (lower != null) + { + if (lower.compareTo(currentVersion) > 0) + { + result = CheckResult.NEW_ESS_BUKKIT; + newVersion = lower; + bukkitResult = bukkitLower; + } + else if (lower.compareTo(currentVersion) < 0) + { + result = CheckResult.UNKNOWN; + } + else + { + result = CheckResult.NEW_BUKKIT; + bukkitResult = bukkitLower; + } + } + + } + + private int getBukkitVersion() + { + final Matcher versionMatch = Pattern.compile("git-Bukkit-(?:(?:[0-9]+)\\.)+[0-9]+-R[\\.0-9]+-(?:[0-9]+-g[0-9a-f]+-)?b([0-9]+)jnks.*").matcher(plugin.getServer().getVersion()); + if (versionMatch.matches()) + { + return Integer.parseInt(versionMatch.group(1)); + } + throw new NumberFormatException("Bukkit Version changed!"); + } + + public Version getNewVersion() + { + return newVersion; + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/UpdateFile.java b/EssentialsUpdate/src/net/ess3/update/UpdateFile.java new file mode 100644 index 000000000..cdab65600 --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/UpdateFile.java @@ -0,0 +1,204 @@ +package net.ess3.update; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.math.BigInteger; +import java.security.KeyFactory; +import java.security.PublicKey; +import java.security.Signature; +import java.security.spec.X509EncodedKeySpec; +import java.util.Collections; +import java.util.Map; +import java.util.TreeMap; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.bukkit.Bukkit; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.Plugin; + + +public class UpdateFile +{ + private final static Logger LOGGER = Bukkit.getLogger(); + private final static String UPDATE_URL = "http://goo.gl/67jev"; + private final static BigInteger PUBLIC_KEY = new BigInteger("5ha6a2d4qdy17ttkg8evh74sl5a87djojwenu12k1lvy8ui6003e6l06rntczpoh99mhc3txj8mqlxw111oyy9yl7s7qpyluyzix3j1odxrxx4u52gxvyu6qiteapczkzvi7rxgeqsozz7b19rdx73a7quo9ybwpz1cr82r7x5k0pg2a73pjjsv2j1awr13azo7klrcxp9y5xxwf5qv1s3tw4zqftli18u0ek5qkbzfbgk1v5n2f11pkwwk6p0mibrn26wnjbv11vyiqgu95o7busmt6vf5q7grpcenl637w83mbin56s3asj1131b2mscj9xep3cbj7la9tgsxl5bj87vzy8sk2d34kzwqdqgh9nry43nqqus12l1stmiv184r8r3jcy8w43e8h1u1mzklldb5eytkuhayqik8l3ns04hwt8sgacvw534be8sx26qrn5s1", 36); + private final transient File file; + private final transient Plugin plugin; + private final transient TreeMap versions = new TreeMap(); + + public UpdateFile(final Plugin plugin) + { + this.plugin = plugin; + final long lastUpdate = Long.parseLong(plugin.getConfig().getString("lastupdate", "0")); + file = new File(plugin.getDataFolder(), "update.yml"); + if (lastUpdate < System.currentTimeMillis() - 1000 * 60 * 60 * 6 || !file.exists()) + { + if (file.exists() && !file.delete()) + { + LOGGER.log(Level.SEVERE, "Could not delete file update.yml!"); + return; + } + if (!downloadFile() || !checkFile()) + { + LOGGER.log(Level.SEVERE, "Could not download and verify file update.yml!"); + return; + } + } + try + { + readVersions(); + } + catch (Exception ex) + { + LOGGER.log(Level.SEVERE, "Could not load update.yml!"); + return; + } + } + + private boolean downloadFile() + { + GetFile getFile; + try + { + getFile = new GetFile(UPDATE_URL); + getFile.saveTo(file); + plugin.getConfig().set("lastupdate", System.currentTimeMillis()); + plugin.getConfig().save(new File(plugin.getDataFolder(), "config.yml")); + return true; + } + catch (IOException ex) + { + LOGGER.log(Level.SEVERE, "Error while downloading update.yml", ex); + return false; + } + } + + private boolean checkFile() + { + BufferedInputStream bis = null; + try + { + bis = new BufferedInputStream(new FileInputStream(file)); + if (bis.read() != '#') + { + throw new IOException("File has to start with #"); + } + final StringBuilder length = new StringBuilder(); + final StringBuilder signature = new StringBuilder(); + boolean isSignature = false; + do + { + final int cur = bis.read(); + if (cur == -1) + { + break; + } + if (cur == ':') + { + isSignature = true; + } + else if (cur == '\n') + { + break; + } + else if ((cur >= '0' && cur <= '9') + || (cur >= 'a' && cur <= 'z')) + { + if (isSignature) + { + signature.append((char)cur); + } + else + { + length.append((char)cur); + } + } + else + { + throw new IOException("Illegal character in signature!"); + } + } + while (true); + if (length.length() == 0 || signature.length() == 0) + { + throw new IOException("Broken signature!"); + } + final int sigLength = new BigInteger(length.toString(), 36).intValue(); + if (sigLength < 0 || sigLength > 2048) + { + throw new IOException("Invalid signature length!"); + } + final byte[] sigBytes = new BigInteger(signature.toString(), 36).toByteArray(); + if (sigLength < sigBytes.length) + { + throw new IOException("Length is less then available bytes."); + } + byte[] realBytes; + if (sigLength == sigBytes.length) + { + realBytes = sigBytes; + } + else + { + realBytes = new byte[sigLength]; + System.arraycopy(sigBytes, 0, realBytes, sigLength - sigBytes.length, sigBytes.length); + } + final X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(PUBLIC_KEY.toByteArray()); + final KeyFactory keyFactory = KeyFactory.getInstance("RSA"); + final PublicKey pubKey = keyFactory.generatePublic(pubKeySpec); + final Signature rsa = Signature.getInstance("SHA256withRSA"); + rsa.initVerify(pubKey); + final byte[] buffer = new byte[2048]; + int readLength; + do + { + readLength = bis.read(buffer); + if (readLength >= 0) + { + rsa.update(buffer, 0, readLength); + } + } + while (readLength >= 0); + return rsa.verify(realBytes); + } + catch (Exception ex) + { + LOGGER.log(Level.SEVERE, ex.getMessage(), ex); + } + finally + { + try + { + if (bis != null) + { + bis.close(); + } + } + catch (IOException ex) + { + LOGGER.log(Level.SEVERE, ex.getMessage(), ex); + } + } + return false; + } + + private void readVersions() throws FileNotFoundException, InvalidConfigurationException, IOException + { + final YamlConfiguration updateConfig = new YamlConfiguration(); + updateConfig.load(file); + versions.clear(); + for (String versionString : updateConfig.getKeys(false)) + { + versions.put(new Version(versionString), new VersionInfo(updateConfig, versionString)); + } + } + + public Map getVersions() + { + return Collections.unmodifiableMap(versions.descendingMap()); + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/UpdateProcess.java b/EssentialsUpdate/src/net/ess3/update/UpdateProcess.java new file mode 100644 index 000000000..f96cdd18f --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/UpdateProcess.java @@ -0,0 +1,199 @@ +package net.ess3.update; + +import net.ess3.update.states.InstallationFinishedEvent; +import net.ess3.update.states.StateMachine; +import net.ess3.update.tasks.SelfUpdate; +import java.util.logging.Level; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +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.PlayerChatEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.plugin.Plugin; + +// TODO: This whole thing should make use of the conversations api +public class UpdateProcess implements Listener +{ + private transient Player currentPlayer; + private final transient Plugin plugin; + private final transient UpdateCheck updateCheck; + private transient StateMachine stateMachine; + + public UpdateProcess(final Plugin plugin, final UpdateCheck updateCheck) + { + super(); + this.plugin = plugin; + this.updateCheck = updateCheck; + } + + public void registerEvents() + { + plugin.getServer().getPluginManager().registerEvents(this, plugin); + } + + public boolean selfUpdate() + { + if (new Version(plugin.getDescription().getVersion()).compareTo(updateCheck.getNewVersion()) < 0) + { + if (currentPlayer != null) + { + currentPlayer.sendMessage("A newer version of EssentialsUpdate is found. Downloading new file and reloading server."); + } + Bukkit.getLogger().log(Level.INFO, "A newer version of EssentialsUpdate is found. Downloading new file and reloading server."); + new SelfUpdate(new AbstractWorkListener(plugin, updateCheck.getNewVersionInfo()) + { + @Override + public void onWorkAbort(final String message) + { + if (message != null && !message.isEmpty() + && UpdateProcess.this.currentPlayer != null + && UpdateProcess.this.currentPlayer.isOnline()) + { + UpdateProcess.this.currentPlayer.sendMessage(message); + } + if (message != null && !message.isEmpty()) + { + Bukkit.getLogger().log(Level.SEVERE, message); + } + UpdateProcess.this.currentPlayer = null; + } + + @Override + public void onWorkDone(final String message) + { + if (message != null && !message.isEmpty() + && UpdateProcess.this.currentPlayer != null + && UpdateProcess.this.currentPlayer.isOnline()) + { + UpdateProcess.this.currentPlayer.sendMessage(message); + } + if (message != null && !message.isEmpty()) + { + Bukkit.getLogger().log(Level.INFO, message); + } + UpdateProcess.this.currentPlayer = null; + } + }).start(); + return true; + } + if (updateCheck.getResult() == UpdateCheck.CheckResult.NEW_ESS_BUKKIT) + { + final String message = "Please update bukkit to version " + updateCheck.getNewBukkitVersion() + " before updating Essentials."; + if (currentPlayer != null) + { + currentPlayer.sendMessage(message); + } + Bukkit.getLogger().log(Level.INFO, message); + currentPlayer = null; + return true; + } + return false; + } + + @EventHandler + public void onInstallationFinished(final InstallationFinishedEvent event) + { + UpdateProcess.this.currentPlayer = null; + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onPlayerChat(final PlayerChatEvent event) + { + if (event.getPlayer() == currentPlayer) + { + final StateMachine.MachineResult result = stateMachine.reactOnMessage(event.getMessage()); + if (result == StateMachine.MachineResult.ABORT) + { + currentPlayer.sendMessage("Installation wizard aborted. You can restart it using /essentialsupdate."); + currentPlayer = null; + } + if (result == StateMachine.MachineResult.DONE) + { + startWork(); + } + event.setCancelled(true); + return; + } + } + + @EventHandler + public void onPlayerJoin(final PlayerJoinEvent event) + { + final Player player = event.getPlayer(); + if (currentPlayer != null && currentPlayer.getName().equals(player.getName())) + { + currentPlayer = player; + player.sendMessage("You quit the game, while the installation wizard was running."); + player.sendMessage("The installation wizard will now resume."); + player.sendMessage("You can exit the wizard by typing quit into the chat."); + stateMachine.resumeInstallation(player); + } + if (player.hasPermission("essentials.update") && !updateCheck.isEssentialsInstalled()) + { + player.sendMessage("Hello " + player.getDisplayName()); + player.sendMessage("Please type /essentialsupdate into the chat to start the installation of Essentials."); + } + if (player.hasPermission("essentials.update")) + { + final UpdateCheck.CheckResult result = updateCheck.getResult(); + switch (result) + { + case NEW_ESS: + player.sendMessage("The new version " + updateCheck.getNewVersion().toString() + " for Essentials is available. Please type /essentialsupdate to update."); + break; + case NEW_BUKKIT: + player.sendMessage("Your bukkit version is not the recommended build for Essentials, please update to version " + updateCheck.getNewBukkitVersion() + "."); + break; + case NEW_ESS_BUKKIT: + player.sendMessage("There is a new version " + updateCheck.getNewVersion().toString() + " of Essentials for Bukkit " + updateCheck.getNewBukkitVersion()); + break; + default: + } + } + } + + public void onCommand(final CommandSender sender) + { + if (sender instanceof Player && sender.hasPermission("essentials.update")) + { + if (currentPlayer == null) + { + currentPlayer = (Player)sender; + if (selfUpdate()) + { + return; + } + stateMachine = new StateMachine(plugin, currentPlayer, updateCheck); + final StateMachine.MachineResult result = stateMachine.askQuestion(); + if (result == StateMachine.MachineResult.DONE) + { + startWork(); + } + } + if (!currentPlayer.equals(sender)) + { + sender.sendMessage("The player " + currentPlayer.getDisplayName() + " is already using the wizard."); + } + } + else + { + sender.sendMessage("Please run the command as op from in game."); + } + } + + private void startWork() + { + currentPlayer.sendMessage("Installation wizard done. Starting installation."); + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() + { + @Override + public void run() + { + stateMachine.startWork(); + } + }); + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/Version.java b/EssentialsUpdate/src/net/ess3/update/Version.java new file mode 100644 index 000000000..84f62b6c8 --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/Version.java @@ -0,0 +1,173 @@ +package net.ess3.update; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + + +public class Version implements Comparable +{ + public enum Type + { + STABLE, PREVIEW, DEVELOPER + } + + public int getMajor() + { + return major; + } + + public int getMinor() + { + return minor; + } + + public int getBuild() + { + return build; + } + + public Type getType() + { + return type; + } + private final transient int major; + private final transient int minor; + private final transient int build; + private final transient Type type; + + public Version(final String versionString) + { + final Matcher matcher = Pattern.compile("(Pre|Dev)?([0-9]+)[_\\.]([0-9]+)[_\\.]([0-9]+).*").matcher(versionString); + if (!matcher.matches() || matcher.groupCount() < 4) + { + type = Type.DEVELOPER; + major = 99; + minor = build = 0; + return; + } + if (versionString.startsWith("Pre")) + { + type = Type.PREVIEW; + } + else if (versionString.startsWith("Dev")) + { + type = Type.DEVELOPER; + } + else + { + type = Type.STABLE; + } + major = Integer.parseInt(matcher.group(2)); + minor = Integer.parseInt(matcher.group(3)); + build = Integer.parseInt(matcher.group(4)); + } + + @Override + public int compareTo(final Version other) + { + int ret = 0; + if (other.getType() == Type.DEVELOPER && getType() != Type.DEVELOPER) + { + ret = -1; + } + else if (getType() == Type.DEVELOPER && other.getType() != Type.DEVELOPER) + { + ret = 1; + } + else if (other.getMajor() > getMajor()) + { + ret = -1; + } + else if (getMajor() > other.getMajor()) + { + ret = 1; + } + else if (other.getMinor() > getMinor()) + { + ret = -1; + } + else if (getMinor() > other.getMinor()) + { + ret = 1; + } + else if (other.getBuild() > getBuild()) + { + ret = -1; + } + else if (getBuild() > other.getBuild()) + { + ret = 1; + } + else if (other.getType() == Type.STABLE && getType() == Type.PREVIEW) + { + ret = -1; + } + else if (getType() == Type.STABLE && other.getType() == Type.PREVIEW) + { + ret = 1; + } + return ret; + } + + @Override + public boolean equals(final Object obj) + { + if (obj == null) + { + return false; + } + if (getClass() != obj.getClass()) + { + return false; + } + final Version other = (Version)obj; + if (this.major != other.major) + { + return false; + } + if (this.minor != other.minor) + { + return false; + } + if (this.build != other.build) + { + return false; + } + if (this.type != other.type) + { + return false; + } + return true; + } + + @Override + public int hashCode() + { + int hash = 5; + hash = 71 * hash + this.major; + hash = 71 * hash + this.minor; + hash = 71 * hash + this.build; + hash = 71 * hash + (this.type == null ? 0 : this.type.hashCode()); + return hash; + } + + @Override + public String toString() + { + final StringBuilder builder = new StringBuilder(); + if (type == Type.DEVELOPER) + { + builder.append("Dev"); + } + if (type == Type.PREVIEW) + { + builder.append("Pre"); + } + builder.append(major); + builder.append('.'); + builder.append(minor); + builder.append('.'); + builder.append(build); + return builder.toString(); + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/VersionInfo.java b/EssentialsUpdate/src/net/ess3/update/VersionInfo.java new file mode 100644 index 000000000..afbe87de8 --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/VersionInfo.java @@ -0,0 +1,49 @@ +package net.ess3.update; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.bukkit.configuration.Configuration; + + +public class VersionInfo +{ + private final transient List changelog; + private final transient int minBukkit; + private final transient int maxBukkit; + private final transient Map modules; + + public VersionInfo(final Configuration updateConfig, final String path) + { + changelog = updateConfig.getStringList(path + ".changelog"); + minBukkit = updateConfig.getInt(path + ".min-bukkit", 0); + maxBukkit = updateConfig.getInt(path + ".max-bukkit", 0); + modules = new HashMap(); + final String modulesPath = path + ".modules"; + for (String module : updateConfig.getKeys(false)) + { + modules.put(module, new ModuleInfo(updateConfig, modulesPath + module)); + } + } + + public List getChangelog() + { + return Collections.unmodifiableList(changelog); + } + + public int getMinBukkit() + { + return minBukkit; + } + + public int getMaxBukkit() + { + return maxBukkit; + } + + public Map getModules() + { + return Collections.unmodifiableMap(modules); + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/chat/AbstractFileCommand.java b/EssentialsUpdate/src/net/ess3/update/chat/AbstractFileCommand.java new file mode 100644 index 000000000..2e6d44f20 --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/chat/AbstractFileCommand.java @@ -0,0 +1,75 @@ +package net.ess3.update.chat; + +import net.ess3.update.PastieUpload; +import java.io.*; +import java.nio.charset.Charset; + +import net.ess3.update.PastieUpload; +import org.bukkit.plugin.Plugin; + + +public abstract class AbstractFileCommand implements Command +{ + private final transient Plugin plugin; + private final static Charset UTF8 = Charset.forName("utf-8"); + + public AbstractFileCommand(final Plugin plugin) + { + this.plugin = plugin; + } + + protected BufferedReader getServerLogReader() throws IOException + { + final File bukkitFolder = plugin.getDataFolder().getAbsoluteFile().getParentFile().getParentFile(); + if (bukkitFolder == null || !bukkitFolder.exists()) + { + throw new IOException("Bukkit folder not found."); + } + final File logFile = new File(bukkitFolder, "server.log"); + if (!logFile.exists()) + { + throw new IOException("Server log not found."); + } + final FileInputStream fis = new FileInputStream(logFile); + try + { + if (logFile.length() > 1000000) + { + fis.skip(logFile.length() - 1000000); + } + return new BufferedReader(new InputStreamReader(fis)); + } + catch (IOException ex) + { + fis.close(); + throw ex; + } + } + + protected BufferedReader getPluginConfig(final String pluginName, final String fileName) throws IOException + { + final File configFolder = new File(plugin.getDataFolder().getAbsoluteFile().getParentFile(), pluginName); + if (!configFolder.exists()) + { + throw new IOException(pluginName + " plugin folder not found."); + } + final File configFile = new File(configFolder, fileName); + if (!configFile.exists()) + { + throw new IOException(pluginName + " plugin file " + fileName + " not found."); + } + return new BufferedReader(new InputStreamReader(new FileInputStream(configFile), UTF8)); + + } + + protected String uploadToPastie(final StringBuilder input) throws IOException + { + if (input.length() > 15000) + { + input.delete(0, input.length() - 15000); + input.append("## Cropped after 15000 bytes"); + } + final PastieUpload pastie = new PastieUpload(); + return pastie.send(input.toString()); + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/chat/Command.java b/EssentialsUpdate/src/net/ess3/update/chat/Command.java new file mode 100644 index 000000000..1e7e94e1c --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/chat/Command.java @@ -0,0 +1,9 @@ +package net.ess3.update.chat; + +import org.bukkit.entity.Player; + + +public interface Command +{ + void run(final IrcBot ircBot, final Player player); +} diff --git a/EssentialsUpdate/src/net/ess3/update/chat/ConfigCommand.java b/EssentialsUpdate/src/net/ess3/update/chat/ConfigCommand.java new file mode 100644 index 000000000..913294b01 --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/chat/ConfigCommand.java @@ -0,0 +1,65 @@ +package net.ess3.update.chat; + +import java.io.BufferedReader; +import java.io.IOException; +import java.util.logging.Level; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + + +public class ConfigCommand extends AbstractFileCommand implements Command +{ + public ConfigCommand(final Plugin plugin) + { + super(plugin); + } + + @Override + public void run(final IrcBot ircBot, final Player player) + { + BufferedReader page = null; + try + { + page = getPluginConfig("Essentials-3", "config.yml"); + final StringBuilder input = new StringBuilder(); + do + { + final String line = page.readLine(); + if (line == null) + { + break; + } + else + { + input.append(line).append("\n"); + } + } + while (true); + page.close(); + final String message = "Essentials config.yml: " + uploadToPastie(input); + player.sendMessage("§6" + ircBot.getNick() + ": §7" + message); + ircBot.sendMessage(message); + } + catch (IOException ex) + { + Bukkit.getLogger().log(Level.SEVERE, null, ex); + player.sendMessage(ex.getMessage()); + } + finally + { + try + { + if (page != null) + { + page.close(); + } + } + catch (IOException ex) + { + Bukkit.getLogger().log(Level.SEVERE, null, ex); + player.sendMessage(ex.getMessage()); + } + } + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/chat/ErrorsCommand.java b/EssentialsUpdate/src/net/ess3/update/chat/ErrorsCommand.java new file mode 100644 index 000000000..6e3c29924 --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/chat/ErrorsCommand.java @@ -0,0 +1,71 @@ +package net.ess3.update.chat; + +import java.io.BufferedReader; +import java.io.IOException; +import java.util.logging.Level; +import java.util.regex.Pattern; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + + +public class ErrorsCommand extends AbstractFileCommand implements Command +{ + private final transient Pattern pattern = Pattern.compile("^[0-9 :-]+\\[INFO\\].*"); + + public ErrorsCommand(final Plugin plugin) + { + super(plugin); + } + + @Override + public void run(final IrcBot ircBot, final Player player) + { + BufferedReader page = null; + try + { + page = getServerLogReader(); + final StringBuilder input = new StringBuilder(); + do + { + final String line = page.readLine(); + if (line == null) + { + break; + } + else + { + if (!pattern.matcher(line).matches()) + { + input.append(line).append("\n"); + } + } + } + while (true); + page.close(); + final String message = "Errors: " + uploadToPastie(input); + player.sendMessage("§6" + ircBot.getNick() + ": §7" + message); + ircBot.sendMessage(message); + } + catch (IOException ex) + { + Bukkit.getLogger().log(Level.SEVERE, null, ex); + player.sendMessage(ex.getMessage()); + } + finally + { + try + { + if (page != null) + { + page.close(); + } + } + catch (IOException ex) + { + Bukkit.getLogger().log(Level.SEVERE, null, ex); + player.sendMessage(ex.getMessage()); + } + } + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/chat/HelpCommand.java b/EssentialsUpdate/src/net/ess3/update/chat/HelpCommand.java new file mode 100644 index 000000000..1e82953f0 --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/chat/HelpCommand.java @@ -0,0 +1,18 @@ +package net.ess3.update.chat; + +import org.bukkit.entity.Player; + + +public class HelpCommand implements Command +{ + @Override + public void run(final IrcBot ircBot, final Player player) + { + player.sendMessage("Commands: (Note: Files send to the chat will be public viewable.)"); + player.sendMessage("!errors - Send the last server errors to the chat."); + player.sendMessage("!startup - Send the last startup messages to the chat."); + player.sendMessage("!config - Sends your Essentials config to the chat."); + player.sendMessage("!list - List all players in chat."); + player.sendMessage("!quit - Leave chat."); + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/chat/IrcBot.java b/EssentialsUpdate/src/net/ess3/update/chat/IrcBot.java new file mode 100644 index 000000000..10ce9ad8a --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/chat/IrcBot.java @@ -0,0 +1,197 @@ +package net.ess3.update.chat; + +import java.io.IOException; +import java.util.logging.Level; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.jibble.pircbot.Colors; +import org.jibble.pircbot.IrcException; +import org.jibble.pircbot.PircBot; +import org.jibble.pircbot.User; + + +public class IrcBot extends PircBot +{ + private static final String CHANNEL = "#essentials"; + private static final int PORT = 6667; + private static final String SERVER = "irc.esper.net"; + private transient boolean reconnect = true; + private final transient Player player; + private transient boolean kicked = false; + + public IrcBot(final Player player, final String nickName, final String versionString) + { + super(); + this.player = player; + setName(nickName); + setLogin("esshelp"); + setVersion(versionString); + connect(); + joinChannel(CHANNEL); + } + + private void connect() + { + try + { + connect(SERVER, PORT); + } + catch (IOException ex) + { + Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); + } + catch (IrcException ex) + { + Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); + } + } + + public void quit() + { + reconnect = false; + disconnect(); + } + + @Override + protected void onConnect() + { + reconnect = true; + } + + @Override + protected void onDisconnect() + { + if (reconnect) + { + int tries = 10; + while (!isConnected()) + { + try + { + tries--; + reconnect(); + } + catch (Exception e) + { + Bukkit.getLogger().log(Level.WARNING, e.getMessage(), e); + try + { + Thread.sleep(10000); + } + catch (InterruptedException ex) + { + Bukkit.getLogger().log(Level.WARNING, e.getMessage(), e); + } + } + if (tries <= 0) + { + player.sendMessage("Connection lost to server."); + kicked = true; + break; + } + } + } + } + + @Override + protected void onKick(final String channel, final String kickerNick, + final String kickerLogin, final String kickerHostname, + final String recipientNick, final String reason) + { + if (recipientNick.equals(getNick())) + { + player.sendMessage("You have been kicked from the channel: " + reason); + quit(); + kicked = true; + } + } + + public boolean isKicked() + { + return kicked; + } + + @Override + protected void onMessage(final String channel, final String sender, + final String login, final String hostname, + final String message) + { + player.sendMessage(formatChatMessage(sender, message, false)); + } + + @Override + protected void onAction(final String sender, final String login, + final String hostname, final String target, + final String action) + { + player.sendMessage(formatChatMessage(sender, action, true)); + } + + @Override + protected void onNotice(final String sourceNick, final String sourceLogin, + final String sourceHostname, final String target, + final String notice) + { + player.sendMessage(formatChatMessage(sourceNick, notice, false)); + } + + @Override + protected void onTopic(final String channel, final String topic, + final String setBy, final long date, + final boolean changed) + { + player.sendMessage(formatChatMessage(channel, topic, false)); + } + + public String formatChatMessage(final String nick, final String message, final boolean action) + { + final StringBuilder builder = new StringBuilder(); + builder.append("§6"); + if (action) + { + builder.append('*'); + } + builder.append(nick); + if (!action) + { + builder.append(':'); + } + builder.append(" §7"); + builder.append(replaceColors(message)); + return builder.toString(); + } + + private String replaceColors(final String message) + { + String m = Colors.removeFormatting(message); + m = m.replaceAll("\u000310(,(0?[0-9]|1[0-5]))?", "§b"); + m = m.replaceAll("\u000311(,(0?[0-9]|1[0-5]))?", "§f"); + m = m.replaceAll("\u000312(,(0?[0-9]|1[0-5]))?", "§9"); + m = m.replaceAll("\u000313(,(0?[0-9]|1[0-5]))?", "§d"); + m = m.replaceAll("\u000314(,(0?[0-9]|1[0-5]))?", "§8"); + m = m.replaceAll("\u000315(,(0?[0-9]|1[0-5]))?", "§7"); + m = m.replaceAll("\u00030?1(,(0?[0-9]|1[0-5]))?", "§0"); + m = m.replaceAll("\u00030?2(,(0?[0-9]|1[0-5]))?", "§1"); + m = m.replaceAll("\u00030?3(,(0?[0-9]|1[0-5]))?", "§2"); + m = m.replaceAll("\u00030?4(,(0?[0-9]|1[0-5]))?", "§c"); + m = m.replaceAll("\u00030?5(,(0?[0-9]|1[0-5]))?", "§4"); + m = m.replaceAll("\u00030?6(,(0?[0-9]|1[0-5]))?", "§5"); + m = m.replaceAll("\u00030?7(,(0?[0-9]|1[0-5]))?", "§6"); + m = m.replaceAll("\u00030?8(,(0?[0-9]|1[0-5]))?", "§e"); + m = m.replaceAll("\u00030?9(,(0?[0-9]|1[0-5]))?", "§a"); + m = m.replaceAll("\u00030?0(,(0?[0-9]|1[0-5]))?", "§f"); + m = m.replace("\u000f", "§7"); + m = Colors.removeColors(m); + return m; + } + + public void sendMessage(final String message) + { + sendMessage(CHANNEL, message); + } + + public User[] getUsers() + { + return getUsers(CHANNEL); + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/chat/ListCommand.java b/EssentialsUpdate/src/net/ess3/update/chat/ListCommand.java new file mode 100644 index 000000000..218b6631b --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/chat/ListCommand.java @@ -0,0 +1,32 @@ +package net.ess3.update.chat; + +import org.bukkit.entity.Player; +import org.jibble.pircbot.User; + + +public class ListCommand implements Command +{ + @Override + public void run(final IrcBot ircBot, final Player player) + { + final User[] members = ircBot.getUsers(); + final StringBuilder message = new StringBuilder(); + for (User user : members) + { + if (message.length() > 0) + { + message.append("§f, "); + } + if (user.isOp() || user.hasVoice()) + { + message.append("§6"); + } + else + { + message.append("§7"); + } + message.append(user.getPrefix()).append(user.getNick()); + } + player.sendMessage(message.toString()); + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/chat/StartupCommand.java b/EssentialsUpdate/src/net/ess3/update/chat/StartupCommand.java new file mode 100644 index 000000000..978da60c2 --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/chat/StartupCommand.java @@ -0,0 +1,77 @@ +package net.ess3.update.chat; + +import java.io.BufferedReader; +import java.io.IOException; +import java.util.logging.Level; +import java.util.regex.Pattern; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + + +public class StartupCommand extends AbstractFileCommand implements Command +{ + private final transient Pattern patternStart = Pattern.compile("^[0-9 :-]+\\[INFO\\] Starting minecraft server version.*"); + private final transient Pattern patternEnd = Pattern.compile("^[0-9 :-]+\\[INFO\\] Done \\([0-9.,]+s\\)! For help, type \"help\".*"); + + public StartupCommand(final Plugin plugin) + { + super(plugin); + } + + @Override + public void run(final IrcBot ircBot, final Player player) + { + BufferedReader page = null; + try + { + page = getServerLogReader(); + final StringBuilder input = new StringBuilder(); + String line; + boolean log = false; + while ((line = page.readLine()) != null) + { + if (patternStart.matcher(line).matches()) + { + if (input.length() > 0) + { + input.delete(0, input.length()); + } + log = true; + } + if (log) + { + input.append(line).append("\n"); + } + if (patternEnd.matcher(line).matches()) + { + log = false; + } + } + page.close(); + final String message = "Startup: " + uploadToPastie(input); + player.sendMessage("§6" + ircBot.getNick() + ": §7" + message); + ircBot.sendMessage(message); + } + catch (IOException ex) + { + Bukkit.getLogger().log(Level.SEVERE, null, ex); + player.sendMessage(ex.getMessage()); + } + finally + { + try + { + if (page != null) + { + page.close(); + } + } + catch (IOException ex) + { + Bukkit.getLogger().log(Level.SEVERE, null, ex); + player.sendMessage(ex.getMessage()); + } + } + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/chat/UsernameUtil.java b/EssentialsUpdate/src/net/ess3/update/chat/UsernameUtil.java new file mode 100644 index 000000000..e9dfdf728 --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/chat/UsernameUtil.java @@ -0,0 +1,124 @@ +package net.ess3.update.chat; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.bukkit.Bukkit; +import org.bukkit.Server; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + + +public final class UsernameUtil +{ + private static final Pattern CB_PATTERN = Pattern.compile("git-Bukkit-([0-9]+).([0-9]+).([0-9]+)-[0-9]+-[0-9a-z]+-b([0-9]+)jnks.*"); + + private UsernameUtil() + { + } + + public static String createUsername(final Player player) + { + final StringBuilder nameBuilder = new StringBuilder(); + final Server server = Bukkit.getServer(); + nameBuilder.append(player.getName()); + + addCraftBukkitVersion(server, nameBuilder); + addEssentialsVersion(server, nameBuilder); + addGroupManagerVersion(server, nameBuilder); + addPermissionsExVersion(server, nameBuilder); + addPermissionsBukkitVersion(server, nameBuilder); + addBPermissionsVersion(server, nameBuilder); + addPermissionsVersion(server, nameBuilder); + + return nameBuilder.toString(); + } + + private static void addPermissionsVersion(final Server server, final StringBuilder nameBuilder) + { + final Plugin perm = server.getPluginManager().getPlugin("Permissions"); + if (perm != null) + { + nameBuilder.append(" P"); + if (!perm.isEnabled()) + { + nameBuilder.append('!'); + } + nameBuilder.append(perm.getDescription().getVersion()); + } + } + + private static void addBPermissionsVersion(final Server server, final StringBuilder nameBuilder) + { + final Plugin bperm = server.getPluginManager().getPlugin("bPermissions"); + if (bperm != null) + { + nameBuilder.append(" BP"); + if (!bperm.isEnabled()) + { + nameBuilder.append('!'); + } + nameBuilder.append(bperm.getDescription().getVersion()); + } + } + + private static void addPermissionsBukkitVersion(final Server server, final StringBuilder nameBuilder) + { + final Plugin permb = server.getPluginManager().getPlugin("PermissionsBukkit"); + if (permb != null) + { + nameBuilder.append(" PB"); + if (!permb.isEnabled()) + { + nameBuilder.append('!'); + } + nameBuilder.append(permb.getDescription().getVersion()); + } + } + + private static void addPermissionsExVersion(final Server server, final StringBuilder nameBuilder) + { + final Plugin pex = server.getPluginManager().getPlugin("PermissionsEx"); + if (pex != null) + { + nameBuilder.append(" PEX"); + if (!pex.isEnabled()) + { + nameBuilder.append('!'); + } + nameBuilder.append(pex.getDescription().getVersion()); + } + } + + private static void addGroupManagerVersion(final Server server, final StringBuilder nameBuilder) + { + final Plugin groupManager = server.getPluginManager().getPlugin("GroupManager"); + if (groupManager != null) + { + nameBuilder.append(" GM"); + if (!groupManager.isEnabled()) + { + nameBuilder.append('!'); + } + } + } + + private static void addEssentialsVersion(final Server server, final StringBuilder nameBuilder) + { + final Plugin essentials = server.getPluginManager().getPlugin("Essentials-3"); + if (essentials != null) + { + nameBuilder.append(" ESS"); + nameBuilder.append(essentials.getDescription().getVersion()); + } + } + + private static void addCraftBukkitVersion(final Server server, final StringBuilder nameBuilder) + { + final Matcher versionMatch = CB_PATTERN.matcher(server.getVersion()); + if (versionMatch.matches()) + { + nameBuilder.append(" CB"); + nameBuilder.append(versionMatch.group(4)); + } + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/states/AbstractState.java b/EssentialsUpdate/src/net/ess3/update/states/AbstractState.java new file mode 100644 index 000000000..5d4e03a2c --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/states/AbstractState.java @@ -0,0 +1,115 @@ +package net.ess3.update.states; + +import net.ess3.update.AbstractWorkListener; +import net.ess3.update.AbstractWorkListener; +import org.bukkit.entity.Player; + + +public abstract class AbstractState +{ + private transient boolean abortion = false; + private final transient StateMap stateMap; + + public AbstractState(final StateMap stateMap) + { + this.stateMap = stateMap; + } + + public T getState(final Class stateClass) + { + if (!stateMap.containsKey(stateClass)) + { + try + { + final AbstractState state = stateClass.getConstructor(StateMap.class).newInstance(stateMap); + stateMap.put(stateClass, state); + } + catch (Exception ex) + { + /* + * This should never happen. All states, that are added to the map automatically, have to have a + * Constructor that accepts the StateMap. + */ + throw new RuntimeException(ex); + } + } + return (T)stateMap.get(stateClass); + } + + public abstract AbstractState getNextState(); + + /** + * Check if we already know the answer, so the user does not have to answer the question. + * + * @return true, if the answer could be guessed. + */ + public boolean guessAnswer() + { + return false; + } + + /** + * Ask the user the question. + * + * @param sender + */ + public abstract void askQuestion(Player sender); + + /** + * React on the answer and set internal variables + * + * @param answer + * @return true, if the answer could be recognized as a valid answer + */ + public abstract boolean reactOnAnswer(String answer); + + public final AbstractState reactOnAnswer(final Player sender, final String answer) + { + final String trimmedAnswer = answer.trim(); + if (trimmedAnswer.equalsIgnoreCase("quit") + || trimmedAnswer.equalsIgnoreCase("bye") + || trimmedAnswer.equalsIgnoreCase("abort") + || trimmedAnswer.equalsIgnoreCase("cancel") + || trimmedAnswer.equalsIgnoreCase("exit")) + { + abort(); + return null; + } + try + { + final boolean found = reactOnAnswer(trimmedAnswer); + if (found) + { + return getNextState(); + } + else + { + sender.sendMessage("Answer not recognized."); + return this; + } + } + catch (RuntimeException ex) + { + sender.sendMessage(ex.toString()); + return this; + } + } + + /** + * Do something based on the answer, that the user gave. + */ + public void doWork(final AbstractWorkListener listener) + { + listener.onWorkDone(); + } + + public boolean isAbortion() + { + return abortion; + } + + protected void abort() + { + abortion = true; + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/states/AbstractYesNoState.java b/EssentialsUpdate/src/net/ess3/update/states/AbstractYesNoState.java new file mode 100644 index 000000000..3ee7d0ee2 --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/states/AbstractYesNoState.java @@ -0,0 +1,57 @@ +package net.ess3.update.states; + + +public abstract class AbstractYesNoState extends AbstractState +{ + private boolean answer = false; + private final transient Class yesState; + private final transient Class noState; + + public AbstractYesNoState(final StateMap states, final Class nextState) + { + this(states, nextState, nextState); + } + + public AbstractYesNoState(final StateMap states, final Class yesState, final Class noState) + { + super(states); + this.yesState = yesState; + this.noState = noState; + } + + @Override + public AbstractState getNextState() + { + return answer + ? (yesState == null ? null : getState(yesState)) + : (noState == null ? null : getState(noState)); + } + + @Override + public boolean reactOnAnswer(final String answer) + { + if (answer.equalsIgnoreCase("yes") + || answer.equalsIgnoreCase("y")) + { + this.answer = true; + return true; + } + if (answer.equalsIgnoreCase("no") + || answer.equalsIgnoreCase("n")) + { + this.answer = false; + return true; + } + return false; + } + + public boolean getAnswer() + { + return answer; + } + + protected void setAnswer(final boolean answer) + { + this.answer = answer; + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/states/AdvancedMode.java b/EssentialsUpdate/src/net/ess3/update/states/AdvancedMode.java new file mode 100644 index 000000000..8ddf06eeb --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/states/AdvancedMode.java @@ -0,0 +1,20 @@ +package net.ess3.update.states; + +import org.bukkit.entity.Player; + + +public class AdvancedMode extends AbstractYesNoState +{ + public AdvancedMode(final StateMap states) + { + super(states, EssentialsChat.class); + } + + @Override + public void askQuestion(final Player sender) + { + sender.sendMessage("This installation mode has a lot of options."); + sender.sendMessage("Do you want use the advanced mode to see all questions?"); + sender.sendMessage("Otherwise the default values will be used."); + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/states/Changelog.java b/EssentialsUpdate/src/net/ess3/update/states/Changelog.java new file mode 100644 index 000000000..42fdc8ca2 --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/states/Changelog.java @@ -0,0 +1,91 @@ +package net.ess3.update.states; + +import net.ess3.update.UpdateCheck; +import net.ess3.update.VersionInfo; +import java.util.List; +import org.bukkit.entity.Player; + + +public class Changelog extends AbstractState +{ + private static final int CHANGES_PER_PAGE = 5; + private transient int page = 0; + private transient boolean confirmed = false; + private transient final List changes; + private transient final int pages; + + public Changelog(final StateMap stateMap) + { + super(stateMap); + changes = getChanges(); + pages = changes.size() / CHANGES_PER_PAGE + (changes.size() % CHANGES_PER_PAGE > 0 ? 1 : 0); + } + + @Override + public AbstractState getNextState() + { + return confirmed ? getState(EssentialsChat.class) : this; + } + + @Override + public boolean guessAnswer() + { + if (pages == 0) + { + confirmed = true; + } + return confirmed; + } + + private List getChanges() + { + final UpdateCheck updateCheck = getState(UpdateOrInstallation.class).getUpdateCheck(); + final VersionInfo versionInfo = updateCheck.getNewVersionInfo(); + return versionInfo.getChangelog(); + } + + @Override + public void askQuestion(final Player sender) + { + if (pages > 1) + { + sender.sendMessage("Changelog, page " + page + " of " + pages + ":"); + } + else + { + sender.sendMessage("Changelog:"); + } + for (int i = page * CHANGES_PER_PAGE; i < Math.min(page * CHANGES_PER_PAGE + CHANGES_PER_PAGE, changes.size()); i++) + { + sender.sendMessage(changes.get(i)); + } + if (pages > 1) + { + sender.sendMessage("Select a page by typing the numbers 1 to " + pages + " to view all changes and then type confirm or abort."); + } + else + { + sender.sendMessage("Type confirm to update Essentials or abort to cancel the update."); + } + } + + @Override + public boolean reactOnAnswer(final String answer) + { + if (answer.equalsIgnoreCase("confirm")) + { + confirmed = true; + return true; + } + if (answer.matches("[0-9]+")) + { + final int page = Integer.parseInt(answer); + if (page <= pages && page > 0) + { + this.page = page - 1; + return true; + } + } + return false; + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/states/EssentialsChat.java b/EssentialsUpdate/src/net/ess3/update/states/EssentialsChat.java new file mode 100644 index 000000000..a62735f5e --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/states/EssentialsChat.java @@ -0,0 +1,47 @@ +package net.ess3.update.states; + +import net.ess3.update.AbstractWorkListener; +import net.ess3.update.tasks.InstallModule; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + + +public class EssentialsChat extends AbstractYesNoState +{ + public EssentialsChat(final StateMap states) + { + super(states, EssentialsChatSettings.class); + } + + @Override + public boolean guessAnswer() + { + final Plugin plugin = Bukkit.getPluginManager().getPlugin("EssentialsChat"); + if (plugin != null) + { + setAnswer(true); + return true; + } + return false; + } + + @Override + public void askQuestion(final Player sender) + { + sender.sendMessage("Do you want to install EssentialsChat? (yes/no)"); + sender.sendMessage("EssentialsChat is a simple chat formatting plugin"); + sender.sendMessage("It allows you to make user prefixes and coloured text."); + } + + @Override + public void doWork(final AbstractWorkListener listener) + { + if (getAnswer()) + { + new InstallModule(listener, "EssentialsChat").start(); + return; + } + listener.onWorkDone(); + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/states/EssentialsChatSettings.java b/EssentialsUpdate/src/net/ess3/update/states/EssentialsChatSettings.java new file mode 100644 index 000000000..db3202ab3 --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/states/EssentialsChatSettings.java @@ -0,0 +1,29 @@ +package net.ess3.update.states; + +import org.bukkit.entity.Player; + + +public class EssentialsChatSettings extends AbstractYesNoState +{ + public EssentialsChatSettings(final StateMap states) + { + super(states, null); + } + + @Override + public boolean guessAnswer() + { + if (getState(AdvancedMode.class).getAnswer()) + { + setAnswer(false); + return true; + } + return false; + } + + @Override + public void askQuestion(final Player sender) + { + sender.sendMessage("Would you like to configure EssentialsChat to prefix ingame messages with their group?"); + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/states/EssentialsGeoIP.java b/EssentialsUpdate/src/net/ess3/update/states/EssentialsGeoIP.java new file mode 100644 index 000000000..cd1865b42 --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/states/EssentialsGeoIP.java @@ -0,0 +1,48 @@ +package net.ess3.update.states; + +import net.ess3.update.AbstractWorkListener; +import net.ess3.update.tasks.InstallModule; +import net.ess3.update.AbstractWorkListener; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + + +public class EssentialsGeoIP extends AbstractYesNoState +{ + public EssentialsGeoIP(final StateMap states) + { + super(states, null); + } + + @Override + public boolean guessAnswer() + { + final Plugin plugin = Bukkit.getPluginManager().getPlugin("EssentialsGeoIP"); + if (plugin != null) + { + setAnswer(true); + return true; + } + return false; + } + + @Override + public void askQuestion(final Player sender) + { + sender.sendMessage("Do you want to install EssentialsGeoIP? (yes/no)"); + sender.sendMessage("EssentialsGeoIP performs a IP lookup on joining players"); + sender.sendMessage("It allows you get a rough idea of where a player is from."); + } + + @Override + public void doWork(final AbstractWorkListener listener) + { + if (getAnswer()) + { + new InstallModule(listener, "EssentialsGeoIP").start(); + return; + } + listener.onWorkDone(); + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/states/EssentialsProtect.java b/EssentialsUpdate/src/net/ess3/update/states/EssentialsProtect.java new file mode 100644 index 000000000..bb3a841a7 --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/states/EssentialsProtect.java @@ -0,0 +1,48 @@ +package net.ess3.update.states; + +import net.ess3.update.AbstractWorkListener; +import net.ess3.update.tasks.InstallModule; +import net.ess3.update.AbstractWorkListener; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + + +public class EssentialsProtect extends AbstractYesNoState +{ + public EssentialsProtect(final StateMap states) + { + super(states, null); + } + + @Override + public boolean guessAnswer() + { + final Plugin plugin = Bukkit.getPluginManager().getPlugin("EssentialsProtect"); + if (plugin != null) + { + setAnswer(true); + return true; + } + return false; + } + + @Override + public void askQuestion(final Player sender) + { + sender.sendMessage("Do you want to install EssentialsProtect? (yes/no)"); + sender.sendMessage("EssentialsProtect is a basic world protection system"); + sender.sendMessage("It allows you to set server wide rules, such as disabling creeper explosions, and preventing fire spread."); + } + + @Override + public void doWork(final AbstractWorkListener listener) + { + if (getAnswer()) + { + new InstallModule(listener, "EssentialsProtect").start(); + return; + } + listener.onWorkDone(); + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/states/InstallationFinishedEvent.java b/EssentialsUpdate/src/net/ess3/update/states/InstallationFinishedEvent.java new file mode 100644 index 000000000..5c38db7ee --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/states/InstallationFinishedEvent.java @@ -0,0 +1,21 @@ +package net.ess3.update.states; + +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + + +public class InstallationFinishedEvent extends Event +{ + private static final HandlerList handlers = new HandlerList(); + + @Override + public HandlerList getHandlers() + { + return handlers; + } + + public static HandlerList getHandlerList() + { + return handlers; + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/states/StateMachine.java b/EssentialsUpdate/src/net/ess3/update/states/StateMachine.java new file mode 100644 index 000000000..b66ca4c58 --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/states/StateMachine.java @@ -0,0 +1,185 @@ +package net.ess3.update.states; + +import net.ess3.update.AbstractWorkListener; +import net.ess3.update.UpdateCheck; +import java.util.Iterator; + +import net.ess3.update.UpdateCheck; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + + +public class StateMachine extends AbstractWorkListener implements Runnable +{ + public enum MachineResult + { + ABORT, WAIT, DONE, NONE + } + private final transient StateMap states = new StateMap(); + private transient AbstractState current; + private transient Player player; + private transient MachineResult result = MachineResult.NONE; + + public StateMachine(final Plugin plugin, final Player player, final UpdateCheck updateCheck) + { + super(plugin, updateCheck.getNewVersionInfo()); + this.player = player; + states.clear(); + final UpdateOrInstallation state = new UpdateOrInstallation(states, updateCheck); + current = states.put(UpdateOrInstallation.class, state); + } + + public MachineResult askQuestion() + { + try + { + while (current.guessAnswer()) + { + current = current.getNextState(); + if (current == null) + { + result = MachineResult.DONE; + break; + } + } + if (current != null) + { + if (player.isOnline()) + { + current.askQuestion(player); + } + result = MachineResult.WAIT; + } + } + catch (RuntimeException ex) + { + player.sendMessage(ex.getMessage()); + finish(); + result = MachineResult.ABORT; + } + return result; + } + + public MachineResult reactOnMessage(final String message) + { + result = MachineResult.NONE; + final AbstractState next = current.reactOnAnswer(player, message); + if (next == null) + { + if (current.isAbortion()) + { + finish(); + result = MachineResult.ABORT; + } + else + { + result = MachineResult.DONE; + } + } + else + { + current = next; + askQuestion(); + } + return result; + } + private transient Iterator iterator; + + public void startWork() + { + iterator = states.values().iterator(); + Bukkit.getScheduler().scheduleAsyncDelayedTask(getPlugin(), this); + } + + @Override + public void run() + { + if (!iterator.hasNext()) + { + Bukkit.getScheduler().scheduleSyncDelayedTask(getPlugin(), new Runnable() + { + @Override + public void run() + { + if (StateMachine.this.player.isOnline()) + { + StateMachine.this.player.sendMessage("Installation done. Reloading server."); + } + finish(); + Bukkit.getServer().reload(); + } + }); + return; + } + final AbstractState state = iterator.next(); + state.doWork(this); + } + + @Override + public void onWorkAbort(final String message) + { + finish(); + Bukkit.getScheduler().scheduleSyncDelayedTask(getPlugin(), new Runnable() + { + @Override + public void run() + { + if (message != null && !message.isEmpty() && StateMachine.this.player.isOnline()) + { + StateMachine.this.player.sendMessage(message); + } + } + }); + } + + @Override + public void onWorkDone(final String message) + { + Bukkit.getScheduler().scheduleSyncDelayedTask(getPlugin(), new Runnable() + { + @Override + public void run() + { + if (message != null && !message.isEmpty() && StateMachine.this.player.isOnline()) + { + StateMachine.this.player.sendMessage(message); + } + Bukkit.getScheduler().scheduleAsyncDelayedTask(getPlugin(), StateMachine.this); + } + }); + } + + private void finish() + { + current = null; + iterator = null; + states.clear(); + getPlugin().getServer().getPluginManager().callEvent(new InstallationFinishedEvent()); + } + + public void resumeInstallation(final Player player) + { + this.player = player; + if (result == MachineResult.WAIT) + { + if (current == null) + { + throw new RuntimeException("State is WAIT, but current state is null!"); + } + current.askQuestion(player); + } + if (result == MachineResult.DONE && iterator != null) + { + player.sendMessage("Installation is still running."); + } + if (result == MachineResult.ABORT) + { + throw new RuntimeException("Player should not be able to resume an aborted installation."); + } + if (result == MachineResult.NONE) + { + throw new RuntimeException("State machine in an undefined state."); + } + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/states/StateMap.java b/EssentialsUpdate/src/net/ess3/update/states/StateMap.java new file mode 100644 index 000000000..397ef7c81 --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/states/StateMap.java @@ -0,0 +1,12 @@ +package net.ess3.update.states; + +import java.util.LinkedHashMap; + + +public class StateMap extends LinkedHashMap, AbstractState> +{ + public StateMap() + { + super(50); + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/states/UpdateOrInstallation.java b/EssentialsUpdate/src/net/ess3/update/states/UpdateOrInstallation.java new file mode 100644 index 000000000..c7bd5127a --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/states/UpdateOrInstallation.java @@ -0,0 +1,61 @@ +package net.ess3.update.states; + +import net.ess3.update.UpdateCheck; +import net.ess3.update.UpdateCheck; +import org.bukkit.entity.Player; + + +public class UpdateOrInstallation extends AbstractState +{ + private final transient UpdateCheck updateCheck; + private transient boolean update = false; + + public UpdateOrInstallation(final StateMap stateMap, final UpdateCheck updateCheck) + { + super(stateMap); + this.updateCheck = updateCheck; + } + + @Override + public boolean guessAnswer() + { + if (getUpdateCheck().isEssentialsInstalled()) + { + update = true; + } + return update; + } + + @Override + public AbstractState getNextState() + { + return update ? getState(Changelog.class) : getState(EssentialsChat.class); + } + + @Override + public void askQuestion(final Player sender) + { + sender.sendMessage("Thank you for choosing Essentials."); + sender.sendMessage("The following installation wizard will guide you through the installation of Essentials."); + sender.sendMessage("Your answers will be saved for a later update."); + sender.sendMessage("Please answer the messages with yes or no, if not otherwise stated."); + sender.sendMessage("Write bye/exit/quit if you want to exit the wizard at anytime."); + sender.sendMessage("Type ok to continue..."); + } + + @Override + public boolean reactOnAnswer(final String answer) + { + return answer.equalsIgnoreCase("ok") || answer.equalsIgnoreCase("k") || answer.equalsIgnoreCase("continue"); + } + + public UpdateCheck getUpdateCheck() + { + return updateCheck; + } + + public boolean isUpdate() + { + return update; + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/tasks/InstallModule.java b/EssentialsUpdate/src/net/ess3/update/tasks/InstallModule.java new file mode 100644 index 000000000..1f7742026 --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/tasks/InstallModule.java @@ -0,0 +1,65 @@ +package net.ess3.update.tasks; + +import net.ess3.update.AbstractWorkListener; +import net.ess3.update.GetFile; +import net.ess3.update.AbstractWorkListener; +import net.ess3.update.GetFile; +import net.ess3.update.ModuleInfo; +import net.ess3.update.VersionInfo; +import java.io.File; +import java.net.URL; +import java.util.logging.Level; + +import net.ess3.update.VersionInfo; +import org.bukkit.Bukkit; + + +public class InstallModule implements Runnable, Task +{ + protected final transient AbstractWorkListener listener; + private final transient String moduleName; + private final transient String fileName; + + public InstallModule(final AbstractWorkListener listener, final String moduleName) + { + this(listener, moduleName, moduleName + ".jar"); + } + + public InstallModule(final AbstractWorkListener listener, final String moduleName, final String fileName) + { + this.listener = listener; + this.moduleName = moduleName; + this.fileName = fileName; + } + + @Override + public void start() + { + Bukkit.getScheduler().scheduleAsyncDelayedTask(listener.getPlugin(), this); + } + + @Override + public void run() + { + final VersionInfo info = listener.getNewVersionInfo(); + final ModuleInfo module = info.getModules().get(moduleName); + if (module == null) + { + listener.onWorkAbort("Module " + moduleName + " not found in VersionInfo."); + return; + } + try + { + final URL downloadUrl = module.getUrl(); + final GetFile getFile = new GetFile(downloadUrl); + getFile.saveTo(new File(listener.getPlugin().getServer().getUpdateFolderFile(), fileName), module.getHash()); + listener.onWorkDone("Module " + moduleName + " downloaded."); + } + catch (Exception ex) + { + Bukkit.getLogger().log(Level.SEVERE, "Failed to download module " + moduleName + " to " + fileName, ex); + listener.onWorkAbort("An error occured, please check your server log."); + return; + } + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/tasks/SelfUpdate.java b/EssentialsUpdate/src/net/ess3/update/tasks/SelfUpdate.java new file mode 100644 index 000000000..bc0d65b5e --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/tasks/SelfUpdate.java @@ -0,0 +1,56 @@ +package net.ess3.update.tasks; + +import net.ess3.update.AbstractWorkListener; +import net.ess3.update.AbstractWorkListener; +import org.bukkit.Bukkit; + + +public class SelfUpdate extends AbstractWorkListener implements Task, Runnable +{ + private final transient AbstractWorkListener listener; + + public SelfUpdate(final AbstractWorkListener listener) + { + super(listener.getPlugin(), listener.getNewVersionInfo()); + this.listener = listener; + } + + @Override + public void onWorkAbort(final String message) + { + listener.onWorkAbort(message); + } + + @Override + public void onWorkDone(final String message) + { + listener.onWorkDone(message); + Bukkit.getScheduler().scheduleSyncDelayedTask(getPlugin(), new Runnable() + { + @Override + public void run() + { + Bukkit.getServer().reload(); + } + }); + } + + @Override + public void start() + { + Bukkit.getScheduler().scheduleSyncDelayedTask(getPlugin(), this); + } + + @Override + public void run() + { + Bukkit.getScheduler().scheduleAsyncDelayedTask(getPlugin(), new Runnable() + { + @Override + public void run() + { + new InstallModule(SelfUpdate.this, "EssentialsUpdate").start(); + } + }); + } +} diff --git a/EssentialsUpdate/src/net/ess3/update/tasks/Task.java b/EssentialsUpdate/src/net/ess3/update/tasks/Task.java new file mode 100644 index 000000000..0dc421446 --- /dev/null +++ b/EssentialsUpdate/src/net/ess3/update/tasks/Task.java @@ -0,0 +1,7 @@ +package net.ess3.update.tasks; + + +public interface Task +{ + void start(); +} diff --git a/EssentialsUpdate/src/plugin.yml b/EssentialsUpdate/src/plugin.yml index 4e7700711..c2811ad63 100644 --- a/EssentialsUpdate/src/plugin.yml +++ b/EssentialsUpdate/src/plugin.yml @@ -1,6 +1,6 @@ # This determines the command prefix when there are conflicts (/name:home, /name:help, etc.) name: EssentialsUpdate -main: com.earth2me.essentials.update.EssentialsUpdate +main: net.ess3.update.EssentialsUpdate # Note to developers: This next line cannot change, or the automatic versioning system will break. version: ${build.number} description: This plugin allows to install or update all Essentials plugins diff --git a/EssentialsUpdate/test/com/earth2me/essentials/update/UploadTest.java b/EssentialsUpdate/test/com/earth2me/essentials/update/UploadTest.java deleted file mode 100644 index a51f03bd7..000000000 --- a/EssentialsUpdate/test/com/earth2me/essentials/update/UploadTest.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.earth2me.essentials.update; - -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; -import junit.framework.TestCase; -import org.junit.Test; - - -public class UploadTest extends TestCase -{ - @Test - public void testPastieUpload() - { - try - { - final PastieUpload pastie = new PastieUpload(); - assertNotNull(pastie); - //final String url = pastie.send("test"); - //System.out.println(url); - } - catch (IOException ex) - { - Logger.getLogger(UploadTest.class.getName()).log(Level.SEVERE, null, ex); - } - } -} diff --git a/EssentialsUpdate/test/com/earth2me/essentials/update/VersionTest.java b/EssentialsUpdate/test/com/earth2me/essentials/update/VersionTest.java deleted file mode 100644 index d77e53542..000000000 --- a/EssentialsUpdate/test/com/earth2me/essentials/update/VersionTest.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.earth2me.essentials.update; - -import com.earth2me.essentials.update.Version.Type; -import java.util.TreeSet; -import junit.framework.TestCase; -import org.junit.Test; - - -public class VersionTest extends TestCase -{ - @Test - public void testStable() - { - final Version instance = new Version("1.2.3"); - assertEquals("Testing Major", 1, instance.getMajor()); - assertEquals("Testing Minor", 2, instance.getMinor()); - assertEquals("Testing Build", 3, instance.getBuild()); - assertEquals("Testing Type", Type.STABLE, instance.getType()); - } - - @Test - public void testDev() - { - final Version instance = new Version("Dev2.3.4"); - assertEquals("Testing Major", 2, instance.getMajor()); - assertEquals("Testing Minor", 3, instance.getMinor()); - assertEquals("Testing Build", 4, instance.getBuild()); - assertEquals("Testing Type", Type.DEVELOPER, instance.getType()); - } - - @Test - public void testTeamCity() - { - final Version instance = new Version("Unknown"); - assertEquals("Testing Type", Type.DEVELOPER, instance.getType()); - } - - @Test - public void testPre() - { - final Version instance = new Version("Pre5.7.400.2"); - assertEquals("Testing Major", 5, instance.getMajor()); - assertEquals("Testing Minor", 7, instance.getMinor()); - assertEquals("Testing Build", 400, instance.getBuild()); - assertEquals("Testing Type", Type.PREVIEW, instance.getType()); - } - - @Test - public void testCompareTo() - { - final Version verA = new Version("1.1.1"); - final Version verB = new Version("Dev1.1.2"); - final Version verC = new Version("1.1.2"); - final Version verD = new Version("1.2.0"); - final Version verE = new Version("2.0.0"); - final Version verF = new Version("Pre1.1.1.1"); - final Version verG = new Version("Dev1.2.2"); - assertTrue("Testing dev", verA.compareTo(verB) < 0); - assertTrue("Testing dev", verB.compareTo(verA) > 0); - assertTrue("Testing build", verA.compareTo(verC) < 0); - assertTrue("Testing build", verC.compareTo(verA) > 0); - assertTrue("Testing minor", verA.compareTo(verD) < 0); - assertTrue("Testing minor", verD.compareTo(verA) > 0); - assertTrue("Testing major", verA.compareTo(verE) < 0); - assertTrue("Testing major", verE.compareTo(verA) > 0); - assertTrue("Testing pre", verF.compareTo(verA) < 0); - assertTrue("Testing pre", verA.compareTo(verF) > 0); - assertTrue("Testing dev vs dev", verB.compareTo(verG) < 0); - assertTrue("Testing dev vs dev", verG.compareTo(verB) > 0); - final TreeSet set = new TreeSet(); - set.add(verA); - set.add(verB); - set.add(verC); - set.add(verD); - set.add(verE); - set.add(verF); - set.add(verG); - assertEquals("Testing sorting", verF, set.pollFirst()); - assertEquals("Testing sorting", verA, set.pollFirst()); - assertEquals("Testing sorting", verC, set.pollFirst()); - assertEquals("Testing sorting", verD, set.pollFirst()); - assertEquals("Testing sorting", verE, set.pollFirst()); - assertEquals("Testing sorting", verB, set.pollFirst()); - assertEquals("Testing sorting", verG, set.pollFirst()); - } -} diff --git a/EssentialsUpdate/test/com/ess3/update/UploadTest.java b/EssentialsUpdate/test/com/ess3/update/UploadTest.java new file mode 100644 index 000000000..4b26e644a --- /dev/null +++ b/EssentialsUpdate/test/com/ess3/update/UploadTest.java @@ -0,0 +1,28 @@ +package com.ess3.update; + +import java.io.IOException; +import java.util.logging.Level; +import java.util.logging.Logger; +import junit.framework.TestCase; +import net.ess3.update.PastieUpload; +import org.junit.Test; + + +public class UploadTest extends TestCase +{ + @Test + public void testPastieUpload() + { + try + { + final PastieUpload pastie = new PastieUpload(); + assertNotNull(pastie); + //final String url = pastie.send("test"); + //System.out.println(url); + } + catch (IOException ex) + { + Logger.getLogger(UploadTest.class.getName()).log(Level.SEVERE, null, ex); + } + } +} diff --git a/EssentialsUpdate/test/com/ess3/update/VersionTest.java b/EssentialsUpdate/test/com/ess3/update/VersionTest.java new file mode 100644 index 000000000..af35dc2dd --- /dev/null +++ b/EssentialsUpdate/test/com/ess3/update/VersionTest.java @@ -0,0 +1,87 @@ +package com.ess3.update; + +import net.ess3.update.Version.Type; +import java.util.TreeSet; +import junit.framework.TestCase; +import net.ess3.update.Version; +import org.junit.Test; + + +public class VersionTest extends TestCase +{ + @Test + public void testStable() + { + final Version instance = new Version("1.2.3"); + assertEquals("Testing Major", 1, instance.getMajor()); + assertEquals("Testing Minor", 2, instance.getMinor()); + assertEquals("Testing Build", 3, instance.getBuild()); + assertEquals("Testing Type", Type.STABLE, instance.getType()); + } + + @Test + public void testDev() + { + final Version instance = new Version("Dev2.3.4"); + assertEquals("Testing Major", 2, instance.getMajor()); + assertEquals("Testing Minor", 3, instance.getMinor()); + assertEquals("Testing Build", 4, instance.getBuild()); + assertEquals("Testing Type", Type.DEVELOPER, instance.getType()); + } + + @Test + public void testTeamCity() + { + final Version instance = new Version("Unknown"); + assertEquals("Testing Type", Type.DEVELOPER, instance.getType()); + } + + @Test + public void testPre() + { + final Version instance = new Version("Pre5.7.400.2"); + assertEquals("Testing Major", 5, instance.getMajor()); + assertEquals("Testing Minor", 7, instance.getMinor()); + assertEquals("Testing Build", 400, instance.getBuild()); + assertEquals("Testing Type", Type.PREVIEW, instance.getType()); + } + + @Test + public void testCompareTo() + { + final Version verA = new Version("1.1.1"); + final Version verB = new Version("Dev1.1.2"); + final Version verC = new Version("1.1.2"); + final Version verD = new Version("1.2.0"); + final Version verE = new Version("2.0.0"); + final Version verF = new Version("Pre1.1.1.1"); + final Version verG = new Version("Dev1.2.2"); + assertTrue("Testing dev", verA.compareTo(verB) < 0); + assertTrue("Testing dev", verB.compareTo(verA) > 0); + assertTrue("Testing build", verA.compareTo(verC) < 0); + assertTrue("Testing build", verC.compareTo(verA) > 0); + assertTrue("Testing minor", verA.compareTo(verD) < 0); + assertTrue("Testing minor", verD.compareTo(verA) > 0); + assertTrue("Testing major", verA.compareTo(verE) < 0); + assertTrue("Testing major", verE.compareTo(verA) > 0); + assertTrue("Testing pre", verF.compareTo(verA) < 0); + assertTrue("Testing pre", verA.compareTo(verF) > 0); + assertTrue("Testing dev vs dev", verB.compareTo(verG) < 0); + assertTrue("Testing dev vs dev", verG.compareTo(verB) > 0); + final TreeSet set = new TreeSet(); + set.add(verA); + set.add(verB); + set.add(verC); + set.add(verD); + set.add(verE); + set.add(verF); + set.add(verG); + assertEquals("Testing sorting", verF, set.pollFirst()); + assertEquals("Testing sorting", verA, set.pollFirst()); + assertEquals("Testing sorting", verC, set.pollFirst()); + assertEquals("Testing sorting", verD, set.pollFirst()); + assertEquals("Testing sorting", verE, set.pollFirst()); + assertEquals("Testing sorting", verB, set.pollFirst()); + assertEquals("Testing sorting", verG, set.pollFirst()); + } +} diff --git a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandsetxmpp.java b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandsetxmpp.java deleted file mode 100644 index 4fe9283df..000000000 --- a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandsetxmpp.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.earth2me.essentials.xmpp; - -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.commands.EssentialsCommand; -import com.earth2me.essentials.commands.NotEnoughArgumentsException; - - -public class Commandsetxmpp extends EssentialsCommand -{ - @Override - protected void run(final IUser user, final String commandLabel, final String[] args) throws NotEnoughArgumentsException - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - - EssentialsXMPP.getInstance().setAddress(user, args[0]); - user.sendMessage("XMPP address set to " + args[0]); - } -} diff --git a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandxmpp.java b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandxmpp.java deleted file mode 100644 index 23bd34170..000000000 --- a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandxmpp.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.earth2me.essentials.xmpp; - -import com.earth2me.essentials.Console; -import com.earth2me.essentials.commands.EssentialsCommand; -import com.earth2me.essentials.commands.NotEnoughArgumentsException; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - - -public class Commandxmpp extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws NotEnoughArgumentsException - { - if (args.length < 2) - { - throw new NotEnoughArgumentsException(); - } - - final String address = EssentialsXMPP.getInstance().getAddress(args[0]); - if (address == null) - { - sender.sendMessage("§cThere are no players matching that name."); - } - else - { - final String message = getFinalArg(args, 1); - final String senderName = sender instanceof Player ? ess.getUser((Player)sender).getDisplayName() : Console.NAME; - sender.sendMessage("[" + senderName + ">" + address + "] " + message); - if (!EssentialsXMPP.getInstance().sendMessage(address, "[" + senderName + "] " + message)) - { - sender.sendMessage("§cError sending message."); - } - } - } -} diff --git a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandxmppspy.java b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandxmppspy.java deleted file mode 100644 index 0a82d31dd..000000000 --- a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/Commandxmppspy.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.earth2me.essentials.xmpp; - -import com.earth2me.essentials.commands.EssentialsCommand; -import com.earth2me.essentials.commands.NotEnoughArgumentsException; -import java.util.List; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - - -public class Commandxmppspy extends EssentialsCommand -{ - @Override - protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws NotEnoughArgumentsException - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - - final List matches = server.matchPlayer(args[0]); - - if (matches.isEmpty()) - { - sender.sendMessage("§cThere are no players matching that name."); - } - - for (Player p : matches) - { - try - { - final boolean toggle = EssentialsXMPP.getInstance().toggleSpy(p); - sender.sendMessage("XMPP Spy " + (toggle ? "enabled" : "disabled") + " for " + p.getDisplayName()); - } - catch (Exception ex) - { - sender.sendMessage("Error: " + ex.getMessage()); - } - } - } -} diff --git a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/EssentialsXMPP.java b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/EssentialsXMPP.java deleted file mode 100644 index 8514d5046..000000000 --- a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/EssentialsXMPP.java +++ /dev/null @@ -1,150 +0,0 @@ -package com.earth2me.essentials.xmpp; - -import static com.earth2me.essentials.I18n._; -import com.earth2me.essentials.api.ICommandHandler; -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.commands.EssentialsCommandHandler; -import java.util.List; -import java.util.Locale; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.plugin.PluginManager; -import org.bukkit.plugin.java.JavaPlugin; - - -public class EssentialsXMPP extends JavaPlugin implements IEssentialsXMPP -{ - private static final Logger LOGGER = Logger.getLogger("Minecraft"); - private static EssentialsXMPP instance = null; - private transient UserManager users; - private transient XMPPManager xmpp; - private transient IEssentials ess; - private transient ICommandHandler commandHandler; - - public static IEssentialsXMPP getInstance() - { - return instance; - } - - @Override - public void onEnable() - { - instance = this; - - final PluginManager pluginManager = getServer().getPluginManager(); - ess = (IEssentials)pluginManager.getPlugin("Essentials3"); - if (!this.getDescription().getVersion().equals(ess.getDescription().getVersion())) - { - LOGGER.log(Level.WARNING, _("versionMismatchAll")); - } - if (!ess.isEnabled()) - { - this.setEnabled(false); - return; - } - - final EssentialsXMPPPlayerListener playerListener = new EssentialsXMPPPlayerListener(ess); - pluginManager.registerEvents(playerListener, this); - - users = new UserManager(this.getDataFolder()); - xmpp = new XMPPManager(this); - - ess.addReloadListener(users); - ess.addReloadListener(xmpp); - - commandHandler = new EssentialsCommandHandler(EssentialsXMPP.class.getClassLoader(), "com.earth2me.essentials.xmpp.Command", "essentials.", ess); - } - - @Override - public void onDisable() - { - if (xmpp != null) - { - xmpp.disconnect(); - } - instance = null; - } - - @Override - public boolean onCommand(final CommandSender sender, final Command command, final String commandLabel, final String[] args) - { - return commandHandler.handleCommand(sender, command, commandLabel, args); - } - - @Override - public void setAddress(final Player user, final String address) - { - final String username = user.getName().toLowerCase(Locale.ENGLISH); - instance.users.setAddress(username, address); - } - - @Override - public String getAddress(final String name) - { - return instance.users.getAddress(name); - } - - @Override - public IUser getUserByAddress(final String address) - { - String username = instance.users.getUserByAddress(address); - return username == null ? null : ess.getUser(username); - } - - @Override - public boolean toggleSpy(final Player user) - { - final String username = user.getName().toLowerCase(Locale.ENGLISH); - final boolean spy = !instance.users.isSpy(username); - instance.users.setSpy(username, spy); - return spy; - } - - @Override - public String getAddress(final Player user) - { - return instance.users.getAddress(user.getName()); - } - - @Override - public boolean sendMessage(final Player user, final String message) - { - return instance.xmpp.sendMessage(instance.users.getAddress(user.getName()), message); - } - - @Override - public boolean sendMessage(final String address, final String message) - { - return instance.xmpp.sendMessage(address, message); - } - - @Override - public List getSpyUsers() - { - return instance.users.getSpyUsers(); - } - - @Override - public void broadcastMessage(final IUser sender, final String message, final String xmppAddress) - { - ess.broadcastMessage(sender, message); - try - { - for (String address : getSpyUsers()) - { - if (!address.equalsIgnoreCase(xmppAddress)) - { - sendMessage(address, message); - } - } - } - catch (Exception ex) - { - // Ignore exceptions - } - } -} diff --git a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/EssentialsXMPPPlayerListener.java b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/EssentialsXMPPPlayerListener.java deleted file mode 100644 index b6daf8114..000000000 --- a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/EssentialsXMPPPlayerListener.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.earth2me.essentials.xmpp; - -import com.earth2me.essentials.api.IEssentials; -import com.earth2me.essentials.api.IUser; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerChatEvent; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.event.player.PlayerQuitEvent; - - -class EssentialsXMPPPlayerListener implements Listener -{ - private final transient IEssentials ess; - - EssentialsXMPPPlayerListener(final IEssentials ess) - { - super(); - this.ess = ess; - } - - @EventHandler(priority= EventPriority.MONITOR) - public void onPlayerJoin(final PlayerJoinEvent event) - { - final IUser user = ess.getUser(event.getPlayer()); - sendMessageToSpyUsers("Player " + user.getDisplayName() + " joined the game"); - } - - @EventHandler(priority= EventPriority.MONITOR) - public void onPlayerChat(final PlayerChatEvent event) - { - final IUser user = ess.getUser(event.getPlayer()); - sendMessageToSpyUsers(String.format(event.getFormat(), user.getDisplayName(), event.getMessage())); - } - - @EventHandler(priority= EventPriority.MONITOR) - public void onPlayerQuit(final PlayerQuitEvent event) - { - final IUser user = ess.getUser(event.getPlayer()); - sendMessageToSpyUsers("Player " + user.getDisplayName() + " left the game"); - } - - private void sendMessageToSpyUsers(final String message) - { - try - { - for (String address : EssentialsXMPP.getInstance().getSpyUsers()) - { - EssentialsXMPP.getInstance().sendMessage(address, message); - } - } - catch (Exception ex) - { - // Ignore exceptions - } - } -} diff --git a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/IEssentialsXMPP.java b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/IEssentialsXMPP.java deleted file mode 100644 index 83851d055..000000000 --- a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/IEssentialsXMPP.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.earth2me.essentials.xmpp; - -import com.earth2me.essentials.api.IUser; -import java.util.List; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; - - -public interface IEssentialsXMPP extends Plugin -{ - String getAddress(final Player user); - - String getAddress(final String name); - - List getSpyUsers(); - - IUser getUserByAddress(final String address); - - boolean sendMessage(final Player user, final String message); - - boolean sendMessage(final String address, final String message); - - void setAddress(final Player user, final String address); - - boolean toggleSpy(final Player user); - - void broadcastMessage(final IUser sender, final String message, final String xmppAddress); -} diff --git a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/UserManager.java b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/UserManager.java deleted file mode 100644 index 0f17e8660..000000000 --- a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/UserManager.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.earth2me.essentials.xmpp; - -import com.earth2me.essentials.api.IReload; -import java.io.File; -import java.io.IOException; -import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.bukkit.configuration.file.YamlConfiguration; - - -public class UserManager implements IReload -{ - private transient YamlConfiguration users; - private final transient File folder; - private final transient List spyusers = new ArrayList(); - private final static String ADDRESS = "address"; - private final static String SPY = "spy"; - - public UserManager(final File folder) - { - this.folder = folder; - onReload(); - } - - public final boolean isSpy(final String username) - { - return users.getBoolean(username.toLowerCase(Locale.ENGLISH) + "." + SPY, false); - } - - public void setSpy(final String username, final boolean spy) - { - setUser(username.toLowerCase(Locale.ENGLISH), getAddress(username), spy); - } - - public final String getAddress(final String username) - { - return users.getString(username.toLowerCase(Locale.ENGLISH) + "." + ADDRESS, null); - } - - public final String getUserByAddress(final String search) - { - final Set usernames = users.getKeys(false); - for (String username : usernames) - { - final String address = users.getString(username + "." + ADDRESS, null); - if (address != null && search.equalsIgnoreCase(address)) - { - return username; - } - } - return null; - } - - public void setAddress(final String username, final String address) - { - setUser(username.toLowerCase(Locale.ENGLISH), address, isSpy(username)); - } - - public List getSpyUsers() - { - return spyusers; - } - - private void setUser(final String username, final String address, final boolean spy) - { - final Map userdata = new HashMap(); - userdata.put(ADDRESS, address); - userdata.put(SPY, spy); - users.set(username, userdata); - try - { - users.save(new File(folder, "users.yml")); - } - catch (IOException ex) - { - Logger.getLogger(UserManager.class.getName()).log(Level.SEVERE, null, ex); - } - onReload(); - } - - @Override - public final void onReload() - { - users = YamlConfiguration.loadConfiguration(new File(folder, "users.yml")); - spyusers.clear(); - final Set keys = users.getKeys(false); - for (String key : keys) - { - if (isSpy(key)) - { - final String address = getAddress(key); - if (address != null) - { - spyusers.add(address); - } - } - } - } -} diff --git a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/XMPPManager.java b/EssentialsXMPP/src/com/earth2me/essentials/xmpp/XMPPManager.java deleted file mode 100644 index c1b1b347f..000000000 --- a/EssentialsXMPP/src/com/earth2me/essentials/xmpp/XMPPManager.java +++ /dev/null @@ -1,375 +0,0 @@ -package com.earth2me.essentials.xmpp; - -import com.earth2me.essentials.api.IReload; -import com.earth2me.essentials.api.IUser; -import com.earth2me.essentials.utils.Util; -import java.io.File; -import java.util.*; -import java.util.logging.Handler; -import java.util.logging.Level; -import java.util.logging.LogRecord; -import java.util.logging.Logger; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.entity.Player; -import org.jivesoftware.smack.*; -import org.jivesoftware.smack.Roster.SubscriptionMode; -import org.jivesoftware.smack.packet.Message; -import org.jivesoftware.smack.packet.Presence; -import org.jivesoftware.smack.util.StringUtils; - - -public final class XMPPManager extends Handler implements MessageListener, ChatManagerListener, IReload -{ - private static final Logger LOGGER = Logger.getLogger("Minecraft"); - private transient YamlConfiguration config = null; - private transient XMPPConnection connection; - private transient ChatManager chatManager; - private final transient Map chats = Collections.synchronizedMap(new HashMap()); - private final transient Set logrecords = Collections.synchronizedSet(new HashSet()); - private final transient IEssentialsXMPP parent; - private transient List logUsers; - private transient Level logLevel; - private transient boolean ignoreLagMessages = true; - private transient Thread loggerThread; - private transient boolean threadrunning = true; - - public XMPPManager(final IEssentialsXMPP parent) - { - super(); - this.parent = parent; - // config.setTemplateName("/config.yml", EssentialsXMPP.class); - onReload(); - } - - public boolean sendMessage(final String address, final String message) - { - if (address != null && !address.isEmpty()) - { - try - { - startChat(address); - final Chat chat; - synchronized (chats) - { - chat = chats.get(address); - } - if (chat != null) - { - if (!connection.isConnected()) - { - disconnect(); - connect(); - } - chat.sendMessage(Util.stripFormat(message)); - return true; - } - } - catch (XMPPException ex) - { - disableChat(address); - } - } - return false; - } - - @Override - public void processMessage(final Chat chat, final Message msg) - { - // Normally we should log the error message - // But we would create a loop if the connection to a log-user fails. - if (msg.getType() != Message.Type.error && msg.getBody().length() > 0) - { - final String message = msg.getBody(); - switch (message.charAt(0)) - { - case '@': - sendPrivateMessage(chat, message); - break; - case '/': - sendCommand(chat, message); - break; - default: - final IUser sender = parent.getUserByAddress(StringUtils.parseBareAddress(chat.getParticipant())); - parent.broadcastMessage(sender, "=" + sender.getDisplayName() + ": " + message, StringUtils.parseBareAddress(chat.getParticipant())); - } - } - } - - private boolean connect() - { - final String server = config.getString("xmpp.server"); - if (server == null || server.equals("example.com")) - { - LOGGER.log(Level.WARNING, "config broken for xmpp"); - return false; - } - final int port = config.getInt("xmpp.port", 5222); - final String serviceName = config.getString("xmpp.servicename", server); - final String xmppuser = config.getString("xmpp.user"); - final String password = config.getString("xmpp.password"); - final ConnectionConfiguration connConf = new ConnectionConfiguration(server, port, serviceName); - final StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append("Connecting to xmpp server ").append(server).append(":").append(port); - stringBuilder.append(" as user ").append(xmppuser).append("."); - LOGGER.log(Level.INFO, stringBuilder.toString()); - connConf.setSASLAuthenticationEnabled(config.getBoolean("xmpp.sasl-enabled", false)); - connConf.setSendPresence(true); - connConf.setReconnectionAllowed(true); - connection = new XMPPConnection(connConf); - try - { - connection.connect(); - connection.login(xmppuser, password); - connection.getRoster().setSubscriptionMode(SubscriptionMode.accept_all); - chatManager = connection.getChatManager(); - chatManager.addChatListener(this); - return true; - } - catch (XMPPException ex) - { - LOGGER.log(Level.WARNING, "Failed to connect to server: " + server, ex); - return false; - } - } - - public void disconnect() - { - if (loggerThread != null) - { - loggerThread.interrupt(); - } - if (chatManager != null) - { - chatManager.removeChatListener(this); - chatManager = null; - } - if (connection != null) - { - connection.disconnect(new Presence(Presence.Type.unavailable)); - } - - } - - @Override - public void chatCreated(final Chat chat, final boolean createdLocally) - { - if (!createdLocally) - { - chat.addMessageListener(this); - final Chat old = chats.put(StringUtils.parseBareAddress(chat.getParticipant()), chat); - if (old != null) - { - old.removeMessageListener(this); - } - } - } - - @Override - public void onReload() - { - LOGGER.removeHandler(this); - config = YamlConfiguration.loadConfiguration(new File(parent.getDataFolder(), "config.yml")); - synchronized (chats) - { - disconnect(); - chats.clear(); - if (!connect()) - { - return; - } - startLoggerThread(); - } - if (config.getBoolean("log-enabled", false)) - { - LOGGER.addHandler(this); - logUsers = config.getStringList("log-users"); - final String level = config.getString("log-level", "info"); - try - { - logLevel = Level.parse(level.toUpperCase(Locale.ENGLISH)); - } - catch (IllegalArgumentException e) - { - logLevel = Level.INFO; - } - ignoreLagMessages = config.getBoolean("ignore-lag-messages", true); - } - } - - @Override - public void publish(final LogRecord logRecord) - { - try - { - if (ignoreLagMessages && logRecord.getMessage().equals("Can't keep up! Did the system time change, or is the server overloaded?")) - { - return; - } - if (logRecord.getLevel().intValue() >= logLevel.intValue()) - { - synchronized (logrecords) - { - logrecords.add(logRecord); - } - } - } - catch (Exception e) - { - // Ignore all exceptions - // Otherwise we create a loop. - } - } - - @Override - public void flush() - { - // Ignore this - } - - @Override - public void close() throws SecurityException - { - // Ignore this - } - - private void startLoggerThread() - { - loggerThread = new Thread(new Runnable() - { - @Override - public void run() - { - final Set copy = new HashSet(); - final Set failedUsers = new HashSet(); - while (threadrunning) - { - synchronized (logrecords) - { - if (!logrecords.isEmpty()) - { - copy.addAll(logrecords); - logrecords.clear(); - } - } - if (!copy.isEmpty()) - { - for (String user : logUsers) - { - try - { - XMPPManager.this.startChat(user); - for (LogRecord logRecord : copy) - { - final String message = String.format("[" + logRecord.getLevel().getLocalizedName() + "] " + logRecord.getMessage(), logRecord.getParameters()); - if (!XMPPManager.this.sendMessage(user, message)) - { - failedUsers.add(user); - break; - } - - } - } - catch (XMPPException ex) - { - failedUsers.add(user); - LOGGER.removeHandler(XMPPManager.this); - LOGGER.log(Level.SEVERE, "Failed to deliver log message! Disabling logging to XMPP.", ex); - } - } - logUsers.removeAll(failedUsers); - if (logUsers.isEmpty()) - { - LOGGER.removeHandler(XMPPManager.this); - threadrunning = false; - } - copy.clear(); - } - try - { - Thread.sleep(2000); - } - catch (InterruptedException ex) - { - threadrunning = false; - } - } - LOGGER.removeHandler(XMPPManager.this); - } - }); - loggerThread.start(); - } - - private void startChat(final String address) throws XMPPException - { - if (chatManager == null) - { - return; - } - synchronized (chats) - { - if (!chats.containsKey(address)) - { - final Chat chat = chatManager.createChat(address, this); - if (chat == null) - { - throw new XMPPException("Could not start Chat with " + address); - } - chats.put(address, chat); - } - } - } - - private void sendPrivateMessage(final Chat chat, final String message) - { - final String[] parts = message.split(" ", 2); - if (parts.length == 2) - { - final List matches = parent.getServer().matchPlayer(parts[0].substring(1)); - - if (matches.isEmpty()) - { - try - { - chat.sendMessage("User " + parts[0] + " not found"); - } - catch (XMPPException ex) - { - LOGGER.log(Level.WARNING, "Failed to send xmpp message.", ex); - } - } - else - { - final String from = "[" + parent.getUserByAddress(StringUtils.parseBareAddress(chat.getParticipant())) + ">"; - for (Player p : matches) - { - p.sendMessage(from + p.getDisplayName() + "] " + message); - } - } - } - } - - private void sendCommand(final Chat chat, final String message) - { - if (config.getStringList("op-users").contains(StringUtils.parseBareAddress(chat.getParticipant()))) - { - try - { - parent.getServer().dispatchCommand(parent.getServer().getConsoleSender(), message.substring(1)); - } - catch (Exception ex) - { - LOGGER.log(Level.SEVERE, ex.getMessage(), ex); - } - } - } - - private void disableChat(final String address) - { - final Chat chat = chats.get(address); - if (chat != null) - { - chat.removeMessageListener(this); - chats.remove(address); - } - } -} diff --git a/EssentialsXMPP/src/net/ess3/xmpp/Commandsetxmpp.java b/EssentialsXMPP/src/net/ess3/xmpp/Commandsetxmpp.java new file mode 100644 index 000000000..57bee3b58 --- /dev/null +++ b/EssentialsXMPP/src/net/ess3/xmpp/Commandsetxmpp.java @@ -0,0 +1,21 @@ +package net.ess3.xmpp; + +import net.ess3.api.IUser; +import net.ess3.commands.EssentialsCommand; +import net.ess3.commands.NotEnoughArgumentsException; + + +public class Commandsetxmpp extends EssentialsCommand +{ + @Override + protected void run(final IUser user, final String commandLabel, final String[] args) throws NotEnoughArgumentsException + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + + EssentialsXMPP.getInstance().setAddress(user, args[0]); + user.sendMessage("XMPP address set to " + args[0]); + } +} diff --git a/EssentialsXMPP/src/net/ess3/xmpp/Commandxmpp.java b/EssentialsXMPP/src/net/ess3/xmpp/Commandxmpp.java new file mode 100644 index 000000000..854a91d96 --- /dev/null +++ b/EssentialsXMPP/src/net/ess3/xmpp/Commandxmpp.java @@ -0,0 +1,36 @@ +package net.ess3.xmpp; + +import net.ess3.Console; +import net.ess3.commands.EssentialsCommand; +import net.ess3.commands.NotEnoughArgumentsException; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + + +public class Commandxmpp extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws NotEnoughArgumentsException + { + if (args.length < 2) + { + throw new NotEnoughArgumentsException(); + } + + final String address = EssentialsXMPP.getInstance().getAddress(args[0]); + if (address == null) + { + sender.sendMessage("§cThere are no players matching that name."); + } + else + { + final String message = getFinalArg(args, 1); + final String senderName = sender instanceof Player ? ess.getUser((Player)sender).getDisplayName() : Console.NAME; + sender.sendMessage("[" + senderName + ">" + address + "] " + message); + if (!EssentialsXMPP.getInstance().sendMessage(address, "[" + senderName + "] " + message)) + { + sender.sendMessage("§cError sending message."); + } + } + } +} diff --git a/EssentialsXMPP/src/net/ess3/xmpp/Commandxmppspy.java b/EssentialsXMPP/src/net/ess3/xmpp/Commandxmppspy.java new file mode 100644 index 000000000..0c59910f4 --- /dev/null +++ b/EssentialsXMPP/src/net/ess3/xmpp/Commandxmppspy.java @@ -0,0 +1,40 @@ +package net.ess3.xmpp; + +import net.ess3.commands.EssentialsCommand; +import net.ess3.commands.NotEnoughArgumentsException; +import java.util.List; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + + +public class Commandxmppspy extends EssentialsCommand +{ + @Override + protected void run(final CommandSender sender, final String commandLabel, final String[] args) throws NotEnoughArgumentsException + { + if (args.length < 1) + { + throw new NotEnoughArgumentsException(); + } + + final List matches = server.matchPlayer(args[0]); + + if (matches.isEmpty()) + { + sender.sendMessage("§cThere are no players matching that name."); + } + + for (Player p : matches) + { + try + { + final boolean toggle = EssentialsXMPP.getInstance().toggleSpy(p); + sender.sendMessage("XMPP Spy " + (toggle ? "enabled" : "disabled") + " for " + p.getDisplayName()); + } + catch (Exception ex) + { + sender.sendMessage("Error: " + ex.getMessage()); + } + } + } +} diff --git a/EssentialsXMPP/src/net/ess3/xmpp/EssentialsXMPP.java b/EssentialsXMPP/src/net/ess3/xmpp/EssentialsXMPP.java new file mode 100644 index 000000000..74ab09fd5 --- /dev/null +++ b/EssentialsXMPP/src/net/ess3/xmpp/EssentialsXMPP.java @@ -0,0 +1,150 @@ +package net.ess3.xmpp; + +import static net.ess3.I18n._; +import net.ess3.api.ICommandHandler; +import net.ess3.api.IEssentials; +import net.ess3.api.IUser; +import net.ess3.commands.EssentialsCommandHandler; +import java.util.List; +import java.util.Locale; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + + +public class EssentialsXMPP extends JavaPlugin implements IEssentialsXMPP +{ + private static final Logger LOGGER = Logger.getLogger("Minecraft"); + private static EssentialsXMPP instance = null; + private transient UserManager users; + private transient XMPPManager xmpp; + private transient IEssentials ess; + private transient ICommandHandler commandHandler; + + public static IEssentialsXMPP getInstance() + { + return instance; + } + + @Override + public void onEnable() + { + instance = this; + + final PluginManager pluginManager = getServer().getPluginManager(); + ess = (IEssentials)pluginManager.getPlugin("Essentials-3"); + if (!this.getDescription().getVersion().equals(ess.getDescription().getVersion())) + { + LOGGER.log(Level.WARNING, _("versionMismatchAll")); + } + if (!ess.isEnabled()) + { + this.setEnabled(false); + return; + } + + final EssentialsXMPPPlayerListener playerListener = new EssentialsXMPPPlayerListener(ess); + pluginManager.registerEvents(playerListener, this); + + users = new UserManager(this.getDataFolder()); + xmpp = new XMPPManager(this); + + ess.addReloadListener(users); + ess.addReloadListener(xmpp); + + commandHandler = new EssentialsCommandHandler(EssentialsXMPP.class.getClassLoader(), "net.ess3.xmpp.Command", "essentials.", ess); + } + + @Override + public void onDisable() + { + if (xmpp != null) + { + xmpp.disconnect(); + } + instance = null; + } + + @Override + public boolean onCommand(final CommandSender sender, final Command command, final String commandLabel, final String[] args) + { + return commandHandler.handleCommand(sender, command, commandLabel, args); + } + + @Override + public void setAddress(final Player user, final String address) + { + final String username = user.getName().toLowerCase(Locale.ENGLISH); + instance.users.setAddress(username, address); + } + + @Override + public String getAddress(final String name) + { + return instance.users.getAddress(name); + } + + @Override + public IUser getUserByAddress(final String address) + { + String username = instance.users.getUserByAddress(address); + return username == null ? null : ess.getUser(username); + } + + @Override + public boolean toggleSpy(final Player user) + { + final String username = user.getName().toLowerCase(Locale.ENGLISH); + final boolean spy = !instance.users.isSpy(username); + instance.users.setSpy(username, spy); + return spy; + } + + @Override + public String getAddress(final Player user) + { + return instance.users.getAddress(user.getName()); + } + + @Override + public boolean sendMessage(final Player user, final String message) + { + return instance.xmpp.sendMessage(instance.users.getAddress(user.getName()), message); + } + + @Override + public boolean sendMessage(final String address, final String message) + { + return instance.xmpp.sendMessage(address, message); + } + + @Override + public List getSpyUsers() + { + return instance.users.getSpyUsers(); + } + + @Override + public void broadcastMessage(final IUser sender, final String message, final String xmppAddress) + { + ess.broadcastMessage(sender, message); + try + { + for (String address : getSpyUsers()) + { + if (!address.equalsIgnoreCase(xmppAddress)) + { + sendMessage(address, message); + } + } + } + catch (Exception ex) + { + // Ignore exceptions + } + } +} diff --git a/EssentialsXMPP/src/net/ess3/xmpp/EssentialsXMPPPlayerListener.java b/EssentialsXMPP/src/net/ess3/xmpp/EssentialsXMPPPlayerListener.java new file mode 100644 index 000000000..4880aead7 --- /dev/null +++ b/EssentialsXMPP/src/net/ess3/xmpp/EssentialsXMPPPlayerListener.java @@ -0,0 +1,58 @@ +package net.ess3.xmpp; + +import net.ess3.api.IEssentials; +import net.ess3.api.IUser; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerChatEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerQuitEvent; + + +class EssentialsXMPPPlayerListener implements Listener +{ + private final transient IEssentials ess; + + EssentialsXMPPPlayerListener(final IEssentials ess) + { + super(); + this.ess = ess; + } + + @EventHandler(priority= EventPriority.MONITOR) + public void onPlayerJoin(final PlayerJoinEvent event) + { + final IUser user = ess.getUser(event.getPlayer()); + sendMessageToSpyUsers("Player " + user.getDisplayName() + " joined the game"); + } + + @EventHandler(priority= EventPriority.MONITOR) + public void onPlayerChat(final PlayerChatEvent event) + { + final IUser user = ess.getUser(event.getPlayer()); + sendMessageToSpyUsers(String.format(event.getFormat(), user.getDisplayName(), event.getMessage())); + } + + @EventHandler(priority= EventPriority.MONITOR) + public void onPlayerQuit(final PlayerQuitEvent event) + { + final IUser user = ess.getUser(event.getPlayer()); + sendMessageToSpyUsers("Player " + user.getDisplayName() + " left the game"); + } + + private void sendMessageToSpyUsers(final String message) + { + try + { + for (String address : EssentialsXMPP.getInstance().getSpyUsers()) + { + EssentialsXMPP.getInstance().sendMessage(address, message); + } + } + catch (Exception ex) + { + // Ignore exceptions + } + } +} diff --git a/EssentialsXMPP/src/net/ess3/xmpp/IEssentialsXMPP.java b/EssentialsXMPP/src/net/ess3/xmpp/IEssentialsXMPP.java new file mode 100644 index 000000000..373a7879d --- /dev/null +++ b/EssentialsXMPP/src/net/ess3/xmpp/IEssentialsXMPP.java @@ -0,0 +1,28 @@ +package net.ess3.xmpp; + +import net.ess3.api.IUser; +import java.util.List; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + + +public interface IEssentialsXMPP extends Plugin +{ + String getAddress(final Player user); + + String getAddress(final String name); + + List getSpyUsers(); + + IUser getUserByAddress(final String address); + + boolean sendMessage(final Player user, final String message); + + boolean sendMessage(final String address, final String message); + + void setAddress(final Player user, final String address); + + boolean toggleSpy(final Player user); + + void broadcastMessage(final IUser sender, final String message, final String xmppAddress); +} diff --git a/EssentialsXMPP/src/net/ess3/xmpp/UserManager.java b/EssentialsXMPP/src/net/ess3/xmpp/UserManager.java new file mode 100644 index 000000000..a2018c006 --- /dev/null +++ b/EssentialsXMPP/src/net/ess3/xmpp/UserManager.java @@ -0,0 +1,100 @@ +package net.ess3.xmpp; + +import net.ess3.api.IReload; +import java.io.File; +import java.io.IOException; +import java.util.*; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.bukkit.configuration.file.YamlConfiguration; + + +public class UserManager implements IReload +{ + private transient YamlConfiguration users; + private final transient File folder; + private final transient List spyusers = new ArrayList(); + private final static String ADDRESS = "address"; + private final static String SPY = "spy"; + + public UserManager(final File folder) + { + this.folder = folder; + onReload(); + } + + public final boolean isSpy(final String username) + { + return users.getBoolean(username.toLowerCase(Locale.ENGLISH) + "." + SPY, false); + } + + public void setSpy(final String username, final boolean spy) + { + setUser(username.toLowerCase(Locale.ENGLISH), getAddress(username), spy); + } + + public final String getAddress(final String username) + { + return users.getString(username.toLowerCase(Locale.ENGLISH) + "." + ADDRESS, null); + } + + public final String getUserByAddress(final String search) + { + final Set usernames = users.getKeys(false); + for (String username : usernames) + { + final String address = users.getString(username + "." + ADDRESS, null); + if (address != null && search.equalsIgnoreCase(address)) + { + return username; + } + } + return null; + } + + public void setAddress(final String username, final String address) + { + setUser(username.toLowerCase(Locale.ENGLISH), address, isSpy(username)); + } + + public List getSpyUsers() + { + return spyusers; + } + + private void setUser(final String username, final String address, final boolean spy) + { + final Map userdata = new HashMap(); + userdata.put(ADDRESS, address); + userdata.put(SPY, spy); + users.set(username, userdata); + try + { + users.save(new File(folder, "users.yml")); + } + catch (IOException ex) + { + Logger.getLogger(UserManager.class.getName()).log(Level.SEVERE, null, ex); + } + onReload(); + } + + @Override + public final void onReload() + { + users = YamlConfiguration.loadConfiguration(new File(folder, "users.yml")); + spyusers.clear(); + final Set keys = users.getKeys(false); + for (String key : keys) + { + if (isSpy(key)) + { + final String address = getAddress(key); + if (address != null) + { + spyusers.add(address); + } + } + } + } +} diff --git a/EssentialsXMPP/src/net/ess3/xmpp/XMPPManager.java b/EssentialsXMPP/src/net/ess3/xmpp/XMPPManager.java new file mode 100644 index 000000000..ff49bc931 --- /dev/null +++ b/EssentialsXMPP/src/net/ess3/xmpp/XMPPManager.java @@ -0,0 +1,375 @@ +package net.ess3.xmpp; + +import net.ess3.api.IReload; +import net.ess3.api.IUser; +import net.ess3.utils.Util; +import java.io.File; +import java.util.*; +import java.util.logging.Handler; +import java.util.logging.Level; +import java.util.logging.LogRecord; +import java.util.logging.Logger; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.entity.Player; +import org.jivesoftware.smack.*; +import org.jivesoftware.smack.Roster.SubscriptionMode; +import org.jivesoftware.smack.packet.Message; +import org.jivesoftware.smack.packet.Presence; +import org.jivesoftware.smack.util.StringUtils; + + +public final class XMPPManager extends Handler implements MessageListener, ChatManagerListener, IReload +{ + private static final Logger LOGGER = Logger.getLogger("Minecraft"); + private transient YamlConfiguration config = null; + private transient XMPPConnection connection; + private transient ChatManager chatManager; + private final transient Map chats = Collections.synchronizedMap(new HashMap()); + private final transient Set logrecords = Collections.synchronizedSet(new HashSet()); + private final transient IEssentialsXMPP parent; + private transient List logUsers; + private transient Level logLevel; + private transient boolean ignoreLagMessages = true; + private transient Thread loggerThread; + private transient boolean threadrunning = true; + + public XMPPManager(final IEssentialsXMPP parent) + { + super(); + this.parent = parent; + // config.setTemplateName("/config.yml", EssentialsXMPP.class); + onReload(); + } + + public boolean sendMessage(final String address, final String message) + { + if (address != null && !address.isEmpty()) + { + try + { + startChat(address); + final Chat chat; + synchronized (chats) + { + chat = chats.get(address); + } + if (chat != null) + { + if (!connection.isConnected()) + { + disconnect(); + connect(); + } + chat.sendMessage(Util.stripFormat(message)); + return true; + } + } + catch (XMPPException ex) + { + disableChat(address); + } + } + return false; + } + + @Override + public void processMessage(final Chat chat, final Message msg) + { + // Normally we should log the error message + // But we would create a loop if the connection to a log-user fails. + if (msg.getType() != Message.Type.error && msg.getBody().length() > 0) + { + final String message = msg.getBody(); + switch (message.charAt(0)) + { + case '@': + sendPrivateMessage(chat, message); + break; + case '/': + sendCommand(chat, message); + break; + default: + final IUser sender = parent.getUserByAddress(StringUtils.parseBareAddress(chat.getParticipant())); + parent.broadcastMessage(sender, "=" + sender.getDisplayName() + ": " + message, StringUtils.parseBareAddress(chat.getParticipant())); + } + } + } + + private boolean connect() + { + final String server = config.getString("xmpp.server"); + if (server == null || server.equals("example.com")) + { + LOGGER.log(Level.WARNING, "config broken for xmpp"); + return false; + } + final int port = config.getInt("xmpp.port", 5222); + final String serviceName = config.getString("xmpp.servicename", server); + final String xmppuser = config.getString("xmpp.user"); + final String password = config.getString("xmpp.password"); + final ConnectionConfiguration connConf = new ConnectionConfiguration(server, port, serviceName); + final StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("Connecting to xmpp server ").append(server).append(":").append(port); + stringBuilder.append(" as user ").append(xmppuser).append("."); + LOGGER.log(Level.INFO, stringBuilder.toString()); + connConf.setSASLAuthenticationEnabled(config.getBoolean("xmpp.sasl-enabled", false)); + connConf.setSendPresence(true); + connConf.setReconnectionAllowed(true); + connection = new XMPPConnection(connConf); + try + { + connection.connect(); + connection.login(xmppuser, password); + connection.getRoster().setSubscriptionMode(SubscriptionMode.accept_all); + chatManager = connection.getChatManager(); + chatManager.addChatListener(this); + return true; + } + catch (XMPPException ex) + { + LOGGER.log(Level.WARNING, "Failed to connect to server: " + server, ex); + return false; + } + } + + public void disconnect() + { + if (loggerThread != null) + { + loggerThread.interrupt(); + } + if (chatManager != null) + { + chatManager.removeChatListener(this); + chatManager = null; + } + if (connection != null) + { + connection.disconnect(new Presence(Presence.Type.unavailable)); + } + + } + + @Override + public void chatCreated(final Chat chat, final boolean createdLocally) + { + if (!createdLocally) + { + chat.addMessageListener(this); + final Chat old = chats.put(StringUtils.parseBareAddress(chat.getParticipant()), chat); + if (old != null) + { + old.removeMessageListener(this); + } + } + } + + @Override + public void onReload() + { + LOGGER.removeHandler(this); + config = YamlConfiguration.loadConfiguration(new File(parent.getDataFolder(), "config.yml")); + synchronized (chats) + { + disconnect(); + chats.clear(); + if (!connect()) + { + return; + } + startLoggerThread(); + } + if (config.getBoolean("log-enabled", false)) + { + LOGGER.addHandler(this); + logUsers = config.getStringList("log-users"); + final String level = config.getString("log-level", "info"); + try + { + logLevel = Level.parse(level.toUpperCase(Locale.ENGLISH)); + } + catch (IllegalArgumentException e) + { + logLevel = Level.INFO; + } + ignoreLagMessages = config.getBoolean("ignore-lag-messages", true); + } + } + + @Override + public void publish(final LogRecord logRecord) + { + try + { + if (ignoreLagMessages && logRecord.getMessage().equals("Can't keep up! Did the system time change, or is the server overloaded?")) + { + return; + } + if (logRecord.getLevel().intValue() >= logLevel.intValue()) + { + synchronized (logrecords) + { + logrecords.add(logRecord); + } + } + } + catch (Exception e) + { + // Ignore all exceptions + // Otherwise we create a loop. + } + } + + @Override + public void flush() + { + // Ignore this + } + + @Override + public void close() throws SecurityException + { + // Ignore this + } + + private void startLoggerThread() + { + loggerThread = new Thread(new Runnable() + { + @Override + public void run() + { + final Set copy = new HashSet(); + final Set failedUsers = new HashSet(); + while (threadrunning) + { + synchronized (logrecords) + { + if (!logrecords.isEmpty()) + { + copy.addAll(logrecords); + logrecords.clear(); + } + } + if (!copy.isEmpty()) + { + for (String user : logUsers) + { + try + { + XMPPManager.this.startChat(user); + for (LogRecord logRecord : copy) + { + final String message = String.format("[" + logRecord.getLevel().getLocalizedName() + "] " + logRecord.getMessage(), logRecord.getParameters()); + if (!XMPPManager.this.sendMessage(user, message)) + { + failedUsers.add(user); + break; + } + + } + } + catch (XMPPException ex) + { + failedUsers.add(user); + LOGGER.removeHandler(XMPPManager.this); + LOGGER.log(Level.SEVERE, "Failed to deliver log message! Disabling logging to XMPP.", ex); + } + } + logUsers.removeAll(failedUsers); + if (logUsers.isEmpty()) + { + LOGGER.removeHandler(XMPPManager.this); + threadrunning = false; + } + copy.clear(); + } + try + { + Thread.sleep(2000); + } + catch (InterruptedException ex) + { + threadrunning = false; + } + } + LOGGER.removeHandler(XMPPManager.this); + } + }); + loggerThread.start(); + } + + private void startChat(final String address) throws XMPPException + { + if (chatManager == null) + { + return; + } + synchronized (chats) + { + if (!chats.containsKey(address)) + { + final Chat chat = chatManager.createChat(address, this); + if (chat == null) + { + throw new XMPPException("Could not start Chat with " + address); + } + chats.put(address, chat); + } + } + } + + private void sendPrivateMessage(final Chat chat, final String message) + { + final String[] parts = message.split(" ", 2); + if (parts.length == 2) + { + final List matches = parent.getServer().matchPlayer(parts[0].substring(1)); + + if (matches.isEmpty()) + { + try + { + chat.sendMessage("User " + parts[0] + " not found"); + } + catch (XMPPException ex) + { + LOGGER.log(Level.WARNING, "Failed to send xmpp message.", ex); + } + } + else + { + final String from = "[" + parent.getUserByAddress(StringUtils.parseBareAddress(chat.getParticipant())) + ">"; + for (Player p : matches) + { + p.sendMessage(from + p.getDisplayName() + "] " + message); + } + } + } + } + + private void sendCommand(final Chat chat, final String message) + { + if (config.getStringList("op-users").contains(StringUtils.parseBareAddress(chat.getParticipant()))) + { + try + { + parent.getServer().dispatchCommand(parent.getServer().getConsoleSender(), message.substring(1)); + } + catch (Exception ex) + { + LOGGER.log(Level.SEVERE, ex.getMessage(), ex); + } + } + } + + private void disableChat(final String address) + { + final Chat chat = chats.get(address); + if (chat != null) + { + chat.removeMessageListener(this); + chats.remove(address); + } + } +} diff --git a/EssentialsXMPP/src/plugin.yml b/EssentialsXMPP/src/plugin.yml index 7109284b7..49f6abd98 100644 --- a/EssentialsXMPP/src/plugin.yml +++ b/EssentialsXMPP/src/plugin.yml @@ -1,13 +1,13 @@ # This determines the command prefix when there are conflicts (/name:home, /name:help, etc.) name: EssentialsXMPP -main: com.earth2me.essentials.xmpp.EssentialsXMPP +main: net.ess3.xmpp.EssentialsXMPP # Note to developers: This next line cannot change, or the automatic versioning system will break. version: ${build.number} website: http://tiny.cc/EssentialsWiki description: Provides xmpp communication. authors: - snowleo -depend: [Essentials3] +depend: [Essentials-3] commands: setxmpp: description: set your xmpp address -- cgit v1.2.3