From dde0b20775c3b9a82f62d381e0d827f49313f46d Mon Sep 17 00:00:00 2001 From: drtshock Date: Tue, 14 Apr 2015 23:06:16 -0500 Subject: [PATCH] Reformat --- Essentials/pom.xml | 242 +- .../AlternativeCommandsHandler.java | 216 +- .../src/com/earth2me/essentials/Backup.java | 268 +- .../earth2me/essentials/ChargeException.java | 17 +- .../earth2me/essentials/CommandSource.java | 85 +- .../src/com/earth2me/essentials/Console.java | 46 +- .../com/earth2me/essentials/Enchantments.java | 278 +- .../com/earth2me/essentials/Essentials.java | 1661 +++---- .../essentials/EssentialsBlockListener.java | 89 +- .../earth2me/essentials/EssentialsConf.java | 1300 +++-- .../essentials/EssentialsEntityListener.java | 344 +- .../essentials/EssentialsPlayerListener.java | 1239 +++-- .../essentials/EssentialsPluginListener.java | 87 +- .../earth2me/essentials/EssentialsTimer.java | 212 +- .../essentials/EssentialsUpgrade.java | 1364 +++--- .../essentials/EssentialsUserConf.java | 101 +- .../com/earth2me/essentials/ExecuteTimer.java | 120 +- .../src/com/earth2me/essentials/I18n.java | 318 +- .../src/com/earth2me/essentials/IConf.java | 5 +- .../com/earth2me/essentials/IEssentials.java | 96 +- .../essentials/IEssentialsModule.java | 3 +- .../src/com/earth2me/essentials/IReplyTo.java | 25 +- .../com/earth2me/essentials/ISettings.java | 220 +- .../src/com/earth2me/essentials/ITarget.java | 5 +- .../src/com/earth2me/essentials/IUser.java | 166 +- .../src/com/earth2me/essentials/ItemDb.java | 520 +- .../src/com/earth2me/essentials/Jails.java | 526 +- .../src/com/earth2me/essentials/Kit.java | 437 +- .../earth2me/essentials/LocationTarget.java | 21 +- .../com/earth2me/essentials/ManagedFile.java | 351 +- .../earth2me/essentials/MetaItemStack.java | 892 ++-- .../src/com/earth2me/essentials/Mob.java | 216 +- .../src/com/earth2me/essentials/MobData.java | 572 +-- .../earth2me/essentials/OfflinePlayer.java | 2796 +++++------ .../earth2me/essentials/PlayerExtension.java | 59 +- .../com/earth2me/essentials/PlayerList.java | 255 +- .../com/earth2me/essentials/PlayerTarget.java | 21 +- .../src/com/earth2me/essentials/Potions.java | 208 +- .../src/com/earth2me/essentials/Settings.java | 2270 ++++----- .../src/com/earth2me/essentials/SpawnMob.java | 478 +- .../essentials/TNTExplodeListener.java | 84 +- .../src/com/earth2me/essentials/Teleport.java | 463 +- .../earth2me/essentials/TimedTeleport.java | 274 +- .../src/com/earth2me/essentials/Trade.java | 701 ++- .../src/com/earth2me/essentials/UUIDMap.java | 312 +- .../src/com/earth2me/essentials/User.java | 1568 +++--- .../src/com/earth2me/essentials/UserData.java | 1754 ++++--- .../src/com/earth2me/essentials/UserMap.java | 391 +- .../src/com/earth2me/essentials/Warps.java | 279 +- .../src/com/earth2me/essentials/Worth.java | 269 +- .../com/earth2me/essentials/api/Economy.java | 766 ++- .../com/earth2me/essentials/api/II18n.java | 14 +- .../com/earth2me/essentials/api/IItemDb.java | 23 +- .../com/earth2me/essentials/api/IJails.java | 94 +- .../com/earth2me/essentials/api/IReload.java | 5 +- .../earth2me/essentials/api/ITeleport.java | 190 +- .../com/earth2me/essentials/api/IWarps.java | 114 +- .../essentials/api/InvalidNameException.java | 20 +- .../essentials/api/InvalidWorldException.java | 21 +- .../api/NoLoanPermittedException.java | 3 +- .../api/UserDoesNotExistException.java | 10 +- .../essentials/commands/Commandafk.java | 104 +- .../essentials/commands/Commandantioch.java | 30 +- .../essentials/commands/Commandback.java | 43 +- .../essentials/commands/Commandbackup.java | 42 +- .../essentials/commands/Commandbalance.java | 66 +- .../commands/Commandbalancetop.java | 301 +- .../essentials/commands/Commandban.java | 111 +- .../essentials/commands/Commandbanip.java | 89 +- .../essentials/commands/Commandbigtree.java | 66 +- .../essentials/commands/Commandbook.java | 135 +- .../essentials/commands/Commandbreak.java | 66 +- .../essentials/commands/Commandbroadcast.java | 45 +- .../essentials/commands/Commandburn.java | 40 +- .../commands/Commandclearinventory.java | 248 +- .../essentials/commands/Commandcompass.java | 81 +- .../essentials/commands/Commandcondense.java | 334 +- .../commands/Commandcustomtext.java | 55 +- .../essentials/commands/Commanddelhome.java | 85 +- .../essentials/commands/Commanddeljail.java | 33 +- .../essentials/commands/Commanddelwarp.java | 33 +- .../essentials/commands/Commanddepth.java | 41 +- .../essentials/commands/Commandeco.java | 199 +- .../essentials/commands/Commandenchant.java | 116 +- .../commands/Commandenderchest.java | 40 +- .../commands/Commandessentials.java | 572 +-- .../essentials/commands/Commandexp.java | 318 +- .../essentials/commands/Commandext.java | 67 +- .../essentials/commands/Commandfeed.java | 102 +- .../essentials/commands/Commandfireball.java | 79 +- .../essentials/commands/Commandfirework.java | 200 +- .../essentials/commands/Commandfly.java | 97 +- .../essentials/commands/Commandgamemode.java | 204 +- .../essentials/commands/Commandgc.java | 108 +- .../essentials/commands/Commandgetpos.java | 75 +- .../essentials/commands/Commandgive.java | 158 +- .../essentials/commands/Commandgod.java | 106 +- .../essentials/commands/Commandhat.java | 86 +- .../essentials/commands/Commandheal.java | 127 +- .../essentials/commands/Commandhelp.java | 85 +- .../essentials/commands/Commandhelpop.java | 63 +- .../essentials/commands/Commandhome.java | 198 +- .../essentials/commands/Commandignore.java | 86 +- .../essentials/commands/Commandinfo.java | 34 +- .../essentials/commands/Commandinvsee.java | 51 +- .../essentials/commands/Commanditem.java | 123 +- .../essentials/commands/Commanditemdb.java | 78 +- .../essentials/commands/Commandjails.java | 19 +- .../essentials/commands/Commandjump.java | 75 +- .../essentials/commands/Commandkick.java | 65 +- .../essentials/commands/Commandkickall.java | 38 +- .../essentials/commands/Commandkill.java | 67 +- .../essentials/commands/Commandkit.java | 201 +- .../commands/Commandkittycannon.java | 63 +- .../essentials/commands/Commandlightning.java | 83 +- .../essentials/commands/Commandlist.java | 203 +- .../essentials/commands/Commandmail.java | 282 +- .../essentials/commands/Commandme.java | 62 +- .../essentials/commands/Commandmore.java | 69 +- .../essentials/commands/Commandmotd.java | 34 +- .../essentials/commands/Commandmsg.java | 118 +- .../essentials/commands/Commandmute.java | 140 +- .../essentials/commands/Commandnear.java | 197 +- .../essentials/commands/Commandnick.java | 218 +- .../essentials/commands/Commandnuke.java | 85 +- .../essentials/commands/Commandpay.java | 69 +- .../essentials/commands/Commandping.java | 33 +- .../essentials/commands/Commandpotion.java | 128 +- .../essentials/commands/Commandpowertool.java | 195 +- .../commands/Commandpowertooltoggle.java | 33 +- .../essentials/commands/Commandptime.java | 376 +- .../essentials/commands/Commandpweather.java | 281 +- .../essentials/commands/Commandr.java | 105 +- .../essentials/commands/Commandrealname.java | 69 +- .../essentials/commands/Commandrecipe.java | 309 +- .../essentials/commands/Commandremove.java | 529 +- .../essentials/commands/Commandrepair.java | 222 +- .../essentials/commands/Commandrules.java | 34 +- .../essentials/commands/Commandseen.java | 345 +- .../essentials/commands/Commandsell.java | 166 +- .../essentials/commands/Commandsethome.java | 132 +- .../essentials/commands/Commandsetjail.java | 31 +- .../essentials/commands/Commandsetwarp.java | 70 +- .../essentials/commands/Commandsetworth.java | 72 +- .../essentials/commands/Commandskull.java | 94 +- .../essentials/commands/Commandsocialspy.java | 96 +- .../essentials/commands/Commandspawner.java | 107 +- .../essentials/commands/Commandspawnmob.java | 109 +- .../essentials/commands/Commandspeed.java | 276 +- .../essentials/commands/Commandsudo.java | 105 +- .../essentials/commands/Commandsuicide.java | 39 +- .../essentials/commands/Commandtempban.java | 105 +- .../essentials/commands/Commandthunder.java | 50 +- .../essentials/commands/Commandtime.java | 278 +- .../commands/Commandtogglejail.java | 157 +- .../essentials/commands/Commandtop.java | 36 +- .../essentials/commands/Commandtp.java | 235 +- .../essentials/commands/Commandtpa.java | 73 +- .../essentials/commands/Commandtpaall.java | 100 +- .../essentials/commands/Commandtpaccept.java | 118 +- .../essentials/commands/Commandtpahere.java | 73 +- .../essentials/commands/Commandtpall.java | 84 +- .../essentials/commands/Commandtpdeny.java | 35 +- .../essentials/commands/Commandtphere.java | 41 +- .../essentials/commands/Commandtpo.java | 72 +- .../essentials/commands/Commandtpohere.java | 43 +- .../essentials/commands/Commandtppos.java | 117 +- .../essentials/commands/Commandtptoggle.java | 86 +- .../essentials/commands/Commandtree.java | 126 +- .../essentials/commands/Commandunban.java | 67 +- .../essentials/commands/Commandunbanip.java | 80 +- .../essentials/commands/Commandunlimited.java | 174 +- .../essentials/commands/Commandvanish.java | 93 +- .../essentials/commands/Commandwarp.java | 191 +- .../essentials/commands/Commandweather.java | 129 +- .../essentials/commands/Commandwhois.java | 87 +- .../essentials/commands/Commandworkbench.java | 19 +- .../essentials/commands/Commandworld.java | 116 +- .../essentials/commands/Commandworth.java | 186 +- .../commands/EssentialsCommand.java | 366 +- .../commands/EssentialsLoopCommand.java | 222 +- .../commands/EssentialsToggleCommand.java | 108 +- .../commands/IEssentialsCommand.java | 15 +- .../commands/NoChargeException.java | 10 +- .../commands/NotEnoughArgumentsException.java | 24 +- .../commands/PlayerExemptException.java | 10 +- .../commands/PlayerNotFoundException.java | 10 +- .../commands/QuietAbortException.java | 17 +- .../commands/WarpNotFoundException.java | 19 +- .../essentials/craftbukkit/BanLookup.java | 46 +- .../essentials/craftbukkit/FakeWorld.java | 1340 +++--- .../craftbukkit/InventoryWorkaround.java | 237 +- .../essentials/craftbukkit/SetExpFix.java | 162 +- .../earth2me/essentials/metrics/Metrics.java | 1520 +++--- .../essentials/metrics/MetricsListener.java | 47 +- .../essentials/metrics/MetricsStarter.java | 404 +- .../essentials/perm/BPermissions2Handler.java | 80 +- .../perm/ConfigPermissionsHandler.java | 32 +- .../essentials/perm/GroupManagerHandler.java | 170 +- .../essentials/perm/IPermissionsHandler.java | 20 +- .../perm/NullPermissionsHandler.java | 69 +- .../perm/PermissionsBukkitHandler.java | 112 +- .../essentials/perm/PermissionsExHandler.java | 156 +- .../essentials/perm/PermissionsHandler.java | 358 +- .../essentials/perm/PrivilegesHandler.java | 84 +- .../essentials/perm/SimplyPermsHandler.java | 74 +- .../essentials/perm/SuperpermsHandler.java | 98 +- .../essentials/perm/ZPermissionsHandler.java | 276 +- .../essentials/register/payment/Method.java | 329 +- .../essentials/register/payment/Methods.java | 444 +- .../register/payment/methods/BOSE7.java | 462 +- .../register/payment/methods/MCUR.java | 270 +- .../register/payment/methods/VaultEco.java | 514 +- .../register/payment/methods/iCo5.java | 550 +-- .../register/payment/methods/iCo6.java | 345 +- .../earth2me/essentials/settings/Jails.java | 14 +- .../earth2me/essentials/settings/Spawns.java | 14 +- .../essentials/signs/EssentialsSign.java | 1090 ++--- .../essentials/signs/SignBalance.java | 24 +- .../essentials/signs/SignBlockListener.java | 449 +- .../earth2me/essentials/signs/SignBuy.java | 49 +- .../essentials/signs/SignDisposal.java | 21 +- .../essentials/signs/SignEnchant.java | 254 +- .../essentials/signs/SignEntityListener.java | 106 +- .../essentials/signs/SignException.java | 17 +- .../earth2me/essentials/signs/SignFree.java | 88 +- .../essentials/signs/SignGameMode.java | 96 +- .../earth2me/essentials/signs/SignHeal.java | 56 +- .../earth2me/essentials/signs/SignInfo.java | 68 +- .../earth2me/essentials/signs/SignKit.java | 138 +- .../earth2me/essentials/signs/SignMail.java | 45 +- .../essentials/signs/SignPlayerListener.java | 132 +- .../essentials/signs/SignProtection.java | 527 +- .../earth2me/essentials/signs/SignRepair.java | 92 +- .../earth2me/essentials/signs/SignSell.java | 44 +- .../essentials/signs/SignSpawnmob.java | 65 +- .../earth2me/essentials/signs/SignTime.java | 89 +- .../earth2me/essentials/signs/SignTrade.java | 717 ++- .../earth2me/essentials/signs/SignWarp.java | 101 +- .../essentials/signs/SignWeather.java | 87 +- .../com/earth2me/essentials/signs/Signs.java | 55 +- .../AbstractDelayedYamlFileReader.java | 96 +- .../AbstractDelayedYamlFileWriter.java | 71 +- .../storage/AsyncStorageObjectHolder.java | 268 +- .../essentials/storage/BukkitConstructor.java | 675 ++- .../earth2me/essentials/storage/Comment.java | 8 +- .../essentials/storage/EnchantmentLevel.java | 115 +- .../storage/IStorageObjectHolder.java | 13 +- .../essentials/storage/IStorageReader.java | 5 +- .../essentials/storage/IStorageWriter.java | 5 +- .../earth2me/essentials/storage/ListType.java | 7 +- .../essentials/storage/MapKeyType.java | 7 +- .../essentials/storage/MapValueType.java | 7 +- .../storage/ObjectLoadException.java | 10 +- .../essentials/storage/StorageObject.java | 3 +- .../essentials/storage/YamlStorageReader.java | 187 +- .../essentials/storage/YamlStorageWriter.java | 533 +-- .../essentials/textreader/BookInput.java | 209 +- .../essentials/textreader/BookPager.java | 273 +- .../essentials/textreader/HelpInput.java | 268 +- .../earth2me/essentials/textreader/IText.java | 15 +- .../textreader/KeywordReplacer.java | 674 ++- .../textreader/SimpleTextInput.java | 51 +- .../textreader/SimpleTextPager.java | 46 +- .../essentials/textreader/TextInput.java | 225 +- .../essentials/textreader/TextPager.java | 272 +- .../earth2me/essentials/utils/DateUtil.java | 297 +- .../essentials/utils/DescParseTickFormat.java | 412 +- .../earth2me/essentials/utils/FormatUtil.java | 240 +- .../essentials/utils/LocationUtil.java | 640 ++- .../earth2me/essentials/utils/NumberUtil.java | 74 +- .../earth2me/essentials/utils/StringUtil.java | 153 +- Essentials/src/net/ess3/api/Economy.java | 5 +- Essentials/src/net/ess3/api/IEssentials.java | 5 +- Essentials/src/net/ess3/api/II18n.java | 3 +- Essentials/src/net/ess3/api/IItemDb.java | 3 +- Essentials/src/net/ess3/api/IJails.java | 3 +- Essentials/src/net/ess3/api/IReload.java | 3 +- Essentials/src/net/ess3/api/ISettings.java | 3 +- Essentials/src/net/ess3/api/ITeleport.java | 3 +- Essentials/src/net/ess3/api/IUser.java | 4 +- Essentials/src/net/ess3/api/IWarps.java | 3 +- .../net/ess3/api/InvalidNameException.java | 20 +- .../net/ess3/api/InvalidWorldException.java | 21 +- .../src/net/ess3/api/MaxMoneyException.java | 10 +- .../ess3/api/NoLoanPermittedException.java | 10 +- .../ess3/api/UserDoesNotExistException.java | 10 +- .../ess3/api/events/AfkStatusChangeEvent.java | 10 +- .../ess3/api/events/GodStatusChangeEvent.java | 10 +- .../api/events/IgnoreStatusChangeEvent.java | 10 +- .../api/events/JailStatusChangeEvent.java | 10 +- .../ess3/api/events/LocalChatSpyEvent.java | 202 +- .../api/events/MuteStatusChangeEvent.java | 10 +- .../net/ess3/api/events/NickChangeEvent.java | 21 +- .../net/ess3/api/events/SignBreakEvent.java | 10 +- .../net/ess3/api/events/SignCreateEvent.java | 10 +- .../src/net/ess3/api/events/SignEvent.java | 82 +- .../ess3/api/events/SignInteractEvent.java | 10 +- .../net/ess3/api/events/StateChangeEvent.java | 82 +- .../ess3/api/events/StatusChangeEvent.java | 31 +- .../api/events/UserBalanceUpdateEvent.java | 65 +- .../com/earth2me/essentials/EconomyTest.java | 197 +- .../com/earth2me/essentials/FakeServer.java | 2286 ++++----- .../com/earth2me/essentials/StorageTest.java | 90 +- .../com/earth2me/essentials/ToggleTest.java | 331 +- .../com/earth2me/essentials/UserTest.java | 146 +- .../com/earth2me/essentials/UtilTest.java | 364 +- EssentialsAntiBuild/pom.xml | 80 +- .../essentials/antibuild/AntiBuildConfig.java | 115 +- .../antibuild/EssentialsAntiBuild.java | 89 +- .../EssentialsAntiBuildListener.java | 475 +- .../antibuild/EssentialsConnect.java | 116 +- .../essentials/antibuild/IAntiBuild.java | 16 +- EssentialsChat/pom.xml | 80 +- .../earth2me/essentials/chat/ChatStore.java | 64 +- .../essentials/chat/EssentialsChat.java | 56 +- .../essentials/chat/EssentialsChatPlayer.java | 137 +- .../EssentialsChatPlayerListenerHighest.java | 41 +- .../EssentialsChatPlayerListenerLowest.java | 83 +- .../EssentialsChatPlayerListenerNormal.java | 219 +- EssentialsGeoIP/pom.xml | 138 +- .../essentials/geoip/EssentialsGeoIP.java | 57 +- .../geoip/EssentialsGeoIPPlayerListener.java | 290 +- .../nbproject/build-impl.xml | 271 +- .../groupmanager/GMConfiguration.java | 293 +- .../anjocaido/groupmanager/GlobalGroups.java | 707 +-- .../anjocaido/groupmanager/GroupManager.java | 4233 +++++++++-------- .../Tasks/BukkitPermsUpdateTask.java | 22 +- .../anjocaido/groupmanager/data/DataUnit.java | 312 +- .../anjocaido/groupmanager/data/Group.java | 305 +- .../groupmanager/data/GroupVariables.java | 141 +- .../org/anjocaido/groupmanager/data/User.java | 519 +- .../groupmanager/data/UserVariables.java | 67 +- .../groupmanager/data/Variables.java | 320 +- .../dataholder/GroupsDataHolder.java | 185 +- .../dataholder/OverloadedWorldHolder.java | 353 +- .../dataholder/UsersDataHolder.java | 159 +- .../dataholder/WorldDataHolder.java | 2386 +++++----- .../dataholder/worlds/WorldsHolder.java | 1266 ++--- .../groupmanager/events/GMGroupEvent.java | 104 +- .../groupmanager/events/GMSystemEvent.java | 76 +- .../groupmanager/events/GMUserEvent.java | 104 +- .../groupmanager/events/GMWorldListener.java | 82 +- .../events/GroupManagerEventHandler.java | 105 +- .../permissions/AnjoPermissionsHandler.java | 2501 +++++----- .../permissions/BukkitPermissions.java | 688 ++- .../PermissionsReaderInterface.java | 391 +- .../groupmanager/utils/GMLoggerHandler.java | 19 +- .../utils/GroupManagerPermissions.java | 86 +- .../utils/PermissionCheckResult.java | 94 +- .../utils/StringPermissionComparator.java | 67 +- .../anjocaido/groupmanager/utils/Tasks.java | 259 +- EssentialsProtect/pom.xml | 80 +- .../essentials/protect/EmergencyListener.java | 66 +- .../essentials/protect/EssentialsConnect.java | 82 +- .../essentials/protect/EssentialsProtect.java | 132 +- .../EssentialsProtectBlockListener.java | 130 +- .../EssentialsProtectEntityListener.java | 476 +- .../EssentialsProtectWeatherListener.java | 56 +- .../earth2me/essentials/protect/IProtect.java | 20 +- .../essentials/protect/ProtectConfig.java | 184 +- EssentialsSpawn/pom.xml | 80 +- .../essentials/spawn/Commandsetspawn.java | 26 +- .../essentials/spawn/Commandspawn.java | 92 +- .../essentials/spawn/EssentialsSpawn.java | 126 +- .../spawn/EssentialsSpawnPlayerListener.java | 262 +- .../essentials/spawn/IEssentialsSpawn.java | 38 +- .../essentials/spawn/SpawnStorage.java | 140 +- EssentialsXMPP/pom.xml | 138 +- .../essentials/xmpp/Commandsetxmpp.java | 28 +- .../earth2me/essentials/xmpp/Commandxmpp.java | 50 +- .../essentials/xmpp/Commandxmppspy.java | 56 +- .../essentials/xmpp/EssentialsXMPP.java | 232 +- .../xmpp/EssentialsXMPPPlayerListener.java | 136 +- .../essentials/xmpp/IEssentialsXMPP.java | 26 +- .../earth2me/essentials/xmpp/UserManager.java | 128 +- .../earth2me/essentials/xmpp/XMPPManager.java | 652 ++- groupmanager-pom.xml | 62 +- nbactions.xml | 53 +- pom.xml | 717 +-- 380 files changed, 38917 insertions(+), 46821 deletions(-) diff --git a/Essentials/pom.xml b/Essentials/pom.xml index 34a420c18..10aab3432 100644 --- a/Essentials/pom.xml +++ b/Essentials/pom.xml @@ -1,45 +1,45 @@ - 4.0.0 + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - - net.ess3 - EssentialsParent - 2.x-SNAPSHOT - + + net.ess3 + EssentialsParent + 2.x-SNAPSHOT + - Essentials + Essentials - http://ess3.net/ + http://ess3.net/ - - Essentials Team - http://ess3.net/ - + + Essentials Team + http://ess3.net/ + - - - GPLv3 - http://www.gnu.org/copyleft/gpl.html - - + + + GPLv3 + http://www.gnu.org/copyleft/gpl.html + + - - scm:git:https://github.com/essentials/Essentials.git - scm:git:https://github.com/essentials/Essentials.git - https://github.com/essentials/Essentials - + + scm:git:https://github.com/essentials/Essentials.git + scm:git:https://github.com/essentials/Essentials.git + https://github.com/essentials/Essentials + - - JIRA - http://essentials3.atlassian.net - + + JIRA + http://essentials3.atlassian.net + - - TeamCity - http://ci.ess3.net/ - + + TeamCity + http://ci.ess3.net/ + @@ -53,92 +53,92 @@ - - org.bukkit - bukkit - 1.7.2-R0.3-SNAPSHOT - system - ${project.basedir}/../lib/bukkit.jar - - - BOSEconomy - BOSEconomy - v0.7.8.1 - system - ${project.basedir}/../lib/BOSEconomy.jar - - - de.bananaco - bPermissions - v2.12-DEV - - - iConomy - iConomy5 - 5 - system - ${project.basedir}/../lib/iCo5.jar - - - iConomy - iConomy6 - 6 - system - ${project.basedir}/../lib/iCo6.jar - - - net.ess3 - GroupManager - ${project.version} - system - ${project.basedir}/../EssentialsGroupManager/dist/EssentialsGroupManager.jar - - - MultiCurrency - MultiCurrency - 2.2 - system - ${project.basedir}/../lib/MultiCurrency.jar - - - com.platymuus - bukkit-permissions - 2.0 - system - ${project.basedir}/../lib/PermissionsBukkit.jar - - - ru.tehkode - PermissionsEx - 1.20.4 - system - ${project.basedir}/../lib/PermissionsEx.jar - - - Privileges - Privileges - 1.8.1 - system - ${project.basedir}/../lib/Privileges.jar - - - SimplyPerms - SimplyPerms - 1.7.6 - system - ${project.basedir}/../lib/SimplyPerms.jar - - - net.milkbowl.vault - Vault - 1.2.32 - - - zPermissions - zPermissions - 1.1 - system - ${project.basedir}/../lib/zPermissions.jar - - + + org.bukkit + bukkit + 1.7.2-R0.3-SNAPSHOT + system + ${project.basedir}/../lib/bukkit.jar + + + BOSEconomy + BOSEconomy + v0.7.8.1 + system + ${project.basedir}/../lib/BOSEconomy.jar + + + de.bananaco + bPermissions + v2.12-DEV + + + iConomy + iConomy5 + 5 + system + ${project.basedir}/../lib/iCo5.jar + + + iConomy + iConomy6 + 6 + system + ${project.basedir}/../lib/iCo6.jar + + + net.ess3 + GroupManager + ${project.version} + system + ${project.basedir}/../EssentialsGroupManager/dist/EssentialsGroupManager.jar + + + MultiCurrency + MultiCurrency + 2.2 + system + ${project.basedir}/../lib/MultiCurrency.jar + + + com.platymuus + bukkit-permissions + 2.0 + system + ${project.basedir}/../lib/PermissionsBukkit.jar + + + ru.tehkode + PermissionsEx + 1.20.4 + system + ${project.basedir}/../lib/PermissionsEx.jar + + + Privileges + Privileges + 1.8.1 + system + ${project.basedir}/../lib/Privileges.jar + + + SimplyPerms + SimplyPerms + 1.7.6 + system + ${project.basedir}/../lib/SimplyPerms.jar + + + net.milkbowl.vault + Vault + 1.2.32 + + + zPermissions + zPermissions + 1.1 + system + ${project.basedir}/../lib/zPermissions.jar + + diff --git a/Essentials/src/com/earth2me/essentials/AlternativeCommandsHandler.java b/Essentials/src/com/earth2me/essentials/AlternativeCommandsHandler.java index 3016ffe59..1822f2cd2 100644 --- a/Essentials/src/com/earth2me/essentials/AlternativeCommandsHandler.java +++ b/Essentials/src/com/earth2me/essentials/AlternativeCommandsHandler.java @@ -1,139 +1,113 @@ package com.earth2me.essentials; -import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; import net.ess3.api.IEssentials; import org.bukkit.command.Command; import org.bukkit.command.PluginCommand; import org.bukkit.command.PluginCommandYamlParser; import org.bukkit.plugin.Plugin; +import java.util.*; +import java.util.logging.Level; +import java.util.logging.Logger; -public class AlternativeCommandsHandler -{ - private static final Logger LOGGER = Logger.getLogger("Essentials"); - private final transient Map> altcommands = new HashMap>(); - private final transient Map disabledList = new HashMap(); - private final transient IEssentials ess; - public AlternativeCommandsHandler(final IEssentials ess) - { - this.ess = ess; - for (Plugin plugin : ess.getServer().getPluginManager().getPlugins()) - { - if (plugin.isEnabled()) - { - addPlugin(plugin); - } - } - } +public class AlternativeCommandsHandler { + private static final Logger LOGGER = Logger.getLogger("Essentials"); + private final transient Map> altcommands = new HashMap>(); + private final transient Map disabledList = new HashMap(); + private final transient IEssentials ess; - 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); + public AlternativeCommandsHandler(final IEssentials ess) { + this.ess = ess; + for (Plugin plugin : ess.getServer().getPluginManager().getPlugins()) { + if (plugin.isEnabled()) { + addPlugin(plugin); + } + } + } - for (Command command : commands) - { - final PluginCommand pc = (PluginCommand)command; - final List labels = new ArrayList(pc.getAliases()); - labels.add(pc.getName()); + 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); - 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); - } - } - } - } + for (Command command : commands) { + final PluginCommand pc = (PluginCommand) command; + final List labels = new ArrayList(pc.getAliases()); + labels.add(pc.getName()); - 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(); - } - } - } + 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 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 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 void executed(final String label, final PluginCommand pc) - { - final String altString = pc.getPlugin().getName() + ":" + pc.getLabel(); - if (ess.getSettings().isDebug()) - { - LOGGER.log(Level.INFO, "Essentials: Alternative command " + label + " found, using " + altString); - } - disabledList.put(label, altString); - } + 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 Map disabledCommands() - { - return disabledList; - } + public void executed(final String label, final PluginCommand pc) { + final String altString = pc.getPlugin().getName() + ":" + pc.getLabel(); + if (ess.getSettings().isDebug()) { + LOGGER.log(Level.INFO, "Essentials: Alternative command " + label + " found, using " + altString); + } + disabledList.put(label, altString); + } + + public Map disabledCommands() { + return disabledList; + } } diff --git a/Essentials/src/com/earth2me/essentials/Backup.java b/Essentials/src/com/earth2me/essentials/Backup.java index 889d2cbfe..1e9115e87 100644 --- a/Essentials/src/com/earth2me/essentials/Backup.java +++ b/Essentials/src/com/earth2me/essentials/Backup.java @@ -1,168 +1,132 @@ package com.earth2me.essentials; -import static com.earth2me.essentials.I18n.tl; +import net.ess3.api.IEssentials; +import org.bukkit.Server; +import org.bukkit.command.CommandSender; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.logging.Level; import java.util.logging.Logger; -import net.ess3.api.IEssentials; -import org.bukkit.Server; -import org.bukkit.command.CommandSender; + +import static com.earth2me.essentials.I18n.tl; -public class Backup implements Runnable -{ - private static final Logger LOGGER = Logger.getLogger("Essentials"); - private transient final Server server; - private transient final IEssentials ess; - private transient boolean running = false; - private transient int taskId = -1; - private transient boolean active = false; +public class Backup implements Runnable { + private static final Logger LOGGER = Logger.getLogger("Essentials"); + private transient final Server server; + private transient final IEssentials ess; + private transient boolean running = false; + private transient int taskId = -1; + private transient boolean active = false; - public Backup(final IEssentials ess) - { - this.ess = ess; - server = ess.getServer(); - if (!ess.getOnlinePlayers().isEmpty()) - { - ess.runTaskAsynchronously(new Runnable() - { - @Override - public void run() - { - startTask(); - } - }); - } - } + public Backup(final IEssentials ess) { + this.ess = ess; + server = ess.getServer(); + if (!ess.getOnlinePlayers().isEmpty()) { + ess.runTaskAsynchronously(new Runnable() { + @Override + public void run() { + startTask(); + } + }); + } + } - public void onPlayerJoin() - { - startTask(); - } + public void onPlayerJoin() { + startTask(); + } - public synchronized void stopTask() - { - running = false; - if (taskId != -1) - { - server.getScheduler().cancelTask(taskId); - } - taskId = -1; - } + public synchronized void stopTask() { + running = false; + if (taskId != -1) { + server.getScheduler().cancelTask(taskId); + } + taskId = -1; + } - private synchronized void startTask() - { - if (!running) - { - final long interval = ess.getSettings().getBackupInterval() * 1200; // minutes -> ticks - if (interval < 1200) - { - return; - } - taskId = ess.scheduleSyncRepeatingTask(this, interval, interval); - running = true; - } - } + private synchronized void startTask() { + if (!running) { + final long interval = ess.getSettings().getBackupInterval() * 1200; // minutes -> ticks + if (interval < 1200) { + return; + } + taskId = ess.scheduleSyncRepeatingTask(this, interval, interval); + running = true; + } + } - @Override - public void run() - { - if (active) - { - return; - } - active = true; - final String command = ess.getSettings().getBackupCommand(); - if (command == null || "".equals(command)) - { - return; - } - if ("save-all".equalsIgnoreCase(command)) - { - final CommandSender cs = server.getConsoleSender(); - server.dispatchCommand(cs, "save-all"); - active = false; - return; - } - LOGGER.log(Level.INFO, tl("backupStarted")); - final CommandSender cs = server.getConsoleSender(); - server.dispatchCommand(cs, "save-all"); - server.dispatchCommand(cs, "save-off"); + @Override + public void run() { + if (active) { + return; + } + active = true; + final String command = ess.getSettings().getBackupCommand(); + if (command == null || "".equals(command)) { + return; + } + if ("save-all".equalsIgnoreCase(command)) { + final CommandSender cs = server.getConsoleSender(); + server.dispatchCommand(cs, "save-all"); + active = false; + return; + } + LOGGER.log(Level.INFO, tl("backupStarted")); + final CommandSender cs = server.getConsoleSender(); + server.dispatchCommand(cs, "save-all"); + server.dispatchCommand(cs, "save-off"); - ess.runTaskAsynchronously(new Runnable() - { - @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(); - ess.runTaskAsynchronously(new Runnable() - { - @Override - public void run() - { - try - { - final BufferedReader reader = new BufferedReader(new InputStreamReader(child.getInputStream())); - try - { - String line; - do - { - line = reader.readLine(); - if (line != null) - { - LOGGER.log(Level.INFO, line); - } - } - while (line != null); - } - finally - { - reader.close(); - } - } - catch (IOException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - } - }); - child.waitFor(); - } - catch (InterruptedException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - catch (IOException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - finally - { - class BackupEnableSaveTask implements Runnable - { - @Override - public void run() - { - server.dispatchCommand(cs, "save-on"); - if (ess.getOnlinePlayers().isEmpty()) - { - stopTask(); - } - active = false; - LOGGER.log(Level.INFO, tl("backupFinished")); - } - } - ess.scheduleSyncDelayedTask(new BackupEnableSaveTask()); - } - } - }); - } + ess.runTaskAsynchronously(new Runnable() { + @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(); + ess.runTaskAsynchronously(new Runnable() { + @Override + public void run() { + try { + final BufferedReader reader = new BufferedReader(new InputStreamReader(child.getInputStream())); + try { + String line; + do { + line = reader.readLine(); + if (line != null) { + LOGGER.log(Level.INFO, line); + } + } while (line != null); + } finally { + reader.close(); + } + } catch (IOException ex) { + LOGGER.log(Level.SEVERE, null, ex); + } + } + }); + child.waitFor(); + } catch (InterruptedException ex) { + LOGGER.log(Level.SEVERE, null, ex); + } catch (IOException ex) { + LOGGER.log(Level.SEVERE, null, ex); + } finally { + class BackupEnableSaveTask implements Runnable { + @Override + public void run() { + server.dispatchCommand(cs, "save-on"); + if (ess.getOnlinePlayers().isEmpty()) { + stopTask(); + } + active = false; + LOGGER.log(Level.INFO, tl("backupFinished")); + } + } + ess.scheduleSyncDelayedTask(new BackupEnableSaveTask()); + } + } + }); + } } diff --git a/Essentials/src/com/earth2me/essentials/ChargeException.java b/Essentials/src/com/earth2me/essentials/ChargeException.java index 2fa4c7289..1c2644aab 100644 --- a/Essentials/src/com/earth2me/essentials/ChargeException.java +++ b/Essentials/src/com/earth2me/essentials/ChargeException.java @@ -1,15 +1,12 @@ package com.earth2me.essentials; -public class ChargeException extends Exception -{ - public ChargeException(final String message) - { - super(message); - } +public class ChargeException extends Exception { + public ChargeException(final String message) { + super(message); + } - public ChargeException(final String message, final Throwable throwable) - { - super(message, throwable); - } + public ChargeException(final String message, final Throwable throwable) { + super(message, throwable); + } } diff --git a/Essentials/src/com/earth2me/essentials/CommandSource.java b/Essentials/src/com/earth2me/essentials/CommandSource.java index 689431a37..bb9049553 100644 --- a/Essentials/src/com/earth2me/essentials/CommandSource.java +++ b/Essentials/src/com/earth2me/essentials/CommandSource.java @@ -4,58 +4,47 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -public class CommandSource implements IReplyTo -{ - private CommandSource replyTo = null; - protected CommandSender sender; +public class CommandSource implements IReplyTo { + private CommandSource replyTo = null; + protected CommandSender sender; - public CommandSource(final CommandSender base) - { - this.sender = base; - } + public CommandSource(final CommandSender base) { + this.sender = base; + } - public final CommandSender getSender() - { - return sender; - } + public final CommandSender getSender() { + return sender; + } - public final Player getPlayer() - { - if (sender instanceof Player) - { - return (Player)sender; - } - return null; - } - - public final boolean isPlayer() - { - return (sender instanceof Player); - } + public final Player getPlayer() { + if (sender instanceof Player) { + return (Player) sender; + } + return null; + } - public final CommandSender setSender(final CommandSender base) - { - return this.sender = base; - } - - - public void sendMessage(String message) - { - if (!message.isEmpty()) - { - sender.sendMessage(message); - } - } + public final boolean isPlayer() { + return (sender instanceof Player); + } - @Override - public void setReplyTo(final CommandSource user) - { - replyTo = user; - } + public final CommandSender setSender(final CommandSender base) { + return this.sender = base; + } - @Override - public CommandSource getReplyTo() - { - return replyTo; - } + + public void sendMessage(String message) { + if (!message.isEmpty()) { + sender.sendMessage(message); + } + } + + @Override + public void setReplyTo(final CommandSource user) { + replyTo = user; + } + + @Override + public CommandSource getReplyTo() { + return replyTo; + } } diff --git a/Essentials/src/com/earth2me/essentials/Console.java b/Essentials/src/com/earth2me/essentials/Console.java index 3954bbb0f..7e560ba81 100644 --- a/Essentials/src/com/earth2me/essentials/Console.java +++ b/Essentials/src/com/earth2me/essentials/Console.java @@ -4,35 +4,29 @@ import org.bukkit.Server; import org.bukkit.command.CommandSender; -public final class Console implements IReplyTo -{ - private static final Console instance = new Console(); - private CommandSource replyTo; - public final static String NAME = "Console"; +public final class Console implements IReplyTo { + private static final Console instance = new Console(); + private CommandSource replyTo; + public final static String NAME = "Console"; - private Console() - { - } + private Console() { + } - public static CommandSender getCommandSender(Server server) throws Exception - { - return server.getConsoleSender(); - } + public static CommandSender getCommandSender(Server server) throws Exception { + return server.getConsoleSender(); + } - @Override - public void setReplyTo(CommandSource user) - { - replyTo = user; - } + @Override + public void setReplyTo(CommandSource user) { + replyTo = user; + } - @Override - public CommandSource getReplyTo() - { - return replyTo; - } + @Override + public CommandSource getReplyTo() { + return replyTo; + } - public static Console getConsoleReplyTo() - { - return instance; - } + public static Console getConsoleReplyTo() { + return instance; + } } diff --git a/Essentials/src/com/earth2me/essentials/Enchantments.java b/Essentials/src/com/earth2me/essentials/Enchantments.java index de987ba0f..17b12fb8a 100644 --- a/Essentials/src/com/earth2me/essentials/Enchantments.java +++ b/Essentials/src/com/earth2me/essentials/Enchantments.java @@ -1,180 +1,172 @@ package com.earth2me.essentials; import com.earth2me.essentials.utils.NumberUtil; +import org.bukkit.enchantments.Enchantment; + import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Set; -import org.bukkit.enchantments.Enchantment; -public class Enchantments -{ - private static final Map ENCHANTMENTS = new HashMap(); - private static final Map ALIASENCHANTMENTS = new HashMap(); +public class Enchantments { + private static final Map ENCHANTMENTS = new HashMap(); + private static final Map ALIASENCHANTMENTS = new HashMap(); - static - { - ENCHANTMENTS.put("alldamage", Enchantment.DAMAGE_ALL); - ALIASENCHANTMENTS.put("alldmg", Enchantment.DAMAGE_ALL); - ENCHANTMENTS.put("sharpness", Enchantment.DAMAGE_ALL); - ALIASENCHANTMENTS.put("sharp", Enchantment.DAMAGE_ALL); - ALIASENCHANTMENTS.put("dal", Enchantment.DAMAGE_ALL); + static { + ENCHANTMENTS.put("alldamage", Enchantment.DAMAGE_ALL); + ALIASENCHANTMENTS.put("alldmg", Enchantment.DAMAGE_ALL); + ENCHANTMENTS.put("sharpness", Enchantment.DAMAGE_ALL); + ALIASENCHANTMENTS.put("sharp", Enchantment.DAMAGE_ALL); + ALIASENCHANTMENTS.put("dal", Enchantment.DAMAGE_ALL); - ENCHANTMENTS.put("ardmg", Enchantment.DAMAGE_ARTHROPODS); - ENCHANTMENTS.put("baneofarthropods", Enchantment.DAMAGE_ARTHROPODS); - ALIASENCHANTMENTS.put("baneofarthropod", Enchantment.DAMAGE_ARTHROPODS); - ALIASENCHANTMENTS.put("arthropod", Enchantment.DAMAGE_ARTHROPODS); - ALIASENCHANTMENTS.put("dar", Enchantment.DAMAGE_ARTHROPODS); + ENCHANTMENTS.put("ardmg", Enchantment.DAMAGE_ARTHROPODS); + ENCHANTMENTS.put("baneofarthropods", Enchantment.DAMAGE_ARTHROPODS); + ALIASENCHANTMENTS.put("baneofarthropod", Enchantment.DAMAGE_ARTHROPODS); + ALIASENCHANTMENTS.put("arthropod", Enchantment.DAMAGE_ARTHROPODS); + ALIASENCHANTMENTS.put("dar", Enchantment.DAMAGE_ARTHROPODS); - ENCHANTMENTS.put("undeaddamage", Enchantment.DAMAGE_UNDEAD); - ENCHANTMENTS.put("smite", Enchantment.DAMAGE_UNDEAD); - ALIASENCHANTMENTS.put("du", Enchantment.DAMAGE_UNDEAD); + ENCHANTMENTS.put("undeaddamage", Enchantment.DAMAGE_UNDEAD); + ENCHANTMENTS.put("smite", Enchantment.DAMAGE_UNDEAD); + ALIASENCHANTMENTS.put("du", Enchantment.DAMAGE_UNDEAD); - ENCHANTMENTS.put("digspeed", Enchantment.DIG_SPEED); - ENCHANTMENTS.put("efficiency", Enchantment.DIG_SPEED); - ALIASENCHANTMENTS.put("minespeed", Enchantment.DIG_SPEED); - ALIASENCHANTMENTS.put("cutspeed", Enchantment.DIG_SPEED); - ALIASENCHANTMENTS.put("ds", Enchantment.DIG_SPEED); - ALIASENCHANTMENTS.put("eff", Enchantment.DIG_SPEED); + ENCHANTMENTS.put("digspeed", Enchantment.DIG_SPEED); + ENCHANTMENTS.put("efficiency", Enchantment.DIG_SPEED); + ALIASENCHANTMENTS.put("minespeed", Enchantment.DIG_SPEED); + ALIASENCHANTMENTS.put("cutspeed", Enchantment.DIG_SPEED); + ALIASENCHANTMENTS.put("ds", Enchantment.DIG_SPEED); + ALIASENCHANTMENTS.put("eff", Enchantment.DIG_SPEED); - ENCHANTMENTS.put("durability", Enchantment.DURABILITY); - ALIASENCHANTMENTS.put("dura", Enchantment.DURABILITY); - ENCHANTMENTS.put("unbreaking", Enchantment.DURABILITY); - ALIASENCHANTMENTS.put("d", Enchantment.DURABILITY); + ENCHANTMENTS.put("durability", Enchantment.DURABILITY); + ALIASENCHANTMENTS.put("dura", Enchantment.DURABILITY); + ENCHANTMENTS.put("unbreaking", Enchantment.DURABILITY); + ALIASENCHANTMENTS.put("d", Enchantment.DURABILITY); - ENCHANTMENTS.put("thorns", Enchantment.THORNS); - ENCHANTMENTS.put("highcrit", Enchantment.THORNS); - ALIASENCHANTMENTS.put("thorn", Enchantment.THORNS); - ALIASENCHANTMENTS.put("highercrit", Enchantment.THORNS); - ALIASENCHANTMENTS.put("t", Enchantment.THORNS); + ENCHANTMENTS.put("thorns", Enchantment.THORNS); + ENCHANTMENTS.put("highcrit", Enchantment.THORNS); + ALIASENCHANTMENTS.put("thorn", Enchantment.THORNS); + ALIASENCHANTMENTS.put("highercrit", Enchantment.THORNS); + ALIASENCHANTMENTS.put("t", Enchantment.THORNS); - ENCHANTMENTS.put("fireaspect", Enchantment.FIRE_ASPECT); - ENCHANTMENTS.put("fire", Enchantment.FIRE_ASPECT); - ALIASENCHANTMENTS.put("meleefire", Enchantment.FIRE_ASPECT); - ALIASENCHANTMENTS.put("meleeflame", Enchantment.FIRE_ASPECT); - ALIASENCHANTMENTS.put("fa", Enchantment.FIRE_ASPECT); + ENCHANTMENTS.put("fireaspect", Enchantment.FIRE_ASPECT); + ENCHANTMENTS.put("fire", Enchantment.FIRE_ASPECT); + ALIASENCHANTMENTS.put("meleefire", Enchantment.FIRE_ASPECT); + ALIASENCHANTMENTS.put("meleeflame", Enchantment.FIRE_ASPECT); + ALIASENCHANTMENTS.put("fa", Enchantment.FIRE_ASPECT); - ENCHANTMENTS.put("knockback", Enchantment.KNOCKBACK); - ALIASENCHANTMENTS.put("kback", Enchantment.KNOCKBACK); - ALIASENCHANTMENTS.put("kb", Enchantment.KNOCKBACK); - ALIASENCHANTMENTS.put("k", Enchantment.KNOCKBACK); + ENCHANTMENTS.put("knockback", Enchantment.KNOCKBACK); + ALIASENCHANTMENTS.put("kback", Enchantment.KNOCKBACK); + ALIASENCHANTMENTS.put("kb", Enchantment.KNOCKBACK); + ALIASENCHANTMENTS.put("k", Enchantment.KNOCKBACK); - ALIASENCHANTMENTS.put("blockslootbonus", Enchantment.LOOT_BONUS_BLOCKS); - ENCHANTMENTS.put("fortune", Enchantment.LOOT_BONUS_BLOCKS); - ALIASENCHANTMENTS.put("fort", Enchantment.LOOT_BONUS_BLOCKS); - ALIASENCHANTMENTS.put("lbb", Enchantment.LOOT_BONUS_BLOCKS); + ALIASENCHANTMENTS.put("blockslootbonus", Enchantment.LOOT_BONUS_BLOCKS); + ENCHANTMENTS.put("fortune", Enchantment.LOOT_BONUS_BLOCKS); + ALIASENCHANTMENTS.put("fort", Enchantment.LOOT_BONUS_BLOCKS); + ALIASENCHANTMENTS.put("lbb", Enchantment.LOOT_BONUS_BLOCKS); - ALIASENCHANTMENTS.put("mobslootbonus", Enchantment.LOOT_BONUS_MOBS); - ENCHANTMENTS.put("mobloot", Enchantment.LOOT_BONUS_MOBS); - ENCHANTMENTS.put("looting", Enchantment.LOOT_BONUS_MOBS); - ALIASENCHANTMENTS.put("lbm", Enchantment.LOOT_BONUS_MOBS); + ALIASENCHANTMENTS.put("mobslootbonus", Enchantment.LOOT_BONUS_MOBS); + ENCHANTMENTS.put("mobloot", Enchantment.LOOT_BONUS_MOBS); + ENCHANTMENTS.put("looting", Enchantment.LOOT_BONUS_MOBS); + ALIASENCHANTMENTS.put("lbm", Enchantment.LOOT_BONUS_MOBS); - ALIASENCHANTMENTS.put("oxygen", Enchantment.OXYGEN); - ENCHANTMENTS.put("respiration", Enchantment.OXYGEN); - ALIASENCHANTMENTS.put("breathing", Enchantment.OXYGEN); - ENCHANTMENTS.put("breath", Enchantment.OXYGEN); - ALIASENCHANTMENTS.put("o", Enchantment.OXYGEN); + ALIASENCHANTMENTS.put("oxygen", Enchantment.OXYGEN); + ENCHANTMENTS.put("respiration", Enchantment.OXYGEN); + ALIASENCHANTMENTS.put("breathing", Enchantment.OXYGEN); + ENCHANTMENTS.put("breath", Enchantment.OXYGEN); + ALIASENCHANTMENTS.put("o", Enchantment.OXYGEN); - ENCHANTMENTS.put("protection", Enchantment.PROTECTION_ENVIRONMENTAL); - ALIASENCHANTMENTS.put("prot", Enchantment.PROTECTION_ENVIRONMENTAL); - ENCHANTMENTS.put("protect", Enchantment.PROTECTION_ENVIRONMENTAL); - ALIASENCHANTMENTS.put("p", Enchantment.PROTECTION_ENVIRONMENTAL); + ENCHANTMENTS.put("protection", Enchantment.PROTECTION_ENVIRONMENTAL); + ALIASENCHANTMENTS.put("prot", Enchantment.PROTECTION_ENVIRONMENTAL); + ENCHANTMENTS.put("protect", Enchantment.PROTECTION_ENVIRONMENTAL); + ALIASENCHANTMENTS.put("p", Enchantment.PROTECTION_ENVIRONMENTAL); - ALIASENCHANTMENTS.put("explosionsprotection", Enchantment.PROTECTION_EXPLOSIONS); - ALIASENCHANTMENTS.put("explosionprotection", Enchantment.PROTECTION_EXPLOSIONS); - ALIASENCHANTMENTS.put("expprot", Enchantment.PROTECTION_EXPLOSIONS); - ALIASENCHANTMENTS.put("blastprotection", Enchantment.PROTECTION_EXPLOSIONS); - ALIASENCHANTMENTS.put("bprotection", Enchantment.PROTECTION_EXPLOSIONS); - ALIASENCHANTMENTS.put("bprotect", Enchantment.PROTECTION_EXPLOSIONS); - ENCHANTMENTS.put("blastprotect", Enchantment.PROTECTION_EXPLOSIONS); - ALIASENCHANTMENTS.put("pe", Enchantment.PROTECTION_EXPLOSIONS); + ALIASENCHANTMENTS.put("explosionsprotection", Enchantment.PROTECTION_EXPLOSIONS); + ALIASENCHANTMENTS.put("explosionprotection", Enchantment.PROTECTION_EXPLOSIONS); + ALIASENCHANTMENTS.put("expprot", Enchantment.PROTECTION_EXPLOSIONS); + ALIASENCHANTMENTS.put("blastprotection", Enchantment.PROTECTION_EXPLOSIONS); + ALIASENCHANTMENTS.put("bprotection", Enchantment.PROTECTION_EXPLOSIONS); + ALIASENCHANTMENTS.put("bprotect", Enchantment.PROTECTION_EXPLOSIONS); + ENCHANTMENTS.put("blastprotect", Enchantment.PROTECTION_EXPLOSIONS); + ALIASENCHANTMENTS.put("pe", Enchantment.PROTECTION_EXPLOSIONS); - ALIASENCHANTMENTS.put("fallprotection", Enchantment.PROTECTION_FALL); - ENCHANTMENTS.put("fallprot", Enchantment.PROTECTION_FALL); - ENCHANTMENTS.put("featherfall", Enchantment.PROTECTION_FALL); - ALIASENCHANTMENTS.put("featherfalling", Enchantment.PROTECTION_FALL); - ALIASENCHANTMENTS.put("pfa", Enchantment.PROTECTION_FALL); + ALIASENCHANTMENTS.put("fallprotection", Enchantment.PROTECTION_FALL); + ENCHANTMENTS.put("fallprot", Enchantment.PROTECTION_FALL); + ENCHANTMENTS.put("featherfall", Enchantment.PROTECTION_FALL); + ALIASENCHANTMENTS.put("featherfalling", Enchantment.PROTECTION_FALL); + ALIASENCHANTMENTS.put("pfa", Enchantment.PROTECTION_FALL); - ALIASENCHANTMENTS.put("fireprotection", Enchantment.PROTECTION_FIRE); - ALIASENCHANTMENTS.put("flameprotection", Enchantment.PROTECTION_FIRE); - ENCHANTMENTS.put("fireprotect", Enchantment.PROTECTION_FIRE); - ALIASENCHANTMENTS.put("flameprotect", Enchantment.PROTECTION_FIRE); - ENCHANTMENTS.put("fireprot", Enchantment.PROTECTION_FIRE); - ALIASENCHANTMENTS.put("flameprot", Enchantment.PROTECTION_FIRE); - ALIASENCHANTMENTS.put("pf", Enchantment.PROTECTION_FIRE); + ALIASENCHANTMENTS.put("fireprotection", Enchantment.PROTECTION_FIRE); + ALIASENCHANTMENTS.put("flameprotection", Enchantment.PROTECTION_FIRE); + ENCHANTMENTS.put("fireprotect", Enchantment.PROTECTION_FIRE); + ALIASENCHANTMENTS.put("flameprotect", Enchantment.PROTECTION_FIRE); + ENCHANTMENTS.put("fireprot", Enchantment.PROTECTION_FIRE); + ALIASENCHANTMENTS.put("flameprot", Enchantment.PROTECTION_FIRE); + ALIASENCHANTMENTS.put("pf", Enchantment.PROTECTION_FIRE); - ENCHANTMENTS.put("projectileprotection", Enchantment.PROTECTION_PROJECTILE); - ENCHANTMENTS.put("projprot", Enchantment.PROTECTION_PROJECTILE); - ALIASENCHANTMENTS.put("pp", Enchantment.PROTECTION_PROJECTILE); + ENCHANTMENTS.put("projectileprotection", Enchantment.PROTECTION_PROJECTILE); + ENCHANTMENTS.put("projprot", Enchantment.PROTECTION_PROJECTILE); + ALIASENCHANTMENTS.put("pp", Enchantment.PROTECTION_PROJECTILE); - ENCHANTMENTS.put("silktouch", Enchantment.SILK_TOUCH); - ALIASENCHANTMENTS.put("softtouch", Enchantment.SILK_TOUCH); - ALIASENCHANTMENTS.put("st", Enchantment.SILK_TOUCH); + ENCHANTMENTS.put("silktouch", Enchantment.SILK_TOUCH); + ALIASENCHANTMENTS.put("softtouch", Enchantment.SILK_TOUCH); + ALIASENCHANTMENTS.put("st", Enchantment.SILK_TOUCH); - ENCHANTMENTS.put("waterworker", Enchantment.WATER_WORKER); - ENCHANTMENTS.put("aquaaffinity", Enchantment.WATER_WORKER); - ALIASENCHANTMENTS.put("watermine", Enchantment.WATER_WORKER); - ALIASENCHANTMENTS.put("ww", Enchantment.WATER_WORKER); + ENCHANTMENTS.put("waterworker", Enchantment.WATER_WORKER); + ENCHANTMENTS.put("aquaaffinity", Enchantment.WATER_WORKER); + ALIASENCHANTMENTS.put("watermine", Enchantment.WATER_WORKER); + ALIASENCHANTMENTS.put("ww", Enchantment.WATER_WORKER); - ALIASENCHANTMENTS.put("firearrow", Enchantment.ARROW_FIRE); - ENCHANTMENTS.put("flame", Enchantment.ARROW_FIRE); - ENCHANTMENTS.put("flamearrow", Enchantment.ARROW_FIRE); - ALIASENCHANTMENTS.put("af", Enchantment.ARROW_FIRE); + ALIASENCHANTMENTS.put("firearrow", Enchantment.ARROW_FIRE); + ENCHANTMENTS.put("flame", Enchantment.ARROW_FIRE); + ENCHANTMENTS.put("flamearrow", Enchantment.ARROW_FIRE); + ALIASENCHANTMENTS.put("af", Enchantment.ARROW_FIRE); - ENCHANTMENTS.put("arrowdamage", Enchantment.ARROW_DAMAGE); - ENCHANTMENTS.put("power", Enchantment.ARROW_DAMAGE); - ALIASENCHANTMENTS.put("arrowpower", Enchantment.ARROW_DAMAGE); - ALIASENCHANTMENTS.put("ad", Enchantment.ARROW_DAMAGE); + ENCHANTMENTS.put("arrowdamage", Enchantment.ARROW_DAMAGE); + ENCHANTMENTS.put("power", Enchantment.ARROW_DAMAGE); + ALIASENCHANTMENTS.put("arrowpower", Enchantment.ARROW_DAMAGE); + ALIASENCHANTMENTS.put("ad", Enchantment.ARROW_DAMAGE); - ENCHANTMENTS.put("arrowknockback", Enchantment.ARROW_KNOCKBACK); - ALIASENCHANTMENTS.put("arrowkb", Enchantment.ARROW_KNOCKBACK); - ENCHANTMENTS.put("punch", Enchantment.ARROW_KNOCKBACK); - ALIASENCHANTMENTS.put("arrowpunch", Enchantment.ARROW_KNOCKBACK); - ALIASENCHANTMENTS.put("ak", Enchantment.ARROW_KNOCKBACK); + ENCHANTMENTS.put("arrowknockback", Enchantment.ARROW_KNOCKBACK); + ALIASENCHANTMENTS.put("arrowkb", Enchantment.ARROW_KNOCKBACK); + ENCHANTMENTS.put("punch", Enchantment.ARROW_KNOCKBACK); + ALIASENCHANTMENTS.put("arrowpunch", Enchantment.ARROW_KNOCKBACK); + ALIASENCHANTMENTS.put("ak", Enchantment.ARROW_KNOCKBACK); - ALIASENCHANTMENTS.put("infinitearrows", Enchantment.ARROW_INFINITE); - ENCHANTMENTS.put("infarrows", Enchantment.ARROW_INFINITE); - ENCHANTMENTS.put("infinity", Enchantment.ARROW_INFINITE); - ALIASENCHANTMENTS.put("infinite", Enchantment.ARROW_INFINITE); - ALIASENCHANTMENTS.put("unlimited", Enchantment.ARROW_INFINITE); - ALIASENCHANTMENTS.put("unlimitedarrows", Enchantment.ARROW_INFINITE); - ALIASENCHANTMENTS.put("ai", Enchantment.ARROW_INFINITE); + ALIASENCHANTMENTS.put("infinitearrows", Enchantment.ARROW_INFINITE); + ENCHANTMENTS.put("infarrows", Enchantment.ARROW_INFINITE); + ENCHANTMENTS.put("infinity", Enchantment.ARROW_INFINITE); + ALIASENCHANTMENTS.put("infinite", Enchantment.ARROW_INFINITE); + ALIASENCHANTMENTS.put("unlimited", Enchantment.ARROW_INFINITE); + ALIASENCHANTMENTS.put("unlimitedarrows", Enchantment.ARROW_INFINITE); + ALIASENCHANTMENTS.put("ai", Enchantment.ARROW_INFINITE); - ENCHANTMENTS.put("luck", Enchantment.LUCK); - ALIASENCHANTMENTS.put("luckofsea", Enchantment.LUCK); - ALIASENCHANTMENTS.put("luckofseas", Enchantment.LUCK); - ALIASENCHANTMENTS.put("rodluck", Enchantment.LUCK); + ENCHANTMENTS.put("luck", Enchantment.LUCK); + ALIASENCHANTMENTS.put("luckofsea", Enchantment.LUCK); + ALIASENCHANTMENTS.put("luckofseas", Enchantment.LUCK); + ALIASENCHANTMENTS.put("rodluck", Enchantment.LUCK); - ENCHANTMENTS.put("lure", Enchantment.LURE); - ALIASENCHANTMENTS.put("rodlure", Enchantment.LURE); - } + ENCHANTMENTS.put("lure", Enchantment.LURE); + ALIASENCHANTMENTS.put("rodlure", Enchantment.LURE); + } - public static Enchantment getByName(String name) - { - Enchantment enchantment; - if (NumberUtil.isInt(name)) - { - enchantment = Enchantment.getById(Integer.parseInt(name)); - } - else - { - enchantment = Enchantment.getByName(name.toUpperCase(Locale.ENGLISH)); - } - if (enchantment == null) - { - enchantment = ENCHANTMENTS.get(name.toLowerCase(Locale.ENGLISH)); - } - if (enchantment == null) - { - enchantment = ALIASENCHANTMENTS.get(name.toLowerCase(Locale.ENGLISH)); - } - return enchantment; - } + public static Enchantment getByName(String name) { + Enchantment enchantment; + if (NumberUtil.isInt(name)) { + enchantment = Enchantment.getById(Integer.parseInt(name)); + } else { + enchantment = Enchantment.getByName(name.toUpperCase(Locale.ENGLISH)); + } + if (enchantment == null) { + enchantment = ENCHANTMENTS.get(name.toLowerCase(Locale.ENGLISH)); + } + if (enchantment == null) { + enchantment = ALIASENCHANTMENTS.get(name.toLowerCase(Locale.ENGLISH)); + } + return enchantment; + } - public static Set> entrySet() - { - return ENCHANTMENTS.entrySet(); - } + public static Set> entrySet() { + return ENCHANTMENTS.entrySet(); + } } diff --git a/Essentials/src/com/earth2me/essentials/Essentials.java b/Essentials/src/com/earth2me/essentials/Essentials.java index e8d0a5d3a..cc68a6c9a 100644 --- a/Essentials/src/com/earth2me/essentials/Essentials.java +++ b/Essentials/src/com/earth2me/essentials/Essentials.java @@ -17,12 +17,7 @@ */ package com.earth2me.essentials; -import static com.earth2me.essentials.I18n.tl; -import com.earth2me.essentials.commands.EssentialsCommand; -import com.earth2me.essentials.commands.IEssentialsCommand; -import com.earth2me.essentials.commands.NoChargeException; -import com.earth2me.essentials.commands.NotEnoughArgumentsException; -import com.earth2me.essentials.commands.QuietAbortException; +import com.earth2me.essentials.commands.*; import com.earth2me.essentials.metrics.Metrics; import com.earth2me.essentials.metrics.MetricsListener; import com.earth2me.essentials.metrics.MetricsStarter; @@ -38,35 +33,15 @@ import com.earth2me.essentials.utils.DateUtil; import com.google.common.base.Function; import com.google.common.base.Throwables; import com.google.common.collect.Iterables; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.UUID; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import net.ess3.api.Economy; +import net.ess3.api.*; import net.ess3.api.IEssentials; -import net.ess3.api.IItemDb; -import net.ess3.api.IJails; import net.ess3.api.ISettings; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Server; import org.bukkit.World; import org.bukkit.block.Block; -import org.bukkit.command.BlockCommandSender; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.command.PluginCommand; -import org.bukkit.command.TabCompleter; +import org.bukkit.command.*; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -85,906 +60,732 @@ import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.scheduler.BukkitTask; import org.yaml.snakeyaml.error.YAMLException; - -public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials -{ - public static final int BUKKIT_VERSION = 3050; - private static final Logger LOGGER = Logger.getLogger("Essentials"); - private transient ISettings settings; - private final transient TNTExplodeListener tntListener = new TNTExplodeListener(this); - private transient Jails jails; - private transient Warps warps; - private transient Worth worth; - private transient List confList; - private transient Backup backup; - private transient ItemDb itemDb; - private transient final Methods paymentMethod = new Methods(); - private transient PermissionsHandler permissionsHandler; - private transient AlternativeCommandsHandler alternativeCommandsHandler; - private transient UserMap userMap; - private transient ExecuteTimer execTimer; - private transient I18n i18n; - private transient Metrics metrics; - private transient EssentialsTimer timer; - private final transient List vanishedPlayers = new ArrayList(); - private transient Method oldGetOnlinePlayers; - - public Essentials() - { - } - - public Essentials(final Server server) - { - super(new JavaPluginLoader(server), new PluginDescriptionFile("Essentials", "", "com.earth2me.essentials.Essentials"), null, null); - } - - @Override - public ISettings getSettings() - { - return settings; - } - - public void setupForTesting(final Server server) throws IOException, InvalidDescriptionException - { - final File dataFolder = File.createTempFile("essentialstest", ""); - if (!dataFolder.delete()) - { - throw new IOException(); - } - if (!dataFolder.mkdir()) - { - throw new IOException(); - } - i18n = new I18n(this); - i18n.onEnable(); - i18n.updateLocale("en"); - LOGGER.log(Level.INFO, tl("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 Settings(this); - userMap = new UserMap(this); - permissionsHandler = new PermissionsHandler(this, false); - Economy.setEss(this); - confList = new ArrayList(); - jails = new Jails(this); - registerListeners(server.getPluginManager()); - } - - @Override - public void onEnable() - { - try - { - LOGGER.setParent(this.getLogger()); - 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, tl("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) - { - wrongVersion(); - this.setEnabled(false); - return; - } - } - else - { - LOGGER.log(Level.INFO, tl("bukkitFormatChanged")); - LOGGER.log(Level.INFO, getServer().getVersion()); - LOGGER.log(Level.INFO, getServer().getBukkitVersion()); - } - execTimer.mark("BukkitCheck"); - - for (Method method : Server.class.getDeclaredMethods()) - { - if (method.getName().endsWith("getOnlinePlayers") && method.getReturnType() == Player[].class) - { - oldGetOnlinePlayers = method; - break; - } - } - - try - { - final EssentialsUpgrade upgrade = new EssentialsUpgrade(this); - upgrade.beforeSettings(); - execTimer.mark("Upgrade"); - confList = new ArrayList(); - settings = new Settings(this); - confList.add(settings); - execTimer.mark("Settings"); - userMap = new UserMap(this); - confList.add(userMap); - execTimer.mark("Init(Usermap)"); - upgrade.afterSettings(); - execTimer.mark("Upgrade2"); - i18n.updateLocale(settings.getLocale()); - warps = new Warps(getServer(), this.getDataFolder()); - confList.add(warps); - execTimer.mark("Init(Spawn/Warp)"); - worth = new Worth(this.getDataFolder()); - confList.add(worth); - itemDb = new ItemDb(this); - confList.add(itemDb); - execTimer.mark("Init(Worth/ItemDB)"); - jails = new Jails(this); - confList.add(jails); - reload(); - } - catch (YAMLException exception) - { - if (pm.getPlugin("EssentialsUpdate") != null) - { - LOGGER.log(Level.SEVERE, tl("essentialsHelp2")); - } - else - { - LOGGER.log(Level.SEVERE, tl("essentialsHelp1")); - } - handleCrash(exception); - return; - } - backup = new Backup(this); - permissionsHandler = new PermissionsHandler(this, settings.useBukkitPermissions()); - alternativeCommandsHandler = new AlternativeCommandsHandler(this); - - timer = new EssentialsTimer(this); - scheduleSyncRepeatingTask(timer, 1000, 50); - - Economy.setEss(this); - execTimer.mark("RegHandler"); - - final MetricsStarter metricsStarter = new MetricsStarter(this); - if (metricsStarter.getStart() != null && metricsStarter.getStart() == true) - { - runTaskLaterAsynchronously(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); - } - } - catch (NumberFormatException ex) - { - handleCrash(ex); - } - catch (Error ex) - { - handleCrash(ex); - throw ex; - } - } - - @Override - public void saveConfig() - { - // We don't use any of the bukkit config writing, as this breaks our config file formatting. - } - - private void registerListeners(PluginManager pm) - { - HandlerList.unregisterAll(this); - - if (getSettings().isDebug()) - { - LOGGER.log(Level.INFO, "Registering Listeners"); - } - - final EssentialsPluginListener serverListener = new EssentialsPluginListener(this); - pm.registerEvents(serverListener, this); - confList.add(serverListener); - - final EssentialsPlayerListener playerListener = new EssentialsPlayerListener(this); - pm.registerEvents(playerListener, this); - - final EssentialsBlockListener blockListener = new EssentialsBlockListener(this); - pm.registerEvents(blockListener, this); - - final SignBlockListener signBlockListener = new SignBlockListener(this); - pm.registerEvents(signBlockListener, this); - - final SignPlayerListener signPlayerListener = new SignPlayerListener(this); - pm.registerEvents(signPlayerListener, this); - - final SignEntityListener signEntityListener = new SignEntityListener(this); - pm.registerEvents(signEntityListener, this); - - final EssentialsEntityListener entityListener = new EssentialsEntityListener(this); - pm.registerEvents(entityListener, this); - - final EssentialsWorldListener worldListener = new EssentialsWorldListener(this); - pm.registerEvents(worldListener, this); - - pm.registerEvents(tntListener, this); - - jails.resetListener(); - } - - @Override - public void onDisable() - { - for (User user : getOnlineUsers()) - { - if (user.isVanished()) - { - user.setVanished(false); - user.sendMessage(tl("unvanishedReload")); - } - user.stopTransaction(); - } - cleanupOpenInventories(); - if (i18n != null) - { - i18n.onDisable(); - } - if (backup != null) - { - backup.stopTask(); - } - Economy.setEss(null); - Trade.closeLog(); - getUserMap().getUUIDMap().forceWriteUUIDMap(); - - HandlerList.unregisterAll(this); - } - - @Override - public void reload() - { - Trade.closeLog(); - - for (IConf iConf : confList) - { - iConf.reloadConfig(); - execTimer.mark("Reload(" + iConf.getClass().getSimpleName() + ")"); - } - - i18n.updateLocale(settings.getLocale()); - - final PluginManager pm = getServer().getPluginManager(); - registerListeners(pm); - } - - @Override - public List onTabComplete(CommandSender sender, - Command command, - String commandLabel, - String[] args) - { - // Allow plugins to override the command via onCommand - if (!getSettings().isCommandOverridden(command.getName()) && (!commandLabel.startsWith("e") || commandLabel.equalsIgnoreCase(command.getName()))) - { - final PluginCommand pc = alternativeCommandsHandler.getAlternative(commandLabel); - if (pc != null) - { - try - { - TabCompleter completer = pc.getTabCompleter(); - if (completer != null) - { - return completer.onTabComplete(sender, command, commandLabel, args); - } - } - catch (final Exception ex) - { - Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); - } - } - } - return null; - } - - @Override - public boolean onCommand(final CommandSender sender, final Command command, final String commandLabel, final String[] args) - { - return onCommandEssentials(sender, command, commandLabel, args, Essentials.class.getClassLoader(), "com.earth2me.essentials.commands.Command", "essentials.", null); - } - - @Override - public boolean onCommandEssentials(final CommandSender cSender, final Command command, final String commandLabel, final String[] args, final ClassLoader classLoader, final String commandPath, final String permissionPrefix, final IEssentialsModule module) - { - // Allow plugins to override the command via onCommand - if (!getSettings().isCommandOverridden(command.getName()) && (!commandLabel.startsWith("e") || commandLabel.equalsIgnoreCase(command.getName()))) - { - final PluginCommand pc = alternativeCommandsHandler.getAlternative(commandLabel); - if (pc != null) - { - alternativeCommandsHandler.executed(commandLabel, pc); - try - { - return pc.execute(cSender, commandLabel, args); - } - catch (final Exception ex) - { - Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); - cSender.sendMessage(ChatColor.RED + "An internal error occurred while attempting to perform this command"); - return true; - } - } - } - - try - { - - User user = null; - Block bSenderBlock = null; - if (cSender instanceof Player) - { - user = getUser((Player)cSender); - } - else if (cSender instanceof BlockCommandSender) - { - BlockCommandSender bsender = (BlockCommandSender)cSender; - bSenderBlock = bsender.getBlock(); - } - - if (bSenderBlock != null) - { - Bukkit.getLogger().log(Level.INFO, "CommandBlock at {0},{1},{2} issued server command: /{3} {4}", new Object[] - { - bSenderBlock.getX(), bSenderBlock.getY(), bSenderBlock.getZ(), commandLabel, EssentialsCommand.getFinalArg(args, 0) - }); - } - else if (user == null) - { - Bukkit.getLogger().log(Level.INFO, "{0} issued server command: /{1} {2}", new Object[] - { - cSender.getName(), commandLabel, EssentialsCommand.getFinalArg(args, 0) - }); - } - - CommandSource sender = new CommandSource(cSender); - - // New mail notification - if (user != null && !getSettings().isCommandDisabled("mail") && !command.getName().equals("mail") && user.isAuthorized("essentials.mail")) - { - final List mail = user.getMails(); - if (mail != null && !mail.isEmpty()) - { - user.sendMessage(tl("youHaveNewMail", mail.size())); - } - } - - //Print version even if admin command is not available #easteregg - if (commandLabel.equalsIgnoreCase("essversion")) - { - sender.sendMessage("This server is running Essentials " + getDescription().getVersion()); - return true; - } - - // Check for disabled commands - if (getSettings().isCommandDisabled(commandLabel)) - { - return true; - } - - IEssentialsCommand cmd; - try - { - cmd = (IEssentialsCommand)classLoader.loadClass(commandPath + command.getName()).newInstance(); - cmd.setEssentials(this); - cmd.setEssentialsModule(module); - } - catch (Exception ex) - { - sender.sendMessage(tl("commandNotLoaded", commandLabel)); - LOGGER.log(Level.SEVERE, tl("commandNotLoaded", commandLabel), ex); - return true; - } - - // Check authorization - if (user != null && !user.isAuthorized(cmd, permissionPrefix)) - { - LOGGER.log(Level.INFO, tl("deniedAccessCommand", user.getName())); - user.sendMessage(tl("noAccessCommand")); - return true; - } - - if (user != null && user.isJailed() && !user.isAuthorized(cmd, "essentials.jail.allow.")) - { - if (user.getJailTimeout() > 0) - { - user.sendMessage(tl("playerJailedFor", user.getName(), DateUtil.formatDateDiff(user.getJailTimeout()))); - } - else - { - user.sendMessage(tl("jailMessage")); - } - return true; - } - - // Run the command - try - { - if (user == null) - { - cmd.run(getServer(), sender, commandLabel, command, args); - } - else - { - cmd.run(getServer(), user, commandLabel, command, args); - } - return true; - } - catch (NoChargeException ex) - { - return true; - } - catch (QuietAbortException 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 (Exception ex) - { - showError(sender, ex, commandLabel); - return true; - } - } - catch (Throwable ex) - { - LOGGER.log(Level.SEVERE, tl("commandFailed", commandLabel), ex); - return true; - } - } - - public void cleanupOpenInventories() - { - for (User user : getOnlineUsers()) - { - if (user.isRecipeSee()) - { - user.getBase().getOpenInventory().getTopInventory().clear(); - user.getBase().getOpenInventory().close(); - user.setRecipeSee(false); - } - if (user.isInvSee() || user.isEnderSee()) - { - user.getBase().getOpenInventory().close(); - user.setInvSee(false); - user.setEnderSee(false); - } - } - } - - @Override - public void showError(final CommandSource sender, final Throwable exception, final String commandLabel) - { - sender.sendMessage(tl("errorWithMessage", exception.getMessage())); - if (getSettings().isDebug()) - { - LOGGER.log(Level.INFO, tl("errorCallingCommand", commandLabel), exception); - } - } - - public static void wrongVersion() - { - LOGGER.log(Level.SEVERE, " * ! * ! * ! * ! * ! * ! * ! * ! * ! * ! * ! * ! *"); - LOGGER.log(Level.SEVERE, tl("notRecommendedBukkit")); - LOGGER.log(Level.SEVERE, tl("requiredBukkit", Integer.toString(BUKKIT_VERSION))); - LOGGER.log(Level.SEVERE, " * ! * ! * ! * ! * ! * ! * ! * ! * ! * ! * ! * ! *"); - } - - @Override - public BukkitScheduler getScheduler() - { - return this.getServer().getScheduler(); - } - - @Override - public IJails getJails() - { - return jails; - } - - @Override - public Warps getWarps() - { - return warps; - } - - @Override - public Worth getWorth() - { - return worth; - } - - @Override - public Backup getBackup() - { - return backup; - } - - @Override - public Metrics getMetrics() - { - return metrics; - } - - @Override - public void setMetrics(Metrics metrics) - { - this.metrics = metrics; - } - - @Deprecated - @Override - public User getUser(final Object base) - { - if (base instanceof Player) - { - return getUser((Player)base); - } - if (base instanceof org.bukkit.OfflinePlayer) - { - return getUser(((org.bukkit.OfflinePlayer)base).getUniqueId()); - } - if (base instanceof UUID) - { - return getUser((UUID)base); - } - if (base instanceof String) - { - return getOfflineUser((String)base); - } - return null; - } - - //This will return null if there is not a match. - @Override - public User getUser(final String base) - { - return getOfflineUser(base); - } - - //This will return null if there is not a match. - @Override - public User getUser(final UUID base) - { - return userMap.getUser(base); - } - - //This will return null if there is not a match. - @Override - public User getOfflineUser(final String name) - { - final User user = userMap.getUser(name); - if (user != null && user.getBase() instanceof OfflinePlayer) - { - //This code should attempt to use the last known name of a user, if Bukkit returns name as null. - final String lastName = user.getLastAccountName(); - if (lastName != null) - { - ((OfflinePlayer)user.getBase()).setName(lastName); - } - else - { - ((OfflinePlayer)user.getBase()).setName(name); - } - } - return user; - } - - //This will create a new user if there is not a match. - @Override - public User getUser(final Player base) - { - if (base == null) - { - return null; - } - - if (userMap == null) - { - LOGGER.log(Level.WARNING, "Essentials userMap not initialized"); - return null; - } - - User user = userMap.getUser(base.getUniqueId()); - - if (user == null) - { - if (getSettings().isDebug()) - { - LOGGER.log(Level.INFO, "Constructing new userfile from base player {0}", base.getName()); - } - user = new User(base, this); - } - else - { - user.update(base); - } - return user; - } - - private void handleCrash(Throwable exception) - { - final PluginManager pm = getServer().getPluginManager(); - 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 : getOnlinePlayers()) - { - player.sendMessage("Essentials failed to load, read the log file."); - } - this.setEnabled(false); - } - - @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 IConf listener) - { - confList.add(listener); - } - - @Override - public Methods getPaymentMethod() - { - return paymentMethod; - } - - @Override - public int broadcastMessage(final String message) - { - return broadcastMessage(null, null, message, true); - } - - @Override - public int broadcastMessage(final IUser sender, final String message) - { - return broadcastMessage(sender, null, message, false); - } - - @Override - public int broadcastMessage(final String permission, final String message) - { - return broadcastMessage(null, permission, message, false); - } - - private int broadcastMessage(final IUser sender, final String permission, final String message, final boolean keywords) - { - if (sender != null && sender.isHidden()) - { - return 0; - } - - IText broadcast = new SimpleTextInput(message); - - final Collection players = getOnlinePlayers(); - - for (Player player : players) - { - final User user = getUser(player); - if ((permission == null && (sender == null || !user.isIgnoredPlayer(sender))) - || (permission != null && user.isAuthorized(permission))) - { - if (keywords) - { - broadcast = new KeywordReplacer(broadcast, new CommandSource(player), this, false); - } - for (String messageText : broadcast.getLines()) - { - user.sendMessage(messageText); - } - } - } - - return players.size(); - } - - @Override - public BukkitTask runTaskAsynchronously(final Runnable run) - { - return this.getScheduler().runTaskAsynchronously(this, run); - } - - @Override - public BukkitTask runTaskLaterAsynchronously(final Runnable run, final long delay) - { - return this.getScheduler().runTaskLaterAsynchronously(this, run, delay); - } - - @Override - public BukkitTask runTaskTimerAsynchronously(final Runnable run, final long delay, final long period) - { - return this.getScheduler().runTaskTimerAsynchronously(this, run, delay, period); - } - - @Override - public int scheduleSyncDelayedTask(final Runnable run) - { - return this.getScheduler().scheduleSyncDelayedTask(this, run); - } - - @Override - public int scheduleSyncDelayedTask(final Runnable run, final long delay) - { - return this.getScheduler().scheduleSyncDelayedTask(this, run, delay); - } - - @Override - public int scheduleSyncRepeatingTask(final Runnable run, final long delay, final long period) - { - return this.getScheduler().scheduleSyncRepeatingTask(this, run, delay, period); - } - - @Override - public TNTExplodeListener getTNTListener() - { - return tntListener; - } - - @Override - public PermissionsHandler getPermissionsHandler() - { - return permissionsHandler; - } - - @Override - public AlternativeCommandsHandler getAlternativeCommandsHandler() - { - return alternativeCommandsHandler; - } - - @Override - public IItemDb getItemDb() - { - return itemDb; - } - - @Override - public UserMap getUserMap() - { - return userMap; - } - - @Override - public I18n getI18n() - { - return i18n; - } - - @Override - public EssentialsTimer getTimer() - { - return timer; - } - - @Override - public List getVanishedPlayers() - { - return vanishedPlayers; - } - - @Override - public Collection getOnlinePlayers() - { - try - { - return (Collection)getServer().getOnlinePlayers(); // Needed for sanity here, the Bukkit API is a bit broken in the sense it only allows subclasses of Player to this list - } - catch (NoSuchMethodError ex) - { - try - { - return Arrays.asList((Player[])oldGetOnlinePlayers.invoke(getServer())); - } - catch (InvocationTargetException ex1) - { - throw Throwables.propagate(ex.getCause()); - } - catch (IllegalAccessException ex1) - { - throw new RuntimeException("Error invoking oldGetOnlinePlayers", ex1); - } - } - } - - @Override - public Iterable getOnlineUsers() - { - return Iterables.transform(getOnlinePlayers(), new Function() - { - - @Override - public User apply(Player player) - { - return getUser(player); - } - }); - } - - private static class EssentialsWorldListener implements Listener, Runnable - { - private transient final IEssentials ess; - - public EssentialsWorldListener(final IEssentials ess) - { - this.ess = ess; - } - - @EventHandler(priority = EventPriority.LOW) - public void onWorldLoad(final WorldLoadEvent event) - { - ess.getJails().onReload(); - ess.getWarps().reloadConfig(); - for (IConf iConf : ((Essentials)ess).confList) - { - if (iConf instanceof IEssentialsModule) - { - iConf.reloadConfig(); - } - } - } - - @EventHandler(priority = EventPriority.LOW) - public void onWorldUnload(final WorldUnloadEvent event) - { - ess.getJails().onReload(); - ess.getWarps().reloadConfig(); - for (IConf iConf : ((Essentials)ess).confList) - { - if (iConf instanceof IEssentialsModule) - { - iConf.reloadConfig(); - } - } - } - - @Override - public void run() - { - ess.reload(); - } - } +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.*; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static com.earth2me.essentials.I18n.tl; + + +public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials { + public static final int BUKKIT_VERSION = 3050; + private static final Logger LOGGER = Logger.getLogger("Essentials"); + private transient ISettings settings; + private final transient TNTExplodeListener tntListener = new TNTExplodeListener(this); + private transient Jails jails; + private transient Warps warps; + private transient Worth worth; + private transient List confList; + private transient Backup backup; + private transient ItemDb itemDb; + private transient final Methods paymentMethod = new Methods(); + private transient PermissionsHandler permissionsHandler; + private transient AlternativeCommandsHandler alternativeCommandsHandler; + private transient UserMap userMap; + private transient ExecuteTimer execTimer; + private transient I18n i18n; + private transient Metrics metrics; + private transient EssentialsTimer timer; + private final transient List vanishedPlayers = new ArrayList(); + private transient Method oldGetOnlinePlayers; + + public Essentials() { + } + + public Essentials(final Server server) { + super(new JavaPluginLoader(server), new PluginDescriptionFile("Essentials", "", "com.earth2me.essentials.Essentials"), null, null); + } + + @Override + public ISettings getSettings() { + return settings; + } + + public void setupForTesting(final Server server) throws IOException, InvalidDescriptionException { + final File dataFolder = File.createTempFile("essentialstest", ""); + if (!dataFolder.delete()) { + throw new IOException(); + } + if (!dataFolder.mkdir()) { + throw new IOException(); + } + i18n = new I18n(this); + i18n.onEnable(); + i18n.updateLocale("en"); + LOGGER.log(Level.INFO, tl("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 Settings(this); + userMap = new UserMap(this); + permissionsHandler = new PermissionsHandler(this, false); + Economy.setEss(this); + confList = new ArrayList(); + jails = new Jails(this); + registerListeners(server.getPluginManager()); + } + + @Override + public void onEnable() { + try { + LOGGER.setParent(this.getLogger()); + 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, tl("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) { + wrongVersion(); + this.setEnabled(false); + return; + } + } else { + LOGGER.log(Level.INFO, tl("bukkitFormatChanged")); + LOGGER.log(Level.INFO, getServer().getVersion()); + LOGGER.log(Level.INFO, getServer().getBukkitVersion()); + } + execTimer.mark("BukkitCheck"); + + for (Method method : Server.class.getDeclaredMethods()) { + if (method.getName().endsWith("getOnlinePlayers") && method.getReturnType() == Player[].class) { + oldGetOnlinePlayers = method; + break; + } + } + + try { + final EssentialsUpgrade upgrade = new EssentialsUpgrade(this); + upgrade.beforeSettings(); + execTimer.mark("Upgrade"); + confList = new ArrayList(); + settings = new Settings(this); + confList.add(settings); + execTimer.mark("Settings"); + userMap = new UserMap(this); + confList.add(userMap); + execTimer.mark("Init(Usermap)"); + upgrade.afterSettings(); + execTimer.mark("Upgrade2"); + i18n.updateLocale(settings.getLocale()); + warps = new Warps(getServer(), this.getDataFolder()); + confList.add(warps); + execTimer.mark("Init(Spawn/Warp)"); + worth = new Worth(this.getDataFolder()); + confList.add(worth); + itemDb = new ItemDb(this); + confList.add(itemDb); + execTimer.mark("Init(Worth/ItemDB)"); + jails = new Jails(this); + confList.add(jails); + reload(); + } catch (YAMLException exception) { + if (pm.getPlugin("EssentialsUpdate") != null) { + LOGGER.log(Level.SEVERE, tl("essentialsHelp2")); + } else { + LOGGER.log(Level.SEVERE, tl("essentialsHelp1")); + } + handleCrash(exception); + return; + } + backup = new Backup(this); + permissionsHandler = new PermissionsHandler(this, settings.useBukkitPermissions()); + alternativeCommandsHandler = new AlternativeCommandsHandler(this); + + timer = new EssentialsTimer(this); + scheduleSyncRepeatingTask(timer, 1000, 50); + + Economy.setEss(this); + execTimer.mark("RegHandler"); + + final MetricsStarter metricsStarter = new MetricsStarter(this); + if (metricsStarter.getStart() != null && metricsStarter.getStart() == true) { + runTaskLaterAsynchronously(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); + } + } catch (NumberFormatException ex) { + handleCrash(ex); + } catch (Error ex) { + handleCrash(ex); + throw ex; + } + } + + @Override + public void saveConfig() { + // We don't use any of the bukkit config writing, as this breaks our config file formatting. + } + + private void registerListeners(PluginManager pm) { + HandlerList.unregisterAll(this); + + if (getSettings().isDebug()) { + LOGGER.log(Level.INFO, "Registering Listeners"); + } + + final EssentialsPluginListener serverListener = new EssentialsPluginListener(this); + pm.registerEvents(serverListener, this); + confList.add(serverListener); + + final EssentialsPlayerListener playerListener = new EssentialsPlayerListener(this); + pm.registerEvents(playerListener, this); + + final EssentialsBlockListener blockListener = new EssentialsBlockListener(this); + pm.registerEvents(blockListener, this); + + final SignBlockListener signBlockListener = new SignBlockListener(this); + pm.registerEvents(signBlockListener, this); + + final SignPlayerListener signPlayerListener = new SignPlayerListener(this); + pm.registerEvents(signPlayerListener, this); + + final SignEntityListener signEntityListener = new SignEntityListener(this); + pm.registerEvents(signEntityListener, this); + + final EssentialsEntityListener entityListener = new EssentialsEntityListener(this); + pm.registerEvents(entityListener, this); + + final EssentialsWorldListener worldListener = new EssentialsWorldListener(this); + pm.registerEvents(worldListener, this); + + pm.registerEvents(tntListener, this); + + jails.resetListener(); + } + + @Override + public void onDisable() { + for (User user : getOnlineUsers()) { + if (user.isVanished()) { + user.setVanished(false); + user.sendMessage(tl("unvanishedReload")); + } + user.stopTransaction(); + } + cleanupOpenInventories(); + if (i18n != null) { + i18n.onDisable(); + } + if (backup != null) { + backup.stopTask(); + } + Economy.setEss(null); + Trade.closeLog(); + getUserMap().getUUIDMap().forceWriteUUIDMap(); + + HandlerList.unregisterAll(this); + } + + @Override + public void reload() { + Trade.closeLog(); + + for (IConf iConf : confList) { + iConf.reloadConfig(); + execTimer.mark("Reload(" + iConf.getClass().getSimpleName() + ")"); + } + + i18n.updateLocale(settings.getLocale()); + + final PluginManager pm = getServer().getPluginManager(); + registerListeners(pm); + } + + @Override + public List onTabComplete(CommandSender sender, Command command, String commandLabel, String[] args) { + // Allow plugins to override the command via onCommand + if (!getSettings().isCommandOverridden(command.getName()) && (!commandLabel.startsWith("e") || commandLabel.equalsIgnoreCase(command.getName()))) { + final PluginCommand pc = alternativeCommandsHandler.getAlternative(commandLabel); + if (pc != null) { + try { + TabCompleter completer = pc.getTabCompleter(); + if (completer != null) { + return completer.onTabComplete(sender, command, commandLabel, args); + } + } catch (final Exception ex) { + Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); + } + } + } + return null; + } + + @Override + public boolean onCommand(final CommandSender sender, final Command command, final String commandLabel, final String[] args) { + return onCommandEssentials(sender, command, commandLabel, args, Essentials.class.getClassLoader(), "com.earth2me.essentials.commands.Command", "essentials.", null); + } + + @Override + public boolean onCommandEssentials(final CommandSender cSender, final Command command, final String commandLabel, final String[] args, final ClassLoader classLoader, final String commandPath, final String permissionPrefix, final IEssentialsModule module) { + // Allow plugins to override the command via onCommand + if (!getSettings().isCommandOverridden(command.getName()) && (!commandLabel.startsWith("e") || commandLabel.equalsIgnoreCase(command.getName()))) { + final PluginCommand pc = alternativeCommandsHandler.getAlternative(commandLabel); + if (pc != null) { + alternativeCommandsHandler.executed(commandLabel, pc); + try { + return pc.execute(cSender, commandLabel, args); + } catch (final Exception ex) { + Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); + cSender.sendMessage(ChatColor.RED + "An internal error occurred while attempting to perform this command"); + return true; + } + } + } + + try { + + User user = null; + Block bSenderBlock = null; + if (cSender instanceof Player) { + user = getUser((Player) cSender); + } else if (cSender instanceof BlockCommandSender) { + BlockCommandSender bsender = (BlockCommandSender) cSender; + bSenderBlock = bsender.getBlock(); + } + + if (bSenderBlock != null) { + Bukkit.getLogger().log(Level.INFO, "CommandBlock at {0},{1},{2} issued server command: /{3} {4}", new Object[]{bSenderBlock.getX(), bSenderBlock.getY(), bSenderBlock.getZ(), commandLabel, EssentialsCommand.getFinalArg(args, 0)}); + } else if (user == null) { + Bukkit.getLogger().log(Level.INFO, "{0} issued server command: /{1} {2}", new Object[]{cSender.getName(), commandLabel, EssentialsCommand.getFinalArg(args, 0)}); + } + + CommandSource sender = new CommandSource(cSender); + + // New mail notification + if (user != null && !getSettings().isCommandDisabled("mail") && !command.getName().equals("mail") && user.isAuthorized("essentials.mail")) { + final List mail = user.getMails(); + if (mail != null && !mail.isEmpty()) { + user.sendMessage(tl("youHaveNewMail", mail.size())); + } + } + + //Print version even if admin command is not available #easteregg + if (commandLabel.equalsIgnoreCase("essversion")) { + sender.sendMessage("This server is running Essentials " + getDescription().getVersion()); + return true; + } + + // Check for disabled commands + if (getSettings().isCommandDisabled(commandLabel)) { + return true; + } + + IEssentialsCommand cmd; + try { + cmd = (IEssentialsCommand) classLoader.loadClass(commandPath + command.getName()).newInstance(); + cmd.setEssentials(this); + cmd.setEssentialsModule(module); + } catch (Exception ex) { + sender.sendMessage(tl("commandNotLoaded", commandLabel)); + LOGGER.log(Level.SEVERE, tl("commandNotLoaded", commandLabel), ex); + return true; + } + + // Check authorization + if (user != null && !user.isAuthorized(cmd, permissionPrefix)) { + LOGGER.log(Level.INFO, tl("deniedAccessCommand", user.getName())); + user.sendMessage(tl("noAccessCommand")); + return true; + } + + if (user != null && user.isJailed() && !user.isAuthorized(cmd, "essentials.jail.allow.")) { + if (user.getJailTimeout() > 0) { + user.sendMessage(tl("playerJailedFor", user.getName(), DateUtil.formatDateDiff(user.getJailTimeout()))); + } else { + user.sendMessage(tl("jailMessage")); + } + return true; + } + + // Run the command + try { + if (user == null) { + cmd.run(getServer(), sender, commandLabel, command, args); + } else { + cmd.run(getServer(), user, commandLabel, command, args); + } + return true; + } catch (NoChargeException ex) { + return true; + } catch (QuietAbortException 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 (Exception ex) { + showError(sender, ex, commandLabel); + return true; + } + } catch (Throwable ex) { + LOGGER.log(Level.SEVERE, tl("commandFailed", commandLabel), ex); + return true; + } + } + + public void cleanupOpenInventories() { + for (User user : getOnlineUsers()) { + if (user.isRecipeSee()) { + user.getBase().getOpenInventory().getTopInventory().clear(); + user.getBase().getOpenInventory().close(); + user.setRecipeSee(false); + } + if (user.isInvSee() || user.isEnderSee()) { + user.getBase().getOpenInventory().close(); + user.setInvSee(false); + user.setEnderSee(false); + } + } + } + + @Override + public void showError(final CommandSource sender, final Throwable exception, final String commandLabel) { + sender.sendMessage(tl("errorWithMessage", exception.getMessage())); + if (getSettings().isDebug()) { + LOGGER.log(Level.INFO, tl("errorCallingCommand", commandLabel), exception); + } + } + + public static void wrongVersion() { + LOGGER.log(Level.SEVERE, " * ! * ! * ! * ! * ! * ! * ! * ! * ! * ! * ! * ! *"); + LOGGER.log(Level.SEVERE, tl("notRecommendedBukkit")); + LOGGER.log(Level.SEVERE, tl("requiredBukkit", Integer.toString(BUKKIT_VERSION))); + LOGGER.log(Level.SEVERE, " * ! * ! * ! * ! * ! * ! * ! * ! * ! * ! * ! * ! *"); + } + + @Override + public BukkitScheduler getScheduler() { + return this.getServer().getScheduler(); + } + + @Override + public IJails getJails() { + return jails; + } + + @Override + public Warps getWarps() { + return warps; + } + + @Override + public Worth getWorth() { + return worth; + } + + @Override + public Backup getBackup() { + return backup; + } + + @Override + public Metrics getMetrics() { + return metrics; + } + + @Override + public void setMetrics(Metrics metrics) { + this.metrics = metrics; + } + + @Deprecated + @Override + public User getUser(final Object base) { + if (base instanceof Player) { + return getUser((Player) base); + } + if (base instanceof org.bukkit.OfflinePlayer) { + return getUser(((org.bukkit.OfflinePlayer) base).getUniqueId()); + } + if (base instanceof UUID) { + return getUser((UUID) base); + } + if (base instanceof String) { + return getOfflineUser((String) base); + } + return null; + } + + //This will return null if there is not a match. + @Override + public User getUser(final String base) { + return getOfflineUser(base); + } + + //This will return null if there is not a match. + @Override + public User getUser(final UUID base) { + return userMap.getUser(base); + } + + //This will return null if there is not a match. + @Override + public User getOfflineUser(final String name) { + final User user = userMap.getUser(name); + if (user != null && user.getBase() instanceof OfflinePlayer) { + //This code should attempt to use the last known name of a user, if Bukkit returns name as null. + final String lastName = user.getLastAccountName(); + if (lastName != null) { + ((OfflinePlayer) user.getBase()).setName(lastName); + } else { + ((OfflinePlayer) user.getBase()).setName(name); + } + } + return user; + } + + //This will create a new user if there is not a match. + @Override + public User getUser(final Player base) { + if (base == null) { + return null; + } + + if (userMap == null) { + LOGGER.log(Level.WARNING, "Essentials userMap not initialized"); + return null; + } + + User user = userMap.getUser(base.getUniqueId()); + + if (user == null) { + if (getSettings().isDebug()) { + LOGGER.log(Level.INFO, "Constructing new userfile from base player {0}", base.getName()); + } + user = new User(base, this); + } else { + user.update(base); + } + return user; + } + + private void handleCrash(Throwable exception) { + final PluginManager pm = getServer().getPluginManager(); + 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 : getOnlinePlayers()) { + player.sendMessage("Essentials failed to load, read the log file."); + } + this.setEnabled(false); + } + + @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 IConf listener) { + confList.add(listener); + } + + @Override + public Methods getPaymentMethod() { + return paymentMethod; + } + + @Override + public int broadcastMessage(final String message) { + return broadcastMessage(null, null, message, true); + } + + @Override + public int broadcastMessage(final IUser sender, final String message) { + return broadcastMessage(sender, null, message, false); + } + + @Override + public int broadcastMessage(final String permission, final String message) { + return broadcastMessage(null, permission, message, false); + } + + private int broadcastMessage(final IUser sender, final String permission, final String message, final boolean keywords) { + if (sender != null && sender.isHidden()) { + return 0; + } + + IText broadcast = new SimpleTextInput(message); + + final Collection players = getOnlinePlayers(); + + for (Player player : players) { + final User user = getUser(player); + if ((permission == null && (sender == null || !user.isIgnoredPlayer(sender))) || (permission != null && user.isAuthorized(permission))) { + if (keywords) { + broadcast = new KeywordReplacer(broadcast, new CommandSource(player), this, false); + } + for (String messageText : broadcast.getLines()) { + user.sendMessage(messageText); + } + } + } + + return players.size(); + } + + @Override + public BukkitTask runTaskAsynchronously(final Runnable run) { + return this.getScheduler().runTaskAsynchronously(this, run); + } + + @Override + public BukkitTask runTaskLaterAsynchronously(final Runnable run, final long delay) { + return this.getScheduler().runTaskLaterAsynchronously(this, run, delay); + } + + @Override + public BukkitTask runTaskTimerAsynchronously(final Runnable run, final long delay, final long period) { + return this.getScheduler().runTaskTimerAsynchronously(this, run, delay, period); + } + + @Override + public int scheduleSyncDelayedTask(final Runnable run) { + return this.getScheduler().scheduleSyncDelayedTask(this, run); + } + + @Override + public int scheduleSyncDelayedTask(final Runnable run, final long delay) { + return this.getScheduler().scheduleSyncDelayedTask(this, run, delay); + } + + @Override + public int scheduleSyncRepeatingTask(final Runnable run, final long delay, final long period) { + return this.getScheduler().scheduleSyncRepeatingTask(this, run, delay, period); + } + + @Override + public TNTExplodeListener getTNTListener() { + return tntListener; + } + + @Override + public PermissionsHandler getPermissionsHandler() { + return permissionsHandler; + } + + @Override + public AlternativeCommandsHandler getAlternativeCommandsHandler() { + return alternativeCommandsHandler; + } + + @Override + public IItemDb getItemDb() { + return itemDb; + } + + @Override + public UserMap getUserMap() { + return userMap; + } + + @Override + public I18n getI18n() { + return i18n; + } + + @Override + public EssentialsTimer getTimer() { + return timer; + } + + @Override + public List getVanishedPlayers() { + return vanishedPlayers; + } + + @Override + public Collection getOnlinePlayers() { + try { + return (Collection) getServer().getOnlinePlayers(); // Needed for sanity here, the Bukkit API is a bit broken in the sense it only allows subclasses of Player to this list + } catch (NoSuchMethodError ex) { + try { + return Arrays.asList((Player[]) oldGetOnlinePlayers.invoke(getServer())); + } catch (InvocationTargetException ex1) { + throw Throwables.propagate(ex.getCause()); + } catch (IllegalAccessException ex1) { + throw new RuntimeException("Error invoking oldGetOnlinePlayers", ex1); + } + } + } + + @Override + public Iterable getOnlineUsers() { + return Iterables.transform(getOnlinePlayers(), new Function() { + + @Override + public User apply(Player player) { + return getUser(player); + } + }); + } + + private static class EssentialsWorldListener implements Listener, Runnable { + private transient final IEssentials ess; + + public EssentialsWorldListener(final IEssentials ess) { + this.ess = ess; + } + + @EventHandler(priority = EventPriority.LOW) + public void onWorldLoad(final WorldLoadEvent event) { + ess.getJails().onReload(); + ess.getWarps().reloadConfig(); + for (IConf iConf : ((Essentials) ess).confList) { + if (iConf instanceof IEssentialsModule) { + iConf.reloadConfig(); + } + } + } + + @EventHandler(priority = EventPriority.LOW) + public void onWorldUnload(final WorldUnloadEvent event) { + ess.getJails().onReload(); + ess.getWarps().reloadConfig(); + for (IConf iConf : ((Essentials) ess).confList) { + if (iConf instanceof IEssentialsModule) { + iConf.reloadConfig(); + } + } + } + + @Override + public void run() { + ess.reload(); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/EssentialsBlockListener.java b/Essentials/src/com/earth2me/essentials/EssentialsBlockListener.java index 0a5908899..324015596 100644 --- a/Essentials/src/com/earth2me/essentials/EssentialsBlockListener.java +++ b/Essentials/src/com/earth2me/essentials/EssentialsBlockListener.java @@ -1,7 +1,6 @@ package com.earth2me.essentials; import com.earth2me.essentials.utils.LocationUtil; -import java.util.Locale; import net.ess3.api.IEssentials; import org.bukkit.GameMode; import org.bukkit.Material; @@ -14,58 +13,48 @@ import org.bukkit.event.Listener; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.inventory.ItemStack; +import java.util.Locale; -public class EssentialsBlockListener implements Listener -{ - private final transient IEssentials ess; - public EssentialsBlockListener(final IEssentials ess) - { - this.ess = ess; - } +public class EssentialsBlockListener implements Listener { + private final transient IEssentials 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 is = LocationUtil.convertBlockToItem(event.getBlockPlaced()); - if (is == null) - { - return; - } + public EssentialsBlockListener(final IEssentials ess) { + this.ess = ess; + } - if (is.getType() == Material.MOB_SPAWNER && event.getItemInHand() != null && event.getPlayer() != null - && event.getItemInHand().getType() == Material.MOB_SPAWNER) - { - final BlockState blockState = event.getBlockPlaced().getState(); - if (blockState instanceof CreatureSpawner) - { - final CreatureSpawner spawner = (CreatureSpawner)blockState; - final EntityType type = EntityType.fromId(event.getItemInHand().getData().getData()); - if (type != null && Mob.fromBukkitType(type) != null) - { - if (ess.getUser(event.getPlayer()).isAuthorized("essentials.spawnerconvert." + Mob.fromBukkitType(type).name().toLowerCase(Locale.ENGLISH))) - { - spawner.setSpawnedType(type); - } - } - } - } + @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 is = LocationUtil.convertBlockToItem(event.getBlockPlaced()); + if (is == null) { + return; + } - final User user = ess.getUser(event.getPlayer()); - if (user.hasUnlimited(is) && user.getBase().getGameMode() == GameMode.SURVIVAL) - { - class UnlimitedItemSpawnTask implements Runnable - { - @Override - public void run() - { - user.getBase().getInventory().addItem(is); - user.getBase().updateInventory(); - } - } - ess.scheduleSyncDelayedTask(new UnlimitedItemSpawnTask()); - } - } + if (is.getType() == Material.MOB_SPAWNER && event.getItemInHand() != null && event.getPlayer() != null && event.getItemInHand().getType() == Material.MOB_SPAWNER) { + final BlockState blockState = event.getBlockPlaced().getState(); + if (blockState instanceof CreatureSpawner) { + final CreatureSpawner spawner = (CreatureSpawner) blockState; + final EntityType type = EntityType.fromId(event.getItemInHand().getData().getData()); + if (type != null && Mob.fromBukkitType(type) != null) { + if (ess.getUser(event.getPlayer()).isAuthorized("essentials.spawnerconvert." + Mob.fromBukkitType(type).name().toLowerCase(Locale.ENGLISH))) { + spawner.setSpawnedType(type); + } + } + } + } + + final User user = ess.getUser(event.getPlayer()); + if (user.hasUnlimited(is) && user.getBase().getGameMode() == GameMode.SURVIVAL) { + class UnlimitedItemSpawnTask implements Runnable { + @Override + public void run() { + user.getBase().getInventory().addItem(is); + user.getBase().updateInventory(); + } + } + ess.scheduleSyncDelayedTask(new UnlimitedItemSpawnTask()); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/EssentialsConf.java b/Essentials/src/com/earth2me/essentials/EssentialsConf.java index 0352007e8..02408163f 100644 --- a/Essentials/src/com/earth2me/essentials/EssentialsConf.java +++ b/Essentials/src/com/earth2me/essentials/EssentialsConf.java @@ -1,7 +1,16 @@ package com.earth2me.essentials; -import static com.earth2me.essentials.I18n.tl; import com.google.common.io.Files; +import net.ess3.api.InvalidWorldException; +import org.bukkit.*; +import org.bukkit.OfflinePlayer; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.Vector; + import java.io.*; import java.math.BigDecimal; import java.math.MathContext; @@ -19,841 +28,646 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.logging.Logger; -import net.ess3.api.InvalidWorldException; -import org.bukkit.*; -import org.bukkit.OfflinePlayer; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.InvalidConfigurationException; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.ItemStack; -import org.bukkit.util.Vector; + +import static com.earth2me.essentials.I18n.tl; -public class EssentialsConf extends YamlConfiguration -{ - protected static final Logger LOGGER = Logger.getLogger("Essentials"); - protected final File configFile; - protected String templateName = null; - protected static final Charset UTF8 = Charset.forName("UTF-8"); - private Class resourceClass = EssentialsConf.class; - private static final ExecutorService EXECUTOR_SERVICE = Executors.newSingleThreadExecutor(); - private final AtomicInteger pendingDiskWrites = new AtomicInteger(0); - private final AtomicBoolean transaction = new AtomicBoolean(false); +public class EssentialsConf extends YamlConfiguration { + protected static final Logger LOGGER = Logger.getLogger("Essentials"); + protected final File configFile; + protected String templateName = null; + protected static final Charset UTF8 = Charset.forName("UTF-8"); + private Class resourceClass = EssentialsConf.class; + private static final ExecutorService EXECUTOR_SERVICE = Executors.newSingleThreadExecutor(); + private final AtomicInteger pendingDiskWrites = new AtomicInteger(0); + private final AtomicBoolean transaction = new AtomicBoolean(false); - public EssentialsConf(final File configFile) - { - super(); - this.configFile = configFile.getAbsoluteFile(); - } - private final byte[] bytebuffer = new byte[1024]; + public EssentialsConf(final File configFile) { + super(); + this.configFile = configFile.getAbsoluteFile(); + } - public synchronized void load() - { - if (pendingDiskWrites.get() != 0) - { - LOGGER.log(Level.INFO, "File {0} not read, because it''s not yet written to disk.", configFile); - return; - } - if (!configFile.getParentFile().exists()) - { - if (!configFile.getParentFile().mkdirs()) - { - LOGGER.log(Level.SEVERE, tl("failedToCreateConfig", configFile.toString())); - } - } - // This will delete files where the first character is 0. In most cases they are broken. - if (configFile.exists() && configFile.length() != 0) - { - try - { - final InputStream input = new FileInputStream(configFile); - try - { - if (input.read() == 0) - { - input.close(); - configFile.delete(); - } - } - catch (IOException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - finally - { - try - { - input.close(); - } - catch (IOException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - } - } - catch (FileNotFoundException ex) - { - LOGGER.log(Level.SEVERE, null, ex); - } - } + private final byte[] bytebuffer = new byte[1024]; - if (!configFile.exists()) - { - if (legacyFileExists()) - { - convertLegacyFile(); - } - else if (altFileExists()) - { - convertAltFile(); - } - else if (templateName != null) - { - LOGGER.log(Level.INFO, tl("creatingConfigFromTemplate", configFile.toString())); - createFromTemplate(); - } - else - { - return; - } - } + public synchronized void load() { + if (pendingDiskWrites.get() != 0) { + LOGGER.log(Level.INFO, "File {0} not read, because it''s not yet written to disk.", configFile); + return; + } + if (!configFile.getParentFile().exists()) { + if (!configFile.getParentFile().mkdirs()) { + LOGGER.log(Level.SEVERE, tl("failedToCreateConfig", configFile.toString())); + } + } + // This will delete files where the first character is 0. In most cases they are broken. + if (configFile.exists() && configFile.length() != 0) { + try { + final InputStream input = new FileInputStream(configFile); + try { + if (input.read() == 0) { + input.close(); + configFile.delete(); + } + } catch (IOException ex) { + LOGGER.log(Level.SEVERE, null, ex); + } finally { + try { + input.close(); + } catch (IOException ex) { + LOGGER.log(Level.SEVERE, null, ex); + } + } + } catch (FileNotFoundException ex) { + LOGGER.log(Level.SEVERE, null, ex); + } + } + + if (!configFile.exists()) { + if (legacyFileExists()) { + convertLegacyFile(); + } else if (altFileExists()) { + convertAltFile(); + } else if (templateName != null) { + LOGGER.log(Level.INFO, tl("creatingConfigFromTemplate", configFile.toString())); + createFromTemplate(); + } else { + return; + } + } - try - { - final FileInputStream inputStream = new FileInputStream(configFile); - try - { - long startSize = configFile.length(); - if (startSize > Integer.MAX_VALUE) - { - throw new InvalidConfigurationException("File too big"); - } - ByteBuffer buffer = ByteBuffer.allocate((int)startSize); - int length; - while ((length = inputStream.read(bytebuffer)) != -1) - { - if (length > buffer.remaining()) - { - ByteBuffer resize = ByteBuffer.allocate(buffer.capacity() + length - buffer.remaining()); - int resizePosition = buffer.position(); - buffer.rewind(); - resize.put(buffer); - resize.position(resizePosition); - buffer = resize; - } - buffer.put(bytebuffer, 0, length); - } - buffer.rewind(); - final CharBuffer data = CharBuffer.allocate(buffer.capacity()); - CharsetDecoder decoder = UTF8.newDecoder(); - CoderResult result = decoder.decode(buffer, data, true); - if (result.isError()) - { - buffer.rewind(); - data.clear(); - LOGGER.log(Level.INFO, "File " + configFile.getAbsolutePath().toString() + " is not utf-8 encoded, trying " + Charset.defaultCharset().displayName()); - decoder = Charset.defaultCharset().newDecoder(); - result = decoder.decode(buffer, data, true); - if (result.isError()) - { - throw new InvalidConfigurationException("Invalid Characters in file " + configFile.getAbsolutePath().toString()); - } - else - { - decoder.flush(data); - } - } - else - { - decoder.flush(data); - } - final int end = data.position(); - data.rewind(); - super.loadFromString(data.subSequence(0, end).toString()); - } - finally - { - inputStream.close(); - } - } - catch (IOException ex) - { - LOGGER.log(Level.SEVERE, ex.getMessage(), ex); - } - catch (InvalidConfigurationException ex) - { - File broken = new File(configFile.getAbsolutePath() + ".broken." + System.currentTimeMillis()); - configFile.renameTo(broken); - LOGGER.log(Level.SEVERE, "The file " + configFile.toString() + " is broken, it has been renamed to " + broken.toString(), ex.getCause()); - } - } + try { + final FileInputStream inputStream = new FileInputStream(configFile); + try { + long startSize = configFile.length(); + if (startSize > Integer.MAX_VALUE) { + throw new InvalidConfigurationException("File too big"); + } + ByteBuffer buffer = ByteBuffer.allocate((int) startSize); + int length; + while ((length = inputStream.read(bytebuffer)) != -1) { + if (length > buffer.remaining()) { + ByteBuffer resize = ByteBuffer.allocate(buffer.capacity() + length - buffer.remaining()); + int resizePosition = buffer.position(); + buffer.rewind(); + resize.put(buffer); + resize.position(resizePosition); + buffer = resize; + } + buffer.put(bytebuffer, 0, length); + } + buffer.rewind(); + final CharBuffer data = CharBuffer.allocate(buffer.capacity()); + CharsetDecoder decoder = UTF8.newDecoder(); + CoderResult result = decoder.decode(buffer, data, true); + if (result.isError()) { + buffer.rewind(); + data.clear(); + LOGGER.log(Level.INFO, "File " + configFile.getAbsolutePath().toString() + " is not utf-8 encoded, trying " + Charset.defaultCharset().displayName()); + decoder = Charset.defaultCharset().newDecoder(); + result = decoder.decode(buffer, data, true); + if (result.isError()) { + throw new InvalidConfigurationException("Invalid Characters in file " + configFile.getAbsolutePath().toString()); + } else { + decoder.flush(data); + } + } else { + decoder.flush(data); + } + final int end = data.position(); + data.rewind(); + super.loadFromString(data.subSequence(0, end).toString()); + } finally { + inputStream.close(); + } + } catch (IOException ex) { + LOGGER.log(Level.SEVERE, ex.getMessage(), ex); + } catch (InvalidConfigurationException ex) { + File broken = new File(configFile.getAbsolutePath() + ".broken." + System.currentTimeMillis()); + configFile.renameTo(broken); + LOGGER.log(Level.SEVERE, "The file " + configFile.toString() + " is broken, it has been renamed to " + broken.toString(), ex.getCause()); + } + } - public boolean legacyFileExists() - { - return false; - } + public boolean legacyFileExists() { + return false; + } - public void convertLegacyFile() - { - LOGGER.log(Level.SEVERE, "Unable to import legacy config file."); - } + public void convertLegacyFile() { + LOGGER.log(Level.SEVERE, "Unable to import legacy config file."); + } - public boolean altFileExists() - { - return false; - } + public boolean altFileExists() { + return false; + } - public void convertAltFile() - { - LOGGER.log(Level.SEVERE, "Unable to import alt config file."); - } + public void convertAltFile() { + LOGGER.log(Level.SEVERE, "Unable to import alt config file."); + } - private void createFromTemplate() - { - InputStream istr = null; - OutputStream ostr = null; - try - { - istr = resourceClass.getResourceAsStream(templateName); - if (istr == null) - { - LOGGER.log(Level.SEVERE, tl("couldNotFindTemplate", templateName)); - return; - } - ostr = new FileOutputStream(configFile); - byte[] buffer = new byte[1024]; - int length = 0; - length = istr.read(buffer); - while (length > 0) - { - ostr.write(buffer, 0, length); - length = istr.read(buffer); - } - } - catch (IOException ex) - { - LOGGER.log(Level.SEVERE, tl("failedToWriteConfig", configFile.toString()), ex); - } - finally - { - try - { - if (istr != null) - { - istr.close(); - } - } - catch (IOException ex) - { - Logger.getLogger(EssentialsConf.class.getName()).log(Level.SEVERE, null, ex); - } - try - { - if (ostr != null) - { - ostr.close(); - } - } - catch (IOException ex) - { - LOGGER.log(Level.SEVERE, tl("failedToCloseConfig", configFile.toString()), ex); - } - } - } + private void createFromTemplate() { + InputStream istr = null; + OutputStream ostr = null; + try { + istr = resourceClass.getResourceAsStream(templateName); + if (istr == null) { + LOGGER.log(Level.SEVERE, tl("couldNotFindTemplate", templateName)); + return; + } + ostr = new FileOutputStream(configFile); + byte[] buffer = new byte[1024]; + int length = 0; + length = istr.read(buffer); + while (length > 0) { + ostr.write(buffer, 0, length); + length = istr.read(buffer); + } + } catch (IOException ex) { + LOGGER.log(Level.SEVERE, tl("failedToWriteConfig", configFile.toString()), ex); + } finally { + try { + if (istr != null) { + istr.close(); + } + } catch (IOException ex) { + Logger.getLogger(EssentialsConf.class.getName()).log(Level.SEVERE, null, ex); + } + try { + if (ostr != null) { + ostr.close(); + } + } catch (IOException ex) { + LOGGER.log(Level.SEVERE, tl("failedToCloseConfig", configFile.toString()), ex); + } + } + } - public void setTemplateName(final String templateName) - { - this.templateName = templateName; - } + public void setTemplateName(final String templateName) { + this.templateName = templateName; + } - public File getFile() - { - return configFile; - } + public File getFile() { + return configFile; + } - public void setTemplateName(final String templateName, final Class resClass) - { - this.templateName = templateName; - this.resourceClass = resClass; - } + public void setTemplateName(final String templateName, final Class resClass) { + this.templateName = templateName; + this.resourceClass = resClass; + } - public void startTransaction() - { - transaction.set(true); - } + public void startTransaction() { + transaction.set(true); + } - public void stopTransaction() - { - transaction.set(false); - save(); - } + public void stopTransaction() { + transaction.set(false); + save(); + } - public void save() - { - try - { - save(configFile); - } - catch (IOException ex) - { - LOGGER.log(Level.SEVERE, ex.getMessage(), ex); - } - } + public void save() { + try { + save(configFile); + } catch (IOException ex) { + LOGGER.log(Level.SEVERE, ex.getMessage(), ex); + } + } - public void saveWithError() throws IOException - { - save(configFile); - } + public void saveWithError() throws IOException { + save(configFile); + } - @Override - public synchronized void save(final File file) throws IOException - { - if (!transaction.get()) - { - delayedSave(file); - } - } + @Override + public synchronized void save(final File file) throws IOException { + if (!transaction.get()) { + delayedSave(file); + } + } - //This may be aborted if there are stagnant requests sitting in queue. - //This needs fixed to discard outstanding save requests. - public synchronized void forceSave() - { - try - { - Future future = delayedSave(configFile); - if (future != null) - { - future.get(); - } - } - catch (InterruptedException ex) - { - LOGGER.log(Level.SEVERE, ex.getMessage(), ex); - } - catch (ExecutionException ex) - { - LOGGER.log(Level.SEVERE, ex.getMessage(), ex); - } - } + //This may be aborted if there are stagnant requests sitting in queue. + //This needs fixed to discard outstanding save requests. + public synchronized void forceSave() { + try { + Future future = delayedSave(configFile); + if (future != null) { + future.get(); + } + } catch (InterruptedException ex) { + LOGGER.log(Level.SEVERE, ex.getMessage(), ex); + } catch (ExecutionException ex) { + LOGGER.log(Level.SEVERE, ex.getMessage(), ex); + } + } - public synchronized void cleanup() - { - forceSave(); - } + public synchronized void cleanup() { + forceSave(); + } - private Future delayedSave(final File file) - { - if (file == null) - { - throw new IllegalArgumentException("File cannot be null"); - } + private Future delayedSave(final File file) { + if (file == null) { + throw new IllegalArgumentException("File cannot be null"); + } - final String data = saveToString(); + final String data = saveToString(); - if (data.length() == 0) - { - return null; - } + if (data.length() == 0) { + return null; + } - Future future = EXECUTOR_SERVICE.submit(new WriteRunner(configFile, data, pendingDiskWrites)); + Future future = EXECUTOR_SERVICE.submit(new WriteRunner(configFile, data, pendingDiskWrites)); - return future; - } + return future; + } - private static class WriteRunner implements Runnable - { - private final File configFile; - private final String data; - private final AtomicInteger pendingDiskWrites; + private static class WriteRunner implements Runnable { + private final File configFile; + private final String data; + private final AtomicInteger pendingDiskWrites; - private WriteRunner(final File configFile, final String data, final AtomicInteger pendingDiskWrites) - { - this.configFile = configFile; - this.data = data; - this.pendingDiskWrites = pendingDiskWrites; - } + private WriteRunner(final File configFile, final String data, final AtomicInteger pendingDiskWrites) { + this.configFile = configFile; + this.data = data; + this.pendingDiskWrites = pendingDiskWrites; + } - @Override - public void run() - { - //long startTime = System.nanoTime(); - synchronized (configFile) - { - if (pendingDiskWrites.get() > 1) - { - // Writes can be skipped, because they are stored in a queue (in the executor). - // Only the last is actually written. - pendingDiskWrites.decrementAndGet(); - //LOGGER.log(Level.INFO, configFile + " skipped writing in " + (System.nanoTime() - startTime) + " nsec."); - return; - } - try - { - Files.createParentDirs(configFile); + @Override + public void run() { + //long startTime = System.nanoTime(); + synchronized (configFile) { + if (pendingDiskWrites.get() > 1) { + // Writes can be skipped, because they are stored in a queue (in the executor). + // Only the last is actually written. + pendingDiskWrites.decrementAndGet(); + //LOGGER.log(Level.INFO, configFile + " skipped writing in " + (System.nanoTime() - startTime) + " nsec."); + return; + } + try { + Files.createParentDirs(configFile); - if (!configFile.exists()) - { - try - { - LOGGER.log(Level.INFO, tl("creatingEmptyConfig", configFile.toString())); - if (!configFile.createNewFile()) - { - LOGGER.log(Level.SEVERE, tl("failedToCreateConfig", configFile.toString())); - return; - } - } - catch (IOException ex) - { - LOGGER.log(Level.SEVERE, tl("failedToCreateConfig", configFile.toString()), ex); - return; - } - } + if (!configFile.exists()) { + try { + LOGGER.log(Level.INFO, tl("creatingEmptyConfig", configFile.toString())); + if (!configFile.createNewFile()) { + LOGGER.log(Level.SEVERE, tl("failedToCreateConfig", configFile.toString())); + return; + } + } catch (IOException ex) { + LOGGER.log(Level.SEVERE, tl("failedToCreateConfig", configFile.toString()), ex); + return; + } + } - final FileOutputStream fos = new FileOutputStream(configFile); - try - { - final OutputStreamWriter writer = new OutputStreamWriter(fos, UTF8); + final FileOutputStream fos = new FileOutputStream(configFile); + try { + final OutputStreamWriter writer = new OutputStreamWriter(fos, UTF8); - try - { - writer.write(data); - } - finally - { - writer.close(); - } - } - finally - { - fos.close(); - } - } - catch (IOException e) - { - LOGGER.log(Level.SEVERE, e.getMessage(), e); - } - finally - { - //LOGGER.log(Level.INFO, configFile + " written to disk in " + (System.nanoTime() - startTime) + " nsec."); - pendingDiskWrites.decrementAndGet(); - } - } - } - } + try { + writer.write(data); + } finally { + writer.close(); + } + } finally { + fos.close(); + } + } catch (IOException e) { + LOGGER.log(Level.SEVERE, e.getMessage(), e); + } finally { + //LOGGER.log(Level.INFO, configFile + " written to disk in " + (System.nanoTime() - startTime) + " nsec."); + pendingDiskWrites.decrementAndGet(); + } + } + } + } - public boolean hasProperty(final String path) - { - return isSet(path); - } + public boolean hasProperty(final String path) { + return isSet(path); + } - public Location getLocation(final String path, final Server server) throws InvalidWorldException - { - final String worldString = (path == null ? "" : path + ".") + "world"; - final String worldName = getString(worldString); - if (worldName == null || worldName.isEmpty()) - { - return null; - } - final World world = server.getWorld(worldName); - if (world == null) - { - throw new InvalidWorldException(worldName); - } - return new Location(world, - getDouble((path == null ? "" : path + ".") + "x", 0), - getDouble((path == null ? "" : path + ".") + "y", 0), - getDouble((path == null ? "" : path + ".") + "z", 0), - (float)getDouble((path == null ? "" : path + ".") + "yaw", 0), - (float)getDouble((path == null ? "" : path + ".") + "pitch", 0)); - } + public Location getLocation(final String path, final Server server) throws InvalidWorldException { + final String worldString = (path == null ? "" : path + ".") + "world"; + final String worldName = getString(worldString); + if (worldName == null || worldName.isEmpty()) { + return null; + } + final World world = server.getWorld(worldName); + if (world == null) { + throw new InvalidWorldException(worldName); + } + return new Location(world, getDouble((path == null ? "" : path + ".") + "x", 0), getDouble((path == null ? "" : path + ".") + "y", 0), getDouble((path == null ? "" : path + ".") + "z", 0), (float) getDouble((path == null ? "" : path + ".") + "yaw", 0), (float) getDouble((path == null ? "" : path + ".") + "pitch", 0)); + } - public void setProperty(final String path, final Location loc) - { - set((path == null ? "" : path + ".") + "world", loc.getWorld().getName()); - set((path == null ? "" : path + ".") + "x", loc.getX()); - set((path == null ? "" : path + ".") + "y", loc.getY()); - set((path == null ? "" : path + ".") + "z", loc.getZ()); - set((path == null ? "" : path + ".") + "yaw", loc.getYaw()); - set((path == null ? "" : path + ".") + "pitch", loc.getPitch()); - } + public void setProperty(final String path, final Location loc) { + set((path == null ? "" : path + ".") + "world", loc.getWorld().getName()); + set((path == null ? "" : path + ".") + "x", loc.getX()); + set((path == null ? "" : path + ".") + "y", loc.getY()); + set((path == null ? "" : path + ".") + "z", loc.getZ()); + set((path == null ? "" : path + ".") + "yaw", loc.getYaw()); + set((path == null ? "" : path + ".") + "pitch", loc.getPitch()); + } - @Override - public ItemStack getItemStack(final String path) - { - final ItemStack stack = new ItemStack( - Material.valueOf(getString(path + ".type", "AIR")), - getInt(path + ".amount", 1), - (short)getInt(path + ".damage", 0)); - final ConfigurationSection enchants = getConfigurationSection(path + ".enchant"); - if (enchants != null) - { - for (String enchant : enchants.getKeys(false)) - { - final Enchantment enchantment = Enchantment.getByName(enchant.toUpperCase(Locale.ENGLISH)); - if (enchantment == null) - { - continue; - } - final int level = getInt(path + ".enchant." + enchant, enchantment.getStartLevel()); - stack.addUnsafeEnchantment(enchantment, level); - } - } - return stack; - /* + @Override + public ItemStack getItemStack(final String path) { + final ItemStack stack = new ItemStack(Material.valueOf(getString(path + ".type", "AIR")), getInt(path + ".amount", 1), (short) getInt(path + ".damage", 0)); + final ConfigurationSection enchants = getConfigurationSection(path + ".enchant"); + if (enchants != null) { + for (String enchant : enchants.getKeys(false)) { + final Enchantment enchantment = Enchantment.getByName(enchant.toUpperCase(Locale.ENGLISH)); + if (enchantment == null) { + continue; + } + final int level = getInt(path + ".enchant." + enchant, enchantment.getStartLevel()); + stack.addUnsafeEnchantment(enchantment, level); + } + } + return stack; + /* * , * (byte)getInt(path + ".data", 0) */ - } + } - public void setProperty(final String path, final ItemStack stack) - { - final Map map = new HashMap(); - map.put("type", stack.getType().toString()); - map.put("amount", stack.getAmount()); - map.put("damage", stack.getDurability()); - Map enchantments = stack.getEnchantments(); - if (!enchantments.isEmpty()) - { - Map enchant = new HashMap(); - for (Map.Entry entry : enchantments.entrySet()) - { - enchant.put(entry.getKey().getName().toLowerCase(Locale.ENGLISH), entry.getValue()); - } - map.put("enchant", enchant); - } - // getData().getData() is broken - //map.put("data", stack.getDurability()); - set(path, map); - } + public void setProperty(final String path, final ItemStack stack) { + final Map map = new HashMap(); + map.put("type", stack.getType().toString()); + map.put("amount", stack.getAmount()); + map.put("damage", stack.getDurability()); + Map enchantments = stack.getEnchantments(); + if (!enchantments.isEmpty()) { + Map enchant = new HashMap(); + for (Map.Entry entry : enchantments.entrySet()) { + enchant.put(entry.getKey().getName().toLowerCase(Locale.ENGLISH), entry.getValue()); + } + map.put("enchant", enchant); + } + // getData().getData() is broken + //map.put("data", stack.getDurability()); + set(path, map); + } - public void setProperty(String path, List object) - { - set(path, new ArrayList(object)); - } + public void setProperty(String path, List object) { + set(path, new ArrayList(object)); + } - public void setProperty(String path, Map object) - { - set(path, new LinkedHashMap(object)); - } + public void setProperty(String path, Map object) { + set(path, new LinkedHashMap(object)); + } - public Object getProperty(String path) - { - return get(path); - } + public Object getProperty(String path) { + return get(path); + } - public void setProperty(final String path, final BigDecimal bigDecimal) - { - set(path, bigDecimal.toString()); - } + public void setProperty(final String path, final BigDecimal bigDecimal) { + set(path, bigDecimal.toString()); + } - public void setProperty(String path, Object object) - { - set(path, object); - } + public void setProperty(String path, Object object) { + set(path, object); + } - public void removeProperty(String path) - { - set(path, null); - } + public void removeProperty(String path) { + set(path, null); + } - @Override - public synchronized Object get(String path) - { - return super.get(path); - } + @Override + public synchronized Object get(String path) { + return super.get(path); + } - @Override - public synchronized Object get(String path, Object def) - { - return super.get(path, def); - } + @Override + public synchronized Object get(String path, Object def) { + return super.get(path, def); + } - public synchronized BigDecimal getBigDecimal(final String path, final BigDecimal def) - { - final String input = super.getString(path); - return toBigDecimal(input, def); - } + public synchronized BigDecimal getBigDecimal(final String path, final BigDecimal def) { + final String input = super.getString(path); + return toBigDecimal(input, def); + } - public static BigDecimal toBigDecimal(final String input, final BigDecimal def) - { - if (input == null || input.isEmpty()) - { - return def; - } - else - { - try - { - return new BigDecimal(input, MathContext.DECIMAL128); - } - catch (NumberFormatException e) - { - return def; - } - catch (ArithmeticException e) - { - return def; - } - } - } + public static BigDecimal toBigDecimal(final String input, final BigDecimal def) { + if (input == null || input.isEmpty()) { + return def; + } else { + try { + return new BigDecimal(input, MathContext.DECIMAL128); + } catch (NumberFormatException e) { + return def; + } catch (ArithmeticException e) { + return def; + } + } + } - @Override - public synchronized boolean getBoolean(String path) - { - return super.getBoolean(path); - } + @Override + public synchronized boolean getBoolean(String path) { + return super.getBoolean(path); + } - @Override - public synchronized boolean getBoolean(String path, boolean def) - { - return super.getBoolean(path, def); - } + @Override + public synchronized boolean getBoolean(String path, boolean def) { + return super.getBoolean(path, def); + } - @Override - public synchronized List getBooleanList(String path) - { - return super.getBooleanList(path); - } + @Override + public synchronized List getBooleanList(String path) { + return super.getBooleanList(path); + } - @Override - public synchronized List getByteList(String path) - { - return super.getByteList(path); - } + @Override + public synchronized List getByteList(String path) { + return super.getByteList(path); + } - @Override - public synchronized List getCharacterList(String path) - { - return super.getCharacterList(path); - } + @Override + public synchronized List getCharacterList(String path) { + return super.getCharacterList(path); + } - @Override - public synchronized ConfigurationSection getConfigurationSection(String path) - { - return super.getConfigurationSection(path); - } + @Override + public synchronized ConfigurationSection getConfigurationSection(String path) { + return super.getConfigurationSection(path); + } - @Override - public synchronized double getDouble(String path) - { - return super.getDouble(path); - } + @Override + public synchronized double getDouble(String path) { + return super.getDouble(path); + } - @Override - public synchronized double getDouble(final String path, final double def) - { - return super.getDouble(path, def); - } + @Override + public synchronized double getDouble(final String path, final double def) { + return super.getDouble(path, def); + } - @Override - public synchronized List getDoubleList(String path) - { - return super.getDoubleList(path); - } + @Override + public synchronized List getDoubleList(String path) { + return super.getDoubleList(path); + } - @Override - public synchronized List getFloatList(String path) - { - return super.getFloatList(path); - } + @Override + public synchronized List getFloatList(String path) { + return super.getFloatList(path); + } - @Override - public synchronized int getInt(String path) - { - return super.getInt(path); - } + @Override + public synchronized int getInt(String path) { + return super.getInt(path); + } - @Override - public synchronized int getInt(String path, int def) - { - return super.getInt(path, def); - } + @Override + public synchronized int getInt(String path, int def) { + return super.getInt(path, def); + } - @Override - public synchronized List getIntegerList(String path) - { - return super.getIntegerList(path); - } + @Override + public synchronized List getIntegerList(String path) { + return super.getIntegerList(path); + } - @Override - public synchronized ItemStack getItemStack(String path, ItemStack def) - { - return super.getItemStack(path, def); - } + @Override + public synchronized ItemStack getItemStack(String path, ItemStack def) { + return super.getItemStack(path, def); + } - @Override - public synchronized Set getKeys(boolean deep) - { - return super.getKeys(deep); - } + @Override + public synchronized Set getKeys(boolean deep) { + return super.getKeys(deep); + } - @Override - public synchronized List getList(String path) - { - return super.getList(path); - } + @Override + public synchronized List getList(String path) { + return super.getList(path); + } - @Override - public synchronized List getList(String path, List def) - { - return super.getList(path, def); - } + @Override + public synchronized List getList(String path, List def) { + return super.getList(path, def); + } - @Override - public synchronized long getLong(String path) - { - return super.getLong(path); - } + @Override + public synchronized long getLong(String path) { + return super.getLong(path); + } - @Override - public synchronized long getLong(final String path, final long def) - { - return super.getLong(path, def); - } + @Override + public synchronized long getLong(final String path, final long def) { + return super.getLong(path, def); + } - @Override - public synchronized List getLongList(String path) - { - return super.getLongList(path); - } + @Override + public synchronized List getLongList(String path) { + return super.getLongList(path); + } - public synchronized Map getMap() - { - return map; - } + public synchronized Map getMap() { + return map; + } - @Override - public synchronized List> getMapList(String path) - { - return super.getMapList(path); - } + @Override + public synchronized List> getMapList(String path) { + return super.getMapList(path); + } - @Override - public synchronized OfflinePlayer getOfflinePlayer(String path) - { - return super.getOfflinePlayer(path); - } + @Override + public synchronized OfflinePlayer getOfflinePlayer(String path) { + return super.getOfflinePlayer(path); + } - @Override - public synchronized OfflinePlayer getOfflinePlayer(String path, OfflinePlayer def) - { - return super.getOfflinePlayer(path, def); - } + @Override + public synchronized OfflinePlayer getOfflinePlayer(String path, OfflinePlayer def) { + return super.getOfflinePlayer(path, def); + } - @Override - public synchronized List getShortList(String path) - { - return super.getShortList(path); - } + @Override + public synchronized List getShortList(String path) { + return super.getShortList(path); + } - @Override - public synchronized String getString(String path) - { - return super.getString(path); - } + @Override + public synchronized String getString(String path) { + return super.getString(path); + } - @Override - public synchronized String getString(String path, String def) - { - return super.getString(path, def); - } + @Override + public synchronized String getString(String path, String def) { + return super.getString(path, def); + } - @Override - public synchronized List getStringList(String path) - { - return super.getStringList(path); - } + @Override + public synchronized List getStringList(String path) { + return super.getStringList(path); + } - @Override - public synchronized Map getValues(boolean deep) - { - return super.getValues(deep); - } + @Override + public synchronized Map getValues(boolean deep) { + return super.getValues(deep); + } - @Override - public synchronized Vector getVector(String path) - { - return super.getVector(path); - } + @Override + public synchronized Vector getVector(String path) { + return super.getVector(path); + } - @Override - public synchronized Vector getVector(String path, Vector def) - { - return super.getVector(path, def); - } + @Override + public synchronized Vector getVector(String path, Vector def) { + return super.getVector(path, def); + } - @Override - public synchronized boolean isBoolean(String path) - { - return super.isBoolean(path); - } + @Override + public synchronized boolean isBoolean(String path) { + return super.isBoolean(path); + } - @Override - public synchronized boolean isConfigurationSection(String path) - { - return super.isConfigurationSection(path); - } + @Override + public synchronized boolean isConfigurationSection(String path) { + return super.isConfigurationSection(path); + } - @Override - public synchronized boolean isDouble(String path) - { - return super.isDouble(path); - } + @Override + public synchronized boolean isDouble(String path) { + return super.isDouble(path); + } - @Override - public synchronized boolean isInt(String path) - { - return super.isInt(path); - } + @Override + public synchronized boolean isInt(String path) { + return super.isInt(path); + } - @Override - public synchronized boolean isItemStack(String path) - { - return super.isItemStack(path); - } + @Override + public synchronized boolean isItemStack(String path) { + return super.isItemStack(path); + } - @Override - public synchronized boolean isList(String path) - { - return super.isList(path); - } + @Override + public synchronized boolean isList(String path) { + return super.isList(path); + } - @Override - public synchronized boolean isLong(String path) - { - return super.isLong(path); - } + @Override + public synchronized boolean isLong(String path) { + return super.isLong(path); + } - @Override - public synchronized boolean isOfflinePlayer(String path) - { - return super.isOfflinePlayer(path); - } + @Override + public synchronized boolean isOfflinePlayer(String path) { + return super.isOfflinePlayer(path); + } - @Override - public synchronized boolean isSet(String path) - { - return super.isSet(path); - } + @Override + public synchronized boolean isSet(String path) { + return super.isSet(path); + } - @Override - public synchronized boolean isString(String path) - { - return super.isString(path); - } + @Override + public synchronized boolean isString(String path) { + return super.isString(path); + } - @Override - public synchronized boolean isVector(String path) - { - return super.isVector(path); - } + @Override + public synchronized boolean isVector(String path) { + return super.isVector(path); + } - @Override - public synchronized void set(String path, Object value) - { - super.set(path, value); - } + @Override + public synchronized void set(String path, Object value) { + super.set(path, value); + } } diff --git a/Essentials/src/com/earth2me/essentials/EssentialsEntityListener.java b/Essentials/src/com/earth2me/essentials/EssentialsEntityListener.java index 5e3bbb1d0..93d165946 100644 --- a/Essentials/src/com/earth2me/essentials/EssentialsEntityListener.java +++ b/Essentials/src/com/earth2me/essentials/EssentialsEntityListener.java @@ -1,10 +1,5 @@ package com.earth2me.essentials; -import static com.earth2me.essentials.I18n.tl; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.Pattern; import net.ess3.api.IEssentials; import org.bukkit.Material; import org.bukkit.entity.*; @@ -15,212 +10,173 @@ import org.bukkit.event.entity.*; import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason; import org.bukkit.inventory.ItemStack; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.regex.Pattern; -public class EssentialsEntityListener implements Listener -{ - private static final Logger LOGGER = Logger.getLogger("Essentials"); - private static final transient Pattern powertoolPlayer = Pattern.compile("\\{player\\}"); - private final IEssentials ess; +import static com.earth2me.essentials.I18n.tl; - public EssentialsEntityListener(IEssentials ess) - { - this.ess = ess; - } - // This method does something undocumented reguarding certain bucket types #EasterEgg - @EventHandler(priority = EventPriority.LOW) - public void onEntityDamage(final EntityDamageByEntityEvent event) - { - final Entity eAttack = event.getDamager(); - final Entity eDefend = event.getEntity(); - if (eAttack instanceof Player) - { - final User attacker = ess.getUser((Player)eAttack); - if (eDefend instanceof Player) - { - onPlayerVsPlayerDamage(event, (Player)eDefend, attacker); - } - else if (eDefend instanceof Ageable) - { - final ItemStack hand = attacker.getBase().getItemInHand(); - if (hand != null && hand.getType() == Material.MILK_BUCKET) - { - ((Ageable)eDefend).setBaby(); - hand.setType(Material.BUCKET); - attacker.getBase().setItemInHand(hand); - attacker.getBase().updateInventory(); - event.setCancelled(true); - } - } - attacker.updateActivity(true); - } - else if (eAttack instanceof Projectile && eDefend instanceof Player) - { - final Projectile projectile = (Projectile)event.getDamager(); - //This should return a ProjectileSource on 1.7.3 beta + - final Object shooter = projectile.getShooter(); - if (shooter instanceof Player) - { - final User attacker = ess.getUser((Player)shooter); - onPlayerVsPlayerDamage(event, (Player)eDefend, attacker); - attacker.updateActivity(true); - } - } - } +public class EssentialsEntityListener implements Listener { + private static final Logger LOGGER = Logger.getLogger("Essentials"); + private static final transient Pattern powertoolPlayer = Pattern.compile("\\{player\\}"); + private final IEssentials ess; - private void onPlayerVsPlayerDamage(final EntityDamageByEntityEvent event, final Player defender, final User attacker) - { - if (ess.getSettings().getLoginAttackDelay() > 0 - && (System.currentTimeMillis() < (attacker.getLastLogin() + ess.getSettings().getLoginAttackDelay())) - && !attacker.isAuthorized("essentials.pvpdelay.exempt")) - { - event.setCancelled(true); - } + public EssentialsEntityListener(IEssentials ess) { + this.ess = ess; + } - if (!defender.equals(attacker.getBase()) && (attacker.hasInvulnerabilityAfterTeleport() || ess.getUser(defender).hasInvulnerabilityAfterTeleport())) - { - event.setCancelled(true); - } + // This method does something undocumented reguarding certain bucket types #EasterEgg + @EventHandler(priority = EventPriority.LOW) + public void onEntityDamage(final EntityDamageByEntityEvent event) { + final Entity eAttack = event.getDamager(); + final Entity eDefend = event.getEntity(); + if (eAttack instanceof Player) { + final User attacker = ess.getUser((Player) eAttack); + if (eDefend instanceof Player) { + onPlayerVsPlayerDamage(event, (Player) eDefend, attacker); + } else if (eDefend instanceof Ageable) { + final ItemStack hand = attacker.getBase().getItemInHand(); + if (hand != null && hand.getType() == Material.MILK_BUCKET) { + ((Ageable) eDefend).setBaby(); + hand.setType(Material.BUCKET); + attacker.getBase().setItemInHand(hand); + attacker.getBase().updateInventory(); + event.setCancelled(true); + } + } + attacker.updateActivity(true); + } else if (eAttack instanceof Projectile && eDefend instanceof Player) { + final Projectile projectile = (Projectile) event.getDamager(); + //This should return a ProjectileSource on 1.7.3 beta + + final Object shooter = projectile.getShooter(); + if (shooter instanceof Player) { + final User attacker = ess.getUser((Player) shooter); + onPlayerVsPlayerDamage(event, (Player) eDefend, attacker); + attacker.updateActivity(true); + } + } + } - if (attacker.isGodModeEnabled() && !attacker.isAuthorized("essentials.god.pvp")) - { - event.setCancelled(true); - } + private void onPlayerVsPlayerDamage(final EntityDamageByEntityEvent event, final Player defender, final User attacker) { + if (ess.getSettings().getLoginAttackDelay() > 0 && (System.currentTimeMillis() < (attacker.getLastLogin() + ess.getSettings().getLoginAttackDelay())) && !attacker.isAuthorized("essentials.pvpdelay.exempt")) { + event.setCancelled(true); + } - if (attacker.isHidden() && !attacker.isAuthorized("essentials.vanish.pvp")) - { - event.setCancelled(true); - } + if (!defender.equals(attacker.getBase()) && (attacker.hasInvulnerabilityAfterTeleport() || ess.getUser(defender).hasInvulnerabilityAfterTeleport())) { + event.setCancelled(true); + } - onPlayerVsPlayerPowertool(event, defender, attacker); - } + if (attacker.isGodModeEnabled() && !attacker.isAuthorized("essentials.god.pvp")) { + event.setCancelled(true); + } - private void onPlayerVsPlayerPowertool(final EntityDamageByEntityEvent event, final Player defender, final User attacker) - { - final List commandList = attacker.getPowertool(attacker.getBase().getItemInHand()); - if (commandList != null && !commandList.isEmpty()) - { - for (final String tempCommand : commandList) - { - final String command = powertoolPlayer.matcher(tempCommand).replaceAll(defender.getName()); - if (command != null && !command.isEmpty() && !command.equals(tempCommand)) - { + if (attacker.isHidden() && !attacker.isAuthorized("essentials.vanish.pvp")) { + event.setCancelled(true); + } - class PowerToolInteractTask implements Runnable - { - @Override - public void run() - { - attacker.getServer().dispatchCommand(attacker.getBase(), command); - LOGGER.log(Level.INFO, String.format("[PT] %s issued server command: /%s", attacker.getName(), command)); - } - } - ess.scheduleSyncDelayedTask(new PowerToolInteractTask()); + onPlayerVsPlayerPowertool(event, defender, attacker); + } - event.setCancelled(true); - return; - } - } - } - } + private void onPlayerVsPlayerPowertool(final EntityDamageByEntityEvent event, final Player defender, final User attacker) { + final List commandList = attacker.getPowertool(attacker.getBase().getItemInHand()); + if (commandList != null && !commandList.isEmpty()) { + for (final String tempCommand : commandList) { + final String command = powertoolPlayer.matcher(tempCommand).replaceAll(defender.getName()); + if (command != null && !command.isEmpty() && !command.equals(tempCommand)) { - @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); - } - } + class PowerToolInteractTask implements Runnable { + @Override + public void run() { + attacker.getServer().dispatchCommand(attacker.getBase(), command); + LOGGER.log(Level.INFO, String.format("[PT] %s issued server command: /%s", attacker.getName(), command)); + } + } + ess.scheduleSyncDelayedTask(new PowerToolInteractTask()); - @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); - } - } + event.setCancelled(true); + return; + } + } + } + } - @EventHandler(priority = EventPriority.LOWEST) - public void onPlayerDeathEvent(final PlayerDeathEvent event) - { - final User user = ess.getUser(event.getEntity()); - if (user.isAuthorized("essentials.back.ondeath") && !ess.getSettings().isCommandDisabled("back")) - { - user.setLastLocation(); - user.sendMessage(tl("backAfterDeath")); - } - if (!ess.getSettings().areDeathMessagesEnabled()) - { - event.setDeathMessage(""); - } - } + @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) - public void onPlayerDeathExpEvent(final PlayerDeathEvent event) - { - final User user = ess.getUser(event.getEntity()); - if (user.isAuthorized("essentials.keepxp")) - { - event.setKeepLevel(true); - event.setDroppedExp(0); - } - } + @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.LOW, ignoreCancelled = true) - public void onFoodLevelChange(final FoodLevelChangeEvent event) - { - if (event.getEntity() instanceof Player) - { - final User user = ess.getUser((Player)event.getEntity()); - if (user.isGodModeEnabled()) - { - if (user.isGodModeEnabledRaw()) - { - user.getBase().setFoodLevel(20); - user.getBase().setSaturation(10); - } - event.setCancelled(true); - } - } - } + @EventHandler(priority = EventPriority.LOWEST) + public void onPlayerDeathEvent(final PlayerDeathEvent event) { + final User user = ess.getUser(event.getEntity()); + if (user.isAuthorized("essentials.back.ondeath") && !ess.getSettings().isCommandDisabled("back")) { + user.setLastLocation(); + user.sendMessage(tl("backAfterDeath")); + } + if (!ess.getSettings().areDeathMessagesEnabled()) { + event.setDeathMessage(""); + } + } - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onEntityRegainHealth(final EntityRegainHealthEvent event) - { - if (event.getRegainReason() == RegainReason.SATIATED && event.getEntity() instanceof Player - && ess.getUser((Player)event.getEntity()).isAfk() && ess.getSettings().getFreezeAfkPlayers()) - { - event.setCancelled(true); - } - } + @EventHandler(priority = EventPriority.LOW) + public void onPlayerDeathExpEvent(final PlayerDeathEvent event) { + final User user = ess.getUser(event.getEntity()); + if (user.isAuthorized("essentials.keepxp")) { + event.setKeepLevel(true); + event.setDroppedExp(0); + } + } - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onPotionSplashEvent(final PotionSplashEvent event) - { - for (LivingEntity entity : event.getAffectedEntities()) - { - if (entity instanceof Player && ess.getUser((Player)entity).isGodModeEnabled()) - { - event.setIntensity(entity, 0d); - } - } - } + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onFoodLevelChange(final FoodLevelChangeEvent event) { + if (event.getEntity() instanceof Player) { + final User user = ess.getUser((Player) event.getEntity()); + if (user.isGodModeEnabled()) { + if (user.isGodModeEnabledRaw()) { + user.getBase().setFoodLevel(20); + user.getBase().setSaturation(10); + } + event.setCancelled(true); + } + } + } - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onEntityShootBow(EntityShootBowEvent event) - { - if (event.getEntity() instanceof Player) - { - final User user = ess.getUser((Player)event.getEntity()); - if (user.isAfk()) - { - user.updateActivity(true); - } - } - } + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onEntityRegainHealth(final EntityRegainHealthEvent event) { + if (event.getRegainReason() == RegainReason.SATIATED && event.getEntity() instanceof Player && ess.getUser((Player) event.getEntity()).isAfk() && ess.getSettings().getFreezeAfkPlayers()) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onPotionSplashEvent(final PotionSplashEvent event) { + for (LivingEntity entity : event.getAffectedEntities()) { + if (entity instanceof Player && ess.getUser((Player) entity).isGodModeEnabled()) { + event.setIntensity(entity, 0d); + } + } + } + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onEntityShootBow(EntityShootBowEvent event) { + if (event.getEntity() instanceof Player) { + final User user = ess.getUser((Player) event.getEntity()); + if (user.isAfk()) { + user.updateActivity(true); + } + } + } } diff --git a/Essentials/src/com/earth2me/essentials/EssentialsPlayerListener.java b/Essentials/src/com/earth2me/essentials/EssentialsPlayerListener.java index 4ca588e6e..f1811988e 100644 --- a/Essentials/src/com/earth2me/essentials/EssentialsPlayerListener.java +++ b/Essentials/src/com/earth2me/essentials/EssentialsPlayerListener.java @@ -1,17 +1,10 @@ package com.earth2me.essentials; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.textreader.IText; import com.earth2me.essentials.textreader.KeywordReplacer; import com.earth2me.essentials.textreader.TextInput; import com.earth2me.essentials.textreader.TextPager; import com.earth2me.essentials.utils.LocationUtil; -import java.io.IOException; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.logging.Level; -import java.util.logging.Logger; import net.ess3.api.IEssentials; import org.bukkit.GameMode; import org.bukkit.Location; @@ -31,747 +24,579 @@ import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; +import java.io.IOException; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.logging.Level; +import java.util.logging.Logger; -public class EssentialsPlayerListener implements Listener -{ - private static final Logger LOGGER = Logger.getLogger("Essentials"); - private final transient IEssentials ess; - - public EssentialsPlayerListener(final IEssentials parent) - { - this.ess = parent; - } - - @EventHandler(priority = EventPriority.NORMAL) - public void onPlayerRespawn(final PlayerRespawnEvent event) - { - final User user = ess.getUser(event.getPlayer()); - updateCompass(user); - user.setDisplayNick(); - - if (ess.getSettings().isTeleportInvulnerability()) - { - user.enableInvulnerabilityAfterTeleport(); - } - } - - @EventHandler(priority = EventPriority.LOWEST) - public void onPlayerChat(final AsyncPlayerChatEvent event) - { - final User user = ess.getUser(event.getPlayer()); - if (user.isMuted()) - { - event.setCancelled(true); - user.sendMessage(tl("voiceSilenced")); - LOGGER.info(tl("mutedUserSpeaks", user.getName())); - } - try - { - final Iterator it = event.getRecipients().iterator(); - while (it.hasNext()) - { - final User u = ess.getUser(it.next()); - if (u.isIgnoredPlayer(user)) - { - it.remove(); - } - } - } - catch (UnsupportedOperationException ex) - { - if (ess.getSettings().isDebug()) - { - ess.getLogger().log(Level.INFO, "Ignore could not block chat due to custom chat plugin event.", ex); - } - else - { - ess.getLogger().info("Ignore could not block chat due to custom chat plugin event."); - } - } - - user.updateActivity(true); - user.setDisplayNick(); - } - - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerMove(final PlayerMoveEvent event) - { - if (event.getFrom().getBlockX() == event.getTo().getBlockX() - && event.getFrom().getBlockZ() == event.getTo().getBlockZ() - && event.getFrom().getBlockY() == event.getTo().getBlockY()) - { - return; - } - - if (!ess.getSettings().cancelAfkOnMove() && !ess.getSettings().getFreezeAfkPlayers()) - { - event.getHandlers().unregister(this); - - if (ess.getSettings().isDebug()) - { - LOGGER.log(Level.INFO, "Unregistering move listener"); - } - - return; - } - - final User user = ess.getUser(event.getPlayer()); - if (user.isAfk() && ess.getSettings().getFreezeAfkPlayers()) - { - final Location from = event.getFrom(); - final Location origTo = event.getTo(); - final Location to = origTo.clone(); - if (ess.getSettings().cancelAfkOnMove() && origTo.getY() >= from.getBlockY() + 1) - { - user.updateActivity(true); - return; - } - 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.HIGHEST) - public void onPlayerQuit(final PlayerQuitEvent event) - { - final User user = ess.getUser(event.getPlayer()); - - if (ess.getSettings().allowSilentJoinQuit() && user.isAuthorized("essentials.silentquit")) - { - event.setQuitMessage(null); - } - else if (ess.getSettings().isCustomQuitMessage() && event.getQuitMessage() != null) - { - final Player player = event.getPlayer(); - event.setQuitMessage( - ess.getSettings().getCustomQuitMessage() - .replace("{PLAYER}", player.getDisplayName()) - .replace("{USERNAME}", player.getName())); - } - - if (ess.getSettings().removeGodOnDisconnect() && user.isGodModeEnabled()) - { - user.setGodModeEnabled(false); - } - if (user.isVanished()) - { - user.setVanished(false); - } - user.setLogoutLocation(); - if (user.isRecipeSee()) - { - user.getBase().getOpenInventory().getTopInventory().clear(); - } - - for (HumanEntity viewer : user.getBase().getInventory().getViewers()) - { - if (viewer instanceof Player) - { - User uviewer = ess.getUser((Player)viewer); - if (uviewer.isInvSee()) - { - uviewer.getBase().closeInventory(); - } - } - } - - user.updateActivity(false); - user.dispose(); - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onPlayerJoin(final PlayerJoinEvent event) - { - final String joinMessage = event.getJoinMessage(); - ess.runTaskAsynchronously(new Runnable() - { - @Override - public void run() - { - delayedJoin(event.getPlayer(), joinMessage); - } - }); - if (ess.getSettings().allowSilentJoinQuit() || ess.getSettings().isCustomJoinMessage()) - { - event.setJoinMessage(null); - } - } - - public void delayedJoin(final Player player, final String message) - { - if (!player.isOnline()) - { - return; - } - - ess.getBackup().onPlayerJoin(); - final User dUser = ess.getUser(player); +import static com.earth2me.essentials.I18n.tl; - if (dUser.isNPC()) - { - dUser.setNPC(false); - } +public class EssentialsPlayerListener implements Listener { + private static final Logger LOGGER = Logger.getLogger("Essentials"); + private final transient IEssentials ess; - final long currentTime = System.currentTimeMillis(); - dUser.checkMuteTimeout(currentTime); - dUser.updateActivity(false); + public EssentialsPlayerListener(final IEssentials parent) { + this.ess = parent; + } - IText tempInput = null; + @EventHandler(priority = EventPriority.NORMAL) + public void onPlayerRespawn(final PlayerRespawnEvent event) { + final User user = ess.getUser(event.getPlayer()); + updateCompass(user); + user.setDisplayNick(); - if (!ess.getSettings().isCommandDisabled("motd")) - { - try - { - tempInput = new TextInput(dUser.getSource(), "motd", true, ess); - } - catch (IOException ex) - { - if (ess.getSettings().isDebug()) - { - LOGGER.log(Level.WARNING, ex.getMessage(), ex); - } - else - { - LOGGER.log(Level.WARNING, ex.getMessage()); - } - } - } + if (ess.getSettings().isTeleportInvulnerability()) { + user.enableInvulnerabilityAfterTeleport(); + } + } - final IText input = tempInput; + @EventHandler(priority = EventPriority.LOWEST) + public void onPlayerChat(final AsyncPlayerChatEvent event) { + final User user = ess.getUser(event.getPlayer()); + if (user.isMuted()) { + event.setCancelled(true); + user.sendMessage(tl("voiceSilenced")); + LOGGER.info(tl("mutedUserSpeaks", user.getName())); + } + try { + final Iterator it = event.getRecipients().iterator(); + while (it.hasNext()) { + final User u = ess.getUser(it.next()); + if (u.isIgnoredPlayer(user)) { + it.remove(); + } + } + } catch (UnsupportedOperationException ex) { + if (ess.getSettings().isDebug()) { + ess.getLogger().log(Level.INFO, "Ignore could not block chat due to custom chat plugin event.", ex); + } else { + ess.getLogger().info("Ignore could not block chat due to custom chat plugin event."); + } + } - class DelayJoinTask implements Runnable - { - @Override - public void run() - { - final User user = ess.getUser(player); + user.updateActivity(true); + user.setDisplayNick(); + } - if (!user.getBase().isOnline()) - { - return; - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerMove(final PlayerMoveEvent event) { + if (event.getFrom().getBlockX() == event.getTo().getBlockX() && event.getFrom().getBlockZ() == event.getTo().getBlockZ() && event.getFrom().getBlockY() == event.getTo().getBlockY()) { + return; + } - user.startTransaction(); + if (!ess.getSettings().cancelAfkOnMove() && !ess.getSettings().getFreezeAfkPlayers()) { + event.getHandlers().unregister(this); - user.setLastAccountName(user.getBase().getName()); - user.setLastLogin(currentTime); - user.setDisplayNick(); - updateCompass(user); + if (ess.getSettings().isDebug()) { + LOGGER.log(Level.INFO, "Unregistering move listener"); + } - if (!ess.getVanishedPlayers().isEmpty() && !user.isAuthorized("essentials.vanish.see")) - { - for (String p : ess.getVanishedPlayers()) - { - Player toVanish = ess.getServer().getPlayerExact(p); - if (toVanish != null && toVanish.isOnline()) - { - user.getBase().hidePlayer(toVanish); - } - } - } + return; + } - if (user.isAuthorized("essentials.sleepingignored")) - { - user.getBase().setSleepingIgnored(true); - } + final User user = ess.getUser(event.getPlayer()); + if (user.isAfk() && ess.getSettings().getFreezeAfkPlayers()) { + final Location from = event.getFrom(); + final Location origTo = event.getTo(); + final Location to = origTo.clone(); + if (ess.getSettings().cancelAfkOnMove() && origTo.getY() >= from.getBlockY() + 1) { + user.updateActivity(true); + return; + } + 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); + } + } - if (ess.getSettings().allowSilentJoinQuit() && (user.isAuthorized("essentials.silentjoin") || user.isAuthorized("essentials.silentjoin.vanish"))) - { - if (user.isAuthorized("essentials.silentjoin.vanish")) - { - user.setVanished(true); - } - } - else if (message == null) - { - //NOOP - } - else if (ess.getSettings().isCustomJoinMessage()) - { - ess.getServer().broadcastMessage( - ess.getSettings().getCustomJoinMessage() - .replace("{PLAYER}", player.getDisplayName()) - .replace("{USERNAME}", player.getName())); - } - else if (ess.getSettings().allowSilentJoinQuit()) - { - ess.getServer().broadcastMessage(message); - } + @EventHandler(priority = EventPriority.HIGHEST) + public void onPlayerQuit(final PlayerQuitEvent event) { + final User user = ess.getUser(event.getPlayer()); - if (input != null && user.isAuthorized("essentials.motd")) - { - final IText output = new KeywordReplacer(input, user.getSource(), ess); - final TextPager pager = new TextPager(output, true); - pager.showPage("1", null, "motd", user.getSource()); - } + if (ess.getSettings().allowSilentJoinQuit() && user.isAuthorized("essentials.silentquit")) { + event.setQuitMessage(null); + } else if (ess.getSettings().isCustomQuitMessage() && event.getQuitMessage() != null) { + final Player player = event.getPlayer(); + event.setQuitMessage(ess.getSettings().getCustomQuitMessage().replace("{PLAYER}", player.getDisplayName()).replace("{USERNAME}", player.getName())); + } - if (!ess.getSettings().isCommandDisabled("mail") && user.isAuthorized("essentials.mail")) - { - final List mail = user.getMails(); - if (mail.isEmpty()) - { - user.sendMessage(tl("noNewMail")); - } - else - { - user.sendMessage(tl("youHaveNewMail", mail.size())); - } - } + if (ess.getSettings().removeGodOnDisconnect() && user.isGodModeEnabled()) { + user.setGodModeEnabled(false); + } + if (user.isVanished()) { + user.setVanished(false); + } + user.setLogoutLocation(); + if (user.isRecipeSee()) { + user.getBase().getOpenInventory().getTopInventory().clear(); + } - if (user.isAuthorized("essentials.fly.safelogin")) - { - user.getBase().setFallDistance(0); - if (LocationUtil.shouldFly(user.getLocation())) - { - user.getBase().setAllowFlight(true); - user.getBase().setFlying(true); - user.getBase().sendMessage(tl("flyMode", tl("enabled"), user.getDisplayName())); - } - } + for (HumanEntity viewer : user.getBase().getInventory().getViewers()) { + if (viewer instanceof Player) { + User uviewer = ess.getUser((Player) viewer); + if (uviewer.isInvSee()) { + uviewer.getBase().closeInventory(); + } + } + } - if (!user.isAuthorized("essentials.speed")) - { - user.getBase().setFlySpeed(0.1f); - user.getBase().setWalkSpeed(0.2f); - } + user.updateActivity(false); + user.dispose(); + } - user.stopTransaction(); - } - } + @EventHandler(priority = EventPriority.HIGHEST) + public void onPlayerJoin(final PlayerJoinEvent event) { + final String joinMessage = event.getJoinMessage(); + ess.runTaskAsynchronously(new Runnable() { + @Override + public void run() { + delayedJoin(event.getPlayer(), joinMessage); + } + }); + if (ess.getSettings().allowSilentJoinQuit() || ess.getSettings().isCustomJoinMessage()) { + event.setJoinMessage(null); + } + } - ess.scheduleSyncDelayedTask(new DelayJoinTask()); - } + public void delayedJoin(final Player player, final String message) { + if (!player.isOnline()) { + return; + } - // Makes the compass item ingame always point to the first essentials home. #EasterEgg - private void updateCompass(final User user) - { - Location loc = user.getHome(user.getLocation()); - if (loc == null) - { - loc = user.getBase().getBedSpawnLocation(); - } - if (loc != null) - { - final Location updateLoc = loc; - user.getBase().setCompassTarget(updateLoc); - } - } + ess.getBackup().onPlayerJoin(); + final User dUser = ess.getUser(player); - @EventHandler(priority = EventPriority.HIGH) - public void onPlayerLogin(final PlayerLoginEvent event) - { - switch (event.getResult()) - { - case KICK_FULL: - final User kfuser = ess.getUser(event.getPlayer()); - if (kfuser.isAuthorized("essentials.joinfullserver")) - { - event.allow(); - return; - } - event.disallow(Result.KICK_FULL, tl("serverFull")); - break; - default: - break; - } - } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerTeleport(final PlayerTeleportEvent event) - { - final boolean backListener = ess.getSettings().registerBackInListener(); - final boolean teleportInvulnerability = ess.getSettings().isTeleportInvulnerability(); - if (backListener || teleportInvulnerability) - { - final User user = ess.getUser(event.getPlayer()); - //There is TeleportCause.COMMMAND but plugins have to actively pass the cause in on their teleports. - if (backListener && (event.getCause() == TeleportCause.PLUGIN || event.getCause() == TeleportCause.COMMAND)) - { - user.setLastLocation(); - } - if (teleportInvulnerability && (event.getCause() == TeleportCause.PLUGIN || event.getCause() == TeleportCause.COMMAND)) - { - user.enableInvulnerabilityAfterTeleport(); - } - } - } + if (dUser.isNPC()) { + dUser.setNPC(false); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerEggThrow(final PlayerEggThrowEvent event) - { - final User user = ess.getUser(event.getPlayer()); - final ItemStack stack = new ItemStack(Material.EGG, 1); - if (user.hasUnlimited(stack)) - { - user.getBase().getInventory().addItem(stack); - user.getBase().updateInventory(); - } - } + final long currentTime = System.currentTimeMillis(); + dUser.checkMuteTimeout(currentTime); + dUser.updateActivity(false); - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerBucketEmpty(final PlayerBucketEmptyEvent event) - { - final User user = ess.getUser(event.getPlayer()); - if (user.hasUnlimited(new ItemStack(event.getBucket()))) - { - event.getItemStack().setType(event.getBucket()); - ess.scheduleSyncDelayedTask(new Runnable() - { - @Override - public void run() - { - user.getBase().updateInventory(); - } - }); - } - } + IText tempInput = null; - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPlayerCommandPreprocess(final PlayerCommandPreprocessEvent event) - { - final Player player = event.getPlayer(); - final String cmd = event.getMessage().toLowerCase(Locale.ENGLISH).split(" ")[0].replace("/", "").toLowerCase(Locale.ENGLISH); - if (ess.getSettings().getSocialSpyCommands().contains(cmd) || ess.getSettings().getSocialSpyCommands().contains("*")) - { - for (User spyer : ess.getOnlineUsers()) - { - if (spyer.isSocialSpyEnabled() && !player.equals(spyer.getBase())) - { - spyer.sendMessage(player.getDisplayName() + " : " + event.getMessage()); - } - } - } - else if (!cmd.equalsIgnoreCase("afk")) - { - final User user = ess.getUser(player); - user.updateActivity(true); - } - } + if (!ess.getSettings().isCommandDisabled("motd")) { + try { + tempInput = new TextInput(dUser.getSource(), "motd", true, ess); + } catch (IOException ex) { + if (ess.getSettings().isDebug()) { + LOGGER.log(Level.WARNING, ex.getMessage(), ex); + } else { + LOGGER.log(Level.WARNING, ex.getMessage()); + } + } + } - @EventHandler(priority = EventPriority.NORMAL) - public void onPlayerChangedWorldFlyReset(final PlayerChangedWorldEvent event) - { - final User user = ess.getUser(event.getPlayer()); - if (user.getBase().getGameMode() != GameMode.CREATIVE && !user.isAuthorized("essentials.fly")) - { - user.getBase().setFallDistance(0f); - user.getBase().setAllowFlight(false); - } - if (!user.isAuthorized("essentials.speed")) - { - user.getBase().setFlySpeed(0.1f); - user.getBase().setWalkSpeed(0.2f); - } - else - { - if (user.getBase().getFlySpeed() > ess.getSettings().getMaxFlySpeed() && !user.isAuthorized("essentials.speed.bypass")) - { - user.getBase().setFlySpeed((float)ess.getSettings().getMaxFlySpeed()); - } - else - { - user.getBase().setFlySpeed(user.getBase().getFlySpeed() * 0.99999f); - } + final IText input = tempInput; - if (user.getBase().getWalkSpeed() > ess.getSettings().getMaxWalkSpeed() && !user.isAuthorized("essentials.speed.bypass")) - { - user.getBase().setWalkSpeed((float)ess.getSettings().getMaxWalkSpeed()); - } - else - { - user.getBase().setWalkSpeed(user.getBase().getWalkSpeed() * 0.99999f); - } - } - } + class DelayJoinTask implements Runnable { + @Override + public void run() { + final User user = ess.getUser(player); - @EventHandler(priority = EventPriority.MONITOR) - public void onPlayerChangedWorld(final PlayerChangedWorldEvent event) - { - final User user = ess.getUser(event.getPlayer()); - final String newWorld = event.getPlayer().getLocation().getWorld().getName(); - user.setDisplayNick(); - updateCompass(user); - if (ess.getSettings().getNoGodWorlds().contains(newWorld) && user.isGodModeEnabledRaw()) - { - user.sendMessage(tl("noGodWorldWarning")); - } + if (!user.getBase().isOnline()) { + return; + } - if (!user.getWorld().getName().equals(newWorld)) - { - user.sendMessage(tl("currentWorld", newWorld)); - } - if (user.isVanished()) - { - user.setVanished(user.isAuthorized("essentials.vanish")); - } - } + user.startTransaction(); - @EventHandler(priority = EventPriority.NORMAL) - public void onPlayerInteract(final PlayerInteractEvent event) - { - switch (event.getAction()) - { - case RIGHT_CLICK_BLOCK: - if (!event.isCancelled() && event.getClickedBlock().getType() == Material.BED_BLOCK && ess.getSettings().getUpdateBedAtDaytime()) - { - User player = ess.getUser(event.getPlayer()); - if (player.isAuthorized("essentials.sethome.bed")) - { - player.getBase().setBedSpawnLocation(event.getClickedBlock().getLocation()); - player.sendMessage(tl("bedSet", player.getLocation().getWorld().getName(), player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ())); - } - } - break; - case LEFT_CLICK_AIR: - if (event.getPlayer().isFlying()) - { - final User user = ess.getUser(event.getPlayer()); - if (user.isFlyClickJump()) - { - useFlyClickJump(user); - return; - } - } - case LEFT_CLICK_BLOCK: - if (event.getItem() != null && event.getItem().getType() != Material.AIR) - { - final User user = ess.getUser(event.getPlayer()); - user.updateActivity(true); - if (user.hasPowerTools() && user.arePowerToolsEnabled() && usePowertools(user, event.getItem().getTypeId())) - { - event.setCancelled(true); - } - } - break; - default: - break; - } - } + user.setLastAccountName(user.getBase().getName()); + user.setLastLogin(currentTime); + user.setDisplayNick(); + updateCompass(user); - // This method allows the /jump lock feature to work, allows teleporting while flying #EasterEgg - private void useFlyClickJump(final User user) - { - try - { - final Location otarget = LocationUtil.getTarget(user.getBase()); + if (!ess.getVanishedPlayers().isEmpty() && !user.isAuthorized("essentials.vanish.see")) { + for (String p : ess.getVanishedPlayers()) { + Player toVanish = ess.getServer().getPlayerExact(p); + if (toVanish != null && toVanish.isOnline()) { + user.getBase().hidePlayer(toVanish); + } + } + } - class DelayedClickJumpTask implements Runnable - { - @Override - public void run() - { - Location loc = user.getLocation(); - loc.setX(otarget.getX()); - loc.setZ(otarget.getZ()); - while (LocationUtil.isBlockDamaging(loc.getWorld(), loc.getBlockX(), loc.getBlockY() - 1, loc.getBlockZ())) - { - loc.setY(loc.getY() + 1d); - } - user.getBase().teleport(loc, TeleportCause.PLUGIN); - } - } - ess.scheduleSyncDelayedTask(new DelayedClickJumpTask()); - } - catch (Exception ex) - { - if (ess.getSettings().isDebug()) - { - LOGGER.log(Level.WARNING, ex.getMessage(), ex); - } - } - } + if (user.isAuthorized("essentials.sleepingignored")) { + user.getBase().setSleepingIgnored(true); + } - private boolean usePowertools(final User user, final int id) - { - final List commandList = user.getPowertool(id); - 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.contains("{player}")) - { - continue; - } - else if (command.startsWith("c:")) - { - used = true; - user.getBase().chat(command.substring(2)); - } - else - { - used = true; + if (ess.getSettings().allowSilentJoinQuit() && (user.isAuthorized("essentials.silentjoin") || user.isAuthorized("essentials.silentjoin.vanish"))) { + if (user.isAuthorized("essentials.silentjoin.vanish")) { + user.setVanished(true); + } + } else if (message == null) { + //NOOP + } else if (ess.getSettings().isCustomJoinMessage()) { + ess.getServer().broadcastMessage(ess.getSettings().getCustomJoinMessage().replace("{PLAYER}", player.getDisplayName()).replace("{USERNAME}", player.getName())); + } else if (ess.getSettings().allowSilentJoinQuit()) { + ess.getServer().broadcastMessage(message); + } - class PowerToolUseTask implements Runnable - { - @Override - public void run() - { - user.getServer().dispatchCommand(user.getBase(), command); - LOGGER.log(Level.INFO, String.format("[PT] %s issued server command: /%s", user.getName(), command)); - } - } - ess.scheduleSyncDelayedTask(new PowerToolUseTask()); + if (input != null && user.isAuthorized("essentials.motd")) { + final IText output = new KeywordReplacer(input, user.getSource(), ess); + final TextPager pager = new TextPager(output, true); + pager.showPage("1", null, "motd", user.getSource()); + } - } - } - return used; - } + if (!ess.getSettings().isCommandDisabled("mail") && user.isAuthorized("essentials.mail")) { + final List mail = user.getMails(); + if (mail.isEmpty()) { + user.sendMessage(tl("noNewMail")); + } else { + user.sendMessage(tl("youHaveNewMail", mail.size())); + } + } - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onPlayerPickupItem(final PlayerPickupItemEvent event) - { - if (ess.getSettings().getDisableItemPickupWhileAfk()) - { - if (ess.getUser(event.getPlayer()).isAfk()) - { - event.setCancelled(true); - } - } - } + if (user.isAuthorized("essentials.fly.safelogin")) { + user.getBase().setFallDistance(0); + if (LocationUtil.shouldFly(user.getLocation())) { + user.getBase().setAllowFlight(true); + user.getBase().setFlying(true); + user.getBase().sendMessage(tl("flyMode", tl("enabled"), user.getDisplayName())); + } + } - @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) - public void onInventoryClickEvent(final InventoryClickEvent event) - { - Player refreshPlayer = null; - final Inventory top = event.getView().getTopInventory(); - final InventoryType type = top.getType(); + if (!user.isAuthorized("essentials.speed")) { + user.getBase().setFlySpeed(0.1f); + user.getBase().setWalkSpeed(0.2f); + } - if (type == InventoryType.PLAYER) - { - final User user = ess.getUser((Player)event.getWhoClicked()); - final InventoryHolder invHolder = top.getHolder(); - if (invHolder != null && invHolder instanceof HumanEntity) - { - final User invOwner = ess.getUser((Player)invHolder); - if (user.isInvSee() && (!user.isAuthorized("essentials.invsee.modify") - || invOwner.isAuthorized("essentials.invsee.preventmodify") - || !invOwner.getBase().isOnline())) - { - event.setCancelled(true); - refreshPlayer = user.getBase(); - } - } - } - else if (type == InventoryType.ENDER_CHEST) - { - final User user = ess.getUser((Player)event.getWhoClicked()); - if (user.isEnderSee() && (!user.isAuthorized("essentials.enderchest.modify"))) - { - event.setCancelled(true); - refreshPlayer = user.getBase(); - } - } - else if (type == InventoryType.WORKBENCH) - { - User user = ess.getUser((Player)event.getWhoClicked()); - if (user.isRecipeSee()) - { - event.setCancelled(true); - refreshPlayer = user.getBase(); - } - } - else if (type == InventoryType.CHEST && top.getSize() == 9) - { - final User user = ess.getUser((Player)event.getWhoClicked()); - final InventoryHolder invHolder = top.getHolder(); - if (invHolder != null && invHolder instanceof HumanEntity && user.isInvSee()) - { - event.setCancelled(true); - refreshPlayer = user.getBase(); - } - } + user.stopTransaction(); + } + } - if (refreshPlayer != null) - { - final Player player = refreshPlayer; - ess.scheduleSyncDelayedTask(new Runnable() - { - @Override - public void run() - { - player.updateInventory(); - } - }, 1); - } - } + ess.scheduleSyncDelayedTask(new DelayJoinTask()); + } - @EventHandler(priority = EventPriority.MONITOR) - public void onInventoryCloseEvent(final InventoryCloseEvent event) - { - Player refreshPlayer = null; - final Inventory top = event.getView().getTopInventory(); - final InventoryType type = top.getType(); - if (type == InventoryType.PLAYER) - { - final User user = ess.getUser((Player)event.getPlayer()); - user.setInvSee(false); - refreshPlayer = user.getBase(); - } - else if (type == InventoryType.ENDER_CHEST) - { - final User user = ess.getUser((Player)event.getPlayer()); - user.setEnderSee(false); - refreshPlayer = user.getBase(); - } - else if (type == InventoryType.WORKBENCH) - { - final User user = ess.getUser((Player)event.getPlayer()); - if (user.isRecipeSee()) - { - user.setRecipeSee(false); - event.getView().getTopInventory().clear(); - refreshPlayer = user.getBase(); - } - } - else if (type == InventoryType.CHEST && top.getSize() == 9) - { - final InventoryHolder invHolder = top.getHolder(); - if (invHolder != null && invHolder instanceof HumanEntity) - { - final User user = ess.getUser((Player)event.getPlayer()); - user.setInvSee(false); - refreshPlayer = user.getBase(); - } - } + // Makes the compass item ingame always point to the first essentials home. #EasterEgg + private void updateCompass(final User user) { + Location loc = user.getHome(user.getLocation()); + if (loc == null) { + loc = user.getBase().getBedSpawnLocation(); + } + if (loc != null) { + final Location updateLoc = loc; + user.getBase().setCompassTarget(updateLoc); + } + } - if (refreshPlayer != null) - { - final Player player = refreshPlayer; - ess.scheduleSyncDelayedTask(new Runnable() - { - @Override - public void run() - { - player.updateInventory(); - } - }, 1); - } - } + @EventHandler(priority = EventPriority.HIGH) + public void onPlayerLogin(final PlayerLoginEvent event) { + switch (event.getResult()) { + case KICK_FULL: + final User kfuser = ess.getUser(event.getPlayer()); + if (kfuser.isAuthorized("essentials.joinfullserver")) { + event.allow(); + return; + } + event.disallow(Result.KICK_FULL, tl("serverFull")); + break; + default: + break; + } + } - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onPlayerFishEvent(final PlayerFishEvent event) - { - final User user = ess.getUser(event.getPlayer()); - user.updateActivity(true); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerTeleport(final PlayerTeleportEvent event) { + final boolean backListener = ess.getSettings().registerBackInListener(); + final boolean teleportInvulnerability = ess.getSettings().isTeleportInvulnerability(); + if (backListener || teleportInvulnerability) { + final User user = ess.getUser(event.getPlayer()); + //There is TeleportCause.COMMMAND but plugins have to actively pass the cause in on their teleports. + if (backListener && (event.getCause() == TeleportCause.PLUGIN || event.getCause() == TeleportCause.COMMAND)) { + user.setLastLocation(); + } + if (teleportInvulnerability && (event.getCause() == TeleportCause.PLUGIN || event.getCause() == TeleportCause.COMMAND)) { + user.enableInvulnerabilityAfterTeleport(); + } + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerEggThrow(final PlayerEggThrowEvent event) { + final User user = ess.getUser(event.getPlayer()); + final ItemStack stack = new ItemStack(Material.EGG, 1); + if (user.hasUnlimited(stack)) { + user.getBase().getInventory().addItem(stack); + user.getBase().updateInventory(); + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerBucketEmpty(final PlayerBucketEmptyEvent event) { + final User user = ess.getUser(event.getPlayer()); + if (user.hasUnlimited(new ItemStack(event.getBucket()))) { + event.getItemStack().setType(event.getBucket()); + ess.scheduleSyncDelayedTask(new Runnable() { + @Override + public void run() { + user.getBase().updateInventory(); + } + }); + } + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPlayerCommandPreprocess(final PlayerCommandPreprocessEvent event) { + final Player player = event.getPlayer(); + final String cmd = event.getMessage().toLowerCase(Locale.ENGLISH).split(" ")[0].replace("/", "").toLowerCase(Locale.ENGLISH); + if (ess.getSettings().getSocialSpyCommands().contains(cmd) || ess.getSettings().getSocialSpyCommands().contains("*")) { + for (User spyer : ess.getOnlineUsers()) { + if (spyer.isSocialSpyEnabled() && !player.equals(spyer.getBase())) { + spyer.sendMessage(player.getDisplayName() + " : " + event.getMessage()); + } + } + } else if (!cmd.equalsIgnoreCase("afk")) { + final User user = ess.getUser(player); + user.updateActivity(true); + } + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onPlayerChangedWorldFlyReset(final PlayerChangedWorldEvent event) { + final User user = ess.getUser(event.getPlayer()); + if (user.getBase().getGameMode() != GameMode.CREATIVE && !user.isAuthorized("essentials.fly")) { + user.getBase().setFallDistance(0f); + user.getBase().setAllowFlight(false); + } + if (!user.isAuthorized("essentials.speed")) { + user.getBase().setFlySpeed(0.1f); + user.getBase().setWalkSpeed(0.2f); + } else { + if (user.getBase().getFlySpeed() > ess.getSettings().getMaxFlySpeed() && !user.isAuthorized("essentials.speed.bypass")) { + user.getBase().setFlySpeed((float) ess.getSettings().getMaxFlySpeed()); + } else { + user.getBase().setFlySpeed(user.getBase().getFlySpeed() * 0.99999f); + } + + if (user.getBase().getWalkSpeed() > ess.getSettings().getMaxWalkSpeed() && !user.isAuthorized("essentials.speed.bypass")) { + user.getBase().setWalkSpeed((float) ess.getSettings().getMaxWalkSpeed()); + } else { + user.getBase().setWalkSpeed(user.getBase().getWalkSpeed() * 0.99999f); + } + } + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerChangedWorld(final PlayerChangedWorldEvent event) { + final User user = ess.getUser(event.getPlayer()); + final String newWorld = event.getPlayer().getLocation().getWorld().getName(); + user.setDisplayNick(); + updateCompass(user); + if (ess.getSettings().getNoGodWorlds().contains(newWorld) && user.isGodModeEnabledRaw()) { + user.sendMessage(tl("noGodWorldWarning")); + } + + if (!user.getWorld().getName().equals(newWorld)) { + user.sendMessage(tl("currentWorld", newWorld)); + } + if (user.isVanished()) { + user.setVanished(user.isAuthorized("essentials.vanish")); + } + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onPlayerInteract(final PlayerInteractEvent event) { + switch (event.getAction()) { + case RIGHT_CLICK_BLOCK: + if (!event.isCancelled() && event.getClickedBlock().getType() == Material.BED_BLOCK && ess.getSettings().getUpdateBedAtDaytime()) { + User player = ess.getUser(event.getPlayer()); + if (player.isAuthorized("essentials.sethome.bed")) { + player.getBase().setBedSpawnLocation(event.getClickedBlock().getLocation()); + player.sendMessage(tl("bedSet", player.getLocation().getWorld().getName(), player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ())); + } + } + break; + case LEFT_CLICK_AIR: + if (event.getPlayer().isFlying()) { + final User user = ess.getUser(event.getPlayer()); + if (user.isFlyClickJump()) { + useFlyClickJump(user); + return; + } + } + case LEFT_CLICK_BLOCK: + if (event.getItem() != null && event.getItem().getType() != Material.AIR) { + final User user = ess.getUser(event.getPlayer()); + user.updateActivity(true); + if (user.hasPowerTools() && user.arePowerToolsEnabled() && usePowertools(user, event.getItem().getTypeId())) { + event.setCancelled(true); + } + } + break; + default: + break; + } + } + + // This method allows the /jump lock feature to work, allows teleporting while flying #EasterEgg + private void useFlyClickJump(final User user) { + try { + final Location otarget = LocationUtil.getTarget(user.getBase()); + + class DelayedClickJumpTask implements Runnable { + @Override + public void run() { + Location loc = user.getLocation(); + loc.setX(otarget.getX()); + loc.setZ(otarget.getZ()); + while (LocationUtil.isBlockDamaging(loc.getWorld(), loc.getBlockX(), loc.getBlockY() - 1, loc.getBlockZ())) { + loc.setY(loc.getY() + 1d); + } + user.getBase().teleport(loc, TeleportCause.PLUGIN); + } + } + ess.scheduleSyncDelayedTask(new DelayedClickJumpTask()); + } catch (Exception ex) { + if (ess.getSettings().isDebug()) { + LOGGER.log(Level.WARNING, ex.getMessage(), ex); + } + } + } + + private boolean usePowertools(final User user, final int id) { + final List commandList = user.getPowertool(id); + 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.contains("{player}")) { + continue; + } else if (command.startsWith("c:")) { + used = true; + user.getBase().chat(command.substring(2)); + } else { + used = true; + + class PowerToolUseTask implements Runnable { + @Override + public void run() { + user.getServer().dispatchCommand(user.getBase(), command); + LOGGER.log(Level.INFO, String.format("[PT] %s issued server command: /%s", user.getName(), command)); + } + } + ess.scheduleSyncDelayedTask(new PowerToolUseTask()); + + } + } + return used; + } + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onPlayerPickupItem(final PlayerPickupItemEvent event) { + if (ess.getSettings().getDisableItemPickupWhileAfk()) { + if (ess.getUser(event.getPlayer()).isAfk()) { + event.setCancelled(true); + } + } + } + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + public void onInventoryClickEvent(final InventoryClickEvent event) { + Player refreshPlayer = null; + final Inventory top = event.getView().getTopInventory(); + final InventoryType type = top.getType(); + + if (type == InventoryType.PLAYER) { + final User user = ess.getUser((Player) event.getWhoClicked()); + final InventoryHolder invHolder = top.getHolder(); + if (invHolder != null && invHolder instanceof HumanEntity) { + final User invOwner = ess.getUser((Player) invHolder); + if (user.isInvSee() && (!user.isAuthorized("essentials.invsee.modify") || invOwner.isAuthorized("essentials.invsee.preventmodify") || !invOwner.getBase().isOnline())) { + event.setCancelled(true); + refreshPlayer = user.getBase(); + } + } + } else if (type == InventoryType.ENDER_CHEST) { + final User user = ess.getUser((Player) event.getWhoClicked()); + if (user.isEnderSee() && (!user.isAuthorized("essentials.enderchest.modify"))) { + event.setCancelled(true); + refreshPlayer = user.getBase(); + } + } else if (type == InventoryType.WORKBENCH) { + User user = ess.getUser((Player) event.getWhoClicked()); + if (user.isRecipeSee()) { + event.setCancelled(true); + refreshPlayer = user.getBase(); + } + } else if (type == InventoryType.CHEST && top.getSize() == 9) { + final User user = ess.getUser((Player) event.getWhoClicked()); + final InventoryHolder invHolder = top.getHolder(); + if (invHolder != null && invHolder instanceof HumanEntity && user.isInvSee()) { + event.setCancelled(true); + refreshPlayer = user.getBase(); + } + } + + if (refreshPlayer != null) { + final Player player = refreshPlayer; + ess.scheduleSyncDelayedTask(new Runnable() { + @Override + public void run() { + player.updateInventory(); + } + }, 1); + } + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onInventoryCloseEvent(final InventoryCloseEvent event) { + Player refreshPlayer = null; + final Inventory top = event.getView().getTopInventory(); + final InventoryType type = top.getType(); + if (type == InventoryType.PLAYER) { + final User user = ess.getUser((Player) event.getPlayer()); + user.setInvSee(false); + refreshPlayer = user.getBase(); + } else if (type == InventoryType.ENDER_CHEST) { + final User user = ess.getUser((Player) event.getPlayer()); + user.setEnderSee(false); + refreshPlayer = user.getBase(); + } else if (type == InventoryType.WORKBENCH) { + final User user = ess.getUser((Player) event.getPlayer()); + if (user.isRecipeSee()) { + user.setRecipeSee(false); + event.getView().getTopInventory().clear(); + refreshPlayer = user.getBase(); + } + } else if (type == InventoryType.CHEST && top.getSize() == 9) { + final InventoryHolder invHolder = top.getHolder(); + if (invHolder != null && invHolder instanceof HumanEntity) { + final User user = ess.getUser((Player) event.getPlayer()); + user.setInvSee(false); + refreshPlayer = user.getBase(); + } + } + + if (refreshPlayer != null) { + final Player player = refreshPlayer; + ess.scheduleSyncDelayedTask(new Runnable() { + @Override + public void run() { + player.updateInventory(); + } + }, 1); + } + } + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onPlayerFishEvent(final PlayerFishEvent event) { + final User user = ess.getUser(event.getPlayer()); + user.updateActivity(true); + } } diff --git a/Essentials/src/com/earth2me/essentials/EssentialsPluginListener.java b/Essentials/src/com/earth2me/essentials/EssentialsPluginListener.java index e917d2ec3..1dd13021a 100644 --- a/Essentials/src/com/earth2me/essentials/EssentialsPluginListener.java +++ b/Essentials/src/com/earth2me/essentials/EssentialsPluginListener.java @@ -2,7 +2,6 @@ package com.earth2me.essentials; import com.earth2me.essentials.perm.PermissionsHandler; import com.earth2me.essentials.register.payment.Methods; -import java.util.logging.Level; import net.ess3.api.IEssentials; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -10,56 +9,48 @@ import org.bukkit.event.Listener; import org.bukkit.event.server.PluginDisableEvent; import org.bukkit.event.server.PluginEnableEvent; +import java.util.logging.Level; -public class EssentialsPluginListener implements Listener, IConf -{ - private final transient IEssentials ess; - public EssentialsPluginListener(final IEssentials ess) - { - this.ess = ess; - } +public class EssentialsPluginListener implements Listener, IConf { + private final transient IEssentials ess; - @EventHandler(priority = EventPriority.MONITOR) - public void onPluginEnable(final PluginEnableEvent event) - { - if (event.getPlugin().getName().equals("EssentialsChat")) - { - ess.getSettings().setEssentialsChatActive(true); - } - ess.getPermissionsHandler().checkPermissions(); - ess.getAlternativeCommandsHandler().addPlugin(event.getPlugin()); - if (!Methods.hasMethod() && Methods.setMethod(ess.getServer().getPluginManager())) - { - ess.getLogger().log(Level.INFO, "Payment method found (" + Methods.getMethod().getLongName() + " version: " + ess.getPaymentMethod().getMethod().getVersion() + ")"); - } - } + public EssentialsPluginListener(final IEssentials ess) { + this.ess = ess; + } - @EventHandler(priority = EventPriority.MONITOR) - public void onPluginDisable(final PluginDisableEvent event) - { - if (event.getPlugin().getName().equals("EssentialsChat")) - { - ess.getSettings().setEssentialsChatActive(false); - } - PermissionsHandler permHandler = ess.getPermissionsHandler(); - if (permHandler != null) - { - permHandler.checkPermissions(); - } - ess.getAlternativeCommandsHandler().removePlugin(event.getPlugin()); - // Check to see if the plugin thats being disabled is the one we are using - if (ess.getPaymentMethod() != null && Methods.hasMethod() && Methods.checkDisabled(event.getPlugin())) - { - ess.getPaymentMethod().reset(); - ess.getLogger().log(Level.INFO, "Payment method was disabled. No longer accepting payments."); - } - } + @EventHandler(priority = EventPriority.MONITOR) + public void onPluginEnable(final PluginEnableEvent event) { + if (event.getPlugin().getName().equals("EssentialsChat")) { + ess.getSettings().setEssentialsChatActive(true); + } + ess.getPermissionsHandler().checkPermissions(); + ess.getAlternativeCommandsHandler().addPlugin(event.getPlugin()); + if (!Methods.hasMethod() && Methods.setMethod(ess.getServer().getPluginManager())) { + ess.getLogger().log(Level.INFO, "Payment method found (" + Methods.getMethod().getLongName() + " version: " + ess.getPaymentMethod().getMethod().getVersion() + ")"); + } + } - @Override - public void reloadConfig() - { - ess.getPermissionsHandler().setUseSuperperms(ess.getSettings().useBukkitPermissions()); - ess.getPermissionsHandler().checkPermissions(); - } + @EventHandler(priority = EventPriority.MONITOR) + public void onPluginDisable(final PluginDisableEvent event) { + if (event.getPlugin().getName().equals("EssentialsChat")) { + ess.getSettings().setEssentialsChatActive(false); + } + PermissionsHandler permHandler = ess.getPermissionsHandler(); + if (permHandler != null) { + permHandler.checkPermissions(); + } + ess.getAlternativeCommandsHandler().removePlugin(event.getPlugin()); + // Check to see if the plugin thats being disabled is the one we are using + if (ess.getPaymentMethod() != null && Methods.hasMethod() && Methods.checkDisabled(event.getPlugin())) { + ess.getPaymentMethod().reset(); + ess.getLogger().log(Level.INFO, "Payment method was disabled. No longer accepting payments."); + } + } + + @Override + public void reloadConfig() { + ess.getPermissionsHandler().setUseSuperperms(ess.getSettings().useBukkitPermissions()); + ess.getPermissionsHandler().checkPermissions(); + } } diff --git a/Essentials/src/com/earth2me/essentials/EssentialsTimer.java b/Essentials/src/com/earth2me/essentials/EssentialsTimer.java index 8f75445e2..d742a259a 100644 --- a/Essentials/src/com/earth2me/essentials/EssentialsTimer.java +++ b/Essentials/src/com/earth2me/essentials/EssentialsTimer.java @@ -1,125 +1,101 @@ package com.earth2me.essentials; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.Set; -import java.util.UUID; -import java.util.logging.Level; import net.ess3.api.IEssentials; import org.bukkit.entity.Player; +import java.util.*; +import java.util.logging.Level; -public class EssentialsTimer implements Runnable -{ - private final transient IEssentials ess; - private final transient Set onlineUsers = new HashSet(); - private transient long lastPoll = System.nanoTime(); - private final LinkedList history = new LinkedList(); - private int skip1 = 0; - private int skip2 = 0; - private final long maxTime = 10 * 1000000; - private final long tickInterval = 50; - - EssentialsTimer(final IEssentials ess) - { - this.ess = ess; - history.add(20d); - } - - @Override - public void run() - { - final long startTime = System.nanoTime(); - final long currentTime = System.currentTimeMillis(); - long timeSpent = (startTime - lastPoll) / 1000; - if (timeSpent == 0) - { - timeSpent = 1; - } - if (history.size() > 10) - { - history.remove(); - } - double tps = tickInterval * 1000000.0 / timeSpent; - if (tps <= 21) - { - history.add(tps); - } - lastPoll = startTime; - int count = 0; - for (Player player : ess.getOnlinePlayers()) - { - count++; - if (skip1 > 0) - { - skip1--; - continue; - } - if (count % 10 == 0) - { - if (System.nanoTime() - startTime > maxTime / 2) - { - skip1 = count - 1; - break; - } - } - try - { - final User user = ess.getUser(player); - onlineUsers.add(user.getBase().getUniqueId()); - user.setLastOnlineActivity(currentTime); - user.checkActivity(); - } - catch (Exception e) - { - ess.getLogger().log(Level.WARNING, "EssentialsTimer Error:", e); - } - } - - count = 0; - final Iterator iterator = onlineUsers.iterator(); - while (iterator.hasNext()) - { - count++; - if (skip2 > 0) - { - skip2--; - continue; - } - if (count % 10 == 0) - { - if (System.nanoTime() - startTime > maxTime) - { - skip2 = count - 1; - break; - } - } - final User user = ess.getUser(iterator.next()); - if (user.getLastOnlineActivity() < currentTime && user.getLastOnlineActivity() > user.getLastLogout()) - { - if (!user.isHidden()) { - user.setLastLogout(user.getLastOnlineActivity()); - } - iterator.remove(); - continue; - } - user.checkMuteTimeout(currentTime); - user.checkJailTimeout(currentTime); - user.resetInvulnerabilityAfterTeleport(); - } - } - - public double getAverageTPS() - { - double avg = 0; - for (Double f : history) - { - if (f != null) - { - avg += f; - } - } - return avg / history.size(); - } + +public class EssentialsTimer implements Runnable { + private final transient IEssentials ess; + private final transient Set onlineUsers = new HashSet(); + private transient long lastPoll = System.nanoTime(); + private final LinkedList history = new LinkedList(); + private int skip1 = 0; + private int skip2 = 0; + private final long maxTime = 10 * 1000000; + private final long tickInterval = 50; + + EssentialsTimer(final IEssentials ess) { + this.ess = ess; + history.add(20d); + } + + @Override + public void run() { + final long startTime = System.nanoTime(); + final long currentTime = System.currentTimeMillis(); + long timeSpent = (startTime - lastPoll) / 1000; + if (timeSpent == 0) { + timeSpent = 1; + } + if (history.size() > 10) { + history.remove(); + } + double tps = tickInterval * 1000000.0 / timeSpent; + if (tps <= 21) { + history.add(tps); + } + lastPoll = startTime; + int count = 0; + for (Player player : ess.getOnlinePlayers()) { + count++; + if (skip1 > 0) { + skip1--; + continue; + } + if (count % 10 == 0) { + if (System.nanoTime() - startTime > maxTime / 2) { + skip1 = count - 1; + break; + } + } + try { + final User user = ess.getUser(player); + onlineUsers.add(user.getBase().getUniqueId()); + user.setLastOnlineActivity(currentTime); + user.checkActivity(); + } catch (Exception e) { + ess.getLogger().log(Level.WARNING, "EssentialsTimer Error:", e); + } + } + + count = 0; + final Iterator iterator = onlineUsers.iterator(); + while (iterator.hasNext()) { + count++; + if (skip2 > 0) { + skip2--; + continue; + } + if (count % 10 == 0) { + if (System.nanoTime() - startTime > maxTime) { + skip2 = count - 1; + break; + } + } + final User user = ess.getUser(iterator.next()); + if (user.getLastOnlineActivity() < currentTime && user.getLastOnlineActivity() > user.getLastLogout()) { + if (!user.isHidden()) { + user.setLastLogout(user.getLastOnlineActivity()); + } + iterator.remove(); + continue; + } + user.checkMuteTimeout(currentTime); + user.checkJailTimeout(currentTime); + user.resetInvulnerabilityAfterTeleport(); + } + } + + public double getAverageTPS() { + double avg = 0; + for (Double f : history) { + if (f != null) { + avg += f; + } + } + return avg / history.size(); + } } diff --git a/Essentials/src/com/earth2me/essentials/EssentialsUpgrade.java b/Essentials/src/com/earth2me/essentials/EssentialsUpgrade.java index 1782362c3..d07304940 100644 --- a/Essentials/src/com/earth2me/essentials/EssentialsUpgrade.java +++ b/Essentials/src/com/earth2me/essentials/EssentialsUpgrade.java @@ -1,12 +1,17 @@ package com.earth2me.essentials; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.craftbukkit.BanLookup; import com.earth2me.essentials.craftbukkit.FakeWorld; import com.earth2me.essentials.settings.Spawns; import com.earth2me.essentials.storage.YamlStorageWriter; import com.earth2me.essentials.utils.StringUtil; import com.google.common.base.Charsets; +import net.ess3.api.IEssentials; +import org.bukkit.BanList; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; + import java.io.*; import java.math.BigInteger; import java.security.DigestInputStream; @@ -14,768 +19,597 @@ import java.security.MessageDigest; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; -import net.ess3.api.IEssentials; -import org.bukkit.BanList; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.World; - - -public class EssentialsUpgrade -{ - private final static Logger LOGGER = Logger.getLogger("Essentials"); - private final transient IEssentials ess; - private final transient EssentialsConf doneFile; - - EssentialsUpgrade(final IEssentials essentials) - { - ess = essentials; - if (!ess.getDataFolder().exists()) - { - ess.getDataFolder().mkdirs(); - } - doneFile = new EssentialsConf(new File(ess.getDataFolder(), "upgrades-done.yml")); - doneFile.load(); - } - - private void moveMotdRulesToFile(String name) - { - if (doneFile.getBoolean("move" + name + "ToFile", false)) - { - return; - } - try - { - final File file = new File(ess.getDataFolder(), name + ".txt"); - if (file.exists()) - { - return; - } - final File configFile = new File(ess.getDataFolder(), "config.yml"); - if (!configFile.exists()) - { - return; - } - final EssentialsConf conf = new EssentialsConf(configFile); - conf.load(); - List lines = conf.getStringList(name); - if (lines != null && !lines.isEmpty()) - { - if (!file.createNewFile()) - { - throw new IOException("Failed to create file " + file); - } - PrintWriter writer = new PrintWriter(file); - - for (String line : lines) - { - writer.println(line); - } - writer.close(); - } - doneFile.setProperty("move" + name + "ToFile", true); - doneFile.save(); - } - catch (IOException e) - { - LOGGER.log(Level.SEVERE, tl("upgradingFilesError"), e); - } - } - - private void removeLinesFromConfig(File file, String regex, String info) throws Exception - { - boolean needUpdate = false; - final BufferedReader bReader = new BufferedReader(new FileReader(file)); - final File tempFile = File.createTempFile("essentialsupgrade", ".tmp.yml", ess.getDataFolder()); - final BufferedWriter bWriter = new BufferedWriter(new FileWriter(tempFile)); - do - { - final String line = bReader.readLine(); - if (line == null) - { - break; - } - if (line.matches(regex)) - { - if (!needUpdate && info != null) - { - bWriter.write(info, 0, info.length()); - bWriter.newLine(); - } - needUpdate = true; - } - else - { - if (line.endsWith("\r\n")) - { - bWriter.write(line, 0, line.length() - 2); - } - else if (line.endsWith("\r") || line.endsWith("\n")) - { - bWriter.write(line, 0, line.length() - 1); - } - else - { - bWriter.write(line, 0, line.length()); - } - bWriter.newLine(); - } - } - while (true); - bReader.close(); - bWriter.close(); - if (needUpdate) - { - if (!file.renameTo(new File(file.getParentFile(), file.getName().concat("." + System.currentTimeMillis() + ".upgradebackup")))) - { - throw new Exception(tl("configFileMoveError")); - } - if (!tempFile.renameTo(file)) - { - throw new Exception(tl("configFileRenameError")); - } - } - else - { - tempFile.delete(); - } - } - - private void updateUsersPowerToolsFormat() - { - if (doneFile.getBoolean("updateUsersPowerToolsFormat", false)) - { - return; - } - final File userdataFolder = new File(ess.getDataFolder(), "userdata"); - if (!userdataFolder.exists() || !userdataFolder.isDirectory()) - { - return; - } - final File[] userFiles = userdataFolder.listFiles(); - - for (File file : userFiles) - { - if (!file.isFile() || !file.getName().endsWith(".yml")) - { - continue; - } - final EssentialsConf config = new EssentialsConf(file); - try - { - config.load(); - if (config.hasProperty("powertools")) - { - @SuppressWarnings("unchecked") - final Map powertools = config.getConfigurationSection("powertools").getValues(false); - if (powertools == null) - { - continue; - } - for (Map.Entry entry : powertools.entrySet()) - { - if (entry.getValue() instanceof String) - { - List temp = new ArrayList(); - temp.add((String)entry.getValue()); - ((Map)powertools).put(entry.getKey(), temp); - } - } - config.forceSave(); - } - } - catch (RuntimeException ex) - { - LOGGER.log(Level.INFO, "File: " + file.toString()); - throw ex; - } - } - doneFile.setProperty("updateUsersPowerToolsFormat", true); - doneFile.save(); - } - - private void updateUsersHomesFormat() - { - if (doneFile.getBoolean("updateUsersHomesFormat", false)) - { - return; - } - final File userdataFolder = new File(ess.getDataFolder(), "userdata"); - if (!userdataFolder.exists() || !userdataFolder.isDirectory()) - { - return; - } - final File[] userFiles = userdataFolder.listFiles(); - - for (File file : userFiles) - { - if (!file.isFile() || !file.getName().endsWith(".yml")) - { - continue; - } - final EssentialsConf config = new EssentialsConf(file); - try - { - - config.load(); - if (config.hasProperty("home") && config.hasProperty("home.default")) - { - @SuppressWarnings("unchecked") - final String defworld = (String)config.getProperty("home.default"); - final Location defloc = getFakeLocation(config, "home.worlds." + defworld); - if (defloc != null) - { - config.setProperty("homes.home", defloc); - } - - Set worlds = config.getConfigurationSection("home.worlds").getKeys(false); - Location loc; - String worldName; - - if (worlds == null) - { - continue; - } - for (String world : worlds) - { - if (defworld.equalsIgnoreCase(world)) - { - continue; - } - loc = getFakeLocation(config, "home.worlds." + world); - if (loc == null) - { - continue; - } - worldName = loc.getWorld().getName().toLowerCase(Locale.ENGLISH); - if (worldName != null && !worldName.isEmpty()) - { - config.setProperty("homes." + worldName, loc); - } - } - config.removeProperty("home"); - config.forceSave(); - } - - } - catch (RuntimeException ex) - { - LOGGER.log(Level.INFO, "File: " + file.toString()); - throw ex; - } - } - doneFile.setProperty("updateUsersHomesFormat", true); - doneFile.save(); - } - - private void sanitizeAllUserFilenames() - { - if (doneFile.getBoolean("sanitizeAllUserFilenames", false)) - { - return; - } - final File usersFolder = new File(ess.getDataFolder(), "userdata"); - if (!usersFolder.exists()) - { - return; - } - final File[] listOfFiles = usersFolder.listFiles(); - for (File listOfFile : listOfFiles) - { - final String filename = listOfFile.getName(); - if (!listOfFile.isFile() || !filename.endsWith(".yml")) - { - continue; - } - final String sanitizedFilename = StringUtil.sanitizeFileName(filename.substring(0, filename.length() - 4)) + ".yml"; - if (sanitizedFilename.equals(filename)) - { - continue; - } - final File tmpFile = new File(listOfFile.getParentFile(), sanitizedFilename + ".tmp"); - final File newFile = new File(listOfFile.getParentFile(), sanitizedFilename); - if (!listOfFile.renameTo(tmpFile)) - { - LOGGER.log(Level.WARNING, tl("userdataMoveError", filename, sanitizedFilename)); - continue; - } - if (newFile.exists()) - { - LOGGER.log(Level.WARNING, tl("duplicatedUserdata", filename, sanitizedFilename)); - continue; - } - if (!tmpFile.renameTo(newFile)) - { - LOGGER.log(Level.WARNING, tl("userdataMoveBackError", sanitizedFilename, sanitizedFilename)); - } - } - doneFile.setProperty("sanitizeAllUserFilenames", true); - doneFile.save(); - } - - private World getFakeWorld(final String name) - { - final File bukkitDirectory = ess.getDataFolder().getParentFile().getParentFile(); - final File worldDirectory = new File(bukkitDirectory, name); - if (worldDirectory.exists() && worldDirectory.isDirectory()) - { - return new FakeWorld(worldDirectory.getName(), World.Environment.NORMAL); - } - return null; - } - - public Location getFakeLocation(EssentialsConf config, String path) - { - String worldName = config.getString((path != null ? path + "." : "") + "world"); - if (worldName == null || worldName.isEmpty()) - { - return null; - } - World world = getFakeWorld(worldName); - if (world == null) - { - return null; - } - return new Location(world, - config.getDouble((path != null ? path + "." : "") + "x", 0), - config.getDouble((path != null ? path + "." : "") + "y", 0), - config.getDouble((path != null ? path + "." : "") + "z", 0), - (float)config.getDouble((path != null ? path + "." : "") + "yaw", 0), - (float)config.getDouble((path != null ? path + "." : "") + "pitch", 0)); - } - - private void deleteOldItemsCsv() - { - if (doneFile.getBoolean("deleteOldItemsCsv", false)) - { - return; - } - final File file = new File(ess.getDataFolder(), "items.csv"); - if (file.exists()) - { - try - { - final Set oldconfigs = new HashSet(); - oldconfigs.add(new BigInteger("66ec40b09ac167079f558d1099e39f10", 16)); // sep 1 - oldconfigs.add(new BigInteger("34284de1ead43b0bee2aae85e75c041d", 16)); // crlf - oldconfigs.add(new BigInteger("c33bc9b8ee003861611bbc2f48eb6f4f", 16)); // jul 24 - oldconfigs.add(new BigInteger("6ff17925430735129fc2a02f830c1daa", 16)); // crlf - - MessageDigest digest = ManagedFile.getDigest(); - final BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); - final DigestInputStream dis = new DigestInputStream(bis, digest); - final byte[] buffer = new byte[1024]; - try - { - while (dis.read(buffer) != -1) - { - } - } - finally - { - dis.close(); - } - - BigInteger hash = new BigInteger(1, digest.digest()); - if (oldconfigs.contains(hash) && !file.delete()) - { - throw new IOException("Could not delete file " + file.toString()); - } - doneFile.setProperty("deleteOldItemsCsv", true); - doneFile.save(); - } - catch (IOException ex) - { - Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); - } - } - } - - private void updateSpawnsToNewSpawnsConfig() - { - if (doneFile.getBoolean("updateSpawnsToNewSpawnsConfig", false)) - { - return; - } - final File configFile = new File(ess.getDataFolder(), "spawn.yml"); - if (configFile.exists()) - { - - final EssentialsConf config = new EssentialsConf(configFile); - try - { - config.load(); - if (!config.hasProperty("spawns")) - { - final Spawns spawns = new Spawns(); - Set keys = config.getKeys(false); - for (String group : keys) - { - Location loc = getFakeLocation(config, group); - spawns.getSpawns().put(group.toLowerCase(Locale.ENGLISH), loc); - } - if (!configFile.renameTo(new File(ess.getDataFolder(), "spawn.yml.old"))) - { - throw new Exception(tl("fileRenameError", "spawn.yml")); - } - PrintWriter writer = new PrintWriter(configFile); - try - { - new YamlStorageWriter(writer).save(spawns); - } - finally - { - writer.close(); - } - } - } - catch (Exception ex) - { - Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); - } - } - doneFile.setProperty("updateSpawnsToNewSpawnsConfig", true); - doneFile.save(); - } - - private void updateJailsToNewJailsConfig() - { - if (doneFile.getBoolean("updateJailsToNewJailsConfig", false)) - { - return; - } - final File configFile = new File(ess.getDataFolder(), "jail.yml"); - if (configFile.exists()) - { - - final EssentialsConf config = new EssentialsConf(configFile); - try - { - config.load(); - if (!config.hasProperty("jails")) - { - final com.earth2me.essentials.settings.Jails jails = new com.earth2me.essentials.settings.Jails(); - Set keys = config.getKeys(false); - for (String jailName : keys) - { - Location loc = getFakeLocation(config, jailName); - jails.getJails().put(jailName.toLowerCase(Locale.ENGLISH), loc); - } - if (!configFile.renameTo(new File(ess.getDataFolder(), "jail.yml.old"))) - { - throw new Exception(tl("fileRenameError", "jail.yml")); - } - PrintWriter writer = new PrintWriter(configFile); - try - { - new YamlStorageWriter(writer).save(jails); - } - finally - { - writer.close(); - } - } - } - catch (Exception ex) - { - Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); - } - } - doneFile.setProperty("updateJailsToNewJailsConfig", true); - doneFile.save(); - } - - private void warnMetrics() - { - if (doneFile.getBoolean("warnMetrics", false)) - { - return; - } - ess.getSettings().setMetricsEnabled(false); - doneFile.setProperty("warnMetrics", true); - doneFile.save(); - } - - private void uuidFileChange() - { - if (doneFile.getBoolean("uuidFileChange", false)) - { - return; - } - - Boolean ignoreUFCache = doneFile.getBoolean("ignore-userfiles-cache", false); - - final File userdir = new File(ess.getDataFolder(), "userdata"); - if (!userdir.exists()) - { - return; - } - - int countFiles = 0; - int countReqFiles = 0; - for (String string : userdir.list()) - { - if (!string.endsWith(".yml") || string.length() < 5) - { - continue; - } - - countFiles++; - - final String name = string.substring(0, string.length() - 4); - UUID uuid = null; - - try - { - uuid = UUID.fromString(name); - } - catch (IllegalArgumentException ex) - { - countReqFiles++; - } - - if (countFiles > 100) - { - break; - } - } - - if (countReqFiles < 1) - { - return; - } - - ess.getLogger().info("#### Starting Essentials UUID userdata conversion in a few seconds. ####"); - ess.getLogger().info("We recommend you take a backup of your server before upgrading from the old username system."); - - try - { - Thread.sleep(15000); - } - catch (InterruptedException ex) - { - // NOOP - } - - uuidFileConvert(ess, ignoreUFCache); - - doneFile.setProperty("uuidFileChange", true); - doneFile.save(); - } - - public static void uuidFileConvert(IEssentials ess, Boolean ignoreUFCache) - { - ess.getLogger().info("Starting Essentials UUID userdata conversion"); - - final File userdir = new File(ess.getDataFolder(), "userdata"); - if (!userdir.exists()) - { - return; - } - - int countFiles = 0; - int countFails = 0; - int countEssCache = 0; - int countBukkit = 0; - - ess.getLogger().info("Found " + userdir.list().length + " files to convert..."); - - for (String string : userdir.list()) - { - if (!string.endsWith(".yml") || string.length() < 5) - { - continue; - } - - final int showProgress = countFiles % 250; - - if (showProgress == 0) - { - ess.getUserMap().getUUIDMap().forceWriteUUIDMap(); - ess.getLogger().info("Converted " + countFiles + "/" + userdir.list().length); - } - - countFiles++; - - String name = string.substring(0, string.length() - 4); - EssentialsUserConf config; - UUID uuid = null; - try - { - uuid = UUID.fromString(name); - } - catch (IllegalArgumentException ex) - { - File file = new File(userdir, string); - EssentialsConf conf = new EssentialsConf(file); - conf.load(); - conf.setProperty("lastAccountName", name); - conf.save(); - - String uuidConf = ignoreUFCache ? "force-uuid" : "uuid"; - - String uuidString = conf.getString(uuidConf, null); - - for (int i = 0; i < 4; i++) - { - try - { - uuid = UUID.fromString(uuidString); - countEssCache++; - break; - } - catch (Exception ex2) - { - if (conf.getBoolean("npc", false)) - { - uuid = UUID.nameUUIDFromBytes(("NPC:" + name).getBytes(Charsets.UTF_8)); - break; - } - - org.bukkit.OfflinePlayer player = ess.getServer().getOfflinePlayer(name); - uuid = player.getUniqueId(); - } - - if (uuid != null) - { - countBukkit++; - break; - } - } - - if (uuid != null) - { - conf.forceSave(); - config = new EssentialsUserConf(name, uuid, new File(userdir, uuid + ".yml")); - config.convertLegacyFile(); - ess.getUserMap().trackUUID(uuid, name, false); - continue; - } - countFails++; - } - } - ess.getUserMap().getUUIDMap().forceWriteUUIDMap(); - - ess.getLogger().info("Converted " + countFiles + "/" + countFiles + ". Conversion complete."); - ess.getLogger().info("Converted via cache: " + countEssCache + " :: Converted via lookup: " + countBukkit + " :: Failed to convert: " + countFails); - ess.getLogger().info("To rerun the conversion type /essentials uuidconvert"); - } - - public void banFormatChange() - { - if (doneFile.getBoolean("banFormatChange", false)) - { - return; - } - - ess.getLogger().info("Starting Essentials ban format conversion"); - - final File userdir = new File(ess.getDataFolder(), "userdata"); - if (!userdir.exists()) - { - return; - } - - int countFiles = 0; - - ess.getLogger().info("Found " + userdir.list().length + " files to convert..."); - - for (String string : userdir.list()) - { - if (!string.endsWith(".yml") || string.length() < 5) - { - continue; - } - - final int showProgress = countFiles % 250; - - if (showProgress == 0) - { - ess.getLogger().info("Converted " + countFiles + "/" + userdir.list().length); - } - - countFiles++; - final File pFile = new File(userdir, string); - final EssentialsConf conf = new EssentialsConf(pFile); - conf.load(); - - String banReason; - Long banTimeout; - - try - { - banReason = conf.getConfigurationSection("ban").getString("reason"); - } - catch (NullPointerException n) - { - banReason = null; - } - - final String playerName = conf.getString("lastAccountName"); - if (playerName != null && playerName.length() > 1 && banReason != null && banReason.length() > 1) - { - try - { - if (conf.getConfigurationSection("ban").contains("timeout")) - { - banTimeout = Long.parseLong(conf.getConfigurationSection("ban").getString("timeout")); - } - else - { - banTimeout = 0L; - } - } - catch (NumberFormatException n) - { - banTimeout = 0L; - } - - if (BanLookup.isBanned(ess, playerName)) - { - updateBan(playerName, banReason, banTimeout); - } - } - conf.removeProperty("ban"); - conf.save(); - } - - doneFile.setProperty("banFormatChange", true); - doneFile.save(); - ess.getLogger().info("Ban format update complete."); - } - - private void updateBan(String playerName, String banReason, Long banTimeout) - { - if (banTimeout == 0) - { - Bukkit.getBanList(BanList.Type.NAME).addBan(playerName, banReason, null, Console.NAME); - } - else - { - Bukkit.getBanList(BanList.Type.NAME).addBan(playerName, banReason, new Date(banTimeout), Console.NAME); - } - } - - public void beforeSettings() - { - if (!ess.getDataFolder().exists()) - { - ess.getDataFolder().mkdirs(); - } - moveMotdRulesToFile("motd"); - moveMotdRulesToFile("rules"); - } - - public void afterSettings() - { - sanitizeAllUserFilenames(); - updateUsersPowerToolsFormat(); - updateUsersHomesFormat(); - deleteOldItemsCsv(); - updateSpawnsToNewSpawnsConfig(); - updateJailsToNewJailsConfig(); - uuidFileChange(); - banFormatChange(); - warnMetrics(); - } + +import static com.earth2me.essentials.I18n.tl; + + +public class EssentialsUpgrade { + private final static Logger LOGGER = Logger.getLogger("Essentials"); + private final transient IEssentials ess; + private final transient EssentialsConf doneFile; + + EssentialsUpgrade(final IEssentials essentials) { + ess = essentials; + if (!ess.getDataFolder().exists()) { + ess.getDataFolder().mkdirs(); + } + doneFile = new EssentialsConf(new File(ess.getDataFolder(), "upgrades-done.yml")); + doneFile.load(); + } + + private void moveMotdRulesToFile(String name) { + if (doneFile.getBoolean("move" + name + "ToFile", false)) { + return; + } + try { + final File file = new File(ess.getDataFolder(), name + ".txt"); + if (file.exists()) { + return; + } + final File configFile = new File(ess.getDataFolder(), "config.yml"); + if (!configFile.exists()) { + return; + } + final EssentialsConf conf = new EssentialsConf(configFile); + conf.load(); + List lines = conf.getStringList(name); + if (lines != null && !lines.isEmpty()) { + if (!file.createNewFile()) { + throw new IOException("Failed to create file " + file); + } + PrintWriter writer = new PrintWriter(file); + + for (String line : lines) { + writer.println(line); + } + writer.close(); + } + doneFile.setProperty("move" + name + "ToFile", true); + doneFile.save(); + } catch (IOException e) { + LOGGER.log(Level.SEVERE, tl("upgradingFilesError"), e); + } + } + + private void removeLinesFromConfig(File file, String regex, String info) throws Exception { + boolean needUpdate = false; + final BufferedReader bReader = new BufferedReader(new FileReader(file)); + final File tempFile = File.createTempFile("essentialsupgrade", ".tmp.yml", ess.getDataFolder()); + final BufferedWriter bWriter = new BufferedWriter(new FileWriter(tempFile)); + do { + final String line = bReader.readLine(); + if (line == null) { + break; + } + if (line.matches(regex)) { + if (!needUpdate && info != null) { + bWriter.write(info, 0, info.length()); + bWriter.newLine(); + } + needUpdate = true; + } else { + if (line.endsWith("\r\n")) { + bWriter.write(line, 0, line.length() - 2); + } else if (line.endsWith("\r") || line.endsWith("\n")) { + bWriter.write(line, 0, line.length() - 1); + } else { + bWriter.write(line, 0, line.length()); + } + bWriter.newLine(); + } + } while (true); + bReader.close(); + bWriter.close(); + if (needUpdate) { + if (!file.renameTo(new File(file.getParentFile(), file.getName().concat("." + System.currentTimeMillis() + ".upgradebackup")))) { + throw new Exception(tl("configFileMoveError")); + } + if (!tempFile.renameTo(file)) { + throw new Exception(tl("configFileRenameError")); + } + } else { + tempFile.delete(); + } + } + + private void updateUsersPowerToolsFormat() { + if (doneFile.getBoolean("updateUsersPowerToolsFormat", false)) { + return; + } + final File userdataFolder = new File(ess.getDataFolder(), "userdata"); + if (!userdataFolder.exists() || !userdataFolder.isDirectory()) { + return; + } + final File[] userFiles = userdataFolder.listFiles(); + + for (File file : userFiles) { + if (!file.isFile() || !file.getName().endsWith(".yml")) { + continue; + } + final EssentialsConf config = new EssentialsConf(file); + try { + config.load(); + if (config.hasProperty("powertools")) { + @SuppressWarnings("unchecked") final Map powertools = config.getConfigurationSection("powertools").getValues(false); + if (powertools == null) { + continue; + } + for (Map.Entry entry : powertools.entrySet()) { + if (entry.getValue() instanceof String) { + List temp = new ArrayList(); + temp.add((String) entry.getValue()); + ((Map) powertools).put(entry.getKey(), temp); + } + } + config.forceSave(); + } + } catch (RuntimeException ex) { + LOGGER.log(Level.INFO, "File: " + file.toString()); + throw ex; + } + } + doneFile.setProperty("updateUsersPowerToolsFormat", true); + doneFile.save(); + } + + private void updateUsersHomesFormat() { + if (doneFile.getBoolean("updateUsersHomesFormat", false)) { + return; + } + final File userdataFolder = new File(ess.getDataFolder(), "userdata"); + if (!userdataFolder.exists() || !userdataFolder.isDirectory()) { + return; + } + final File[] userFiles = userdataFolder.listFiles(); + + for (File file : userFiles) { + if (!file.isFile() || !file.getName().endsWith(".yml")) { + continue; + } + final EssentialsConf config = new EssentialsConf(file); + try { + + config.load(); + if (config.hasProperty("home") && config.hasProperty("home.default")) { + @SuppressWarnings("unchecked") final String defworld = (String) config.getProperty("home.default"); + final Location defloc = getFakeLocation(config, "home.worlds." + defworld); + if (defloc != null) { + config.setProperty("homes.home", defloc); + } + + Set worlds = config.getConfigurationSection("home.worlds").getKeys(false); + Location loc; + String worldName; + + if (worlds == null) { + continue; + } + for (String world : worlds) { + if (defworld.equalsIgnoreCase(world)) { + continue; + } + loc = getFakeLocation(config, "home.worlds." + world); + if (loc == null) { + continue; + } + worldName = loc.getWorld().getName().toLowerCase(Locale.ENGLISH); + if (worldName != null && !worldName.isEmpty()) { + config.setProperty("homes." + worldName, loc); + } + } + config.removeProperty("home"); + config.forceSave(); + } + + } catch (RuntimeException ex) { + LOGGER.log(Level.INFO, "File: " + file.toString()); + throw ex; + } + } + doneFile.setProperty("updateUsersHomesFormat", true); + doneFile.save(); + } + + private void sanitizeAllUserFilenames() { + if (doneFile.getBoolean("sanitizeAllUserFilenames", false)) { + return; + } + final File usersFolder = new File(ess.getDataFolder(), "userdata"); + if (!usersFolder.exists()) { + return; + } + final File[] listOfFiles = usersFolder.listFiles(); + for (File listOfFile : listOfFiles) { + final String filename = listOfFile.getName(); + if (!listOfFile.isFile() || !filename.endsWith(".yml")) { + continue; + } + final String sanitizedFilename = StringUtil.sanitizeFileName(filename.substring(0, filename.length() - 4)) + ".yml"; + if (sanitizedFilename.equals(filename)) { + continue; + } + final File tmpFile = new File(listOfFile.getParentFile(), sanitizedFilename + ".tmp"); + final File newFile = new File(listOfFile.getParentFile(), sanitizedFilename); + if (!listOfFile.renameTo(tmpFile)) { + LOGGER.log(Level.WARNING, tl("userdataMoveError", filename, sanitizedFilename)); + continue; + } + if (newFile.exists()) { + LOGGER.log(Level.WARNING, tl("duplicatedUserdata", filename, sanitizedFilename)); + continue; + } + if (!tmpFile.renameTo(newFile)) { + LOGGER.log(Level.WARNING, tl("userdataMoveBackError", sanitizedFilename, sanitizedFilename)); + } + } + doneFile.setProperty("sanitizeAllUserFilenames", true); + doneFile.save(); + } + + private World getFakeWorld(final String name) { + final File bukkitDirectory = ess.getDataFolder().getParentFile().getParentFile(); + final File worldDirectory = new File(bukkitDirectory, name); + if (worldDirectory.exists() && worldDirectory.isDirectory()) { + return new FakeWorld(worldDirectory.getName(), World.Environment.NORMAL); + } + return null; + } + + public Location getFakeLocation(EssentialsConf config, String path) { + String worldName = config.getString((path != null ? path + "." : "") + "world"); + if (worldName == null || worldName.isEmpty()) { + return null; + } + World world = getFakeWorld(worldName); + if (world == null) { + return null; + } + return new Location(world, config.getDouble((path != null ? path + "." : "") + "x", 0), config.getDouble((path != null ? path + "." : "") + "y", 0), config.getDouble((path != null ? path + "." : "") + "z", 0), (float) config.getDouble((path != null ? path + "." : "") + "yaw", 0), (float) config.getDouble((path != null ? path + "." : "") + "pitch", 0)); + } + + private void deleteOldItemsCsv() { + if (doneFile.getBoolean("deleteOldItemsCsv", false)) { + return; + } + final File file = new File(ess.getDataFolder(), "items.csv"); + if (file.exists()) { + try { + final Set oldconfigs = new HashSet(); + oldconfigs.add(new BigInteger("66ec40b09ac167079f558d1099e39f10", 16)); // sep 1 + oldconfigs.add(new BigInteger("34284de1ead43b0bee2aae85e75c041d", 16)); // crlf + oldconfigs.add(new BigInteger("c33bc9b8ee003861611bbc2f48eb6f4f", 16)); // jul 24 + oldconfigs.add(new BigInteger("6ff17925430735129fc2a02f830c1daa", 16)); // crlf + + MessageDigest digest = ManagedFile.getDigest(); + final BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); + final DigestInputStream dis = new DigestInputStream(bis, digest); + final byte[] buffer = new byte[1024]; + try { + while (dis.read(buffer) != -1) { + } + } finally { + dis.close(); + } + + BigInteger hash = new BigInteger(1, digest.digest()); + if (oldconfigs.contains(hash) && !file.delete()) { + throw new IOException("Could not delete file " + file.toString()); + } + doneFile.setProperty("deleteOldItemsCsv", true); + doneFile.save(); + } catch (IOException ex) { + Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); + } + } + } + + private void updateSpawnsToNewSpawnsConfig() { + if (doneFile.getBoolean("updateSpawnsToNewSpawnsConfig", false)) { + return; + } + final File configFile = new File(ess.getDataFolder(), "spawn.yml"); + if (configFile.exists()) { + + final EssentialsConf config = new EssentialsConf(configFile); + try { + config.load(); + if (!config.hasProperty("spawns")) { + final Spawns spawns = new Spawns(); + Set keys = config.getKeys(false); + for (String group : keys) { + Location loc = getFakeLocation(config, group); + spawns.getSpawns().put(group.toLowerCase(Locale.ENGLISH), loc); + } + if (!configFile.renameTo(new File(ess.getDataFolder(), "spawn.yml.old"))) { + throw new Exception(tl("fileRenameError", "spawn.yml")); + } + PrintWriter writer = new PrintWriter(configFile); + try { + new YamlStorageWriter(writer).save(spawns); + } finally { + writer.close(); + } + } + } catch (Exception ex) { + Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); + } + } + doneFile.setProperty("updateSpawnsToNewSpawnsConfig", true); + doneFile.save(); + } + + private void updateJailsToNewJailsConfig() { + if (doneFile.getBoolean("updateJailsToNewJailsConfig", false)) { + return; + } + final File configFile = new File(ess.getDataFolder(), "jail.yml"); + if (configFile.exists()) { + + final EssentialsConf config = new EssentialsConf(configFile); + try { + config.load(); + if (!config.hasProperty("jails")) { + final com.earth2me.essentials.settings.Jails jails = new com.earth2me.essentials.settings.Jails(); + Set keys = config.getKeys(false); + for (String jailName : keys) { + Location loc = getFakeLocation(config, jailName); + jails.getJails().put(jailName.toLowerCase(Locale.ENGLISH), loc); + } + if (!configFile.renameTo(new File(ess.getDataFolder(), "jail.yml.old"))) { + throw new Exception(tl("fileRenameError", "jail.yml")); + } + PrintWriter writer = new PrintWriter(configFile); + try { + new YamlStorageWriter(writer).save(jails); + } finally { + writer.close(); + } + } + } catch (Exception ex) { + Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); + } + } + doneFile.setProperty("updateJailsToNewJailsConfig", true); + doneFile.save(); + } + + private void warnMetrics() { + if (doneFile.getBoolean("warnMetrics", false)) { + return; + } + ess.getSettings().setMetricsEnabled(false); + doneFile.setProperty("warnMetrics", true); + doneFile.save(); + } + + private void uuidFileChange() { + if (doneFile.getBoolean("uuidFileChange", false)) { + return; + } + + Boolean ignoreUFCache = doneFile.getBoolean("ignore-userfiles-cache", false); + + final File userdir = new File(ess.getDataFolder(), "userdata"); + if (!userdir.exists()) { + return; + } + + int countFiles = 0; + int countReqFiles = 0; + for (String string : userdir.list()) { + if (!string.endsWith(".yml") || string.length() < 5) { + continue; + } + + countFiles++; + + final String name = string.substring(0, string.length() - 4); + UUID uuid = null; + + try { + uuid = UUID.fromString(name); + } catch (IllegalArgumentException ex) { + countReqFiles++; + } + + if (countFiles > 100) { + break; + } + } + + if (countReqFiles < 1) { + return; + } + + ess.getLogger().info("#### Starting Essentials UUID userdata conversion in a few seconds. ####"); + ess.getLogger().info("We recommend you take a backup of your server before upgrading from the old username system."); + + try { + Thread.sleep(15000); + } catch (InterruptedException ex) { + // NOOP + } + + uuidFileConvert(ess, ignoreUFCache); + + doneFile.setProperty("uuidFileChange", true); + doneFile.save(); + } + + public static void uuidFileConvert(IEssentials ess, Boolean ignoreUFCache) { + ess.getLogger().info("Starting Essentials UUID userdata conversion"); + + final File userdir = new File(ess.getDataFolder(), "userdata"); + if (!userdir.exists()) { + return; + } + + int countFiles = 0; + int countFails = 0; + int countEssCache = 0; + int countBukkit = 0; + + ess.getLogger().info("Found " + userdir.list().length + " files to convert..."); + + for (String string : userdir.list()) { + if (!string.endsWith(".yml") || string.length() < 5) { + continue; + } + + final int showProgress = countFiles % 250; + + if (showProgress == 0) { + ess.getUserMap().getUUIDMap().forceWriteUUIDMap(); + ess.getLogger().info("Converted " + countFiles + "/" + userdir.list().length); + } + + countFiles++; + + String name = string.substring(0, string.length() - 4); + EssentialsUserConf config; + UUID uuid = null; + try { + uuid = UUID.fromString(name); + } catch (IllegalArgumentException ex) { + File file = new File(userdir, string); + EssentialsConf conf = new EssentialsConf(file); + conf.load(); + conf.setProperty("lastAccountName", name); + conf.save(); + + String uuidConf = ignoreUFCache ? "force-uuid" : "uuid"; + + String uuidString = conf.getString(uuidConf, null); + + for (int i = 0; i < 4; i++) { + try { + uuid = UUID.fromString(uuidString); + countEssCache++; + break; + } catch (Exception ex2) { + if (conf.getBoolean("npc", false)) { + uuid = UUID.nameUUIDFromBytes(("NPC:" + name).getBytes(Charsets.UTF_8)); + break; + } + + org.bukkit.OfflinePlayer player = ess.getServer().getOfflinePlayer(name); + uuid = player.getUniqueId(); + } + + if (uuid != null) { + countBukkit++; + break; + } + } + + if (uuid != null) { + conf.forceSave(); + config = new EssentialsUserConf(name, uuid, new File(userdir, uuid + ".yml")); + config.convertLegacyFile(); + ess.getUserMap().trackUUID(uuid, name, false); + continue; + } + countFails++; + } + } + ess.getUserMap().getUUIDMap().forceWriteUUIDMap(); + + ess.getLogger().info("Converted " + countFiles + "/" + countFiles + ". Conversion complete."); + ess.getLogger().info("Converted via cache: " + countEssCache + " :: Converted via lookup: " + countBukkit + " :: Failed to convert: " + countFails); + ess.getLogger().info("To rerun the conversion type /essentials uuidconvert"); + } + + public void banFormatChange() { + if (doneFile.getBoolean("banFormatChange", false)) { + return; + } + + ess.getLogger().info("Starting Essentials ban format conversion"); + + final File userdir = new File(ess.getDataFolder(), "userdata"); + if (!userdir.exists()) { + return; + } + + int countFiles = 0; + + ess.getLogger().info("Found " + userdir.list().length + " files to convert..."); + + for (String string : userdir.list()) { + if (!string.endsWith(".yml") || string.length() < 5) { + continue; + } + + final int showProgress = countFiles % 250; + + if (showProgress == 0) { + ess.getLogger().info("Converted " + countFiles + "/" + userdir.list().length); + } + + countFiles++; + final File pFile = new File(userdir, string); + final EssentialsConf conf = new EssentialsConf(pFile); + conf.load(); + + String banReason; + Long banTimeout; + + try { + banReason = conf.getConfigurationSection("ban").getString("reason"); + } catch (NullPointerException n) { + banReason = null; + } + + final String playerName = conf.getString("lastAccountName"); + if (playerName != null && playerName.length() > 1 && banReason != null && banReason.length() > 1) { + try { + if (conf.getConfigurationSection("ban").contains("timeout")) { + banTimeout = Long.parseLong(conf.getConfigurationSection("ban").getString("timeout")); + } else { + banTimeout = 0L; + } + } catch (NumberFormatException n) { + banTimeout = 0L; + } + + if (BanLookup.isBanned(ess, playerName)) { + updateBan(playerName, banReason, banTimeout); + } + } + conf.removeProperty("ban"); + conf.save(); + } + + doneFile.setProperty("banFormatChange", true); + doneFile.save(); + ess.getLogger().info("Ban format update complete."); + } + + private void updateBan(String playerName, String banReason, Long banTimeout) { + if (banTimeout == 0) { + Bukkit.getBanList(BanList.Type.NAME).addBan(playerName, banReason, null, Console.NAME); + } else { + Bukkit.getBanList(BanList.Type.NAME).addBan(playerName, banReason, new Date(banTimeout), Console.NAME); + } + } + + public void beforeSettings() { + if (!ess.getDataFolder().exists()) { + ess.getDataFolder().mkdirs(); + } + moveMotdRulesToFile("motd"); + moveMotdRulesToFile("rules"); + } + + public void afterSettings() { + sanitizeAllUserFilenames(); + updateUsersPowerToolsFormat(); + updateUsersHomesFormat(); + deleteOldItemsCsv(); + updateSpawnsToNewSpawnsConfig(); + updateJailsToNewJailsConfig(); + uuidFileChange(); + banFormatChange(); + warnMetrics(); + } } diff --git a/Essentials/src/com/earth2me/essentials/EssentialsUserConf.java b/Essentials/src/com/earth2me/essentials/EssentialsUserConf.java index cbfba46b1..b1539b3b4 100644 --- a/Essentials/src/com/earth2me/essentials/EssentialsUserConf.java +++ b/Essentials/src/com/earth2me/essentials/EssentialsUserConf.java @@ -2,75 +2,62 @@ package com.earth2me.essentials; import com.google.common.base.Charsets; import com.google.common.io.Files; +import org.bukkit.Bukkit; + import java.io.File; import java.io.IOException; import java.util.Locale; import java.util.UUID; import java.util.logging.Level; -import org.bukkit.Bukkit; -public class EssentialsUserConf extends EssentialsConf -{ - public final String username; - public final UUID uuid; +public class EssentialsUserConf extends EssentialsConf { + public final String username; + public final UUID uuid; - public EssentialsUserConf(final String username, final UUID uuid, final File configFile) - { - super(configFile); - this.username = username; - this.uuid = uuid; - } + public EssentialsUserConf(final String username, final UUID uuid, final File configFile) { + super(configFile); + this.username = username; + this.uuid = uuid; + } - @Override - public boolean legacyFileExists() - { - final File file = new File(configFile.getParentFile(), username + ".yml"); - return file.exists(); - } + @Override + public boolean legacyFileExists() { + final File file = new File(configFile.getParentFile(), username + ".yml"); + return file.exists(); + } - @Override - public void convertLegacyFile() - { - final File file = new File(configFile.getParentFile(), username + ".yml"); - try - { - Files.move(file, new File(configFile.getParentFile(), uuid + ".yml")); - } - catch (IOException ex) - { - Bukkit.getLogger().log(Level.WARNING, "Failed to migrate user: " + username, ex); - } + @Override + public void convertLegacyFile() { + final File file = new File(configFile.getParentFile(), username + ".yml"); + try { + Files.move(file, new File(configFile.getParentFile(), uuid + ".yml")); + } catch (IOException ex) { + Bukkit.getLogger().log(Level.WARNING, "Failed to migrate user: " + username, ex); + } - setProperty("lastAccountName", username); - } + setProperty("lastAccountName", username); + } - private File getAltFile() - { - final UUID fn = UUID.nameUUIDFromBytes(("OfflinePlayer:" + username.toLowerCase(Locale.ENGLISH)).getBytes(Charsets.UTF_8)); - return new File(configFile.getParentFile(), fn.toString() + ".yml"); - } + private File getAltFile() { + final UUID fn = UUID.nameUUIDFromBytes(("OfflinePlayer:" + username.toLowerCase(Locale.ENGLISH)).getBytes(Charsets.UTF_8)); + return new File(configFile.getParentFile(), fn.toString() + ".yml"); + } - @Override - public boolean altFileExists() - { - if (username.equals(username.toLowerCase())) - { - return false; - } - return getAltFile().exists(); - } + @Override + public boolean altFileExists() { + if (username.equals(username.toLowerCase())) { + return false; + } + return getAltFile().exists(); + } - @Override - public void convertAltFile() - { - try - { - Files.move(getAltFile(), new File(configFile.getParentFile(), uuid + ".yml")); - } - catch (IOException ex) - { - Bukkit.getLogger().log(Level.WARNING, "Failed to migrate user: " + username, ex); - } - } + @Override + public void convertAltFile() { + try { + Files.move(getAltFile(), new File(configFile.getParentFile(), uuid + ".yml")); + } catch (IOException ex) { + Bukkit.getLogger().log(Level.WARNING, "Failed to migrate user: " + username, ex); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/ExecuteTimer.java b/Essentials/src/com/earth2me/essentials/ExecuteTimer.java index f9da468b5..65061697e 100644 --- a/Essentials/src/com/earth2me/essentials/ExecuteTimer.java +++ b/Essentials/src/com/earth2me/essentials/ExecuteTimer.java @@ -7,83 +7,69 @@ 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 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 ExecuteTimer() { + times = new ArrayList(); + } - public void start() - { - times.clear(); - mark("start"); + 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 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; + 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(); - } + 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(); + } - private static class ExecuteRecord - { - private final String mark; - private final long time; + private static 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 ExecuteRecord(final String mark, final long time) { + this.mark = mark; + this.time = time; + } - public String getMark() - { - return mark; - } + public String getMark() { + return mark; + } - public long getTime() - { - return time; - } - } + public long getTime() { + return time; + } + } } \ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/I18n.java b/Essentials/src/com/earth2me/essentials/I18n.java index 478b6b5d1..91d91583f 100644 --- a/Essentials/src/com/earth2me/essentials/I18n.java +++ b/Essentials/src/com/earth2me/essentials/I18n.java @@ -1,5 +1,7 @@ package com.earth2me.essentials; +import net.ess3.api.IEssentials; + import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; @@ -11,208 +13,154 @@ import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; -import net.ess3.api.IEssentials; -import org.bukkit.Bukkit; -public class I18n implements net.ess3.api.II18n -{ - private static I18n instance; - private static final String MESSAGES = "messages"; - private final transient Locale defaultLocale = Locale.getDefault(); - private transient Locale currentLocale = defaultLocale; - private transient ResourceBundle customBundle; - private transient ResourceBundle localeBundle; - private final transient ResourceBundle defaultBundle; - private transient Map messageFormatCache = new HashMap(); - private final transient IEssentials ess; - private static final Pattern NODOUBLEMARK = Pattern.compile("''"); - private static final ResourceBundle NULL_BUNDLE = new ResourceBundle() - { - public Enumeration getKeys() - { - return null; - } +public class I18n implements net.ess3.api.II18n { + private static I18n instance; + private static final String MESSAGES = "messages"; + private final transient Locale defaultLocale = Locale.getDefault(); + private transient Locale currentLocale = defaultLocale; + private transient ResourceBundle customBundle; + private transient ResourceBundle localeBundle; + private final transient ResourceBundle defaultBundle; + private transient Map messageFormatCache = new HashMap(); + private final transient IEssentials ess; + private static final Pattern NODOUBLEMARK = Pattern.compile("''"); + private static final ResourceBundle NULL_BUNDLE = new ResourceBundle() { + public Enumeration getKeys() { + return null; + } - protected Object handleGetObject(String key) - { - return null; - } - }; + protected Object handleGetObject(String key) { + return null; + } + }; - public I18n(final IEssentials ess) - { - this.ess = ess; - defaultBundle = ResourceBundle.getBundle(MESSAGES, Locale.ENGLISH); - localeBundle = defaultBundle; - customBundle = NULL_BUNDLE; - } + public I18n(final IEssentials ess) { + this.ess = ess; + defaultBundle = ResourceBundle.getBundle(MESSAGES, Locale.ENGLISH); + localeBundle = defaultBundle; + customBundle = NULL_BUNDLE; + } - public void onEnable() - { - instance = this; - } + public void onEnable() { + instance = this; + } - public void onDisable() - { - instance = null; - } + public void onDisable() { + instance = null; + } - @Override - public Locale getCurrentLocale() - { - return currentLocale; - } + @Override + public Locale getCurrentLocale() { + return currentLocale; + } - private String translate(final String string) - { - try - { - try - { - return customBundle.getString(string); - } - catch (MissingResourceException ex) - { - return localeBundle.getString(string); - } - } - catch (MissingResourceException ex) - { - Logger.getLogger("Essentials").log(Level.WARNING, String.format("Missing translation key \"%s\" in translation file %s", ex.getKey(), localeBundle.getLocale().toString()), ex); - return defaultBundle.getString(string); - } - } + private String translate(final String string) { + try { + try { + return customBundle.getString(string); + } catch (MissingResourceException ex) { + return localeBundle.getString(string); + } + } catch (MissingResourceException ex) { + Logger.getLogger("Essentials").log(Level.WARNING, String.format("Missing translation key \"%s\" in translation file %s", ex.getKey(), localeBundle.getLocale().toString()), ex); + return defaultBundle.getString(string); + } + } - public static String tl(final String string, final Object... objects) - { - if (instance == null) - { - return ""; - } - if (objects.length == 0) - { - return NODOUBLEMARK.matcher(instance.translate(string)).replaceAll("'"); - } - else - { - return instance.format(string, objects); - } - } + public static String tl(final String string, final Object... objects) { + if (instance == null) { + return ""; + } + if (objects.length == 0) { + return NODOUBLEMARK.matcher(instance.translate(string)).replaceAll("'"); + } else { + return instance.format(string, objects); + } + } - public String format(final String string, final Object... objects) - { - String format = translate(string); - MessageFormat messageFormat = messageFormatCache.get(format); - if (messageFormat == null) - { - try - { - messageFormat = new MessageFormat(format); - } - catch (IllegalArgumentException e) - { - ess.getLogger().log(Level.SEVERE, "Invalid Translation key for '" + string + "': " + e.getMessage()); - format = format.replaceAll("\\{(\\D*?)\\}", "\\[$1\\]"); - messageFormat = new MessageFormat(format); - } - messageFormatCache.put(format, messageFormat); - } - return messageFormat.format(objects); - } + public String format(final String string, final Object... objects) { + String format = translate(string); + MessageFormat messageFormat = messageFormatCache.get(format); + if (messageFormat == null) { + try { + messageFormat = new MessageFormat(format); + } catch (IllegalArgumentException e) { + ess.getLogger().log(Level.SEVERE, "Invalid Translation key for '" + string + "': " + e.getMessage()); + format = format.replaceAll("\\{(\\D*?)\\}", "\\[$1\\]"); + messageFormat = new MessageFormat(format); + } + messageFormatCache.put(format, messageFormat); + } + return messageFormat.format(objects); + } - public void updateLocale(final String loc) - { - if (loc != null && !loc.isEmpty()) - { - 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(); - messageFormatCache = new HashMap(); - Logger.getLogger("Essentials").log(Level.INFO, String.format("Using locale %s", currentLocale.toString())); + public void updateLocale(final String loc) { + if (loc != null && !loc.isEmpty()) { + 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(); + messageFormatCache = new HashMap(); + Logger.getLogger("Essentials").log(Level.INFO, String.format("Using locale %s", currentLocale.toString())); - try - { - localeBundle = ResourceBundle.getBundle(MESSAGES, currentLocale); - } - catch (MissingResourceException ex) - { - localeBundle = NULL_BUNDLE; - } + try { + localeBundle = ResourceBundle.getBundle(MESSAGES, currentLocale); + } catch (MissingResourceException ex) { + localeBundle = NULL_BUNDLE; + } - try - { - customBundle = ResourceBundle.getBundle(MESSAGES, currentLocale, new FileResClassLoader(I18n.class.getClassLoader(), ess)); - } - catch (MissingResourceException ex) - { - customBundle = NULL_BUNDLE; - } - } + try { + customBundle = ResourceBundle.getBundle(MESSAGES, currentLocale, new FileResClassLoader(I18n.class.getClassLoader(), ess)); + } catch (MissingResourceException ex) { + customBundle = NULL_BUNDLE; + } + } - public static String capitalCase(final String input) - { - return input == null || input.length() == 0 - ? input - : input.toUpperCase(Locale.ENGLISH).charAt(0) - + input.toLowerCase(Locale.ENGLISH).substring(1); - } + 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; + private static class FileResClassLoader extends ClassLoader { + private final transient File dataFolder; - FileResClassLoader(final ClassLoader classLoader, final IEssentials ess) - { - super(classLoader); - this.dataFolder = ess.getDataFolder(); - } + 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 null; - } + @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 null; + } - @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 null; - } - } + @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 null; + } + } } diff --git a/Essentials/src/com/earth2me/essentials/IConf.java b/Essentials/src/com/earth2me/essentials/IConf.java index 600c7ed48..251084d69 100644 --- a/Essentials/src/com/earth2me/essentials/IConf.java +++ b/Essentials/src/com/earth2me/essentials/IConf.java @@ -1,6 +1,5 @@ package com.earth2me.essentials; -public interface IConf -{ - public void reloadConfig(); +public interface IConf { + public void reloadConfig(); } diff --git a/Essentials/src/com/earth2me/essentials/IEssentials.java b/Essentials/src/com/earth2me/essentials/IEssentials.java index 3f6f05703..e896e02da 100644 --- a/Essentials/src/com/earth2me/essentials/IEssentials.java +++ b/Essentials/src/com/earth2me/essentials/IEssentials.java @@ -6,9 +6,6 @@ import com.earth2me.essentials.api.IWarps; import com.earth2me.essentials.metrics.Metrics; import com.earth2me.essentials.perm.PermissionsHandler; import com.earth2me.essentials.register.payment.Methods; -import java.util.Collection; -import java.util.List; -import java.util.UUID; import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; @@ -17,83 +14,86 @@ import org.bukkit.plugin.Plugin; import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.scheduler.BukkitTask; +import java.util.Collection; +import java.util.List; +import java.util.UUID; -public interface IEssentials extends Plugin -{ - void addReloadListener(IConf listener); - void reload(); +public interface IEssentials extends Plugin { + void addReloadListener(IConf listener); - boolean onCommandEssentials(CommandSender sender, Command command, String commandLabel, String[] args, ClassLoader classLoader, String commandPath, String permissionPrefix, IEssentialsModule module); + void reload(); - @Deprecated - User getUser(Object base); - - User getUser(UUID base); - - User getUser(String base); - - User getUser(Player base); + boolean onCommandEssentials(CommandSender sender, Command command, String commandLabel, String[] args, ClassLoader classLoader, String commandPath, String permissionPrefix, IEssentialsModule module); - I18n getI18n(); + @Deprecated + User getUser(Object base); - User getOfflineUser(String name); + User getUser(UUID base); - World getWorld(String name); + User getUser(String base); - int broadcastMessage(String message); + User getUser(Player base); - int broadcastMessage(IUser sender, String message); + I18n getI18n(); - int broadcastMessage(String permission, String message); + User getOfflineUser(String name); - ISettings getSettings(); + World getWorld(String name); - BukkitScheduler getScheduler(); + int broadcastMessage(String message); - IJails getJails(); + int broadcastMessage(IUser sender, String message); - IWarps getWarps(); + int broadcastMessage(String permission, String message); - Worth getWorth(); + ISettings getSettings(); - Backup getBackup(); + BukkitScheduler getScheduler(); - Methods getPaymentMethod(); + IJails getJails(); - BukkitTask runTaskAsynchronously(Runnable run); + IWarps getWarps(); - BukkitTask runTaskLaterAsynchronously(Runnable run, long delay); - - BukkitTask runTaskTimerAsynchronously(Runnable run, long delay, long period); + Worth getWorth(); - int scheduleSyncDelayedTask(Runnable run); + Backup getBackup(); - int scheduleSyncDelayedTask(Runnable run, long delay); + Methods getPaymentMethod(); - int scheduleSyncRepeatingTask(Runnable run, long delay, long period); + BukkitTask runTaskAsynchronously(Runnable run); - TNTExplodeListener getTNTListener(); + BukkitTask runTaskLaterAsynchronously(Runnable run, long delay); - PermissionsHandler getPermissionsHandler(); + BukkitTask runTaskTimerAsynchronously(Runnable run, long delay, long period); - AlternativeCommandsHandler getAlternativeCommandsHandler(); + int scheduleSyncDelayedTask(Runnable run); - void showError(CommandSource sender, Throwable exception, String commandLabel); + int scheduleSyncDelayedTask(Runnable run, long delay); - IItemDb getItemDb(); + int scheduleSyncRepeatingTask(Runnable run, long delay, long period); - UserMap getUserMap(); + TNTExplodeListener getTNTListener(); - Metrics getMetrics(); + PermissionsHandler getPermissionsHandler(); - void setMetrics(Metrics metrics); + AlternativeCommandsHandler getAlternativeCommandsHandler(); - EssentialsTimer getTimer(); + void showError(CommandSource sender, Throwable exception, String commandLabel); - List getVanishedPlayers(); + IItemDb getItemDb(); - Collection getOnlinePlayers(); + UserMap getUserMap(); - Iterable getOnlineUsers(); + Metrics getMetrics(); + + void setMetrics(Metrics metrics); + + EssentialsTimer getTimer(); + + List getVanishedPlayers(); + + Collection getOnlinePlayers(); + + Iterable getOnlineUsers(); } diff --git a/Essentials/src/com/earth2me/essentials/IEssentialsModule.java b/Essentials/src/com/earth2me/essentials/IEssentialsModule.java index 69a1a494c..9efad58de 100644 --- a/Essentials/src/com/earth2me/essentials/IEssentialsModule.java +++ b/Essentials/src/com/earth2me/essentials/IEssentialsModule.java @@ -1,6 +1,5 @@ package com.earth2me.essentials; -public interface IEssentialsModule -{ +public interface IEssentialsModule { } diff --git a/Essentials/src/com/earth2me/essentials/IReplyTo.java b/Essentials/src/com/earth2me/essentials/IReplyTo.java index ee8e80b4c..562a86fe4 100644 --- a/Essentials/src/com/earth2me/essentials/IReplyTo.java +++ b/Essentials/src/com/earth2me/essentials/IReplyTo.java @@ -1,16 +1,17 @@ package com.earth2me.essentials; -public interface IReplyTo -{ - /** - * Sets the user to reply to - * @param user - */ - public void setReplyTo(CommandSource user); +public interface IReplyTo { + /** + * Sets the user to reply to + * + * @param user + */ + public void setReplyTo(CommandSource user); - /** - * Gets the user the sender should reply to - * @return - */ - public CommandSource getReplyTo(); + /** + * Gets the user the sender should reply to + * + * @return + */ + public CommandSource getReplyTo(); } diff --git a/Essentials/src/com/earth2me/essentials/ISettings.java b/Essentials/src/com/earth2me/essentials/ISettings.java index beab3574a..d407ca161 100644 --- a/Essentials/src/com/earth2me/essentials/ISettings.java +++ b/Essentials/src/com/earth2me/essentials/ISettings.java @@ -3,216 +3,216 @@ package com.earth2me.essentials; import com.earth2me.essentials.commands.IEssentialsCommand; import com.earth2me.essentials.signs.EssentialsSign; import com.earth2me.essentials.textreader.IText; -import java.math.BigDecimal; -import java.util.List; -import java.util.Map; -import java.util.Set; import org.bukkit.ChatColor; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.event.EventPriority; +import java.math.BigDecimal; +import java.util.List; +import java.util.Map; +import java.util.Set; -public interface ISettings extends IConf -{ - boolean areSignsDisabled(); - IText getAnnounceNewPlayerFormat(); +public interface ISettings extends IConf { + boolean areSignsDisabled(); - boolean getAnnounceNewPlayers(); + IText getAnnounceNewPlayerFormat(); - String getNewPlayerKit(); + boolean getAnnounceNewPlayers(); - String getBackupCommand(); + String getNewPlayerKit(); - long getBackupInterval(); + String getBackupCommand(); - String getChatFormat(String group); + long getBackupInterval(); - int getChatRadius(); - - char getChatShout(); - - char getChatQuestion(); + String getChatFormat(String group); - BigDecimal getCommandCost(IEssentialsCommand cmd); + int getChatRadius(); - BigDecimal getCommandCost(String label); + char getChatShout(); - String getCurrencySymbol(); + char getChatQuestion(); - int getOversizedStackSize(); + BigDecimal getCommandCost(IEssentialsCommand cmd); - int getDefaultStackSize(); + BigDecimal getCommandCost(String label); - double getHealCooldown(); + String getCurrencySymbol(); - Set getSocialSpyCommands(); + int getOversizedStackSize(); - Map getKit(String name); + int getDefaultStackSize(); - ConfigurationSection getKits(); + double getHealCooldown(); - String getLocale(); + Set getSocialSpyCommands(); - String getNewbieSpawn(); + Map getKit(String name); - String getNicknamePrefix(); + ConfigurationSection getKits(); - ChatColor getOperatorColor() throws Exception; + String getLocale(); - boolean getPerWarpPermission(); + String getNewbieSpawn(); - boolean getProtectBoolean(final String configName, boolean def); + String getNicknamePrefix(); - int getProtectCreeperMaxHeight(); + ChatColor getOperatorColor() throws Exception; - List getProtectList(final String configName); + boolean getPerWarpPermission(); - boolean getProtectPreventSpawn(final String creatureName); + boolean getProtectBoolean(final String configName, boolean def); - String getProtectString(final String configName); + int getProtectCreeperMaxHeight(); - boolean getRespawnAtHome(); + List getProtectList(final String configName); - Set getMultipleHomes(); + boolean getProtectPreventSpawn(final String creatureName); - int getHomeLimit(String set); + String getProtectString(final String configName); - int getHomeLimit(User user); + boolean getRespawnAtHome(); - int getSpawnMobLimit(); + Set getMultipleHomes(); - BigDecimal getStartingBalance(); + int getHomeLimit(String set); - boolean isTeleportSafetyEnabled(); + int getHomeLimit(User user); - double getTeleportCooldown(); + int getSpawnMobLimit(); - double getTeleportDelay(); + BigDecimal getStartingBalance(); - boolean hidePermissionlessHelp(); + boolean isTeleportSafetyEnabled(); - boolean isCommandDisabled(final IEssentialsCommand cmd); + double getTeleportCooldown(); - boolean isCommandDisabled(String label); + double getTeleportDelay(); - boolean isCommandOverridden(String name); + boolean hidePermissionlessHelp(); - boolean isDebug(); + boolean isCommandDisabled(final IEssentialsCommand cmd); - boolean isEcoDisabled(); + boolean isCommandDisabled(String label); - boolean isTradeInStacks(int id); + boolean isCommandOverridden(String name); - List itemSpawnBlacklist(); + boolean isDebug(); - List enabledSigns(); + boolean isEcoDisabled(); - boolean permissionBasedItemSpawn(); + boolean isTradeInStacks(int id); - boolean showNonEssCommandsInHelp(); + List itemSpawnBlacklist(); - boolean warnOnBuildDisallow(); + List enabledSigns(); - boolean warnOnSmite(); + boolean permissionBasedItemSpawn(); - BigDecimal getMaxMoney(); + boolean showNonEssCommandsInHelp(); - BigDecimal getMinMoney(); + boolean warnOnBuildDisallow(); - boolean isEcoLogEnabled(); + boolean warnOnSmite(); - boolean isEcoLogUpdateEnabled(); + BigDecimal getMaxMoney(); - boolean removeGodOnDisconnect(); + BigDecimal getMinMoney(); - boolean changeDisplayName(); + boolean isEcoLogEnabled(); - boolean changePlayerListName(); + boolean isEcoLogUpdateEnabled(); - boolean isPlayerCommand(String string); + boolean removeGodOnDisconnect(); - boolean useBukkitPermissions(); + boolean changeDisplayName(); - boolean addPrefixSuffix(); + boolean changePlayerListName(); - boolean disablePrefix(); + boolean isPlayerCommand(String string); - boolean disableSuffix(); + boolean useBukkitPermissions(); - long getAutoAfk(); + boolean addPrefixSuffix(); - long getAutoAfkKick(); + boolean disablePrefix(); - boolean getFreezeAfkPlayers(); + boolean disableSuffix(); - boolean cancelAfkOnMove(); + long getAutoAfk(); - boolean cancelAfkOnInteract(); + long getAutoAfkKick(); - boolean areDeathMessagesEnabled(); + boolean getFreezeAfkPlayers(); - void setDebug(boolean debug); + boolean cancelAfkOnMove(); - Set getNoGodWorlds(); + boolean cancelAfkOnInteract(); - boolean getUpdateBedAtDaytime(); + boolean areDeathMessagesEnabled(); - boolean allowUnsafeEnchantments(); + void setDebug(boolean debug); - boolean getRepairEnchanted(); + Set getNoGodWorlds(); - boolean isWorldTeleportPermissions(); + boolean getUpdateBedAtDaytime(); - boolean isWorldHomePermissions(); + boolean allowUnsafeEnchantments(); - boolean registerBackInListener(); + boolean getRepairEnchanted(); - boolean getDisableItemPickupWhileAfk(); + boolean isWorldTeleportPermissions(); - EventPriority getRespawnPriority(); + boolean isWorldHomePermissions(); - long getTpaAcceptCancellation(); + boolean registerBackInListener(); - boolean isMetricsEnabled(); + boolean getDisableItemPickupWhileAfk(); - void setMetricsEnabled(boolean metricsEnabled); + EventPriority getRespawnPriority(); - long getTeleportInvulnerability(); + long getTpaAcceptCancellation(); - boolean isTeleportInvulnerability(); + boolean isMetricsEnabled(); - long getLoginAttackDelay(); + void setMetricsEnabled(boolean metricsEnabled); - int getSignUsePerSecond(); + long getTeleportInvulnerability(); - double getMaxFlySpeed(); + boolean isTeleportInvulnerability(); - double getMaxWalkSpeed(); + long getLoginAttackDelay(); - int getMailsPerMinute(); + int getSignUsePerSecond(); - long getEconomyLagWarning(); - - long getPermissionsLagWarning(); + double getMaxFlySpeed(); - void setEssentialsChatActive(boolean b); + double getMaxWalkSpeed(); - long getMaxTempban(); + int getMailsPerMinute(); - Map getListGroupConfig(); + long getEconomyLagWarning(); - int getMaxNickLength(); + long getPermissionsLagWarning(); - int getMaxUserCacheCount(); + void setEssentialsChatActive(boolean b); - boolean allowSilentJoinQuit(); + long getMaxTempban(); - boolean isCustomJoinMessage(); + Map getListGroupConfig(); - String getCustomJoinMessage(); + int getMaxNickLength(); - boolean isCustomQuitMessage(); + int getMaxUserCacheCount(); - String getCustomQuitMessage(); + boolean allowSilentJoinQuit(); + + boolean isCustomJoinMessage(); + + String getCustomJoinMessage(); + + boolean isCustomQuitMessage(); + + String getCustomQuitMessage(); } diff --git a/Essentials/src/com/earth2me/essentials/ITarget.java b/Essentials/src/com/earth2me/essentials/ITarget.java index 87b867c13..23ed4a0c0 100644 --- a/Essentials/src/com/earth2me/essentials/ITarget.java +++ b/Essentials/src/com/earth2me/essentials/ITarget.java @@ -3,7 +3,6 @@ package com.earth2me.essentials; import org.bukkit.Location; -public interface ITarget -{ - public Location getLocation(); +public interface ITarget { + public Location getLocation(); } \ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/IUser.java b/Essentials/src/com/earth2me/essentials/IUser.java index 43e729e31..b8dffbae3 100644 --- a/Essentials/src/com/earth2me/essentials/IUser.java +++ b/Essentials/src/com/earth2me/essentials/IUser.java @@ -1,144 +1,146 @@ package com.earth2me.essentials; import com.earth2me.essentials.commands.IEssentialsCommand; -import java.math.BigDecimal; -import java.util.List; -import java.util.Map; -import java.util.Set; import net.ess3.api.ITeleport; import net.ess3.api.MaxMoneyException; import org.bukkit.Location; import org.bukkit.entity.Player; +import java.math.BigDecimal; +import java.util.List; +import java.util.Map; +import java.util.Set; -public interface IUser -{ - boolean isAuthorized(String node); - boolean isAuthorized(IEssentialsCommand cmd); +public interface IUser { + boolean isAuthorized(String node); - boolean isAuthorized(IEssentialsCommand cmd, String permissionPrefix); + boolean isAuthorized(IEssentialsCommand cmd); - void healCooldown() throws Exception; + boolean isAuthorized(IEssentialsCommand cmd, String permissionPrefix); - void giveMoney(BigDecimal value) throws MaxMoneyException; + void healCooldown() throws Exception; - void giveMoney(final BigDecimal value, final CommandSource initiator) throws MaxMoneyException; - - void payUser(final User reciever, final BigDecimal value) throws Exception; + void giveMoney(BigDecimal value) throws MaxMoneyException; - void takeMoney(BigDecimal value); + void giveMoney(final BigDecimal value, final CommandSource initiator) throws MaxMoneyException; - void takeMoney(final BigDecimal value, final CommandSource initiator); + void payUser(final User reciever, final BigDecimal value) throws Exception; - boolean canAfford(BigDecimal value); + void takeMoney(BigDecimal value); - Boolean canSpawnItem(final int itemId); + void takeMoney(final BigDecimal value, final CommandSource initiator); - void setLastLocation(); + boolean canAfford(BigDecimal value); - void setLogoutLocation(); + Boolean canSpawnItem(final int itemId); - void requestTeleport(final User player, final boolean here); + void setLastLocation(); - ITeleport getTeleport(); + void setLogoutLocation(); - BigDecimal getMoney(); + void requestTeleport(final User player, final boolean here); - void setMoney(final BigDecimal value) throws MaxMoneyException; + ITeleport getTeleport(); - void setAfk(final boolean set); + BigDecimal getMoney(); - /** - * 'Hidden' Represents when a player is hidden from others. This status includes when the player is hidden via other - * supported plugins. Use isVanished() if you want to check if a user is vanished by Essentials. - * - * @return If the user is hidden or not - * @see isVanished - */ - boolean isHidden(); + void setMoney(final BigDecimal value) throws MaxMoneyException; - void setHidden(boolean vanish); + void setAfk(final boolean set); - boolean isGodModeEnabled(); + /** + * 'Hidden' Represents when a player is hidden from others. This status includes when the player is hidden via other + * supported plugins. Use isVanished() if you want to check if a user is vanished by Essentials. + * + * @return If the user is hidden or not + * + * @see isVanished + */ + boolean isHidden(); - String getGroup(); + void setHidden(boolean vanish); - boolean inGroup(final String group); + boolean isGodModeEnabled(); - boolean canBuild(); + String getGroup(); - long getTeleportRequestTime(); + boolean inGroup(final String group); - void enableInvulnerabilityAfterTeleport(); + boolean canBuild(); - void resetInvulnerabilityAfterTeleport(); + long getTeleportRequestTime(); - boolean hasInvulnerabilityAfterTeleport(); + void enableInvulnerabilityAfterTeleport(); - /** - * 'Vanished' Represents when a player is hidden from others by Essentials. This status does NOT include when the - * player is hidden via other plugins. Use isHidden() if you want to check if a user is vanished by any supported - * plugin. - * - * @return If the user is vanished or not - * @see isHidden - */ - boolean isVanished(); + void resetInvulnerabilityAfterTeleport(); - void setVanished(boolean vanish); + boolean hasInvulnerabilityAfterTeleport(); - boolean isIgnoreExempt(); + /** + * 'Vanished' Represents when a player is hidden from others by Essentials. This status does NOT include when the + * player is hidden via other plugins. Use isHidden() if you want to check if a user is vanished by any supported + * plugin. + * + * @return If the user is vanished or not + * + * @see isHidden + */ + boolean isVanished(); - public void sendMessage(String message); + void setVanished(boolean vanish); - /* - * UserData - */ - Location getHome(String name) throws Exception; + boolean isIgnoreExempt(); - Location getHome(Location loc) throws Exception; + public void sendMessage(String message); - List getHomes(); + /* + * UserData + */ + Location getHome(String name) throws Exception; - void setHome(String name, Location loc); + Location getHome(Location loc) throws Exception; - void delHome(String name) throws Exception; + List getHomes(); - boolean hasHome(); + void setHome(String name, Location loc); - Location getLastLocation(); + void delHome(String name) throws Exception; - Location getLogoutLocation(); + boolean hasHome(); - long getLastTeleportTimestamp(); + Location getLastLocation(); - void setLastTeleportTimestamp(long time); + Location getLogoutLocation(); - String getJail(); + long getLastTeleportTimestamp(); - void setJail(String jail); + void setLastTeleportTimestamp(long time); - List getMails(); + String getJail(); - void addMail(String mail); + void setJail(String jail); - boolean isAfk(); + List getMails(); - void setConfigProperty(String node, Object object); + void addMail(String mail); - Set getConfigKeys(); + boolean isAfk(); - Map getConfigMap(); + void setConfigProperty(String node, Object object); - Map getConfigMap(String node); + Set getConfigKeys(); - /* - * PlayerExtension - */ - Player getBase(); + Map getConfigMap(); - CommandSource getSource(); + Map getConfigMap(String node); - public String getName(); + /* + * PlayerExtension + */ + Player getBase(); + + CommandSource getSource(); + + public String getName(); } diff --git a/Essentials/src/com/earth2me/essentials/ItemDb.java b/Essentials/src/com/earth2me/essentials/ItemDb.java index 6d0b1725a..baa98f9c1 100644 --- a/Essentials/src/com/earth2me/essentials/ItemDb.java +++ b/Essentials/src/com/earth2me/essentials/ItemDb.java @@ -1,313 +1,249 @@ package com.earth2me.essentials; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.utils.NumberUtil; import com.earth2me.essentials.utils.StringUtil; -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import net.ess3.api.IEssentials; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; -public class ItemDb implements IConf, net.ess3.api.IItemDb -{ - private final transient IEssentials ess; - private final transient Map items = new HashMap(); - private final transient Map> names = new HashMap>(); - private final transient Map primaryName = new HashMap(); - private final transient Map durabilities = new HashMap(); - private final transient ManagedFile file; - private final transient Pattern splitPattern = Pattern.compile("((.*)[:+',;.](\\d+))"); - - public ItemDb(final IEssentials ess) - { - this.ess = ess; - file = new ManagedFile("items.csv", ess); - } - - @Override - public void reloadConfig() - { - final List lines = file.getLines(); - - if (lines.isEmpty()) - { - return; - } - - durabilities.clear(); - items.clear(); - names.clear(); - primaryName.clear(); - - for (String line : lines) - { - line = line.trim().toLowerCase(Locale.ENGLISH); - if (line.length() > 0 && line.charAt(0) == '#') - { - continue; - } - - final String[] parts = line.split("[^a-z0-9]"); - if (parts.length < 2) - { - continue; - } - - final int numeric = Integer.parseInt(parts[1]); - final short data = parts.length > 2 && !parts[2].equals("0") ? Short.parseShort(parts[2]) : 0; - String itemName = parts[0].toLowerCase(Locale.ENGLISH); - - durabilities.put(itemName, data); - items.put(itemName, numeric); - - ItemData itemData = new ItemData(numeric, data); - if (names.containsKey(itemData)) - { - List nameList = names.get(itemData); - nameList.add(itemName); - Collections.sort(nameList, new LengthCompare()); - } - else - { - List nameList = new ArrayList(); - nameList.add(itemName); - names.put(itemData, nameList); - primaryName.put(itemData, itemName); - } - } - } - - @Override - public ItemStack get(final String id, final int quantity) throws Exception - { - final ItemStack retval = get(id.toLowerCase(Locale.ENGLISH)); - retval.setAmount(quantity); - return retval; - } - - @Override - public ItemStack get(final String id) throws Exception - { - int itemid = 0; - String itemname = null; - short metaData = 0; - Matcher parts = splitPattern.matcher(id); - if (parts.matches()) - { - itemname = parts.group(2); - metaData = Short.parseShort(parts.group(3)); - } - else - { - itemname = id; - } - - if (NumberUtil.isInt(itemname)) - { - itemid = Integer.parseInt(itemname); - } - else if (NumberUtil.isInt(id)) - { - itemid = Integer.parseInt(id); - } - else - { - itemname = itemname.toLowerCase(Locale.ENGLISH); - } - - if (itemid < 1) - { - if (items.containsKey(itemname)) - { - itemid = items.get(itemname); - if (durabilities.containsKey(itemname) && metaData == 0) - { - metaData = durabilities.get(itemname); - } - } - else if (Material.getMaterial(itemname.toUpperCase(Locale.ENGLISH)) != null) - { - Material bMaterial = Material.getMaterial(itemname.toUpperCase(Locale.ENGLISH)); - itemid = bMaterial.getId(); - } - else - { - try - { - Material bMaterial = Bukkit.getUnsafe().getMaterialFromInternalName(itemname.toLowerCase(Locale.ENGLISH)); - itemid = bMaterial.getId(); - } - catch (Throwable throwable) - { - throw new Exception(tl("unknownItemName", itemname), throwable); - } - } - } - - if (itemid < 1) - { - throw new Exception(tl("unknownItemName", itemname)); - } - - final Material mat = Material.getMaterial(itemid); - if (mat == null) - { - throw new Exception(tl("unknownItemId", itemid)); - } - final ItemStack retval = new ItemStack(mat); - retval.setAmount(mat.getMaxStackSize()); - retval.setDurability(metaData); - return retval; - } - - @Override - public List getMatching(User user, String[] args) throws Exception - { - List is = new ArrayList(); - - if (args.length < 1) - { - is.add(user.getBase().getItemInHand()); - } - else if (args[0].equalsIgnoreCase("hand")) - { - is.add(user.getBase().getItemInHand()); - } - else if (args[0].equalsIgnoreCase("inventory") || args[0].equalsIgnoreCase("invent") || args[0].equalsIgnoreCase("all")) - { - for (ItemStack stack : user.getBase().getInventory().getContents()) - { - if (stack == null || stack.getType() == Material.AIR) - { - continue; - } - is.add(stack); - } - } - else if (args[0].equalsIgnoreCase("blocks")) - { - for (ItemStack stack : user.getBase().getInventory().getContents()) - { - if (stack == null || stack.getTypeId() > 255 || stack.getType() == Material.AIR) - { - continue; - } - is.add(stack); - } - } - else - { - is.add(get(args[0])); - } - - if (is.isEmpty() || is.get(0).getType() == Material.AIR) - { - throw new Exception(tl("itemSellAir")); - } - - return is; - } - - @Override - public String names(ItemStack item) - { - ItemData itemData = new ItemData(item.getTypeId(), item.getDurability()); - List nameList = names.get(itemData); - if (nameList == null) - { - itemData = new ItemData(item.getTypeId(), (short)0); - nameList = names.get(itemData); - if (nameList == null) - { - return null; - } - } - - if (nameList.size() > 15) - { - nameList = nameList.subList(0, 14); - } - return StringUtil.joinList(", ", nameList); - } - - @Override - public String name(ItemStack item) - { - ItemData itemData = new ItemData(item.getTypeId(), item.getDurability()); - String name = primaryName.get(itemData); - if (name == null) - { - itemData = new ItemData(item.getTypeId(), (short)0); - name = primaryName.get(itemData); - if (name == null) - { - return null; - } - } - return name; - } +import static com.earth2me.essentials.I18n.tl; - static class ItemData - { - final private int itemNo; - final private short itemData; +public class ItemDb implements IConf, net.ess3.api.IItemDb { + private final transient IEssentials ess; + private final transient Map items = new HashMap(); + private final transient Map> names = new HashMap>(); + private final transient Map primaryName = new HashMap(); + private final transient Map durabilities = new HashMap(); + private final transient ManagedFile file; + private final transient Pattern splitPattern = Pattern.compile("((.*)[:+',;.](\\d+))"); - ItemData(final int itemNo, final short itemData) - { - this.itemNo = itemNo; - this.itemData = itemData; - } + public ItemDb(final IEssentials ess) { + this.ess = ess; + file = new ManagedFile("items.csv", ess); + } - public int getItemNo() - { - return itemNo; - } + @Override + public void reloadConfig() { + final List lines = file.getLines(); - public short getItemData() - { - return itemData; - } + if (lines.isEmpty()) { + return; + } - @Override - public int hashCode() - { - return (31 * itemNo) ^ itemData; - } + durabilities.clear(); + items.clear(); + names.clear(); + primaryName.clear(); - @Override - public boolean equals(Object o) - { - if (o == null) - { - return false; - } - if (!(o instanceof ItemData)) - { - return false; - } - ItemData pairo = (ItemData)o; - return this.itemNo == pairo.getItemNo() - && this.itemData == pairo.getItemData(); - } - } + for (String line : lines) { + line = line.trim().toLowerCase(Locale.ENGLISH); + if (line.length() > 0 && line.charAt(0) == '#') { + continue; + } + + final String[] parts = line.split("[^a-z0-9]"); + if (parts.length < 2) { + continue; + } + + final int numeric = Integer.parseInt(parts[1]); + final short data = parts.length > 2 && !parts[2].equals("0") ? Short.parseShort(parts[2]) : 0; + String itemName = parts[0].toLowerCase(Locale.ENGLISH); + + durabilities.put(itemName, data); + items.put(itemName, numeric); + + ItemData itemData = new ItemData(numeric, data); + if (names.containsKey(itemData)) { + List nameList = names.get(itemData); + nameList.add(itemName); + Collections.sort(nameList, new LengthCompare()); + } else { + List nameList = new ArrayList(); + nameList.add(itemName); + names.put(itemData, nameList); + primaryName.put(itemData, itemName); + } + } + } + + @Override + public ItemStack get(final String id, final int quantity) throws Exception { + final ItemStack retval = get(id.toLowerCase(Locale.ENGLISH)); + retval.setAmount(quantity); + return retval; + } + + @Override + public ItemStack get(final String id) throws Exception { + int itemid = 0; + String itemname = null; + short metaData = 0; + Matcher parts = splitPattern.matcher(id); + if (parts.matches()) { + itemname = parts.group(2); + metaData = Short.parseShort(parts.group(3)); + } else { + itemname = id; + } + + if (NumberUtil.isInt(itemname)) { + itemid = Integer.parseInt(itemname); + } else if (NumberUtil.isInt(id)) { + itemid = Integer.parseInt(id); + } else { + itemname = itemname.toLowerCase(Locale.ENGLISH); + } + + if (itemid < 1) { + if (items.containsKey(itemname)) { + itemid = items.get(itemname); + if (durabilities.containsKey(itemname) && metaData == 0) { + metaData = durabilities.get(itemname); + } + } else if (Material.getMaterial(itemname.toUpperCase(Locale.ENGLISH)) != null) { + Material bMaterial = Material.getMaterial(itemname.toUpperCase(Locale.ENGLISH)); + itemid = bMaterial.getId(); + } else { + try { + Material bMaterial = Bukkit.getUnsafe().getMaterialFromInternalName(itemname.toLowerCase(Locale.ENGLISH)); + itemid = bMaterial.getId(); + } catch (Throwable throwable) { + throw new Exception(tl("unknownItemName", itemname), throwable); + } + } + } + + if (itemid < 1) { + throw new Exception(tl("unknownItemName", itemname)); + } + + final Material mat = Material.getMaterial(itemid); + if (mat == null) { + throw new Exception(tl("unknownItemId", itemid)); + } + final ItemStack retval = new ItemStack(mat); + retval.setAmount(mat.getMaxStackSize()); + retval.setDurability(metaData); + return retval; + } + + @Override + public List getMatching(User user, String[] args) throws Exception { + List is = new ArrayList(); + + if (args.length < 1) { + is.add(user.getBase().getItemInHand()); + } else if (args[0].equalsIgnoreCase("hand")) { + is.add(user.getBase().getItemInHand()); + } else if (args[0].equalsIgnoreCase("inventory") || args[0].equalsIgnoreCase("invent") || args[0].equalsIgnoreCase("all")) { + for (ItemStack stack : user.getBase().getInventory().getContents()) { + if (stack == null || stack.getType() == Material.AIR) { + continue; + } + is.add(stack); + } + } else if (args[0].equalsIgnoreCase("blocks")) { + for (ItemStack stack : user.getBase().getInventory().getContents()) { + if (stack == null || stack.getTypeId() > 255 || stack.getType() == Material.AIR) { + continue; + } + is.add(stack); + } + } else { + is.add(get(args[0])); + } + + if (is.isEmpty() || is.get(0).getType() == Material.AIR) { + throw new Exception(tl("itemSellAir")); + } + + return is; + } + + @Override + public String names(ItemStack item) { + ItemData itemData = new ItemData(item.getTypeId(), item.getDurability()); + List nameList = names.get(itemData); + if (nameList == null) { + itemData = new ItemData(item.getTypeId(), (short) 0); + nameList = names.get(itemData); + if (nameList == null) { + return null; + } + } + + if (nameList.size() > 15) { + nameList = nameList.subList(0, 14); + } + return StringUtil.joinList(", ", nameList); + } + + @Override + public String name(ItemStack item) { + ItemData itemData = new ItemData(item.getTypeId(), item.getDurability()); + String name = primaryName.get(itemData); + if (name == null) { + itemData = new ItemData(item.getTypeId(), (short) 0); + name = primaryName.get(itemData); + if (name == null) { + return null; + } + } + return name; + } - class LengthCompare implements java.util.Comparator - { - public LengthCompare() - { - super(); - } + static class ItemData { + final private int itemNo; + final private short itemData; - @Override - public int compare(String s1, String s2) - { - return s1.length() - s2.length(); - } - } + ItemData(final int itemNo, final short itemData) { + this.itemNo = itemNo; + this.itemData = itemData; + } + + public int getItemNo() { + return itemNo; + } + + public short getItemData() { + return itemData; + } + + @Override + public int hashCode() { + return (31 * itemNo) ^ itemData; + } + + @Override + public boolean equals(Object o) { + if (o == null) { + return false; + } + if (!(o instanceof ItemData)) { + return false; + } + ItemData pairo = (ItemData) o; + return this.itemNo == pairo.getItemNo() && this.itemData == pairo.getItemData(); + } + } + + + class LengthCompare implements java.util.Comparator { + public LengthCompare() { + super(); + } + + @Override + public int compare(String s1, String s2) { + return s1.length() - s2.length(); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/Jails.java b/Essentials/src/com/earth2me/essentials/Jails.java index afbb7673a..3e5860acb 100644 --- a/Essentials/src/com/earth2me/essentials/Jails.java +++ b/Essentials/src/com/earth2me/essentials/Jails.java @@ -1,11 +1,6 @@ package com.earth2me.essentials; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.storage.AsyncStorageObjectHolder; -import java.io.File; -import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; import net.ess3.api.IEssentials; import net.ess3.api.IUser; import org.bukkit.Bukkit; @@ -28,313 +23,242 @@ import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.plugin.PluginManager; +import java.io.File; +import java.util.*; +import java.util.logging.Level; +import java.util.logging.Logger; -public class Jails extends AsyncStorageObjectHolder implements net.ess3.api.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); - reloadConfig(); - } - - private void registerListeners() - { - enabled = true; - final PluginManager pluginManager = ess.getServer().getPluginManager(); - final JailListener blockListener = new JailListener(); - pluginManager.registerEvents(blockListener, ess); - if (ess.getSettings().isDebug()) - { - LOGGER.log(Level.INFO, "Registering Jail listener"); - } - } - - @Override - public File getStorageFile() - { - return new File(ess.getDataFolder(), "jail.yml"); - } - - @Override - public void finishRead() - { - checkRegister(); - } - - @Override - public void finishWrite() - { - checkRegister(); - } - - public void resetListener() - { - enabled = false; - checkRegister(); - } - - private void checkRegister() - { - if (enabled == false && getCount() > 0) - { - 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(tl("jailNotExist")); - } - Location loc = getData().getJails().get(jailName.toLowerCase(Locale.ENGLISH)); - if (loc == null || loc.getWorld() == null) - { - throw new Exception(tl("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.getBase().isOnline()) - { - Location loc = getJail(jail); - user.getTeleport().now(loc, false, TeleportCause.COMMAND); - } - user.setJail(jail); - } - 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), loc); - } - finally - { - unlock(); - } - } - - @Override - public int getCount() - { - try - { - return getList().size(); - } - catch (Exception ex) - { - return 0; - } - } +import static com.earth2me.essentials.I18n.tl; - private class JailListener implements Listener - { - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onJailBlockBreak(final BlockBreakEvent event) - { - final User user = ess.getUser(event.getPlayer()); - if (user.isJailed()) - { - event.setCancelled(true); - } - } +public class Jails extends AsyncStorageObjectHolder implements net.ess3.api.IJails { + private static final transient Logger LOGGER = Bukkit.getLogger(); + private static transient boolean enabled = false; - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onJailBlockPlace(final BlockPlaceEvent event) - { - final User user = ess.getUser(event.getPlayer()); - if (user.isJailed()) - { - event.setCancelled(true); - } - } + public Jails(final IEssentials ess) { + super(ess, com.earth2me.essentials.settings.Jails.class); + reloadConfig(); + } - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onJailBlockDamage(final BlockDamageEvent event) - { - final User user = ess.getUser(event.getPlayer()); - if (user.isJailed()) - { - event.setCancelled(true); - } - } + private void registerListeners() { + enabled = true; + final PluginManager pluginManager = ess.getServer().getPluginManager(); + final JailListener blockListener = new JailListener(); + pluginManager.registerEvents(blockListener, ess); + if (ess.getSettings().isDebug()) { + LOGGER.log(Level.INFO, "Registering Jail listener"); + } + } - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onJailEntityDamageByEntity(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 User user = ess.getUser((Player)damager); - if (user != null && user.isJailed()) - { - event.setCancelled(true); - } - } - } + @Override + public File getStorageFile() { + return new File(ess.getDataFolder(), "jail.yml"); + } - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onJailPlayerInteract(final PlayerInteractEvent event) - { - final User user = ess.getUser(event.getPlayer()); - if (user.isJailed()) - { - event.setCancelled(true); - } - } + @Override + public void finishRead() { + checkRegister(); + } - @EventHandler(priority = EventPriority.HIGHEST) - public void onJailPlayerRespawn(final PlayerRespawnEvent event) - { - final User user = ess.getUser(event.getPlayer()); - if (!user.isJailed() || user.getJail() == null || user.getJail().isEmpty()) - { - return; - } + @Override + public void finishWrite() { + checkRegister(); + } - try - { - event.setRespawnLocation(getJail(user.getJail())); - } - catch (Exception ex) - { - if (ess.getSettings().isDebug()) - { - LOGGER.log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex); - } - else - { - LOGGER.log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage())); - } - } - } + public void resetListener() { + enabled = false; + checkRegister(); + } - @EventHandler(priority = EventPriority.HIGH) - public void onJailPlayerTeleport(final PlayerTeleportEvent event) - { - final User user = ess.getUser(event.getPlayer()); - if (!user.isJailed() || user.getJail() == null || user.getJail().isEmpty()) - { - return; - } + private void checkRegister() { + if (enabled == false && getCount() > 0) { + registerListeners(); + } + } - try - { - event.setTo(getJail(user.getJail())); - } - catch (Exception ex) - { - if (ess.getSettings().isDebug()) - { - LOGGER.log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex); - } - else - { - LOGGER.log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage())); - } - } - user.sendMessage(tl("jailMessage")); - } + @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(tl("jailNotExist")); + } + Location loc = getData().getJails().get(jailName.toLowerCase(Locale.ENGLISH)); + if (loc == null || loc.getWorld() == null) { + throw new Exception(tl("jailNotExist")); + } + return loc; + } finally { + unlock(); + } + } - @EventHandler(priority = EventPriority.HIGHEST) - public void onJailPlayerJoin(final PlayerJoinEvent event) - { - final User user = ess.getUser(event.getPlayer()); - final long currentTime = System.currentTimeMillis(); - user.checkJailTimeout(currentTime); - if (!user.isJailed() || user.getJail() == null || user.getJail().isEmpty()) - { - return; - } + @Override + public Collection getList() throws Exception { + acquireReadLock(); + try { + if (getData().getJails() == null) { + return Collections.emptyList(); + } + return new ArrayList(getData().getJails().keySet()); + } finally { + unlock(); + } + } - try - { - sendToJail(user, user.getJail()); - } - catch (Exception ex) - { - if (ess.getSettings().isDebug()) - { - LOGGER.log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex); - } - else - { - LOGGER.log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage())); - } - } - user.sendMessage(tl("jailMessage")); - } - } + @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.getBase().isOnline()) { + Location loc = getJail(jail); + user.getTeleport().now(loc, false, TeleportCause.COMMAND); + } + user.setJail(jail); + } 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), 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 onJailBlockBreak(final BlockBreakEvent event) { + final User user = ess.getUser(event.getPlayer()); + if (user.isJailed()) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onJailBlockPlace(final BlockPlaceEvent event) { + final User user = ess.getUser(event.getPlayer()); + if (user.isJailed()) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onJailBlockDamage(final BlockDamageEvent event) { + final User user = ess.getUser(event.getPlayer()); + if (user.isJailed()) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onJailEntityDamageByEntity(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 User user = ess.getUser((Player) damager); + if (user != null && user.isJailed()) { + event.setCancelled(true); + } + } + } + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onJailPlayerInteract(final PlayerInteractEvent event) { + final User user = ess.getUser(event.getPlayer()); + if (user.isJailed()) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onJailPlayerRespawn(final PlayerRespawnEvent event) { + final User user = ess.getUser(event.getPlayer()); + if (!user.isJailed() || user.getJail() == null || user.getJail().isEmpty()) { + return; + } + + try { + event.setRespawnLocation(getJail(user.getJail())); + } catch (Exception ex) { + if (ess.getSettings().isDebug()) { + LOGGER.log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex); + } else { + LOGGER.log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage())); + } + } + } + + @EventHandler(priority = EventPriority.HIGH) + public void onJailPlayerTeleport(final PlayerTeleportEvent event) { + final User user = ess.getUser(event.getPlayer()); + if (!user.isJailed() || user.getJail() == null || user.getJail().isEmpty()) { + return; + } + + try { + event.setTo(getJail(user.getJail())); + } catch (Exception ex) { + if (ess.getSettings().isDebug()) { + LOGGER.log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex); + } else { + LOGGER.log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage())); + } + } + user.sendMessage(tl("jailMessage")); + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onJailPlayerJoin(final PlayerJoinEvent event) { + final User user = ess.getUser(event.getPlayer()); + final long currentTime = System.currentTimeMillis(); + user.checkJailTimeout(currentTime); + if (!user.isJailed() || user.getJail() == null || user.getJail().isEmpty()) { + return; + } + + try { + sendToJail(user, user.getJail()); + } catch (Exception ex) { + if (ess.getSettings().isDebug()) { + LOGGER.log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex); + } else { + LOGGER.log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage())); + } + } + user.sendMessage(tl("jailMessage")); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/Kit.java b/Essentials/src/com/earth2me/essentials/Kit.java index 6152e8396..0de37957f 100644 --- a/Essentials/src/com/earth2me/essentials/Kit.java +++ b/Essentials/src/com/earth2me/essentials/Kit.java @@ -1,7 +1,5 @@ package com.earth2me.essentials; -import static com.earth2me.essentials.I18n.tl; -import static com.earth2me.essentials.I18n.capitalCase; import com.earth2me.essentials.Trade.OverflowType; import com.earth2me.essentials.commands.NoChargeException; import com.earth2me.essentials.craftbukkit.InventoryWorkaround; @@ -10,284 +8,227 @@ import com.earth2me.essentials.textreader.KeywordReplacer; import com.earth2me.essentials.textreader.SimpleTextInput; import com.earth2me.essentials.utils.DateUtil; import com.earth2me.essentials.utils.NumberUtil; -import java.math.BigDecimal; -import java.util.*; -import java.util.logging.Level; import net.ess3.api.IEssentials; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.inventory.ItemStack; +import java.math.BigDecimal; +import java.util.*; +import java.util.logging.Level; -public class Kit -{ - final IEssentials ess; - final String kitName; - final Map kit; - final Trade charge; +import static com.earth2me.essentials.I18n.capitalCase; +import static com.earth2me.essentials.I18n.tl; - public Kit(final String kitName, final IEssentials ess) throws Exception - { - this.kitName = kitName; - this.ess = ess; - this.kit = ess.getSettings().getKit(kitName); - this.charge = new Trade("kit-" + kitName, new Trade("kit-kit", ess), ess); - if (kit == null) - { - throw new Exception(tl("kitNotFound")); - } - } +public class Kit { + final IEssentials ess; + final String kitName; + final Map kit; + final Trade charge; - //TODO: Convert this to use one of the new text classes? - public static String listKits(final IEssentials ess, final User user) throws Exception - { - try - { - final ConfigurationSection kits = ess.getSettings().getKits(); - final StringBuilder list = new StringBuilder(); - for (String kitItem : kits.getKeys(false)) - { - if (user == null) - { - list.append(" ").append(capitalCase(kitItem)); - } - else if (user.isAuthorized("essentials.kits." + kitItem.toLowerCase(Locale.ENGLISH))) - { - String cost = ""; - String name = capitalCase(kitItem); - BigDecimal costPrice = new Trade("kit-" + kitItem.toLowerCase(Locale.ENGLISH), ess).getCommandCost(user); - if (costPrice.signum() > 0) - { - cost = tl("kitCost", NumberUtil.displayCurrency(costPrice, ess)); - } + public Kit(final String kitName, final IEssentials ess) throws Exception { + this.kitName = kitName; + this.ess = ess; + this.kit = ess.getSettings().getKit(kitName); + this.charge = new Trade("kit-" + kitName, new Trade("kit-kit", ess), ess); - Kit kit = new Kit(kitItem, ess); - if (kit.getNextUse(user) != 0) - { - name = tl("kitDelay", name); - } + if (kit == null) { + throw new Exception(tl("kitNotFound")); + } + } - list.append(" ").append(name).append(cost); - } - } - return list.toString().trim(); - } - catch (Exception ex) - { - throw new Exception(tl("kitError"), ex); - } + //TODO: Convert this to use one of the new text classes? + public static String listKits(final IEssentials ess, final User user) throws Exception { + try { + final ConfigurationSection kits = ess.getSettings().getKits(); + final StringBuilder list = new StringBuilder(); + for (String kitItem : kits.getKeys(false)) { + if (user == null) { + list.append(" ").append(capitalCase(kitItem)); + } else if (user.isAuthorized("essentials.kits." + kitItem.toLowerCase(Locale.ENGLISH))) { + String cost = ""; + String name = capitalCase(kitItem); + BigDecimal costPrice = new Trade("kit-" + kitItem.toLowerCase(Locale.ENGLISH), ess).getCommandCost(user); + if (costPrice.signum() > 0) { + cost = tl("kitCost", NumberUtil.displayCurrency(costPrice, ess)); + } - } + Kit kit = new Kit(kitItem, ess); + if (kit.getNextUse(user) != 0) { + name = tl("kitDelay", name); + } - public String getName() - { - return kitName; - } + list.append(" ").append(name).append(cost); + } + } + return list.toString().trim(); + } catch (Exception ex) { + throw new Exception(tl("kitError"), ex); + } - public void checkPerms(final User user) throws Exception - { - if (!user.isAuthorized("essentials.kits." + kitName)) - { - throw new Exception(tl("noKitPermission", "essentials.kits." + kitName)); - } - } + } - public void checkDelay(final User user) throws Exception - { - long nextUse = getNextUse(user); + public String getName() { + return kitName; + } - if (nextUse == 0L) - { - return; - } - else if (nextUse < 0L) - { - user.sendMessage(tl("kitOnce")); - throw new NoChargeException(); - } - else - { - user.sendMessage(tl("kitTimed", DateUtil.formatDateDiff(nextUse))); - throw new NoChargeException(); - } - } + public void checkPerms(final User user) throws Exception { + if (!user.isAuthorized("essentials.kits." + kitName)) { + throw new Exception(tl("noKitPermission", "essentials.kits." + kitName)); + } + } - public void checkAffordable(final User user) throws Exception - { - charge.isAffordableFor(user); - } + public void checkDelay(final User user) throws Exception { + long nextUse = getNextUse(user); - public void setTime(final User user) throws Exception - { - final Calendar time = new GregorianCalendar(); - user.setKitTimestamp(kitName, time.getTimeInMillis()); - } + if (nextUse == 0L) { + return; + } else if (nextUse < 0L) { + user.sendMessage(tl("kitOnce")); + throw new NoChargeException(); + } else { + user.sendMessage(tl("kitTimed", DateUtil.formatDateDiff(nextUse))); + throw new NoChargeException(); + } + } - public void chargeUser(final User user) throws Exception - { - charge.charge(user); - } + public void checkAffordable(final User user) throws Exception { + charge.isAffordableFor(user); + } - public long getNextUse(final User user) throws Exception - { - if (user.isAuthorized("essentials.kit.exemptdelay")) - { - return 0L; - } + public void setTime(final User user) throws Exception { + final Calendar time = new GregorianCalendar(); + user.setKitTimestamp(kitName, time.getTimeInMillis()); + } - final Calendar time = new GregorianCalendar(); + public void chargeUser(final User user) throws Exception { + charge.charge(user); + } - double delay = 0; - try - { - // Make sure delay is valid - delay = kit.containsKey("delay") ? ((Number)kit.get("delay")).doubleValue() : 0.0d; - } - catch (Exception e) - { - throw new Exception(tl("kitError2")); - } + public long getNextUse(final User user) throws Exception { + if (user.isAuthorized("essentials.kit.exemptdelay")) { + return 0L; + } - // When was the last kit used? - final long lastTime = user.getKitTimestamp(kitName); + final Calendar time = new GregorianCalendar(); - // When can be use the kit again? - final Calendar delayTime = new GregorianCalendar(); - delayTime.setTimeInMillis(lastTime); - delayTime.add(Calendar.SECOND, (int)delay); - delayTime.add(Calendar.MILLISECOND, (int)((delay * 1000.0) % 1000.0)); + double delay = 0; + try { + // Make sure delay is valid + delay = kit.containsKey("delay") ? ((Number) kit.get("delay")).doubleValue() : 0.0d; + } catch (Exception e) { + throw new Exception(tl("kitError2")); + } - if (lastTime == 0L || lastTime > time.getTimeInMillis()) - { - // If we have no record of kit use, or its corrupted, give them benifit of the doubt. - return 0L; - } - else if (delay < 0d) - { - // If the kit has a negative kit time, it can only be used once. - return -1; - } - else if (delayTime.before(time)) - { - // If the kit was used in the past, but outside the delay time, it can be used. - return 0L; - } - else - { - // If the kit has been used recently, return the next time it can be used. - return delayTime.getTimeInMillis(); - } - } + // When was the last kit used? + final long lastTime = user.getKitTimestamp(kitName); - public List getItems(final User user) throws Exception - { - if (kit == null) - { - throw new Exception(tl("kitNotFound")); - } - try - { - final List itemList = new ArrayList(); - final Object kitItems = kit.get("items"); - if (kitItems instanceof List) - { - for (Object item : (List)kitItems) - { - if (item instanceof String) - { - itemList.add(item.toString()); - continue; - } - throw new Exception("Invalid kit item: " + item.toString()); - } - return itemList; - } - throw new Exception("Invalid item list"); - } - catch (Exception e) - { - ess.getLogger().log(Level.WARNING, "Error parsing kit " + kitName + ": " + e.getMessage()); - throw new Exception(tl("kitError2"), e); - } - } + // When can be use the kit again? + final Calendar delayTime = new GregorianCalendar(); + delayTime.setTimeInMillis(lastTime); + delayTime.add(Calendar.SECOND, (int) delay); + delayTime.add(Calendar.MILLISECOND, (int) ((delay * 1000.0) % 1000.0)); - public void expandItems(final User user) throws Exception - { - expandItems(user, getItems(user)); - } + if (lastTime == 0L || lastTime > time.getTimeInMillis()) { + // If we have no record of kit use, or its corrupted, give them benifit of the doubt. + return 0L; + } else if (delay < 0d) { + // If the kit has a negative kit time, it can only be used once. + return -1; + } else if (delayTime.before(time)) { + // If the kit was used in the past, but outside the delay time, it can be used. + return 0L; + } else { + // If the kit has been used recently, return the next time it can be used. + return delayTime.getTimeInMillis(); + } + } - public void expandItems(final User user, final List items) throws Exception - { - try - { - IText input = new SimpleTextInput(items); - IText output = new KeywordReplacer(input, user.getSource(), ess); + public List getItems(final User user) throws Exception { + if (kit == null) { + throw new Exception(tl("kitNotFound")); + } + try { + final List itemList = new ArrayList(); + final Object kitItems = kit.get("items"); + if (kitItems instanceof List) { + for (Object item : (List) kitItems) { + if (item instanceof String) { + itemList.add(item.toString()); + continue; + } + throw new Exception("Invalid kit item: " + item.toString()); + } + return itemList; + } + throw new Exception("Invalid item list"); + } catch (Exception e) { + ess.getLogger().log(Level.WARNING, "Error parsing kit " + kitName + ": " + e.getMessage()); + throw new Exception(tl("kitError2"), e); + } + } - boolean spew = false; - final boolean allowUnsafe = ess.getSettings().allowUnsafeEnchantments(); - for (String kitItem : output.getLines()) - { - if (kitItem.startsWith(ess.getSettings().getCurrencySymbol())) - { - BigDecimal value = new BigDecimal(kitItem.substring(ess.getSettings().getCurrencySymbol().length()).trim()); - Trade t = new Trade(value, ess); - t.pay(user, OverflowType.DROP); - continue; - } + public void expandItems(final User user) throws Exception { + expandItems(user, getItems(user)); + } - final String[] parts = kitItem.split(" +"); - final ItemStack parseStack = ess.getItemDb().get(parts[0], parts.length > 1 ? Integer.parseInt(parts[1]) : 1); + public void expandItems(final User user, final List items) throws Exception { + try { + IText input = new SimpleTextInput(items); + IText output = new KeywordReplacer(input, user.getSource(), ess); - if (parseStack.getType() == Material.AIR) - { - continue; - } + boolean spew = false; + final boolean allowUnsafe = ess.getSettings().allowUnsafeEnchantments(); + for (String kitItem : output.getLines()) { + if (kitItem.startsWith(ess.getSettings().getCurrencySymbol())) { + BigDecimal value = new BigDecimal(kitItem.substring(ess.getSettings().getCurrencySymbol().length()).trim()); + Trade t = new Trade(value, ess); + t.pay(user, OverflowType.DROP); + continue; + } - final MetaItemStack metaStack = new MetaItemStack(parseStack); + final String[] parts = kitItem.split(" +"); + final ItemStack parseStack = ess.getItemDb().get(parts[0], parts.length > 1 ? Integer.parseInt(parts[1]) : 1); - if (parts.length > 2) - { - // We pass a null sender here because kits should not do perm checks - metaStack.parseStringMeta(null, allowUnsafe, parts, 2, ess); - } + if (parseStack.getType() == Material.AIR) { + continue; + } - final Map overfilled; - final boolean allowOversizedStacks = user.isAuthorized("essentials.oversizedstacks"); - if (allowOversizedStacks) - { - overfilled = InventoryWorkaround.addOversizedItems(user.getBase().getInventory(), ess.getSettings().getOversizedStackSize(), metaStack.getItemStack()); - } - else - { - overfilled = InventoryWorkaround.addItems(user.getBase().getInventory(), metaStack.getItemStack()); - } - for (ItemStack itemStack : overfilled.values()) - { - int spillAmount = itemStack.getAmount(); - if (!allowOversizedStacks) - { - itemStack.setAmount(spillAmount < itemStack.getMaxStackSize() ? spillAmount : itemStack.getMaxStackSize()); - } - while (spillAmount > 0) - { - user.getWorld().dropItemNaturally(user.getLocation(), itemStack); - spillAmount -= itemStack.getAmount(); - } - spew = true; - } - } - user.getBase().updateInventory(); - if (spew) - { - user.sendMessage(tl("kitInvFull")); - } - } - catch (Exception e) - { - user.getBase().updateInventory(); - ess.getLogger().log(Level.WARNING, e.getMessage()); - throw new Exception(tl("kitError2"), e); - } - } + final MetaItemStack metaStack = new MetaItemStack(parseStack); + + if (parts.length > 2) { + // We pass a null sender here because kits should not do perm checks + metaStack.parseStringMeta(null, allowUnsafe, parts, 2, ess); + } + + final Map overfilled; + final boolean allowOversizedStacks = user.isAuthorized("essentials.oversizedstacks"); + if (allowOversizedStacks) { + overfilled = InventoryWorkaround.addOversizedItems(user.getBase().getInventory(), ess.getSettings().getOversizedStackSize(), metaStack.getItemStack()); + } else { + overfilled = InventoryWorkaround.addItems(user.getBase().getInventory(), metaStack.getItemStack()); + } + for (ItemStack itemStack : overfilled.values()) { + int spillAmount = itemStack.getAmount(); + if (!allowOversizedStacks) { + itemStack.setAmount(spillAmount < itemStack.getMaxStackSize() ? spillAmount : itemStack.getMaxStackSize()); + } + while (spillAmount > 0) { + user.getWorld().dropItemNaturally(user.getLocation(), itemStack); + spillAmount -= itemStack.getAmount(); + } + spew = true; + } + } + user.getBase().updateInventory(); + if (spew) { + user.sendMessage(tl("kitInvFull")); + } + } catch (Exception e) { + user.getBase().updateInventory(); + ess.getLogger().log(Level.WARNING, e.getMessage()); + throw new Exception(tl("kitError2"), e); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/LocationTarget.java b/Essentials/src/com/earth2me/essentials/LocationTarget.java index 1641373af..5d3ca71a1 100644 --- a/Essentials/src/com/earth2me/essentials/LocationTarget.java +++ b/Essentials/src/com/earth2me/essentials/LocationTarget.java @@ -3,18 +3,15 @@ package com.earth2me.essentials; import org.bukkit.Location; -public class LocationTarget implements ITarget -{ - private final Location location; +public class LocationTarget implements ITarget { + private final Location location; - LocationTarget(Location location) - { - this.location = location; - } + LocationTarget(Location location) { + this.location = location; + } - @Override - public Location getLocation() - { - return location; - } + @Override + public Location getLocation() { + return location; + } } \ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/ManagedFile.java b/Essentials/src/com/earth2me/essentials/ManagedFile.java index 3fa46d5c3..6d86ea52c 100644 --- a/Essentials/src/com/earth2me/essentials/ManagedFile.java +++ b/Essentials/src/com/earth2me/essentials/ManagedFile.java @@ -1,6 +1,8 @@ package com.earth2me.essentials; -import static com.earth2me.essentials.I18n.tl; +import net.ess3.api.IEssentials; +import org.bukkit.Bukkit; + import java.io.*; import java.math.BigInteger; import java.security.DigestInputStream; @@ -11,218 +13,155 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.logging.Level; -import net.ess3.api.IEssentials; -import org.bukkit.Bukkit; + +import static com.earth2me.essentials.I18n.tl; -public class ManagedFile -{ - private static final int BUFFERSIZE = 1024 * 8; - private final transient File file; +public class ManagedFile { + private static final int BUFFERSIZE = 1024 * 8; + private final transient File file; - public ManagedFile(final String filename, final IEssentials ess) - { - file = new File(ess.getDataFolder(), filename); + 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 { + 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, tl("itemsCsvNotLoaded"), ex); - } - } - } + if (!file.exists()) { + try { + copyResourceAscii("/" + filename, file); + } catch (IOException ex) { + Bukkit.getLogger().log(Level.SEVERE, tl("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 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 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 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(); - } - } + 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/MetaItemStack.java b/Essentials/src/com/earth2me/essentials/MetaItemStack.java index c39028627..6c223e1de 100644 --- a/Essentials/src/com/earth2me/essentials/MetaItemStack.java +++ b/Essentials/src/com/earth2me/essentials/MetaItemStack.java @@ -1,16 +1,11 @@ package com.earth2me.essentials; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.textreader.BookInput; import com.earth2me.essentials.textreader.BookPager; import com.earth2me.essentials.textreader.IText; import com.earth2me.essentials.utils.FormatUtil; import com.earth2me.essentials.utils.NumberUtil; -import java.util.*; -import java.util.regex.Pattern; - import com.google.common.base.Joiner; -import java.util.logging.Level; import net.ess3.api.IEssentials; import org.bukkit.Color; import org.bukkit.DyeColor; @@ -22,556 +17,405 @@ import org.bukkit.inventory.meta.*; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; +import java.util.*; +import java.util.logging.Level; +import java.util.regex.Pattern; -public class MetaItemStack -{ - private static final Map colorMap = new HashMap(); - private static final Map fireworkShape = new HashMap(); +import static com.earth2me.essentials.I18n.tl; - static - { - for (DyeColor color : DyeColor.values()) - { - colorMap.put(color.name(), color); - } - for (FireworkEffect.Type type : FireworkEffect.Type.values()) - { - fireworkShape.put(type.name(), type); - } - } - private final transient Pattern splitPattern = Pattern.compile("[:+',;.]"); - private ItemStack stack; - private FireworkEffect.Builder builder = FireworkEffect.builder(); - private PotionEffectType pEffectType; - private PotionEffect pEffect; - private boolean validFirework = false; - private boolean validPotionEffect = false; - private boolean validPotionDuration = false; - private boolean validPotionPower = false; - private boolean completePotion = false; - private int power = 1; - private int duration = 120; - public MetaItemStack(final ItemStack stack) - { - this.stack = stack.clone(); - } +public class MetaItemStack { + private static final Map colorMap = new HashMap(); + private static final Map fireworkShape = new HashMap(); - public ItemStack getItemStack() - { - return stack; - } + static { + for (DyeColor color : DyeColor.values()) { + colorMap.put(color.name(), color); + } + for (FireworkEffect.Type type : FireworkEffect.Type.values()) { + fireworkShape.put(type.name(), type); + } + } - public boolean isValidFirework() - { - return validFirework; - } + private final transient Pattern splitPattern = Pattern.compile("[:+',;.]"); + private ItemStack stack; + private FireworkEffect.Builder builder = FireworkEffect.builder(); + private PotionEffectType pEffectType; + private PotionEffect pEffect; + private boolean validFirework = false; + private boolean validPotionEffect = false; + private boolean validPotionDuration = false; + private boolean validPotionPower = false; + private boolean completePotion = false; + private int power = 1; + private int duration = 120; - public boolean isValidPotion() - { - return validPotionEffect && validPotionDuration && validPotionPower; - } + public MetaItemStack(final ItemStack stack) { + this.stack = stack.clone(); + } - public FireworkEffect.Builder getFireworkBuilder() - { - return builder; - } + public ItemStack getItemStack() { + return stack; + } - public PotionEffect getPotionEffect() - { - return pEffect; - } + public boolean isValidFirework() { + return validFirework; + } - public boolean completePotion() - { - return completePotion; - } + public boolean isValidPotion() { + return validPotionEffect && validPotionDuration && validPotionPower; + } - private void resetPotionMeta() - { - pEffect = null; - pEffectType = null; - validPotionEffect = false; - validPotionDuration = false; - validPotionPower = false; - completePotion = true; - } + public FireworkEffect.Builder getFireworkBuilder() { + return builder; + } - public boolean canSpawn(final IEssentials ess) - { - try - { - ess.getServer().getUnsafe().modifyItemStack(stack, "{}"); - return true; - } - catch (NullPointerException npe) - { - if (ess.getSettings().isDebug()) - { - ess.getLogger().log(Level.INFO, "Itemstack is invalid", npe); - } - return false; - } - catch (NoSuchMethodError nsme) - { - return true; - } - catch (Throwable throwable) - { - if (ess.getSettings().isDebug()) - { - ess.getLogger().log(Level.INFO, "Itemstack is invalid", throwable); - } - return false; - } - } + public PotionEffect getPotionEffect() { + return pEffect; + } - public void parseStringMeta(final CommandSource sender, final boolean allowUnsafe, String[] string, int fromArg, final IEssentials ess) throws Exception - { - if (string[fromArg].startsWith("{") && hasMetaPermission(sender, "vanilla", false, true, ess)) - { - try - { - stack = ess.getServer().getUnsafe().modifyItemStack(stack, Joiner.on(' ').join(Arrays.asList(string).subList(fromArg, string.length))); - } - catch (NullPointerException npe) - { - if (ess.getSettings().isDebug()) - { - ess.getLogger().log(Level.INFO, "Itemstack is invalid", npe); - } - } - catch (NoSuchMethodError nsme) - { - throw new Exception(tl("noMetaJson"), nsme); - } - catch (Throwable throwable) - { - throw new Exception(throwable.getMessage(), throwable); - } - } - else - { - for (int i = fromArg; i < string.length; i++) - { - addStringMeta(sender, allowUnsafe, string[i], ess); - } - if (validFirework) - { - if (!hasMetaPermission(sender, "firework", true, true, ess)) - { - throw new Exception(tl("noMetaFirework")); - } - FireworkEffect effect = builder.build(); - FireworkMeta fmeta = (FireworkMeta)stack.getItemMeta(); - fmeta.addEffect(effect); - if (fmeta.getEffects().size() > 1 && !hasMetaPermission(sender, "firework-multiple", true, true, ess)) - { - throw new Exception(tl("multipleCharges")); - } - stack.setItemMeta(fmeta); - } - } - } + public boolean completePotion() { + return completePotion; + } - public void addStringMeta(final CommandSource sender, final boolean allowUnsafe, final String string, final IEssentials ess) throws Exception - { - final String[] split = splitPattern.split(string, 2); - if (split.length < 1) - { - return; - } + private void resetPotionMeta() { + pEffect = null; + pEffectType = null; + validPotionEffect = false; + validPotionDuration = false; + validPotionPower = false; + completePotion = true; + } - if (split.length > 1 && split[0].equalsIgnoreCase("name") && hasMetaPermission(sender, "name", false, true, ess)) - { - final String displayName = FormatUtil.replaceFormat(split[1].replace('_', ' ')); - final ItemMeta meta = stack.getItemMeta(); - meta.setDisplayName(displayName); - stack.setItemMeta(meta); - } - else if (split.length > 1 && (split[0].equalsIgnoreCase("lore") || split[0].equalsIgnoreCase("desc")) && hasMetaPermission(sender, "lore", false, true, ess)) - { - final List lore = new ArrayList(); - for (String line : split[1].split("\\|")) - { - lore.add(FormatUtil.replaceFormat(line.replace('_', ' '))); - } - final ItemMeta meta = stack.getItemMeta(); - meta.setLore(lore); - stack.setItemMeta(meta); - } - else if (split.length > 1 && (split[0].equalsIgnoreCase("player") || split[0].equalsIgnoreCase("owner")) && stack.getType() == Material.SKULL_ITEM && hasMetaPermission(sender, "head", false, true, ess)) - { - if (stack.getDurability() == 3) - { - final String owner = split[1]; - final SkullMeta meta = (SkullMeta)stack.getItemMeta(); - meta.setOwner(owner); - stack.setItemMeta(meta); - } - else - { - throw new Exception(tl("onlyPlayerSkulls")); - } - } - else if (split.length > 1 && split[0].equalsIgnoreCase("book") && stack.getType() == Material.WRITTEN_BOOK - && (hasMetaPermission(sender, "book", true, true, ess) || hasMetaPermission(sender, "chapter-" + split[1].toLowerCase(Locale.ENGLISH), true, true, ess))) - { - final BookMeta meta = (BookMeta)stack.getItemMeta(); - final IText input = new BookInput("book", true, ess); - final BookPager pager = new BookPager(input); + public boolean canSpawn(final IEssentials ess) { + try { + ess.getServer().getUnsafe().modifyItemStack(stack, "{}"); + return true; + } catch (NullPointerException npe) { + if (ess.getSettings().isDebug()) { + ess.getLogger().log(Level.INFO, "Itemstack is invalid", npe); + } + return false; + } catch (NoSuchMethodError nsme) { + return true; + } catch (Throwable throwable) { + if (ess.getSettings().isDebug()) { + ess.getLogger().log(Level.INFO, "Itemstack is invalid", throwable); + } + return false; + } + } - List pages = pager.getPages(split[1]); - meta.setPages(pages); - stack.setItemMeta(meta); - } - else if (split.length > 1 && split[0].equalsIgnoreCase("author") && stack.getType() == Material.WRITTEN_BOOK && hasMetaPermission(sender, "author", false, true, ess)) - { - final String author = FormatUtil.replaceFormat(split[1]); - final BookMeta meta = (BookMeta)stack.getItemMeta(); - meta.setAuthor(author); - stack.setItemMeta(meta); - } - else if (split.length > 1 && split[0].equalsIgnoreCase("title") && stack.getType() == Material.WRITTEN_BOOK && hasMetaPermission(sender, "title", false, true, ess)) - { - final String title = FormatUtil.replaceFormat(split[1].replace('_', ' ')); - final BookMeta meta = (BookMeta)stack.getItemMeta(); - meta.setTitle(title); - stack.setItemMeta(meta); - } - else if (split.length > 1 && split[0].equalsIgnoreCase("power") && stack.getType() == Material.FIREWORK && hasMetaPermission(sender, "firework-power", false, true, ess)) - { - final int power = NumberUtil.isInt(split[1]) ? Integer.parseInt(split[1]) : 0; - final FireworkMeta meta = (FireworkMeta)stack.getItemMeta(); - meta.setPower(power > 3 ? 4 : power); - stack.setItemMeta(meta); - } - else if (stack.getType() == Material.FIREWORK) //WARNING - Meta for fireworks will be ignored after this point. - { - addFireworkMeta(sender, false, string, ess); - } - else if (stack.getType() == Material.POTION) //WARNING - Meta for potions will be ignored after this point. - { - addPotionMeta(sender, false, string, ess); - } - else if (split.length > 1 && (split[0].equalsIgnoreCase("color") || split[0].equalsIgnoreCase("colour")) - && (stack.getType() == Material.LEATHER_BOOTS - || stack.getType() == Material.LEATHER_CHESTPLATE - || stack.getType() == Material.LEATHER_HELMET - || stack.getType() == Material.LEATHER_LEGGINGS)) - { - final String[] color = split[1].split("(\\||,)"); - if (color.length == 3) - { - final int red = NumberUtil.isInt(color[0]) ? Integer.parseInt(color[0]) : 0; - final int green = NumberUtil.isInt(color[1]) ? Integer.parseInt(color[1]) : 0; - final int blue = NumberUtil.isInt(color[2]) ? Integer.parseInt(color[2]) : 0; - final LeatherArmorMeta meta = (LeatherArmorMeta)stack.getItemMeta(); - meta.setColor(Color.fromRGB(red, green, blue)); - stack.setItemMeta(meta); - } - else - { - throw new Exception(tl("leatherSyntax")); - } - } - else - { - parseEnchantmentStrings(sender, allowUnsafe, split, ess); - } - } + public void parseStringMeta(final CommandSource sender, final boolean allowUnsafe, String[] string, int fromArg, final IEssentials ess) throws Exception { + if (string[fromArg].startsWith("{") && hasMetaPermission(sender, "vanilla", false, true, ess)) { + try { + stack = ess.getServer().getUnsafe().modifyItemStack(stack, Joiner.on(' ').join(Arrays.asList(string).subList(fromArg, string.length))); + } catch (NullPointerException npe) { + if (ess.getSettings().isDebug()) { + ess.getLogger().log(Level.INFO, "Itemstack is invalid", npe); + } + } catch (NoSuchMethodError nsme) { + throw new Exception(tl("noMetaJson"), nsme); + } catch (Throwable throwable) { + throw new Exception(throwable.getMessage(), throwable); + } + } else { + for (int i = fromArg; i < string.length; i++) { + addStringMeta(sender, allowUnsafe, string[i], ess); + } + if (validFirework) { + if (!hasMetaPermission(sender, "firework", true, true, ess)) { + throw new Exception(tl("noMetaFirework")); + } + FireworkEffect effect = builder.build(); + FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta(); + fmeta.addEffect(effect); + if (fmeta.getEffects().size() > 1 && !hasMetaPermission(sender, "firework-multiple", true, true, ess)) { + throw new Exception(tl("multipleCharges")); + } + stack.setItemMeta(fmeta); + } + } + } - public void addFireworkMeta(final CommandSource sender, final boolean allowShortName, final String string, final IEssentials ess) throws Exception - { - if (stack.getType() == Material.FIREWORK) - { - final String[] split = splitPattern.split(string, 2); + public void addStringMeta(final CommandSource sender, final boolean allowUnsafe, final String string, final IEssentials ess) throws Exception { + final String[] split = splitPattern.split(string, 2); + if (split.length < 1) { + return; + } - if (split.length < 2) - { - return; - } + if (split.length > 1 && split[0].equalsIgnoreCase("name") && hasMetaPermission(sender, "name", false, true, ess)) { + final String displayName = FormatUtil.replaceFormat(split[1].replace('_', ' ')); + final ItemMeta meta = stack.getItemMeta(); + meta.setDisplayName(displayName); + stack.setItemMeta(meta); + } else if (split.length > 1 && (split[0].equalsIgnoreCase("lore") || split[0].equalsIgnoreCase("desc")) && hasMetaPermission(sender, "lore", false, true, ess)) { + final List lore = new ArrayList(); + for (String line : split[1].split("\\|")) { + lore.add(FormatUtil.replaceFormat(line.replace('_', ' '))); + } + final ItemMeta meta = stack.getItemMeta(); + meta.setLore(lore); + stack.setItemMeta(meta); + } else if (split.length > 1 && (split[0].equalsIgnoreCase("player") || split[0].equalsIgnoreCase("owner")) && stack.getType() == Material.SKULL_ITEM && hasMetaPermission(sender, "head", false, true, ess)) { + if (stack.getDurability() == 3) { + final String owner = split[1]; + final SkullMeta meta = (SkullMeta) stack.getItemMeta(); + meta.setOwner(owner); + stack.setItemMeta(meta); + } else { + throw new Exception(tl("onlyPlayerSkulls")); + } + } else if (split.length > 1 && split[0].equalsIgnoreCase("book") && stack.getType() == Material.WRITTEN_BOOK && (hasMetaPermission(sender, "book", true, true, ess) || hasMetaPermission(sender, "chapter-" + split[1].toLowerCase(Locale.ENGLISH), true, true, ess))) { + final BookMeta meta = (BookMeta) stack.getItemMeta(); + final IText input = new BookInput("book", true, ess); + final BookPager pager = new BookPager(input); - if (split[0].equalsIgnoreCase("color") || split[0].equalsIgnoreCase("colour") || (allowShortName && split[0].equalsIgnoreCase("c"))) - { - if (validFirework) - { - if (!hasMetaPermission(sender, "firework", true, true, ess)) - { - throw new Exception(tl("noMetaFirework")); - } - FireworkEffect effect = builder.build(); - FireworkMeta fmeta = (FireworkMeta)stack.getItemMeta(); - fmeta.addEffect(effect); - if (fmeta.getEffects().size() > 1 && !hasMetaPermission(sender, "firework-multiple", true, true, ess)) - { - throw new Exception(tl("multipleCharges")); - } - stack.setItemMeta(fmeta); - builder = FireworkEffect.builder(); - } + List pages = pager.getPages(split[1]); + meta.setPages(pages); + stack.setItemMeta(meta); + } else if (split.length > 1 && split[0].equalsIgnoreCase("author") && stack.getType() == Material.WRITTEN_BOOK && hasMetaPermission(sender, "author", false, true, ess)) { + final String author = FormatUtil.replaceFormat(split[1]); + final BookMeta meta = (BookMeta) stack.getItemMeta(); + meta.setAuthor(author); + stack.setItemMeta(meta); + } else if (split.length > 1 && split[0].equalsIgnoreCase("title") && stack.getType() == Material.WRITTEN_BOOK && hasMetaPermission(sender, "title", false, true, ess)) { + final String title = FormatUtil.replaceFormat(split[1].replace('_', ' ')); + final BookMeta meta = (BookMeta) stack.getItemMeta(); + meta.setTitle(title); + stack.setItemMeta(meta); + } else if (split.length > 1 && split[0].equalsIgnoreCase("power") && stack.getType() == Material.FIREWORK && hasMetaPermission(sender, "firework-power", false, true, ess)) { + final int power = NumberUtil.isInt(split[1]) ? Integer.parseInt(split[1]) : 0; + final FireworkMeta meta = (FireworkMeta) stack.getItemMeta(); + meta.setPower(power > 3 ? 4 : power); + stack.setItemMeta(meta); + } else if (stack.getType() == Material.FIREWORK) //WARNING - Meta for fireworks will be ignored after this point. + { + addFireworkMeta(sender, false, string, ess); + } else if (stack.getType() == Material.POTION) //WARNING - Meta for potions will be ignored after this point. + { + addPotionMeta(sender, false, string, ess); + } else if (split.length > 1 && (split[0].equalsIgnoreCase("color") || split[0].equalsIgnoreCase("colour")) && (stack.getType() == Material.LEATHER_BOOTS || stack.getType() == Material.LEATHER_CHESTPLATE || stack.getType() == Material.LEATHER_HELMET || stack.getType() == Material.LEATHER_LEGGINGS)) { + final String[] color = split[1].split("(\\||,)"); + if (color.length == 3) { + final int red = NumberUtil.isInt(color[0]) ? Integer.parseInt(color[0]) : 0; + final int green = NumberUtil.isInt(color[1]) ? Integer.parseInt(color[1]) : 0; + final int blue = NumberUtil.isInt(color[2]) ? Integer.parseInt(color[2]) : 0; + final LeatherArmorMeta meta = (LeatherArmorMeta) stack.getItemMeta(); + meta.setColor(Color.fromRGB(red, green, blue)); + stack.setItemMeta(meta); + } else { + throw new Exception(tl("leatherSyntax")); + } + } else { + parseEnchantmentStrings(sender, allowUnsafe, split, ess); + } + } - List primaryColors = new ArrayList(); - String[] colors = split[1].split(","); - for (String color : colors) - { - if (colorMap.containsKey(color.toUpperCase())) - { - validFirework = true; - primaryColors.add(colorMap.get(color.toUpperCase()).getFireworkColor()); - } - else - { - throw new Exception(tl("invalidFireworkFormat", split[1], split[0])); - } - } - builder.withColor(primaryColors); - } - else if (split[0].equalsIgnoreCase("shape") || split[0].equalsIgnoreCase("type") || (allowShortName && (split[0].equalsIgnoreCase("s") || split[0].equalsIgnoreCase("t")))) - { - FireworkEffect.Type finalEffect = null; - split[1] = (split[1].equalsIgnoreCase("large") ? "BALL_LARGE" : split[1]); - if (fireworkShape.containsKey(split[1].toUpperCase())) - { - finalEffect = fireworkShape.get(split[1].toUpperCase()); - } - else - { - throw new Exception(tl("invalidFireworkFormat", split[1], split[0])); - } - if (finalEffect != null) - { - builder.with(finalEffect); - } - } - else if (split[0].equalsIgnoreCase("fade") || (allowShortName && split[0].equalsIgnoreCase("f"))) - { - List fadeColors = new ArrayList(); - String[] colors = split[1].split(","); - for (String color : colors) - { - if (colorMap.containsKey(color.toUpperCase())) - { - fadeColors.add(colorMap.get(color.toUpperCase()).getFireworkColor()); - } - else - { - throw new Exception(tl("invalidFireworkFormat", split[1], split[0])); - } - } - if (!fadeColors.isEmpty()) - { - builder.withFade(fadeColors); - } - } - else if (split[0].equalsIgnoreCase("effect") || (allowShortName && split[0].equalsIgnoreCase("e"))) - { - String[] effects = split[1].split(","); - for (String effect : effects) - { - if (effect.equalsIgnoreCase("twinkle")) - { - builder.flicker(true); - } - else if (effect.equalsIgnoreCase("trail")) - { - builder.trail(true); - } - else - { - throw new Exception(tl("invalidFireworkFormat", split[1], split[0])); - } - } - } - } - } + public void addFireworkMeta(final CommandSource sender, final boolean allowShortName, final String string, final IEssentials ess) throws Exception { + if (stack.getType() == Material.FIREWORK) { + final String[] split = splitPattern.split(string, 2); - public void addPotionMeta(final CommandSource sender, final boolean allowShortName, final String string, final IEssentials ess) throws Exception - { - if (stack.getType() == Material.POTION) - { - final String[] split = splitPattern.split(string, 2); + if (split.length < 2) { + return; + } - if (split.length < 2) - { - return; - } + if (split[0].equalsIgnoreCase("color") || split[0].equalsIgnoreCase("colour") || (allowShortName && split[0].equalsIgnoreCase("c"))) { + if (validFirework) { + if (!hasMetaPermission(sender, "firework", true, true, ess)) { + throw new Exception(tl("noMetaFirework")); + } + FireworkEffect effect = builder.build(); + FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta(); + fmeta.addEffect(effect); + if (fmeta.getEffects().size() > 1 && !hasMetaPermission(sender, "firework-multiple", true, true, ess)) { + throw new Exception(tl("multipleCharges")); + } + stack.setItemMeta(fmeta); + builder = FireworkEffect.builder(); + } - if (split[0].equalsIgnoreCase("effect") || (allowShortName && split[0].equalsIgnoreCase("e"))) - { - pEffectType = Potions.getByName(split[1]); - if (pEffectType != null && pEffectType.getName() != null) - { - if (hasMetaPermission(sender, "potions." + pEffectType.getName().toLowerCase(Locale.ENGLISH), true, false, ess)) - { - validPotionEffect = true; - } - else - { - throw new Exception(tl("noPotionEffectPerm", pEffectType.getName().toLowerCase(Locale.ENGLISH))); - } - } - else - { - throw new Exception(tl("invalidPotionMeta", split[1])); - } - } - else if (split[0].equalsIgnoreCase("power") || (allowShortName && split[0].equalsIgnoreCase("p"))) - { - if (NumberUtil.isInt(split[1])) - { - validPotionPower = true; - power = Integer.parseInt(split[1]); - if (power > 0 && power < 4) - { - power -= 1; - } - } - else - { - throw new Exception(tl("invalidPotionMeta", split[1])); - } - } - else if (split[0].equalsIgnoreCase("duration") || (allowShortName && split[0].equalsIgnoreCase("d"))) - { - if (NumberUtil.isInt(split[1])) - { - validPotionDuration = true; - duration = Integer.parseInt(split[1]) * 20; //Duration is in ticks by default, converted to seconds - } - else - { - throw new Exception(tl("invalidPotionMeta", split[1])); - } - } + List primaryColors = new ArrayList(); + String[] colors = split[1].split(","); + for (String color : colors) { + if (colorMap.containsKey(color.toUpperCase())) { + validFirework = true; + primaryColors.add(colorMap.get(color.toUpperCase()).getFireworkColor()); + } else { + throw new Exception(tl("invalidFireworkFormat", split[1], split[0])); + } + } + builder.withColor(primaryColors); + } else if (split[0].equalsIgnoreCase("shape") || split[0].equalsIgnoreCase("type") || (allowShortName && (split[0].equalsIgnoreCase("s") || split[0].equalsIgnoreCase("t")))) { + FireworkEffect.Type finalEffect = null; + split[1] = (split[1].equalsIgnoreCase("large") ? "BALL_LARGE" : split[1]); + if (fireworkShape.containsKey(split[1].toUpperCase())) { + finalEffect = fireworkShape.get(split[1].toUpperCase()); + } else { + throw new Exception(tl("invalidFireworkFormat", split[1], split[0])); + } + if (finalEffect != null) { + builder.with(finalEffect); + } + } else if (split[0].equalsIgnoreCase("fade") || (allowShortName && split[0].equalsIgnoreCase("f"))) { + List fadeColors = new ArrayList(); + String[] colors = split[1].split(","); + for (String color : colors) { + if (colorMap.containsKey(color.toUpperCase())) { + fadeColors.add(colorMap.get(color.toUpperCase()).getFireworkColor()); + } else { + throw new Exception(tl("invalidFireworkFormat", split[1], split[0])); + } + } + if (!fadeColors.isEmpty()) { + builder.withFade(fadeColors); + } + } else if (split[0].equalsIgnoreCase("effect") || (allowShortName && split[0].equalsIgnoreCase("e"))) { + String[] effects = split[1].split(","); + for (String effect : effects) { + if (effect.equalsIgnoreCase("twinkle")) { + builder.flicker(true); + } else if (effect.equalsIgnoreCase("trail")) { + builder.trail(true); + } else { + throw new Exception(tl("invalidFireworkFormat", split[1], split[0])); + } + } + } + } + } - if (isValidPotion()) - { - PotionMeta pmeta = (PotionMeta)stack.getItemMeta(); - pEffect = pEffectType.createEffect(duration, power); - if (pmeta.getCustomEffects().size() > 1 && !hasMetaPermission(sender, "potions.multiple", true, false, ess)) - { - throw new Exception(tl("multiplePotionEffects")); - } - pmeta.addCustomEffect(pEffect, true); - stack.setItemMeta(pmeta); - resetPotionMeta(); - } - } - } + public void addPotionMeta(final CommandSource sender, final boolean allowShortName, final String string, final IEssentials ess) throws Exception { + if (stack.getType() == Material.POTION) { + final String[] split = splitPattern.split(string, 2); - private void parseEnchantmentStrings(final CommandSource sender, final boolean allowUnsafe, final String[] split, final IEssentials ess) throws Exception - { - final Enchantment enchantment = Enchantments.getByName(split[0]); - if (enchantment == null || !hasMetaPermission(sender, "enchantments." + enchantment.getName().toLowerCase(Locale.ENGLISH), false, false, ess)) - { - return; - } + if (split.length < 2) { + return; + } - int level = -1; - if (split.length > 1) - { - try - { - level = Integer.parseInt(split[1]); - } - catch (NumberFormatException ex) - { - level = -1; - } - } + if (split[0].equalsIgnoreCase("effect") || (allowShortName && split[0].equalsIgnoreCase("e"))) { + pEffectType = Potions.getByName(split[1]); + if (pEffectType != null && pEffectType.getName() != null) { + if (hasMetaPermission(sender, "potions." + pEffectType.getName().toLowerCase(Locale.ENGLISH), true, false, ess)) { + validPotionEffect = true; + } else { + throw new Exception(tl("noPotionEffectPerm", pEffectType.getName().toLowerCase(Locale.ENGLISH))); + } + } else { + throw new Exception(tl("invalidPotionMeta", split[1])); + } + } else if (split[0].equalsIgnoreCase("power") || (allowShortName && split[0].equalsIgnoreCase("p"))) { + if (NumberUtil.isInt(split[1])) { + validPotionPower = true; + power = Integer.parseInt(split[1]); + if (power > 0 && power < 4) { + power -= 1; + } + } else { + throw new Exception(tl("invalidPotionMeta", split[1])); + } + } else if (split[0].equalsIgnoreCase("duration") || (allowShortName && split[0].equalsIgnoreCase("d"))) { + if (NumberUtil.isInt(split[1])) { + validPotionDuration = true; + duration = Integer.parseInt(split[1]) * 20; //Duration is in ticks by default, converted to seconds + } else { + throw new Exception(tl("invalidPotionMeta", split[1])); + } + } - if (level < 0 || (!allowUnsafe && level > enchantment.getMaxLevel())) - { - level = enchantment.getMaxLevel(); - } - addEnchantment(sender, allowUnsafe, enchantment, level); - } + if (isValidPotion()) { + PotionMeta pmeta = (PotionMeta) stack.getItemMeta(); + pEffect = pEffectType.createEffect(duration, power); + if (pmeta.getCustomEffects().size() > 1 && !hasMetaPermission(sender, "potions.multiple", true, false, ess)) { + throw new Exception(tl("multiplePotionEffects")); + } + pmeta.addCustomEffect(pEffect, true); + stack.setItemMeta(pmeta); + resetPotionMeta(); + } + } + } - public void addEnchantment(final CommandSource sender, final boolean allowUnsafe, final Enchantment enchantment, final int level) throws Exception - { - if (enchantment == null) - { - throw new Exception(tl("enchantmentNotFound")); - } - try - { - if (stack.getType().equals(Material.ENCHANTED_BOOK)) - { - EnchantmentStorageMeta meta = (EnchantmentStorageMeta)stack.getItemMeta(); - if (level == 0) - { - meta.removeStoredEnchant(enchantment); - } - else - { - meta.addStoredEnchant(enchantment, level, allowUnsafe); - } - stack.setItemMeta(meta); - } - else // all other material types besides ENCHANTED_BOOK - { - if (level == 0) - { - stack.removeEnchantment(enchantment); - } - else - { - if (allowUnsafe) - { - stack.addUnsafeEnchantment(enchantment, level); - } - else - { - stack.addEnchantment(enchantment, level); - } - } - } - } - catch (Exception ex) - { - throw new Exception("Enchantment " + enchantment.getName() + ": " + ex.getMessage(), ex); - } - } + private void parseEnchantmentStrings(final CommandSource sender, final boolean allowUnsafe, final String[] split, final IEssentials ess) throws Exception { + final Enchantment enchantment = Enchantments.getByName(split[0]); + if (enchantment == null || !hasMetaPermission(sender, "enchantments." + enchantment.getName().toLowerCase(Locale.ENGLISH), false, false, ess)) { + return; + } - public Enchantment getEnchantment(final User user, final String name) throws Exception - { - final Enchantment enchantment = Enchantments.getByName(name); - if (enchantment == null) - { - return null; - } + int level = -1; + if (split.length > 1) { + try { + level = Integer.parseInt(split[1]); + } catch (NumberFormatException ex) { + level = -1; + } + } - final String enchantmentName = enchantment.getName().toLowerCase(Locale.ENGLISH); + if (level < 0 || (!allowUnsafe && level > enchantment.getMaxLevel())) { + level = enchantment.getMaxLevel(); + } + addEnchantment(sender, allowUnsafe, enchantment, level); + } - if (!hasMetaPermission(user, "enchantments." + enchantmentName, true, false)) - { - throw new Exception(tl("enchantmentPerm", enchantmentName)); - } - return enchantment; - } + public void addEnchantment(final CommandSource sender, final boolean allowUnsafe, final Enchantment enchantment, final int level) throws Exception { + if (enchantment == null) { + throw new Exception(tl("enchantmentNotFound")); + } + try { + if (stack.getType().equals(Material.ENCHANTED_BOOK)) { + EnchantmentStorageMeta meta = (EnchantmentStorageMeta) stack.getItemMeta(); + if (level == 0) { + meta.removeStoredEnchant(enchantment); + } else { + meta.addStoredEnchant(enchantment, level, allowUnsafe); + } + stack.setItemMeta(meta); + } else // all other material types besides ENCHANTED_BOOK + { + if (level == 0) { + stack.removeEnchantment(enchantment); + } else { + if (allowUnsafe) { + stack.addUnsafeEnchantment(enchantment, level); + } else { + stack.addEnchantment(enchantment, level); + } + } + } + } catch (Exception ex) { + throw new Exception("Enchantment " + enchantment.getName() + ": " + ex.getMessage(), ex); + } + } - private boolean hasMetaPermission(final CommandSource sender, final String metaPerm, final boolean graceful, final boolean includeBase, final IEssentials ess) throws Exception - { - final User user = sender != null && sender.isPlayer() ? ess.getUser(sender.getPlayer()) : null; - return hasMetaPermission(user, metaPerm, graceful, includeBase); - } + public Enchantment getEnchantment(final User user, final String name) throws Exception { + final Enchantment enchantment = Enchantments.getByName(name); + if (enchantment == null) { + return null; + } - private boolean hasMetaPermission(final User user, final String metaPerm, final boolean graceful, final boolean includeBase) throws Exception - { - final String permBase = includeBase ? "essentials.itemspawn.meta-" : "essentials."; - if (user == null || user.isAuthorized(permBase + metaPerm)) - { - return true; - } + final String enchantmentName = enchantment.getName().toLowerCase(Locale.ENGLISH); - if (graceful) - { - return false; - } - else - { - throw new Exception(tl("noMetaPerm", metaPerm)); - } - } + if (!hasMetaPermission(user, "enchantments." + enchantmentName, true, false)) { + throw new Exception(tl("enchantmentPerm", enchantmentName)); + } + return enchantment; + } + + private boolean hasMetaPermission(final CommandSource sender, final String metaPerm, final boolean graceful, final boolean includeBase, final IEssentials ess) throws Exception { + final User user = sender != null && sender.isPlayer() ? ess.getUser(sender.getPlayer()) : null; + return hasMetaPermission(user, metaPerm, graceful, includeBase); + } + + private boolean hasMetaPermission(final User user, final String metaPerm, final boolean graceful, final boolean includeBase) throws Exception { + final String permBase = includeBase ? "essentials.itemspawn.meta-" : "essentials."; + if (user == null || user.isAuthorized(permBase + metaPerm)) { + return true; + } + + if (graceful) { + return false; + } else { + throw new Exception(tl("noMetaPerm", metaPerm)); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/Mob.java b/Essentials/src/com/earth2me/essentials/Mob.java index 712f5cc0f..67edcf344 100644 --- a/Essentials/src/com/earth2me/essentials/Mob.java +++ b/Essentials/src/com/earth2me/essentials/Mob.java @@ -1,138 +1,128 @@ package com.earth2me.essentials; -import static com.earth2me.essentials.I18n.tl; -import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; import org.bukkit.Location; import org.bukkit.Server; import org.bukkit.World; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; +import java.util.*; +import java.util.logging.Level; +import java.util.logging.Logger; + +import static com.earth2me.essentials.I18n.tl; + // Suffixes can be appended on the end of a mob name to make it plural // Entities without a suffix, will default to 's' -public enum Mob -{ - 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), - HORSE("Horse", Enemies.FRIENDLY, EntityType.HORSE), - 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), - WITHER("Wither", Enemies.ENEMY, EntityType.WITHER), - BAT("Bat", Enemies.FRIENDLY, EntityType.BAT), - WITCH("Witch", Enemies.ENEMY, EntityType.WITCH), - BOAT("Boat", Enemies.NEUTRAL, EntityType.BOAT), - MINECART("Minecart", Enemies.NEUTRAL, EntityType.MINECART), - MINECART_CHEST("ChestMinecart", Enemies.NEUTRAL, EntityType.MINECART_CHEST), - MINECART_FURNACE("FurnaceMinecart", Enemies.NEUTRAL, EntityType.MINECART_FURNACE), - MINECART_TNT("TNTMinecart", Enemies.NEUTRAL, EntityType.MINECART_TNT), - MINECART_HOPPER("HopperMinecart", Enemies.NEUTRAL, EntityType.MINECART_HOPPER), - MINECART_MOB_SPAWNER("SpawnerMinecart", Enemies.NEUTRAL, EntityType.MINECART_MOB_SPAWNER), - ENDERCRYSTAL("EnderCrystal", Enemies.NEUTRAL, EntityType.ENDER_CRYSTAL), - EXPERIENCEORB("ExperienceOrb", Enemies.NEUTRAL, EntityType.EXPERIENCE_ORB); - public static final Logger logger = Logger.getLogger("Essentials"); +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), + HORSE("Horse", Enemies.FRIENDLY, EntityType.HORSE), + 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), + WITHER("Wither", Enemies.ENEMY, EntityType.WITHER), + BAT("Bat", Enemies.FRIENDLY, EntityType.BAT), + WITCH("Witch", Enemies.ENEMY, EntityType.WITCH), + BOAT("Boat", Enemies.NEUTRAL, EntityType.BOAT), + MINECART("Minecart", Enemies.NEUTRAL, EntityType.MINECART), + MINECART_CHEST("ChestMinecart", Enemies.NEUTRAL, EntityType.MINECART_CHEST), + MINECART_FURNACE("FurnaceMinecart", Enemies.NEUTRAL, EntityType.MINECART_FURNACE), + MINECART_TNT("TNTMinecart", Enemies.NEUTRAL, EntityType.MINECART_TNT), + MINECART_HOPPER("HopperMinecart", Enemies.NEUTRAL, EntityType.MINECART_HOPPER), + MINECART_MOB_SPAWNER("SpawnerMinecart", Enemies.NEUTRAL, EntityType.MINECART_MOB_SPAWNER), + ENDERCRYSTAL("EnderCrystal", Enemies.NEUTRAL, EntityType.ENDER_CRYSTAL), + EXPERIENCEORB("ExperienceOrb", Enemies.NEUTRAL, EntityType.EXPERIENCE_ORB); + public static final Logger logger = Logger.getLogger("Essentials"); - 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, 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(); - private static final Map bukkitMap = new HashMap(); + private Mob(String n, Enemies en, EntityType type) { + this.name = n; + this.type = en; + this.bukkitType = type; + } - static - { - for (Mob mob : Mob.values()) - { - hashMap.put(mob.name.toLowerCase(Locale.ENGLISH), mob); - bukkitMap.put(mob.bukkitType, mob); - } - } + public String suffix = "s"; + final public String name; + final public Enemies type; + final private EntityType bukkitType; + private static final Map hashMap = new HashMap(); + private static final Map bukkitMap = new HashMap(); - public static Set getMobList() - { - return Collections.unmodifiableSet(hashMap.keySet()); - } + static { + for (Mob mob : Mob.values()) { + hashMap.put(mob.name.toLowerCase(Locale.ENGLISH), mob); + bukkitMap.put(mob.bukkitType, mob); + } + } - public Entity spawn(final World world, final Server server, final Location loc) throws MobException - { - final Entity entity = world.spawn(loc, (Class)this.bukkitType.getEntityClass()); - if (entity == null) - { - logger.log(Level.WARNING, tl("unableToSpawnMob")); - throw new MobException(); - } - return entity; - } + public static Set getMobList() { + return Collections.unmodifiableSet(hashMap.keySet()); + } + + public Entity spawn(final World world, final Server server, final Location loc) throws MobException { + final Entity entity = world.spawn(loc, (Class) this.bukkitType.getEntityClass()); + if (entity == null) { + logger.log(Level.WARNING, tl("unableToSpawnMob")); + throw new MobException(); + } + return entity; + } - public enum Enemies - { - FRIENDLY("friendly"), - NEUTRAL("neutral"), - ENEMY("enemy"); + public enum Enemies { + FRIENDLY("friendly"), + NEUTRAL("neutral"), + ENEMY("enemy"); - private Enemies(final String type) - { - this.type = type; - } - final protected String type; - } + private Enemies(final String type) { + this.type = type; + } - public EntityType getType() - { - return bukkitType; - } + final protected String type; + } - public static Mob fromName(final String name) - { - return hashMap.get(name.toLowerCase(Locale.ENGLISH)); - } + public EntityType getType() { + return bukkitType; + } - public static Mob fromBukkitType(final EntityType type) - { - return bukkitMap.get(type); - } + public static Mob fromName(final String name) { + return hashMap.get(name.toLowerCase(Locale.ENGLISH)); + } + + public static Mob fromBukkitType(final EntityType type) { + return bukkitMap.get(type); + } - public static class MobException extends Exception - { - private static final long serialVersionUID = 1L; - } + public static class MobException extends Exception { + private static final long serialVersionUID = 1L; + } } diff --git a/Essentials/src/com/earth2me/essentials/MobData.java b/Essentials/src/com/earth2me/essentials/MobData.java index 790cc631b..a81def700 100644 --- a/Essentials/src/com/earth2me/essentials/MobData.java +++ b/Essentials/src/com/earth2me/essentials/MobData.java @@ -1,351 +1,267 @@ package com.earth2me.essentials; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.utils.StringUtil; -import java.util.*; -import java.util.logging.Logger; import org.bukkit.DyeColor; import org.bukkit.Material; -import org.bukkit.entity.Ageable; -import org.bukkit.entity.Creeper; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.ExperienceOrb; -import org.bukkit.entity.Horse; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Ocelot; -import org.bukkit.entity.Pig; -import org.bukkit.entity.Player; -import org.bukkit.entity.Skeleton; -import org.bukkit.entity.Slime; -import org.bukkit.entity.Tameable; -import org.bukkit.entity.Villager; -import org.bukkit.entity.Wolf; -import org.bukkit.entity.Zombie; +import org.bukkit.entity.*; import org.bukkit.inventory.EntityEquipment; import org.bukkit.inventory.ItemStack; import org.bukkit.material.Colorable; +import java.util.*; +import java.util.logging.Logger; -public enum MobData -{ - BABY_AGEABLE("baby", Ageable.class, Data.BABY, true), - ADULT_AGEABLE("adult", Ageable.class, Data.ADULT, true), - BABY_PIG("piglet", EntityType.PIG, Data.BABY, false), - BABY_WOLF("puppy", EntityType.WOLF, Data.BABY, false), - BABY_CHICKEN("chick", EntityType.CHICKEN, Data.BABY, false), - BABY_HORSE("colt", EntityType.HORSE, Data.BABY, false), - BABY_OCELOT("kitten", EntityType.OCELOT, Data.BABY, false), - BABY_SHEEP("lamb", EntityType.SHEEP, Data.BABY, false), - BABY_COW("calf", EntityType.COW.getEntityClass(), Data.BABY, false), - BABY_VILLAGER("child", EntityType.VILLAGER, Data.BABY, false), - TAMED_TAMEABLE("tamed", Tameable.class, Data.TAMED, true), - TAME_TAMEABLE("tame", Tameable.class, Data.TAMED, false), - RANDOM_SHEEP("random", EntityType.SHEEP, Data.COLORABLE, true), - COLORABLE_SHEEP("", StringUtil.joinList(DyeColor.values()).toLowerCase(Locale.ENGLISH), EntityType.SHEEP, Data.COLORABLE, true), - DONKEY_HORSE("donkey", EntityType.HORSE, Horse.Variant.DONKEY, true), - MULE_HORSE("mule", EntityType.HORSE, Horse.Variant.MULE, true), - SKELETON_HORSE("skeleton", EntityType.HORSE, Horse.Variant.SKELETON_HORSE, true), - UNDEAD_HORSE("undead", EntityType.HORSE, Horse.Variant.UNDEAD_HORSE, true), - ZOMBIE_HORSE("zombie", EntityType.HORSE, Horse.Variant.UNDEAD_HORSE, false), - POLKA_HORSE("polka", EntityType.HORSE, Horse.Style.BLACK_DOTS, true), - SOOTY_HORSE("sooty", EntityType.HORSE, Horse.Style.BLACK_DOTS, false), - BLAZE_HORSE("blaze", EntityType.HORSE, Horse.Style.WHITE, true), - SOCKS_HORSE("socks", EntityType.HORSE, Horse.Style.WHITE, false), - LEOPARD_HORSE("leopard", EntityType.HORSE, Horse.Style.WHITE_DOTS, true), - APPALOOSA_HORSE("appaloosa", EntityType.HORSE, Horse.Style.WHITE_DOTS, false), - PAINT_HORSE("paint", EntityType.HORSE, Horse.Style.WHITEFIELD, true), - MILKY_HORSE("milky", EntityType.HORSE, Horse.Style.WHITEFIELD, false), - SPLOTCHY_HORSE("splotchy", EntityType.HORSE, Horse.Style.WHITEFIELD, false), - BLACK_HORSE("black", EntityType.HORSE, Horse.Color.BLACK, true), - CHESTNUT_HORSE("chestnut", EntityType.HORSE, Horse.Color.CHESTNUT, true), - LIVER_HORSE("liver", EntityType.HORSE, Horse.Color.CHESTNUT, false), - CREAMY_HORSE("creamy", EntityType.HORSE, Horse.Color.CREAMY, true), - FLAXEN_HORSE("flaxen", EntityType.HORSE, Horse.Color.CREAMY, false), - GRAY_HORSE("gray", EntityType.HORSE, Horse.Color.GRAY, true), - DAPPLE_HORSE("dapple", EntityType.HORSE, Horse.Color.GRAY, false), - BUCKSKIN_HORSE("buckskin", EntityType.HORSE, Horse.Color.DARK_BROWN, true), - DARKBROWN_HORSE("darkbrown", EntityType.HORSE, Horse.Color.DARK_BROWN, false), - DARK_HORSE("dark", EntityType.HORSE, Horse.Color.DARK_BROWN, false), - DBROWN_HORSE("dbrown", EntityType.HORSE, Horse.Color.DARK_BROWN, false), - BAY_HORSE("bay", EntityType.HORSE, Horse.Color.BROWN, true), - BROWN_HORSE("brown", EntityType.HORSE, Horse.Color.BROWN, false), - CHEST_HORSE("chest", EntityType.HORSE, Data.CHEST, true), - SADDLE_HORSE("saddle", EntityType.HORSE, Data.HORSESADDLE, true), - GOLD_ARMOR_HORSE("goldarmor", EntityType.HORSE, Material.GOLD_BARDING, true), - DIAMOND_ARMOR_HORSE("diamondarmor", EntityType.HORSE, Material.DIAMOND_BARDING, true), - ARMOR_HORSE("armor", EntityType.HORSE, Material.IRON_BARDING, true), - SIAMESE_CAT("siamese", EntityType.OCELOT, Ocelot.Type.SIAMESE_CAT, true), - WHITE_CAT("white", EntityType.OCELOT, Ocelot.Type.SIAMESE_CAT, false), - RED_CAT("red", EntityType.OCELOT, Ocelot.Type.RED_CAT, true), - ORANGE_CAT("orange", EntityType.OCELOT, Ocelot.Type.RED_CAT, false), - TABBY_CAT("tabby", EntityType.OCELOT, Ocelot.Type.RED_CAT, false), - BLACK_CAT("black", EntityType.OCELOT, Ocelot.Type.BLACK_CAT, true), - TUXEDO_CAT("tuxedo", EntityType.OCELOT, Ocelot.Type.BLACK_CAT, false), - VILLAGER_ZOMBIE("villager", EntityType.ZOMBIE.getEntityClass(), Data.VILLAGER, true), - BABY_ZOMBIE("baby", EntityType.ZOMBIE.getEntityClass(), Data.BABYZOMBIE, true), - ADULT_ZOMBIE("adult", EntityType.ZOMBIE.getEntityClass(), Data.ADULTZOMBIE, true), - DIAMOND_SWORD_ZOMBIE("diamondsword", EntityType.ZOMBIE.getEntityClass(), Material.DIAMOND_SWORD, true), - GOLD_SWORD_ZOMBIE("goldsword", EntityType.ZOMBIE.getEntityClass(), Material.GOLD_SWORD, true), - IRON_SWORD_ZOMBIE("ironsword", EntityType.ZOMBIE.getEntityClass(), Material.IRON_SWORD, true), - STONE_SWORD_ZOMBIE("stonesword", EntityType.ZOMBIE.getEntityClass(), Material.STONE_SWORD, false), - SWORD_ZOMBIE("sword", EntityType.ZOMBIE.getEntityClass(), Material.STONE_SWORD, true), - DIAMOND_SWORD_SKELETON("diamondsword", EntityType.SKELETON, Material.DIAMOND_SWORD, true), - GOLD_SWORD_SKELETON("goldsword", EntityType.SKELETON, Material.GOLD_SWORD, true), - IRON_SWORD_SKELETON("ironsword", EntityType.SKELETON, Material.IRON_SWORD, true), - STONE_SWORD_SKELETON("stonesword", EntityType.SKELETON, Material.STONE_SWORD, false), - SWORD_SKELETON("sword", EntityType.SKELETON, Material.STONE_SWORD, true), - BOW_SKELETON("bow", EntityType.SKELETON, Material.BOW, true), - WHITHER_SKELETON("wither", EntityType.SKELETON, Data.WITHER, true), - POWERED_CREEPER("powered", EntityType.CREEPER, Data.ELECTRIFIED, true), - ELECTRIC_CREEPER("electric", EntityType.CREEPER, Data.ELECTRIFIED, false), - CHARGED_CREEPER("charged", EntityType.CREEPER, Data.ELECTRIFIED, false), - SADDLE_PIG("saddle", EntityType.PIG, Data.PIGSADDLE, true), - ANGRY_WOLF("angry", EntityType.WOLF, Data.ANGRY, true), - RABID_WOLF("rabid", EntityType.WOLF, Data.ANGRY, false), - FARMER_VILLAGER("farmer", EntityType.VILLAGER, Villager.Profession.FARMER, true), - LIBRARIAN_VILLAGER("librarian", EntityType.VILLAGER, Villager.Profession.LIBRARIAN, true), - PRIEST_VILLAGER("priest", EntityType.VILLAGER, Villager.Profession.PRIEST, true), - FATHER_VILLAGER("father", EntityType.VILLAGER, Villager.Profession.PRIEST, false), - SMITH_VILLAGER("smith", EntityType.VILLAGER, Villager.Profession.BLACKSMITH, true), - BUTCHER_VILLAGER("butcher", EntityType.VILLAGER, Villager.Profession.BUTCHER, true), - SIZE_SLIME("", "<1-100>", EntityType.SLIME.getEntityClass(), Data.SIZE, true), - NUM_EXPERIENCE_ORB("", "<1-2000000000>", EntityType.EXPERIENCE_ORB, Data.EXP, true); +import static com.earth2me.essentials.I18n.tl; - public enum Data - { - ADULT, - BABY, - CHEST, - ADULTZOMBIE, - BABYZOMBIE, - VILLAGER, - HORSESADDLE, - PIGSADDLE, - ELECTRIFIED, - WITHER, - ANGRY, - TAMED, - COLORABLE, - EXP, - SIZE; - } - public static final Logger logger = Logger.getLogger("Essentials"); +public enum MobData { + BABY_AGEABLE("baby", Ageable.class, Data.BABY, true), + ADULT_AGEABLE("adult", Ageable.class, Data.ADULT, true), + BABY_PIG("piglet", EntityType.PIG, Data.BABY, false), + BABY_WOLF("puppy", EntityType.WOLF, Data.BABY, false), + BABY_CHICKEN("chick", EntityType.CHICKEN, Data.BABY, false), + BABY_HORSE("colt", EntityType.HORSE, Data.BABY, false), + BABY_OCELOT("kitten", EntityType.OCELOT, Data.BABY, false), + BABY_SHEEP("lamb", EntityType.SHEEP, Data.BABY, false), + BABY_COW("calf", EntityType.COW.getEntityClass(), Data.BABY, false), + BABY_VILLAGER("child", EntityType.VILLAGER, Data.BABY, false), + TAMED_TAMEABLE("tamed", Tameable.class, Data.TAMED, true), + TAME_TAMEABLE("tame", Tameable.class, Data.TAMED, false), + RANDOM_SHEEP("random", EntityType.SHEEP, Data.COLORABLE, true), + COLORABLE_SHEEP("", StringUtil.joinList(DyeColor.values()).toLowerCase(Locale.ENGLISH), EntityType.SHEEP, Data.COLORABLE, true), + DONKEY_HORSE("donkey", EntityType.HORSE, Horse.Variant.DONKEY, true), + MULE_HORSE("mule", EntityType.HORSE, Horse.Variant.MULE, true), + SKELETON_HORSE("skeleton", EntityType.HORSE, Horse.Variant.SKELETON_HORSE, true), + UNDEAD_HORSE("undead", EntityType.HORSE, Horse.Variant.UNDEAD_HORSE, true), + ZOMBIE_HORSE("zombie", EntityType.HORSE, Horse.Variant.UNDEAD_HORSE, false), + POLKA_HORSE("polka", EntityType.HORSE, Horse.Style.BLACK_DOTS, true), + SOOTY_HORSE("sooty", EntityType.HORSE, Horse.Style.BLACK_DOTS, false), + BLAZE_HORSE("blaze", EntityType.HORSE, Horse.Style.WHITE, true), + SOCKS_HORSE("socks", EntityType.HORSE, Horse.Style.WHITE, false), + LEOPARD_HORSE("leopard", EntityType.HORSE, Horse.Style.WHITE_DOTS, true), + APPALOOSA_HORSE("appaloosa", EntityType.HORSE, Horse.Style.WHITE_DOTS, false), + PAINT_HORSE("paint", EntityType.HORSE, Horse.Style.WHITEFIELD, true), + MILKY_HORSE("milky", EntityType.HORSE, Horse.Style.WHITEFIELD, false), + SPLOTCHY_HORSE("splotchy", EntityType.HORSE, Horse.Style.WHITEFIELD, false), + BLACK_HORSE("black", EntityType.HORSE, Horse.Color.BLACK, true), + CHESTNUT_HORSE("chestnut", EntityType.HORSE, Horse.Color.CHESTNUT, true), + LIVER_HORSE("liver", EntityType.HORSE, Horse.Color.CHESTNUT, false), + CREAMY_HORSE("creamy", EntityType.HORSE, Horse.Color.CREAMY, true), + FLAXEN_HORSE("flaxen", EntityType.HORSE, Horse.Color.CREAMY, false), + GRAY_HORSE("gray", EntityType.HORSE, Horse.Color.GRAY, true), + DAPPLE_HORSE("dapple", EntityType.HORSE, Horse.Color.GRAY, false), + BUCKSKIN_HORSE("buckskin", EntityType.HORSE, Horse.Color.DARK_BROWN, true), + DARKBROWN_HORSE("darkbrown", EntityType.HORSE, Horse.Color.DARK_BROWN, false), + DARK_HORSE("dark", EntityType.HORSE, Horse.Color.DARK_BROWN, false), + DBROWN_HORSE("dbrown", EntityType.HORSE, Horse.Color.DARK_BROWN, false), + BAY_HORSE("bay", EntityType.HORSE, Horse.Color.BROWN, true), + BROWN_HORSE("brown", EntityType.HORSE, Horse.Color.BROWN, false), + CHEST_HORSE("chest", EntityType.HORSE, Data.CHEST, true), + SADDLE_HORSE("saddle", EntityType.HORSE, Data.HORSESADDLE, true), + GOLD_ARMOR_HORSE("goldarmor", EntityType.HORSE, Material.GOLD_BARDING, true), + DIAMOND_ARMOR_HORSE("diamondarmor", EntityType.HORSE, Material.DIAMOND_BARDING, true), + ARMOR_HORSE("armor", EntityType.HORSE, Material.IRON_BARDING, true), + SIAMESE_CAT("siamese", EntityType.OCELOT, Ocelot.Type.SIAMESE_CAT, true), + WHITE_CAT("white", EntityType.OCELOT, Ocelot.Type.SIAMESE_CAT, false), + RED_CAT("red", EntityType.OCELOT, Ocelot.Type.RED_CAT, true), + ORANGE_CAT("orange", EntityType.OCELOT, Ocelot.Type.RED_CAT, false), + TABBY_CAT("tabby", EntityType.OCELOT, Ocelot.Type.RED_CAT, false), + BLACK_CAT("black", EntityType.OCELOT, Ocelot.Type.BLACK_CAT, true), + TUXEDO_CAT("tuxedo", EntityType.OCELOT, Ocelot.Type.BLACK_CAT, false), + VILLAGER_ZOMBIE("villager", EntityType.ZOMBIE.getEntityClass(), Data.VILLAGER, true), + BABY_ZOMBIE("baby", EntityType.ZOMBIE.getEntityClass(), Data.BABYZOMBIE, true), + ADULT_ZOMBIE("adult", EntityType.ZOMBIE.getEntityClass(), Data.ADULTZOMBIE, true), + DIAMOND_SWORD_ZOMBIE("diamondsword", EntityType.ZOMBIE.getEntityClass(), Material.DIAMOND_SWORD, true), + GOLD_SWORD_ZOMBIE("goldsword", EntityType.ZOMBIE.getEntityClass(), Material.GOLD_SWORD, true), + IRON_SWORD_ZOMBIE("ironsword", EntityType.ZOMBIE.getEntityClass(), Material.IRON_SWORD, true), + STONE_SWORD_ZOMBIE("stonesword", EntityType.ZOMBIE.getEntityClass(), Material.STONE_SWORD, false), + SWORD_ZOMBIE("sword", EntityType.ZOMBIE.getEntityClass(), Material.STONE_SWORD, true), + DIAMOND_SWORD_SKELETON("diamondsword", EntityType.SKELETON, Material.DIAMOND_SWORD, true), + GOLD_SWORD_SKELETON("goldsword", EntityType.SKELETON, Material.GOLD_SWORD, true), + IRON_SWORD_SKELETON("ironsword", EntityType.SKELETON, Material.IRON_SWORD, true), + STONE_SWORD_SKELETON("stonesword", EntityType.SKELETON, Material.STONE_SWORD, false), + SWORD_SKELETON("sword", EntityType.SKELETON, Material.STONE_SWORD, true), + BOW_SKELETON("bow", EntityType.SKELETON, Material.BOW, true), + WHITHER_SKELETON("wither", EntityType.SKELETON, Data.WITHER, true), + POWERED_CREEPER("powered", EntityType.CREEPER, Data.ELECTRIFIED, true), + ELECTRIC_CREEPER("electric", EntityType.CREEPER, Data.ELECTRIFIED, false), + CHARGED_CREEPER("charged", EntityType.CREEPER, Data.ELECTRIFIED, false), + SADDLE_PIG("saddle", EntityType.PIG, Data.PIGSADDLE, true), + ANGRY_WOLF("angry", EntityType.WOLF, Data.ANGRY, true), + RABID_WOLF("rabid", EntityType.WOLF, Data.ANGRY, false), + FARMER_VILLAGER("farmer", EntityType.VILLAGER, Villager.Profession.FARMER, true), + LIBRARIAN_VILLAGER("librarian", EntityType.VILLAGER, Villager.Profession.LIBRARIAN, true), + PRIEST_VILLAGER("priest", EntityType.VILLAGER, Villager.Profession.PRIEST, true), + FATHER_VILLAGER("father", EntityType.VILLAGER, Villager.Profession.PRIEST, false), + SMITH_VILLAGER("smith", EntityType.VILLAGER, Villager.Profession.BLACKSMITH, true), + BUTCHER_VILLAGER("butcher", EntityType.VILLAGER, Villager.Profession.BUTCHER, true), + SIZE_SLIME("", "<1-100>", EntityType.SLIME.getEntityClass(), Data.SIZE, true), + NUM_EXPERIENCE_ORB("", "<1-2000000000>", EntityType.EXPERIENCE_ORB, Data.EXP, true); - private MobData(String n, Object type, Object value, boolean isPublic) - { - this.nickname = n; - this.matched = n; - this.helpMessage = n; - this.type = type; - this.value = value; - this.isPublic = isPublic; - } - private MobData(String n, String h, Object type, Object value, boolean isPublic) - { - this.nickname = n; - this.matched = n; - this.helpMessage = h; - this.type = type; - this.value = value; - this.isPublic = isPublic; - } - final private String nickname; - final private String helpMessage; - final private Object type; - final private Object value; - final private boolean isPublic; - private String matched; + public enum Data { + ADULT, + BABY, + CHEST, + ADULTZOMBIE, + BABYZOMBIE, + VILLAGER, + HORSESADDLE, + PIGSADDLE, + ELECTRIFIED, + WITHER, + ANGRY, + TAMED, + COLORABLE, + EXP, + SIZE; + } - public static LinkedHashMap getPossibleData(final Entity spawned, boolean publicOnly) - { - LinkedHashMap mobList = new LinkedHashMap(); - for (MobData data : MobData.values()) - { - if (data.type instanceof EntityType && spawned.getType().equals(data.type) && ((publicOnly && data.isPublic) || !publicOnly)) - { - mobList.put(data.nickname.toLowerCase(Locale.ENGLISH), data); - } - else if (data.type instanceof Class && ((Class)data.type).isAssignableFrom(spawned.getClass()) && ((publicOnly && data.isPublic) || !publicOnly)) - { - mobList.put(data.nickname.toLowerCase(Locale.ENGLISH), data); - } - } + public static final Logger logger = Logger.getLogger("Essentials"); - return mobList; - } + private MobData(String n, Object type, Object value, boolean isPublic) { + this.nickname = n; + this.matched = n; + this.helpMessage = n; + this.type = type; + this.value = value; + this.isPublic = isPublic; + } - public static List getValidHelp(final Entity spawned) - { - List output = new ArrayList(); - LinkedHashMap posData = getPossibleData(spawned, true); + private MobData(String n, String h, Object type, Object value, boolean isPublic) { + this.nickname = n; + this.matched = n; + this.helpMessage = h; + this.type = type; + this.value = value; + this.isPublic = isPublic; + } - for (MobData data : posData.values()) - { - output.add(data.helpMessage); - } - return output; - } + final private String nickname; + final private String helpMessage; + final private Object type; + final private Object value; + final private boolean isPublic; + private String matched; - public static MobData fromData(final Entity spawned, final String name) - { - if (name.isEmpty()) - { - return null; - } + public static LinkedHashMap getPossibleData(final Entity spawned, boolean publicOnly) { + LinkedHashMap mobList = new LinkedHashMap(); + for (MobData data : MobData.values()) { + if (data.type instanceof EntityType && spawned.getType().equals(data.type) && ((publicOnly && data.isPublic) || !publicOnly)) { + mobList.put(data.nickname.toLowerCase(Locale.ENGLISH), data); + } else if (data.type instanceof Class && ((Class) data.type).isAssignableFrom(spawned.getClass()) && ((publicOnly && data.isPublic) || !publicOnly)) { + mobList.put(data.nickname.toLowerCase(Locale.ENGLISH), data); + } + } - LinkedHashMap posData = getPossibleData(spawned, false); - for (String data : posData.keySet()) - { - if (name.contains(data)) - { - return posData.get(data); - } - } - return null; - } + return mobList; + } - public String getMatched() - { - return this.matched; - } + public static List getValidHelp(final Entity spawned) { + List output = new ArrayList(); + LinkedHashMap posData = getPossibleData(spawned, true); - public void setData(final Entity spawned, final Player target, final String rawData) throws Exception - { - if (this.value.equals(Data.ANGRY)) - { - ((Wolf)spawned).setAngry(true); - } - else if (this.value.equals(Data.ADULT)) - { - ((Ageable)spawned).setAdult(); - } - else if (this.value.equals(Data.BABY)) - { - ((Ageable)spawned).setBaby(); - } - else if (this.value.equals(Data.ADULTZOMBIE)) - { - ((Zombie)spawned).setBaby(false); - } - else if (this.value.equals(Data.BABYZOMBIE)) - { - ((Zombie)spawned).setBaby(true); - } - else if (this.value.equals(Data.CHEST)) - { - ((Horse)spawned).setTamed(true); - ((Horse)spawned).setCarryingChest(true); - } - else if (this.value.equals(Data.ELECTRIFIED)) - { - ((Creeper)spawned).setPowered(true); - } - else if (this.value.equals(Data.HORSESADDLE)) - { - final Horse horse = ((Horse)spawned); - horse.setTamed(true); - horse.setOwner(target); - horse.getInventory().setSaddle(new ItemStack(Material.SADDLE, 1)); - } - else if (this.value.equals(Data.PIGSADDLE)) - { - ((Pig)spawned).setSaddle(true); - } - else if (this.value.equals(Data.TAMED)) - { - final Tameable tameable = ((Tameable)spawned); - tameable.setTamed(true); - tameable.setOwner(target); - } - else if (this.value.equals(Data.VILLAGER)) - { - ((Zombie)spawned).setVillager(this.value.equals(Data.VILLAGER)); - } - else if (this.value.equals(Data.WITHER)) - { - ((Skeleton)spawned).setSkeletonType(Skeleton.SkeletonType.WITHER); - } - else if (this.value.equals(Data.COLORABLE)) - { - final String color = rawData.toUpperCase(Locale.ENGLISH); - try - { - if (color.equals("RANDOM")) - { - final Random rand = new Random(); - ((Colorable)spawned).setColor(DyeColor.values()[rand.nextInt(DyeColor.values().length)]); - } - else if (!color.isEmpty()) - { - ((Colorable)spawned).setColor(DyeColor.valueOf(color)); - } - this.matched = rawData; - } - catch (Exception e) - { - throw new Exception(tl("sheepMalformedColor"), e); - } - } - else if (this.value.equals(Data.EXP)) - { - try - { - ((ExperienceOrb)spawned).setExperience(Integer.parseInt(rawData)); - this.matched = rawData; - } - catch (NumberFormatException e) - { - throw new Exception(tl("invalidNumber"), e); - } - } - else if (this.value.equals(Data.SIZE)) - { - try - { - ((Slime)spawned).setSize(Integer.parseInt(rawData)); - this.matched = rawData; - } - catch (NumberFormatException e) - { - throw new Exception(tl("slimeMalformedSize"), e); - } - } - else if (this.value instanceof Horse.Color) - { - ((Horse)spawned).setColor((Horse.Color)this.value); - } - else if (this.value instanceof Horse.Style) - { - ((Horse)spawned).setStyle((Horse.Style)this.value); - } - else if (this.value instanceof Horse.Variant) - { - ((Horse)spawned).setVariant((Horse.Variant)this.value); - } - else if (this.value instanceof Ocelot.Type) - { - ((Ocelot)spawned).setCatType((Ocelot.Type)this.value); - } - else if (this.value instanceof Villager.Profession) - { - ((Villager)spawned).setProfession((Villager.Profession)this.value); - } - else if (this.value instanceof Material) - { - if (this.type.equals(EntityType.HORSE)) - { - ((Horse)spawned).setTamed(true); - ((Horse)spawned).getInventory().setArmor(new ItemStack((Material)this.value, 1)); - } - else if (this.type.equals(EntityType.ZOMBIE.getEntityClass()) || this.type.equals(EntityType.SKELETON)) - { - final EntityEquipment invent = ((LivingEntity)spawned).getEquipment(); - invent.setItemInHand(new ItemStack((Material)this.value, 1)); - invent.setItemInHandDropChance(0.1f); - } - } - } + for (MobData data : posData.values()) { + output.add(data.helpMessage); + } + return output; + } + + public static MobData fromData(final Entity spawned, final String name) { + if (name.isEmpty()) { + return null; + } + + LinkedHashMap posData = getPossibleData(spawned, false); + for (String data : posData.keySet()) { + if (name.contains(data)) { + return posData.get(data); + } + } + return null; + } + + public String getMatched() { + return this.matched; + } + + public void setData(final Entity spawned, final Player target, final String rawData) throws Exception { + if (this.value.equals(Data.ANGRY)) { + ((Wolf) spawned).setAngry(true); + } else if (this.value.equals(Data.ADULT)) { + ((Ageable) spawned).setAdult(); + } else if (this.value.equals(Data.BABY)) { + ((Ageable) spawned).setBaby(); + } else if (this.value.equals(Data.ADULTZOMBIE)) { + ((Zombie) spawned).setBaby(false); + } else if (this.value.equals(Data.BABYZOMBIE)) { + ((Zombie) spawned).setBaby(true); + } else if (this.value.equals(Data.CHEST)) { + ((Horse) spawned).setTamed(true); + ((Horse) spawned).setCarryingChest(true); + } else if (this.value.equals(Data.ELECTRIFIED)) { + ((Creeper) spawned).setPowered(true); + } else if (this.value.equals(Data.HORSESADDLE)) { + final Horse horse = ((Horse) spawned); + horse.setTamed(true); + horse.setOwner(target); + horse.getInventory().setSaddle(new ItemStack(Material.SADDLE, 1)); + } else if (this.value.equals(Data.PIGSADDLE)) { + ((Pig) spawned).setSaddle(true); + } else if (this.value.equals(Data.TAMED)) { + final Tameable tameable = ((Tameable) spawned); + tameable.setTamed(true); + tameable.setOwner(target); + } else if (this.value.equals(Data.VILLAGER)) { + ((Zombie) spawned).setVillager(this.value.equals(Data.VILLAGER)); + } else if (this.value.equals(Data.WITHER)) { + ((Skeleton) spawned).setSkeletonType(Skeleton.SkeletonType.WITHER); + } else if (this.value.equals(Data.COLORABLE)) { + final String color = rawData.toUpperCase(Locale.ENGLISH); + try { + if (color.equals("RANDOM")) { + final Random rand = new Random(); + ((Colorable) spawned).setColor(DyeColor.values()[rand.nextInt(DyeColor.values().length)]); + } else if (!color.isEmpty()) { + ((Colorable) spawned).setColor(DyeColor.valueOf(color)); + } + this.matched = rawData; + } catch (Exception e) { + throw new Exception(tl("sheepMalformedColor"), e); + } + } else if (this.value.equals(Data.EXP)) { + try { + ((ExperienceOrb) spawned).setExperience(Integer.parseInt(rawData)); + this.matched = rawData; + } catch (NumberFormatException e) { + throw new Exception(tl("invalidNumber"), e); + } + } else if (this.value.equals(Data.SIZE)) { + try { + ((Slime) spawned).setSize(Integer.parseInt(rawData)); + this.matched = rawData; + } catch (NumberFormatException e) { + throw new Exception(tl("slimeMalformedSize"), e); + } + } else if (this.value instanceof Horse.Color) { + ((Horse) spawned).setColor((Horse.Color) this.value); + } else if (this.value instanceof Horse.Style) { + ((Horse) spawned).setStyle((Horse.Style) this.value); + } else if (this.value instanceof Horse.Variant) { + ((Horse) spawned).setVariant((Horse.Variant) this.value); + } else if (this.value instanceof Ocelot.Type) { + ((Ocelot) spawned).setCatType((Ocelot.Type) this.value); + } else if (this.value instanceof Villager.Profession) { + ((Villager) spawned).setProfession((Villager.Profession) this.value); + } else if (this.value instanceof Material) { + if (this.type.equals(EntityType.HORSE)) { + ((Horse) spawned).setTamed(true); + ((Horse) spawned).getInventory().setArmor(new ItemStack((Material) this.value, 1)); + } else if (this.type.equals(EntityType.ZOMBIE.getEntityClass()) || this.type.equals(EntityType.SKELETON)) { + final EntityEquipment invent = ((LivingEntity) spawned).getEquipment(); + invent.setItemInHand(new ItemStack((Material) this.value, 1)); + invent.setItemInHandDropChance(0.1f); + } + } + } } diff --git a/Essentials/src/com/earth2me/essentials/OfflinePlayer.java b/Essentials/src/com/earth2me/essentials/OfflinePlayer.java index 2fda39778..1df8ec209 100644 --- a/Essentials/src/com/earth2me/essentials/OfflinePlayer.java +++ b/Essentials/src/com/earth2me/essentials/OfflinePlayer.java @@ -1,8 +1,5 @@ package com.earth2me.essentials; -import static com.earth2me.essentials.I18n.tl; -import java.net.InetSocketAddress; -import java.util.*; import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.conversations.Conversation; @@ -23,1527 +20,1274 @@ import org.bukkit.potion.PotionEffectType; import org.bukkit.scoreboard.Scoreboard; import org.bukkit.util.Vector; - -public class OfflinePlayer implements Player -{ - private final transient Server server; - private transient Location location = new Location(null, 0, 0, 0, 0, 0); - private transient World world; - private transient org.bukkit.OfflinePlayer base; - private boolean allowFlight = false; - private boolean isFlying = false; - private String name = null; - - public OfflinePlayer(final UUID uuid, final Server server) - { - this.server = server; - this.world = server.getWorlds().get(0); - this.base = server.getOfflinePlayer(uuid); - this.name = base.getName(); - } - - public OfflinePlayer(final String name, final Server server) - { - this.server = server; - this.world = server.getWorlds().get(0); - this.base = server.getOfflinePlayer(name); - this.name = name; - } - - @Override - public void sendMessage(final String string) - { - } - - @Override - public String getDisplayName() - { - return base.getName(); - } - - @Override - public void setDisplayName(String string) - { - } - - @Override - public void setCompassTarget(Location lctn) - { - } - - @Override - public InetSocketAddress getAddress() - { - return null; - } - - @Override - public void kickPlayer(String string) - { - } - - @Override - public PlayerInventory getInventory() - { - return null; - } - - @Override - public ItemStack getItemInHand() - { - return null; - } - - @Override - public void setItemInHand(ItemStack is) - { - } - - @Override - public double getHealth() - { - return 0; - } - - @Override - public void setHealth(double d) - { - } - - @Override - public Egg throwEgg() - { - return null; - } - - @Override - public Snowball throwSnowball() - { - return null; - } - - @Override - public Arrow shootArrow() - { - return null; - } - - @Override - public boolean isInsideVehicle() - { - return false; - } - - @Override - public boolean leaveVehicle() - { - return false; - } - - @Override - public Vehicle getVehicle() - { - return null; - } - - @Override - public Location getLocation() - { - return location; - } - - @Override - public World getWorld() - { - return world; - } - - public void setLocation(Location loc) - { - location = loc; - world = loc.getWorld(); - } - - public void teleportTo(Location lctn) - { - } - - public void teleportTo(Entity entity) - { - } - - @Override - public int getEntityId() - { - return -1; - } - - @Override - public boolean performCommand(String string) - { - return false; - } - - @Override - public int getRemainingAir() - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void setRemainingAir(int i) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public int getMaximumAir() - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void setMaximumAir(int i) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public boolean isSneaking() - { - return false; - } - - @Override - public void setSneaking(boolean bln) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void updateInventory() - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void chat(String string) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public double getEyeHeight() - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public double getEyeHeight(boolean bln) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public List getLineOfSight(HashSet hs, int i) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public Block getTargetBlock(HashSet hs, int i) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public List getLastTwoTargetBlocks(HashSet hs, int i) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public int getFireTicks() - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public int getMaxFireTicks() - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void setFireTicks(int i) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void remove() - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public Server getServer() - { - return server; - } - - public Vector getMomentum() - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - public void setMomentum(Vector vector) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void setVelocity(Vector vector) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public Vector getVelocity() - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void damage(double d) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void damage(double d, Entity entity) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public Location getEyeLocation() - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void sendRawMessage(String string) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public Location getCompassTarget() - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public int getMaximumNoDamageTicks() - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void setMaximumNoDamageTicks(int i) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public double getLastDamage() - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void setLastDamage(double d) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public int getNoDamageTicks() - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void setNoDamageTicks(int i) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public boolean teleport(Location lctn) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public boolean teleport(Entity entity) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public Entity getPassenger() - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public boolean setPassenger(Entity entity) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public boolean isEmpty() - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public boolean eject() - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void saveData() - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void loadData() - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public boolean isSleeping() - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public int getSleepTicks() - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public List getNearbyEntities(double d, double d1, double d2) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public boolean isDead() - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public float getFallDistance() - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void setFallDistance(float f) - { - } - - @Override - public void setSleepingIgnored(boolean bln) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public boolean isSleepingIgnored() - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void awardAchievement(Achievement a) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void removeAchievement(Achievement achievement) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public boolean hasAchievement(Achievement achievement) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void incrementStatistic(Statistic ststc) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void decrementStatistic(Statistic statistic) throws IllegalArgumentException - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void incrementStatistic(Statistic ststc, int i) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void decrementStatistic(Statistic statistic, int i) throws IllegalArgumentException - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void setStatistic(Statistic statistic, int i) throws IllegalArgumentException - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public int getStatistic(Statistic statistic) throws IllegalArgumentException - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void incrementStatistic(Statistic ststc, Material mtrl) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void decrementStatistic(Statistic statistic, Material material) throws IllegalArgumentException - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public int getStatistic(Statistic statistic, Material material) throws IllegalArgumentException - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void incrementStatistic(Statistic ststc, Material mtrl, int i) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void decrementStatistic(Statistic statistic, Material material, int i) throws IllegalArgumentException - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void setStatistic(Statistic statistic, Material material, int i) throws IllegalArgumentException - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void incrementStatistic(Statistic statistic, EntityType entityType) throws IllegalArgumentException - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void decrementStatistic(Statistic statistic, EntityType entityType) throws IllegalArgumentException - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public int getStatistic(Statistic statistic, EntityType entityType) throws IllegalArgumentException - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void incrementStatistic(Statistic statistic, EntityType entityType, int i) throws IllegalArgumentException - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void decrementStatistic(Statistic statistic, EntityType entityType, int i) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void setStatistic(Statistic statistic, EntityType entityType, int i) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void playNote(Location lctn, byte b, byte b1) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void sendBlockChange(Location lctn, Material mtrl, byte b) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void sendBlockChange(Location lctn, int i, byte b) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void setLastDamageCause(EntityDamageEvent ede) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public EntityDamageEvent getLastDamageCause() - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public void playEffect(Location lctn, Effect effect, int i) - { - throw new UnsupportedOperationException(tl("notSupportedYet")); - } - - @Override - public boolean sendChunkChange(Location lctn, int i, int i1, int i2, byte[] bytes) - { - return true; - } - - @Override - public void playNote(Location lctn, Instrument i, Note note) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setPlayerTime(long l, boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public long getPlayerTime() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public long getPlayerTimeOffset() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isPlayerTimeRelative() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void resetPlayerTime() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isPermissionSet(String string) - { - return false; - } - - @Override - public boolean isPermissionSet(Permission prmsn) - { - return false; - } - - @Override - public boolean hasPermission(String string) - { - return false; - } - - @Override - public boolean hasPermission(Permission prmsn) - { - return false; - } - - @Override - public PermissionAttachment addAttachment(Plugin plugin, String string, boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public PermissionAttachment addAttachment(Plugin plugin) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public PermissionAttachment addAttachment(Plugin plugin, String string, boolean bln, int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public PermissionAttachment addAttachment(Plugin plugin, int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void removeAttachment(PermissionAttachment pa) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void recalculatePermissions() - { - } - - @Override - public Set getEffectivePermissions() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void sendMap(MapView mv) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public GameMode getGameMode() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setGameMode(GameMode gm) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getLevel() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setLevel(int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getTotalExperience() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setTotalExperience(int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public float getExhaustion() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setExhaustion(float f) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public float getSaturation() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setSaturation(float f) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getFoodLevel() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setFoodLevel(int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isSprinting() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setSprinting(boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setPlayerListName(String name) - { - } - - @Override - public String getPlayerListName() - { - return name; - } - - @Override - public int getTicksLived() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setTicksLived(int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public double getMaxHealth() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void giveExp(int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public float getExp() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setExp(float f) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean teleport(Location lctn, TeleportCause tc) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean teleport(Entity entity, TeleportCause tc) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Player getKiller() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - void setName(final String name) - { - this.name = base.getName(); - if (this.name == null) - { - this.name = name; - } - } - - @Override - public void sendPluginMessage(Plugin plugin, String string, byte[] bytes) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Set getListeningPluginChannels() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setAllowFlight(boolean bln) - { - allowFlight = bln; - } - - @Override - public boolean getAllowFlight() - { - return allowFlight; - } - - @Override - public void setBedSpawnLocation(Location lctn) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setBedSpawnLocation(Location lctn, boolean force) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void playEffect(EntityEffect ee) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void hidePlayer(Player player) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void showPlayer(Player player) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean canSee(Player player) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean addPotionEffect(PotionEffect pe) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean addPotionEffect(PotionEffect pe, boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean addPotionEffects(Collection clctn) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean hasPotionEffect(PotionEffectType pet) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void removePotionEffect(PotionEffectType pet) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Collection getActivePotionEffects() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public T launchProjectile(Class arg0) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public EntityType getType() - { - return EntityType.PLAYER; - } - - @Override - public void playEffect(Location lctn, Effect effect, T t) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean setWindowProperty(Property prprt, int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public InventoryView getOpenInventory() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public InventoryView openInventory(Inventory invntr) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public InventoryView openWorkbench(Location lctn, boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public InventoryView openEnchanting(Location lctn, boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void openInventory(InventoryView iv) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void closeInventory() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public ItemStack getItemOnCursor() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setItemOnCursor(ItemStack is) - { - 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 boolean isConversing() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void acceptConversationInput(String string) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean beginConversation(Conversation c) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void abandonConversation(Conversation c) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void sendMessage(String[] strings) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isBlocking() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void abandonConversation(Conversation arg0, ConversationAbandonedEvent arg1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isFlying() - { - return isFlying; - } - - @Override - public void setFlying(boolean arg0) - { - isFlying = arg0; - } - - @Override - public int getExpToLevel() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean hasLineOfSight(Entity entity) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isValid() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setFlySpeed(float value) throws IllegalArgumentException - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setWalkSpeed(float value) throws IllegalArgumentException - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public float getFlySpeed() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public float getWalkSpeed() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Inventory getEnderChest() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void playSound(Location arg0, Sound arg1, float arg2, float arg3) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void giveExpLevels(int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean getRemoveWhenFarAway() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setRemoveWhenFarAway(boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public EntityEquipment getEquipment() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setCanPickupItems(boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean getCanPickupItems() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Location getLocation(Location lctn) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setTexturePack(String string) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setResourcePack(String s) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setMaxHealth(double i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void resetMaxHealth() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setCustomName(String string) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public String getCustomName() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setCustomNameVisible(boolean bln) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isCustomNameVisible() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setPlayerWeather(WeatherType arg0) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public WeatherType getPlayerWeather() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void resetPlayerWeather() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isOnGround() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Scoreboard getScoreboard() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setScoreboard(Scoreboard scrbrd) throws IllegalArgumentException, IllegalStateException - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int _INVALID_getLastDamage() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void _INVALID_setLastDamage(int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void _INVALID_damage(int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void _INVALID_damage(int i, Entity entity) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int _INVALID_getHealth() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void _INVALID_setHealth(int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int _INVALID_getMaxHealth() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void _INVALID_setMaxHealth(int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void playSound(Location arg0, String arg1, float arg2, float arg3) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isHealthScaled() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setHealthScaled(boolean arg0) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setHealthScale(double arg0) throws IllegalArgumentException - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public double getHealthScale() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isLeashed() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Entity getLeashHolder() throws IllegalStateException - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean setLeashHolder(Entity arg0) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public T launchProjectile(Class type, Vector vector) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void sendSignChange(Location arg0, String[] arg1) throws IllegalArgumentException - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Location getBedSpawnLocation() - { - return null; - } - - @Override - public String getName() - { - return name; - } - - @Override - public UUID getUniqueId() - { - return base.getUniqueId(); - } - - @Override - public boolean isOp() - { - return base.isOp(); - } - - @Override - public void setOp(boolean value) - { - base.setOp(value); - } - - @Override - public boolean isOnline() - { - return base.isOnline(); - } - - @Override - public boolean isBanned() - { - if (base.getName() == null && getName() != null) - { - return server.getBanList(BanList.Type.NAME).isBanned(getName()); - } - return base.isBanned(); - } - - @Override - public void setBanned(boolean banned) - { - if (base.getName() == null && getName() != null) - { - if (banned) - { - server.getBanList(BanList.Type.NAME).addBan(getName(), null, null, null); - } - else - { - server.getBanList(BanList.Type.NAME).pardon(getName()); - } - } - base.setBanned(banned); - } - - @Override - public boolean isWhitelisted() - { - return base.isWhitelisted(); - } - - @Override - public void setWhitelisted(boolean value) - { - base.setWhitelisted(value); - } - - @Override - public Player getPlayer() - { - return base.getPlayer(); - } - - @Override - public long getFirstPlayed() - { - return base.getFirstPlayed(); - } - - @Override - public long getLastPlayed() - { - return base.getLastPlayed(); - } - - @Override - public boolean hasPlayedBefore() - { - return base.hasPlayedBefore(); - } - - @Override - public Map serialize() - { - return base.serialize(); - } +import java.net.InetSocketAddress; +import java.util.*; + +import static com.earth2me.essentials.I18n.tl; + + +public class OfflinePlayer implements Player { + private final transient Server server; + private transient Location location = new Location(null, 0, 0, 0, 0, 0); + private transient World world; + private transient org.bukkit.OfflinePlayer base; + private boolean allowFlight = false; + private boolean isFlying = false; + private String name = null; + + public OfflinePlayer(final UUID uuid, final Server server) { + this.server = server; + this.world = server.getWorlds().get(0); + this.base = server.getOfflinePlayer(uuid); + this.name = base.getName(); + } + + public OfflinePlayer(final String name, final Server server) { + this.server = server; + this.world = server.getWorlds().get(0); + this.base = server.getOfflinePlayer(name); + this.name = name; + } + + @Override + public void sendMessage(final String string) { + } + + @Override + public String getDisplayName() { + return base.getName(); + } + + @Override + public void setDisplayName(String string) { + } + + @Override + public void setCompassTarget(Location lctn) { + } + + @Override + public InetSocketAddress getAddress() { + return null; + } + + @Override + public void kickPlayer(String string) { + } + + @Override + public PlayerInventory getInventory() { + return null; + } + + @Override + public ItemStack getItemInHand() { + return null; + } + + @Override + public void setItemInHand(ItemStack is) { + } + + @Override + public double getHealth() { + return 0; + } + + @Override + public void setHealth(double d) { + } + + @Override + public Egg throwEgg() { + return null; + } + + @Override + public Snowball throwSnowball() { + return null; + } + + @Override + public Arrow shootArrow() { + return null; + } + + @Override + public boolean isInsideVehicle() { + return false; + } + + @Override + public boolean leaveVehicle() { + return false; + } + + @Override + public Vehicle getVehicle() { + return null; + } + + @Override + public Location getLocation() { + return location; + } + + @Override + public World getWorld() { + return world; + } + + public void setLocation(Location loc) { + location = loc; + world = loc.getWorld(); + } + + public void teleportTo(Location lctn) { + } + + public void teleportTo(Entity entity) { + } + + @Override + public int getEntityId() { + return -1; + } + + @Override + public boolean performCommand(String string) { + return false; + } + + @Override + public int getRemainingAir() { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void setRemainingAir(int i) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public int getMaximumAir() { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void setMaximumAir(int i) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public boolean isSneaking() { + return false; + } + + @Override + public void setSneaking(boolean bln) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void updateInventory() { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void chat(String string) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public double getEyeHeight() { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public double getEyeHeight(boolean bln) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public List getLineOfSight(HashSet hs, int i) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public Block getTargetBlock(HashSet hs, int i) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public List getLastTwoTargetBlocks(HashSet hs, int i) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public int getFireTicks() { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public int getMaxFireTicks() { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void setFireTicks(int i) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void remove() { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public Server getServer() { + return server; + } + + public Vector getMomentum() { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + public void setMomentum(Vector vector) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void setVelocity(Vector vector) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public Vector getVelocity() { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void damage(double d) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void damage(double d, Entity entity) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public Location getEyeLocation() { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void sendRawMessage(String string) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public Location getCompassTarget() { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public int getMaximumNoDamageTicks() { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void setMaximumNoDamageTicks(int i) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public double getLastDamage() { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void setLastDamage(double d) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public int getNoDamageTicks() { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void setNoDamageTicks(int i) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public boolean teleport(Location lctn) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public boolean teleport(Entity entity) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public Entity getPassenger() { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public boolean setPassenger(Entity entity) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public boolean isEmpty() { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public boolean eject() { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void saveData() { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void loadData() { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public boolean isSleeping() { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public int getSleepTicks() { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public List getNearbyEntities(double d, double d1, double d2) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public boolean isDead() { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public float getFallDistance() { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void setFallDistance(float f) { + } + + @Override + public void setSleepingIgnored(boolean bln) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public boolean isSleepingIgnored() { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void awardAchievement(Achievement a) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void removeAchievement(Achievement achievement) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public boolean hasAchievement(Achievement achievement) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void incrementStatistic(Statistic ststc) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void decrementStatistic(Statistic statistic) throws IllegalArgumentException { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void incrementStatistic(Statistic ststc, int i) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void decrementStatistic(Statistic statistic, int i) throws IllegalArgumentException { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void setStatistic(Statistic statistic, int i) throws IllegalArgumentException { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public int getStatistic(Statistic statistic) throws IllegalArgumentException { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void incrementStatistic(Statistic ststc, Material mtrl) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void decrementStatistic(Statistic statistic, Material material) throws IllegalArgumentException { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public int getStatistic(Statistic statistic, Material material) throws IllegalArgumentException { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void incrementStatistic(Statistic ststc, Material mtrl, int i) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void decrementStatistic(Statistic statistic, Material material, int i) throws IllegalArgumentException { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void setStatistic(Statistic statistic, Material material, int i) throws IllegalArgumentException { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void incrementStatistic(Statistic statistic, EntityType entityType) throws IllegalArgumentException { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void decrementStatistic(Statistic statistic, EntityType entityType) throws IllegalArgumentException { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public int getStatistic(Statistic statistic, EntityType entityType) throws IllegalArgumentException { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void incrementStatistic(Statistic statistic, EntityType entityType, int i) throws IllegalArgumentException { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void decrementStatistic(Statistic statistic, EntityType entityType, int i) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void setStatistic(Statistic statistic, EntityType entityType, int i) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void playNote(Location lctn, byte b, byte b1) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void sendBlockChange(Location lctn, Material mtrl, byte b) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void sendBlockChange(Location lctn, int i, byte b) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void setLastDamageCause(EntityDamageEvent ede) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public EntityDamageEvent getLastDamageCause() { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public void playEffect(Location lctn, Effect effect, int i) { + throw new UnsupportedOperationException(tl("notSupportedYet")); + } + + @Override + public boolean sendChunkChange(Location lctn, int i, int i1, int i2, byte[] bytes) { + return true; + } + + @Override + public void playNote(Location lctn, Instrument i, Note note) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setPlayerTime(long l, boolean bln) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public long getPlayerTime() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public long getPlayerTimeOffset() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isPlayerTimeRelative() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void resetPlayerTime() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isPermissionSet(String string) { + return false; + } + + @Override + public boolean isPermissionSet(Permission prmsn) { + return false; + } + + @Override + public boolean hasPermission(String string) { + return false; + } + + @Override + public boolean hasPermission(Permission prmsn) { + return false; + } + + @Override + public PermissionAttachment addAttachment(Plugin plugin, String string, boolean bln) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public PermissionAttachment addAttachment(Plugin plugin) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public PermissionAttachment addAttachment(Plugin plugin, String string, boolean bln, int i) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public PermissionAttachment addAttachment(Plugin plugin, int i) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void removeAttachment(PermissionAttachment pa) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void recalculatePermissions() { + } + + @Override + public Set getEffectivePermissions() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void sendMap(MapView mv) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public GameMode getGameMode() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setGameMode(GameMode gm) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int getLevel() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setLevel(int i) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int getTotalExperience() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setTotalExperience(int i) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public float getExhaustion() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setExhaustion(float f) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public float getSaturation() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setSaturation(float f) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int getFoodLevel() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setFoodLevel(int i) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isSprinting() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setSprinting(boolean bln) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setPlayerListName(String name) { + } + + @Override + public String getPlayerListName() { + return name; + } + + @Override + public int getTicksLived() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setTicksLived(int i) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public double getMaxHealth() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void giveExp(int i) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public float getExp() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setExp(float f) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean teleport(Location lctn, TeleportCause tc) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean teleport(Entity entity, TeleportCause tc) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Player getKiller() { + throw new UnsupportedOperationException("Not supported yet."); + } + + void setName(final String name) { + this.name = base.getName(); + if (this.name == null) { + this.name = name; + } + } + + @Override + public void sendPluginMessage(Plugin plugin, String string, byte[] bytes) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Set getListeningPluginChannels() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setAllowFlight(boolean bln) { + allowFlight = bln; + } + + @Override + public boolean getAllowFlight() { + return allowFlight; + } + + @Override + public void setBedSpawnLocation(Location lctn) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setBedSpawnLocation(Location lctn, boolean force) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void playEffect(EntityEffect ee) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void hidePlayer(Player player) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void showPlayer(Player player) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean canSee(Player player) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean addPotionEffect(PotionEffect pe) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean addPotionEffect(PotionEffect pe, boolean bln) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean addPotionEffects(Collection clctn) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean hasPotionEffect(PotionEffectType pet) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void removePotionEffect(PotionEffectType pet) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Collection getActivePotionEffects() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public T launchProjectile(Class arg0) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public EntityType getType() { + return EntityType.PLAYER; + } + + @Override + public void playEffect(Location lctn, Effect effect, T t) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean setWindowProperty(Property prprt, int i) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public InventoryView getOpenInventory() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public InventoryView openInventory(Inventory invntr) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public InventoryView openWorkbench(Location lctn, boolean bln) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public InventoryView openEnchanting(Location lctn, boolean bln) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void openInventory(InventoryView iv) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void closeInventory() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public ItemStack getItemOnCursor() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setItemOnCursor(ItemStack is) { + 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 boolean isConversing() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void acceptConversationInput(String string) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean beginConversation(Conversation c) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void abandonConversation(Conversation c) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void sendMessage(String[] strings) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isBlocking() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void abandonConversation(Conversation arg0, ConversationAbandonedEvent arg1) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isFlying() { + return isFlying; + } + + @Override + public void setFlying(boolean arg0) { + isFlying = arg0; + } + + @Override + public int getExpToLevel() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean hasLineOfSight(Entity entity) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isValid() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setFlySpeed(float value) throws IllegalArgumentException { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setWalkSpeed(float value) throws IllegalArgumentException { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public float getFlySpeed() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public float getWalkSpeed() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Inventory getEnderChest() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void playSound(Location arg0, Sound arg1, float arg2, float arg3) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void giveExpLevels(int i) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean getRemoveWhenFarAway() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setRemoveWhenFarAway(boolean bln) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public EntityEquipment getEquipment() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setCanPickupItems(boolean bln) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean getCanPickupItems() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Location getLocation(Location lctn) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setTexturePack(String string) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setResourcePack(String s) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setMaxHealth(double i) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void resetMaxHealth() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setCustomName(String string) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public String getCustomName() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setCustomNameVisible(boolean bln) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isCustomNameVisible() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setPlayerWeather(WeatherType arg0) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public WeatherType getPlayerWeather() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void resetPlayerWeather() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isOnGround() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Scoreboard getScoreboard() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setScoreboard(Scoreboard scrbrd) throws IllegalArgumentException, IllegalStateException { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int _INVALID_getLastDamage() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void _INVALID_setLastDamage(int i) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void _INVALID_damage(int i) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void _INVALID_damage(int i, Entity entity) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int _INVALID_getHealth() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void _INVALID_setHealth(int i) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int _INVALID_getMaxHealth() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void _INVALID_setMaxHealth(int i) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void playSound(Location arg0, String arg1, float arg2, float arg3) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isHealthScaled() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setHealthScaled(boolean arg0) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setHealthScale(double arg0) throws IllegalArgumentException { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public double getHealthScale() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isLeashed() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Entity getLeashHolder() throws IllegalStateException { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean setLeashHolder(Entity arg0) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public T launchProjectile(Class type, Vector vector) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void sendSignChange(Location arg0, String[] arg1) throws IllegalArgumentException { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Location getBedSpawnLocation() { + return null; + } + + @Override + public String getName() { + return name; + } + + @Override + public UUID getUniqueId() { + return base.getUniqueId(); + } + + @Override + public boolean isOp() { + return base.isOp(); + } + + @Override + public void setOp(boolean value) { + base.setOp(value); + } + + @Override + public boolean isOnline() { + return base.isOnline(); + } + + @Override + public boolean isBanned() { + if (base.getName() == null && getName() != null) { + return server.getBanList(BanList.Type.NAME).isBanned(getName()); + } + return base.isBanned(); + } + + @Override + public void setBanned(boolean banned) { + if (base.getName() == null && getName() != null) { + if (banned) { + server.getBanList(BanList.Type.NAME).addBan(getName(), null, null, null); + } else { + server.getBanList(BanList.Type.NAME).pardon(getName()); + } + } + base.setBanned(banned); + } + + @Override + public boolean isWhitelisted() { + return base.isWhitelisted(); + } + + @Override + public void setWhitelisted(boolean value) { + base.setWhitelisted(value); + } + + @Override + public Player getPlayer() { + return base.getPlayer(); + } + + @Override + public long getFirstPlayed() { + return base.getFirstPlayed(); + } + + @Override + public long getLastPlayed() { + return base.getLastPlayed(); + } + + @Override + public boolean hasPlayedBefore() { + return base.hasPlayedBefore(); + } + + @Override + public Map serialize() { + return base.serialize(); + } } diff --git a/Essentials/src/com/earth2me/essentials/PlayerExtension.java b/Essentials/src/com/earth2me/essentials/PlayerExtension.java index 36c2289e3..211f6ee9c 100644 --- a/Essentials/src/com/earth2me/essentials/PlayerExtension.java +++ b/Essentials/src/com/earth2me/essentials/PlayerExtension.java @@ -1,48 +1,35 @@ package com.earth2me.essentials; -import lombok.Delegate; import org.bukkit.Location; import org.bukkit.Server; import org.bukkit.World; -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.ServerOperator; -public class PlayerExtension -{ - protected Player base; +public class PlayerExtension { + protected Player base; - public PlayerExtension(final Player base) - { - this.base = base; - } + public PlayerExtension(final Player base) { + this.base = base; + } - public final Player getBase() - { - return base; - } + public final Player getBase() { + return base; + } - public final Player setBase(final Player base) - { - return this.base = base; - } - - public Server getServer() - { - return base.getServer(); - } - - public World getWorld() { - return base.getWorld(); - } - - public Location getLocation() { - return base.getLocation(); - } + public final Player setBase(final Player base) { + return this.base = base; + } + + public Server getServer() { + return base.getServer(); + } + + public World getWorld() { + return base.getWorld(); + } + + public Location getLocation() { + return base.getLocation(); + } } diff --git a/Essentials/src/com/earth2me/essentials/PlayerList.java b/Essentials/src/com/earth2me/essentials/PlayerList.java index fb8a1f0bc..9bf6c1aaf 100644 --- a/Essentials/src/com/earth2me/essentials/PlayerList.java +++ b/Essentials/src/com/earth2me/essentials/PlayerList.java @@ -1,156 +1,123 @@ package com.earth2me.essentials; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.utils.FormatUtil; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; import org.bukkit.Server; -import org.bukkit.entity.Player; + +import java.util.*; + +import static com.earth2me.essentials.I18n.tl; -public class PlayerList -{ - // Cosmetic list formatting - public static String listUsers(final IEssentials ess, final List users, final String seperator) - { - final StringBuilder groupString = new StringBuilder(); - Collections.sort(users); - boolean needComma = false; - for (User user : users) - { - if (needComma) - { - groupString.append(seperator); - } - needComma = true; - if (user.isAfk()) - { - groupString.append(tl("listAfkTag")); - } - if (user.isHidden()) - { - groupString.append(tl("listHiddenTag")); - } - user.setDisplayNick(); - groupString.append(user.getDisplayName()); - groupString.append("\u00a7f"); - } - return groupString.toString(); - } +public class PlayerList { + // Cosmetic list formatting + public static String listUsers(final IEssentials ess, final List users, final String seperator) { + final StringBuilder groupString = new StringBuilder(); + Collections.sort(users); + boolean needComma = false; + for (User user : users) { + if (needComma) { + groupString.append(seperator); + } + needComma = true; + if (user.isAfk()) { + groupString.append(tl("listAfkTag")); + } + if (user.isHidden()) { + groupString.append(tl("listHiddenTag")); + } + user.setDisplayNick(); + groupString.append(user.getDisplayName()); + groupString.append("\u00a7f"); + } + return groupString.toString(); + } - // Produce a user summary: There are 5 out of maximum 10 players online. - public static String listSummary(final IEssentials ess, final User user, final boolean showHidden) - { - Server server = ess.getServer(); - int playerHidden = 0; - int hiddenCount = 0; - for (User onlinePlayer : ess.getOnlineUsers()) - { - if (onlinePlayer.isHidden() || (user != null && !user.getBase().canSee(onlinePlayer.getBase()))) - { - playerHidden++; - if (showHidden || user.getBase().canSee(onlinePlayer.getBase())) - { - hiddenCount++; - } - } - } - String online; - if (hiddenCount > 0) - { - online = tl("listAmountHidden", ess.getOnlinePlayers().size() - playerHidden, hiddenCount, server.getMaxPlayers()); - } - else - { - online = tl("listAmount", ess.getOnlinePlayers().size() - playerHidden, server.getMaxPlayers()); - } - return online; - } + // Produce a user summary: There are 5 out of maximum 10 players online. + public static String listSummary(final IEssentials ess, final User user, final boolean showHidden) { + Server server = ess.getServer(); + int playerHidden = 0; + int hiddenCount = 0; + for (User onlinePlayer : ess.getOnlineUsers()) { + if (onlinePlayer.isHidden() || (user != null && !user.getBase().canSee(onlinePlayer.getBase()))) { + playerHidden++; + if (showHidden || user.getBase().canSee(onlinePlayer.getBase())) { + hiddenCount++; + } + } + } + String online; + if (hiddenCount > 0) { + online = tl("listAmountHidden", ess.getOnlinePlayers().size() - playerHidden, hiddenCount, server.getMaxPlayers()); + } else { + online = tl("listAmount", ess.getOnlinePlayers().size() - playerHidden, server.getMaxPlayers()); + } + return online; + } - // Build the basic player list, divided by groups. - public static Map> getPlayerLists(final IEssentials ess, final User sender, final boolean showHidden) - { - Server server = ess.getServer(); - final Map> playerList = new HashMap>(); - for (User onlineUser : ess.getOnlineUsers()) - { - if ((sender == null && !showHidden && onlineUser.isHidden()) || - (sender != null && !showHidden && !sender.getBase().canSee(onlineUser.getBase()))) - { - continue; - } - final String group = FormatUtil.stripFormat(FormatUtil.stripEssentialsFormat(onlineUser.getGroup().toLowerCase())); - List list = playerList.get(group); - if (list == null) - { - list = new ArrayList(); - playerList.put(group, list); - } - list.add(onlineUser); - } - return playerList; - } + // Build the basic player list, divided by groups. + public static Map> getPlayerLists(final IEssentials ess, final User sender, final boolean showHidden) { + Server server = ess.getServer(); + final Map> playerList = new HashMap>(); + for (User onlineUser : ess.getOnlineUsers()) { + if ((sender == null && !showHidden && onlineUser.isHidden()) || (sender != null && !showHidden && !sender.getBase().canSee(onlineUser.getBase()))) { + continue; + } + final String group = FormatUtil.stripFormat(FormatUtil.stripEssentialsFormat(onlineUser.getGroup().toLowerCase())); + List list = playerList.get(group); + if (list == null) { + list = new ArrayList(); + playerList.put(group, list); + } + list.add(onlineUser); + } + return playerList; + } - // Handle the merging of groups - public static List getMergedList(final IEssentials ess, final Map> playerList, final String groupName) - { - final Set configGroups = ess.getSettings().getListGroupConfig().keySet(); - final List users = new ArrayList(); - for (String configGroup : configGroups) - { - if (configGroup.equalsIgnoreCase(groupName)) - { - String[] groupValues = ess.getSettings().getListGroupConfig().get(configGroup).toString().trim().split(" "); - for (String groupValue : groupValues) - { - groupValue = groupValue.toLowerCase(Locale.ENGLISH); - if (groupValue == null || groupValue.isEmpty()) - { - continue; - } - List u = playerList.get(groupValue.trim()); - if (u == null || u.isEmpty()) - { - continue; - } - playerList.remove(groupValue); - users.addAll(u); - } - } - } - return users; - } + // Handle the merging of groups + public static List getMergedList(final IEssentials ess, final Map> playerList, final String groupName) { + final Set configGroups = ess.getSettings().getListGroupConfig().keySet(); + final List users = new ArrayList(); + for (String configGroup : configGroups) { + if (configGroup.equalsIgnoreCase(groupName)) { + String[] groupValues = ess.getSettings().getListGroupConfig().get(configGroup).toString().trim().split(" "); + for (String groupValue : groupValues) { + groupValue = groupValue.toLowerCase(Locale.ENGLISH); + if (groupValue == null || groupValue.isEmpty()) { + continue; + } + List u = playerList.get(groupValue.trim()); + if (u == null || u.isEmpty()) { + continue; + } + playerList.remove(groupValue); + users.addAll(u); + } + } + } + return users; + } - // Output a playerlist of just a single group, /list - public static String listGroupUsers(final IEssentials ess, final Map> playerList, final String groupName) throws Exception - { - final List users = getMergedList(ess, playerList, groupName); - final List groupUsers = playerList.get(groupName); - if (groupUsers != null && !groupUsers.isEmpty()) - { - users.addAll(groupUsers); - } - if (users == null || users.isEmpty()) - { - throw new Exception(tl("groupDoesNotExist")); - } - final StringBuilder displayGroupName = new StringBuilder(); - displayGroupName.append(Character.toTitleCase(groupName.charAt(0))); - displayGroupName.append(groupName.substring(1)); - return outputFormat(displayGroupName.toString(), listUsers(ess, users, ", ")); - } + // Output a playerlist of just a single group, /list + public static String listGroupUsers(final IEssentials ess, final Map> playerList, final String groupName) throws Exception { + final List users = getMergedList(ess, playerList, groupName); + final List groupUsers = playerList.get(groupName); + if (groupUsers != null && !groupUsers.isEmpty()) { + users.addAll(groupUsers); + } + if (users == null || users.isEmpty()) { + throw new Exception(tl("groupDoesNotExist")); + } + final StringBuilder displayGroupName = new StringBuilder(); + displayGroupName.append(Character.toTitleCase(groupName.charAt(0))); + displayGroupName.append(groupName.substring(1)); + return outputFormat(displayGroupName.toString(), listUsers(ess, users, ", ")); + } - // Build the output string - public static String outputFormat(final String group, final String message) - { - final StringBuilder outputString = new StringBuilder(); - outputString.append(tl("listGroupTag", FormatUtil.replaceFormat(group))); - outputString.append(message); - return outputString.toString(); - } + // Build the output string + public static String outputFormat(final String group, final String message) { + final StringBuilder outputString = new StringBuilder(); + outputString.append(tl("listGroupTag", FormatUtil.replaceFormat(group))); + outputString.append(message); + return outputString.toString(); + } } diff --git a/Essentials/src/com/earth2me/essentials/PlayerTarget.java b/Essentials/src/com/earth2me/essentials/PlayerTarget.java index 6fd714ca1..d582f612e 100644 --- a/Essentials/src/com/earth2me/essentials/PlayerTarget.java +++ b/Essentials/src/com/earth2me/essentials/PlayerTarget.java @@ -5,18 +5,15 @@ import org.bukkit.Location; import org.bukkit.entity.Player; -public class PlayerTarget implements ITarget -{ - private final String name; +public class PlayerTarget implements ITarget { + private final String name; - public PlayerTarget(Player entity) - { - this.name = entity.getName(); - } + public PlayerTarget(Player entity) { + this.name = entity.getName(); + } - @Override - public Location getLocation() - { - return Bukkit.getServer().getPlayerExact(name).getLocation(); - } + @Override + public Location getLocation() { + return Bukkit.getServer().getPlayerExact(name).getLocation(); + } } \ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/Potions.java b/Essentials/src/com/earth2me/essentials/Potions.java index 616225814..b0d699f76 100644 --- a/Essentials/src/com/earth2me/essentials/Potions.java +++ b/Essentials/src/com/earth2me/essentials/Potions.java @@ -1,145 +1,137 @@ package com.earth2me.essentials; import com.earth2me.essentials.utils.NumberUtil; +import org.bukkit.potion.PotionEffectType; + import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Set; -import org.bukkit.potion.PotionEffectType; -public class Potions -{ - private static final Map POTIONS = new HashMap(); - private static final Map ALIASPOTIONS = new HashMap(); +public class Potions { + private static final Map POTIONS = new HashMap(); + private static final Map ALIASPOTIONS = new HashMap(); - static - { + static { - POTIONS.put("speed", PotionEffectType.SPEED); - ALIASPOTIONS.put("fast", PotionEffectType.SPEED); - ALIASPOTIONS.put("runfast", PotionEffectType.SPEED); - ALIASPOTIONS.put("sprint", PotionEffectType.SPEED); - ALIASPOTIONS.put("swift", PotionEffectType.SPEED); + POTIONS.put("speed", PotionEffectType.SPEED); + ALIASPOTIONS.put("fast", PotionEffectType.SPEED); + ALIASPOTIONS.put("runfast", PotionEffectType.SPEED); + ALIASPOTIONS.put("sprint", PotionEffectType.SPEED); + ALIASPOTIONS.put("swift", PotionEffectType.SPEED); - POTIONS.put("slowness", PotionEffectType.SLOW); - ALIASPOTIONS.put("slow", PotionEffectType.SLOW); - ALIASPOTIONS.put("sluggish", PotionEffectType.SLOW); + POTIONS.put("slowness", PotionEffectType.SLOW); + ALIASPOTIONS.put("slow", PotionEffectType.SLOW); + ALIASPOTIONS.put("sluggish", PotionEffectType.SLOW); - POTIONS.put("haste", PotionEffectType.FAST_DIGGING); - ALIASPOTIONS.put("superpick", PotionEffectType.FAST_DIGGING); - ALIASPOTIONS.put("quickmine", PotionEffectType.FAST_DIGGING); - ALIASPOTIONS.put("digspeed", PotionEffectType.FAST_DIGGING); - ALIASPOTIONS.put("digfast", PotionEffectType.FAST_DIGGING); - ALIASPOTIONS.put("sharp", PotionEffectType.FAST_DIGGING); + POTIONS.put("haste", PotionEffectType.FAST_DIGGING); + ALIASPOTIONS.put("superpick", PotionEffectType.FAST_DIGGING); + ALIASPOTIONS.put("quickmine", PotionEffectType.FAST_DIGGING); + ALIASPOTIONS.put("digspeed", PotionEffectType.FAST_DIGGING); + ALIASPOTIONS.put("digfast", PotionEffectType.FAST_DIGGING); + ALIASPOTIONS.put("sharp", PotionEffectType.FAST_DIGGING); - POTIONS.put("fatigue", PotionEffectType.SLOW_DIGGING); - ALIASPOTIONS.put("slow", PotionEffectType.SLOW_DIGGING); - ALIASPOTIONS.put("dull", PotionEffectType.SLOW_DIGGING); + POTIONS.put("fatigue", PotionEffectType.SLOW_DIGGING); + ALIASPOTIONS.put("slow", PotionEffectType.SLOW_DIGGING); + ALIASPOTIONS.put("dull", PotionEffectType.SLOW_DIGGING); - POTIONS.put("strength", PotionEffectType.INCREASE_DAMAGE); - ALIASPOTIONS.put("strong", PotionEffectType.INCREASE_DAMAGE); - ALIASPOTIONS.put("bull", PotionEffectType.INCREASE_DAMAGE); - ALIASPOTIONS.put("attack", PotionEffectType.INCREASE_DAMAGE); + POTIONS.put("strength", PotionEffectType.INCREASE_DAMAGE); + ALIASPOTIONS.put("strong", PotionEffectType.INCREASE_DAMAGE); + ALIASPOTIONS.put("bull", PotionEffectType.INCREASE_DAMAGE); + ALIASPOTIONS.put("attack", PotionEffectType.INCREASE_DAMAGE); - POTIONS.put("heal", PotionEffectType.HEAL); - ALIASPOTIONS.put("healthy", PotionEffectType.HEAL); - ALIASPOTIONS.put("instaheal", PotionEffectType.HEAL); + POTIONS.put("heal", PotionEffectType.HEAL); + ALIASPOTIONS.put("healthy", PotionEffectType.HEAL); + ALIASPOTIONS.put("instaheal", PotionEffectType.HEAL); - POTIONS.put("harm", PotionEffectType.HARM); - ALIASPOTIONS.put("harming", PotionEffectType.HARM); - ALIASPOTIONS.put("injure", PotionEffectType.HARM); - ALIASPOTIONS.put("damage", PotionEffectType.HARM); - ALIASPOTIONS.put("inflict", PotionEffectType.HARM); + POTIONS.put("harm", PotionEffectType.HARM); + ALIASPOTIONS.put("harming", PotionEffectType.HARM); + ALIASPOTIONS.put("injure", PotionEffectType.HARM); + ALIASPOTIONS.put("damage", PotionEffectType.HARM); + ALIASPOTIONS.put("inflict", PotionEffectType.HARM); - POTIONS.put("jump", PotionEffectType.JUMP); - ALIASPOTIONS.put("leap", PotionEffectType.JUMP); + POTIONS.put("jump", PotionEffectType.JUMP); + ALIASPOTIONS.put("leap", PotionEffectType.JUMP); - POTIONS.put("nausea", PotionEffectType.CONFUSION); - ALIASPOTIONS.put("sick", PotionEffectType.CONFUSION); - ALIASPOTIONS.put("sickness", PotionEffectType.CONFUSION); - ALIASPOTIONS.put("confusion", PotionEffectType.CONFUSION); + POTIONS.put("nausea", PotionEffectType.CONFUSION); + ALIASPOTIONS.put("sick", PotionEffectType.CONFUSION); + ALIASPOTIONS.put("sickness", PotionEffectType.CONFUSION); + ALIASPOTIONS.put("confusion", PotionEffectType.CONFUSION); - POTIONS.put("regeneration", PotionEffectType.REGENERATION); - ALIASPOTIONS.put("regen", PotionEffectType.REGENERATION); + POTIONS.put("regeneration", PotionEffectType.REGENERATION); + ALIASPOTIONS.put("regen", PotionEffectType.REGENERATION); - POTIONS.put("resistance", PotionEffectType.DAMAGE_RESISTANCE); - ALIASPOTIONS.put("dmgresist", PotionEffectType.DAMAGE_RESISTANCE); - ALIASPOTIONS.put("armor", PotionEffectType.DAMAGE_RESISTANCE); + POTIONS.put("resistance", PotionEffectType.DAMAGE_RESISTANCE); + ALIASPOTIONS.put("dmgresist", PotionEffectType.DAMAGE_RESISTANCE); + ALIASPOTIONS.put("armor", PotionEffectType.DAMAGE_RESISTANCE); - POTIONS.put("fireresist", PotionEffectType.FIRE_RESISTANCE); - ALIASPOTIONS.put("fireresistance", PotionEffectType.FIRE_RESISTANCE); - ALIASPOTIONS.put("resistfire", PotionEffectType.FIRE_RESISTANCE); + POTIONS.put("fireresist", PotionEffectType.FIRE_RESISTANCE); + ALIASPOTIONS.put("fireresistance", PotionEffectType.FIRE_RESISTANCE); + ALIASPOTIONS.put("resistfire", PotionEffectType.FIRE_RESISTANCE); - POTIONS.put("waterbreath", PotionEffectType.WATER_BREATHING); - ALIASPOTIONS.put("waterbreathing", PotionEffectType.WATER_BREATHING); + POTIONS.put("waterbreath", PotionEffectType.WATER_BREATHING); + ALIASPOTIONS.put("waterbreathing", PotionEffectType.WATER_BREATHING); - POTIONS.put("invisibility", PotionEffectType.INVISIBILITY); - ALIASPOTIONS.put("invisible", PotionEffectType.INVISIBILITY); - ALIASPOTIONS.put("invis", PotionEffectType.INVISIBILITY); - ALIASPOTIONS.put("vanish", PotionEffectType.INVISIBILITY); - ALIASPOTIONS.put("disappear", PotionEffectType.INVISIBILITY); + POTIONS.put("invisibility", PotionEffectType.INVISIBILITY); + ALIASPOTIONS.put("invisible", PotionEffectType.INVISIBILITY); + ALIASPOTIONS.put("invis", PotionEffectType.INVISIBILITY); + ALIASPOTIONS.put("vanish", PotionEffectType.INVISIBILITY); + ALIASPOTIONS.put("disappear", PotionEffectType.INVISIBILITY); - POTIONS.put("blindness", PotionEffectType.BLINDNESS); - ALIASPOTIONS.put("blind", PotionEffectType.BLINDNESS); + POTIONS.put("blindness", PotionEffectType.BLINDNESS); + ALIASPOTIONS.put("blind", PotionEffectType.BLINDNESS); - POTIONS.put("nightvision", PotionEffectType.NIGHT_VISION); - ALIASPOTIONS.put("vision", PotionEffectType.NIGHT_VISION); + POTIONS.put("nightvision", PotionEffectType.NIGHT_VISION); + ALIASPOTIONS.put("vision", PotionEffectType.NIGHT_VISION); - POTIONS.put("hunger", PotionEffectType.HUNGER); - ALIASPOTIONS.put("hungry", PotionEffectType.HUNGER); - ALIASPOTIONS.put("starve", PotionEffectType.HUNGER); + POTIONS.put("hunger", PotionEffectType.HUNGER); + ALIASPOTIONS.put("hungry", PotionEffectType.HUNGER); + ALIASPOTIONS.put("starve", PotionEffectType.HUNGER); - POTIONS.put("weakness", PotionEffectType.WEAKNESS); - ALIASPOTIONS.put("weak", PotionEffectType.WEAKNESS); + POTIONS.put("weakness", PotionEffectType.WEAKNESS); + ALIASPOTIONS.put("weak", PotionEffectType.WEAKNESS); - POTIONS.put("poison", PotionEffectType.POISON); - ALIASPOTIONS.put("venom", PotionEffectType.POISON); + POTIONS.put("poison", PotionEffectType.POISON); + ALIASPOTIONS.put("venom", PotionEffectType.POISON); - POTIONS.put("wither", PotionEffectType.WITHER); - ALIASPOTIONS.put("decay", PotionEffectType.WITHER); + POTIONS.put("wither", PotionEffectType.WITHER); + ALIASPOTIONS.put("decay", PotionEffectType.WITHER); - POTIONS.put("healthboost", PotionEffectType.HEALTH_BOOST); - ALIASPOTIONS.put("boost", PotionEffectType.HEALTH_BOOST); + POTIONS.put("healthboost", PotionEffectType.HEALTH_BOOST); + ALIASPOTIONS.put("boost", PotionEffectType.HEALTH_BOOST); - POTIONS.put("absorption", PotionEffectType.ABSORPTION); - ALIASPOTIONS.put("absorb", PotionEffectType.ABSORPTION); + POTIONS.put("absorption", PotionEffectType.ABSORPTION); + ALIASPOTIONS.put("absorb", PotionEffectType.ABSORPTION); - POTIONS.put("saturation", PotionEffectType.SATURATION); - ALIASPOTIONS.put("food", PotionEffectType.SATURATION); - - POTIONS.put("waterbreathing", PotionEffectType.WATER_BREATHING); - ALIASPOTIONS.put("underwaterbreathing", PotionEffectType.WATER_BREATHING); - ALIASPOTIONS.put("waterbreath", PotionEffectType.WATER_BREATHING); - ALIASPOTIONS.put("underwaterbreath", PotionEffectType.WATER_BREATHING); - ALIASPOTIONS.put("air", PotionEffectType.WATER_BREATHING); - } + POTIONS.put("saturation", PotionEffectType.SATURATION); + ALIASPOTIONS.put("food", PotionEffectType.SATURATION); - public static PotionEffectType getByName(String name) - { - PotionEffectType peffect; - if (NumberUtil.isInt(name)) - { - peffect = PotionEffectType.getById(Integer.parseInt(name)); - } - else - { - peffect = PotionEffectType.getByName(name.toUpperCase(Locale.ENGLISH)); - } - if (peffect == null) - { - peffect = POTIONS.get(name.toLowerCase(Locale.ENGLISH)); - } - if (peffect == null) - { - peffect = ALIASPOTIONS.get(name.toLowerCase(Locale.ENGLISH)); - } - return peffect; - } + POTIONS.put("waterbreathing", PotionEffectType.WATER_BREATHING); + ALIASPOTIONS.put("underwaterbreathing", PotionEffectType.WATER_BREATHING); + ALIASPOTIONS.put("waterbreath", PotionEffectType.WATER_BREATHING); + ALIASPOTIONS.put("underwaterbreath", PotionEffectType.WATER_BREATHING); + ALIASPOTIONS.put("air", PotionEffectType.WATER_BREATHING); + } - public static Set> entrySet() - { - return POTIONS.entrySet(); - } + public static PotionEffectType getByName(String name) { + PotionEffectType peffect; + if (NumberUtil.isInt(name)) { + peffect = PotionEffectType.getById(Integer.parseInt(name)); + } else { + peffect = PotionEffectType.getByName(name.toUpperCase(Locale.ENGLISH)); + } + if (peffect == null) { + peffect = POTIONS.get(name.toLowerCase(Locale.ENGLISH)); + } + if (peffect == null) { + peffect = ALIASPOTIONS.get(name.toLowerCase(Locale.ENGLISH)); + } + return peffect; + } + + public static Set> entrySet() { + return POTIONS.entrySet(); + } } diff --git a/Essentials/src/com/earth2me/essentials/Settings.java b/Essentials/src/com/earth2me/essentials/Settings.java index b4eea4705..1b0b5f0cb 100644 --- a/Essentials/src/com/earth2me/essentials/Settings.java +++ b/Essentials/src/com/earth2me/essentials/Settings.java @@ -1,1237 +1,1065 @@ package com.earth2me.essentials; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.commands.IEssentialsCommand; import com.earth2me.essentials.signs.EssentialsSign; import com.earth2me.essentials.signs.Signs; import com.earth2me.essentials.textreader.IText; import com.earth2me.essentials.textreader.SimpleTextInput; import com.earth2me.essentials.utils.FormatUtil; -import java.io.File; -import java.math.BigDecimal; -import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; import net.ess3.api.IEssentials; import org.bukkit.ChatColor; -import org.bukkit.command.PluginCommand; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.MemoryConfiguration; import org.bukkit.event.EventPriority; import org.bukkit.inventory.ItemStack; - -public class Settings implements net.ess3.api.ISettings -{ - private final transient EssentialsConf config; - private static final Logger logger = Logger.getLogger("Essentials"); - private final transient IEssentials ess; - private boolean metricsEnabled = true; - - public Settings(IEssentials ess) - { - this.ess = ess; - config = new EssentialsConf(new File(ess.getDataFolder(), "config.yml")); - config.setTemplateName("/config.yml"); - reloadConfig(); - } - - @Override - public boolean getRespawnAtHome() - { - return config.getBoolean("respawn-at-home", false); - } - - @Override - public boolean getUpdateBedAtDaytime() - { - return config.getBoolean("update-bed-at-daytime", true); - } - - @Override - public Set getMultipleHomes() - { - final ConfigurationSection section = config.getConfigurationSection("sethome-multiple"); - return section == null ? null : section.getKeys(false); - } - - @Override - public int getHomeLimit(final User user) - { - int limit = 1; - if (user.isAuthorized("essentials.sethome.multiple")) - { - limit = getHomeLimit("default"); - } - - final Set homeList = getMultipleHomes(); - if (homeList != null) - { - for (String set : homeList) - { - if (user.isAuthorized("essentials.sethome.multiple." + set) && (limit < getHomeLimit(set))) - { - limit = getHomeLimit(set); - } - } - } - return limit; - } - - @Override - public int getHomeLimit(final String set) - { - return config.getInt("sethome-multiple." + set, config.getInt("sethome-multiple.default", 3)); - } - private int chatRadius = 0; - - private int _getChatRadius() - { - return config.getInt("chat.radius", config.getInt("chat-radius", 0)); - } - - @Override - public int getChatRadius() - { - return chatRadius; - } - // #easteregg - private char chatShout = '!'; - - private char _getChatShout() - { - return config.getString("chat.shout", "!").charAt(0); - } - - @Override - public char getChatShout() - { - return chatShout; - } - // #easteregg - private char chatQuestion = '?'; - - private char _getChatQuestion() - { - return config.getString("chat.question", "?").charAt(0); - } - - @Override - public char getChatQuestion() - { - return chatQuestion; - } - private boolean teleportSafety; - - public boolean _isTeleportSafetyEnabled() - { - return config.getBoolean("teleport-safety", true); - } - - @Override - public boolean isTeleportSafetyEnabled() - { - return teleportSafety; - } - - @Override - public double getTeleportDelay() - { - return config.getDouble("teleport-delay", 0); - } - - @Override - public int getOversizedStackSize() - { - return config.getInt("oversized-stacksize", 64); - } - - @Override - public int getDefaultStackSize() - { - return config.getInt("default-stack-size", -1); - } - - @Override - public BigDecimal getStartingBalance() - { - return config.getBigDecimal("starting-balance", BigDecimal.ZERO); - } - - @Override - public boolean isCommandDisabled(final IEssentialsCommand cmd) - { - return isCommandDisabled(cmd.getName()); - } - private Set disabledCommands = new HashSet(); - - @Override - public boolean isCommandDisabled(String label) - { - return disabledCommands.contains(label); - } - - private Set getDisabledCommands() - { - Set disCommands = new HashSet(); - for (String c : config.getStringList("disabled-commands")) - { - disCommands.add(c.toLowerCase(Locale.ENGLISH)); - } - for (String c : config.getKeys(false)) - { - if (c.startsWith("disable-")) - { - disCommands.add(c.substring(8).toLowerCase(Locale.ENGLISH)); - } - } - return disCommands; - } - - @Override - public boolean isPlayerCommand(String label) - { - for (String c : config.getStringList("player-commands")) - { - if (!c.equalsIgnoreCase(label)) - { - continue; - } - return true; - } - return false; - } - - @Override - public boolean isCommandOverridden(String name) - { - for (String c : config.getStringList("overridden-commands")) - { - if (!c.equalsIgnoreCase(name)) - { - continue; - } - return true; - } - return config.getBoolean("override-" + name.toLowerCase(Locale.ENGLISH), false); - } - private ConfigurationSection commandCosts; - - @Override - public BigDecimal getCommandCost(IEssentialsCommand cmd) - { - return getCommandCost(cmd.getName()); - } - - private ConfigurationSection _getCommandCosts() - { - if (config.isConfigurationSection("command-costs")) - { - final ConfigurationSection section = config.getConfigurationSection("command-costs"); - final ConfigurationSection newSection = new MemoryConfiguration(); - for (String command : section.getKeys(false)) - { - if (command.charAt(0) == '/') - { - ess.getLogger().warning("Invalid command cost. '" + command + "' should not start with '/'."); - } - if (section.isDouble(command)) - { - newSection.set(command.toLowerCase(Locale.ENGLISH), section.getDouble(command)); - } - else if (section.isInt(command)) - { - newSection.set(command.toLowerCase(Locale.ENGLISH), (double)section.getInt(command)); - } - else if (section.isString(command)) - { - String costString = section.getString(command); - try - { - double cost = Double.parseDouble(costString.trim().replace(getCurrencySymbol(), "").replaceAll("\\W", "")); - newSection.set(command.toLowerCase(Locale.ENGLISH), cost); - } - catch (NumberFormatException ex) - { - ess.getLogger().warning("Invalid command cost for: " + command + " (" + costString + ")"); - } - - } - else - { - ess.getLogger().warning("Invalid command cost for: " + command); - } - } - return newSection; - } - return null; - } - - @Override - public BigDecimal getCommandCost(String name) - { - name = name.replace('.', '_').replace('/', '_'); - if (commandCosts != null) - { - return EssentialsConf.toBigDecimal(commandCosts.getString(name), BigDecimal.ZERO); - } - return BigDecimal.ZERO; - } - private Set socialSpyCommands = new HashSet(); - - private Set _getSocialSpyCommands() - { - Set socialspyCommands = new HashSet(); - - if (config.isList("socialspy-commands")) - { - for (String c : config.getStringList("socialspy-commands")) - { - socialspyCommands.add(c.toLowerCase(Locale.ENGLISH)); - } - } - else - { - socialspyCommands.addAll(Arrays.asList("msg", "r", "mail", "m", "whisper", "emsg", "t", "tell", "er", "reply", "ereply", "email", "action", "describe", "eme", "eaction", "edescribe", "etell", "ewhisper", "pm")); - } - - return socialspyCommands; - } - - @Override - public Set getSocialSpyCommands() - { - return socialSpyCommands; - } - private String nicknamePrefix = "~"; - - private String _getNicknamePrefix() - { - return config.getString("nickname-prefix", "~"); - } - - @Override - public String getNicknamePrefix() - { - return nicknamePrefix; - } - - @Override - public double getTeleportCooldown() - { - return config.getDouble("teleport-cooldown", 0); - } - - @Override - public double getHealCooldown() - { - return config.getDouble("heal-cooldown", 0); - } - private ConfigurationSection kits; - - private ConfigurationSection _getKits() - { - if (config.isConfigurationSection("kits")) - { - final ConfigurationSection section = config.getConfigurationSection("kits"); - final ConfigurationSection newSection = new MemoryConfiguration(); - for (String kitItem : section.getKeys(false)) - { - if (section.isConfigurationSection(kitItem)) - { - newSection.set(kitItem.toLowerCase(Locale.ENGLISH), section.getConfigurationSection(kitItem)); - } - } - return newSection; - } - return null; - } - - @Override - public ConfigurationSection getKits() - { - return kits; - } - - @Override - public Map getKit(String name) - { - name = name.replace('.', '_').replace('/', '_'); - if (getKits() != null) - { - final ConfigurationSection kits = getKits(); - if (kits.isConfigurationSection(name)) - { - return kits.getConfigurationSection(name).getValues(true); - } - } - return null; - } - private ChatColor operatorColor = null; - - @Override - public ChatColor getOperatorColor() - { - return operatorColor; - } - - private ChatColor _getOperatorColor() - { - String colorName = config.getString("ops-name-color", null); - - if (colorName == null) - { - return ChatColor.DARK_RED; - } - if ("none".equalsIgnoreCase(colorName) || colorName.isEmpty()) - { - return null; - } - - try - { - return ChatColor.valueOf(colorName.toUpperCase(Locale.ENGLISH)); - } - catch (IllegalArgumentException ex) - { - } - - return ChatColor.getByChar(colorName); - } - - @Override - public int getSpawnMobLimit() - { - return config.getInt("spawnmob-limit", 10); - } - - @Override - public boolean showNonEssCommandsInHelp() - { - return config.getBoolean("non-ess-in-help", true); - } - - @Override - public boolean hidePermissionlessHelp() - { - return config.getBoolean("hide-permissionless-help", true); - } - - @Override - public int getProtectCreeperMaxHeight() - { - return config.getInt("protect.creeper.max-height", -1); - } - - @Override - public boolean areSignsDisabled() - { - return !signsEnabled; - } - - @Override - public long getBackupInterval() - { - return config.getInt("backup.interval", 1440); // 1440 = 24 * 60 - } - - @Override - public String getBackupCommand() - { - return config.getString("backup.command", null); - } - private final Map chatFormats = Collections.synchronizedMap(new HashMap()); - - @Override - public String getChatFormat(String group) - { - String mFormat = chatFormats.get(group); - if (mFormat == null) - { - mFormat = config.getString("chat.group-formats." + (group == null ? "Default" : group), - config.getString("chat.format", "&7[{GROUP}]&r {DISPLAYNAME}&7:&r {MESSAGE}")); - mFormat = FormatUtil.replaceFormat(mFormat); - mFormat = mFormat.replace("{DISPLAYNAME}", "%1$s"); - mFormat = mFormat.replace("{MESSAGE}", "%2$s"); - mFormat = mFormat.replace("{GROUP}", "{0}"); - mFormat = mFormat.replace("{WORLD}", "{1}"); - mFormat = mFormat.replace("{WORLDNAME}", "{1}"); - mFormat = mFormat.replace("{SHORTWORLDNAME}", "{2}"); - mFormat = mFormat.replace("{TEAMPREFIX}", "{3}"); - mFormat = mFormat.replace("{TEAMSUFFIX}", "{4}"); - mFormat = mFormat.replace("{TEAMNAME}", "{5}"); - mFormat = "§r".concat(mFormat); - chatFormats.put(group, mFormat); - } - return mFormat; - } - - @Override - public boolean getAnnounceNewPlayers() - { - return !config.getString("newbies.announce-format", "-").isEmpty(); - } - - @Override - public IText getAnnounceNewPlayerFormat() - { - return new SimpleTextInput(FormatUtil.replaceFormat(config.getString("newbies.announce-format", "&dWelcome {DISPLAYNAME} to the server!"))); - } - - @Override - public String getNewPlayerKit() - { - return config.getString("newbies.kit", ""); - } - - @Override - public String getNewbieSpawn() - { - return config.getString("newbies.spawnpoint", "default"); - } - - @Override - public boolean getPerWarpPermission() - { - return config.getBoolean("per-warp-permission", false); - } - - @Override - public Map getListGroupConfig() - { - if (config.isConfigurationSection("list")) - { - Map values = config.getConfigurationSection("list").getValues(false); - if (!values.isEmpty()) - { - return values; - } - } - Map defaultMap = new HashMap(); - if (config.getBoolean("sort-list-by-groups", false)) - { - defaultMap.put("ListByGroup", "ListByGroup"); - } - else - { - defaultMap.put("Players", "*"); - } - return defaultMap; - } - - @Override - public void reloadConfig() - { - config.load(); - noGodWorlds = new HashSet(config.getStringList("no-god-in-worlds")); - enabledSigns = _getEnabledSigns(); - teleportSafety = _isTeleportSafetyEnabled(); - teleportInvulnerabilityTime = _getTeleportInvulnerability(); - teleportInvulnerability = _isTeleportInvulnerability(); - disableItemPickupWhileAfk = _getDisableItemPickupWhileAfk(); - registerBackInListener = _registerBackInListener(); - cancelAfkOnInteract = _cancelAfkOnInteract(); - cancelAfkOnMove = _cancelAfkOnMove() && cancelAfkOnInteract; - getFreezeAfkPlayers = _getFreezeAfkPlayers(); - itemSpawnBl = _getItemSpawnBlacklist(); - loginAttackDelay = _getLoginAttackDelay(); - signUsePerSecond = _getSignUsePerSecond(); - kits = _getKits(); - chatFormats.clear(); - changeDisplayName = _changeDisplayName(); - disabledCommands = getDisabledCommands(); - nicknamePrefix = _getNicknamePrefix(); - operatorColor = _getOperatorColor(); - changePlayerListName = _changePlayerListName(); - configDebug = _isDebug(); - prefixsuffixconfigured = _isPrefixSuffixConfigured(); - addprefixsuffix = _addPrefixSuffix(); - disablePrefix = _disablePrefix(); - disableSuffix = _disableSuffix(); - chatRadius = _getChatRadius(); - chatShout = _getChatShout(); - chatQuestion = _getChatQuestion(); - commandCosts = _getCommandCosts(); - socialSpyCommands = _getSocialSpyCommands(); - warnOnBuildDisallow = _warnOnBuildDisallow(); - mailsPerMinute = _getMailsPerMinute(); - maxMoney = _getMaxMoney(); - minMoney = _getMinMoney(); - permissionsLagWarning = _getPermissionsLagWarning(); - economyLagWarning = _getEconomyLagWarning(); - economyLog = _isEcoLogEnabled(); - economyLogUpdate = _isEcoLogUpdateEnabled(); - economyDisabled = _isEcoDisabled(); - allowSilentJoin = _allowSilentJoinQuit(); - customJoinMessage = _getCustomJoinMessage(); - isCustomJoinMessage = !customJoinMessage.equals("none"); - customQuitMessage = _getCustomQuitMessage(); - isCustomQuitMessage = !customQuitMessage.equals("none"); - } - private List itemSpawnBl = new ArrayList(); - - @Override - public List itemSpawnBlacklist() - { - return itemSpawnBl; - } - - private List _getItemSpawnBlacklist() - { - final List epItemSpwn = new ArrayList(); - if (ess.getItemDb() == null) - { - logger.log(Level.FINE, "Aborting ItemSpawnBL read, itemDB not yet loaded."); - return epItemSpwn; - } - for (String itemName : config.getString("item-spawn-blacklist", "").split(",")) - { - itemName = itemName.trim(); - if (itemName.isEmpty()) - { - continue; - } - try - { - final ItemStack iStack = ess.getItemDb().get(itemName); - epItemSpwn.add(iStack.getTypeId()); - } - catch (Exception ex) - { - logger.log(Level.SEVERE, tl("unknownItemInList", itemName, "item-spawn-blacklist")); - } - } - return epItemSpwn; - } - private List enabledSigns = new ArrayList(); - private boolean signsEnabled = false; - - @Override - public List enabledSigns() - { - return enabledSigns; - } - - private List _getEnabledSigns() - { - List newSigns = new ArrayList(); - - for (String signName : config.getStringList("enabledSigns")) - { - signName = signName.trim().toUpperCase(Locale.ENGLISH); - if (signName.isEmpty()) - { - continue; - } - if (signName.equals("COLOR") || signName.equals("COLOUR")) - { - signsEnabled = true; - continue; - } - try - { - newSigns.add(Signs.valueOf(signName).getSign()); - } - catch (Exception ex) - { - logger.log(Level.SEVERE, tl("unknownItemInList", signName, "enabledSigns")); - continue; - } - signsEnabled = true; - } - return newSigns; - } - private boolean warnOnBuildDisallow; - - private boolean _warnOnBuildDisallow() - { - return config.getBoolean("protect.disable.warn-on-build-disallow", false); - } - - @Override - public boolean warnOnBuildDisallow() - { - return warnOnBuildDisallow; - } - private boolean debug = false; - private boolean configDebug = false; - - private boolean _isDebug() - { - return config.getBoolean("debug", false); - } - - @Override - public boolean isDebug() - { - return debug || configDebug; - } - - @Override - public boolean warnOnSmite() - { - return config.getBoolean("warn-on-smite", true); - } - - @Override - public boolean permissionBasedItemSpawn() - { - return config.getBoolean("permission-based-item-spawn", false); - } - - @Override - public String getLocale() - { - return config.getString("locale", ""); - } - - //This method should always only return one character due to the implementation of the calling methods - //If you need to use a string currency, for example "coins", use the translation key 'currency'. - @Override - public String getCurrencySymbol() - { - return config.getString("currency-symbol", "$").concat("$").substring(0, 1).replaceAll("[0-9]", "$"); - } - - // #easteregg - @Override - public boolean isTradeInStacks(int id) - { - return config.getBoolean("trade-in-stacks-" + id, false); - } - // #easteregg - private boolean economyDisabled = false; - - public boolean _isEcoDisabled() - { - return config.getBoolean("disable-eco", false); - } - - @Override - public boolean isEcoDisabled() - { - return economyDisabled; - } - - @Override - public boolean getProtectPreventSpawn(final String creatureName) - { - return config.getBoolean("protect.prevent.spawn." + creatureName, false); - } - - @Override - public List getProtectList(final String configName) - { - final List list = new ArrayList(); - for (String itemName : config.getString(configName, "").split(",")) - { - itemName = itemName.trim(); - if (itemName.isEmpty()) - { - continue; - } - ItemStack itemStack; - try - { - itemStack = ess.getItemDb().get(itemName); - list.add(itemStack.getTypeId()); - } - catch (Exception ex) - { - logger.log(Level.SEVERE, tl("unknownItemInList", itemName, configName)); - } - } - return list; - } - - @Override - public String getProtectString(final String configName) - { - return config.getString(configName, null); - } - - @Override - public boolean getProtectBoolean(final String configName, boolean def) - { - return config.getBoolean(configName, def); - } - private static final BigDecimal MAXMONEY = new BigDecimal("10000000000000"); - private BigDecimal maxMoney = MAXMONEY; - - private BigDecimal _getMaxMoney() - { - return config.getBigDecimal("max-money", MAXMONEY); - } - - @Override - public BigDecimal getMaxMoney() - { - return maxMoney; - } - private static final BigDecimal MINMONEY = new BigDecimal("-10000000000000"); - private BigDecimal minMoney = MINMONEY; - - private BigDecimal _getMinMoney() - { - BigDecimal min = config.getBigDecimal("min-money", MINMONEY); - if (min.signum() > 0) - { - min = min.negate(); - } - return min; - } - - @Override - public BigDecimal getMinMoney() - { - return minMoney; - } - private boolean economyLog = false; - - @Override - public boolean isEcoLogEnabled() - { - return economyLog; - } - - public boolean _isEcoLogEnabled() - { - return config.getBoolean("economy-log-enabled", false); - } - // #easteregg - private boolean economyLogUpdate = false; - - @Override - public boolean isEcoLogUpdateEnabled() - { - return economyLogUpdate; - } - - public boolean _isEcoLogUpdateEnabled() - { - return config.getBoolean("economy-log-update-enabled", false); - } - - @Override - public boolean removeGodOnDisconnect() - { - return config.getBoolean("remove-god-on-disconnect", false); - } - private boolean changeDisplayName = true; - - private boolean _changeDisplayName() - { - return config.getBoolean("change-displayname", true); - } - - @Override - public boolean changeDisplayName() - { - return changeDisplayName; - } - private boolean changePlayerListName = false; - - private boolean _changePlayerListName() - { - return config.getBoolean("change-playerlist", false); - } - - @Override - public boolean changePlayerListName() - { - return changePlayerListName; - } - - @Override - public boolean useBukkitPermissions() - { - return config.getBoolean("use-bukkit-permissions", false); - } - private boolean prefixsuffixconfigured = false; - private boolean addprefixsuffix = false; - private boolean essentialsChatActive = false; - - private boolean _addPrefixSuffix() - { - return config.getBoolean("add-prefix-suffix", false); - } - - private boolean _isPrefixSuffixConfigured() - { - return config.hasProperty("add-prefix-suffix"); - } - - @Override - public void setEssentialsChatActive(boolean essentialsChatActive) - { - this.essentialsChatActive = essentialsChatActive; - } - - @Override - public boolean addPrefixSuffix() - { - return prefixsuffixconfigured ? addprefixsuffix : essentialsChatActive; - } - // #easteregg - private boolean disablePrefix = false; - - private boolean _disablePrefix() - { - return config.getBoolean("disablePrefix", false); - } - - @Override - public boolean disablePrefix() - { - return disablePrefix; - } - // #easteregg - private boolean disableSuffix = false; - - private boolean _disableSuffix() - { - return config.getBoolean("disableSuffix", false); - } - - @Override - public boolean disableSuffix() - { - return disableSuffix; - } - - @Override - public long getAutoAfk() - { - return config.getLong("auto-afk", 300); - } - - @Override - public long getAutoAfkKick() - { - return config.getLong("auto-afk-kick", -1); - } - private boolean getFreezeAfkPlayers; - - @Override - public boolean getFreezeAfkPlayers() - { - return getFreezeAfkPlayers; - } - - private boolean _getFreezeAfkPlayers() - { - return config.getBoolean("freeze-afk-players", false); - } - private boolean cancelAfkOnMove; - - @Override - public boolean cancelAfkOnMove() - { - return cancelAfkOnMove; - } - - private boolean _cancelAfkOnMove() - { - return config.getBoolean("cancel-afk-on-move", true); - } - private boolean cancelAfkOnInteract; - - @Override - public boolean cancelAfkOnInteract() - { - return cancelAfkOnInteract; - } - - private boolean _cancelAfkOnInteract() - { - return config.getBoolean("cancel-afk-on-interact", true); - } - - @Override - public boolean areDeathMessagesEnabled() - { - return config.getBoolean("death-messages", true); - } - private Set noGodWorlds = new HashSet(); - - @Override - public Set getNoGodWorlds() - { - return noGodWorlds; - } - - @Override - public void setDebug(final boolean debug) - { - this.debug = debug; - } - - @Override - public boolean getRepairEnchanted() - { - return config.getBoolean("repair-enchanted", true); - } - - @Override - public boolean allowUnsafeEnchantments() - { - return config.getBoolean("unsafe-enchantments", false); - } - - @Override - public boolean isWorldTeleportPermissions() - { - return config.getBoolean("world-teleport-permissions", false); - } - - @Override - public boolean isWorldHomePermissions() - { - return config.getBoolean("world-home-permissions", false); - } - private boolean registerBackInListener; - - @Override - public boolean registerBackInListener() - { - return registerBackInListener; - } - - private boolean _registerBackInListener() - { - return config.getBoolean("register-back-in-listener", false); - } - private boolean disableItemPickupWhileAfk; - - @Override - public boolean getDisableItemPickupWhileAfk() - { - return disableItemPickupWhileAfk; - } - - private boolean _getDisableItemPickupWhileAfk() - { - return config.getBoolean("disable-item-pickup-while-afk", false); - } - - @Override - public EventPriority getRespawnPriority() - { - String priority = config.getString("respawn-listener-priority", "normal").toLowerCase(Locale.ENGLISH); - if ("lowest".equals(priority)) - { - return EventPriority.LOWEST; - } - if ("low".equals(priority)) - { - return EventPriority.LOW; - } - if ("normal".equals(priority)) - { - return EventPriority.NORMAL; - } - if ("high".equals(priority)) - { - return EventPriority.HIGH; - } - if ("highest".equals(priority)) - { - return EventPriority.HIGHEST; - } - return EventPriority.NORMAL; - } - - @Override - public long getTpaAcceptCancellation() - { - return config.getLong("tpa-accept-cancellation", 120); - } - - @Override - public boolean isMetricsEnabled() - { - return metricsEnabled; - } - - @Override - public void setMetricsEnabled(boolean metricsEnabled) - { - this.metricsEnabled = metricsEnabled; - } - private long teleportInvulnerabilityTime; - - private long _getTeleportInvulnerability() - { - return config.getLong("teleport-invulnerability", 0) * 1000; - } - - @Override - public long getTeleportInvulnerability() - { - return teleportInvulnerabilityTime; - } - private boolean teleportInvulnerability; - - private boolean _isTeleportInvulnerability() - { - return (config.getLong("teleport-invulnerability", 0) > 0); - } - - @Override - public boolean isTeleportInvulnerability() - { - return teleportInvulnerability; - } - private long loginAttackDelay; - - private long _getLoginAttackDelay() - { - return config.getLong("login-attack-delay", 0) * 1000; - } - - @Override - public long getLoginAttackDelay() - { - return loginAttackDelay; - } - private int signUsePerSecond; - - private int _getSignUsePerSecond() - { - final int perSec = config.getInt("sign-use-per-second", 4); - return perSec > 0 ? perSec : 1; - } - - @Override - public int getSignUsePerSecond() - { - return signUsePerSecond; - } - - @Override - public double getMaxFlySpeed() - { - double maxSpeed = config.getDouble("max-fly-speed", 0.8); - return maxSpeed > 1.0 ? 1.0 : Math.abs(maxSpeed); - } - - @Override - public double getMaxWalkSpeed() - { - double maxSpeed = config.getDouble("max-walk-speed", 0.8); - return maxSpeed > 1.0 ? 1.0 : Math.abs(maxSpeed); - } - private int mailsPerMinute; - - private int _getMailsPerMinute() - { - return config.getInt("mails-per-minute", 1000); - } - - @Override - public int getMailsPerMinute() - { - return mailsPerMinute; - } - // #easteregg - private long economyLagWarning; - - private long _getEconomyLagWarning() - { - // Default to 25ms - final long value = (long)(config.getDouble("economy-lag-warning", 25.0) * 1000000); - return value; - } - - @Override - public long getEconomyLagWarning() - { - return economyLagWarning; - } - - // #easteregg - private long permissionsLagWarning; - - private long _getPermissionsLagWarning() - { - // Default to 25ms - final long value = (long)(config.getDouble("permissions-lag-warning", 25.0) * 1000000); - return value; - } - - @Override - public long getPermissionsLagWarning() - { - return permissionsLagWarning; - } - - @Override - public long getMaxTempban() - { - return config.getLong("max-tempban-time", -1); - } - - @Override - public int getMaxNickLength() - { - return config.getInt("max-nick-length", 30); - } - private boolean allowSilentJoin; - - public boolean _allowSilentJoinQuit() - { - return config.getBoolean("allow-silent-join-quit", false); - } - - @Override - public boolean allowSilentJoinQuit() - { - return allowSilentJoin; - } - private String customJoinMessage; - private boolean isCustomJoinMessage; - - public String _getCustomJoinMessage() - { - return FormatUtil.replaceFormat(config.getString("custom-join-message", "none")); - } - - @Override - public String getCustomJoinMessage() - { - return customJoinMessage; - } - - @Override - public boolean isCustomJoinMessage() - { - return isCustomJoinMessage; - } - private String customQuitMessage; - private boolean isCustomQuitMessage; - - public String _getCustomQuitMessage() - { - return FormatUtil.replaceFormat(config.getString("custom-quit-message", "none")); - } - - @Override - public String getCustomQuitMessage() - { - return customQuitMessage; - } - - @Override - public boolean isCustomQuitMessage() - { - return isCustomQuitMessage; - } - - // #easteregg - @Override - public int getMaxUserCacheCount() - { - long count = Runtime.getRuntime().maxMemory() / 1024 / 96; - return config.getInt("max-user-cache-count", (int)count); - } +import java.io.File; +import java.math.BigDecimal; +import java.util.*; +import java.util.logging.Level; +import java.util.logging.Logger; + +import static com.earth2me.essentials.I18n.tl; + + +public class Settings implements net.ess3.api.ISettings { + private final transient EssentialsConf config; + private static final Logger logger = Logger.getLogger("Essentials"); + private final transient IEssentials ess; + private boolean metricsEnabled = true; + + public Settings(IEssentials ess) { + this.ess = ess; + config = new EssentialsConf(new File(ess.getDataFolder(), "config.yml")); + config.setTemplateName("/config.yml"); + reloadConfig(); + } + + @Override + public boolean getRespawnAtHome() { + return config.getBoolean("respawn-at-home", false); + } + + @Override + public boolean getUpdateBedAtDaytime() { + return config.getBoolean("update-bed-at-daytime", true); + } + + @Override + public Set getMultipleHomes() { + final ConfigurationSection section = config.getConfigurationSection("sethome-multiple"); + return section == null ? null : section.getKeys(false); + } + + @Override + public int getHomeLimit(final User user) { + int limit = 1; + if (user.isAuthorized("essentials.sethome.multiple")) { + limit = getHomeLimit("default"); + } + + final Set homeList = getMultipleHomes(); + if (homeList != null) { + for (String set : homeList) { + if (user.isAuthorized("essentials.sethome.multiple." + set) && (limit < getHomeLimit(set))) { + limit = getHomeLimit(set); + } + } + } + return limit; + } + + @Override + public int getHomeLimit(final String set) { + return config.getInt("sethome-multiple." + set, config.getInt("sethome-multiple.default", 3)); + } + + private int chatRadius = 0; + + private int _getChatRadius() { + return config.getInt("chat.radius", config.getInt("chat-radius", 0)); + } + + @Override + public int getChatRadius() { + return chatRadius; + } + + // #easteregg + private char chatShout = '!'; + + private char _getChatShout() { + return config.getString("chat.shout", "!").charAt(0); + } + + @Override + public char getChatShout() { + return chatShout; + } + + // #easteregg + private char chatQuestion = '?'; + + private char _getChatQuestion() { + return config.getString("chat.question", "?").charAt(0); + } + + @Override + public char getChatQuestion() { + return chatQuestion; + } + + private boolean teleportSafety; + + public boolean _isTeleportSafetyEnabled() { + return config.getBoolean("teleport-safety", true); + } + + @Override + public boolean isTeleportSafetyEnabled() { + return teleportSafety; + } + + @Override + public double getTeleportDelay() { + return config.getDouble("teleport-delay", 0); + } + + @Override + public int getOversizedStackSize() { + return config.getInt("oversized-stacksize", 64); + } + + @Override + public int getDefaultStackSize() { + return config.getInt("default-stack-size", -1); + } + + @Override + public BigDecimal getStartingBalance() { + return config.getBigDecimal("starting-balance", BigDecimal.ZERO); + } + + @Override + public boolean isCommandDisabled(final IEssentialsCommand cmd) { + return isCommandDisabled(cmd.getName()); + } + + private Set disabledCommands = new HashSet(); + + @Override + public boolean isCommandDisabled(String label) { + return disabledCommands.contains(label); + } + + private Set getDisabledCommands() { + Set disCommands = new HashSet(); + for (String c : config.getStringList("disabled-commands")) { + disCommands.add(c.toLowerCase(Locale.ENGLISH)); + } + for (String c : config.getKeys(false)) { + if (c.startsWith("disable-")) { + disCommands.add(c.substring(8).toLowerCase(Locale.ENGLISH)); + } + } + return disCommands; + } + + @Override + public boolean isPlayerCommand(String label) { + for (String c : config.getStringList("player-commands")) { + if (!c.equalsIgnoreCase(label)) { + continue; + } + return true; + } + return false; + } + + @Override + public boolean isCommandOverridden(String name) { + for (String c : config.getStringList("overridden-commands")) { + if (!c.equalsIgnoreCase(name)) { + continue; + } + return true; + } + return config.getBoolean("override-" + name.toLowerCase(Locale.ENGLISH), false); + } + + private ConfigurationSection commandCosts; + + @Override + public BigDecimal getCommandCost(IEssentialsCommand cmd) { + return getCommandCost(cmd.getName()); + } + + private ConfigurationSection _getCommandCosts() { + if (config.isConfigurationSection("command-costs")) { + final ConfigurationSection section = config.getConfigurationSection("command-costs"); + final ConfigurationSection newSection = new MemoryConfiguration(); + for (String command : section.getKeys(false)) { + if (command.charAt(0) == '/') { + ess.getLogger().warning("Invalid command cost. '" + command + "' should not start with '/'."); + } + if (section.isDouble(command)) { + newSection.set(command.toLowerCase(Locale.ENGLISH), section.getDouble(command)); + } else if (section.isInt(command)) { + newSection.set(command.toLowerCase(Locale.ENGLISH), (double) section.getInt(command)); + } else if (section.isString(command)) { + String costString = section.getString(command); + try { + double cost = Double.parseDouble(costString.trim().replace(getCurrencySymbol(), "").replaceAll("\\W", "")); + newSection.set(command.toLowerCase(Locale.ENGLISH), cost); + } catch (NumberFormatException ex) { + ess.getLogger().warning("Invalid command cost for: " + command + " (" + costString + ")"); + } + + } else { + ess.getLogger().warning("Invalid command cost for: " + command); + } + } + return newSection; + } + return null; + } + + @Override + public BigDecimal getCommandCost(String name) { + name = name.replace('.', '_').replace('/', '_'); + if (commandCosts != null) { + return EssentialsConf.toBigDecimal(commandCosts.getString(name), BigDecimal.ZERO); + } + return BigDecimal.ZERO; + } + + private Set socialSpyCommands = new HashSet(); + + private Set _getSocialSpyCommands() { + Set socialspyCommands = new HashSet(); + + if (config.isList("socialspy-commands")) { + for (String c : config.getStringList("socialspy-commands")) { + socialspyCommands.add(c.toLowerCase(Locale.ENGLISH)); + } + } else { + socialspyCommands.addAll(Arrays.asList("msg", "r", "mail", "m", "whisper", "emsg", "t", "tell", "er", "reply", "ereply", "email", "action", "describe", "eme", "eaction", "edescribe", "etell", "ewhisper", "pm")); + } + + return socialspyCommands; + } + + @Override + public Set getSocialSpyCommands() { + return socialSpyCommands; + } + + private String nicknamePrefix = "~"; + + private String _getNicknamePrefix() { + return config.getString("nickname-prefix", "~"); + } + + @Override + public String getNicknamePrefix() { + return nicknamePrefix; + } + + @Override + public double getTeleportCooldown() { + return config.getDouble("teleport-cooldown", 0); + } + + @Override + public double getHealCooldown() { + return config.getDouble("heal-cooldown", 0); + } + + private ConfigurationSection kits; + + private ConfigurationSection _getKits() { + if (config.isConfigurationSection("kits")) { + final ConfigurationSection section = config.getConfigurationSection("kits"); + final ConfigurationSection newSection = new MemoryConfiguration(); + for (String kitItem : section.getKeys(false)) { + if (section.isConfigurationSection(kitItem)) { + newSection.set(kitItem.toLowerCase(Locale.ENGLISH), section.getConfigurationSection(kitItem)); + } + } + return newSection; + } + return null; + } + + @Override + public ConfigurationSection getKits() { + return kits; + } + + @Override + public Map getKit(String name) { + name = name.replace('.', '_').replace('/', '_'); + if (getKits() != null) { + final ConfigurationSection kits = getKits(); + if (kits.isConfigurationSection(name)) { + return kits.getConfigurationSection(name).getValues(true); + } + } + return null; + } + + private ChatColor operatorColor = null; + + @Override + public ChatColor getOperatorColor() { + return operatorColor; + } + + private ChatColor _getOperatorColor() { + String colorName = config.getString("ops-name-color", null); + + if (colorName == null) { + return ChatColor.DARK_RED; + } + if ("none".equalsIgnoreCase(colorName) || colorName.isEmpty()) { + return null; + } + + try { + return ChatColor.valueOf(colorName.toUpperCase(Locale.ENGLISH)); + } catch (IllegalArgumentException ex) { + } + + return ChatColor.getByChar(colorName); + } + + @Override + public int getSpawnMobLimit() { + return config.getInt("spawnmob-limit", 10); + } + + @Override + public boolean showNonEssCommandsInHelp() { + return config.getBoolean("non-ess-in-help", true); + } + + @Override + public boolean hidePermissionlessHelp() { + return config.getBoolean("hide-permissionless-help", true); + } + + @Override + public int getProtectCreeperMaxHeight() { + return config.getInt("protect.creeper.max-height", -1); + } + + @Override + public boolean areSignsDisabled() { + return !signsEnabled; + } + + @Override + public long getBackupInterval() { + return config.getInt("backup.interval", 1440); // 1440 = 24 * 60 + } + + @Override + public String getBackupCommand() { + return config.getString("backup.command", null); + } + + private final Map chatFormats = Collections.synchronizedMap(new HashMap()); + + @Override + public String getChatFormat(String group) { + String mFormat = chatFormats.get(group); + if (mFormat == null) { + mFormat = config.getString("chat.group-formats." + (group == null ? "Default" : group), config.getString("chat.format", "&7[{GROUP}]&r {DISPLAYNAME}&7:&r {MESSAGE}")); + mFormat = FormatUtil.replaceFormat(mFormat); + mFormat = mFormat.replace("{DISPLAYNAME}", "%1$s"); + mFormat = mFormat.replace("{MESSAGE}", "%2$s"); + mFormat = mFormat.replace("{GROUP}", "{0}"); + mFormat = mFormat.replace("{WORLD}", "{1}"); + mFormat = mFormat.replace("{WORLDNAME}", "{1}"); + mFormat = mFormat.replace("{SHORTWORLDNAME}", "{2}"); + mFormat = mFormat.replace("{TEAMPREFIX}", "{3}"); + mFormat = mFormat.replace("{TEAMSUFFIX}", "{4}"); + mFormat = mFormat.replace("{TEAMNAME}", "{5}"); + mFormat = "§r".concat(mFormat); + chatFormats.put(group, mFormat); + } + return mFormat; + } + + @Override + public boolean getAnnounceNewPlayers() { + return !config.getString("newbies.announce-format", "-").isEmpty(); + } + + @Override + public IText getAnnounceNewPlayerFormat() { + return new SimpleTextInput(FormatUtil.replaceFormat(config.getString("newbies.announce-format", "&dWelcome {DISPLAYNAME} to the server!"))); + } + + @Override + public String getNewPlayerKit() { + return config.getString("newbies.kit", ""); + } + + @Override + public String getNewbieSpawn() { + return config.getString("newbies.spawnpoint", "default"); + } + + @Override + public boolean getPerWarpPermission() { + return config.getBoolean("per-warp-permission", false); + } + + @Override + public Map getListGroupConfig() { + if (config.isConfigurationSection("list")) { + Map values = config.getConfigurationSection("list").getValues(false); + if (!values.isEmpty()) { + return values; + } + } + Map defaultMap = new HashMap(); + if (config.getBoolean("sort-list-by-groups", false)) { + defaultMap.put("ListByGroup", "ListByGroup"); + } else { + defaultMap.put("Players", "*"); + } + return defaultMap; + } + + @Override + public void reloadConfig() { + config.load(); + noGodWorlds = new HashSet(config.getStringList("no-god-in-worlds")); + enabledSigns = _getEnabledSigns(); + teleportSafety = _isTeleportSafetyEnabled(); + teleportInvulnerabilityTime = _getTeleportInvulnerability(); + teleportInvulnerability = _isTeleportInvulnerability(); + disableItemPickupWhileAfk = _getDisableItemPickupWhileAfk(); + registerBackInListener = _registerBackInListener(); + cancelAfkOnInteract = _cancelAfkOnInteract(); + cancelAfkOnMove = _cancelAfkOnMove() && cancelAfkOnInteract; + getFreezeAfkPlayers = _getFreezeAfkPlayers(); + itemSpawnBl = _getItemSpawnBlacklist(); + loginAttackDelay = _getLoginAttackDelay(); + signUsePerSecond = _getSignUsePerSecond(); + kits = _getKits(); + chatFormats.clear(); + changeDisplayName = _changeDisplayName(); + disabledCommands = getDisabledCommands(); + nicknamePrefix = _getNicknamePrefix(); + operatorColor = _getOperatorColor(); + changePlayerListName = _changePlayerListName(); + configDebug = _isDebug(); + prefixsuffixconfigured = _isPrefixSuffixConfigured(); + addprefixsuffix = _addPrefixSuffix(); + disablePrefix = _disablePrefix(); + disableSuffix = _disableSuffix(); + chatRadius = _getChatRadius(); + chatShout = _getChatShout(); + chatQuestion = _getChatQuestion(); + commandCosts = _getCommandCosts(); + socialSpyCommands = _getSocialSpyCommands(); + warnOnBuildDisallow = _warnOnBuildDisallow(); + mailsPerMinute = _getMailsPerMinute(); + maxMoney = _getMaxMoney(); + minMoney = _getMinMoney(); + permissionsLagWarning = _getPermissionsLagWarning(); + economyLagWarning = _getEconomyLagWarning(); + economyLog = _isEcoLogEnabled(); + economyLogUpdate = _isEcoLogUpdateEnabled(); + economyDisabled = _isEcoDisabled(); + allowSilentJoin = _allowSilentJoinQuit(); + customJoinMessage = _getCustomJoinMessage(); + isCustomJoinMessage = !customJoinMessage.equals("none"); + customQuitMessage = _getCustomQuitMessage(); + isCustomQuitMessage = !customQuitMessage.equals("none"); + } + + private List itemSpawnBl = new ArrayList(); + + @Override + public List itemSpawnBlacklist() { + return itemSpawnBl; + } + + private List _getItemSpawnBlacklist() { + final List epItemSpwn = new ArrayList(); + if (ess.getItemDb() == null) { + logger.log(Level.FINE, "Aborting ItemSpawnBL read, itemDB not yet loaded."); + return epItemSpwn; + } + for (String itemName : config.getString("item-spawn-blacklist", "").split(",")) { + itemName = itemName.trim(); + if (itemName.isEmpty()) { + continue; + } + try { + final ItemStack iStack = ess.getItemDb().get(itemName); + epItemSpwn.add(iStack.getTypeId()); + } catch (Exception ex) { + logger.log(Level.SEVERE, tl("unknownItemInList", itemName, "item-spawn-blacklist")); + } + } + return epItemSpwn; + } + + private List enabledSigns = new ArrayList(); + private boolean signsEnabled = false; + + @Override + public List enabledSigns() { + return enabledSigns; + } + + private List _getEnabledSigns() { + List newSigns = new ArrayList(); + + for (String signName : config.getStringList("enabledSigns")) { + signName = signName.trim().toUpperCase(Locale.ENGLISH); + if (signName.isEmpty()) { + continue; + } + if (signName.equals("COLOR") || signName.equals("COLOUR")) { + signsEnabled = true; + continue; + } + try { + newSigns.add(Signs.valueOf(signName).getSign()); + } catch (Exception ex) { + logger.log(Level.SEVERE, tl("unknownItemInList", signName, "enabledSigns")); + continue; + } + signsEnabled = true; + } + return newSigns; + } + + private boolean warnOnBuildDisallow; + + private boolean _warnOnBuildDisallow() { + return config.getBoolean("protect.disable.warn-on-build-disallow", false); + } + + @Override + public boolean warnOnBuildDisallow() { + return warnOnBuildDisallow; + } + + private boolean debug = false; + private boolean configDebug = false; + + private boolean _isDebug() { + return config.getBoolean("debug", false); + } + + @Override + public boolean isDebug() { + return debug || configDebug; + } + + @Override + public boolean warnOnSmite() { + return config.getBoolean("warn-on-smite", true); + } + + @Override + public boolean permissionBasedItemSpawn() { + return config.getBoolean("permission-based-item-spawn", false); + } + + @Override + public String getLocale() { + return config.getString("locale", ""); + } + + //This method should always only return one character due to the implementation of the calling methods + //If you need to use a string currency, for example "coins", use the translation key 'currency'. + @Override + public String getCurrencySymbol() { + return config.getString("currency-symbol", "$").concat("$").substring(0, 1).replaceAll("[0-9]", "$"); + } + + // #easteregg + @Override + public boolean isTradeInStacks(int id) { + return config.getBoolean("trade-in-stacks-" + id, false); + } + + // #easteregg + private boolean economyDisabled = false; + + public boolean _isEcoDisabled() { + return config.getBoolean("disable-eco", false); + } + + @Override + public boolean isEcoDisabled() { + return economyDisabled; + } + + @Override + public boolean getProtectPreventSpawn(final String creatureName) { + return config.getBoolean("protect.prevent.spawn." + creatureName, false); + } + + @Override + public List getProtectList(final String configName) { + final List list = new ArrayList(); + for (String itemName : config.getString(configName, "").split(",")) { + itemName = itemName.trim(); + if (itemName.isEmpty()) { + continue; + } + ItemStack itemStack; + try { + itemStack = ess.getItemDb().get(itemName); + list.add(itemStack.getTypeId()); + } catch (Exception ex) { + logger.log(Level.SEVERE, tl("unknownItemInList", itemName, configName)); + } + } + return list; + } + + @Override + public String getProtectString(final String configName) { + return config.getString(configName, null); + } + + @Override + public boolean getProtectBoolean(final String configName, boolean def) { + return config.getBoolean(configName, def); + } + + private static final BigDecimal MAXMONEY = new BigDecimal("10000000000000"); + private BigDecimal maxMoney = MAXMONEY; + + private BigDecimal _getMaxMoney() { + return config.getBigDecimal("max-money", MAXMONEY); + } + + @Override + public BigDecimal getMaxMoney() { + return maxMoney; + } + + private static final BigDecimal MINMONEY = new BigDecimal("-10000000000000"); + private BigDecimal minMoney = MINMONEY; + + private BigDecimal _getMinMoney() { + BigDecimal min = config.getBigDecimal("min-money", MINMONEY); + if (min.signum() > 0) { + min = min.negate(); + } + return min; + } + + @Override + public BigDecimal getMinMoney() { + return minMoney; + } + + private boolean economyLog = false; + + @Override + public boolean isEcoLogEnabled() { + return economyLog; + } + + public boolean _isEcoLogEnabled() { + return config.getBoolean("economy-log-enabled", false); + } + + // #easteregg + private boolean economyLogUpdate = false; + + @Override + public boolean isEcoLogUpdateEnabled() { + return economyLogUpdate; + } + + public boolean _isEcoLogUpdateEnabled() { + return config.getBoolean("economy-log-update-enabled", false); + } + + @Override + public boolean removeGodOnDisconnect() { + return config.getBoolean("remove-god-on-disconnect", false); + } + + private boolean changeDisplayName = true; + + private boolean _changeDisplayName() { + return config.getBoolean("change-displayname", true); + } + + @Override + public boolean changeDisplayName() { + return changeDisplayName; + } + + private boolean changePlayerListName = false; + + private boolean _changePlayerListName() { + return config.getBoolean("change-playerlist", false); + } + + @Override + public boolean changePlayerListName() { + return changePlayerListName; + } + + @Override + public boolean useBukkitPermissions() { + return config.getBoolean("use-bukkit-permissions", false); + } + + private boolean prefixsuffixconfigured = false; + private boolean addprefixsuffix = false; + private boolean essentialsChatActive = false; + + private boolean _addPrefixSuffix() { + return config.getBoolean("add-prefix-suffix", false); + } + + private boolean _isPrefixSuffixConfigured() { + return config.hasProperty("add-prefix-suffix"); + } + + @Override + public void setEssentialsChatActive(boolean essentialsChatActive) { + this.essentialsChatActive = essentialsChatActive; + } + + @Override + public boolean addPrefixSuffix() { + return prefixsuffixconfigured ? addprefixsuffix : essentialsChatActive; + } + + // #easteregg + private boolean disablePrefix = false; + + private boolean _disablePrefix() { + return config.getBoolean("disablePrefix", false); + } + + @Override + public boolean disablePrefix() { + return disablePrefix; + } + + // #easteregg + private boolean disableSuffix = false; + + private boolean _disableSuffix() { + return config.getBoolean("disableSuffix", false); + } + + @Override + public boolean disableSuffix() { + return disableSuffix; + } + + @Override + public long getAutoAfk() { + return config.getLong("auto-afk", 300); + } + + @Override + public long getAutoAfkKick() { + return config.getLong("auto-afk-kick", -1); + } + + private boolean getFreezeAfkPlayers; + + @Override + public boolean getFreezeAfkPlayers() { + return getFreezeAfkPlayers; + } + + private boolean _getFreezeAfkPlayers() { + return config.getBoolean("freeze-afk-players", false); + } + + private boolean cancelAfkOnMove; + + @Override + public boolean cancelAfkOnMove() { + return cancelAfkOnMove; + } + + private boolean _cancelAfkOnMove() { + return config.getBoolean("cancel-afk-on-move", true); + } + + private boolean cancelAfkOnInteract; + + @Override + public boolean cancelAfkOnInteract() { + return cancelAfkOnInteract; + } + + private boolean _cancelAfkOnInteract() { + return config.getBoolean("cancel-afk-on-interact", true); + } + + @Override + public boolean areDeathMessagesEnabled() { + return config.getBoolean("death-messages", true); + } + + private Set noGodWorlds = new HashSet(); + + @Override + public Set getNoGodWorlds() { + return noGodWorlds; + } + + @Override + public void setDebug(final boolean debug) { + this.debug = debug; + } + + @Override + public boolean getRepairEnchanted() { + return config.getBoolean("repair-enchanted", true); + } + + @Override + public boolean allowUnsafeEnchantments() { + return config.getBoolean("unsafe-enchantments", false); + } + + @Override + public boolean isWorldTeleportPermissions() { + return config.getBoolean("world-teleport-permissions", false); + } + + @Override + public boolean isWorldHomePermissions() { + return config.getBoolean("world-home-permissions", false); + } + + private boolean registerBackInListener; + + @Override + public boolean registerBackInListener() { + return registerBackInListener; + } + + private boolean _registerBackInListener() { + return config.getBoolean("register-back-in-listener", false); + } + + private boolean disableItemPickupWhileAfk; + + @Override + public boolean getDisableItemPickupWhileAfk() { + return disableItemPickupWhileAfk; + } + + private boolean _getDisableItemPickupWhileAfk() { + return config.getBoolean("disable-item-pickup-while-afk", false); + } + + @Override + public EventPriority getRespawnPriority() { + String priority = config.getString("respawn-listener-priority", "normal").toLowerCase(Locale.ENGLISH); + if ("lowest".equals(priority)) { + return EventPriority.LOWEST; + } + if ("low".equals(priority)) { + return EventPriority.LOW; + } + if ("normal".equals(priority)) { + return EventPriority.NORMAL; + } + if ("high".equals(priority)) { + return EventPriority.HIGH; + } + if ("highest".equals(priority)) { + return EventPriority.HIGHEST; + } + return EventPriority.NORMAL; + } + + @Override + public long getTpaAcceptCancellation() { + return config.getLong("tpa-accept-cancellation", 120); + } + + @Override + public boolean isMetricsEnabled() { + return metricsEnabled; + } + + @Override + public void setMetricsEnabled(boolean metricsEnabled) { + this.metricsEnabled = metricsEnabled; + } + + private long teleportInvulnerabilityTime; + + private long _getTeleportInvulnerability() { + return config.getLong("teleport-invulnerability", 0) * 1000; + } + + @Override + public long getTeleportInvulnerability() { + return teleportInvulnerabilityTime; + } + + private boolean teleportInvulnerability; + + private boolean _isTeleportInvulnerability() { + return (config.getLong("teleport-invulnerability", 0) > 0); + } + + @Override + public boolean isTeleportInvulnerability() { + return teleportInvulnerability; + } + + private long loginAttackDelay; + + private long _getLoginAttackDelay() { + return config.getLong("login-attack-delay", 0) * 1000; + } + + @Override + public long getLoginAttackDelay() { + return loginAttackDelay; + } + + private int signUsePerSecond; + + private int _getSignUsePerSecond() { + final int perSec = config.getInt("sign-use-per-second", 4); + return perSec > 0 ? perSec : 1; + } + + @Override + public int getSignUsePerSecond() { + return signUsePerSecond; + } + + @Override + public double getMaxFlySpeed() { + double maxSpeed = config.getDouble("max-fly-speed", 0.8); + return maxSpeed > 1.0 ? 1.0 : Math.abs(maxSpeed); + } + + @Override + public double getMaxWalkSpeed() { + double maxSpeed = config.getDouble("max-walk-speed", 0.8); + return maxSpeed > 1.0 ? 1.0 : Math.abs(maxSpeed); + } + + private int mailsPerMinute; + + private int _getMailsPerMinute() { + return config.getInt("mails-per-minute", 1000); + } + + @Override + public int getMailsPerMinute() { + return mailsPerMinute; + } + + // #easteregg + private long economyLagWarning; + + private long _getEconomyLagWarning() { + // Default to 25ms + final long value = (long) (config.getDouble("economy-lag-warning", 25.0) * 1000000); + return value; + } + + @Override + public long getEconomyLagWarning() { + return economyLagWarning; + } + + // #easteregg + private long permissionsLagWarning; + + private long _getPermissionsLagWarning() { + // Default to 25ms + final long value = (long) (config.getDouble("permissions-lag-warning", 25.0) * 1000000); + return value; + } + + @Override + public long getPermissionsLagWarning() { + return permissionsLagWarning; + } + + @Override + public long getMaxTempban() { + return config.getLong("max-tempban-time", -1); + } + + @Override + public int getMaxNickLength() { + return config.getInt("max-nick-length", 30); + } + + private boolean allowSilentJoin; + + public boolean _allowSilentJoinQuit() { + return config.getBoolean("allow-silent-join-quit", false); + } + + @Override + public boolean allowSilentJoinQuit() { + return allowSilentJoin; + } + + private String customJoinMessage; + private boolean isCustomJoinMessage; + + public String _getCustomJoinMessage() { + return FormatUtil.replaceFormat(config.getString("custom-join-message", "none")); + } + + @Override + public String getCustomJoinMessage() { + return customJoinMessage; + } + + @Override + public boolean isCustomJoinMessage() { + return isCustomJoinMessage; + } + + private String customQuitMessage; + private boolean isCustomQuitMessage; + + public String _getCustomQuitMessage() { + return FormatUtil.replaceFormat(config.getString("custom-quit-message", "none")); + } + + @Override + public String getCustomQuitMessage() { + return customQuitMessage; + } + + @Override + public boolean isCustomQuitMessage() { + return isCustomQuitMessage; + } + + // #easteregg + @Override + public int getMaxUserCacheCount() { + long count = Runtime.getRuntime().maxMemory() / 1024 / 96; + return config.getInt("max-user-cache-count", (int) count); + } } diff --git a/Essentials/src/com/earth2me/essentials/SpawnMob.java b/Essentials/src/com/earth2me/essentials/SpawnMob.java index a191528dd..e1ee3ef07 100644 --- a/Essentials/src/com/earth2me/essentials/SpawnMob.java +++ b/Essentials/src/com/earth2me/essentials/SpawnMob.java @@ -1,14 +1,8 @@ package com.earth2me.essentials; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.Mob.MobException; import com.earth2me.essentials.utils.LocationUtil; import com.earth2me.essentials.utils.StringUtil; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Set; import net.ess3.api.IEssentials; import org.bukkit.Location; import org.bukkit.Material; @@ -18,306 +12,248 @@ import org.bukkit.entity.*; import org.bukkit.inventory.EntityEquipment; import org.bukkit.inventory.ItemStack; +import java.util.*; -public class SpawnMob -{ - public static String mobList(final User user) - { - final Set mobList = Mob.getMobList(); - final Set availableList = new HashSet(); - for (String mob : mobList) - { - if (user.isAuthorized("essentials.spawnmob." + mob.toLowerCase(Locale.ENGLISH))) - { - availableList.add(mob); - } - } - if (availableList.isEmpty()) - { - availableList.add(tl("none")); - } - return StringUtil.joinList(availableList); - } +import static com.earth2me.essentials.I18n.tl; - public static List mobParts(final String mobString) - { - String[] mobParts = mobString.split(","); - List mobs = new ArrayList(); +public class SpawnMob { + public static String mobList(final User user) { + final Set mobList = Mob.getMobList(); + final Set availableList = new HashSet(); + for (String mob : mobList) { + if (user.isAuthorized("essentials.spawnmob." + mob.toLowerCase(Locale.ENGLISH))) { + availableList.add(mob); + } + } + if (availableList.isEmpty()) { + availableList.add(tl("none")); + } + return StringUtil.joinList(availableList); + } - for (String mobPart : mobParts) - { - String[] mobDatas = mobPart.split(":"); - mobs.add(mobDatas[0]); - } - return mobs; - } + public static List mobParts(final String mobString) { + String[] mobParts = mobString.split(","); - public static List mobData(final String mobString) - { - String[] mobParts = mobString.split(","); + List mobs = new ArrayList(); - List mobData = new ArrayList(); + for (String mobPart : mobParts) { + String[] mobDatas = mobPart.split(":"); + mobs.add(mobDatas[0]); + } + return mobs; + } - for (String mobPart : mobParts) - { - String[] mobDatas = mobPart.split(":"); - if (mobDatas.length == 1) - { - if (mobPart.contains(":")) - { - mobData.add(""); - } - else - { - mobData.add(null); - } - } - else - { - mobData.add(mobDatas[1]); - } - } + public static List mobData(final String mobString) { + String[] mobParts = mobString.split(","); - return mobData; - } + List mobData = new ArrayList(); - // This method spawns a mob where the user is looking, owned by user - public static void spawnmob(final IEssentials ess, final Server server, final User user, final List parts, final List data, int mobCount) throws Exception - { - final Block block = LocationUtil.getTarget(user.getBase()).getBlock(); - if (block == null) - { - throw new Exception(tl("unableToSpawnMob")); - } - spawnmob(ess, server, user.getSource(), user, block.getLocation(), parts, data, mobCount); - } + for (String mobPart : mobParts) { + String[] mobDatas = mobPart.split(":"); + if (mobDatas.length == 1) { + if (mobPart.contains(":")) { + mobData.add(""); + } else { + mobData.add(null); + } + } else { + mobData.add(mobDatas[1]); + } + } - // This method spawns a mob at target, owned by target - public static void spawnmob(final IEssentials ess, final Server server, final CommandSource sender, final User target, final List parts, final List data, int mobCount) throws Exception - { - spawnmob(ess, server, sender, target, target.getLocation(), parts, data, mobCount); - } + return mobData; + } - // This method spawns a mob at loc, owned by target - public static void spawnmob(final IEssentials ess, final Server server, final CommandSource sender, final User target, final Location loc, final List parts, final List data, int mobCount) throws Exception - { - final Location sloc = LocationUtil.getSafeDestination(loc); + // This method spawns a mob where the user is looking, owned by user + public static void spawnmob(final IEssentials ess, final Server server, final User user, final List parts, final List data, int mobCount) throws Exception { + final Block block = LocationUtil.getTarget(user.getBase()).getBlock(); + if (block == null) { + throw new Exception(tl("unableToSpawnMob")); + } + spawnmob(ess, server, user.getSource(), user, block.getLocation(), parts, data, mobCount); + } - for (int i = 0; i < parts.size(); i++) - { - Mob mob = Mob.fromName(parts.get(i)); - checkSpawnable(ess, sender, mob); - } + // This method spawns a mob at target, owned by target + public static void spawnmob(final IEssentials ess, final Server server, final CommandSource sender, final User target, final List parts, final List data, int mobCount) throws Exception { + spawnmob(ess, server, sender, target, target.getLocation(), parts, data, mobCount); + } - final int serverLimit = ess.getSettings().getSpawnMobLimit(); - int effectiveLimit = serverLimit / parts.size(); + // This method spawns a mob at loc, owned by target + public static void spawnmob(final IEssentials ess, final Server server, final CommandSource sender, final User target, final Location loc, final List parts, final List data, int mobCount) throws Exception { + final Location sloc = LocationUtil.getSafeDestination(loc); - if (effectiveLimit < 1) - { - effectiveLimit = 1; - while (parts.size() > serverLimit) - { - parts.remove(serverLimit); - } - } + for (int i = 0; i < parts.size(); i++) { + Mob mob = Mob.fromName(parts.get(i)); + checkSpawnable(ess, sender, mob); + } - if (mobCount > effectiveLimit) - { - mobCount = effectiveLimit; - sender.sendMessage(tl("mobSpawnLimit")); - } + final int serverLimit = ess.getSettings().getSpawnMobLimit(); + int effectiveLimit = serverLimit / parts.size(); - Mob mob = Mob.fromName(parts.get(0)); // Get the first mob - try - { - for (int i = 0; i < mobCount; i++) - { - spawnMob(ess, server, sender, target, sloc, parts, data); - } - sender.sendMessage(mobCount * parts.size() + " " + mob.name.toLowerCase(Locale.ENGLISH) + mob.suffix + " " + tl("spawned")); - } - catch (MobException e1) - { - throw new Exception(tl("unableToSpawnMob"), e1); - } - catch (NumberFormatException e2) - { - throw new Exception(tl("numberRequired"), e2); - } - catch (NullPointerException np) - { - throw new Exception(tl("soloMob"), np); - } - } + if (effectiveLimit < 1) { + effectiveLimit = 1; + while (parts.size() > serverLimit) { + parts.remove(serverLimit); + } + } - private static void spawnMob(final IEssentials ess, final Server server, final CommandSource sender, final User target, final Location sloc, List parts, List data) throws Exception - { - Mob mob; - Entity spawnedMob = null; - Entity spawnedMount; + if (mobCount > effectiveLimit) { + mobCount = effectiveLimit; + sender.sendMessage(tl("mobSpawnLimit")); + } - for (int i = 0; i < parts.size(); i++) - { - if (i == 0) - { - mob = Mob.fromName(parts.get(i)); - spawnedMob = mob.spawn(sloc.getWorld(), server, sloc); - defaultMobData(mob.getType(), spawnedMob); + Mob mob = Mob.fromName(parts.get(0)); // Get the first mob + try { + for (int i = 0; i < mobCount; i++) { + spawnMob(ess, server, sender, target, sloc, parts, data); + } + sender.sendMessage(mobCount * parts.size() + " " + mob.name.toLowerCase(Locale.ENGLISH) + mob.suffix + " " + tl("spawned")); + } catch (MobException e1) { + throw new Exception(tl("unableToSpawnMob"), e1); + } catch (NumberFormatException e2) { + throw new Exception(tl("numberRequired"), e2); + } catch (NullPointerException np) { + throw new Exception(tl("soloMob"), np); + } + } - if (data.get(i) != null) - { - changeMobData(sender, mob.getType(), spawnedMob, data.get(i).toLowerCase(Locale.ENGLISH), target); - } - } + private static void spawnMob(final IEssentials ess, final Server server, final CommandSource sender, final User target, final Location sloc, List parts, List data) throws Exception { + Mob mob; + Entity spawnedMob = null; + Entity spawnedMount; - int next = (i + 1); - if (next < parts.size()) //If it's the last mob in the list, don't set the mount - { - Mob mMob = Mob.fromName(parts.get(next)); - spawnedMount = mMob.spawn(sloc.getWorld(), server, sloc); - defaultMobData(mMob.getType(), spawnedMount); + for (int i = 0; i < parts.size(); i++) { + if (i == 0) { + mob = Mob.fromName(parts.get(i)); + spawnedMob = mob.spawn(sloc.getWorld(), server, sloc); + defaultMobData(mob.getType(), spawnedMob); - if (data.get(next) != null) - { - changeMobData(sender, mMob.getType(), spawnedMount, data.get(next).toLowerCase(Locale.ENGLISH), target); - } + if (data.get(i) != null) { + changeMobData(sender, mob.getType(), spawnedMob, data.get(i).toLowerCase(Locale.ENGLISH), target); + } + } - spawnedMob.setPassenger(spawnedMount); + int next = (i + 1); + if (next < parts.size()) //If it's the last mob in the list, don't set the mount + { + Mob mMob = Mob.fromName(parts.get(next)); + spawnedMount = mMob.spawn(sloc.getWorld(), server, sloc); + defaultMobData(mMob.getType(), spawnedMount); - spawnedMob = spawnedMount; - } - } - } + if (data.get(next) != null) { + changeMobData(sender, mMob.getType(), spawnedMount, data.get(next).toLowerCase(Locale.ENGLISH), target); + } - private static void checkSpawnable(IEssentials ess, CommandSource sender, Mob mob) throws Exception - { - if (mob == null) - { - throw new Exception(tl("invalidMob")); - } + spawnedMob.setPassenger(spawnedMount); - if (ess.getSettings().getProtectPreventSpawn(mob.getType().toString().toLowerCase(Locale.ENGLISH))) - { - throw new Exception(tl("disabledToSpawnMob")); - } + spawnedMob = spawnedMount; + } + } + } - if (sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.spawnmob." + mob.name.toLowerCase(Locale.ENGLISH))) - { - throw new Exception(tl("noPermToSpawnMob")); - } - } + private static void checkSpawnable(IEssentials ess, CommandSource sender, Mob mob) throws Exception { + if (mob == null) { + throw new Exception(tl("invalidMob")); + } - private static void changeMobData(final CommandSource sender, final EntityType type, final Entity spawned, final String inputData, final User target) throws Exception - { - String data = inputData; + if (ess.getSettings().getProtectPreventSpawn(mob.getType().toString().toLowerCase(Locale.ENGLISH))) { + throw new Exception(tl("disabledToSpawnMob")); + } - if (data.isEmpty()) - { - sender.sendMessage(tl("mobDataList", StringUtil.joinList(MobData.getValidHelp(spawned)))); - } - - if (spawned instanceof Zombie) - { - ((Zombie)spawned).setBaby(false); - } - else if(spawned instanceof Ageable) - { - ((Ageable)spawned).setAdult(); - } + if (sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.spawnmob." + mob.name.toLowerCase(Locale.ENGLISH))) { + throw new Exception(tl("noPermToSpawnMob")); + } + } - if (spawned instanceof Zombie || type == EntityType.SKELETON) - { - if (inputData.contains("armor") || inputData.contains("armour")) - { - final EntityEquipment invent = ((LivingEntity)spawned).getEquipment(); - if (inputData.contains("noarmor") || inputData.contains("noarmour")) - { - invent.clear(); - } - else if (inputData.contains("diamond")) - { - invent.setBoots(new ItemStack(Material.DIAMOND_BOOTS, 1)); - invent.setLeggings(new ItemStack(Material.DIAMOND_LEGGINGS, 1)); - invent.setChestplate(new ItemStack(Material.DIAMOND_CHESTPLATE, 1)); - invent.setHelmet(new ItemStack(Material.DIAMOND_HELMET, 1)); - } - else if (inputData.contains("gold")) - { - invent.setBoots(new ItemStack(Material.GOLD_BOOTS, 1)); - invent.setLeggings(new ItemStack(Material.GOLD_LEGGINGS, 1)); - invent.setChestplate(new ItemStack(Material.GOLD_CHESTPLATE, 1)); - invent.setHelmet(new ItemStack(Material.GOLD_HELMET, 1)); - } - else if (inputData.contains("leather")) - { - invent.setBoots(new ItemStack(Material.LEATHER_BOOTS, 1)); - invent.setLeggings(new ItemStack(Material.LEATHER_LEGGINGS, 1)); - invent.setChestplate(new ItemStack(Material.LEATHER_CHESTPLATE, 1)); - invent.setHelmet(new ItemStack(Material.LEATHER_HELMET, 1)); - } - else - { - invent.setBoots(new ItemStack(Material.IRON_BOOTS, 1)); - invent.setLeggings(new ItemStack(Material.IRON_LEGGINGS, 1)); - invent.setChestplate(new ItemStack(Material.IRON_CHESTPLATE, 1)); - invent.setHelmet(new ItemStack(Material.IRON_HELMET, 1)); - } - invent.setBootsDropChance(0f); - invent.setLeggingsDropChance(0f); - invent.setChestplateDropChance(0f); - invent.setHelmetDropChance(0f); - } + private static void changeMobData(final CommandSource sender, final EntityType type, final Entity spawned, final String inputData, final User target) throws Exception { + String data = inputData; - } + if (data.isEmpty()) { + sender.sendMessage(tl("mobDataList", StringUtil.joinList(MobData.getValidHelp(spawned)))); + } - MobData newData = MobData.fromData(spawned, data); - while (newData != null) - { - newData.setData(spawned, target.getBase(), data); - data = data.replace(newData.getMatched(), ""); - newData = MobData.fromData(spawned, data); - } - } + if (spawned instanceof Zombie) { + ((Zombie) spawned).setBaby(false); + } else if (spawned instanceof Ageable) { + ((Ageable) spawned).setAdult(); + } - private static void defaultMobData(final EntityType type, final Entity spawned) - { - if (type == EntityType.SKELETON) - { - final EntityEquipment invent = ((LivingEntity)spawned).getEquipment(); - invent.setItemInHand(new ItemStack(Material.BOW, 1)); - invent.setItemInHandDropChance(0.1f); + if (spawned instanceof Zombie || type == EntityType.SKELETON) { + if (inputData.contains("armor") || inputData.contains("armour")) { + final EntityEquipment invent = ((LivingEntity) spawned).getEquipment(); + if (inputData.contains("noarmor") || inputData.contains("noarmour")) { + invent.clear(); + } else if (inputData.contains("diamond")) { + invent.setBoots(new ItemStack(Material.DIAMOND_BOOTS, 1)); + invent.setLeggings(new ItemStack(Material.DIAMOND_LEGGINGS, 1)); + invent.setChestplate(new ItemStack(Material.DIAMOND_CHESTPLATE, 1)); + invent.setHelmet(new ItemStack(Material.DIAMOND_HELMET, 1)); + } else if (inputData.contains("gold")) { + invent.setBoots(new ItemStack(Material.GOLD_BOOTS, 1)); + invent.setLeggings(new ItemStack(Material.GOLD_LEGGINGS, 1)); + invent.setChestplate(new ItemStack(Material.GOLD_CHESTPLATE, 1)); + invent.setHelmet(new ItemStack(Material.GOLD_HELMET, 1)); + } else if (inputData.contains("leather")) { + invent.setBoots(new ItemStack(Material.LEATHER_BOOTS, 1)); + invent.setLeggings(new ItemStack(Material.LEATHER_LEGGINGS, 1)); + invent.setChestplate(new ItemStack(Material.LEATHER_CHESTPLATE, 1)); + invent.setHelmet(new ItemStack(Material.LEATHER_HELMET, 1)); + } else { + invent.setBoots(new ItemStack(Material.IRON_BOOTS, 1)); + invent.setLeggings(new ItemStack(Material.IRON_LEGGINGS, 1)); + invent.setChestplate(new ItemStack(Material.IRON_CHESTPLATE, 1)); + invent.setHelmet(new ItemStack(Material.IRON_HELMET, 1)); + } + invent.setBootsDropChance(0f); + invent.setLeggingsDropChance(0f); + invent.setChestplateDropChance(0f); + invent.setHelmetDropChance(0f); + } - invent.setBoots(new ItemStack(Material.GOLD_BOOTS, 1)); - invent.setBootsDropChance(0.0f); - } + } - if (type == EntityType.PIG_ZOMBIE) - { - final PigZombie zombie = ((PigZombie)spawned); - zombie.setVillager(false); - - final EntityEquipment invent = zombie.getEquipment(); - invent.setItemInHand(new ItemStack(Material.GOLD_SWORD, 1)); - invent.setItemInHandDropChance(0.1f); + MobData newData = MobData.fromData(spawned, data); + while (newData != null) { + newData.setData(spawned, target.getBase(), data); + data = data.replace(newData.getMatched(), ""); + newData = MobData.fromData(spawned, data); + } + } - invent.setBoots(new ItemStack(Material.GOLD_BOOTS, 1)); - invent.setBootsDropChance(0.0f); - } + private static void defaultMobData(final EntityType type, final Entity spawned) { + if (type == EntityType.SKELETON) { + final EntityEquipment invent = ((LivingEntity) spawned).getEquipment(); + invent.setItemInHand(new ItemStack(Material.BOW, 1)); + invent.setItemInHandDropChance(0.1f); - if (type == EntityType.ZOMBIE) - { - final Zombie zombie = ((Zombie)spawned); - zombie.setVillager(false); - - final EntityEquipment invent = zombie.getEquipment(); - invent.setBoots(new ItemStack(Material.GOLD_BOOTS, 1)); - invent.setBootsDropChance(0.0f); - } + invent.setBoots(new ItemStack(Material.GOLD_BOOTS, 1)); + invent.setBootsDropChance(0.0f); + } - if (type == EntityType.HORSE) - { - ((Horse)spawned).setJumpStrength(1.2); - } - } + if (type == EntityType.PIG_ZOMBIE) { + final PigZombie zombie = ((PigZombie) spawned); + zombie.setVillager(false); + + final EntityEquipment invent = zombie.getEquipment(); + invent.setItemInHand(new ItemStack(Material.GOLD_SWORD, 1)); + invent.setItemInHandDropChance(0.1f); + + invent.setBoots(new ItemStack(Material.GOLD_BOOTS, 1)); + invent.setBootsDropChance(0.0f); + } + + if (type == EntityType.ZOMBIE) { + final Zombie zombie = ((Zombie) spawned); + zombie.setVillager(false); + + final EntityEquipment invent = zombie.getEquipment(); + invent.setBoots(new ItemStack(Material.GOLD_BOOTS, 1)); + invent.setBootsDropChance(0.0f); + } + + if (type == EntityType.HORSE) { + ((Horse) spawned).setJumpStrength(1.2); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/TNTExplodeListener.java b/Essentials/src/com/earth2me/essentials/TNTExplodeListener.java index 2318347c8..b0239ae69 100644 --- a/Essentials/src/com/earth2me/essentials/TNTExplodeListener.java +++ b/Essentials/src/com/earth2me/essentials/TNTExplodeListener.java @@ -8,55 +8,45 @@ import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityExplodeEvent; -public class TNTExplodeListener implements Listener, Runnable -{ - private final transient IEssentials ess; - private transient boolean enabled = false; - private transient int timer = -1; +public class TNTExplodeListener implements Listener, Runnable { + private final transient IEssentials ess; + private transient boolean enabled = false; + private transient int timer = -1; - public TNTExplodeListener(final IEssentials ess) - { - super(); - this.ess = ess; - } + public TNTExplodeListener(final IEssentials ess) { + super(); + this.ess = ess; + } - public void enable() - { - if (!enabled) - { - enabled = true; - timer = ess.scheduleSyncDelayedTask(this, 200); - return; - } - if (timer != -1) - { - ess.getScheduler().cancelTask(timer); - timer = ess.scheduleSyncDelayedTask(this, 200); - } - } + public void enable() { + if (!enabled) { + enabled = true; + timer = ess.scheduleSyncDelayedTask(this, 200); + return; + } + if (timer != -1) { + ess.getScheduler().cancelTask(timer); + timer = ess.scheduleSyncDelayedTask(this, 200); + } + } - @EventHandler(priority = EventPriority.LOW) - public void onEntityExplode(final EntityExplodeEvent event) - { - if (!enabled) - { - return; - } - if (event.getEntity() instanceof LivingEntity) - { - return; - } - if (event.blockList().size() < 1) - { - return; - } - event.setCancelled(true); - event.getLocation().getWorld().createExplosion(event.getLocation(), 0F); - } + @EventHandler(priority = EventPriority.LOW) + public void onEntityExplode(final EntityExplodeEvent event) { + if (!enabled) { + 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 = false; - } + @Override + public void run() { + enabled = false; + } } diff --git a/Essentials/src/com/earth2me/essentials/Teleport.java b/Essentials/src/com/earth2me/essentials/Teleport.java index 4858ad423..fc0820ab5 100644 --- a/Essentials/src/com/earth2me/essentials/Teleport.java +++ b/Essentials/src/com/earth2me/essentials/Teleport.java @@ -1,11 +1,7 @@ package com.earth2me.essentials; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.utils.DateUtil; import com.earth2me.essentials.utils.LocationUtil; -import java.math.BigDecimal; -import java.util.Calendar; -import java.util.GregorianCalendar; import net.ess3.api.IEssentials; import net.ess3.api.IUser; import org.bukkit.Location; @@ -13,284 +9,241 @@ import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; +import java.math.BigDecimal; +import java.util.Calendar; +import java.util.GregorianCalendar; -public class Teleport implements net.ess3.api.ITeleport -{ - private final IUser teleportOwner; - private final IEssentials ess; - private TimedTeleport timedTeleport; +import static com.earth2me.essentials.I18n.tl; - public Teleport(IUser user, IEssentials ess) - { - this.teleportOwner = user; - this.ess = ess; - } - public void cooldown(boolean check) throws Exception - { - final Calendar time = new GregorianCalendar(); - if (teleportOwner.getLastTeleportTimestamp() > 0) - { - // Take the current time, and remove the delay from it. - final double cooldown = ess.getSettings().getTeleportCooldown(); - final Calendar earliestTime = new GregorianCalendar(); - earliestTime.add(Calendar.SECOND, -(int)cooldown); - earliestTime.add(Calendar.MILLISECOND, -(int)((cooldown * 1000.0) % 1000.0)); - // This value contains the most recent time a teleportPlayer could have been used that would allow another use. - final long earliestLong = earliestTime.getTimeInMillis(); +public class Teleport implements net.ess3.api.ITeleport { + private final IUser teleportOwner; + private final IEssentials ess; + private TimedTeleport timedTeleport; - // When was the last teleportPlayer used? - final Long lastTime = teleportOwner.getLastTeleportTimestamp(); + public Teleport(IUser user, IEssentials ess) { + this.teleportOwner = user; + this.ess = ess; + } - if (lastTime > time.getTimeInMillis()) - { - // This is to make sure time didn't get messed up on last teleportPlayer use. - // If this happens, let's give the user the benifit of the doubt. - teleportOwner.setLastTeleportTimestamp(time.getTimeInMillis()); - return; - } - else if (lastTime > earliestLong && !teleportOwner.isAuthorized("essentials.teleport.cooldown.bypass")) - { - time.setTimeInMillis(lastTime); - time.add(Calendar.SECOND, (int)cooldown); - time.add(Calendar.MILLISECOND, (int)((cooldown * 1000.0) % 1000.0)); - throw new Exception(tl("timeBeforeTeleport", DateUtil.formatDateDiff(time.getTimeInMillis()))); - } - } - // if justCheck is set, don't update lastTeleport; we're just checking - if (!check) - { - teleportOwner.setLastTeleportTimestamp(time.getTimeInMillis()); - } - } + public void cooldown(boolean check) throws Exception { + final Calendar time = new GregorianCalendar(); + if (teleportOwner.getLastTeleportTimestamp() > 0) { + // Take the current time, and remove the delay from it. + final double cooldown = ess.getSettings().getTeleportCooldown(); + final Calendar earliestTime = new GregorianCalendar(); + earliestTime.add(Calendar.SECOND, -(int) cooldown); + earliestTime.add(Calendar.MILLISECOND, -(int) ((cooldown * 1000.0) % 1000.0)); + // This value contains the most recent time a teleportPlayer could have been used that would allow another use. + final long earliestLong = earliestTime.getTimeInMillis(); - private void warnUser(final IUser user, final double delay) - { - Calendar c = new GregorianCalendar(); - c.add(Calendar.SECOND, (int)delay); - c.add(Calendar.MILLISECOND, (int)((delay * 1000.0) % 1000.0)); - user.sendMessage(tl("dontMoveMessage", DateUtil.formatDateDiff(c.getTimeInMillis()))); - } + // When was the last teleportPlayer used? + final Long lastTime = teleportOwner.getLastTeleportTimestamp(); - //The now function is used when you want to skip tp delay when teleporting someone to a location or player. - @Override - public void now(Location loc, boolean cooldown, TeleportCause cause) throws Exception - { - if (cooldown) - { - cooldown(false); - } - final ITarget target = new LocationTarget(loc); - now(teleportOwner, target, cause); - } + if (lastTime > time.getTimeInMillis()) { + // This is to make sure time didn't get messed up on last teleportPlayer use. + // If this happens, let's give the user the benifit of the doubt. + teleportOwner.setLastTeleportTimestamp(time.getTimeInMillis()); + return; + } else if (lastTime > earliestLong && !teleportOwner.isAuthorized("essentials.teleport.cooldown.bypass")) { + time.setTimeInMillis(lastTime); + time.add(Calendar.SECOND, (int) cooldown); + time.add(Calendar.MILLISECOND, (int) ((cooldown * 1000.0) % 1000.0)); + throw new Exception(tl("timeBeforeTeleport", DateUtil.formatDateDiff(time.getTimeInMillis()))); + } + } + // if justCheck is set, don't update lastTeleport; we're just checking + if (!check) { + teleportOwner.setLastTeleportTimestamp(time.getTimeInMillis()); + } + } - @Override - public void now(Player entity, boolean cooldown, TeleportCause cause) throws Exception - { - if (cooldown) - { - cooldown(false); - } - final ITarget target = new PlayerTarget(entity); - now(teleportOwner, target, cause); - teleportOwner.sendMessage(tl("teleporting", target.getLocation().getWorld().getName(), target.getLocation().getBlockX(), target.getLocation().getBlockY(), target.getLocation().getBlockZ())); - } + private void warnUser(final IUser user, final double delay) { + Calendar c = new GregorianCalendar(); + c.add(Calendar.SECOND, (int) delay); + c.add(Calendar.MILLISECOND, (int) ((delay * 1000.0) % 1000.0)); + user.sendMessage(tl("dontMoveMessage", DateUtil.formatDateDiff(c.getTimeInMillis()))); + } - protected void now(IUser teleportee, ITarget target, TeleportCause cause) throws Exception - { - cancel(false); - teleportee.setLastLocation(); - final Location loc = target.getLocation(); + //The now function is used when you want to skip tp delay when teleporting someone to a location or player. + @Override + public void now(Location loc, boolean cooldown, TeleportCause cause) throws Exception { + if (cooldown) { + cooldown(false); + } + final ITarget target = new LocationTarget(loc); + now(teleportOwner, target, cause); + } - if (LocationUtil.isBlockUnsafeForUser(teleportee, loc.getWorld(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())) - { - if (ess.getSettings().isTeleportSafetyEnabled()) - { - if (teleportee.getBase().isInsideVehicle()) - { - teleportee.getBase().leaveVehicle(); - } - teleportee.getBase().teleport(LocationUtil.getSafeDestination(teleportee, loc), cause); - } - else - { - throw new Exception(tl("unsafeTeleportDestination", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); - } - } - else - { - if (teleportee.getBase().isInsideVehicle()) - { - teleportee.getBase().leaveVehicle(); - } - teleportee.getBase().teleport(LocationUtil.getRoundedDestination(loc), cause); - } - } + @Override + public void now(Player entity, boolean cooldown, TeleportCause cause) throws Exception { + if (cooldown) { + cooldown(false); + } + final ITarget target = new PlayerTarget(entity); + now(teleportOwner, target, cause); + teleportOwner.sendMessage(tl("teleporting", target.getLocation().getWorld().getName(), target.getLocation().getBlockX(), target.getLocation().getBlockY(), target.getLocation().getBlockZ())); + } - //The teleportPlayer function is used when you want to normally teleportPlayer someone to a location or player. - //This method is nolonger used internally and will be removed. - @Deprecated - @Override - public void teleport(Location loc, Trade chargeFor) throws Exception - { - teleport(loc, chargeFor, TeleportCause.PLUGIN); - } + protected void now(IUser teleportee, ITarget target, TeleportCause cause) throws Exception { + cancel(false); + teleportee.setLastLocation(); + final Location loc = target.getLocation(); - @Override - public void teleport(Location loc, Trade chargeFor, TeleportCause cause) throws Exception - { - teleport(teleportOwner, new LocationTarget(loc), chargeFor, cause); - } + if (LocationUtil.isBlockUnsafeForUser(teleportee, loc.getWorld(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())) { + if (ess.getSettings().isTeleportSafetyEnabled()) { + if (teleportee.getBase().isInsideVehicle()) { + teleportee.getBase().leaveVehicle(); + } + teleportee.getBase().teleport(LocationUtil.getSafeDestination(teleportee, loc), cause); + } else { + throw new Exception(tl("unsafeTeleportDestination", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); + } + } else { + if (teleportee.getBase().isInsideVehicle()) { + teleportee.getBase().leaveVehicle(); + } + teleportee.getBase().teleport(LocationUtil.getRoundedDestination(loc), cause); + } + } - //This is used when teleporting to a player - @Override - public void teleport(Player entity, Trade chargeFor, TeleportCause cause) throws Exception - { - ITarget target = new PlayerTarget(entity); - teleportOwner.sendMessage(tl("teleportToPlayer", entity.getDisplayName())); - teleport(teleportOwner, target, chargeFor, cause); - } + //The teleportPlayer function is used when you want to normally teleportPlayer someone to a location or player. + //This method is nolonger used internally and will be removed. + @Deprecated + @Override + public void teleport(Location loc, Trade chargeFor) throws Exception { + teleport(loc, chargeFor, TeleportCause.PLUGIN); + } - //This is used when teleporting to stored location - @Override - public void teleportPlayer(IUser teleportee, Location loc, Trade chargeFor, TeleportCause cause) throws Exception - { - teleport(teleportee, new LocationTarget(loc), chargeFor, cause); - } + @Override + public void teleport(Location loc, Trade chargeFor, TeleportCause cause) throws Exception { + teleport(teleportOwner, new LocationTarget(loc), chargeFor, cause); + } - //This is used on /tphere - @Override - public void teleportPlayer(IUser teleportee, Player entity, Trade chargeFor, TeleportCause cause) throws Exception - { - ITarget target = new PlayerTarget(entity); - teleport(teleportee, target, chargeFor, cause); - teleportee.sendMessage(tl("teleporting", target.getLocation().getWorld().getName(), target.getLocation().getBlockX(), target.getLocation().getBlockY(), target.getLocation().getBlockZ())); - teleportOwner.sendMessage(tl("teleporting", target.getLocation().getWorld().getName(), target.getLocation().getBlockX(), target.getLocation().getBlockY(), target.getLocation().getBlockZ())); - } + //This is used when teleporting to a player + @Override + public void teleport(Player entity, Trade chargeFor, TeleportCause cause) throws Exception { + ITarget target = new PlayerTarget(entity); + teleportOwner.sendMessage(tl("teleportToPlayer", entity.getDisplayName())); + teleport(teleportOwner, target, chargeFor, cause); + } - private void teleport(IUser teleportee, ITarget target, Trade chargeFor, TeleportCause cause) throws Exception - { - double delay = ess.getSettings().getTeleportDelay(); + //This is used when teleporting to stored location + @Override + public void teleportPlayer(IUser teleportee, Location loc, Trade chargeFor, TeleportCause cause) throws Exception { + teleport(teleportee, new LocationTarget(loc), chargeFor, cause); + } - Trade cashCharge = chargeFor; + //This is used on /tphere + @Override + public void teleportPlayer(IUser teleportee, Player entity, Trade chargeFor, TeleportCause cause) throws Exception { + ITarget target = new PlayerTarget(entity); + teleport(teleportee, target, chargeFor, cause); + teleportee.sendMessage(tl("teleporting", target.getLocation().getWorld().getName(), target.getLocation().getBlockX(), target.getLocation().getBlockY(), target.getLocation().getBlockZ())); + teleportOwner.sendMessage(tl("teleporting", target.getLocation().getWorld().getName(), target.getLocation().getBlockX(), target.getLocation().getBlockY(), target.getLocation().getBlockZ())); + } - if (chargeFor != null) - { - chargeFor.isAffordableFor(teleportOwner); + private void teleport(IUser teleportee, ITarget target, Trade chargeFor, TeleportCause cause) throws Exception { + double delay = ess.getSettings().getTeleportDelay(); - //This code is to make sure that commandcosts are checked in the initial world, and not in the resulting world. - if (!chargeFor.getCommandCost(teleportOwner).equals(BigDecimal.ZERO)) - { - //By converting a command cost to a regular cost, the command cost permission isn't checked when executing the charge after teleport. - cashCharge = new Trade(chargeFor.getCommandCost(teleportOwner), ess); - } - } + Trade cashCharge = chargeFor; - cooldown(true); - if (delay <= 0 || teleportOwner.isAuthorized("essentials.teleport.timer.bypass") - || teleportee.isAuthorized("essentials.teleport.timer.bypass")) - { - cooldown(false); - now(teleportee, target, cause); - if (cashCharge != null) - { - cashCharge.charge(teleportOwner); - } - return; - } + if (chargeFor != null) { + chargeFor.isAffordableFor(teleportOwner); - cancel(false); - warnUser(teleportee, delay); - initTimer((long)(delay * 1000.0), teleportee, target, cashCharge, cause, false); - } + //This code is to make sure that commandcosts are checked in the initial world, and not in the resulting world. + if (!chargeFor.getCommandCost(teleportOwner).equals(BigDecimal.ZERO)) { + //By converting a command cost to a regular cost, the command cost permission isn't checked when executing the charge after teleport. + cashCharge = new Trade(chargeFor.getCommandCost(teleportOwner), ess); + } + } - //The respawn function is a wrapper used to handle tp fallback, on /jail and /home - @Override - public void respawn(final Trade chargeFor, TeleportCause cause) throws Exception - { - double delay = ess.getSettings().getTeleportDelay(); - if (chargeFor != null) - { - chargeFor.isAffordableFor(teleportOwner); - } - cooldown(true); - if (delay <= 0 || teleportOwner.isAuthorized("essentials.teleport.timer.bypass")) - { - cooldown(false); - respawnNow(teleportOwner, cause); - if (chargeFor != null) - { - chargeFor.charge(teleportOwner); - } - return; - } + cooldown(true); + if (delay <= 0 || teleportOwner.isAuthorized("essentials.teleport.timer.bypass") || teleportee.isAuthorized("essentials.teleport.timer.bypass")) { + cooldown(false); + now(teleportee, target, cause); + if (cashCharge != null) { + cashCharge.charge(teleportOwner); + } + return; + } - cancel(false); - warnUser(teleportOwner, delay); - initTimer((long)(delay * 1000.0), teleportOwner, null, chargeFor, cause, true); - } + cancel(false); + warnUser(teleportee, delay); + initTimer((long) (delay * 1000.0), teleportee, target, cashCharge, cause, false); + } - protected void respawnNow(IUser teleportee, TeleportCause cause) throws Exception - { - final Player player = teleportee.getBase(); - Location bed = player.getBedSpawnLocation(); - if (bed != null) - { - now(teleportee, new LocationTarget(bed), cause); - } - else - { - if (ess.getSettings().isDebug()) - { - ess.getLogger().info("Could not find bed spawn, forcing respawn event."); - } - final PlayerRespawnEvent pre = new PlayerRespawnEvent(player, player.getWorld().getSpawnLocation(), false); - ess.getServer().getPluginManager().callEvent(pre); - now(teleportee, new LocationTarget(pre.getRespawnLocation()), cause); - } - } + //The respawn function is a wrapper used to handle tp fallback, on /jail and /home + @Override + public void respawn(final Trade chargeFor, TeleportCause cause) throws Exception { + double delay = ess.getSettings().getTeleportDelay(); + if (chargeFor != null) { + chargeFor.isAffordableFor(teleportOwner); + } + cooldown(true); + if (delay <= 0 || teleportOwner.isAuthorized("essentials.teleport.timer.bypass")) { + cooldown(false); + respawnNow(teleportOwner, cause); + if (chargeFor != null) { + chargeFor.charge(teleportOwner); + } + return; + } - //The warp function is a wrapper used to teleportPlayer a player to a /warp - @Override - public void warp(IUser teleportee, String warp, Trade chargeFor, TeleportCause cause) throws Exception - { - Location loc = ess.getWarps().getWarp(warp); - teleportee.sendMessage(tl("warpingTo", warp, loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); - if (!teleportee.equals(teleportOwner)) - { - teleportOwner.sendMessage(tl("warpingTo", warp, loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); - } - teleport(teleportee, new LocationTarget(loc), chargeFor, cause); - } + cancel(false); + warnUser(teleportOwner, delay); + initTimer((long) (delay * 1000.0), teleportOwner, null, chargeFor, cause, true); + } - //The back function is a wrapper used to teleportPlayer a player /back to their previous location. - @Override - public void back(Trade chargeFor) throws Exception - { - final Location loc = teleportOwner.getLastLocation(); - teleportOwner.sendMessage(tl("backUsageMsg", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); - teleport(teleportOwner, new LocationTarget(loc), chargeFor, TeleportCause.COMMAND); - } + protected void respawnNow(IUser teleportee, TeleportCause cause) throws Exception { + final Player player = teleportee.getBase(); + Location bed = player.getBedSpawnLocation(); + if (bed != null) { + now(teleportee, new LocationTarget(bed), cause); + } else { + if (ess.getSettings().isDebug()) { + ess.getLogger().info("Could not find bed spawn, forcing respawn event."); + } + final PlayerRespawnEvent pre = new PlayerRespawnEvent(player, player.getWorld().getSpawnLocation(), false); + ess.getServer().getPluginManager().callEvent(pre); + now(teleportee, new LocationTarget(pre.getRespawnLocation()), cause); + } + } - //This function is used to throw a user back after a jail sentence - @Override - public void back() throws Exception - { - now(teleportOwner, new LocationTarget(teleportOwner.getLastLocation()), TeleportCause.COMMAND); - } + //The warp function is a wrapper used to teleportPlayer a player to a /warp + @Override + public void warp(IUser teleportee, String warp, Trade chargeFor, TeleportCause cause) throws Exception { + Location loc = ess.getWarps().getWarp(warp); + teleportee.sendMessage(tl("warpingTo", warp, loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); + if (!teleportee.equals(teleportOwner)) { + teleportOwner.sendMessage(tl("warpingTo", warp, loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); + } + teleport(teleportee, new LocationTarget(loc), chargeFor, cause); + } - //If we need to cancelTimer a pending teleportPlayer call this method - private void cancel(boolean notifyUser) - { - if (timedTeleport != null) - { - timedTeleport.cancelTimer(notifyUser); - timedTeleport = null; - } - } + //The back function is a wrapper used to teleportPlayer a player /back to their previous location. + @Override + public void back(Trade chargeFor) throws Exception { + final Location loc = teleportOwner.getLastLocation(); + teleportOwner.sendMessage(tl("backUsageMsg", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); + teleport(teleportOwner, new LocationTarget(loc), chargeFor, TeleportCause.COMMAND); + } - private void initTimer(long delay, IUser teleportUser, ITarget target, Trade chargeFor, TeleportCause cause, boolean respawn) - { - timedTeleport = new TimedTeleport(teleportOwner, ess, this, delay, teleportUser, target, chargeFor, cause, respawn); - } + //This function is used to throw a user back after a jail sentence + @Override + public void back() throws Exception { + now(teleportOwner, new LocationTarget(teleportOwner.getLastLocation()), TeleportCause.COMMAND); + } + + //If we need to cancelTimer a pending teleportPlayer call this method + private void cancel(boolean notifyUser) { + if (timedTeleport != null) { + timedTeleport.cancelTimer(notifyUser); + timedTeleport = null; + } + } + + private void initTimer(long delay, IUser teleportUser, ITarget target, Trade chargeFor, TeleportCause cause, boolean respawn) { + timedTeleport = new TimedTeleport(teleportOwner, ess, this, delay, teleportUser, target, chargeFor, cause, respawn); + } } diff --git a/Essentials/src/com/earth2me/essentials/TimedTeleport.java b/Essentials/src/com/earth2me/essentials/TimedTeleport.java index e426c1cec..0544c6c8c 100644 --- a/Essentials/src/com/earth2me/essentials/TimedTeleport.java +++ b/Essentials/src/com/earth2me/essentials/TimedTeleport.java @@ -1,177 +1,143 @@ package com.earth2me.essentials; -import static com.earth2me.essentials.I18n.tl; -import java.util.UUID; import net.ess3.api.IEssentials; import net.ess3.api.IUser; import org.bukkit.Location; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; +import java.util.UUID; -public class TimedTeleport implements Runnable -{ - private static final double MOVE_CONSTANT = 0.3; - private final IUser teleportOwner; - private final IEssentials ess; - private final Teleport teleport; - private final UUID timer_teleportee; - private int timer_task = -1; - private final long timer_started; // time this task was initiated - private final long timer_delay; // how long to delay the teleportPlayer - private double timer_health; - // note that I initially stored a clone of the location for reference, but... - // when comparing locations, I got incorrect mismatches (rounding errors, looked like) - // so, the X/Y/Z values are stored instead and rounded off - private final long timer_initX; - private final long timer_initY; - private final long timer_initZ; - private final ITarget timer_teleportTarget; - private final boolean timer_respawn; - private final boolean timer_canMove; - private final Trade timer_chargeFor; - private final TeleportCause timer_cause; +import static com.earth2me.essentials.I18n.tl; - public TimedTeleport(IUser user, IEssentials ess, Teleport teleport, long delay, IUser teleportUser, ITarget target, Trade chargeFor, TeleportCause cause, boolean respawn) - { - this.teleportOwner = user; - this.ess = ess; - this.teleport = teleport; - this.timer_started = System.currentTimeMillis(); - this.timer_delay = delay; - this.timer_health = teleportUser.getBase().getHealth(); - this.timer_initX = Math.round(teleportUser.getBase().getLocation().getX() * MOVE_CONSTANT); - this.timer_initY = Math.round(teleportUser.getBase().getLocation().getY() * MOVE_CONSTANT); - this.timer_initZ = Math.round(teleportUser.getBase().getLocation().getZ() * MOVE_CONSTANT); - this.timer_teleportee = teleportUser.getBase().getUniqueId(); - this.timer_teleportTarget = target; - this.timer_chargeFor = chargeFor; - this.timer_cause = cause; - this.timer_respawn = respawn; - this.timer_canMove = user.isAuthorized("essentials.teleport.timer.move"); +public class TimedTeleport implements Runnable { + private static final double MOVE_CONSTANT = 0.3; + private final IUser teleportOwner; + private final IEssentials ess; + private final Teleport teleport; + private final UUID timer_teleportee; + private int timer_task = -1; + private final long timer_started; // time this task was initiated + private final long timer_delay; // how long to delay the teleportPlayer + private double timer_health; + // note that I initially stored a clone of the location for reference, but... + // when comparing locations, I got incorrect mismatches (rounding errors, looked like) + // so, the X/Y/Z values are stored instead and rounded off + private final long timer_initX; + private final long timer_initY; + private final long timer_initZ; + private final ITarget timer_teleportTarget; + private final boolean timer_respawn; + private final boolean timer_canMove; + private final Trade timer_chargeFor; + private final TeleportCause timer_cause; - timer_task = ess.runTaskTimerAsynchronously(this, 20, 20).getTaskId(); - } + public TimedTeleport(IUser user, IEssentials ess, Teleport teleport, long delay, IUser teleportUser, ITarget target, Trade chargeFor, TeleportCause cause, boolean respawn) { - @Override - public void run() - { + this.teleportOwner = user; + this.ess = ess; + this.teleport = teleport; + this.timer_started = System.currentTimeMillis(); + this.timer_delay = delay; + this.timer_health = teleportUser.getBase().getHealth(); + this.timer_initX = Math.round(teleportUser.getBase().getLocation().getX() * MOVE_CONSTANT); + this.timer_initY = Math.round(teleportUser.getBase().getLocation().getY() * MOVE_CONSTANT); + this.timer_initZ = Math.round(teleportUser.getBase().getLocation().getZ() * MOVE_CONSTANT); + this.timer_teleportee = teleportUser.getBase().getUniqueId(); + this.timer_teleportTarget = target; + this.timer_chargeFor = chargeFor; + this.timer_cause = cause; + this.timer_respawn = respawn; + this.timer_canMove = user.isAuthorized("essentials.teleport.timer.move"); - if (teleportOwner == null || !teleportOwner.getBase().isOnline() || teleportOwner.getBase().getLocation() == null) - { - cancelTimer(false); - return; - } + timer_task = ess.runTaskTimerAsynchronously(this, 20, 20).getTaskId(); + } - final IUser teleportUser = ess.getUser(this.timer_teleportee); + @Override + public void run() { - if (teleportUser == null || !teleportUser.getBase().isOnline()) - { - cancelTimer(false); - return; - } + if (teleportOwner == null || !teleportOwner.getBase().isOnline() || teleportOwner.getBase().getLocation() == null) { + cancelTimer(false); + return; + } - final Location currLocation = teleportUser.getBase().getLocation(); - if (currLocation == null) - { - cancelTimer(false); - return; - } + final IUser teleportUser = ess.getUser(this.timer_teleportee); - if (!timer_canMove - && (Math.round(currLocation.getX() * MOVE_CONSTANT) != timer_initX - || Math.round(currLocation.getY() * MOVE_CONSTANT) != timer_initY - || Math.round(currLocation.getZ() * MOVE_CONSTANT) != timer_initZ - || teleportUser.getBase().getHealth() < timer_health)) - { - // user moved, cancelTimer teleportPlayer - cancelTimer(true); - return; - } + if (teleportUser == null || !teleportUser.getBase().isOnline()) { + cancelTimer(false); + return; + } - class DelayedTeleportTask implements Runnable - { - @Override - public void run() - { + final Location currLocation = teleportUser.getBase().getLocation(); + if (currLocation == null) { + cancelTimer(false); + return; + } - timer_health = teleportUser.getBase().getHealth(); // in case user healed, then later gets injured - final long now = System.currentTimeMillis(); - if (now > timer_started + timer_delay) - { - try - { - teleport.cooldown(false); - } - catch (Exception ex) - { - teleportOwner.sendMessage(tl("cooldownWithMessage", ex.getMessage())); - if (teleportOwner != teleportUser) - { - teleportUser.sendMessage(tl("cooldownWithMessage", ex.getMessage())); - } - } - try - { - cancelTimer(false); - teleportUser.sendMessage(tl("teleportationCommencing")); + if (!timer_canMove && (Math.round(currLocation.getX() * MOVE_CONSTANT) != timer_initX || Math.round(currLocation.getY() * MOVE_CONSTANT) != timer_initY || Math.round(currLocation.getZ() * MOVE_CONSTANT) != timer_initZ || teleportUser.getBase().getHealth() < timer_health)) { + // user moved, cancelTimer teleportPlayer + cancelTimer(true); + return; + } - try - { - if (timer_chargeFor != null) - { - timer_chargeFor.isAffordableFor(teleportOwner); - } - if (timer_respawn) - { - teleport.respawnNow(teleportUser, timer_cause); - } - else - { - teleport.now(teleportUser, timer_teleportTarget, timer_cause); - } - if (timer_chargeFor != null) - { - timer_chargeFor.charge(teleportOwner); - } - } - catch (Exception ex) - { - } + class DelayedTeleportTask implements Runnable { + @Override + public void run() { - } - catch (Exception ex) - { - ess.showError(teleportOwner.getSource(), ex, "\\ teleport"); - } - } - } - } - ess.scheduleSyncDelayedTask(new DelayedTeleportTask()); - } + timer_health = teleportUser.getBase().getHealth(); // in case user healed, then later gets injured + final long now = System.currentTimeMillis(); + if (now > timer_started + timer_delay) { + try { + teleport.cooldown(false); + } catch (Exception ex) { + teleportOwner.sendMessage(tl("cooldownWithMessage", ex.getMessage())); + if (teleportOwner != teleportUser) { + teleportUser.sendMessage(tl("cooldownWithMessage", ex.getMessage())); + } + } + try { + cancelTimer(false); + teleportUser.sendMessage(tl("teleportationCommencing")); - //If we need to cancelTimer a pending teleportPlayer call this method - public void cancelTimer(boolean notifyUser) - { - if (timer_task == -1) - { - return; - } - try - { - ess.getServer().getScheduler().cancelTask(timer_task); - if (notifyUser) - { - teleportOwner.sendMessage(tl("pendingTeleportCancelled")); - if (timer_teleportee != null && !timer_teleportee.equals(teleportOwner.getBase().getUniqueId())) - { - ess.getUser(timer_teleportee).sendMessage(tl("pendingTeleportCancelled")); - } - } - } - finally - { - timer_task = -1; - } - } + try { + if (timer_chargeFor != null) { + timer_chargeFor.isAffordableFor(teleportOwner); + } + if (timer_respawn) { + teleport.respawnNow(teleportUser, timer_cause); + } else { + teleport.now(teleportUser, timer_teleportTarget, timer_cause); + } + if (timer_chargeFor != null) { + timer_chargeFor.charge(teleportOwner); + } + } catch (Exception ex) { + } + + } catch (Exception ex) { + ess.showError(teleportOwner.getSource(), ex, "\\ teleport"); + } + } + } + } + ess.scheduleSyncDelayedTask(new DelayedTeleportTask()); + } + + //If we need to cancelTimer a pending teleportPlayer call this method + public void cancelTimer(boolean notifyUser) { + if (timer_task == -1) { + return; + } + try { + ess.getServer().getScheduler().cancelTask(timer_task); + if (notifyUser) { + teleportOwner.sendMessage(tl("pendingTeleportCancelled")); + if (timer_teleportee != null && !timer_teleportee.equals(teleportOwner.getBase().getUniqueId())) { + ess.getUser(timer_teleportee).sendMessage(tl("pendingTeleportCancelled")); + } + } + } finally { + timer_task = -1; + } + } } diff --git a/Essentials/src/com/earth2me/essentials/Trade.java b/Essentials/src/com/earth2me/essentials/Trade.java index c5298a4b1..e003dccac 100644 --- a/Essentials/src/com/earth2me/essentials/Trade.java +++ b/Essentials/src/com/earth2me/essentials/Trade.java @@ -1,9 +1,15 @@ package com.earth2me.essentials; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.craftbukkit.InventoryWorkaround; import com.earth2me.essentials.craftbukkit.SetExpFix; import com.earth2me.essentials.utils.NumberUtil; +import net.ess3.api.IEssentials; +import net.ess3.api.IUser; +import net.ess3.api.MaxMoneyException; +import org.bukkit.Location; +import org.bukkit.entity.Item; +import org.bukkit.inventory.ItemStack; + import java.io.File; import java.io.FileWriter; import java.io.IOException; @@ -14,439 +20,340 @@ import java.util.Locale; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; -import net.ess3.api.IEssentials; -import net.ess3.api.IUser; -import net.ess3.api.MaxMoneyException; -import org.bukkit.Location; -import org.bukkit.entity.Item; -import org.bukkit.inventory.ItemStack; + +import static com.earth2me.essentials.I18n.tl; -public class Trade -{ - private final transient String command; - private final transient Trade fallbackTrade; - private final transient BigDecimal money; - private final transient ItemStack itemStack; - private final transient Integer exp; - private final transient IEssentials ess; +public class Trade { + private final transient String command; + private final transient Trade fallbackTrade; + private final transient BigDecimal money; + private final transient ItemStack itemStack; + private final transient Integer exp; + private final transient IEssentials ess; - public enum TradeType - { - MONEY, - EXP, - ITEM - } + public enum TradeType { + MONEY, + EXP, + ITEM + } - public enum OverflowType - { - ABORT, - DROP, - RETURN - } + public enum OverflowType { + ABORT, + DROP, + RETURN + } - public Trade(final String command, final IEssentials ess) - { - this(command, null, null, null, null, ess); - } + public Trade(final String command, final IEssentials ess) { + this(command, null, null, null, null, ess); + } - public Trade(final String command, final Trade fallback, final IEssentials ess) - { - this(command, fallback, null, null, null, ess); - } + public Trade(final String command, final Trade fallback, final IEssentials ess) { + this(command, fallback, null, null, null, ess); + } - @Deprecated - public Trade(final double money, final com.earth2me.essentials.IEssentials ess) - { - this(null, null, BigDecimal.valueOf(money), null, null, (IEssentials)ess); - } + @Deprecated + public Trade(final double money, final com.earth2me.essentials.IEssentials ess) { + this(null, null, BigDecimal.valueOf(money), null, null, (IEssentials) ess); + } - public Trade(final BigDecimal money, final IEssentials ess) - { - this(null, null, money, null, null, ess); - } + public Trade(final BigDecimal 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 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); - } + public Trade(final int exp, final IEssentials ess) { + this(null, null, null, null, exp, ess); + } - private Trade(final String command, final Trade fallback, final BigDecimal money, final ItemStack item, final Integer exp, final IEssentials ess) - { - this.command = command; - this.fallbackTrade = fallback; - this.money = money; - this.itemStack = item; - this.exp = exp; - this.ess = ess; - } + private Trade(final String command, final Trade fallback, final BigDecimal money, final ItemStack item, final Integer exp, final IEssentials ess) { + this.command = command; + this.fallbackTrade = fallback; + this.money = money; + this.itemStack = item; + this.exp = exp; + this.ess = ess; + } - public void isAffordableFor(final IUser user) throws ChargeException - { + public void isAffordableFor(final IUser user) throws ChargeException { - if (ess.getSettings().isDebug()) - { - ess.getLogger().log(Level.INFO, "checking if " + user.getName() + " can afford charge."); - } + if (ess.getSettings().isDebug()) { + ess.getLogger().log(Level.INFO, "checking if " + user.getName() + " can afford charge."); + } - if (getMoney() != null - && getMoney().signum() > 0 - && !user.canAfford(getMoney())) - { - throw new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(getMoney(), ess))); - } + if (getMoney() != null && getMoney().signum() > 0 && !user.canAfford(getMoney())) { + throw new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(getMoney(), ess))); + } - if (getItemStack() != null - && !user.getBase().getInventory().containsAtLeast(itemStack, itemStack.getAmount())) - { - throw new ChargeException(tl("missingItems", getItemStack().getAmount(), ess.getItemDb().name(getItemStack()))); - } + if (getItemStack() != null && !user.getBase().getInventory().containsAtLeast(itemStack, itemStack.getAmount())) { + throw new ChargeException(tl("missingItems", getItemStack().getAmount(), ess.getItemDb().name(getItemStack()))); + } - BigDecimal money; - if (command != null && !command.isEmpty() - && (money = getCommandCost(user)).signum() > 0 - && !user.canAfford(money)) - { - throw new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(money, ess))); - } + BigDecimal money; + if (command != null && !command.isEmpty() && (money = getCommandCost(user)).signum() > 0 && !user.canAfford(money)) { + throw new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(money, ess))); + } - if (exp != null && exp > 0 - && SetExpFix.getTotalExperience(user.getBase()) < exp) - { - throw new ChargeException(tl("notEnoughExperience")); - } - } + if (exp != null && exp > 0 && SetExpFix.getTotalExperience(user.getBase()) < exp) { + throw new ChargeException(tl("notEnoughExperience")); + } + } - public boolean pay(final IUser user) throws MaxMoneyException - { - return pay(user, OverflowType.ABORT) == null; - } + public boolean pay(final IUser user) throws MaxMoneyException { + return pay(user, OverflowType.ABORT) == null; + } - public Map pay(final IUser user, final OverflowType type) throws MaxMoneyException - { - if (getMoney() != null && getMoney().signum() > 0) - { - if (ess.getSettings().isDebug()) - { - ess.getLogger().log(Level.INFO, "paying user " + user.getName() + " via trade " + getMoney().toPlainString()); - } - user.giveMoney(getMoney()); - } - if (getItemStack() != null) - { - // This stores the would be overflow - Map overFlow = InventoryWorkaround.addAllItems(user.getBase().getInventory(), getItemStack()); + public Map pay(final IUser user, final OverflowType type) throws MaxMoneyException { + if (getMoney() != null && getMoney().signum() > 0) { + if (ess.getSettings().isDebug()) { + ess.getLogger().log(Level.INFO, "paying user " + user.getName() + " via trade " + getMoney().toPlainString()); + } + user.giveMoney(getMoney()); + } + if (getItemStack() != null) { + // This stores the would be overflow + Map overFlow = InventoryWorkaround.addAllItems(user.getBase().getInventory(), getItemStack()); - if (overFlow != null) - { - switch (type) - { - case ABORT: - if (ess.getSettings().isDebug()) - { - ess.getLogger().log(Level.INFO, "abort paying " + user.getName() + " itemstack " + getItemStack().toString() + " due to lack of inventory space "); - } + if (overFlow != null) { + switch (type) { + case ABORT: + if (ess.getSettings().isDebug()) { + ess.getLogger().log(Level.INFO, "abort paying " + user.getName() + " itemstack " + getItemStack().toString() + " due to lack of inventory space "); + } - return overFlow; + return overFlow; - case RETURN: - // Pay the user the items, and return overflow - final Map returnStack = InventoryWorkaround.addItems(user.getBase().getInventory(), getItemStack()); - user.getBase().updateInventory(); + case RETURN: + // Pay the user the items, and return overflow + final Map returnStack = InventoryWorkaround.addItems(user.getBase().getInventory(), getItemStack()); + user.getBase().updateInventory(); - if (ess.getSettings().isDebug()) - { - ess.getLogger().log(Level.INFO, "paying " + user.getName() + " partial itemstack " + getItemStack().toString() + " with overflow " + returnStack.get(0).toString()); - } + if (ess.getSettings().isDebug()) { + ess.getLogger().log(Level.INFO, "paying " + user.getName() + " partial itemstack " + getItemStack().toString() + " with overflow " + returnStack.get(0).toString()); + } - return returnStack; + return returnStack; - case DROP: - // Pay the users the items directly, and drop the rest, will always return no overflow. - final Map leftOver = InventoryWorkaround.addItems(user.getBase().getInventory(), getItemStack()); - final Location loc = user.getBase().getLocation(); - for (ItemStack loStack : leftOver.values()) - { - final int maxStackSize = loStack.getType().getMaxStackSize(); - final int stacks = loStack.getAmount() / maxStackSize; - final int leftover = loStack.getAmount() % maxStackSize; - final Item[] itemStacks = new Item[stacks + (leftover > 0 ? 1 : 0)]; - for (int i = 0; i < stacks; i++) - { - final ItemStack stack = loStack.clone(); - stack.setAmount(maxStackSize); - itemStacks[i] = loc.getWorld().dropItem(loc, stack); - } - if (leftover > 0) - { - final ItemStack stack = loStack.clone(); - stack.setAmount(leftover); - itemStacks[stacks] = loc.getWorld().dropItem(loc, stack); - } - } - if (ess.getSettings().isDebug()) - { - ess.getLogger().log(Level.INFO, "paying " + user.getName() + " partial itemstack " + getItemStack().toString() + " and dropping overflow " + leftOver.get(0).toString()); - } - } - } - else if (ess.getSettings().isDebug()) - { - ess.getLogger().log(Level.INFO, "paying " + user.getName() + " itemstack " + getItemStack().toString()); - } - user.getBase().updateInventory(); - } - if (getExperience() != null) - { - SetExpFix.setTotalExperience(user.getBase(), SetExpFix.getTotalExperience(user.getBase()) + getExperience()); - } - return null; - } + case DROP: + // Pay the users the items directly, and drop the rest, will always return no overflow. + final Map leftOver = InventoryWorkaround.addItems(user.getBase().getInventory(), getItemStack()); + final Location loc = user.getBase().getLocation(); + for (ItemStack loStack : leftOver.values()) { + final int maxStackSize = loStack.getType().getMaxStackSize(); + final int stacks = loStack.getAmount() / maxStackSize; + final int leftover = loStack.getAmount() % maxStackSize; + final Item[] itemStacks = new Item[stacks + (leftover > 0 ? 1 : 0)]; + for (int i = 0; i < stacks; i++) { + final ItemStack stack = loStack.clone(); + stack.setAmount(maxStackSize); + itemStacks[i] = loc.getWorld().dropItem(loc, stack); + } + if (leftover > 0) { + final ItemStack stack = loStack.clone(); + stack.setAmount(leftover); + itemStacks[stacks] = loc.getWorld().dropItem(loc, stack); + } + } + if (ess.getSettings().isDebug()) { + ess.getLogger().log(Level.INFO, "paying " + user.getName() + " partial itemstack " + getItemStack().toString() + " and dropping overflow " + leftOver.get(0).toString()); + } + } + } else if (ess.getSettings().isDebug()) { + ess.getLogger().log(Level.INFO, "paying " + user.getName() + " itemstack " + getItemStack().toString()); + } + user.getBase().updateInventory(); + } + if (getExperience() != null) { + SetExpFix.setTotalExperience(user.getBase(), SetExpFix.getTotalExperience(user.getBase()) + getExperience()); + } + return null; + } - public void charge(final IUser user) throws ChargeException - { - if (ess.getSettings().isDebug()) - { - ess.getLogger().log(Level.INFO, "attempting to charge user " + user.getName()); - } - if (getMoney() != null) - { - if (ess.getSettings().isDebug()) - { - ess.getLogger().log(Level.INFO, "charging user " + user.getName() + " money " + getMoney().toPlainString()); - } - if (!user.canAfford(getMoney()) && getMoney().signum() > 0) - { - throw new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(getMoney(), ess))); - } - user.takeMoney(getMoney()); - } - if (getItemStack() != null) - { - if (ess.getSettings().isDebug()) - { - ess.getLogger().log(Level.INFO, "charging user " + user.getName() + " itemstack " + getItemStack().toString()); - } - if (!user.getBase().getInventory().containsAtLeast(getItemStack(), getItemStack().getAmount())) - { - throw new ChargeException(tl("missingItems", getItemStack().getAmount(), getItemStack().getType().toString().toLowerCase(Locale.ENGLISH).replace("_", " "))); - } - user.getBase().getInventory().removeItem(getItemStack()); - user.getBase().updateInventory(); - } - if (command != null) - { - final BigDecimal cost = getCommandCost(user); - if (!user.canAfford(cost) && cost.signum() > 0) - { - throw new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(cost, ess))); - } - user.takeMoney(cost); - } - if (getExperience() != null) - { - if (ess.getSettings().isDebug()) - { - ess.getLogger().log(Level.INFO, "charging user " + user.getName() + " exp " + getExperience()); - } - final int experience = SetExpFix.getTotalExperience(user.getBase()); - if (experience < getExperience() && getExperience() > 0) - { - throw new ChargeException(tl("notEnoughExperience")); - } - SetExpFix.setTotalExperience(user.getBase(), experience - getExperience()); - } - if (ess.getSettings().isDebug()) - { - ess.getLogger().log(Level.INFO, "charge user " + user.getName() + " completed"); - } - } + public void charge(final IUser user) throws ChargeException { + if (ess.getSettings().isDebug()) { + ess.getLogger().log(Level.INFO, "attempting to charge user " + user.getName()); + } + if (getMoney() != null) { + if (ess.getSettings().isDebug()) { + ess.getLogger().log(Level.INFO, "charging user " + user.getName() + " money " + getMoney().toPlainString()); + } + if (!user.canAfford(getMoney()) && getMoney().signum() > 0) { + throw new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(getMoney(), ess))); + } + user.takeMoney(getMoney()); + } + if (getItemStack() != null) { + if (ess.getSettings().isDebug()) { + ess.getLogger().log(Level.INFO, "charging user " + user.getName() + " itemstack " + getItemStack().toString()); + } + if (!user.getBase().getInventory().containsAtLeast(getItemStack(), getItemStack().getAmount())) { + throw new ChargeException(tl("missingItems", getItemStack().getAmount(), getItemStack().getType().toString().toLowerCase(Locale.ENGLISH).replace("_", " "))); + } + user.getBase().getInventory().removeItem(getItemStack()); + user.getBase().updateInventory(); + } + if (command != null) { + final BigDecimal cost = getCommandCost(user); + if (!user.canAfford(cost) && cost.signum() > 0) { + throw new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(cost, ess))); + } + user.takeMoney(cost); + } + if (getExperience() != null) { + if (ess.getSettings().isDebug()) { + ess.getLogger().log(Level.INFO, "charging user " + user.getName() + " exp " + getExperience()); + } + final int experience = SetExpFix.getTotalExperience(user.getBase()); + if (experience < getExperience() && getExperience() > 0) { + throw new ChargeException(tl("notEnoughExperience")); + } + SetExpFix.setTotalExperience(user.getBase(), experience - getExperience()); + } + if (ess.getSettings().isDebug()) { + ess.getLogger().log(Level.INFO, "charge user " + user.getName() + " completed"); + } + } - public BigDecimal getMoney() - { - return money; - } + public BigDecimal getMoney() { + return money; + } - public ItemStack getItemStack() - { - return itemStack; - } + public ItemStack getItemStack() { + return itemStack; + } - public Integer getExperience() - { - return exp; - } + public Integer getExperience() { + return exp; + } - public TradeType getType() - { - if (getExperience() != null) - { - return TradeType.EXP; - } + public TradeType getType() { + if (getExperience() != null) { + return TradeType.EXP; + } - if (getItemStack() != null) - { - return TradeType.ITEM; - } + if (getItemStack() != null) { + return TradeType.ITEM; + } - return TradeType.MONEY; - } + return TradeType.MONEY; + } - public BigDecimal getCommandCost(final IUser user) - { - BigDecimal cost = BigDecimal.ZERO; - if (command != null && !command.isEmpty()) - { - cost = ess.getSettings().getCommandCost(command.charAt(0) == '/' ? command.substring(1) : command); - if (cost.signum() == 0 && fallbackTrade != null) - { - cost = fallbackTrade.getCommandCost(user); - } + public BigDecimal getCommandCost(final IUser user) { + BigDecimal cost = BigDecimal.ZERO; + if (command != null && !command.isEmpty()) { + cost = ess.getSettings().getCommandCost(command.charAt(0) == '/' ? command.substring(1) : command); + if (cost.signum() == 0 && fallbackTrade != null) { + cost = fallbackTrade.getCommandCost(user); + } - if (ess.getSettings().isDebug()) - { - ess.getLogger().log(Level.INFO, "calculated command (" + command + ") cost for " + user.getName() + " as " + cost); - } - } - if (cost.signum() != 0 && (user.isAuthorized("essentials.nocommandcost.all") - || user.isAuthorized("essentials.nocommandcost." + command))) - { - return BigDecimal.ZERO; - } - return cost; - } - private static FileWriter fw = null; + if (ess.getSettings().isDebug()) { + ess.getLogger().log(Level.INFO, "calculated command (" + command + ") cost for " + user.getName() + " as " + cost); + } + } + if (cost.signum() != 0 && (user.isAuthorized("essentials.nocommandcost.all") || user.isAuthorized("essentials.nocommandcost." + command))) { + return BigDecimal.ZERO; + } + return cost; + } - public static void log(String type, String subtype, String event, String sender, Trade charge, String receiver, Trade pay, Location loc, IEssentials ess) - { - //isEcoLogUpdateEnabled() - This refers to log entries with no location, ie API updates #EasterEgg - //isEcoLogEnabled() - This refers to log entries with with location, ie /pay /sell and eco signs. + private static FileWriter fw = null; - if ((loc == null && !ess.getSettings().isEcoLogUpdateEnabled()) - || (loc != null && !ess.getSettings().isEcoLogEnabled())) - { - return; - } - if (fw == null) - { - try - { - fw = new FileWriter(new File(ess.getDataFolder(), "trade.log"), true); - } - catch (IOException ex) - { - Logger.getLogger("Essentials").log(Level.SEVERE, null, ex); - } - } - StringBuilder sb = new StringBuilder(); - sb.append(type).append(",").append(subtype).append(",").append(event).append(",\""); - sb.append(DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(new Date())); - sb.append("\",\""); - if (sender != null) - { - sb.append(sender); - } - sb.append("\","); - if (charge == null) - { - sb.append("\"\",\"\",\"\""); - } - else - { - if (charge.getItemStack() != null) - { - sb.append(charge.getItemStack().getAmount()).append(","); - sb.append(charge.getItemStack().getType().toString()).append(","); - sb.append(charge.getItemStack().getDurability()); - } - if (charge.getMoney() != null) - { - sb.append(charge.getMoney()).append(","); - sb.append("money").append(","); - sb.append(ess.getSettings().getCurrencySymbol()); - } - if (charge.getExperience() != null) - { - sb.append(charge.getExperience()).append(","); - sb.append("exp").append(","); - sb.append("\"\""); - } - } - sb.append(",\""); - if (receiver != null) - { - sb.append(receiver); - } - sb.append("\","); - if (pay == null) - { - sb.append("\"\",\"\",\"\""); - } - else - { - if (pay.getItemStack() != null) - { - sb.append(pay.getItemStack().getAmount()).append(","); - sb.append(pay.getItemStack().getType().toString()).append(","); - sb.append(pay.getItemStack().getDurability()); - } - if (pay.getMoney() != null) - { - sb.append(pay.getMoney()).append(","); - sb.append("money").append(","); - sb.append(ess.getSettings().getCurrencySymbol()); - } - if (pay.getExperience() != null) - { - sb.append(pay.getExperience()).append(","); - sb.append("exp").append(","); - sb.append("\"\""); - } - } - if (loc == null) - { - sb.append(",\"\",\"\",\"\",\"\""); - } - else - { - sb.append(",\""); - sb.append(loc.getWorld().getName()).append("\","); - sb.append(loc.getBlockX()).append(","); - sb.append(loc.getBlockY()).append(","); - sb.append(loc.getBlockZ()).append(","); - } - sb.append("\n"); - try - { - fw.write(sb.toString()); - fw.flush(); - } - catch (IOException ex) - { - Logger.getLogger("Essentials").log(Level.SEVERE, null, ex); - } - } + public static void log(String type, String subtype, String event, String sender, Trade charge, String receiver, Trade pay, Location loc, IEssentials ess) { + //isEcoLogUpdateEnabled() - This refers to log entries with no location, ie API updates #EasterEgg + //isEcoLogEnabled() - This refers to log entries with with location, ie /pay /sell and eco signs. - public static void closeLog() - { - if (fw != null) - { - try - { - fw.close(); - } - catch (IOException ex) - { - Logger.getLogger("Essentials").log(Level.SEVERE, null, ex); - } - fw = null; - } - } + if ((loc == null && !ess.getSettings().isEcoLogUpdateEnabled()) || (loc != null && !ess.getSettings().isEcoLogEnabled())) { + return; + } + if (fw == null) { + try { + fw = new FileWriter(new File(ess.getDataFolder(), "trade.log"), true); + } catch (IOException ex) { + Logger.getLogger("Essentials").log(Level.SEVERE, null, ex); + } + } + StringBuilder sb = new StringBuilder(); + sb.append(type).append(",").append(subtype).append(",").append(event).append(",\""); + sb.append(DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(new Date())); + sb.append("\",\""); + if (sender != null) { + sb.append(sender); + } + sb.append("\","); + if (charge == null) { + sb.append("\"\",\"\",\"\""); + } else { + if (charge.getItemStack() != null) { + sb.append(charge.getItemStack().getAmount()).append(","); + sb.append(charge.getItemStack().getType().toString()).append(","); + sb.append(charge.getItemStack().getDurability()); + } + if (charge.getMoney() != null) { + sb.append(charge.getMoney()).append(","); + sb.append("money").append(","); + sb.append(ess.getSettings().getCurrencySymbol()); + } + if (charge.getExperience() != null) { + sb.append(charge.getExperience()).append(","); + sb.append("exp").append(","); + sb.append("\"\""); + } + } + sb.append(",\""); + if (receiver != null) { + sb.append(receiver); + } + sb.append("\","); + if (pay == null) { + sb.append("\"\",\"\",\"\""); + } else { + if (pay.getItemStack() != null) { + sb.append(pay.getItemStack().getAmount()).append(","); + sb.append(pay.getItemStack().getType().toString()).append(","); + sb.append(pay.getItemStack().getDurability()); + } + if (pay.getMoney() != null) { + sb.append(pay.getMoney()).append(","); + sb.append("money").append(","); + sb.append(ess.getSettings().getCurrencySymbol()); + } + if (pay.getExperience() != null) { + sb.append(pay.getExperience()).append(","); + sb.append("exp").append(","); + sb.append("\"\""); + } + } + if (loc == null) { + sb.append(",\"\",\"\",\"\",\"\""); + } else { + sb.append(",\""); + sb.append(loc.getWorld().getName()).append("\","); + sb.append(loc.getBlockX()).append(","); + sb.append(loc.getBlockY()).append(","); + sb.append(loc.getBlockZ()).append(","); + } + sb.append("\n"); + try { + fw.write(sb.toString()); + fw.flush(); + } catch (IOException ex) { + Logger.getLogger("Essentials").log(Level.SEVERE, null, ex); + } + } + + public static void closeLog() { + if (fw != null) { + try { + fw.close(); + } catch (IOException ex) { + Logger.getLogger("Essentials").log(Level.SEVERE, null, ex); + } + fw = null; + } + } } diff --git a/Essentials/src/com/earth2me/essentials/UUIDMap.java b/Essentials/src/com/earth2me/essentials/UUIDMap.java index e77a9149d..188f0ab7c 100644 --- a/Essentials/src/com/earth2me/essentials/UUIDMap.java +++ b/Essentials/src/com/earth2me/essentials/UUIDMap.java @@ -1,212 +1,158 @@ package com.earth2me.essentials; import com.google.common.io.Files; -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; +import org.bukkit.Bukkit; + +import java.io.*; import java.util.ArrayList; import java.util.Map; import java.util.UUID; -import java.util.concurrent.ConcurrentSkipListMap; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; +import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.regex.Pattern; -import org.bukkit.Bukkit; -public class UUIDMap -{ - private final transient net.ess3.api.IEssentials ess; - private File userList; - private final transient Pattern splitPattern = Pattern.compile(","); - private static final ExecutorService EXECUTOR_SERVICE = Executors.newSingleThreadExecutor(); - private final AtomicInteger pendingDiskWrites = new AtomicInteger(0); +public class UUIDMap { + private final transient net.ess3.api.IEssentials ess; + private File userList; + private final transient Pattern splitPattern = Pattern.compile(","); + private static final ExecutorService EXECUTOR_SERVICE = Executors.newSingleThreadExecutor(); + private final AtomicInteger pendingDiskWrites = new AtomicInteger(0); - public UUIDMap(final net.ess3.api.IEssentials ess) - { - this.ess = ess; - userList = new File(ess.getDataFolder(), "usermap.csv"); + public UUIDMap(final net.ess3.api.IEssentials ess) { + this.ess = ess; + userList = new File(ess.getDataFolder(), "usermap.csv"); - } + } - public void loadAllUsers(final ConcurrentSkipListMap names, final ConcurrentSkipListMap> history) - { - try - { - if (!userList.exists()) - { - userList.createNewFile(); - } + public void loadAllUsers(final ConcurrentSkipListMap names, final ConcurrentSkipListMap> history) { + try { + if (!userList.exists()) { + userList.createNewFile(); + } - synchronized (pendingDiskWrites) - { - if (ess.getSettings().isDebug()) - { - ess.getLogger().log(Level.INFO, "Reading usermap from disk"); - } + synchronized (pendingDiskWrites) { + if (ess.getSettings().isDebug()) { + ess.getLogger().log(Level.INFO, "Reading usermap from disk"); + } - names.clear(); - history.clear(); + names.clear(); + history.clear(); - final BufferedReader reader = new BufferedReader(new FileReader(userList)); - try - { - while (true) - { - final String line = reader.readLine(); - if (line == null) - { - break; - } - else - { - final String[] values = splitPattern.split(line); - if (values.length == 2) - { - final String name = values[0]; - final UUID uuid = UUID.fromString(values[1]); - names.put(name, uuid); - if (!history.containsKey(uuid)) - { - final ArrayList list = new ArrayList(); - list.add(name); - history.put(uuid, list); - } - else - { - final ArrayList list = history.get(uuid); - if (!list.contains(name)) - { - list.add(name); - } - } - } - } - } - } - finally - { - reader.close(); - } - } - } - catch (IOException ex) - { - Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); - } - } + final BufferedReader reader = new BufferedReader(new FileReader(userList)); + try { + while (true) { + final String line = reader.readLine(); + if (line == null) { + break; + } else { + final String[] values = splitPattern.split(line); + if (values.length == 2) { + final String name = values[0]; + final UUID uuid = UUID.fromString(values[1]); + names.put(name, uuid); + if (!history.containsKey(uuid)) { + final ArrayList list = new ArrayList(); + list.add(name); + history.put(uuid, list); + } else { + final ArrayList list = history.get(uuid); + if (!list.contains(name)) { + list.add(name); + } + } + } + } + } + } finally { + reader.close(); + } + } + } catch (IOException ex) { + Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex); + } + } - public void writeUUIDMap() - { - _writeUUIDMap(); - } + public void writeUUIDMap() { + _writeUUIDMap(); + } - public void forceWriteUUIDMap() - { - if (ess.getSettings().isDebug()) - { - ess.getLogger().log(Level.INFO, "Forcing usermap write to disk"); - } - try - { - Future future = _writeUUIDMap();; - if (future != null) - { - future.get(); - } - } - catch (InterruptedException ex) - { - ess.getLogger().log(Level.SEVERE, ex.getMessage(), ex); - } - catch (ExecutionException ex) - { - ess.getLogger().log(Level.SEVERE, ex.getMessage(), ex); - } - } + public void forceWriteUUIDMap() { + if (ess.getSettings().isDebug()) { + ess.getLogger().log(Level.INFO, "Forcing usermap write to disk"); + } + try { + Future future = _writeUUIDMap(); + ; + if (future != null) { + future.get(); + } + } catch (InterruptedException ex) { + ess.getLogger().log(Level.SEVERE, ex.getMessage(), ex); + } catch (ExecutionException ex) { + ess.getLogger().log(Level.SEVERE, ex.getMessage(), ex); + } + } - public Future _writeUUIDMap() - { - final ConcurrentSkipListMap names = ess.getUserMap().getNames(); - if (names.size() < 1) - { - return null; - } - pendingDiskWrites.incrementAndGet(); - Future future = EXECUTOR_SERVICE.submit(new WriteRunner(ess.getDataFolder(), userList, names, pendingDiskWrites)); - return future; - } + public Future _writeUUIDMap() { + final ConcurrentSkipListMap names = ess.getUserMap().getNames(); + if (names.size() < 1) { + return null; + } + pendingDiskWrites.incrementAndGet(); + Future future = EXECUTOR_SERVICE.submit(new WriteRunner(ess.getDataFolder(), userList, names, pendingDiskWrites)); + return future; + } - private static class WriteRunner implements Runnable - { - private final File location; - private final File endFile; - private final ConcurrentSkipListMap names; - private final AtomicInteger pendingDiskWrites; + private static class WriteRunner implements Runnable { + private final File location; + private final File endFile; + private final ConcurrentSkipListMap names; + private final AtomicInteger pendingDiskWrites; - private WriteRunner(final File location, final File endFile, final ConcurrentSkipListMap names, final AtomicInteger pendingDiskWrites) - { - this.location = location; - this.endFile = endFile; - this.names = names; - this.pendingDiskWrites = pendingDiskWrites; - } + private WriteRunner(final File location, final File endFile, final ConcurrentSkipListMap names, final AtomicInteger pendingDiskWrites) { + this.location = location; + this.endFile = endFile; + this.names = names; + this.pendingDiskWrites = pendingDiskWrites; + } - @Override - public void run() - { - synchronized (pendingDiskWrites) - { - if (pendingDiskWrites.get() > 1) - { - pendingDiskWrites.decrementAndGet(); - return; - } + @Override + public void run() { + synchronized (pendingDiskWrites) { + if (pendingDiskWrites.get() > 1) { + pendingDiskWrites.decrementAndGet(); + return; + } - File configFile = null; + File configFile = null; - try - { - configFile = File.createTempFile("usermap", ".tmp.csv", location); + try { + configFile = File.createTempFile("usermap", ".tmp.csv", location); - final BufferedWriter bWriter = new BufferedWriter(new FileWriter(configFile)); - for (Map.Entry entry : names.entrySet()) - { - bWriter.write(entry.getKey() + "," + entry.getValue().toString()); - bWriter.newLine(); - } + final BufferedWriter bWriter = new BufferedWriter(new FileWriter(configFile)); + for (Map.Entry entry : names.entrySet()) { + bWriter.write(entry.getKey() + "," + entry.getValue().toString()); + bWriter.newLine(); + } - bWriter.close(); - Files.move(configFile, endFile); - } - catch (IOException ex) - { - try - { - if (configFile != null && configFile.exists()) - { - Files.move(configFile, new File(endFile.getParentFile(), "usermap.bak.csv")); - } - } - catch (Exception ex2) - { - Bukkit.getLogger().log(Level.SEVERE, ex2.getMessage(), ex2); - } - Bukkit.getLogger().log(Level.WARNING, ex.getMessage(), ex); - } - finally - { - pendingDiskWrites.decrementAndGet(); - } - } - } - } + bWriter.close(); + Files.move(configFile, endFile); + } catch (IOException ex) { + try { + if (configFile != null && configFile.exists()) { + Files.move(configFile, new File(endFile.getParentFile(), "usermap.bak.csv")); + } + } catch (Exception ex2) { + Bukkit.getLogger().log(Level.SEVERE, ex2.getMessage(), ex2); + } + Bukkit.getLogger().log(Level.WARNING, ex.getMessage(), ex); + } finally { + pendingDiskWrites.decrementAndGet(); + } + } + } + } } \ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/User.java b/Essentials/src/com/earth2me/essentials/User.java index 41a32e529..a12cd2df4 100644 --- a/Essentials/src/com/earth2me/essentials/User.java +++ b/Essentials/src/com/earth2me/essentials/User.java @@ -1,18 +1,11 @@ package com.earth2me.essentials; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.commands.IEssentialsCommand; import com.earth2me.essentials.register.payment.Method; import com.earth2me.essentials.register.payment.Methods; import com.earth2me.essentials.utils.DateUtil; import com.earth2me.essentials.utils.FormatUtil; import com.earth2me.essentials.utils.NumberUtil; -import java.math.BigDecimal; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.UUID; -import java.util.logging.Level; -import java.util.logging.Logger; import net.ess3.api.IEssentials; import net.ess3.api.MaxMoneyException; import net.ess3.api.events.AfkStatusChangeEvent; @@ -24,875 +17,694 @@ import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; - -public class User extends UserData implements Comparable, IReplyTo, net.ess3.api.IUser -{ - private static final Logger logger = Logger.getLogger("Essentials"); - private CommandSource replyTo = null; - private transient UUID teleportRequester; - private transient boolean teleportRequestHere; - private transient Location teleportLocation; - private transient boolean vanished; - private transient final Teleport teleport; - private transient long teleportRequestTime; - private transient long lastOnlineActivity; - private transient long lastThrottledAction; - private transient long lastActivity = System.currentTimeMillis(); - private boolean hidden = false; - private boolean rightClickJump = false; - private transient Location afkPosition = null; - private boolean invSee = false; - private boolean recipeSee = false; - private boolean enderSee = false; - private transient long teleportInvulnerabilityTimestamp = 0; - - public User(final Player base, final IEssentials ess) - { - super(base, ess); - teleport = new Teleport(this, ess); - if (isAfk()) - { - afkPosition = this.getLocation(); - } - if (this.getBase().isOnline()) - { - lastOnlineActivity = System.currentTimeMillis(); - } - } - - User update(final Player base) - { - setBase(base); - return this; - } - - @Override - public boolean isAuthorized(final IEssentialsCommand cmd) - { - return isAuthorized(cmd, "essentials."); - } - - @Override - public boolean isAuthorized(final IEssentialsCommand cmd, final String permissionPrefix) - { - return isAuthorized(permissionPrefix + (cmd.getName().equals("r") ? "msg" : cmd.getName())); - } - - @Override - public boolean isAuthorized(final String node) - { - final boolean result = isAuthorizedCheck(node); - if (ess.getSettings().isDebug()) - { - ess.getLogger().log(Level.INFO, "checking if " + base.getName() + " has " + node + " - " + result); - } - return result; - } - - private boolean isAuthorizedCheck(final String node) - { - - if (base instanceof OfflinePlayer) - { - return false; - } - - try - { - return ess.getPermissionsHandler().hasPermission(base, node); - } - catch (Exception ex) - { - if (ess.getSettings().isDebug()) - { - ess.getLogger().log(Level.SEVERE, "Permission System Error: " + ess.getPermissionsHandler().getName() + " returned: " + ex.getMessage(), ex); - } - else - { - ess.getLogger().log(Level.SEVERE, "Permission System Error: " + ess.getPermissionsHandler().getName() + " returned: " + ex.getMessage()); - } - - return false; - } - } - - @Override - public void healCooldown() throws Exception - { - final Calendar now = new GregorianCalendar(); - if (getLastHealTimestamp() > 0) - { - final double cooldown = ess.getSettings().getHealCooldown(); - final Calendar cooldownTime = new GregorianCalendar(); - cooldownTime.setTimeInMillis(getLastHealTimestamp()); - cooldownTime.add(Calendar.SECOND, (int)cooldown); - cooldownTime.add(Calendar.MILLISECOND, (int)((cooldown * 1000.0) % 1000.0)); - if (cooldownTime.after(now) && !isAuthorized("essentials.heal.cooldown.bypass")) - { - throw new Exception(tl("timeBeforeHeal", DateUtil.formatDateDiff(cooldownTime.getTimeInMillis()))); - } - } - setLastHealTimestamp(now.getTimeInMillis()); - } - - @Override - public void giveMoney(final BigDecimal value) throws MaxMoneyException - { - giveMoney(value, (CommandSource)null); - } - - @Override - public void giveMoney(final BigDecimal value, final CommandSource initiator) throws MaxMoneyException - { - if (value.signum() == 0) - { - return; - } - setMoney(getMoney().add(value)); - sendMessage(tl("addedToAccount", NumberUtil.displayCurrency(value, ess))); - if (initiator != null) - { - initiator.sendMessage(tl("addedToOthersAccount", NumberUtil.displayCurrency(value, ess), this.getDisplayName(), NumberUtil.displayCurrency(getMoney(), ess))); - } - } - - @Override - public void payUser(final User reciever, final BigDecimal value) throws ChargeException, MaxMoneyException - { - if (value.signum() == 0) - { - return; - } - if (canAfford(value)) - { - setMoney(getMoney().subtract(value)); - reciever.setMoney(reciever.getMoney().add(value)); - sendMessage(tl("moneySentTo", NumberUtil.displayCurrency(value, ess), reciever.getDisplayName())); - reciever.sendMessage(tl("moneyRecievedFrom", NumberUtil.displayCurrency(value, ess), getDisplayName())); - } - else - { - throw new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(value, ess))); - } - } - - @Override - public void takeMoney(final BigDecimal value) - { - takeMoney(value, (CommandSource)null); - } - - @Override - public void takeMoney(final BigDecimal value, final CommandSource initiator) - { - if (value.signum() == 0) - { - return; - } - try - { - setMoney(getMoney().subtract(value)); - } - catch (MaxMoneyException ex) - { - ess.getLogger().log(Level.WARNING, "Invalid call to takeMoney, total balance can't be more than the max-money limit.", ex); - } - sendMessage(tl("takenFromAccount", NumberUtil.displayCurrency(value, ess))); - if (initiator != null) - { - initiator.sendMessage(tl("takenFromOthersAccount", NumberUtil.displayCurrency(value, ess), this.getDisplayName(), NumberUtil.displayCurrency(getMoney(), ess))); - } - } - - @Override - public boolean canAfford(final BigDecimal cost) - { - return canAfford(cost, true); - } - - public boolean canAfford(final BigDecimal cost, final boolean permcheck) - { - if (cost.signum() <= 0) - { - return true; - } - final BigDecimal remainingBalance = getMoney().subtract(cost); - if (!permcheck || isAuthorized("essentials.eco.loan")) - { - return (remainingBalance.compareTo(ess.getSettings().getMinMoney()) >= 0); - } - return (remainingBalance.signum() >= 0); - } - - public void dispose() - { - ess.runTaskAsynchronously(new Runnable() - { - @Override - public void run() - { - _dispose(); - } - }); - } - - private void _dispose() - { - if (!base.isOnline()) - { - this.base = new OfflinePlayer(getConfigUUID(), ess.getServer()); - } - cleanup(); - } - - @Override - public Boolean canSpawnItem(final int itemId) - { - return !ess.getSettings().itemSpawnBlacklist().contains(itemId); - } - - @Override - public void setLastLocation() - { - setLastLocation(this.getLocation()); - } - - @Override - public void setLogoutLocation() - { - setLogoutLocation(this.getLocation()); - } - - @Override - public void requestTeleport(final User player, final boolean here) - { - teleportRequestTime = System.currentTimeMillis(); - teleportRequester = player == null ? null : player.getBase().getUniqueId(); - teleportRequestHere = here; - if (player == null) - { - teleportLocation = null; - } - else - { - teleportLocation = here ? player.getLocation() : this.getLocation(); - } - } - - public UUID getTeleportRequest() - { - return teleportRequester; - } - - public boolean isTpRequestHere() - { - return teleportRequestHere; - } - - public Location getTpRequestLocation() - { - return teleportLocation; - } - - public String getNick(final boolean longnick) - { - final StringBuilder prefix = new StringBuilder(); - String nickname; - String suffix = ""; - final String nick = getNickname(); - if (ess.getSettings().isCommandDisabled("nick") || nick == null || nick.isEmpty() || nick.equals(getName())) - { - nickname = getName(); - } - else if (nick.equalsIgnoreCase(getName())) { - nickname = nick; - } - else - { - nickname = ess.getSettings().getNicknamePrefix() + nick; - suffix = "§r"; - } - - if (this.getBase().isOp()) - { - try - { - final ChatColor opPrefix = ess.getSettings().getOperatorColor(); - if (opPrefix != null && opPrefix.toString().length() > 0) - { - prefix.insert(0, opPrefix.toString()); - suffix = "§r"; - } - } - catch (Exception e) - { - } - } - - if (ess.getSettings().addPrefixSuffix()) - { - //These two extra toggles are not documented, because they are mostly redundant #EasterEgg - if (!ess.getSettings().disablePrefix()) - { - final String ptext = ess.getPermissionsHandler().getPrefix(base).replace('&', '§'); - prefix.insert(0, ptext); - suffix = "§r"; - } - if (!ess.getSettings().disableSuffix()) - { - final String stext = ess.getPermissionsHandler().getSuffix(base).replace('&', '§'); - suffix = stext + "§r"; - suffix = suffix.replace("§f§f", "§f").replace("§f§r", "§r").replace("§r§r", "§r"); - } - } - final String strPrefix = prefix.toString(); - String output = strPrefix + nickname + suffix; - if (!longnick && output.length() > 16) - { - output = strPrefix + nickname; - } - if (!longnick && output.length() > 16) - { - output = FormatUtil.lastCode(strPrefix) + nickname; - } - if (!longnick && output.length() > 16) - { - output = FormatUtil.lastCode(strPrefix) + nickname.substring(0, 14); - } - if (output.charAt(output.length() - 1) == '§') - { - output = output.substring(0, output.length() - 1); - } - return output; - } - - public void setDisplayNick() - { - if (base.isOnline() && ess.getSettings().changeDisplayName()) - { - this.getBase().setDisplayName(getNick(true)); - if (ess.getSettings().changePlayerListName()) - { - String name = getNick(false); - try - { - this.getBase().setPlayerListName(name); - } - catch (IllegalArgumentException e) - { - if (ess.getSettings().isDebug()) - { - logger.log(Level.INFO, "Playerlist for " + name + " was not updated. Name clashed with another online player."); - } - } - } - } - } - - public String getDisplayName() - { - return super.getBase().getDisplayName() == null ? super.getBase().getName() : super.getBase().getDisplayName(); - } - - @Override - public Teleport getTeleport() - { - return teleport; - } - - public long getLastOnlineActivity() - { - return lastOnlineActivity; - } - - public void setLastOnlineActivity(final long timestamp) - { - lastOnlineActivity = timestamp; - } - - @Override - public BigDecimal getMoney() - { - final long start = System.nanoTime(); - final BigDecimal value = _getMoney(); - final long elapsed = System.nanoTime() - start; - if (elapsed > ess.getSettings().getEconomyLagWarning()) - { - ess.getLogger().log(Level.INFO, "Lag Notice - Slow Economy Response - Request took over {0}ms!", elapsed / 1000000.0); - } - return value; - } - - private BigDecimal _getMoney() - { - if (ess.getSettings().isEcoDisabled()) - { - if (ess.getSettings().isDebug()) - { - ess.getLogger().info("Internal economy functions disabled, aborting balance check."); - } - return BigDecimal.ZERO; - } - if (Methods.hasMethod()) - { - try - { - final Method method = Methods.getMethod(); - if (!method.hasAccount(this.getName())) - { - throw new Exception(); - } - final Method.MethodAccount account = Methods.getMethod().getAccount(this.getName()); - return BigDecimal.valueOf(account.balance()); - } - catch (Exception ex) - { - } - } - return super.getMoney(); - } - - @Override - public void setMoney(final BigDecimal value) throws MaxMoneyException - { - if (ess.getSettings().isEcoDisabled()) - { - if (ess.getSettings().isDebug()) - { - ess.getLogger().info("Internal economy functions disabled, aborting balance change."); - } - return; - } - final BigDecimal oldBalance = _getMoney(); - if (Methods.hasMethod()) - { - try - { - final Method method = Methods.getMethod(); - if (!method.hasAccount(this.getName())) - { - throw new Exception(); - } - final Method.MethodAccount account = Methods.getMethod().getAccount(this.getName()); - account.set(value.doubleValue()); - } - catch (Exception ex) - { - } - } - super.setMoney(value, true); - ess.getServer().getPluginManager().callEvent(new UserBalanceUpdateEvent(this.getBase(), oldBalance, value)); - Trade.log("Update", "Set", "API", getName(), new Trade(value, ess), null, null, null, ess); - } - - public void updateMoneyCache(final BigDecimal value) - { - if (ess.getSettings().isEcoDisabled()) - { - return; - } - if (Methods.hasMethod() && super.getMoney() != value) - { - try - { - super.setMoney(value, false); - } - catch (MaxMoneyException ex) - { - // We don't want to throw any errors here, just updating a cache - } - } - } - - @Override - public void setAfk(final boolean set) - { - final AfkStatusChangeEvent afkEvent = new AfkStatusChangeEvent(this, set); - ess.getServer().getPluginManager().callEvent(afkEvent); - if (afkEvent.isCancelled()) - { - return; - } - - this.getBase().setSleepingIgnored(this.isAuthorized("essentials.sleepingignored") ? true : set); - if (set && !isAfk()) - { - afkPosition = this.getLocation(); - } - else if (!set && isAfk()) - { - afkPosition = null; - } - _setAfk(set); - } - - public boolean toggleAfk() - { - setAfk(!isAfk()); - return isAfk(); - } - - @Override - public boolean isHidden() - { - return hidden; - } - - public boolean isHidden(final Player player) - { - return hidden || !player.canSee(getBase()); - } - - @Override - public void setHidden(final boolean hidden) - { - this.hidden = hidden; - if (hidden == true) - { - setLastLogout(getLastOnlineActivity()); - } - } - - //Returns true if status expired during this check - public boolean checkJailTimeout(final long currentTime) - { - if (getJailTimeout() > 0 && getJailTimeout() < currentTime && isJailed()) - { - setJailTimeout(0); - setJailed(false); - sendMessage(tl("haveBeenReleased")); - setJail(null); - try - { - getTeleport().back(); - } - catch (Exception ex) - { - try - { - getTeleport().respawn(null, TeleportCause.PLUGIN); - } - catch (Exception ex1) - { - } - } - return true; - } - return false; - } - - //Returns true if status expired during this check - public boolean checkMuteTimeout(final long currentTime) - { - if (getMuteTimeout() > 0 && getMuteTimeout() < currentTime && isMuted()) - { - setMuteTimeout(0); - sendMessage(tl("canTalkAgain")); - setMuted(false); - return true; - } - return false; - } - - public void updateActivity(final boolean broadcast) - { - if (isAfk() && ess.getSettings().cancelAfkOnInteract()) - { - setAfk(false); - if (broadcast && !isHidden()) - { - setDisplayNick(); - final String msg = tl("userIsNotAway", getDisplayName()); - if (!msg.isEmpty()) - { - ess.broadcastMessage(this, msg); - } - } - } - lastActivity = System.currentTimeMillis(); - } - - public void checkActivity() - { - final long autoafkkick = ess.getSettings().getAutoAfkKick(); - if (autoafkkick > 0 && lastActivity > 0 && (lastActivity + (autoafkkick * 1000)) < System.currentTimeMillis() - && !isHidden() && !isAuthorized("essentials.kick.exempt") && !isAuthorized("essentials.afk.kickexempt")) - { - final String kickReason = tl("autoAfkKickReason", autoafkkick / 60.0); - lastActivity = 0; - this.getBase().kickPlayer(kickReason); - - - for (User user : ess.getOnlineUsers()) - { - if (user.isAuthorized("essentials.kick.notify")) - { - user.sendMessage(tl("playerKicked", Console.NAME, getName(), kickReason)); - } - } - } - final long autoafk = ess.getSettings().getAutoAfk(); - if (!isAfk() && autoafk > 0 && lastActivity + autoafk * 1000 < System.currentTimeMillis() && isAuthorized("essentials.afk.auto")) - { - setAfk(true); - if (!isHidden()) - { - setDisplayNick(); - final String msg = tl("userIsAway", getDisplayName()); - if (!msg.isEmpty()) - { - ess.broadcastMessage(this, msg); - } - } - } - } - - public Location getAfkPosition() - { - return afkPosition; - } - - @Override - public boolean isGodModeEnabled() - { - return (super.isGodModeEnabled() && !ess.getSettings().getNoGodWorlds().contains(this.getLocation().getWorld().getName())) - || (isAfk() && ess.getSettings().getFreezeAfkPlayers()); - } - - public boolean isGodModeEnabledRaw() - { - return super.isGodModeEnabled(); - } - - @Override - public String getGroup() - { - final String result = ess.getPermissionsHandler().getGroup(base); - if (ess.getSettings().isDebug()) - { - ess.getLogger().log(Level.INFO, "looking up groupname of " + base.getName() + " - " + result); - } - return result; - } - - @Override - public boolean inGroup(final String group) - { - final boolean result = ess.getPermissionsHandler().inGroup(base, group); - if (ess.getSettings().isDebug()) - { - ess.getLogger().log(Level.INFO, "checking if " + base.getName() + " is in group " + group + " - " + result); - } - return result; - } - - @Override - public boolean canBuild() - { - if (this.getBase().isOp()) - { - return true; - } - return ess.getPermissionsHandler().canBuild(base, getGroup()); - } - - public long getTeleportRequestTime() - { - return teleportRequestTime; - } - - public boolean isInvSee() - { - return invSee; - } - - public void setInvSee(final boolean set) - { - invSee = set; - } - - public boolean isEnderSee() - { - return enderSee; - } - - public void setEnderSee(final boolean set) - { - enderSee = set; - } - - @Override - public void enableInvulnerabilityAfterTeleport() - { - final long time = ess.getSettings().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(); - } - - public boolean canInteractVanished() - { - return isAuthorized("essentials.vanish.interact"); - } - - @Override - public boolean isVanished() - { - return vanished; - } - - @Override - public void setVanished(final boolean set) - { - vanished = set; - if (set) - { - for (User user : ess.getOnlineUsers()) - { - if (!user.isAuthorized("essentials.vanish.see")) - { - user.getBase().hidePlayer(getBase()); - } - } - setHidden(true); - ess.getVanishedPlayers().add(getName()); - if (isAuthorized("essentials.vanish.effect")) - { - this.getBase().addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, Integer.MAX_VALUE, 1, false)); - } - } - else - { - for (Player p : ess.getOnlinePlayers()) - { - p.showPlayer(getBase()); - } - setHidden(false); - ess.getVanishedPlayers().remove(getName()); - if (isAuthorized("essentials.vanish.effect")) - { - this.getBase().removePotionEffect(PotionEffectType.INVISIBILITY); - } - } - } - - public boolean checkSignThrottle() - { - if (isSignThrottled()) - { - return true; - } - updateThrottle(); - return false; - } - - public boolean isSignThrottled() - { - final long minTime = lastThrottledAction + (1000 / ess.getSettings().getSignUsePerSecond()); - return (System.currentTimeMillis() < minTime); - } - - public void updateThrottle() - { - lastThrottledAction = System.currentTimeMillis(); - } - - public boolean isFlyClickJump() - { - return rightClickJump; - } - - public void setRightClickJump(boolean rightClickJump) - { - this.rightClickJump = rightClickJump; - } - - @Override - public boolean isIgnoreExempt() - { - return this.isAuthorized("essentials.chat.ignoreexempt"); - } - - public boolean isRecipeSee() - { - return recipeSee; - } - - public void setRecipeSee(boolean recipeSee) - { - this.recipeSee = recipeSee; - } - - @Override - public void sendMessage(String message) - { - if (!message.isEmpty()) - { - base.sendMessage(message); - } - } - - @Override - public void setReplyTo(final CommandSource user) - { - replyTo = user; - } - - @Override - public CommandSource getReplyTo() - { - return replyTo; - } - - @Override - public int compareTo(final User other) - { - return FormatUtil.stripFormat(getDisplayName()).compareToIgnoreCase(FormatUtil.stripFormat(other.getDisplayName())); - } - - @Override - public boolean equals(final Object object) - { - if (!(object instanceof User)) - { - return false; - } - return this.getName().equalsIgnoreCase(((User)object).getName()); - - } - - @Override - public int hashCode() - { - return this.getName().hashCode(); - } - - @Override - public CommandSource getSource() - { - return new CommandSource(getBase()); - } - - @Override - public String getName() - { - return this.getBase().getName(); - } +import java.math.BigDecimal; +import java.util.Calendar; +import java.util.GregorianCalendar; +import java.util.UUID; +import java.util.logging.Level; +import java.util.logging.Logger; + +import static com.earth2me.essentials.I18n.tl; + + +public class User extends UserData implements Comparable, IReplyTo, net.ess3.api.IUser { + private static final Logger logger = Logger.getLogger("Essentials"); + private CommandSource replyTo = null; + private transient UUID teleportRequester; + private transient boolean teleportRequestHere; + private transient Location teleportLocation; + private transient boolean vanished; + private transient final Teleport teleport; + private transient long teleportRequestTime; + private transient long lastOnlineActivity; + private transient long lastThrottledAction; + private transient long lastActivity = System.currentTimeMillis(); + private boolean hidden = false; + private boolean rightClickJump = false; + private transient Location afkPosition = null; + private boolean invSee = false; + private boolean recipeSee = false; + private boolean enderSee = false; + private transient long teleportInvulnerabilityTimestamp = 0; + + public User(final Player base, final IEssentials ess) { + super(base, ess); + teleport = new Teleport(this, ess); + if (isAfk()) { + afkPosition = this.getLocation(); + } + if (this.getBase().isOnline()) { + lastOnlineActivity = System.currentTimeMillis(); + } + } + + User update(final Player base) { + setBase(base); + return this; + } + + @Override + public boolean isAuthorized(final IEssentialsCommand cmd) { + return isAuthorized(cmd, "essentials."); + } + + @Override + public boolean isAuthorized(final IEssentialsCommand cmd, final String permissionPrefix) { + return isAuthorized(permissionPrefix + (cmd.getName().equals("r") ? "msg" : cmd.getName())); + } + + @Override + public boolean isAuthorized(final String node) { + final boolean result = isAuthorizedCheck(node); + if (ess.getSettings().isDebug()) { + ess.getLogger().log(Level.INFO, "checking if " + base.getName() + " has " + node + " - " + result); + } + return result; + } + + private boolean isAuthorizedCheck(final String node) { + + if (base instanceof OfflinePlayer) { + return false; + } + + try { + return ess.getPermissionsHandler().hasPermission(base, node); + } catch (Exception ex) { + if (ess.getSettings().isDebug()) { + ess.getLogger().log(Level.SEVERE, "Permission System Error: " + ess.getPermissionsHandler().getName() + " returned: " + ex.getMessage(), ex); + } else { + ess.getLogger().log(Level.SEVERE, "Permission System Error: " + ess.getPermissionsHandler().getName() + " returned: " + ex.getMessage()); + } + + return false; + } + } + + @Override + public void healCooldown() throws Exception { + final Calendar now = new GregorianCalendar(); + if (getLastHealTimestamp() > 0) { + final double cooldown = ess.getSettings().getHealCooldown(); + final Calendar cooldownTime = new GregorianCalendar(); + cooldownTime.setTimeInMillis(getLastHealTimestamp()); + cooldownTime.add(Calendar.SECOND, (int) cooldown); + cooldownTime.add(Calendar.MILLISECOND, (int) ((cooldown * 1000.0) % 1000.0)); + if (cooldownTime.after(now) && !isAuthorized("essentials.heal.cooldown.bypass")) { + throw new Exception(tl("timeBeforeHeal", DateUtil.formatDateDiff(cooldownTime.getTimeInMillis()))); + } + } + setLastHealTimestamp(now.getTimeInMillis()); + } + + @Override + public void giveMoney(final BigDecimal value) throws MaxMoneyException { + giveMoney(value, (CommandSource) null); + } + + @Override + public void giveMoney(final BigDecimal value, final CommandSource initiator) throws MaxMoneyException { + if (value.signum() == 0) { + return; + } + setMoney(getMoney().add(value)); + sendMessage(tl("addedToAccount", NumberUtil.displayCurrency(value, ess))); + if (initiator != null) { + initiator.sendMessage(tl("addedToOthersAccount", NumberUtil.displayCurrency(value, ess), this.getDisplayName(), NumberUtil.displayCurrency(getMoney(), ess))); + } + } + + @Override + public void payUser(final User reciever, final BigDecimal value) throws ChargeException, MaxMoneyException { + if (value.signum() == 0) { + return; + } + if (canAfford(value)) { + setMoney(getMoney().subtract(value)); + reciever.setMoney(reciever.getMoney().add(value)); + sendMessage(tl("moneySentTo", NumberUtil.displayCurrency(value, ess), reciever.getDisplayName())); + reciever.sendMessage(tl("moneyRecievedFrom", NumberUtil.displayCurrency(value, ess), getDisplayName())); + } else { + throw new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(value, ess))); + } + } + + @Override + public void takeMoney(final BigDecimal value) { + takeMoney(value, (CommandSource) null); + } + + @Override + public void takeMoney(final BigDecimal value, final CommandSource initiator) { + if (value.signum() == 0) { + return; + } + try { + setMoney(getMoney().subtract(value)); + } catch (MaxMoneyException ex) { + ess.getLogger().log(Level.WARNING, "Invalid call to takeMoney, total balance can't be more than the max-money limit.", ex); + } + sendMessage(tl("takenFromAccount", NumberUtil.displayCurrency(value, ess))); + if (initiator != null) { + initiator.sendMessage(tl("takenFromOthersAccount", NumberUtil.displayCurrency(value, ess), this.getDisplayName(), NumberUtil.displayCurrency(getMoney(), ess))); + } + } + + @Override + public boolean canAfford(final BigDecimal cost) { + return canAfford(cost, true); + } + + public boolean canAfford(final BigDecimal cost, final boolean permcheck) { + if (cost.signum() <= 0) { + return true; + } + final BigDecimal remainingBalance = getMoney().subtract(cost); + if (!permcheck || isAuthorized("essentials.eco.loan")) { + return (remainingBalance.compareTo(ess.getSettings().getMinMoney()) >= 0); + } + return (remainingBalance.signum() >= 0); + } + + public void dispose() { + ess.runTaskAsynchronously(new Runnable() { + @Override + public void run() { + _dispose(); + } + }); + } + + private void _dispose() { + if (!base.isOnline()) { + this.base = new OfflinePlayer(getConfigUUID(), ess.getServer()); + } + cleanup(); + } + + @Override + public Boolean canSpawnItem(final int itemId) { + return !ess.getSettings().itemSpawnBlacklist().contains(itemId); + } + + @Override + public void setLastLocation() { + setLastLocation(this.getLocation()); + } + + @Override + public void setLogoutLocation() { + setLogoutLocation(this.getLocation()); + } + + @Override + public void requestTeleport(final User player, final boolean here) { + teleportRequestTime = System.currentTimeMillis(); + teleportRequester = player == null ? null : player.getBase().getUniqueId(); + teleportRequestHere = here; + if (player == null) { + teleportLocation = null; + } else { + teleportLocation = here ? player.getLocation() : this.getLocation(); + } + } + + public UUID getTeleportRequest() { + return teleportRequester; + } + + public boolean isTpRequestHere() { + return teleportRequestHere; + } + + public Location getTpRequestLocation() { + return teleportLocation; + } + + public String getNick(final boolean longnick) { + final StringBuilder prefix = new StringBuilder(); + String nickname; + String suffix = ""; + final String nick = getNickname(); + if (ess.getSettings().isCommandDisabled("nick") || nick == null || nick.isEmpty() || nick.equals(getName())) { + nickname = getName(); + } else if (nick.equalsIgnoreCase(getName())) { + nickname = nick; + } else { + nickname = ess.getSettings().getNicknamePrefix() + nick; + suffix = "§r"; + } + + if (this.getBase().isOp()) { + try { + final ChatColor opPrefix = ess.getSettings().getOperatorColor(); + if (opPrefix != null && opPrefix.toString().length() > 0) { + prefix.insert(0, opPrefix.toString()); + suffix = "§r"; + } + } catch (Exception e) { + } + } + + if (ess.getSettings().addPrefixSuffix()) { + //These two extra toggles are not documented, because they are mostly redundant #EasterEgg + if (!ess.getSettings().disablePrefix()) { + final String ptext = ess.getPermissionsHandler().getPrefix(base).replace('&', '§'); + prefix.insert(0, ptext); + suffix = "§r"; + } + if (!ess.getSettings().disableSuffix()) { + final String stext = ess.getPermissionsHandler().getSuffix(base).replace('&', '§'); + suffix = stext + "§r"; + suffix = suffix.replace("§f§f", "§f").replace("§f§r", "§r").replace("§r§r", "§r"); + } + } + final String strPrefix = prefix.toString(); + String output = strPrefix + nickname + suffix; + if (!longnick && output.length() > 16) { + output = strPrefix + nickname; + } + if (!longnick && output.length() > 16) { + output = FormatUtil.lastCode(strPrefix) + nickname; + } + if (!longnick && output.length() > 16) { + output = FormatUtil.lastCode(strPrefix) + nickname.substring(0, 14); + } + if (output.charAt(output.length() - 1) == '§') { + output = output.substring(0, output.length() - 1); + } + return output; + } + + public void setDisplayNick() { + if (base.isOnline() && ess.getSettings().changeDisplayName()) { + this.getBase().setDisplayName(getNick(true)); + if (ess.getSettings().changePlayerListName()) { + String name = getNick(false); + try { + this.getBase().setPlayerListName(name); + } catch (IllegalArgumentException e) { + if (ess.getSettings().isDebug()) { + logger.log(Level.INFO, "Playerlist for " + name + " was not updated. Name clashed with another online player."); + } + } + } + } + } + + public String getDisplayName() { + return super.getBase().getDisplayName() == null ? super.getBase().getName() : super.getBase().getDisplayName(); + } + + @Override + public Teleport getTeleport() { + return teleport; + } + + public long getLastOnlineActivity() { + return lastOnlineActivity; + } + + public void setLastOnlineActivity(final long timestamp) { + lastOnlineActivity = timestamp; + } + + @Override + public BigDecimal getMoney() { + final long start = System.nanoTime(); + final BigDecimal value = _getMoney(); + final long elapsed = System.nanoTime() - start; + if (elapsed > ess.getSettings().getEconomyLagWarning()) { + ess.getLogger().log(Level.INFO, "Lag Notice - Slow Economy Response - Request took over {0}ms!", elapsed / 1000000.0); + } + return value; + } + + private BigDecimal _getMoney() { + if (ess.getSettings().isEcoDisabled()) { + if (ess.getSettings().isDebug()) { + ess.getLogger().info("Internal economy functions disabled, aborting balance check."); + } + return BigDecimal.ZERO; + } + if (Methods.hasMethod()) { + try { + final Method method = Methods.getMethod(); + if (!method.hasAccount(this.getName())) { + throw new Exception(); + } + final Method.MethodAccount account = Methods.getMethod().getAccount(this.getName()); + return BigDecimal.valueOf(account.balance()); + } catch (Exception ex) { + } + } + return super.getMoney(); + } + + @Override + public void setMoney(final BigDecimal value) throws MaxMoneyException { + if (ess.getSettings().isEcoDisabled()) { + if (ess.getSettings().isDebug()) { + ess.getLogger().info("Internal economy functions disabled, aborting balance change."); + } + return; + } + final BigDecimal oldBalance = _getMoney(); + if (Methods.hasMethod()) { + try { + final Method method = Methods.getMethod(); + if (!method.hasAccount(this.getName())) { + throw new Exception(); + } + final Method.MethodAccount account = Methods.getMethod().getAccount(this.getName()); + account.set(value.doubleValue()); + } catch (Exception ex) { + } + } + super.setMoney(value, true); + ess.getServer().getPluginManager().callEvent(new UserBalanceUpdateEvent(this.getBase(), oldBalance, value)); + Trade.log("Update", "Set", "API", getName(), new Trade(value, ess), null, null, null, ess); + } + + public void updateMoneyCache(final BigDecimal value) { + if (ess.getSettings().isEcoDisabled()) { + return; + } + if (Methods.hasMethod() && super.getMoney() != value) { + try { + super.setMoney(value, false); + } catch (MaxMoneyException ex) { + // We don't want to throw any errors here, just updating a cache + } + } + } + + @Override + public void setAfk(final boolean set) { + final AfkStatusChangeEvent afkEvent = new AfkStatusChangeEvent(this, set); + ess.getServer().getPluginManager().callEvent(afkEvent); + if (afkEvent.isCancelled()) { + return; + } + + this.getBase().setSleepingIgnored(this.isAuthorized("essentials.sleepingignored") ? true : set); + if (set && !isAfk()) { + afkPosition = this.getLocation(); + } else if (!set && isAfk()) { + afkPosition = null; + } + _setAfk(set); + } + + public boolean toggleAfk() { + setAfk(!isAfk()); + return isAfk(); + } + + @Override + public boolean isHidden() { + return hidden; + } + + public boolean isHidden(final Player player) { + return hidden || !player.canSee(getBase()); + } + + @Override + public void setHidden(final boolean hidden) { + this.hidden = hidden; + if (hidden == true) { + setLastLogout(getLastOnlineActivity()); + } + } + + //Returns true if status expired during this check + public boolean checkJailTimeout(final long currentTime) { + if (getJailTimeout() > 0 && getJailTimeout() < currentTime && isJailed()) { + setJailTimeout(0); + setJailed(false); + sendMessage(tl("haveBeenReleased")); + setJail(null); + try { + getTeleport().back(); + } catch (Exception ex) { + try { + getTeleport().respawn(null, TeleportCause.PLUGIN); + } catch (Exception ex1) { + } + } + return true; + } + return false; + } + + //Returns true if status expired during this check + public boolean checkMuteTimeout(final long currentTime) { + if (getMuteTimeout() > 0 && getMuteTimeout() < currentTime && isMuted()) { + setMuteTimeout(0); + sendMessage(tl("canTalkAgain")); + setMuted(false); + return true; + } + return false; + } + + public void updateActivity(final boolean broadcast) { + if (isAfk() && ess.getSettings().cancelAfkOnInteract()) { + setAfk(false); + if (broadcast && !isHidden()) { + setDisplayNick(); + final String msg = tl("userIsNotAway", getDisplayName()); + if (!msg.isEmpty()) { + ess.broadcastMessage(this, msg); + } + } + } + lastActivity = System.currentTimeMillis(); + } + + public void checkActivity() { + final long autoafkkick = ess.getSettings().getAutoAfkKick(); + if (autoafkkick > 0 && lastActivity > 0 && (lastActivity + (autoafkkick * 1000)) < System.currentTimeMillis() && !isHidden() && !isAuthorized("essentials.kick.exempt") && !isAuthorized("essentials.afk.kickexempt")) { + final String kickReason = tl("autoAfkKickReason", autoafkkick / 60.0); + lastActivity = 0; + this.getBase().kickPlayer(kickReason); + + + for (User user : ess.getOnlineUsers()) { + if (user.isAuthorized("essentials.kick.notify")) { + user.sendMessage(tl("playerKicked", Console.NAME, getName(), kickReason)); + } + } + } + final long autoafk = ess.getSettings().getAutoAfk(); + if (!isAfk() && autoafk > 0 && lastActivity + autoafk * 1000 < System.currentTimeMillis() && isAuthorized("essentials.afk.auto")) { + setAfk(true); + if (!isHidden()) { + setDisplayNick(); + final String msg = tl("userIsAway", getDisplayName()); + if (!msg.isEmpty()) { + ess.broadcastMessage(this, msg); + } + } + } + } + + public Location getAfkPosition() { + return afkPosition; + } + + @Override + public boolean isGodModeEnabled() { + return (super.isGodModeEnabled() && !ess.getSettings().getNoGodWorlds().contains(this.getLocation().getWorld().getName())) || (isAfk() && ess.getSettings().getFreezeAfkPlayers()); + } + + public boolean isGodModeEnabledRaw() { + return super.isGodModeEnabled(); + } + + @Override + public String getGroup() { + final String result = ess.getPermissionsHandler().getGroup(base); + if (ess.getSettings().isDebug()) { + ess.getLogger().log(Level.INFO, "looking up groupname of " + base.getName() + " - " + result); + } + return result; + } + + @Override + public boolean inGroup(final String group) { + final boolean result = ess.getPermissionsHandler().inGroup(base, group); + if (ess.getSettings().isDebug()) { + ess.getLogger().log(Level.INFO, "checking if " + base.getName() + " is in group " + group + " - " + result); + } + return result; + } + + @Override + public boolean canBuild() { + if (this.getBase().isOp()) { + return true; + } + return ess.getPermissionsHandler().canBuild(base, getGroup()); + } + + public long getTeleportRequestTime() { + return teleportRequestTime; + } + + public boolean isInvSee() { + return invSee; + } + + public void setInvSee(final boolean set) { + invSee = set; + } + + public boolean isEnderSee() { + return enderSee; + } + + public void setEnderSee(final boolean set) { + enderSee = set; + } + + @Override + public void enableInvulnerabilityAfterTeleport() { + final long time = ess.getSettings().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(); + } + + public boolean canInteractVanished() { + return isAuthorized("essentials.vanish.interact"); + } + + @Override + public boolean isVanished() { + return vanished; + } + + @Override + public void setVanished(final boolean set) { + vanished = set; + if (set) { + for (User user : ess.getOnlineUsers()) { + if (!user.isAuthorized("essentials.vanish.see")) { + user.getBase().hidePlayer(getBase()); + } + } + setHidden(true); + ess.getVanishedPlayers().add(getName()); + if (isAuthorized("essentials.vanish.effect")) { + this.getBase().addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, Integer.MAX_VALUE, 1, false)); + } + } else { + for (Player p : ess.getOnlinePlayers()) { + p.showPlayer(getBase()); + } + setHidden(false); + ess.getVanishedPlayers().remove(getName()); + if (isAuthorized("essentials.vanish.effect")) { + this.getBase().removePotionEffect(PotionEffectType.INVISIBILITY); + } + } + } + + public boolean checkSignThrottle() { + if (isSignThrottled()) { + return true; + } + updateThrottle(); + return false; + } + + public boolean isSignThrottled() { + final long minTime = lastThrottledAction + (1000 / ess.getSettings().getSignUsePerSecond()); + return (System.currentTimeMillis() < minTime); + } + + public void updateThrottle() { + lastThrottledAction = System.currentTimeMillis(); + } + + public boolean isFlyClickJump() { + return rightClickJump; + } + + public void setRightClickJump(boolean rightClickJump) { + this.rightClickJump = rightClickJump; + } + + @Override + public boolean isIgnoreExempt() { + return this.isAuthorized("essentials.chat.ignoreexempt"); + } + + public boolean isRecipeSee() { + return recipeSee; + } + + public void setRecipeSee(boolean recipeSee) { + this.recipeSee = recipeSee; + } + + @Override + public void sendMessage(String message) { + if (!message.isEmpty()) { + base.sendMessage(message); + } + } + + @Override + public void setReplyTo(final CommandSource user) { + replyTo = user; + } + + @Override + public CommandSource getReplyTo() { + return replyTo; + } + + @Override + public int compareTo(final User other) { + return FormatUtil.stripFormat(getDisplayName()).compareToIgnoreCase(FormatUtil.stripFormat(other.getDisplayName())); + } + + @Override + public boolean equals(final Object object) { + if (!(object instanceof User)) { + return false; + } + return this.getName().equalsIgnoreCase(((User) object).getName()); + + } + + @Override + public int hashCode() { + return this.getName().hashCode(); + } + + @Override + public CommandSource getSource() { + return new CommandSource(getBase()); + } + + @Override + public String getName() { + return this.getBase().getName(); + } } diff --git a/Essentials/src/com/earth2me/essentials/UserData.java b/Essentials/src/com/earth2me/essentials/UserData.java index 136e74fbe..45de8d113 100644 --- a/Essentials/src/com/earth2me/essentials/UserData.java +++ b/Essentials/src/com/earth2me/essentials/UserData.java @@ -1,11 +1,7 @@ package com.earth2me.essentials; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.utils.NumberUtil; import com.earth2me.essentials.utils.StringUtil; -import java.io.File; -import java.math.BigDecimal; -import java.util.*; import net.ess3.api.IEssentials; import net.ess3.api.InvalidWorldException; import net.ess3.api.MaxMoneyException; @@ -14,959 +10,799 @@ import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; - -public abstract class UserData extends PlayerExtension implements IConf -{ - protected final transient IEssentials ess; - private final EssentialsUserConf config; - private final File folder; - - protected UserData(Player base, IEssentials ess) - { - super(base); - this.ess = ess; - folder = new File(ess.getDataFolder(), "userdata"); - if (!folder.exists()) - { - folder.mkdirs(); - } - - String filename; - try - { - filename = base.getUniqueId().toString(); - } - catch (Throwable ex) - { - ess.getLogger().warning("Falling back to old username system for " + base.getName()); - filename = base.getName(); - } - - config = new EssentialsUserConf(base.getName(), base.getUniqueId(), new File(folder, filename + ".yml")); - reloadConfig(); - } - - public final void reset() - { - config.forceSave(); - config.getFile().delete(); - if (config.username != null) - { - ess.getUserMap().removeUser(config.username); - } - } - - public final void cleanup() - { - config.cleanup(); - } - - @Override - public final void reloadConfig() - { - config.load(); - money = _getMoney(); - unlimited = _getUnlimited(); - powertools = _getPowertools(); - homes = _getHomes(); - lastLocation = _getLastLocation(); - lastTeleportTimestamp = _getLastTeleportTimestamp(); - lastHealTimestamp = _getLastHealTimestamp(); - jail = _getJail(); - mails = _getMails(); - teleportEnabled = _getTeleportEnabled(); - godmode = _getGodModeEnabled(); - muted = _getMuted(); - muteTimeout = _getMuteTimeout(); - jailed = _getJailed(); - jailTimeout = _getJailTimeout(); - lastLogin = _getLastLogin(); - lastLogout = _getLastLogout(); - lastLoginAddress = _getLastLoginAddress(); - afk = _getAfk(); - geolocation = _getGeoLocation(); - isSocialSpyEnabled = _isSocialSpyEnabled(); - isNPC = _isNPC(); - arePowerToolsEnabled = _arePowerToolsEnabled(); - kitTimestamps = _getKitTimestamps(); - nickname = _getNickname(); - ignoredPlayers = _getIgnoredPlayers(); - logoutLocation = _getLogoutLocation(); - lastAccountName = _getLastAccountName(); - } - private BigDecimal money; - - private BigDecimal _getMoney() - { - BigDecimal result = ess.getSettings().getStartingBalance(); - BigDecimal maxMoney = ess.getSettings().getMaxMoney(); - BigDecimal minMoney = ess.getSettings().getMinMoney(); - - if (config.hasProperty("money")) - { - result = config.getBigDecimal("money", result); - } - if (result.compareTo(maxMoney) > 0) - { - result = maxMoney; - } - if (result.compareTo(minMoney) < 0) - { - result = minMoney; - } - return result; - } - - public BigDecimal getMoney() - { - return money; - } - - public void setMoney(BigDecimal value, boolean throwError) throws MaxMoneyException - { - BigDecimal maxMoney = ess.getSettings().getMaxMoney(); - BigDecimal minMoney = ess.getSettings().getMinMoney(); - if (value.compareTo(maxMoney) > 0) - { - if (throwError) - { - throw new MaxMoneyException(); - } - money = maxMoney; - } - else - { - money = value; - } - if (money.compareTo(minMoney) < 0) - { - money = minMoney; - } - config.setProperty("money", money); - stopTransaction(); - } - private Map homes; - - private Map _getHomes() - { - if (config.isConfigurationSection("homes")) - { - return config.getConfigurationSection("homes").getValues(false); - } - return new HashMap(); - } - - private String getHomeName(String search) - { - if (NumberUtil.isInt(search)) - { - try - { - search = getHomes().get(Integer.parseInt(search) - 1); - } - catch (NumberFormatException e) - { - } - catch (IndexOutOfBoundsException e) - { - } - } - return search; - } - - public Location getHome(String name) throws Exception - { - String search = getHomeName(name); - return config.getLocation("homes." + search, this.getBase().getServer()); - } - - public Location getHome(final Location world) - { - try - { - if (getHomes().isEmpty()) - { - return null; - } - Location loc; - for (String home : getHomes()) - { - loc = config.getLocation("homes." + home, this.getBase().getServer()); - if (world.getWorld() == loc.getWorld()) - { - return loc; - } - - } - loc = config.getLocation("homes." + getHomes().get(0), this.getBase().getServer()); - return loc; - } - catch (InvalidWorldException ex) - { - return null; - } - } - - public List getHomes() - { - return new ArrayList(homes.keySet()); - } - - public void setHome(String name, Location loc) - { - //Invalid names will corrupt the yaml - name = StringUtil.safeString(name); - homes.put(name, loc); - config.setProperty("homes." + name, loc); - config.save(); - } - - public void delHome(String name) throws Exception - { - String search = getHomeName(name); - if (!homes.containsKey(search)) - { - search = StringUtil.safeString(search); - } - if (homes.containsKey(search)) - { - homes.remove(search); - config.removeProperty("homes." + search); - config.save(); - } - else - { - throw new Exception(tl("invalidHome", search)); - } - } - - public boolean hasHome() - { - if (config.hasProperty("home")) - { - return true; - } - return false; - } - private String nickname; - - public String _getNickname() - { - return config.getString("nickname"); - } - - public String getNickname() - { - return nickname; - } - - public void setNickname(String nick) - { - nickname = nick; - config.setProperty("nickname", nick); - config.save(); - } - private List unlimited; - - private List _getUnlimited() - { - return config.getIntegerList("unlimited"); - } - - public List getUnlimited() - { - return unlimited; - } - - public boolean hasUnlimited(ItemStack stack) - { - return unlimited.contains(stack.getTypeId()); - } - - public void setUnlimited(ItemStack stack, boolean state) - { - if (unlimited.contains(stack.getTypeId())) - { - unlimited.remove(Integer.valueOf(stack.getTypeId())); - } - if (state) - { - unlimited.add(stack.getTypeId()); - } - config.setProperty("unlimited", unlimited); - config.save(); - } - private Map powertools; - - private Map _getPowertools() - { - if (config.isConfigurationSection("powertools")) - { - return config.getConfigurationSection("powertools").getValues(false); - } - return new HashMap(); - } - - public void clearAllPowertools() - { - powertools.clear(); - config.setProperty("powertools", powertools); - config.save(); - } - - @SuppressWarnings("unchecked") - public List getPowertool(ItemStack stack) - { - return (List)powertools.get("" + stack.getTypeId()); - } - - @SuppressWarnings("unchecked") - public List getPowertool(int id) - { - return (List)powertools.get("" + id); - } - - public void setPowertool(ItemStack stack, List commandList) - { - if (commandList == null || commandList.isEmpty()) - { - powertools.remove("" + stack.getTypeId()); - } - else - { - powertools.put("" + stack.getTypeId(), commandList); - } - config.setProperty("powertools", powertools); - config.save(); - } - - public boolean hasPowerTools() - { - return !powertools.isEmpty(); - } - private Location lastLocation; - - private Location _getLastLocation() - { - try - { - return config.getLocation("lastlocation", this.getBase().getServer()); - } - catch (InvalidWorldException e) - { - return null; - } - } - - public Location getLastLocation() - { - return lastLocation; - } - - public void setLastLocation(Location loc) - { - if (loc == null || loc.getWorld() == null) - { - return; - } - lastLocation = loc; - config.setProperty("lastlocation", loc); - config.save(); - } - private Location logoutLocation; - - private Location _getLogoutLocation() - { - try - { - return config.getLocation("logoutlocation", this.getBase().getServer()); - } - catch (InvalidWorldException e) - { - return null; - } - } - - public Location getLogoutLocation() - { - return logoutLocation; - } - - public void setLogoutLocation(Location loc) - { - if (loc == null || loc.getWorld() == null) - { - return; - } - logoutLocation = loc; - config.setProperty("logoutlocation", loc); - config.save(); - } - private long lastTeleportTimestamp; - - private long _getLastTeleportTimestamp() - { - return config.getLong("timestamps.lastteleport", 0); - } - - public long getLastTeleportTimestamp() - { - return lastTeleportTimestamp; - } - - public void setLastTeleportTimestamp(long time) - { - lastTeleportTimestamp = time; - config.setProperty("timestamps.lastteleport", time); - config.save(); - } - private long lastHealTimestamp; - - private long _getLastHealTimestamp() - { - return config.getLong("timestamps.lastheal", 0); - } - - public long getLastHealTimestamp() - { - return lastHealTimestamp; - } - - public void setLastHealTimestamp(long time) - { - lastHealTimestamp = time; - config.setProperty("timestamps.lastheal", time); - config.save(); - } - private String jail; - - private String _getJail() - { - return config.getString("jail"); - } - - public String getJail() - { - return jail; - } - - public void setJail(String jail) - { - if (jail == null || jail.isEmpty()) - { - this.jail = null; - config.removeProperty("jail"); - } - else - { - this.jail = jail; - config.setProperty("jail", jail); - } - config.save(); - } - private List mails; - - private List _getMails() - { - return config.getStringList("mail"); - } - - public List getMails() - { - return mails; - } - - public void setMails(List mails) - { - if (mails == null) - { - config.removeProperty("mail"); - mails = _getMails(); - } - else - { - config.setProperty("mail", mails); - } - this.mails = mails; - config.save(); - } - - public void addMail(String mail) - { - mails.add(mail); - setMails(mails); - } - private boolean teleportEnabled; - - private boolean _getTeleportEnabled() - { - return config.getBoolean("teleportenabled", true); - } - - public boolean isTeleportEnabled() - { - return teleportEnabled; - } - - public void setTeleportEnabled(boolean set) - { - teleportEnabled = set; - config.setProperty("teleportenabled", set); - config.save(); - } - private List ignoredPlayers; - - public List _getIgnoredPlayers() - { - return Collections.synchronizedList(config.getStringList("ignore")); - } - - public void setIgnoredPlayers(List players) - { - if (players == null || players.isEmpty()) - { - ignoredPlayers = Collections.synchronizedList(new ArrayList()); - config.removeProperty("ignore"); - } - else - { - ignoredPlayers = players; - config.setProperty("ignore", players); - } - config.save(); - } - - @Deprecated - public boolean isIgnoredPlayer(final String userName) - { - final IUser user = ess.getUser(userName); - if (user == null || !user.getBase().isOnline()) - { - return false; - } - return isIgnoredPlayer(user); - } - - public boolean isIgnoredPlayer(IUser user) - { - return (ignoredPlayers.contains(user.getName().toLowerCase(Locale.ENGLISH)) && !user.isIgnoreExempt()); - } - - public void setIgnoredPlayer(IUser user, boolean set) - { - if (set) - { - ignoredPlayers.add(user.getName().toLowerCase(Locale.ENGLISH)); - } - else - { - ignoredPlayers.remove(user.getName().toLowerCase(Locale.ENGLISH)); - } - setIgnoredPlayers(ignoredPlayers); - } - private boolean godmode; - - private boolean _getGodModeEnabled() - { - return config.getBoolean("godmode", false); - } - - public boolean isGodModeEnabled() - { - return godmode; - } - - public void setGodModeEnabled(boolean set) - { - godmode = set; - config.setProperty("godmode", set); - config.save(); - } - private boolean muted; - - public boolean _getMuted() - { - return config.getBoolean("muted", false); - } - - public boolean getMuted() - { - return muted; - } - - public boolean isMuted() - { - return muted; - } - - public void setMuted(boolean set) - { - muted = set; - config.setProperty("muted", set); - config.save(); - } - private long muteTimeout; - - private long _getMuteTimeout() - { - return config.getLong("timestamps.mute", 0); - } - - public long getMuteTimeout() - { - return muteTimeout; - } - - public void setMuteTimeout(long time) - { - muteTimeout = time; - config.setProperty("timestamps.mute", time); - config.save(); - } - private boolean jailed; - - private boolean _getJailed() - { - return config.getBoolean("jailed", false); - } - - public boolean isJailed() - { - return jailed; - } - - public void setJailed(boolean set) - { - jailed = set; - config.setProperty("jailed", set); - config.save(); - } - - public boolean toggleJailed() - { - boolean ret = !isJailed(); - setJailed(ret); - return ret; - } - private long jailTimeout; - - private long _getJailTimeout() - { - return config.getLong("timestamps.jail", 0); - } - - public long getJailTimeout() - { - return jailTimeout; - } - - public void setJailTimeout(long time) - { - jailTimeout = time; - config.setProperty("timestamps.jail", time); - config.save(); - } - - private long lastLogin; - - private long _getLastLogin() - { - return config.getLong("timestamps.login", 0); - } - - public long getLastLogin() - { - return lastLogin; - } - - private void _setLastLogin(long time) - { - lastLogin = time; - config.setProperty("timestamps.login", time); - } - - public void setLastLogin(long time) - { - _setLastLogin(time); - if (base.getAddress() != null && base.getAddress().getAddress() != null) - { - _setLastLoginAddress(base.getAddress().getAddress().getHostAddress()); - } - config.save(); - } - private long lastLogout; - - private long _getLastLogout() - { - return config.getLong("timestamps.logout", 0); - } - - public long getLastLogout() - { - return lastLogout; - } - - public void setLastLogout(long time) - { - lastLogout = time; - config.setProperty("timestamps.logout", time); - config.save(); - } - private String lastLoginAddress; - - private String _getLastLoginAddress() - { - return config.getString("ipAddress", ""); - } - - public String getLastLoginAddress() - { - return lastLoginAddress; - } - - private void _setLastLoginAddress(String address) - { - lastLoginAddress = address; - config.setProperty("ipAddress", address); - } - private boolean afk; - - private boolean _getAfk() - { - return config.getBoolean("afk", false); - } - - public boolean isAfk() - { - return afk; - } - - public void _setAfk(boolean set) - { - afk = set; - config.setProperty("afk", set); - config.save(); - } - private boolean newplayer; - private String geolocation; - - private String _getGeoLocation() - { - return config.getString("geolocation"); - } - - public String getGeoLocation() - { - return geolocation; - } - - public void setGeoLocation(String geolocation) - { - if (geolocation == null || geolocation.isEmpty()) - { - this.geolocation = null; - config.removeProperty("geolocation"); - } - else - { - this.geolocation = geolocation; - config.setProperty("geolocation", geolocation); - } - config.save(); - } - private boolean isSocialSpyEnabled; - - private boolean _isSocialSpyEnabled() - { - return config.getBoolean("socialspy", false); - } - - public boolean isSocialSpyEnabled() - { - return isSocialSpyEnabled; - } - - public void setSocialSpyEnabled(boolean status) - { - isSocialSpyEnabled = status; - config.setProperty("socialspy", status); - config.save(); - } - private boolean isNPC; - - private boolean _isNPC() - { - return config.getBoolean("npc", false); - } - - public boolean isNPC() - { - return isNPC; - } - private String lastAccountName = null; - - public String getLastAccountName() - { - return lastAccountName; - } - - public String _getLastAccountName() - { - return config.getString("lastAccountName", null); - } - - public void setLastAccountName(String lastAccountName) - { - this.lastAccountName = lastAccountName; - config.setProperty("lastAccountName", lastAccountName); - config.save(); - ess.getUserMap().trackUUID(getConfigUUID(), lastAccountName, true); - } - - public void setNPC(boolean set) - { - isNPC = set; - config.setProperty("npc", set); - config.save(); - } - private boolean arePowerToolsEnabled; - - public boolean arePowerToolsEnabled() - { - return arePowerToolsEnabled; - } - - public void setPowerToolsEnabled(boolean set) - { - arePowerToolsEnabled = set; - config.setProperty("powertoolsenabled", set); - config.save(); - } - - public boolean togglePowerToolsEnabled() - { - boolean ret = !arePowerToolsEnabled(); - setPowerToolsEnabled(ret); - return ret; - } - - private boolean _arePowerToolsEnabled() - { - return config.getBoolean("powertoolsenabled", true); - } - private Map kitTimestamps; - - private Map _getKitTimestamps() - { - - if (config.isConfigurationSection("timestamps.kits")) - { - final ConfigurationSection section = config.getConfigurationSection("timestamps.kits"); - final Map timestamps = new HashMap(); - for (String command : section.getKeys(false)) - { - if (section.isLong(command)) - { - timestamps.put(command.toLowerCase(Locale.ENGLISH), section.getLong(command)); - } - else if (section.isInt(command)) - { - timestamps.put(command.toLowerCase(Locale.ENGLISH), (long)section.getInt(command)); - } - } - return timestamps; - } - return new HashMap(); - } - - public long getKitTimestamp(String name) - { - name = name.replace('.', '_').replace('/', '_'); - if (kitTimestamps != null && kitTimestamps.containsKey(name)) - { - return kitTimestamps.get(name); - } - return 0l; - } - - public void setKitTimestamp(final String name, final long time) - { - kitTimestamps.put(name.toLowerCase(Locale.ENGLISH), time); - config.setProperty("timestamps.kits", kitTimestamps); - config.save(); - } - - public void setConfigProperty(String node, Object object) - { - final String prefix = "info."; - node = prefix + node; - if (object instanceof Map) - { - config.setProperty(node, (Map)object); - } - else if (object instanceof List) - { - config.setProperty(node, (List)object); - } - else if (object instanceof Location) - { - config.setProperty(node, (Location)object); - } - else if (object instanceof ItemStack) - { - config.setProperty(node, (ItemStack)object); - } - else - { - config.setProperty(node, object); - } - config.save(); - } - - public Set getConfigKeys() - { - if (config.isConfigurationSection("info")) - { - return config.getConfigurationSection("info").getKeys(true); - } - return new HashSet(); - } - - public Map getConfigMap() - { - if (config.isConfigurationSection("info")) - { - return config.getConfigurationSection("info").getValues(true); - } - return new HashMap(); - } - - public Map getConfigMap(String node) - { - if (config.isConfigurationSection("info." + node)) - { - return config.getConfigurationSection("info." + node).getValues(true); - } - return new HashMap(); - } - - public UUID getConfigUUID() - { - return config.uuid; - } - - public void save() - { - config.save(); - } - - public void startTransaction() - { - config.startTransaction(); - } - - public void stopTransaction() - { - config.stopTransaction(); - } +import java.io.File; +import java.math.BigDecimal; +import java.util.*; + +import static com.earth2me.essentials.I18n.tl; + + +public abstract class UserData extends PlayerExtension implements IConf { + protected final transient IEssentials ess; + private final EssentialsUserConf config; + private final File folder; + + protected UserData(Player base, IEssentials ess) { + super(base); + this.ess = ess; + folder = new File(ess.getDataFolder(), "userdata"); + if (!folder.exists()) { + folder.mkdirs(); + } + + String filename; + try { + filename = base.getUniqueId().toString(); + } catch (Throwable ex) { + ess.getLogger().warning("Falling back to old username system for " + base.getName()); + filename = base.getName(); + } + + config = new EssentialsUserConf(base.getName(), base.getUniqueId(), new File(folder, filename + ".yml")); + reloadConfig(); + } + + public final void reset() { + config.forceSave(); + config.getFile().delete(); + if (config.username != null) { + ess.getUserMap().removeUser(config.username); + } + } + + public final void cleanup() { + config.cleanup(); + } + + @Override + public final void reloadConfig() { + config.load(); + money = _getMoney(); + unlimited = _getUnlimited(); + powertools = _getPowertools(); + homes = _getHomes(); + lastLocation = _getLastLocation(); + lastTeleportTimestamp = _getLastTeleportTimestamp(); + lastHealTimestamp = _getLastHealTimestamp(); + jail = _getJail(); + mails = _getMails(); + teleportEnabled = _getTeleportEnabled(); + godmode = _getGodModeEnabled(); + muted = _getMuted(); + muteTimeout = _getMuteTimeout(); + jailed = _getJailed(); + jailTimeout = _getJailTimeout(); + lastLogin = _getLastLogin(); + lastLogout = _getLastLogout(); + lastLoginAddress = _getLastLoginAddress(); + afk = _getAfk(); + geolocation = _getGeoLocation(); + isSocialSpyEnabled = _isSocialSpyEnabled(); + isNPC = _isNPC(); + arePowerToolsEnabled = _arePowerToolsEnabled(); + kitTimestamps = _getKitTimestamps(); + nickname = _getNickname(); + ignoredPlayers = _getIgnoredPlayers(); + logoutLocation = _getLogoutLocation(); + lastAccountName = _getLastAccountName(); + } + + private BigDecimal money; + + private BigDecimal _getMoney() { + BigDecimal result = ess.getSettings().getStartingBalance(); + BigDecimal maxMoney = ess.getSettings().getMaxMoney(); + BigDecimal minMoney = ess.getSettings().getMinMoney(); + + if (config.hasProperty("money")) { + result = config.getBigDecimal("money", result); + } + if (result.compareTo(maxMoney) > 0) { + result = maxMoney; + } + if (result.compareTo(minMoney) < 0) { + result = minMoney; + } + return result; + } + + public BigDecimal getMoney() { + return money; + } + + public void setMoney(BigDecimal value, boolean throwError) throws MaxMoneyException { + BigDecimal maxMoney = ess.getSettings().getMaxMoney(); + BigDecimal minMoney = ess.getSettings().getMinMoney(); + if (value.compareTo(maxMoney) > 0) { + if (throwError) { + throw new MaxMoneyException(); + } + money = maxMoney; + } else { + money = value; + } + if (money.compareTo(minMoney) < 0) { + money = minMoney; + } + config.setProperty("money", money); + stopTransaction(); + } + + private Map homes; + + private Map _getHomes() { + if (config.isConfigurationSection("homes")) { + return config.getConfigurationSection("homes").getValues(false); + } + return new HashMap(); + } + + private String getHomeName(String search) { + if (NumberUtil.isInt(search)) { + try { + search = getHomes().get(Integer.parseInt(search) - 1); + } catch (NumberFormatException e) { + } catch (IndexOutOfBoundsException e) { + } + } + return search; + } + + public Location getHome(String name) throws Exception { + String search = getHomeName(name); + return config.getLocation("homes." + search, this.getBase().getServer()); + } + + public Location getHome(final Location world) { + try { + if (getHomes().isEmpty()) { + return null; + } + Location loc; + for (String home : getHomes()) { + loc = config.getLocation("homes." + home, this.getBase().getServer()); + if (world.getWorld() == loc.getWorld()) { + return loc; + } + + } + loc = config.getLocation("homes." + getHomes().get(0), this.getBase().getServer()); + return loc; + } catch (InvalidWorldException ex) { + return null; + } + } + + public List getHomes() { + return new ArrayList(homes.keySet()); + } + + public void setHome(String name, Location loc) { + //Invalid names will corrupt the yaml + name = StringUtil.safeString(name); + homes.put(name, loc); + config.setProperty("homes." + name, loc); + config.save(); + } + + public void delHome(String name) throws Exception { + String search = getHomeName(name); + if (!homes.containsKey(search)) { + search = StringUtil.safeString(search); + } + if (homes.containsKey(search)) { + homes.remove(search); + config.removeProperty("homes." + search); + config.save(); + } else { + throw new Exception(tl("invalidHome", search)); + } + } + + public boolean hasHome() { + if (config.hasProperty("home")) { + return true; + } + return false; + } + + private String nickname; + + public String _getNickname() { + return config.getString("nickname"); + } + + public String getNickname() { + return nickname; + } + + public void setNickname(String nick) { + nickname = nick; + config.setProperty("nickname", nick); + config.save(); + } + + private List unlimited; + + private List _getUnlimited() { + return config.getIntegerList("unlimited"); + } + + public List getUnlimited() { + return unlimited; + } + + public boolean hasUnlimited(ItemStack stack) { + return unlimited.contains(stack.getTypeId()); + } + + public void setUnlimited(ItemStack stack, boolean state) { + if (unlimited.contains(stack.getTypeId())) { + unlimited.remove(Integer.valueOf(stack.getTypeId())); + } + if (state) { + unlimited.add(stack.getTypeId()); + } + config.setProperty("unlimited", unlimited); + config.save(); + } + + private Map powertools; + + private Map _getPowertools() { + if (config.isConfigurationSection("powertools")) { + return config.getConfigurationSection("powertools").getValues(false); + } + return new HashMap(); + } + + public void clearAllPowertools() { + powertools.clear(); + config.setProperty("powertools", powertools); + config.save(); + } + + @SuppressWarnings("unchecked") + public List getPowertool(ItemStack stack) { + return (List) powertools.get("" + stack.getTypeId()); + } + + @SuppressWarnings("unchecked") + public List getPowertool(int id) { + return (List) powertools.get("" + id); + } + + public void setPowertool(ItemStack stack, List commandList) { + if (commandList == null || commandList.isEmpty()) { + powertools.remove("" + stack.getTypeId()); + } else { + powertools.put("" + stack.getTypeId(), commandList); + } + config.setProperty("powertools", powertools); + config.save(); + } + + public boolean hasPowerTools() { + return !powertools.isEmpty(); + } + + private Location lastLocation; + + private Location _getLastLocation() { + try { + return config.getLocation("lastlocation", this.getBase().getServer()); + } catch (InvalidWorldException e) { + return null; + } + } + + public Location getLastLocation() { + return lastLocation; + } + + public void setLastLocation(Location loc) { + if (loc == null || loc.getWorld() == null) { + return; + } + lastLocation = loc; + config.setProperty("lastlocation", loc); + config.save(); + } + + private Location logoutLocation; + + private Location _getLogoutLocation() { + try { + return config.getLocation("logoutlocation", this.getBase().getServer()); + } catch (InvalidWorldException e) { + return null; + } + } + + public Location getLogoutLocation() { + return logoutLocation; + } + + public void setLogoutLocation(Location loc) { + if (loc == null || loc.getWorld() == null) { + return; + } + logoutLocation = loc; + config.setProperty("logoutlocation", loc); + config.save(); + } + + private long lastTeleportTimestamp; + + private long _getLastTeleportTimestamp() { + return config.getLong("timestamps.lastteleport", 0); + } + + public long getLastTeleportTimestamp() { + return lastTeleportTimestamp; + } + + public void setLastTeleportTimestamp(long time) { + lastTeleportTimestamp = time; + config.setProperty("timestamps.lastteleport", time); + config.save(); + } + + private long lastHealTimestamp; + + private long _getLastHealTimestamp() { + return config.getLong("timestamps.lastheal", 0); + } + + public long getLastHealTimestamp() { + return lastHealTimestamp; + } + + public void setLastHealTimestamp(long time) { + lastHealTimestamp = time; + config.setProperty("timestamps.lastheal", time); + config.save(); + } + + private String jail; + + private String _getJail() { + return config.getString("jail"); + } + + public String getJail() { + return jail; + } + + public void setJail(String jail) { + if (jail == null || jail.isEmpty()) { + this.jail = null; + config.removeProperty("jail"); + } else { + this.jail = jail; + config.setProperty("jail", jail); + } + config.save(); + } + + private List mails; + + private List _getMails() { + return config.getStringList("mail"); + } + + public List getMails() { + return mails; + } + + public void setMails(List mails) { + if (mails == null) { + config.removeProperty("mail"); + mails = _getMails(); + } else { + config.setProperty("mail", mails); + } + this.mails = mails; + config.save(); + } + + public void addMail(String mail) { + mails.add(mail); + setMails(mails); + } + + private boolean teleportEnabled; + + private boolean _getTeleportEnabled() { + return config.getBoolean("teleportenabled", true); + } + + public boolean isTeleportEnabled() { + return teleportEnabled; + } + + public void setTeleportEnabled(boolean set) { + teleportEnabled = set; + config.setProperty("teleportenabled", set); + config.save(); + } + + private List ignoredPlayers; + + public List _getIgnoredPlayers() { + return Collections.synchronizedList(config.getStringList("ignore")); + } + + public void setIgnoredPlayers(List players) { + if (players == null || players.isEmpty()) { + ignoredPlayers = Collections.synchronizedList(new ArrayList()); + config.removeProperty("ignore"); + } else { + ignoredPlayers = players; + config.setProperty("ignore", players); + } + config.save(); + } + + @Deprecated + public boolean isIgnoredPlayer(final String userName) { + final IUser user = ess.getUser(userName); + if (user == null || !user.getBase().isOnline()) { + return false; + } + return isIgnoredPlayer(user); + } + + public boolean isIgnoredPlayer(IUser user) { + return (ignoredPlayers.contains(user.getName().toLowerCase(Locale.ENGLISH)) && !user.isIgnoreExempt()); + } + + public void setIgnoredPlayer(IUser user, boolean set) { + if (set) { + ignoredPlayers.add(user.getName().toLowerCase(Locale.ENGLISH)); + } else { + ignoredPlayers.remove(user.getName().toLowerCase(Locale.ENGLISH)); + } + setIgnoredPlayers(ignoredPlayers); + } + + private boolean godmode; + + private boolean _getGodModeEnabled() { + return config.getBoolean("godmode", false); + } + + public boolean isGodModeEnabled() { + return godmode; + } + + public void setGodModeEnabled(boolean set) { + godmode = set; + config.setProperty("godmode", set); + config.save(); + } + + private boolean muted; + + public boolean _getMuted() { + return config.getBoolean("muted", false); + } + + public boolean getMuted() { + return muted; + } + + public boolean isMuted() { + return muted; + } + + public void setMuted(boolean set) { + muted = set; + config.setProperty("muted", set); + config.save(); + } + + private long muteTimeout; + + private long _getMuteTimeout() { + return config.getLong("timestamps.mute", 0); + } + + public long getMuteTimeout() { + return muteTimeout; + } + + public void setMuteTimeout(long time) { + muteTimeout = time; + config.setProperty("timestamps.mute", time); + config.save(); + } + + private boolean jailed; + + private boolean _getJailed() { + return config.getBoolean("jailed", false); + } + + public boolean isJailed() { + return jailed; + } + + public void setJailed(boolean set) { + jailed = set; + config.setProperty("jailed", set); + config.save(); + } + + public boolean toggleJailed() { + boolean ret = !isJailed(); + setJailed(ret); + return ret; + } + + private long jailTimeout; + + private long _getJailTimeout() { + return config.getLong("timestamps.jail", 0); + } + + public long getJailTimeout() { + return jailTimeout; + } + + public void setJailTimeout(long time) { + jailTimeout = time; + config.setProperty("timestamps.jail", time); + config.save(); + } + + private long lastLogin; + + private long _getLastLogin() { + return config.getLong("timestamps.login", 0); + } + + public long getLastLogin() { + return lastLogin; + } + + private void _setLastLogin(long time) { + lastLogin = time; + config.setProperty("timestamps.login", time); + } + + public void setLastLogin(long time) { + _setLastLogin(time); + if (base.getAddress() != null && base.getAddress().getAddress() != null) { + _setLastLoginAddress(base.getAddress().getAddress().getHostAddress()); + } + config.save(); + } + + private long lastLogout; + + private long _getLastLogout() { + return config.getLong("timestamps.logout", 0); + } + + public long getLastLogout() { + return lastLogout; + } + + public void setLastLogout(long time) { + lastLogout = time; + config.setProperty("timestamps.logout", time); + config.save(); + } + + private String lastLoginAddress; + + private String _getLastLoginAddress() { + return config.getString("ipAddress", ""); + } + + public String getLastLoginAddress() { + return lastLoginAddress; + } + + private void _setLastLoginAddress(String address) { + lastLoginAddress = address; + config.setProperty("ipAddress", address); + } + + private boolean afk; + + private boolean _getAfk() { + return config.getBoolean("afk", false); + } + + public boolean isAfk() { + return afk; + } + + public void _setAfk(boolean set) { + afk = set; + config.setProperty("afk", set); + config.save(); + } + + private boolean newplayer; + private String geolocation; + + private String _getGeoLocation() { + return config.getString("geolocation"); + } + + public String getGeoLocation() { + return geolocation; + } + + public void setGeoLocation(String geolocation) { + if (geolocation == null || geolocation.isEmpty()) { + this.geolocation = null; + config.removeProperty("geolocation"); + } else { + this.geolocation = geolocation; + config.setProperty("geolocation", geolocation); + } + config.save(); + } + + private boolean isSocialSpyEnabled; + + private boolean _isSocialSpyEnabled() { + return config.getBoolean("socialspy", false); + } + + public boolean isSocialSpyEnabled() { + return isSocialSpyEnabled; + } + + public void setSocialSpyEnabled(boolean status) { + isSocialSpyEnabled = status; + config.setProperty("socialspy", status); + config.save(); + } + + private boolean isNPC; + + private boolean _isNPC() { + return config.getBoolean("npc", false); + } + + public boolean isNPC() { + return isNPC; + } + + private String lastAccountName = null; + + public String getLastAccountName() { + return lastAccountName; + } + + public String _getLastAccountName() { + return config.getString("lastAccountName", null); + } + + public void setLastAccountName(String lastAccountName) { + this.lastAccountName = lastAccountName; + config.setProperty("lastAccountName", lastAccountName); + config.save(); + ess.getUserMap().trackUUID(getConfigUUID(), lastAccountName, true); + } + + public void setNPC(boolean set) { + isNPC = set; + config.setProperty("npc", set); + config.save(); + } + + private boolean arePowerToolsEnabled; + + public boolean arePowerToolsEnabled() { + return arePowerToolsEnabled; + } + + public void setPowerToolsEnabled(boolean set) { + arePowerToolsEnabled = set; + config.setProperty("powertoolsenabled", set); + config.save(); + } + + public boolean togglePowerToolsEnabled() { + boolean ret = !arePowerToolsEnabled(); + setPowerToolsEnabled(ret); + return ret; + } + + private boolean _arePowerToolsEnabled() { + return config.getBoolean("powertoolsenabled", true); + } + + private Map kitTimestamps; + + private Map _getKitTimestamps() { + + if (config.isConfigurationSection("timestamps.kits")) { + final ConfigurationSection section = config.getConfigurationSection("timestamps.kits"); + final Map timestamps = new HashMap(); + for (String command : section.getKeys(false)) { + if (section.isLong(command)) { + timestamps.put(command.toLowerCase(Locale.ENGLISH), section.getLong(command)); + } else if (section.isInt(command)) { + timestamps.put(command.toLowerCase(Locale.ENGLISH), (long) section.getInt(command)); + } + } + return timestamps; + } + return new HashMap(); + } + + public long getKitTimestamp(String name) { + name = name.replace('.', '_').replace('/', '_'); + if (kitTimestamps != null && kitTimestamps.containsKey(name)) { + return kitTimestamps.get(name); + } + return 0l; + } + + public void setKitTimestamp(final String name, final long time) { + kitTimestamps.put(name.toLowerCase(Locale.ENGLISH), time); + config.setProperty("timestamps.kits", kitTimestamps); + config.save(); + } + + public void setConfigProperty(String node, Object object) { + final String prefix = "info."; + node = prefix + node; + if (object instanceof Map) { + config.setProperty(node, (Map) object); + } else if (object instanceof List) { + config.setProperty(node, (List) object); + } else if (object instanceof Location) { + config.setProperty(node, (Location) object); + } else if (object instanceof ItemStack) { + config.setProperty(node, (ItemStack) object); + } else { + config.setProperty(node, object); + } + config.save(); + } + + public Set getConfigKeys() { + if (config.isConfigurationSection("info")) { + return config.getConfigurationSection("info").getKeys(true); + } + return new HashSet(); + } + + public Map getConfigMap() { + if (config.isConfigurationSection("info")) { + return config.getConfigurationSection("info").getValues(true); + } + return new HashMap(); + } + + public Map getConfigMap(String node) { + if (config.isConfigurationSection("info." + node)) { + return config.getConfigurationSection("info." + node).getValues(true); + } + return new HashMap(); + } + + public UUID getConfigUUID() { + return config.uuid; + } + + public void save() { + config.save(); + } + + public void startTransaction() { + config.startTransaction(); + } + + public void stopTransaction() { + config.stopTransaction(); + } } diff --git a/Essentials/src/com/earth2me/essentials/UserMap.java b/Essentials/src/com/earth2me/essentials/UserMap.java index a53731599..788f6c55c 100644 --- a/Essentials/src/com/earth2me/essentials/UserMap.java +++ b/Essentials/src/com/earth2me/essentials/UserMap.java @@ -4,257 +4,200 @@ import com.earth2me.essentials.utils.StringUtil; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; -import com.google.common.cache.RemovalCause; -import com.google.common.cache.RemovalListener; -import com.google.common.cache.RemovalNotification; import com.google.common.util.concurrent.UncheckedExecutionException; -import java.io.File; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.ConcurrentSkipListMap; -import java.util.concurrent.ConcurrentSkipListSet; -import java.util.concurrent.ExecutionException; import net.ess3.api.IEssentials; import org.bukkit.entity.Player; +import java.io.File; +import java.util.*; +import java.util.concurrent.ConcurrentSkipListMap; +import java.util.concurrent.ConcurrentSkipListSet; +import java.util.concurrent.ExecutionException; -public class UserMap extends CacheLoader implements IConf -{ - private final transient IEssentials ess; - private final transient Cache users; - private final transient ConcurrentSkipListSet keys = new ConcurrentSkipListSet(); - private final transient ConcurrentSkipListMap names = new ConcurrentSkipListMap(); - private final transient ConcurrentSkipListMap> history = new ConcurrentSkipListMap>(); - private UUIDMap uuidMap; - public UserMap(final IEssentials ess) - { - super(); - this.ess = ess; - uuidMap = new UUIDMap(ess); - //RemovalListener remListener = new UserMapRemovalListener(); - //users = CacheBuilder.newBuilder().maximumSize(ess.getSettings().getMaxUserCacheCount()).softValues().removalListener(remListener).build(this); - users = CacheBuilder.newBuilder().maximumSize(ess.getSettings().getMaxUserCacheCount()).softValues().build(this); - } +public class UserMap extends CacheLoader implements IConf { + private final transient IEssentials ess; + private final transient Cache users; + private final transient ConcurrentSkipListSet keys = new ConcurrentSkipListSet(); + private final transient ConcurrentSkipListMap names = new ConcurrentSkipListMap(); + private final transient ConcurrentSkipListMap> history = new ConcurrentSkipListMap>(); + private UUIDMap uuidMap; - private void loadAllUsersAsync(final IEssentials ess) - { - ess.runTaskAsynchronously(new Runnable() - { - @Override - public void run() - { - synchronized (users) - { - final File userdir = new File(ess.getDataFolder(), "userdata"); - if (!userdir.exists()) - { - return; - } - keys.clear(); - users.invalidateAll(); - for (String string : userdir.list()) - { - if (!string.endsWith(".yml")) - { - continue; - } - final String name = string.substring(0, string.length() - 4); - try - { - keys.add(UUID.fromString(name)); - } - catch (IllegalArgumentException ex) - { - //Ignore these users till they rejoin. - } - } - uuidMap.loadAllUsers(names, history); - } - } - }); - } + public UserMap(final IEssentials ess) { + super(); + this.ess = ess; + uuidMap = new UUIDMap(ess); + //RemovalListener remListener = new UserMapRemovalListener(); + //users = CacheBuilder.newBuilder().maximumSize(ess.getSettings().getMaxUserCacheCount()).softValues().removalListener(remListener).build(this); + users = CacheBuilder.newBuilder().maximumSize(ess.getSettings().getMaxUserCacheCount()).softValues().build(this); + } - public boolean userExists(final UUID uuid) - { - return keys.contains(uuid); - } + private void loadAllUsersAsync(final IEssentials ess) { + ess.runTaskAsynchronously(new Runnable() { + @Override + public void run() { + synchronized (users) { + final File userdir = new File(ess.getDataFolder(), "userdata"); + if (!userdir.exists()) { + return; + } + keys.clear(); + users.invalidateAll(); + for (String string : userdir.list()) { + if (!string.endsWith(".yml")) { + continue; + } + final String name = string.substring(0, string.length() - 4); + try { + keys.add(UUID.fromString(name)); + } catch (IllegalArgumentException ex) { + //Ignore these users till they rejoin. + } + } + uuidMap.loadAllUsers(names, history); + } + } + }); + } - public User getUser(final String name) - { - try - { - final String sanitizedName = StringUtil.safeString(name); - if (names.containsKey(sanitizedName)) - { - final UUID uuid = names.get(sanitizedName); - return getUser(uuid); - } + public boolean userExists(final UUID uuid) { + return keys.contains(uuid); + } - final File userFile = getUserFileFromString(sanitizedName); - if (userFile.exists()) - { - ess.getLogger().info("Importing user " + name + " to usermap."); - User user = new User(new OfflinePlayer(sanitizedName, ess.getServer()), ess); - trackUUID(user.getBase().getUniqueId(), user.getName(), true); - return user; - } - return null; - } - catch (UncheckedExecutionException ex) - { - return null; - } - } + public User getUser(final String name) { + try { + final String sanitizedName = StringUtil.safeString(name); + if (names.containsKey(sanitizedName)) { + final UUID uuid = names.get(sanitizedName); + return getUser(uuid); + } - public User getUser(final UUID uuid) - { - try - { - return users.get(uuid.toString()); - } - catch (ExecutionException ex) - { - return null; - } - catch (UncheckedExecutionException ex) - { - return null; - } - } + final File userFile = getUserFileFromString(sanitizedName); + if (userFile.exists()) { + ess.getLogger().info("Importing user " + name + " to usermap."); + User user = new User(new OfflinePlayer(sanitizedName, ess.getServer()), ess); + trackUUID(user.getBase().getUniqueId(), user.getName(), true); + return user; + } + return null; + } catch (UncheckedExecutionException ex) { + return null; + } + } - public void trackUUID(final UUID uuid, final String name, boolean replace) - { - if (uuid != null) - { - keys.add(uuid); - if (name != null && name.length() > 0) - { - final String keyName = StringUtil.safeString(name); - if (!names.containsKey(keyName)) - { - names.put(keyName, uuid); - uuidMap.writeUUIDMap(); - } - else if (!names.get(keyName).equals(uuid)) - { - if (replace) - { - ess.getLogger().info("Found new UUID for " + name + ". Replacing " + names.get(keyName).toString() + " with " + uuid.toString()); - names.put(keyName, uuid); - uuidMap.writeUUIDMap(); - } - else - { - if (ess.getSettings().isDebug()) - { - ess.getLogger().info("Found old UUID for " + name + " (" + uuid.toString() + "). Not adding to usermap."); - } - } - } - } - } - } + public User getUser(final UUID uuid) { + try { + return users.get(uuid.toString()); + } catch (ExecutionException ex) { + return null; + } catch (UncheckedExecutionException ex) { + return null; + } + } - @Override - public User load(final String stringUUID) throws Exception - { - UUID uuid = UUID.fromString(stringUUID); - Player player = ess.getServer().getPlayer(uuid); - if (player != null) - { - final User user = new User(player, ess); - trackUUID(uuid, user.getName(), true); - return user; - } + public void trackUUID(final UUID uuid, final String name, boolean replace) { + if (uuid != null) { + keys.add(uuid); + if (name != null && name.length() > 0) { + final String keyName = StringUtil.safeString(name); + if (!names.containsKey(keyName)) { + names.put(keyName, uuid); + uuidMap.writeUUIDMap(); + } else if (!names.get(keyName).equals(uuid)) { + if (replace) { + ess.getLogger().info("Found new UUID for " + name + ". Replacing " + names.get(keyName).toString() + " with " + uuid.toString()); + names.put(keyName, uuid); + uuidMap.writeUUIDMap(); + } else { + if (ess.getSettings().isDebug()) { + ess.getLogger().info("Found old UUID for " + name + " (" + uuid.toString() + "). Not adding to usermap."); + } + } + } + } + } + } - final File userFile = getUserFileFromID(uuid); + @Override + public User load(final String stringUUID) throws Exception { + UUID uuid = UUID.fromString(stringUUID); + Player player = ess.getServer().getPlayer(uuid); + if (player != null) { + final User user = new User(player, ess); + trackUUID(uuid, user.getName(), true); + return user; + } - if (userFile.exists()) - { - player = new OfflinePlayer(uuid, ess.getServer()); - final User user = new User(player, ess); - ((OfflinePlayer)player).setName(user.getLastAccountName()); - trackUUID(uuid, user.getName(), false); - return user; - } + final File userFile = getUserFileFromID(uuid); - throw new Exception("User not found!"); - } + if (userFile.exists()) { + player = new OfflinePlayer(uuid, ess.getServer()); + final User user = new User(player, ess); + ((OfflinePlayer) player).setName(user.getLastAccountName()); + trackUUID(uuid, user.getName(), false); + return user; + } - @Override - public void reloadConfig() - { - getUUIDMap().forceWriteUUIDMap(); - loadAllUsersAsync(ess); - } + throw new Exception("User not found!"); + } - public void invalidateAll() - { - users.invalidateAll(); - } + @Override + public void reloadConfig() { + getUUIDMap().forceWriteUUIDMap(); + loadAllUsersAsync(ess); + } - public void removeUser(final String name) - { - if (names == null) - { - ess.getLogger().warning("Name collection is null, cannot remove user."); - return; - } - UUID uuid = names.get(name); - if (uuid != null) - { - keys.remove(uuid); - users.invalidate(uuid); - } - names.remove(name); - names.remove(StringUtil.safeString(name)); - } + public void invalidateAll() { + users.invalidateAll(); + } - public Set getAllUniqueUsers() - { - return Collections.unmodifiableSet(keys.clone()); - } + public void removeUser(final String name) { + if (names == null) { + ess.getLogger().warning("Name collection is null, cannot remove user."); + return; + } + UUID uuid = names.get(name); + if (uuid != null) { + keys.remove(uuid); + users.invalidate(uuid); + } + names.remove(name); + names.remove(StringUtil.safeString(name)); + } - public int getUniqueUsers() - { - return keys.size(); - } + public Set getAllUniqueUsers() { + return Collections.unmodifiableSet(keys.clone()); + } - protected ConcurrentSkipListMap getNames() - { - return names; - } + public int getUniqueUsers() { + return keys.size(); + } - protected ConcurrentSkipListMap> getHistory() - { - return history; - } + protected ConcurrentSkipListMap getNames() { + return names; + } - public List getUserHistory(final UUID uuid) - { - return history.get(uuid); - } + protected ConcurrentSkipListMap> getHistory() { + return history; + } - public UUIDMap getUUIDMap() - { - return uuidMap; - } + public List getUserHistory(final UUID uuid) { + return history.get(uuid); + } - private File getUserFileFromID(final UUID uuid) - { - final File userFolder = new File(ess.getDataFolder(), "userdata"); - return new File(userFolder, uuid.toString() + ".yml"); - } + public UUIDMap getUUIDMap() { + return uuidMap; + } - public File getUserFileFromString(final String name) - { - final File userFolder = new File(ess.getDataFolder(), "userdata"); - return new File(userFolder, StringUtil.sanitizeFileName(name) + ".yml"); - } + private File getUserFileFromID(final UUID uuid) { + final File userFolder = new File(ess.getDataFolder(), "userdata"); + return new File(userFolder, uuid.toString() + ".yml"); + } + + public File getUserFileFromString(final String name) { + final File userFolder = new File(ess.getDataFolder(), "userdata"); + return new File(userFolder, StringUtil.sanitizeFileName(name) + ".yml"); + } // class UserMapRemovalListener implements RemovalListener // { // @Override diff --git a/Essentials/src/com/earth2me/essentials/Warps.java b/Essentials/src/com/earth2me/essentials/Warps.java index 3e0f93a55..bff2f970f 100644 --- a/Essentials/src/com/earth2me/essentials/Warps.java +++ b/Essentials/src/com/earth2me/essentials/Warps.java @@ -1,180 +1,149 @@ package com.earth2me.essentials; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.commands.WarpNotFoundException; import com.earth2me.essentials.utils.StringUtil; -import java.io.File; -import java.io.IOException; -import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; import net.ess3.api.InvalidNameException; import net.ess3.api.InvalidWorldException; import org.bukkit.Location; import org.bukkit.Server; +import java.io.File; +import java.io.IOException; +import java.util.*; +import java.util.logging.Level; +import java.util.logging.Logger; -public class Warps implements IConf, net.ess3.api.IWarps -{ - private static final Logger logger = Logger.getLogger("Essentials"); - private final Map warpPoints = new HashMap(); - private final File warpsFolder; - private final Server server; +import static com.earth2me.essentials.I18n.tl; - public Warps(Server server, File dataFolder) - { - this.server = server; - warpsFolder = new File(dataFolder, "warps"); - if (!warpsFolder.exists()) - { - warpsFolder.mkdirs(); - } - reloadConfig(); - } - @Override - public boolean isEmpty() - { - return warpPoints.isEmpty(); - } +public class Warps implements IConf, net.ess3.api.IWarps { + private static final Logger logger = Logger.getLogger("Essentials"); + private final Map warpPoints = new HashMap(); + private final File warpsFolder; + private final Server server; - @Override - public Collection getList() - { - final List keys = new ArrayList(); - for (StringIgnoreCase stringIgnoreCase : warpPoints.keySet()) - { - keys.add(stringIgnoreCase.getString()); - } - Collections.sort(keys, String.CASE_INSENSITIVE_ORDER); - return keys; - } + public Warps(Server server, File dataFolder) { + this.server = server; + warpsFolder = new File(dataFolder, "warps"); + if (!warpsFolder.exists()) { + warpsFolder.mkdirs(); + } + reloadConfig(); + } - @Override - public Location getWarp(String warp) throws WarpNotFoundException, InvalidWorldException - { - EssentialsConf conf = warpPoints.get(new StringIgnoreCase(warp)); - if (conf == null) - { - throw new WarpNotFoundException(); - } - return conf.getLocation(null, server); - } + @Override + public boolean isEmpty() { + return warpPoints.isEmpty(); + } - @Override - public void setWarp(String name, Location loc) throws Exception - { - String filename = StringUtil.sanitizeFileName(name); - EssentialsConf conf = warpPoints.get(new StringIgnoreCase(name)); - if (conf == null) - { - File confFile = new File(warpsFolder, filename + ".yml"); - if (confFile.exists()) - { - throw new Exception(tl("similarWarpExist")); - } - conf = new EssentialsConf(confFile); - warpPoints.put(new StringIgnoreCase(name), conf); - } - conf.setProperty(null, loc); - conf.setProperty("name", name); - try - { - conf.saveWithError(); - } - catch (IOException ex) - { - throw new IOException(tl("invalidWarpName")); - } - } + @Override + public Collection getList() { + final List keys = new ArrayList(); + for (StringIgnoreCase stringIgnoreCase : warpPoints.keySet()) { + keys.add(stringIgnoreCase.getString()); + } + Collections.sort(keys, String.CASE_INSENSITIVE_ORDER); + return keys; + } - @Override - public void removeWarp(String name) throws Exception - { - EssentialsConf conf = warpPoints.get(new StringIgnoreCase(name)); - if (conf == null) - { - throw new Exception(tl("warpNotExist")); - } - if (!conf.getFile().delete()) - { - throw new Exception(tl("warpDeleteError")); - } - warpPoints.remove(new StringIgnoreCase(name)); - } + @Override + public Location getWarp(String warp) throws WarpNotFoundException, InvalidWorldException { + EssentialsConf conf = warpPoints.get(new StringIgnoreCase(warp)); + if (conf == null) { + throw new WarpNotFoundException(); + } + return conf.getLocation(null, server); + } - @Override - public final void reloadConfig() - { - warpPoints.clear(); - File[] listOfFiles = warpsFolder.listFiles(); - if (listOfFiles.length >= 1) - { - for (int i = 0; i < listOfFiles.length; i++) - { - String filename = listOfFiles[i].getName(); - if (listOfFiles[i].isFile() && filename.endsWith(".yml")) - { - try - { - EssentialsConf conf = new EssentialsConf(listOfFiles[i]); - conf.load(); - String name = conf.getString("name"); - if (name != null) - { - warpPoints.put(new StringIgnoreCase(name), conf); - } - } - catch (Exception ex) - { - logger.log(Level.WARNING, tl("loadWarpError", filename), ex); - } - } - } - } - } + @Override + public void setWarp(String name, Location loc) throws Exception { + String filename = StringUtil.sanitizeFileName(name); + EssentialsConf conf = warpPoints.get(new StringIgnoreCase(name)); + if (conf == null) { + File confFile = new File(warpsFolder, filename + ".yml"); + if (confFile.exists()) { + throw new Exception(tl("similarWarpExist")); + } + conf = new EssentialsConf(confFile); + warpPoints.put(new StringIgnoreCase(name), conf); + } + conf.setProperty(null, loc); + conf.setProperty("name", name); + try { + conf.saveWithError(); + } catch (IOException ex) { + throw new IOException(tl("invalidWarpName")); + } + } - //This is here for future 3.x api support. Not implemented here becasue storage is handled differently - @Override - public File getWarpFile(String name) throws InvalidNameException - { - throw new UnsupportedOperationException("Not supported yet."); - } + @Override + public void removeWarp(String name) throws Exception { + EssentialsConf conf = warpPoints.get(new StringIgnoreCase(name)); + if (conf == null) { + throw new Exception(tl("warpNotExist")); + } + if (!conf.getFile().delete()) { + throw new Exception(tl("warpDeleteError")); + } + warpPoints.remove(new StringIgnoreCase(name)); + } - @Override - public int getCount() - { - return getList().size(); - } + @Override + public final void reloadConfig() { + warpPoints.clear(); + File[] listOfFiles = warpsFolder.listFiles(); + if (listOfFiles.length >= 1) { + for (int i = 0; i < listOfFiles.length; i++) { + String filename = listOfFiles[i].getName(); + if (listOfFiles[i].isFile() && filename.endsWith(".yml")) { + try { + EssentialsConf conf = new EssentialsConf(listOfFiles[i]); + conf.load(); + String name = conf.getString("name"); + if (name != null) { + warpPoints.put(new StringIgnoreCase(name), conf); + } + } catch (Exception ex) { + logger.log(Level.WARNING, tl("loadWarpError", filename), ex); + } + } + } + } + } - private static class StringIgnoreCase - { - private final String string; + //This is here for future 3.x api support. Not implemented here becasue storage is handled differently + @Override + public File getWarpFile(String name) throws InvalidNameException { + throw new UnsupportedOperationException("Not supported yet."); + } - public StringIgnoreCase(String string) - { - this.string = string; - } + @Override + public int getCount() { + return getList().size(); + } - @Override - public int hashCode() - { - return getString().toLowerCase(Locale.ENGLISH).hashCode(); - } + private static class StringIgnoreCase { + private final String string; - @Override - public boolean equals(Object o) - { - if (o instanceof StringIgnoreCase) - { - return getString().equalsIgnoreCase(((StringIgnoreCase)o).getString()); - } - return false; - } + public StringIgnoreCase(String string) { + this.string = string; + } - public String getString() - { - return 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/Worth.java b/Essentials/src/com/earth2me/essentials/Worth.java index 91394a35a..d029f3f59 100644 --- a/Essentials/src/com/earth2me/essentials/Worth.java +++ b/Essentials/src/com/earth2me/essentials/Worth.java @@ -1,176 +1,141 @@ package com.earth2me.essentials; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.commands.NotEnoughArgumentsException; -import java.io.File; -import java.math.BigDecimal; -import java.util.Locale; -import java.util.logging.Logger; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.inventory.ItemStack; +import java.io.File; +import java.math.BigDecimal; +import java.util.Locale; -public class Worth implements IConf -{ - private final EssentialsConf config; +import static com.earth2me.essentials.I18n.tl; - public Worth(File dataFolder) - { - config = new EssentialsConf(new File(dataFolder, "worth.yml")); - config.setTemplateName("/worth.yml"); - config.load(); - } - public BigDecimal getPrice(ItemStack itemStack) - { - String itemname = itemStack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""); - BigDecimal result; +public class Worth implements IConf { + private final EssentialsConf config; - //First check for matches with item name - result = config.getBigDecimal("worth." + itemname + "." + itemStack.getDurability(), BigDecimal.ONE.negate()); - if (result.signum() < 0) - { - final ConfigurationSection itemNameMatch = config.getConfigurationSection("worth." + itemname); - if (itemNameMatch != null && itemNameMatch.getKeys(false).size() == 1) - { - result = config.getBigDecimal("worth." + itemname + ".0", BigDecimal.ONE.negate()); - } - } - if (result.signum() < 0) - { - result = config.getBigDecimal("worth." + itemname + ".*", BigDecimal.ONE.negate()); - } - if (result.signum() < 0) - { - result = config.getBigDecimal("worth." + itemname, BigDecimal.ONE.negate()); - } + public Worth(File dataFolder) { + config = new EssentialsConf(new File(dataFolder, "worth.yml")); + config.setTemplateName("/worth.yml"); + config.load(); + } - //Now we should check for item ID - if (result.signum() < 0) - { - result = config.getBigDecimal("worth." + itemStack.getTypeId() + "." + itemStack.getDurability(), BigDecimal.ONE.negate()); - } - if (result.signum() < 0) - { - final ConfigurationSection itemNumberMatch = config.getConfigurationSection("worth." + itemStack.getTypeId()); - if (itemNumberMatch != null && itemNumberMatch.getKeys(false).size() == 1) - { - result = config.getBigDecimal("worth." + itemStack.getTypeId() + ".0", BigDecimal.ONE.negate()); - } - } - if (result.signum() < 0) - { - result = config.getBigDecimal("worth." + itemStack.getTypeId() + ".*", BigDecimal.ONE.negate()); - } - if (result.signum() < 0) - { - result = config.getBigDecimal("worth." + itemStack.getTypeId(), BigDecimal.ONE.negate()); - } + public BigDecimal getPrice(ItemStack itemStack) { + String itemname = itemStack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""); + BigDecimal result; - //This is to match the old worth syntax - if (result.signum() < 0) - { - result = config.getBigDecimal("worth-" + itemStack.getTypeId(), BigDecimal.ONE.negate()); - } - if (result.signum() < 0) - { - return null; - } - return result; - } + //First check for matches with item name + result = config.getBigDecimal("worth." + itemname + "." + itemStack.getDurability(), BigDecimal.ONE.negate()); + if (result.signum() < 0) { + final ConfigurationSection itemNameMatch = config.getConfigurationSection("worth." + itemname); + if (itemNameMatch != null && itemNameMatch.getKeys(false).size() == 1) { + result = config.getBigDecimal("worth." + itemname + ".0", BigDecimal.ONE.negate()); + } + } + if (result.signum() < 0) { + result = config.getBigDecimal("worth." + itemname + ".*", BigDecimal.ONE.negate()); + } + if (result.signum() < 0) { + result = config.getBigDecimal("worth." + itemname, BigDecimal.ONE.negate()); + } - public int getAmount(IEssentials ess, User user, ItemStack is, String[] args, boolean isBulkSell) throws Exception - { - if (is == null || is.getType() == Material.AIR) - { - throw new Exception(tl("itemSellAir")); - } - int id = is.getTypeId(); - int amount = 0; + //Now we should check for item ID + if (result.signum() < 0) { + result = config.getBigDecimal("worth." + itemStack.getTypeId() + "." + itemStack.getDurability(), BigDecimal.ONE.negate()); + } + if (result.signum() < 0) { + final ConfigurationSection itemNumberMatch = config.getConfigurationSection("worth." + itemStack.getTypeId()); + if (itemNumberMatch != null && itemNumberMatch.getKeys(false).size() == 1) { + result = config.getBigDecimal("worth." + itemStack.getTypeId() + ".0", BigDecimal.ONE.negate()); + } + } + if (result.signum() < 0) { + result = config.getBigDecimal("worth." + itemStack.getTypeId() + ".*", BigDecimal.ONE.negate()); + } + if (result.signum() < 0) { + result = config.getBigDecimal("worth." + itemStack.getTypeId(), BigDecimal.ONE.negate()); + } - if (args.length > 1) - { - try - { - amount = Integer.parseInt(args[1].replaceAll("[^0-9]", "")); - } - catch (NumberFormatException ex) - { - throw new NotEnoughArgumentsException(ex); - } - if (args[1].startsWith("-")) - { - amount = -amount; - } - } + //This is to match the old worth syntax + if (result.signum() < 0) { + result = config.getBigDecimal("worth-" + itemStack.getTypeId(), BigDecimal.ONE.negate()); + } + if (result.signum() < 0) { + return null; + } + return result; + } - boolean stack = args.length > 1 && args[1].endsWith("s"); - boolean requireStack = ess.getSettings().isTradeInStacks(id); + public int getAmount(IEssentials ess, User user, ItemStack is, String[] args, boolean isBulkSell) throws Exception { + if (is == null || is.getType() == Material.AIR) { + throw new Exception(tl("itemSellAir")); + } + int id = is.getTypeId(); + int amount = 0; - if (requireStack && !stack) - { - throw new Exception(tl("itemMustBeStacked")); - } + if (args.length > 1) { + try { + amount = Integer.parseInt(args[1].replaceAll("[^0-9]", "")); + } catch (NumberFormatException ex) { + throw new NotEnoughArgumentsException(ex); + } + if (args[1].startsWith("-")) { + amount = -amount; + } + } - int max = 0; - for (ItemStack s : user.getBase().getInventory().getContents()) - { - if (s == null || !s.isSimilar(is)) - { - continue; - } - max += s.getAmount(); - } + boolean stack = args.length > 1 && args[1].endsWith("s"); + boolean requireStack = ess.getSettings().isTradeInStacks(id); - if (stack) - { - amount *= is.getType().getMaxStackSize(); - } - if (amount < 1) - { - amount += max; - } + if (requireStack && !stack) { + throw new Exception(tl("itemMustBeStacked")); + } - if (requireStack) - { - amount -= amount % is.getType().getMaxStackSize(); - } - if (amount > max || amount < 1) - { - if (!isBulkSell) - { - user.sendMessage(tl("itemNotEnough2")); - user.sendMessage(tl("itemNotEnough3")); - throw new Exception(tl("itemNotEnough1")); - } - else - { - return amount; - } - } + int max = 0; + for (ItemStack s : user.getBase().getInventory().getContents()) { + if (s == null || !s.isSimilar(is)) { + continue; + } + max += s.getAmount(); + } - return amount; - } + if (stack) { + amount *= is.getType().getMaxStackSize(); + } + if (amount < 1) { + amount += max; + } - public void setPrice(ItemStack itemStack, double price) - { - if (itemStack.getType().getData() == null) - { - config.setProperty("worth." + itemStack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""), price); - } - else - { - // Bukkit-bug: getDurability still contains the correct value, while getData().getData() is 0. - config.setProperty("worth." + itemStack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", "") + "." + itemStack.getDurability(), price); - } - config.removeProperty("worth-" + itemStack.getTypeId()); - config.save(); - } + if (requireStack) { + amount -= amount % is.getType().getMaxStackSize(); + } + if (amount > max || amount < 1) { + if (!isBulkSell) { + user.sendMessage(tl("itemNotEnough2")); + user.sendMessage(tl("itemNotEnough3")); + throw new Exception(tl("itemNotEnough1")); + } else { + return amount; + } + } - @Override - public void reloadConfig() - { - config.load(); - } + return amount; + } + + public void setPrice(ItemStack itemStack, double price) { + if (itemStack.getType().getData() == null) { + config.setProperty("worth." + itemStack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""), price); + } else { + // Bukkit-bug: getDurability still contains the correct value, while getData().getData() is 0. + config.setProperty("worth." + itemStack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", "") + "." + itemStack.getDurability(), price); + } + config.removeProperty("worth-" + itemStack.getTypeId()); + config.save(); + } + + @Override + public void reloadConfig() { + config.load(); + } } diff --git a/Essentials/src/com/earth2me/essentials/api/Economy.java b/Essentials/src/com/earth2me/essentials/api/Economy.java index 35c733ae0..cbd6215b2 100644 --- a/Essentials/src/com/earth2me/essentials/api/Economy.java +++ b/Essentials/src/com/earth2me/essentials/api/Economy.java @@ -1,464 +1,402 @@ package com.earth2me.essentials.api; -import com.earth2me.essentials.EssentialsConf; import com.earth2me.essentials.EssentialsUserConf; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.Trade; import com.earth2me.essentials.User; -import static com.earth2me.essentials.api.Economy.add; -import static com.earth2me.essentials.api.Economy.divide; -import static com.earth2me.essentials.api.Economy.format; -import static com.earth2me.essentials.api.Economy.getMoneyExact; -import static com.earth2me.essentials.api.Economy.hasEnough; -import static com.earth2me.essentials.api.Economy.hasLess; -import static com.earth2me.essentials.api.Economy.hasMore; -import static com.earth2me.essentials.api.Economy.multiply; -import static com.earth2me.essentials.api.Economy.setMoney; -import static com.earth2me.essentials.api.Economy.substract; import com.earth2me.essentials.utils.NumberUtil; import com.earth2me.essentials.utils.StringUtil; import com.google.common.base.Charsets; +import net.ess3.api.IEssentials; +import net.ess3.api.MaxMoneyException; + import java.io.File; import java.math.BigDecimal; import java.math.MathContext; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; -import net.ess3.api.IEssentials; -import net.ess3.api.MaxMoneyException; /** * Instead of using this api directly, we recommend to use the register plugin: http://bit.ly/RegisterMethod */ -public class Economy -{ - public Economy() - { - } - private static final Logger logger = Logger.getLogger("Essentials"); - private static IEssentials ess; - private static final String noCallBeforeLoad = "Essentials API is called before Essentials is loaded."; - public static final MathContext MATH_CONTEXT = MathContext.DECIMAL128; +public class Economy { + public Economy() { + } - /** - * @param aEss the ess to set - */ - public static void setEss(IEssentials aEss) - { - ess = aEss; - } + private static final Logger logger = Logger.getLogger("Essentials"); + private static IEssentials ess; + private static final String noCallBeforeLoad = "Essentials API is called before Essentials is loaded."; + public static final MathContext MATH_CONTEXT = MathContext.DECIMAL128; - private static void createNPCFile(String name) - { - File folder = new File(ess.getDataFolder(), "userdata"); - name = StringUtil.safeString(name); - if (!folder.exists()) - { - folder.mkdirs(); - } - UUID npcUUID = UUID.nameUUIDFromBytes(("NPC:" + name).getBytes(Charsets.UTF_8)); - EssentialsUserConf npcConfig = new EssentialsUserConf(name, npcUUID, new File(folder, npcUUID.toString() + ".yml")); - npcConfig.load(); - npcConfig.setProperty("npc", true); - npcConfig.setProperty("lastAccountName", name); - npcConfig.setProperty("money", ess.getSettings().getStartingBalance()); - npcConfig.forceSave(); - ess.getUserMap().trackUUID(npcUUID, name, false); - } + /** + * @param aEss the ess to set + */ + public static void setEss(IEssentials aEss) { + ess = aEss; + } - private static void deleteNPC(String name) - { - User user = ess.getUser(name); - user.reset(); - } + private static void createNPCFile(String name) { + File folder = new File(ess.getDataFolder(), "userdata"); + name = StringUtil.safeString(name); + if (!folder.exists()) { + folder.mkdirs(); + } + UUID npcUUID = UUID.nameUUIDFromBytes(("NPC:" + name).getBytes(Charsets.UTF_8)); + EssentialsUserConf npcConfig = new EssentialsUserConf(name, npcUUID, new File(folder, npcUUID.toString() + ".yml")); + npcConfig.load(); + npcConfig.setProperty("npc", true); + npcConfig.setProperty("lastAccountName", name); + npcConfig.setProperty("money", ess.getSettings().getStartingBalance()); + npcConfig.forceSave(); + ess.getUserMap().trackUUID(npcUUID, name, false); + } - private static User getUserByName(String name) - { - if (ess == null) - { - throw new RuntimeException(noCallBeforeLoad); - } - if (name == null) - { - throw new RuntimeException("Economy username cannot be null"); - } - return ess.getUser(name); - } + private static void deleteNPC(String name) { + User user = ess.getUser(name); + user.reset(); + } - /** - * Returns the balance of a user - * - * @param name Name of the user - * @return balance - * @throws UserDoesNotExistException - */ - @Deprecated - public static double getMoney(String name) throws UserDoesNotExistException - { - return getMoneyExact(name).doubleValue(); - } + private static User getUserByName(String name) { + if (ess == null) { + throw new RuntimeException(noCallBeforeLoad); + } + if (name == null) { + throw new RuntimeException("Economy username cannot be null"); + } + return ess.getUser(name); + } - public static BigDecimal getMoneyExact(String name) throws UserDoesNotExistException - { - User user = getUserByName(name); - if (user == null) - { - throw new UserDoesNotExistException(name); - } - return user.getMoney(); - } + /** + * Returns the balance of a user + * + * @param name Name of the user + * + * @return balance + * + * @throws UserDoesNotExistException + */ + @Deprecated + public static double getMoney(String name) throws UserDoesNotExistException { + return getMoneyExact(name).doubleValue(); + } - /** - * 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 - */ - @Deprecated - public static void setMoney(String name, double balance) throws UserDoesNotExistException, NoLoanPermittedException - { - try - { - setMoney(name, BigDecimal.valueOf(balance)); - } - catch (ArithmeticException e) - { - logger.log(Level.WARNING, "Failed to set balance of " + name + " to " + balance + ": " + e.getMessage(), e); - } - } + public static BigDecimal getMoneyExact(String name) throws UserDoesNotExistException { + User user = getUserByName(name); + if (user == null) { + throw new UserDoesNotExistException(name); + } + return user.getMoney(); + } - public static void setMoney(String name, BigDecimal balance) throws UserDoesNotExistException, NoLoanPermittedException - { - User user = getUserByName(name); - if (user == null) - { - throw new UserDoesNotExistException(name); - } - if (balance.compareTo(ess.getSettings().getMinMoney()) < 0) - { - throw new NoLoanPermittedException(); - } - if (balance.signum() < 0 && !user.isAuthorized("essentials.eco.loan")) - { - throw new NoLoanPermittedException(); - } - try - { - user.setMoney(balance); - } - catch (MaxMoneyException ex) - { - //TODO: Update API to show max balance errors - } - Trade.log("API", "Set", "API", name, new Trade(balance, ess), null, null, null, ess); - } + /** + * 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 + */ + @Deprecated + public static void setMoney(String name, double balance) throws UserDoesNotExistException, NoLoanPermittedException { + try { + setMoney(name, BigDecimal.valueOf(balance)); + } catch (ArithmeticException e) { + logger.log(Level.WARNING, "Failed to set balance of " + name + " to " + balance + ": " + e.getMessage(), e); + } + } - /** - * 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 - */ - @Deprecated - public static void add(String name, double amount) throws UserDoesNotExistException, NoLoanPermittedException - { - try - { - add(name, BigDecimal.valueOf(amount)); - } - catch (ArithmeticException e) - { - logger.log(Level.WARNING, "Failed to add " + amount + " to balance of " + name + ": " + e.getMessage(), e); - } - } + public static void setMoney(String name, BigDecimal balance) throws UserDoesNotExistException, NoLoanPermittedException { + User user = getUserByName(name); + if (user == null) { + throw new UserDoesNotExistException(name); + } + if (balance.compareTo(ess.getSettings().getMinMoney()) < 0) { + throw new NoLoanPermittedException(); + } + if (balance.signum() < 0 && !user.isAuthorized("essentials.eco.loan")) { + throw new NoLoanPermittedException(); + } + try { + user.setMoney(balance); + } catch (MaxMoneyException ex) { + //TODO: Update API to show max balance errors + } + Trade.log("API", "Set", "API", name, new Trade(balance, ess), null, null, null, ess); + } - public static void add(String name, BigDecimal amount) throws UserDoesNotExistException, NoLoanPermittedException, ArithmeticException - { - BigDecimal result = getMoneyExact(name).add(amount, MATH_CONTEXT); - setMoney(name, result); - Trade.log("API", "Add", "API", name, new Trade(amount, ess), null, null, null, ess); - } + /** + * 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 + */ + @Deprecated + public static void add(String name, double amount) throws UserDoesNotExistException, NoLoanPermittedException { + try { + add(name, BigDecimal.valueOf(amount)); + } catch (ArithmeticException e) { + logger.log(Level.WARNING, "Failed to add " + amount + " to balance of " + name + ": " + e.getMessage(), e); + } + } - /** - * 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 - */ - @Deprecated - public static void subtract(String name, double amount) throws UserDoesNotExistException, NoLoanPermittedException - { - try - { - substract(name, BigDecimal.valueOf(amount)); - } - catch (ArithmeticException e) - { - logger.log(Level.WARNING, "Failed to substract " + amount + " of balance of " + name + ": " + e.getMessage(), e); - } - } + public static void add(String name, BigDecimal amount) throws UserDoesNotExistException, NoLoanPermittedException, ArithmeticException { + BigDecimal result = getMoneyExact(name).add(amount, MATH_CONTEXT); + setMoney(name, result); + Trade.log("API", "Add", "API", name, new Trade(amount, ess), null, null, null, ess); + } - public static void substract(String name, BigDecimal amount) throws UserDoesNotExistException, NoLoanPermittedException, ArithmeticException - { - BigDecimal result = getMoneyExact(name).subtract(amount, MATH_CONTEXT); - setMoney(name, result); - Trade.log("API", "Subtract", "API", name, new Trade(amount, ess), null, null, null, ess); - } + /** + * 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 + */ + @Deprecated + public static void subtract(String name, double amount) throws UserDoesNotExistException, NoLoanPermittedException { + try { + substract(name, BigDecimal.valueOf(amount)); + } catch (ArithmeticException e) { + logger.log(Level.WARNING, "Failed to substract " + amount + " of balance of " + name + ": " + e.getMessage(), e); + } + } - /** - * 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 - */ - @Deprecated - public static void divide(String name, double amount) throws UserDoesNotExistException, NoLoanPermittedException - { - try - { - divide(name, BigDecimal.valueOf(amount)); - } - catch (ArithmeticException e) - { - logger.log(Level.WARNING, "Failed to divide balance of " + name + " by " + amount + ": " + e.getMessage(), e); - } - } + public static void substract(String name, BigDecimal amount) throws UserDoesNotExistException, NoLoanPermittedException, ArithmeticException { + BigDecimal result = getMoneyExact(name).subtract(amount, MATH_CONTEXT); + setMoney(name, result); + Trade.log("API", "Subtract", "API", name, new Trade(amount, ess), null, null, null, ess); + } - public static void divide(String name, BigDecimal amount) throws UserDoesNotExistException, NoLoanPermittedException, ArithmeticException - { - BigDecimal result = getMoneyExact(name).divide(amount, MATH_CONTEXT); - setMoney(name, result); - Trade.log("API", "Divide", "API", name, new Trade(amount, ess), null, null, null, ess); - } + /** + * 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 + */ + @Deprecated + public static void divide(String name, double amount) throws UserDoesNotExistException, NoLoanPermittedException { + try { + divide(name, BigDecimal.valueOf(amount)); + } catch (ArithmeticException e) { + logger.log(Level.WARNING, "Failed to divide balance of " + name + " by " + amount + ": " + e.getMessage(), e); + } + } - /** - * 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 - */ - @Deprecated - public static void multiply(String name, double amount) throws UserDoesNotExistException, NoLoanPermittedException - { - try - { - multiply(name, BigDecimal.valueOf(amount)); - } - catch (ArithmeticException e) - { - logger.log(Level.WARNING, "Failed to multiply balance of " + name + " by " + amount + ": " + e.getMessage(), e); - } - } + public static void divide(String name, BigDecimal amount) throws UserDoesNotExistException, NoLoanPermittedException, ArithmeticException { + BigDecimal result = getMoneyExact(name).divide(amount, MATH_CONTEXT); + setMoney(name, result); + Trade.log("API", "Divide", "API", name, new Trade(amount, ess), null, null, null, ess); + } - public static void multiply(String name, BigDecimal amount) throws UserDoesNotExistException, NoLoanPermittedException, ArithmeticException - { - BigDecimal result = getMoneyExact(name).multiply(amount, MATH_CONTEXT); - setMoney(name, result); - Trade.log("API", "Multiply", "API", name, new Trade(amount, ess), null, null, null, ess); - } + /** + * 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 + */ + @Deprecated + public static void multiply(String name, double amount) throws UserDoesNotExistException, NoLoanPermittedException { + try { + multiply(name, BigDecimal.valueOf(amount)); + } catch (ArithmeticException e) { + logger.log(Level.WARNING, "Failed to multiply balance of " + name + " by " + amount + ": " + e.getMessage(), e); + } + } - /** - * 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); - } - setMoney(name, ess.getSettings().getStartingBalance()); - Trade.log("API", "Reset", "API", name, new Trade(BigDecimal.ZERO, ess), null, null, null, ess); - } + public static void multiply(String name, BigDecimal amount) throws UserDoesNotExistException, NoLoanPermittedException, ArithmeticException { + BigDecimal result = getMoneyExact(name).multiply(amount, MATH_CONTEXT); + setMoney(name, result); + Trade.log("API", "Multiply", "API", name, new Trade(amount, ess), null, null, null, ess); + } - /** - * @param name Name of the user - * @param amount The amount of money the user should have - * @return true, if the user has more or an equal amount of money - * @throws UserDoesNotExistException If a user by that name does not exists - */ - @Deprecated - public static boolean hasEnough(String name, double amount) throws UserDoesNotExistException - { - try - { - return hasEnough(name, BigDecimal.valueOf(amount)); - } - catch (ArithmeticException e) - { - logger.log(Level.WARNING, "Failed to compare balance of " + name + " with " + amount + ": " + e.getMessage(), e); - return false; - } - } + /** + * 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); + } + setMoney(name, ess.getSettings().getStartingBalance()); + Trade.log("API", "Reset", "API", name, new Trade(BigDecimal.ZERO, ess), null, null, null, ess); + } - public static boolean hasEnough(String name, BigDecimal amount) throws UserDoesNotExistException, ArithmeticException - { - return amount.compareTo(getMoneyExact(name)) <= 0; - } + /** + * @param name Name of the user + * @param amount The amount of money the user should have + * + * @return true, if the user has more or an equal amount of money + * + * @throws UserDoesNotExistException If a user by that name does not exists + */ + @Deprecated + public static boolean hasEnough(String name, double amount) throws UserDoesNotExistException { + try { + return hasEnough(name, BigDecimal.valueOf(amount)); + } catch (ArithmeticException e) { + logger.log(Level.WARNING, "Failed to compare balance of " + name + " with " + amount + ": " + e.getMessage(), e); + return false; + } + } - /** - * @param name Name of the user - * @param amount The amount of money the user should have - * @return true, if the user has more money - * @throws UserDoesNotExistException If a user by that name does not exists - */ - @Deprecated - public static boolean hasMore(String name, double amount) throws UserDoesNotExistException - { - try - { - return hasMore(name, BigDecimal.valueOf(amount)); - } - catch (ArithmeticException e) - { - logger.log(Level.WARNING, "Failed to compare balance of " + name + " with " + amount + ": " + e.getMessage(), e); - return false; - } - } + public static boolean hasEnough(String name, BigDecimal amount) throws UserDoesNotExistException, ArithmeticException { + return amount.compareTo(getMoneyExact(name)) <= 0; + } - public static boolean hasMore(String name, BigDecimal amount) throws UserDoesNotExistException, ArithmeticException - { - return amount.compareTo(getMoneyExact(name)) < 0; - } + /** + * @param name Name of the user + * @param amount The amount of money the user should have + * + * @return true, if the user has more money + * + * @throws UserDoesNotExistException If a user by that name does not exists + */ + @Deprecated + public static boolean hasMore(String name, double amount) throws UserDoesNotExistException { + try { + return hasMore(name, BigDecimal.valueOf(amount)); + } catch (ArithmeticException e) { + logger.log(Level.WARNING, "Failed to compare balance of " + name + " with " + amount + ": " + e.getMessage(), e); + return false; + } + } - /** - * @param name Name of the user - * @param amount The amount of money the user should not have - * @return true, if the user has less money - * @throws UserDoesNotExistException If a user by that name does not exists - */ - @Deprecated - public static boolean hasLess(String name, double amount) throws UserDoesNotExistException - { - try - { - return hasLess(name, BigDecimal.valueOf(amount)); - } - catch (ArithmeticException e) - { - logger.log(Level.WARNING, "Failed to compare balance of " + name + " with " + amount + ": " + e.getMessage(), e); - return false; - } - } + public static boolean hasMore(String name, BigDecimal amount) throws UserDoesNotExistException, ArithmeticException { + return amount.compareTo(getMoneyExact(name)) < 0; + } - public static boolean hasLess(String name, BigDecimal amount) throws UserDoesNotExistException, ArithmeticException - { - return amount.compareTo(getMoneyExact(name)) > 0; - } + /** + * @param name Name of the user + * @param amount The amount of money the user should not have + * + * @return true, if the user has less money + * + * @throws UserDoesNotExistException If a user by that name does not exists + */ + @Deprecated + public static boolean hasLess(String name, double amount) throws UserDoesNotExistException { + try { + return hasLess(name, BigDecimal.valueOf(amount)); + } catch (ArithmeticException e) { + logger.log(Level.WARNING, "Failed to compare balance of " + name + " with " + amount + ": " + e.getMessage(), e); + return false; + } + } - /** - * 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 getMoneyExact(name).signum() < 0; - } + public static boolean hasLess(String name, BigDecimal amount) throws UserDoesNotExistException, ArithmeticException { + return amount.compareTo(getMoneyExact(name)) > 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 - */ - @Deprecated - public static String format(double amount) - { - try - { - return format(BigDecimal.valueOf(amount)); - } - catch (NumberFormatException e) - { - logger.log(Level.WARNING, "Failed to display " + amount + ": " + e.getMessage(), e); - return "NaN"; - } - } + /** + * 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 getMoneyExact(name).signum() < 0; + } - public static String format(BigDecimal amount) - { - if (ess == null) - { - throw new RuntimeException(noCallBeforeLoad); - } - return NumberUtil.displayCurrency(amount, ess); - } + /** + * Formats the amount of money like all other Essentials functions. Example: $100000 or $12345.67 + * + * @param amount The amount of money + * + * @return Formatted money + */ + @Deprecated + public static String format(double amount) { + try { + return format(BigDecimal.valueOf(amount)); + } catch (NumberFormatException e) { + logger.log(Level.WARNING, "Failed to display " + amount + ": " + e.getMessage(), e); + return "NaN"; + } + } - /** - * 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) - { - return getUserByName(name) != null; - } + public static String format(BigDecimal amount) { + if (ess == null) { + throw new RuntimeException(noCallBeforeLoad); + } + return NumberUtil.displayCurrency(amount, ess); + } - /** - * Test if a player is a npc - * - * @param name Name of the player - * @return true, if it's a npc - * @throws UserDoesNotExistException - */ - public static boolean isNPC(String name) throws UserDoesNotExistException - { - User user = getUserByName(name); - if (user == null) - { - throw new UserDoesNotExistException(name); - } - return user.isNPC(); - } + /** + * 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) { + return getUserByName(name) != null; + } - /** - * Creates dummy files for a npc, if there is no player yet with that name. - * - * @param name Name of the player - * @return true, if a new npc was created - */ - public static boolean createNPC(String name) - { - User user = getUserByName(name); - if (user == null) - { - createNPCFile(name); - return true; - } - return false; - } + /** + * Test if a player is a npc + * + * @param name Name of the player + * + * @return true, if it's a npc + * + * @throws UserDoesNotExistException + */ + public static boolean isNPC(String name) throws UserDoesNotExistException { + User user = getUserByName(name); + if (user == null) { + throw new UserDoesNotExistException(name); + } + return user.isNPC(); + } - /** - * Deletes a user, if it is marked as npc. - * - * @param name Name of the player - * @throws UserDoesNotExistException - */ - public static void removeNPC(String name) throws UserDoesNotExistException - { - User user = getUserByName(name); - if (user == null) - { - throw new UserDoesNotExistException(name); - } - deleteNPC(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) { + User user = getUserByName(name); + if (user == null) { + createNPCFile(name); + return true; + } + return false; + } + + /** + * Deletes a user, if it is marked as npc. + * + * @param name Name of the player + * + * @throws UserDoesNotExistException + */ + public static void removeNPC(String name) throws UserDoesNotExistException { + User user = getUserByName(name); + if (user == null) { + throw new UserDoesNotExistException(name); + } + deleteNPC(name); + } } diff --git a/Essentials/src/com/earth2me/essentials/api/II18n.java b/Essentials/src/com/earth2me/essentials/api/II18n.java index 6845ba8d1..4adb9a958 100644 --- a/Essentials/src/com/earth2me/essentials/api/II18n.java +++ b/Essentials/src/com/earth2me/essentials/api/II18n.java @@ -3,11 +3,11 @@ package com.earth2me.essentials.api; import java.util.Locale; -public interface II18n -{ - /** - * Gets the current locale setting - * @return the current locale, if not set it will return the default locale - */ - Locale getCurrentLocale(); +public interface II18n { + /** + * Gets the current locale setting + * + * @return the current locale, if not set it will return the default locale + */ + Locale getCurrentLocale(); } diff --git a/Essentials/src/com/earth2me/essentials/api/IItemDb.java b/Essentials/src/com/earth2me/essentials/api/IItemDb.java index a1da6dd8e..12aab0223 100644 --- a/Essentials/src/com/earth2me/essentials/api/IItemDb.java +++ b/Essentials/src/com/earth2me/essentials/api/IItemDb.java @@ -1,20 +1,19 @@ - package com.earth2me.essentials.api; import com.earth2me.essentials.User; -import java.util.List; import org.bukkit.inventory.ItemStack; +import java.util.List; -public interface IItemDb -{ - ItemStack get(final String name, final int quantity) throws Exception; - ItemStack get(final String name) throws Exception; - - public String names(ItemStack item); - - public String name(ItemStack item); - - List getMatching(User user, String[] args) throws Exception; +public interface IItemDb { + ItemStack get(final String name, final int quantity) throws Exception; + + ItemStack get(final String name) throws Exception; + + public String names(ItemStack item); + + public String name(ItemStack item); + + List getMatching(User user, String[] args) throws Exception; } diff --git a/Essentials/src/com/earth2me/essentials/api/IJails.java b/Essentials/src/com/earth2me/essentials/api/IJails.java index ea45ea73a..b065c9951 100644 --- a/Essentials/src/com/earth2me/essentials/api/IJails.java +++ b/Essentials/src/com/earth2me/essentials/api/IJails.java @@ -1,53 +1,65 @@ package com.earth2me.essentials.api; -import java.util.Collection; import net.ess3.api.IUser; import org.bukkit.Location; +import java.util.Collection; -public interface IJails extends IReload -{ - /** - * Gets the location of the jail with the given name - * @param jailName The name of the jail - * @return the location of the jail - * @throws Exception if the jail does not exist - */ - Location getJail(String jailName) throws Exception; - /** - * Gets a list of jails by names - * @return a list of jails, if there are none the list will be empty - * @throws Exception - */ - Collection getList() throws Exception; +public interface IJails extends IReload { + /** + * Gets the location of the jail with the given name + * + * @param jailName The name of the jail + * + * @return the location of the jail + * + * @throws Exception if the jail does not exist + */ + Location getJail(String jailName) throws Exception; - /** - * Gets the number of jails - * @return the size of the list of jails - */ - int getCount(); + /** + * Gets a list of jails by names + * + * @return a list of jails, if there are none the list will be empty + * + * @throws Exception + */ + Collection getList() throws Exception; - /** - * Remove the jail with the given name - * @param jail the jail to remove - * @throws Exception if the jail does not exist - */ - void removeJail(String jail) throws Exception; + /** + * Gets the number of jails + * + * @return the size of the list of jails + */ + int getCount(); - /** - * Attempts to send the given user to the given jail - * @param user the user to send to jail - * @param jail the jail to send the user to - * @throws Exception if the user is offline or jail does not exist - */ - void sendToJail(IUser user, String jail) throws Exception; + /** + * Remove the jail with the given name + * + * @param jail the jail to remove + * + * @throws Exception if the jail does not exist + */ + void removeJail(String jail) throws Exception; - /** - * Set a new jail with the given name and location - * @param jailName the name of the jail being set - * @param loc the location of the jail being set - * @throws Exception - */ - void setJail(String jailName, Location loc) throws Exception; + /** + * Attempts to send the given user to the given jail + * + * @param user the user to send to jail + * @param jail the jail to send the user to + * + * @throws Exception if the user is offline or jail does not exist + */ + void sendToJail(IUser user, String jail) throws Exception; + + /** + * Set a new jail with the given name and location + * + * @param jailName the name of the jail being set + * @param loc the location of the jail being set + * + * @throws Exception + */ + void setJail(String jailName, Location loc) throws Exception; } diff --git a/Essentials/src/com/earth2me/essentials/api/IReload.java b/Essentials/src/com/earth2me/essentials/api/IReload.java index 75403b55c..49528e053 100644 --- a/Essentials/src/com/earth2me/essentials/api/IReload.java +++ b/Essentials/src/com/earth2me/essentials/api/IReload.java @@ -1,7 +1,6 @@ package com.earth2me.essentials.api; -public interface IReload -{ - void onReload(); +public interface IReload { + void onReload(); } diff --git a/Essentials/src/com/earth2me/essentials/api/ITeleport.java b/Essentials/src/com/earth2me/essentials/api/ITeleport.java index a14f4a5e1..fe7d6d1d3 100644 --- a/Essentials/src/com/earth2me/essentials/api/ITeleport.java +++ b/Essentials/src/com/earth2me/essentials/api/ITeleport.java @@ -7,106 +7,114 @@ import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerTeleportEvent; -public interface ITeleport -{ - /** - * Used to skip teleportPlayer delay when teleporting someone to a location or player. - * - * @param loc - Where should the player end up - * @param cooldown - If cooldown should be enforced - * @param cause - The reported teleportPlayer cause - * @throws Exception - */ - void now(Location loc, boolean cooldown, PlayerTeleportEvent.TeleportCause cause) throws Exception; +public interface ITeleport { + /** + * Used to skip teleportPlayer delay when teleporting someone to a location or player. + * + * @param loc - Where should the player end up + * @param cooldown - If cooldown should be enforced + * @param cause - The reported teleportPlayer cause + * + * @throws Exception + */ + void now(Location loc, boolean cooldown, PlayerTeleportEvent.TeleportCause cause) throws Exception; - /** - * Used to skip teleportPlayer delay when teleporting someone to a location or player. - * - * @param entity - Where should the player end up - * @param cooldown - If cooldown should be enforced - * @param cause - The reported teleportPlayer cause - * @throws Exception - */ - void now(Player entity, boolean cooldown, PlayerTeleportEvent.TeleportCause cause) throws Exception; + /** + * Used to skip teleportPlayer delay when teleporting someone to a location or player. + * + * @param entity - Where should the player end up + * @param cooldown - If cooldown should be enforced + * @param cause - The reported teleportPlayer cause + * + * @throws Exception + */ + void now(Player entity, boolean cooldown, PlayerTeleportEvent.TeleportCause cause) throws Exception; - @Deprecated - void teleport(Location loc, Trade chargeFor) throws Exception; + @Deprecated + void teleport(Location loc, Trade chargeFor) throws Exception; - /** - * Teleport a player to a specific location - * - * @param loc - Where should the player end up - * @param chargeFor - What the user will be charged if teleportPlayer is successful - * @param cause - The reported teleportPlayer cause - * @throws Exception - */ - void teleport(Location loc, Trade chargeFor, PlayerTeleportEvent.TeleportCause cause) throws Exception; + /** + * Teleport a player to a specific location + * + * @param loc - Where should the player end up + * @param chargeFor - What the user will be charged if teleportPlayer is successful + * @param cause - The reported teleportPlayer cause + * + * @throws Exception + */ + void teleport(Location loc, Trade chargeFor, PlayerTeleportEvent.TeleportCause cause) throws Exception; - /** - * Teleport a player to a specific player - * - * @param entity - Where should the player end up - * @param chargeFor - What the user will be charged if teleportPlayer is successful - * @param cause - The reported teleportPlayer cause - * @throws Exception - */ - void teleport(Player entity, Trade chargeFor, PlayerTeleportEvent.TeleportCause cause) throws Exception; + /** + * Teleport a player to a specific player + * + * @param entity - Where should the player end up + * @param chargeFor - What the user will be charged if teleportPlayer is successful + * @param cause - The reported teleportPlayer cause + * + * @throws Exception + */ + void teleport(Player entity, Trade chargeFor, PlayerTeleportEvent.TeleportCause cause) throws Exception; - /** - * Teleport a player to a specific location - * - * @param otherUser - Which user will be teleported - * @param loc - Where should the player end up - * @param chargeFor - What the user will be charged if teleportPlayer is successful - * @param cause - The reported teleportPlayer cause - * @throws Exception - */ - void teleportPlayer(IUser otherUser, Location loc, Trade chargeFor, PlayerTeleportEvent.TeleportCause cause) throws Exception; + /** + * Teleport a player to a specific location + * + * @param otherUser - Which user will be teleported + * @param loc - Where should the player end up + * @param chargeFor - What the user will be charged if teleportPlayer is successful + * @param cause - The reported teleportPlayer cause + * + * @throws Exception + */ + void teleportPlayer(IUser otherUser, Location loc, Trade chargeFor, PlayerTeleportEvent.TeleportCause cause) throws Exception; - /** - * Teleport a player to a specific player - * - * @param otherUser - Which user will be teleported - * @param entity - Where should the player end up - * @param chargeFor - What the user will be charged if teleportPlayer is successful - * @param cause - The reported teleportPlayer cause - * @throws Exception - */ - void teleportPlayer(IUser otherUser, Player entity, Trade chargeFor, PlayerTeleportEvent.TeleportCause cause) throws Exception; + /** + * Teleport a player to a specific player + * + * @param otherUser - Which user will be teleported + * @param entity - Where should the player end up + * @param chargeFor - What the user will be charged if teleportPlayer is successful + * @param cause - The reported teleportPlayer cause + * + * @throws Exception + */ + void teleportPlayer(IUser otherUser, Player entity, Trade chargeFor, PlayerTeleportEvent.TeleportCause cause) throws Exception; - /** - * Teleport wrapper used to handle tp fallback on /jail and /home - * - * @param chargeFor - What the user will be charged if teleportPlayer is successful - * @param cause - The reported teleportPlayer cause - * @throws Exception - */ - public void respawn(final Trade chargeFor, PlayerTeleportEvent.TeleportCause cause) throws Exception; + /** + * Teleport wrapper used to handle tp fallback on /jail and /home + * + * @param chargeFor - What the user will be charged if teleportPlayer is successful + * @param cause - The reported teleportPlayer cause + * + * @throws Exception + */ + public void respawn(final Trade chargeFor, PlayerTeleportEvent.TeleportCause cause) throws Exception; - /** - * Teleport wrapper used to handle /warp teleports - * - * @param otherUser - Which user will be teleported - * @param warp - The name of the warp the user will be teleported too. - * @param chargeFor - What the user will be charged if teleportPlayer is successful - * @param cause - The reported teleportPlayer cause - * @throws Exception - */ - public void warp(IUser otherUser, String warp, Trade chargeFor, PlayerTeleportEvent.TeleportCause cause) throws Exception; + /** + * Teleport wrapper used to handle /warp teleports + * + * @param otherUser - Which user will be teleported + * @param warp - The name of the warp the user will be teleported too. + * @param chargeFor - What the user will be charged if teleportPlayer is successful + * @param cause - The reported teleportPlayer cause + * + * @throws Exception + */ + public void warp(IUser otherUser, String warp, Trade chargeFor, PlayerTeleportEvent.TeleportCause cause) throws Exception; - /** - * Teleport wrapper used to handle /back teleports - * - * @param chargeFor - What the user will be charged if teleportPlayer is successful - * @throws Exception - */ - public void back(Trade chargeFor) throws Exception; + /** + * Teleport wrapper used to handle /back teleports + * + * @param chargeFor - What the user will be charged if teleportPlayer is successful + * + * @throws Exception + */ + public void back(Trade chargeFor) throws Exception; - /** - * Teleport wrapper used to handle throwing user home after a jail sentence - * - * @throws Exception - */ - public void back() throws Exception; + /** + * Teleport wrapper used to handle throwing user home after a jail sentence + * + * @throws Exception + */ + public void back() throws Exception; } diff --git a/Essentials/src/com/earth2me/essentials/api/IWarps.java b/Essentials/src/com/earth2me/essentials/api/IWarps.java index 705822d8e..207b2afdb 100644 --- a/Essentials/src/com/earth2me/essentials/api/IWarps.java +++ b/Essentials/src/com/earth2me/essentials/api/IWarps.java @@ -2,67 +2,73 @@ package com.earth2me.essentials.api; import com.earth2me.essentials.IConf; import com.earth2me.essentials.commands.WarpNotFoundException; -import java.io.File; -import java.util.Collection; import org.bukkit.Location; +import java.io.File; +import java.util.Collection; -public interface IWarps extends IConf -{ - /** - * Get a warp by name - * - * @param warp - Warp name - * @return - Location the warp is set to - * @throws WarpNotFoundException When the warp is not found - * @throws InvalidWorldException When the world the warp is in is not found - */ - Location getWarp(String warp) throws WarpNotFoundException, net.ess3.api.InvalidWorldException; - /** - * Gets a list of warps - * - * @return - A {@link Collection} of warps - */ - Collection getList(); +public interface IWarps extends IConf { + /** + * Get a warp by name + * + * @param warp - Warp name + * + * @return - Location the warp is set to + * + * @throws WarpNotFoundException When the warp is not found + * @throws InvalidWorldException When the world the warp is in is not found + */ + Location getWarp(String warp) throws WarpNotFoundException, net.ess3.api.InvalidWorldException; - /** - * Gets the number of warps - * - * @return the size of the list of warps - */ - int getCount(); + /** + * Gets a list of warps + * + * @return - A {@link Collection} of warps + */ + Collection getList(); - /** - * Delete a warp from the warp DB - * - * @param name - Name of warp - * @throws Exception - */ - void removeWarp(String name) throws Exception; + /** + * Gets the number of warps + * + * @return the size of the list of warps + */ + int getCount(); - /** - * Set a warp - * - * @param name - Name of warp - * @param loc - Location of warp - * @throws Exception - */ - void setWarp(String name, Location loc) throws Exception; + /** + * Delete a warp from the warp DB + * + * @param name - Name of warp + * + * @throws Exception + */ + void removeWarp(String name) throws Exception; - /** - * Check to see if the file is empty - * - * @return - */ - boolean isEmpty(); + /** + * Set a warp + * + * @param name - Name of warp + * @param loc - Location of warp + * + * @throws Exception + */ + void setWarp(String name, Location loc) throws Exception; - /** - * Get a warp file note: this is not yet implemented, as 3.x uses different storage methods - * - * @param name - name of file - * @return - an instance of the file - * @throws InvalidNameException - When the file is not found - */ - File getWarpFile(String name) throws net.ess3.api.InvalidNameException; + /** + * Check to see if the file is empty + * + * @return + */ + boolean isEmpty(); + + /** + * Get a warp file note: this is not yet implemented, as 3.x uses different storage methods + * + * @param name - name of file + * + * @return - an instance of the file + * + * @throws InvalidNameException - When the file is not found + */ + File getWarpFile(String name) throws net.ess3.api.InvalidNameException; } diff --git a/Essentials/src/com/earth2me/essentials/api/InvalidNameException.java b/Essentials/src/com/earth2me/essentials/api/InvalidNameException.java index b62a74ce3..66df7af53 100644 --- a/Essentials/src/com/earth2me/essentials/api/InvalidNameException.java +++ b/Essentials/src/com/earth2me/essentials/api/InvalidNameException.java @@ -1,16 +1,14 @@ package com.earth2me.essentials.api; -public class InvalidNameException extends Exception -{ - /** - * NOTE: This is not implemented yet, just here for future 3.x api support - * Allow serialization of the InvalidNameException exception - */ - private static final long serialVersionUID = 1485321420293663139L; +public class InvalidNameException extends Exception { + /** + * NOTE: This is not implemented yet, just here for future 3.x api support Allow serialization of the + * InvalidNameException exception + */ + private static final long serialVersionUID = 1485321420293663139L; - public InvalidNameException(Throwable thrwbl) - { - super(thrwbl); - } + public InvalidNameException(Throwable thrwbl) { + super(thrwbl); + } } diff --git a/Essentials/src/com/earth2me/essentials/api/InvalidWorldException.java b/Essentials/src/com/earth2me/essentials/api/InvalidWorldException.java index e5b87464c..6e22640c9 100644 --- a/Essentials/src/com/earth2me/essentials/api/InvalidWorldException.java +++ b/Essentials/src/com/earth2me/essentials/api/InvalidWorldException.java @@ -3,18 +3,15 @@ package com.earth2me.essentials.api; import static com.earth2me.essentials.I18n.tl; -public class InvalidWorldException extends Exception -{ - private final String world; +public class InvalidWorldException extends Exception { + private final String world; - public InvalidWorldException(final String world) - { - super(tl("invalidWorld")); - this.world = world; - } + public InvalidWorldException(final String world) { + super(tl("invalidWorld")); + this.world = world; + } - public String getWorld() - { - return this.world; - } + public String getWorld() { + return this.world; + } } diff --git a/Essentials/src/com/earth2me/essentials/api/NoLoanPermittedException.java b/Essentials/src/com/earth2me/essentials/api/NoLoanPermittedException.java index 234369f3d..a52ad0bea 100644 --- a/Essentials/src/com/earth2me/essentials/api/NoLoanPermittedException.java +++ b/Essentials/src/com/earth2me/essentials/api/NoLoanPermittedException.java @@ -1,7 +1,6 @@ package com.earth2me.essentials.api; -public class NoLoanPermittedException extends net.ess3.api.NoLoanPermittedException -{ +public class NoLoanPermittedException extends net.ess3.api.NoLoanPermittedException { } diff --git a/Essentials/src/com/earth2me/essentials/api/UserDoesNotExistException.java b/Essentials/src/com/earth2me/essentials/api/UserDoesNotExistException.java index fd51c04e8..316ee6365 100644 --- a/Essentials/src/com/earth2me/essentials/api/UserDoesNotExistException.java +++ b/Essentials/src/com/earth2me/essentials/api/UserDoesNotExistException.java @@ -3,10 +3,8 @@ package com.earth2me.essentials.api; import static com.earth2me.essentials.I18n.tl; -public class UserDoesNotExistException extends Exception -{ - public UserDoesNotExistException(String name) - { - super(tl("userDoesNotExist", name)); - } +public class UserDoesNotExistException extends Exception { + public UserDoesNotExistException(String name) { + super(tl("userDoesNotExist", name)); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandafk.java b/Essentials/src/com/earth2me/essentials/commands/Commandafk.java index 0052677b5..3d33f7524 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandafk.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandafk.java @@ -1,71 +1,55 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import org.bukkit.Server; +import static com.earth2me.essentials.I18n.tl; -public class Commandafk extends EssentialsCommand -{ - public Commandafk() - { - super("afk"); - } - @Override - public void run(Server server, User user, String commandLabel, String[] args) throws Exception - { - if (args.length > 0 && user.isAuthorized("essentials.afk.others")) - { - User afkUser = getPlayer(server, user, args, 0); - toggleAfk(afkUser); - } - else - { - toggleAfk(user); - } - } - - @Override - public void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception - { - if (args.length > 0) - { - User afkUser = getPlayer(server, args, 0, true, false); - toggleAfk(afkUser); - } - else - { - throw new NotEnoughArgumentsException(); - } - } +public class Commandafk extends EssentialsCommand { + public Commandafk() { + super("afk"); + } - private void toggleAfk(User user) - { - user.setDisplayNick(); - String msg = ""; - if (!user.toggleAfk()) - { - //user.sendMessage(_("markedAsNotAway")); - if (!user.isHidden()) - { - msg = tl("userIsNotAway", user.getDisplayName()); - } - user.updateActivity(false); - } - else - { - //user.sendMessage(_("markedAsAway")); - if (!user.isHidden()) - { - msg = tl("userIsAway", user.getDisplayName()); - } - } - if (!msg.isEmpty()) - { - ess.broadcastMessage(user, msg); - } - } + @Override + public void run(Server server, User user, String commandLabel, String[] args) throws Exception { + if (args.length > 0 && user.isAuthorized("essentials.afk.others")) { + User afkUser = getPlayer(server, user, args, 0); + toggleAfk(afkUser); + } else { + toggleAfk(user); + } + } + + @Override + public void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception { + if (args.length > 0) { + User afkUser = getPlayer(server, args, 0, true, false); + toggleAfk(afkUser); + } else { + throw new NotEnoughArgumentsException(); + } + } + + private void toggleAfk(User user) { + user.setDisplayNick(); + String msg = ""; + if (!user.toggleAfk()) { + //user.sendMessage(_("markedAsNotAway")); + if (!user.isHidden()) { + msg = tl("userIsNotAway", user.getDisplayName()); + } + user.updateActivity(false); + } else { + //user.sendMessage(_("markedAsAway")); + if (!user.isHidden()) { + msg = tl("userIsAway", user.getDisplayName()); + } + } + if (!msg.isEmpty()) { + ess.broadcastMessage(user, msg); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandantioch.java b/Essentials/src/com/earth2me/essentials/commands/Commandantioch.java index c9b7e54ed..e5fd889e6 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandantioch.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandantioch.java @@ -7,23 +7,19 @@ import org.bukkit.Server; import org.bukkit.entity.TNTPrimed; // This command has a in theme message that only shows if you supply a parameter #EasterEgg -public class Commandantioch extends EssentialsCommand -{ - public Commandantioch() - { - super("antioch"); - } +public class Commandantioch extends EssentialsCommand { + public Commandantioch() { + super("antioch"); + } - @Override - public void run(final Server server, final User 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."); - } + @Override + public void run(final Server server, final User 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.getBase()); - loc.getWorld().spawn(loc, TNTPrimed.class); - } + final Location loc = LocationUtil.getTarget(user.getBase()); + 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 index 5db82d048..618c84e7a 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandback.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandback.java @@ -1,33 +1,28 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.Trade; import com.earth2me.essentials.User; import org.bukkit.Server; +import static com.earth2me.essentials.I18n.tl; -public class Commandback extends EssentialsCommand -{ - public Commandback() - { - super("back"); - } - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (user.getLastLocation() == null) - { - throw new Exception(tl("noLocationFound")); - } - if (user.getWorld() != user.getLastLocation().getWorld() && ess.getSettings().isWorldTeleportPermissions() - && !user.isAuthorized("essentials.worlds." + user.getLastLocation().getWorld().getName())) - { - throw new Exception(tl("noPerm", "essentials.worlds." + user.getLastLocation().getWorld().getName())); - } - final Trade charge = new Trade(this.getName(), ess); - charge.isAffordableFor(user); - user.getTeleport().back(charge); - throw new NoChargeException(); - } +public class Commandback extends EssentialsCommand { + public Commandback() { + super("back"); + } + + @Override + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (user.getLastLocation() == null) { + throw new Exception(tl("noLocationFound")); + } + if (user.getWorld() != user.getLastLocation().getWorld() && ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + user.getLastLocation().getWorld().getName())) { + throw new Exception(tl("noPerm", "essentials.worlds." + user.getLastLocation().getWorld().getName())); + } + final Trade charge = new Trade(this.getName(), ess); + charge.isAffordableFor(user); + 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 index a384cb6bd..801794625 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbackup.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbackup.java @@ -2,31 +2,27 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.Backup; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import org.bukkit.Server; +import static com.earth2me.essentials.I18n.tl; -public class Commandbackup extends EssentialsCommand -{ - public Commandbackup() - { - super("backup"); - } - @Override - protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - final Backup backup = ess.getBackup(); - if (backup == null) - { - throw new Exception(tl("backupDisabled")); - } - final String command = ess.getSettings().getBackupCommand(); - if (command == null || "".equals(command) || "save-all".equalsIgnoreCase(command)) - { - throw new Exception(tl("backupDisabled")); - } - backup.run(); - sender.sendMessage(tl("backupStarted")); - } +public class Commandbackup extends EssentialsCommand { + public Commandbackup() { + super("backup"); + } + + @Override + protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + final Backup backup = ess.getBackup(); + if (backup == null) { + throw new Exception(tl("backupDisabled")); + } + final String command = ess.getSettings().getBackupCommand(); + if (command == null || "".equals(command) || "save-all".equalsIgnoreCase(command)) { + throw new Exception(tl("backupDisabled")); + } + backup.run(); + sender.sendMessage(tl("backupStarted")); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbalance.java b/Essentials/src/com/earth2me/essentials/commands/Commandbalance.java index 5015c3574..52abaade5 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbalance.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbalance.java @@ -1,49 +1,41 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.NumberUtil; -import java.math.BigDecimal; import org.bukkit.Server; +import java.math.BigDecimal; -public class Commandbalance extends EssentialsCommand -{ - public Commandbalance() - { - super("balance"); - } +import static com.earth2me.essentials.I18n.tl; - @Override - protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - User target = getPlayer(server, args, 0, true, true); - sender.sendMessage(tl("balanceOther", target.isHidden() ? target.getName() : target.getDisplayName(), NumberUtil.displayCurrency(target.getMoney(), ess))); - } +public class Commandbalance extends EssentialsCommand { + public Commandbalance() { + super("balance"); + } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (args.length == 1 && user.isAuthorized("essentials.balance.others")) - { - final User target = getPlayer(server, args, 0, true, true); - final BigDecimal bal = target.getMoney(); - user.sendMessage(tl("balanceOther", target.isHidden() ? target.getName() : target.getDisplayName(), NumberUtil.displayCurrency(bal, ess))); - } - else if (args.length < 2) - { - final BigDecimal bal = user.getMoney(); - user.sendMessage(tl("balance", NumberUtil.displayCurrency(bal, ess))); - } - else - { - throw new NotEnoughArgumentsException(); - } - } + @Override + protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } + + User target = getPlayer(server, args, 0, true, true); + sender.sendMessage(tl("balanceOther", target.isHidden() ? target.getName() : target.getDisplayName(), NumberUtil.displayCurrency(target.getMoney(), ess))); + } + + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (args.length == 1 && user.isAuthorized("essentials.balance.others")) { + final User target = getPlayer(server, args, 0, true, true); + final BigDecimal bal = target.getMoney(); + user.sendMessage(tl("balanceOther", target.isHidden() ? target.getName() : target.getDisplayName(), NumberUtil.displayCurrency(bal, ess))); + } else if (args.length < 2) { + final BigDecimal bal = user.getMoney(); + user.sendMessage(tl("balance", NumberUtil.displayCurrency(bal, ess))); + } else { + throw new NotEnoughArgumentsException(); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbalancetop.java b/Essentials/src/com/earth2me/essentials/commands/Commandbalancetop.java index 41f78ad11..e8c9bcd0b 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbalancetop.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbalancetop.java @@ -1,199 +1,160 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import com.earth2me.essentials.textreader.SimpleTextInput; import com.earth2me.essentials.textreader.TextPager; import com.earth2me.essentials.utils.NumberUtil; +import org.bukkit.Server; + import java.math.BigDecimal; import java.text.DateFormat; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.locks.ReentrantReadWriteLock; -import org.bukkit.Server; + +import static com.earth2me.essentials.I18n.tl; -public class Commandbalancetop extends EssentialsCommand -{ - public Commandbalancetop() - { - super("balancetop"); - } - private static final int CACHETIME = 2 * 60 * 1000; - public static final int MINUSERS = 50; - private static final SimpleTextInput cache = new SimpleTextInput(); - private static long cacheage = 0; - private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); +public class Commandbalancetop extends EssentialsCommand { + public Commandbalancetop() { + super("balancetop"); + } - @Override - protected void run(final Server server, final CommandSource 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.isPlayer() || ess.getUser(sender.getPlayer()).isAuthorized("essentials.balancetop.force"))) - { - force = true; - } - } - } + private static final int CACHETIME = 2 * 60 * 1000; + public static final int MINUSERS = 50; + private static final SimpleTextInput cache = new SimpleTextInput(); + private static long cacheage = 0; + private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); - if (!force && lock.readLock().tryLock()) - { - try - { - if (cacheage > System.currentTimeMillis() - CACHETIME) - { - outputCache(sender, commandLabel, page); - return; - } - if (ess.getUserMap().getUniqueUsers() > MINUSERS) - { - sender.sendMessage(tl("orderBalances", ess.getUserMap().getUniqueUsers())); - } - } - finally - { - lock.readLock().unlock(); - } - ess.runTaskAsynchronously(new Viewer(sender, commandLabel, page, force)); - } - else - { - if (ess.getUserMap().getUniqueUsers() > MINUSERS) - { - sender.sendMessage(tl("orderBalances", ess.getUserMap().getUniqueUsers())); - } - ess.runTaskAsynchronously(new Viewer(sender, commandLabel, page, force)); - } + @Override + protected void run(final Server server, final CommandSource 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.isPlayer() || ess.getUser(sender.getPlayer()).isAuthorized("essentials.balancetop.force"))) { + force = true; + } + } + } - } + if (!force && lock.readLock().tryLock()) { + try { + if (cacheage > System.currentTimeMillis() - CACHETIME) { + outputCache(sender, commandLabel, page); + return; + } + if (ess.getUserMap().getUniqueUsers() > MINUSERS) { + sender.sendMessage(tl("orderBalances", ess.getUserMap().getUniqueUsers())); + } + } finally { + lock.readLock().unlock(); + } + ess.runTaskAsynchronously(new Viewer(sender, commandLabel, page, force)); + } else { + if (ess.getUserMap().getUniqueUsers() > MINUSERS) { + sender.sendMessage(tl("orderBalances", ess.getUserMap().getUniqueUsers())); + } + ess.runTaskAsynchronously(new Viewer(sender, commandLabel, page, force)); + } - private static void outputCache(final CommandSource sender, String command, int page) - { - final Calendar cal = Calendar.getInstance(); - cal.setTimeInMillis(cacheage); - final DateFormat format = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); - sender.sendMessage(tl("balanceTop", format.format(cal.getTime()))); - new TextPager(cache).showPage(Integer.toString(page), null, "balancetop", sender); - } + } + + private static void outputCache(final CommandSource sender, String command, int page) { + final Calendar cal = Calendar.getInstance(); + cal.setTimeInMillis(cacheage); + final DateFormat format = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); + sender.sendMessage(tl("balanceTop", format.format(cal.getTime()))); + new TextPager(cache).showPage(Integer.toString(page), null, "balancetop", sender); + } - private class Calculator implements Runnable - { - private final transient Viewer viewer; - private final boolean force; + 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; - } + 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(); - BigDecimal totalMoney = BigDecimal.ZERO; - if (ess.getSettings().isEcoDisabled()) - { - if (ess.getSettings().isDebug()) - { - ess.getLogger().info("Internal economy functions disabled, aborting baltop."); - } - } - else - { - for (UUID u : ess.getUserMap().getAllUniqueUsers()) - { - final User user = ess.getUserMap().getUser(u); - if (user != null) - { - final BigDecimal userMoney = user.getMoney(); - user.updateMoneyCache(userMoney); - totalMoney = totalMoney.add(userMoney); - final String name = user.isHidden() ? user.getName() : user.getDisplayName(); - balances.put(name, userMoney); - } - } - } + @Override + public void run() { + lock.writeLock().lock(); + try { + if (force || cacheage <= System.currentTimeMillis() - CACHETIME) { + cache.getLines().clear(); + final Map balances = new HashMap(); + BigDecimal totalMoney = BigDecimal.ZERO; + if (ess.getSettings().isEcoDisabled()) { + if (ess.getSettings().isDebug()) { + ess.getLogger().info("Internal economy functions disabled, aborting baltop."); + } + } else { + for (UUID u : ess.getUserMap().getAllUniqueUsers()) { + final User user = ess.getUserMap().getUser(u); + if (user != null) { + final BigDecimal userMoney = user.getMoney(); + user.updateMoneyCache(userMoney); + totalMoney = totalMoney.add(userMoney); + final String name = user.isHidden() ? user.getName() : user.getDisplayName(); + balances.put(name, userMoney); + } + } + } - final List> sortedEntries = new ArrayList>(balances.entrySet()); - Collections.sort(sortedEntries, new Comparator>() - { - @Override - public int compare(final Entry entry1, final Entry entry2) - { - return entry2.getValue().compareTo(entry1.getValue()); - } - }); + final List> sortedEntries = new ArrayList>(balances.entrySet()); + Collections.sort(sortedEntries, new Comparator>() { + @Override + public int compare(final Entry entry1, final Entry entry2) { + return entry2.getValue().compareTo(entry1.getValue()); + } + }); - cache.getLines().add(tl("serverTotal", NumberUtil.displayCurrency(totalMoney, ess))); - int pos = 1; - for (Map.Entry entry : sortedEntries) - { - cache.getLines().add(pos + ". " + entry.getKey() + ", " + NumberUtil.displayCurrency(entry.getValue(), ess)); - pos++; - } - cacheage = System.currentTimeMillis(); - } - } - finally - { - lock.writeLock().unlock(); - } - ess.runTaskAsynchronously(viewer); - } - } + cache.getLines().add(tl("serverTotal", NumberUtil.displayCurrency(totalMoney, ess))); + int pos = 1; + for (Map.Entry entry : sortedEntries) { + cache.getLines().add(pos + ". " + entry.getKey() + ", " + NumberUtil.displayCurrency(entry.getValue(), ess)); + pos++; + } + cacheage = System.currentTimeMillis(); + } + } finally { + lock.writeLock().unlock(); + } + ess.runTaskAsynchronously(viewer); + } + } - private class Viewer implements Runnable - { - private final transient CommandSource sender; - private final transient int page; - private final transient boolean force; - private final transient String commandLabel; + private class Viewer implements Runnable { + private final transient CommandSource sender; + private final transient int page; + private final transient boolean force; + private final transient String commandLabel; - public Viewer(final CommandSource sender, final String commandLabel, final int page, final boolean force) - { - this.sender = sender; - this.page = page; - this.force = force; - this.commandLabel = commandLabel; - } + public Viewer(final CommandSource sender, final String commandLabel, final int page, final boolean force) { + this.sender = sender; + this.page = page; + this.force = force; + this.commandLabel = commandLabel; + } - @Override - public void run() - { - lock.readLock().lock(); - try - { - if (!force && cacheage > System.currentTimeMillis() - CACHETIME) - { - outputCache(sender, commandLabel, page); - return; - } - } - finally - { - lock.readLock().unlock(); - } - ess.runTaskAsynchronously(new Calculator(new Viewer(sender, commandLabel, page, false), force)); - } - } + @Override + public void run() { + lock.readLock().lock(); + try { + if (!force && cacheage > System.currentTimeMillis() - CACHETIME) { + outputCache(sender, commandLabel, page); + return; + } + } finally { + lock.readLock().unlock(); + } + ess.runTaskAsynchronously(new Calculator(new Viewer(sender, commandLabel, page, false), force)); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandban.java b/Essentials/src/com/earth2me/essentials/commands/Commandban.java index 7a594c8d2..73067dc45 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandban.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandban.java @@ -2,79 +2,64 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.Console; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.OfflinePlayer; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.FormatUtil; -import java.util.logging.Level; import org.bukkit.BanList; -import org.bukkit.Bukkit; import org.bukkit.Server; +import java.util.logging.Level; -public class Commandban extends EssentialsCommand -{ - public Commandban() - { - super("ban"); - } +import static com.earth2me.essentials.I18n.tl; - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - boolean nomatch = false; - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - User user; - try - { - user = getPlayer(server, args, 0, true, true); - } - catch (PlayerNotFoundException e) - { - nomatch = true; - user = ess.getUser(new OfflinePlayer(args[0], ess.getServer())); - } - if (!user.getBase().isOnline()) - { - if (sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.ban.offline")) - { - throw new Exception(tl("banExemptOffline")); - } - } - else - { - if (user.isAuthorized("essentials.ban.exempt") && sender.isPlayer()) - { - throw new Exception(tl("banExempt")); - } - } - final String senderName = sender.isPlayer() ? sender.getPlayer().getDisplayName() : Console.NAME; - String banReason; - if (args.length > 1) - { - banReason = FormatUtil.replaceFormat(getFinalArg(args, 1).replace("\\n", "\n").replace("|", "\n")); - } - else - { - banReason = tl("defaultBanReason"); - } - - ess.getServer().getBanList(BanList.Type.NAME).addBan(user.getName(), banReason, null, senderName); +public class Commandban extends EssentialsCommand { + public Commandban() { + super("ban"); + } - String banDisplay = tl("banFormat", banReason, senderName); - - user.getBase().kickPlayer(banDisplay); - server.getLogger().log(Level.INFO, tl("playerBanned", senderName, user.getName(), banDisplay)); + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + boolean nomatch = false; + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } + User user; + try { + user = getPlayer(server, args, 0, true, true); + } catch (PlayerNotFoundException e) { + nomatch = true; + user = ess.getUser(new OfflinePlayer(args[0], ess.getServer())); + } + if (!user.getBase().isOnline()) { + if (sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.ban.offline")) { + throw new Exception(tl("banExemptOffline")); + } + } else { + if (user.isAuthorized("essentials.ban.exempt") && sender.isPlayer()) { + throw new Exception(tl("banExempt")); + } + } - if (nomatch) - { - sender.sendMessage(tl("userUnknown", user.getName())); - } + final String senderName = sender.isPlayer() ? sender.getPlayer().getDisplayName() : Console.NAME; + String banReason; + if (args.length > 1) { + banReason = FormatUtil.replaceFormat(getFinalArg(args, 1).replace("\\n", "\n").replace("|", "\n")); + } else { + banReason = tl("defaultBanReason"); + } - ess.broadcastMessage("essentials.ban.notify", tl("playerBanned", senderName, user.getName(), banReason)); - } + ess.getServer().getBanList(BanList.Type.NAME).addBan(user.getName(), banReason, null, senderName); + + String banDisplay = tl("banFormat", banReason, senderName); + + user.getBase().kickPlayer(banDisplay); + server.getLogger().log(Level.INFO, tl("playerBanned", senderName, user.getName(), banDisplay)); + + if (nomatch) { + sender.sendMessage(tl("userUnknown", user.getName())); + } + + ess.broadcastMessage("essentials.ban.notify", tl("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 index f538ba4ae..20cc516b2 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbanip.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbanip.java @@ -2,69 +2,56 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.Console; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.FormatUtil; -import java.util.logging.Level; import org.bukkit.BanList; -import org.bukkit.Bukkit; import org.bukkit.Server; +import java.util.logging.Level; + +import static com.earth2me.essentials.I18n.tl; + //TODO: Add kick to online players matching ip ban. -public class Commandbanip extends EssentialsCommand -{ - public Commandbanip() - { - super("banip"); - } +public class Commandbanip extends EssentialsCommand { + public Commandbanip() { + super("banip"); + } - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } - final String senderName = sender.isPlayer() ? sender.getPlayer().getDisplayName() : Console.NAME; + final String senderName = sender.isPlayer() ? sender.getPlayer().getDisplayName() : Console.NAME; - String ipAddress; - if (FormatUtil.validIP(args[0])) - { - ipAddress = args[0]; - } - else - { - try - { - User player = getPlayer(server, args, 0, true, true); - ipAddress = player.getLastLoginAddress(); - } - catch (PlayerNotFoundException ex) - { - ipAddress = args[0]; - } - } + String ipAddress; + if (FormatUtil.validIP(args[0])) { + ipAddress = args[0]; + } else { + try { + User player = getPlayer(server, args, 0, true, true); + ipAddress = player.getLastLoginAddress(); + } catch (PlayerNotFoundException ex) { + ipAddress = args[0]; + } + } - if (ipAddress.isEmpty()) - { - throw new PlayerNotFoundException(); - } + if (ipAddress.isEmpty()) { + throw new PlayerNotFoundException(); + } - String banReason; - if (args.length > 1) - { - banReason = FormatUtil.replaceFormat(getFinalArg(args, 1).replace("\\n", "\n").replace("|", "\n")); - } - else - { - banReason = tl("defaultBanReason"); - } + String banReason; + if (args.length > 1) { + banReason = FormatUtil.replaceFormat(getFinalArg(args, 1).replace("\\n", "\n").replace("|", "\n")); + } else { + banReason = tl("defaultBanReason"); + } - ess.getServer().getBanList(BanList.Type.IP).addBan(ipAddress, banReason, null, senderName); - server.getLogger().log(Level.INFO, tl("playerBanIpAddress", senderName, ipAddress, banReason)); + ess.getServer().getBanList(BanList.Type.IP).addBan(ipAddress, banReason, null, senderName); + server.getLogger().log(Level.INFO, tl("playerBanIpAddress", senderName, ipAddress, banReason)); - ess.broadcastMessage("essentials.ban.notify", tl("playerBanIpAddress", senderName, ipAddress, banReason)); - } + ess.broadcastMessage("essentials.ban.notify", tl("playerBanIpAddress", senderName, ipAddress, banReason)); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbigtree.java b/Essentials/src/com/earth2me/essentials/commands/Commandbigtree.java index ed5b7957e..89895af0e 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbigtree.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbigtree.java @@ -1,51 +1,39 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.LocationUtil; import org.bukkit.Location; import org.bukkit.Server; import org.bukkit.TreeType; +import static com.earth2me.essentials.I18n.tl; -public class Commandbigtree extends EssentialsCommand -{ - public Commandbigtree() - { - super("bigtree"); - } - @Override - public void run(final Server server, final User 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(); - } +public class Commandbigtree extends EssentialsCommand { + public Commandbigtree() { + super("bigtree"); + } - final Location loc = LocationUtil.getTarget(user.getBase()); - final Location safeLocation = LocationUtil.getSafeDestination(loc); - final boolean success = user.getWorld().generateTree(safeLocation, tree); - if (success) - { - user.sendMessage(tl("bigTreeSuccess")); - } - else - { - throw new Exception(tl("bigTreeFailure")); - } - } + @Override + public void run(final Server server, final User 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.getBase()); + final Location safeLocation = LocationUtil.getSafeDestination(loc); + final boolean success = user.getWorld().generateTree(safeLocation, tree); + if (success) { + user.sendMessage(tl("bigTreeSuccess")); + } else { + throw new Exception(tl("bigTreeFailure")); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbook.java b/Essentials/src/com/earth2me/essentials/commands/Commandbook.java index 9b602c357..5d38455c9 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbook.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbook.java @@ -1,92 +1,69 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import org.bukkit.Material; import org.bukkit.Server; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BookMeta; +import static com.earth2me.essentials.I18n.tl; -public class Commandbook extends EssentialsCommand -{ - public Commandbook() - { - super("book"); - } - //TODO: Translate this - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - final ItemStack item = user.getBase().getItemInHand(); - final String player = user.getName(); - if (item.getType() == Material.WRITTEN_BOOK) - { - BookMeta bmeta = (BookMeta)item.getItemMeta(); +public class Commandbook extends EssentialsCommand { + public Commandbook() { + super("book"); + } - if (args.length > 1 && args[0].equalsIgnoreCase("author")) - { - if (user.isAuthorized("essentials.book.author") && (isAuthor(bmeta, player) || user.isAuthorized("essentials.book.others"))) - { - bmeta.setAuthor(args[1]); - item.setItemMeta(bmeta); - user.sendMessage(tl("bookAuthorSet", getFinalArg(args, 1))); - } - else - { - throw new Exception(tl("denyChangeAuthor")); - } - } - else if (args.length > 1 && args[0].equalsIgnoreCase("title")) - { - if (user.isAuthorized("essentials.book.title") && (isAuthor(bmeta, player) || user.isAuthorized("essentials.book.others"))) - { - bmeta.setTitle(args[1]); - item.setItemMeta(bmeta); - user.sendMessage(tl("bookTitleSet", getFinalArg(args, 1))); - } - else - { - throw new Exception(tl("denyChangeTitle")); - } - } - else - { - if (isAuthor(bmeta, player) || user.isAuthorized("essentials.book.others")) - { - ItemStack newItem = new ItemStack(Material.BOOK_AND_QUILL, item.getAmount()); - newItem.setItemMeta(bmeta); - user.getBase().setItemInHand(newItem); - user.sendMessage(tl("editBookContents")); - } - else - { - throw new Exception(tl("denyBookEdit")); - } - } - } - else if (item.getType() == Material.BOOK_AND_QUILL) - { - BookMeta bmeta = (BookMeta)item.getItemMeta(); - if (!user.isAuthorized("essentials.book.author")) - { - bmeta.setAuthor(player); - } - ItemStack newItem = new ItemStack(Material.WRITTEN_BOOK, item.getAmount()); - newItem.setItemMeta(bmeta); - user.getBase().setItemInHand(newItem); - user.sendMessage(tl("bookLocked")); - } - else - { - throw new Exception(tl("holdBook")); - } - } + //TODO: Translate this + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + final ItemStack item = user.getBase().getItemInHand(); + final String player = user.getName(); + if (item.getType() == Material.WRITTEN_BOOK) { + BookMeta bmeta = (BookMeta) item.getItemMeta(); - private boolean isAuthor(BookMeta bmeta, String player) - { - String author = bmeta.getAuthor(); - return author != null && author.equalsIgnoreCase(player); - } + if (args.length > 1 && args[0].equalsIgnoreCase("author")) { + if (user.isAuthorized("essentials.book.author") && (isAuthor(bmeta, player) || user.isAuthorized("essentials.book.others"))) { + bmeta.setAuthor(args[1]); + item.setItemMeta(bmeta); + user.sendMessage(tl("bookAuthorSet", getFinalArg(args, 1))); + } else { + throw new Exception(tl("denyChangeAuthor")); + } + } else if (args.length > 1 && args[0].equalsIgnoreCase("title")) { + if (user.isAuthorized("essentials.book.title") && (isAuthor(bmeta, player) || user.isAuthorized("essentials.book.others"))) { + bmeta.setTitle(args[1]); + item.setItemMeta(bmeta); + user.sendMessage(tl("bookTitleSet", getFinalArg(args, 1))); + } else { + throw new Exception(tl("denyChangeTitle")); + } + } else { + if (isAuthor(bmeta, player) || user.isAuthorized("essentials.book.others")) { + ItemStack newItem = new ItemStack(Material.BOOK_AND_QUILL, item.getAmount()); + newItem.setItemMeta(bmeta); + user.getBase().setItemInHand(newItem); + user.sendMessage(tl("editBookContents")); + } else { + throw new Exception(tl("denyBookEdit")); + } + } + } else if (item.getType() == Material.BOOK_AND_QUILL) { + BookMeta bmeta = (BookMeta) item.getItemMeta(); + if (!user.isAuthorized("essentials.book.author")) { + bmeta.setAuthor(player); + } + ItemStack newItem = new ItemStack(Material.WRITTEN_BOOK, item.getAmount()); + newItem.setItemMeta(bmeta); + user.getBase().setItemInHand(newItem); + user.sendMessage(tl("bookLocked")); + } else { + throw new Exception(tl("holdBook")); + } + } + + private boolean isAuthor(BookMeta bmeta, String player) { + String author = bmeta.getAuthor(); + return author != null && author.equalsIgnoreCase(player); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandbreak.java b/Essentials/src/com/earth2me/essentials/commands/Commandbreak.java index f4b4a6764..e6b36246a 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbreak.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbreak.java @@ -1,48 +1,40 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import org.bukkit.Material; import org.bukkit.Server; import org.bukkit.block.Block; import org.bukkit.event.block.BlockBreakEvent; +import static com.earth2me.essentials.I18n.tl; -public class Commandbreak extends EssentialsCommand -{ - public Commandbreak() - { - super("break"); - } - //TODO: Switch to use util class - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - final Block block = user.getBase().getTargetBlock(null, 20); - if (block == null) - { - throw new NoChargeException(); - } - if (block.getType() == Material.AIR) - { - throw new NoChargeException(); - } - if (block.getType() == Material.BEDROCK && !user.isAuthorized("essentials.break.bedrock")) - { - throw new Exception(tl("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); - } - } +public class Commandbreak extends EssentialsCommand { + public Commandbreak() { + super("break"); + } + + //TODO: Switch to use util class + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + final Block block = user.getBase().getTargetBlock(null, 20); + if (block == null) { + throw new NoChargeException(); + } + if (block.getType() == Material.AIR) { + throw new NoChargeException(); + } + if (block.getType() == Material.BEDROCK && !user.isAuthorized("essentials.break.bedrock")) { + throw new Exception(tl("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 index 2b692b78b..dfd165f59 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandbroadcast.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandbroadcast.java @@ -1,38 +1,33 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.FormatUtil; import org.bukkit.Server; +import static com.earth2me.essentials.I18n.tl; -public class Commandbroadcast extends EssentialsCommand -{ - public Commandbroadcast() - { - super("broadcast"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - sendBroadcast(user.getDisplayName(), args); - } +public class Commandbroadcast extends EssentialsCommand { + public Commandbroadcast() { + super("broadcast"); + } - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - sendBroadcast(sender.getSender().getName(), args); - } + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + sendBroadcast(user.getDisplayName(), args); + } - private void sendBroadcast(final String name, final String[] args) throws NotEnoughArgumentsException - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + sendBroadcast(sender.getSender().getName(), args); + } - ess.broadcastMessage(tl("broadcast", FormatUtil.replaceFormat(getFinalArg(args, 0)).replace("\\n", "\n"), name)); - } + private void sendBroadcast(final String name, final String[] args) throws NotEnoughArgumentsException { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } + + ess.broadcastMessage(tl("broadcast", FormatUtil.replaceFormat(getFinalArg(args, 0)).replace("\\n", "\n"), name)); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandburn.java b/Essentials/src/com/earth2me/essentials/commands/Commandburn.java index e9665a745..ac430c5cc 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandburn.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandburn.java @@ -1,33 +1,29 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import org.bukkit.Server; +import static com.earth2me.essentials.I18n.tl; -public class Commandburn extends EssentialsCommand -{ - public Commandburn() - { - super("burn"); - } - @Override - protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 2) - { - throw new NotEnoughArgumentsException(); - } +public class Commandburn extends EssentialsCommand { + public Commandburn() { + super("burn"); + } - if (args[0].trim().length() < 2) - { - throw new NotEnoughArgumentsException(); - } + @Override + protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 2) { + throw new NotEnoughArgumentsException(); + } - User user = getPlayer(server, sender, args, 0); - user.getBase().setFireTicks(Integer.parseInt(args[1]) * 20); - sender.sendMessage(tl("burnMsg", user.getDisplayName(), Integer.parseInt(args[1]))); - } + if (args[0].trim().length() < 2) { + throw new NotEnoughArgumentsException(); + } + + User user = getPlayer(server, sender, args, 0); + user.getBase().setFireTicks(Integer.parseInt(args[1]) * 20); + sender.sendMessage(tl("burnMsg", user.getDisplayName(), Integer.parseInt(args[1]))); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandclearinventory.java b/Essentials/src/com/earth2me/essentials/commands/Commandclearinventory.java index 311cb3e13..853ae8f65 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandclearinventory.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandclearinventory.java @@ -1,161 +1,129 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.NumberUtil; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Locale; import org.bukkit.Server; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Locale; -public class Commandclearinventory extends EssentialsCommand -{ - public Commandclearinventory() - { - super("clearinventory"); - } - private static final int BASE_AMOUNT = 100000; - private static final int EXTENDED_CAP = 8; +import static com.earth2me.essentials.I18n.tl; - @Override - public void run(Server server, User user, String commandLabel, String[] args) throws Exception - { - parseCommand(server, user.getSource(), args, user.isAuthorized("essentials.clearinventory.others"), user.isAuthorized("essentials.clearinventory.all") || user.isAuthorized("essentials.clearinventory.multiple")); - } - @Override - protected void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception - { - parseCommand(server, sender, args, true, true); - } +public class Commandclearinventory extends EssentialsCommand { + public Commandclearinventory() { + super("clearinventory"); + } - private void parseCommand(Server server, CommandSource sender, String[] args, boolean allowOthers, boolean allowAll) throws Exception - { - Collection players = new ArrayList(); - int offset = 0; + private static final int BASE_AMOUNT = 100000; + private static final int EXTENDED_CAP = 8; - if (sender.isPlayer()) - { - players.add(sender.getPlayer()); - } + @Override + public void run(Server server, User user, String commandLabel, String[] args) throws Exception { + parseCommand(server, user.getSource(), args, user.isAuthorized("essentials.clearinventory.others"), user.isAuthorized("essentials.clearinventory.all") || user.isAuthorized("essentials.clearinventory.multiple")); + } - if (allowAll && args.length > 0 && args[0].contentEquals("*")) - { - sender.sendMessage(tl("inventoryClearingFromAll")); - offset = 1; - players = ess.getOnlinePlayers(); - } - else if (allowOthers && args.length > 0 && args[0].trim().length() > 2) - { - offset = 1; - players = server.matchPlayer(args[0].trim()); - } + @Override + protected void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception { + parseCommand(server, sender, args, true, true); + } - if (players.size() < 1) - { - throw new PlayerNotFoundException(); - } - for (Player player : players) - { - clearHandler(sender, player, args, offset, players.size() < EXTENDED_CAP); - } - } + private void parseCommand(Server server, CommandSource sender, String[] args, boolean allowOthers, boolean allowAll) throws Exception { + Collection players = new ArrayList(); + int offset = 0; - protected void clearHandler(CommandSource sender, Player player, String[] args, int offset, boolean showExtended) throws Exception - { - short data = -1; - int type = -1; - int amount = -1; + if (sender.isPlayer()) { + players.add(sender.getPlayer()); + } - if (args.length > (offset + 1) && NumberUtil.isInt(args[(offset + 1)])) - { - amount = Integer.parseInt(args[(offset + 1)]); - } - if (args.length > offset) - { - if (args[offset].equalsIgnoreCase("**")) - { - type = -2; - } - else if (!args[offset].equalsIgnoreCase("*")) - { - final String[] split = args[offset].split(":"); - final ItemStack item = ess.getItemDb().get(split[0]); - type = item.getTypeId(); + if (allowAll && args.length > 0 && args[0].contentEquals("*")) { + sender.sendMessage(tl("inventoryClearingFromAll")); + offset = 1; + players = ess.getOnlinePlayers(); + } else if (allowOthers && args.length > 0 && args[0].trim().length() > 2) { + offset = 1; + players = server.matchPlayer(args[0].trim()); + } - if (split.length > 1 && NumberUtil.isInt(split[1])) - { - data = Short.parseShort(split[1]); - } - else - { - data = item.getDurability(); - } - } - } + if (players.size() < 1) { + throw new PlayerNotFoundException(); + } + for (Player player : players) { + clearHandler(sender, player, args, offset, players.size() < EXTENDED_CAP); + } + } - if (type == -1) // type -1 represents wildcard or all items - { - if (showExtended) - { - sender.sendMessage(tl("inventoryClearingAllItems", player.getDisplayName())); - } - player.getInventory().clear(); - } - else if (type == -2) // type -2 represents double wildcard or all items and armor - { - if (showExtended) - { - sender.sendMessage(tl("inventoryClearingAllArmor", player.getDisplayName())); - } - player.getInventory().clear(); - player.getInventory().setArmorContents(null); - } - else - { - if (data == -1) // data -1 means that all subtypes will be cleared - { - ItemStack stack = new ItemStack(type); - if (showExtended) - { - sender.sendMessage(tl("inventoryClearingAllStack", stack.getType().toString().toLowerCase(Locale.ENGLISH), player.getDisplayName())); - } - player.getInventory().clear(type, data); - } - else if (amount == -1) // amount -1 means all items will be cleared - { - ItemStack stack = new ItemStack(type, BASE_AMOUNT, data); - ItemStack removedStack = player.getInventory().removeItem(stack).get(0); - final int removedAmount = (BASE_AMOUNT - removedStack.getAmount()); - if (removedAmount > 0 || showExtended) - { - sender.sendMessage(tl("inventoryClearingStack", removedAmount, stack.getType().toString().toLowerCase(Locale.ENGLISH), player.getDisplayName())); - } - } - else - { - if (amount < 0) - { - amount = 1; - } - ItemStack stack = new ItemStack(type, amount, data); - if (player.getInventory().containsAtLeast(stack, amount)) - { - sender.sendMessage(tl("inventoryClearingStack", amount, stack.getType().toString().toLowerCase(Locale.ENGLISH), player.getDisplayName())); - player.getInventory().removeItem(stack); - } - else - { - if (showExtended) - { - sender.sendMessage(tl("inventoryClearFail", player.getDisplayName(), amount, stack.getType().toString().toLowerCase(Locale.ENGLISH))); - } - } - } - } - } + protected void clearHandler(CommandSource sender, Player player, String[] args, int offset, boolean showExtended) throws Exception { + short data = -1; + int type = -1; + int amount = -1; + + if (args.length > (offset + 1) && NumberUtil.isInt(args[(offset + 1)])) { + amount = Integer.parseInt(args[(offset + 1)]); + } + if (args.length > offset) { + if (args[offset].equalsIgnoreCase("**")) { + type = -2; + } else if (!args[offset].equalsIgnoreCase("*")) { + final String[] split = args[offset].split(":"); + final ItemStack item = ess.getItemDb().get(split[0]); + type = item.getTypeId(); + + if (split.length > 1 && NumberUtil.isInt(split[1])) { + data = Short.parseShort(split[1]); + } else { + data = item.getDurability(); + } + } + } + + if (type == -1) // type -1 represents wildcard or all items + { + if (showExtended) { + sender.sendMessage(tl("inventoryClearingAllItems", player.getDisplayName())); + } + player.getInventory().clear(); + } else if (type == -2) // type -2 represents double wildcard or all items and armor + { + if (showExtended) { + sender.sendMessage(tl("inventoryClearingAllArmor", player.getDisplayName())); + } + player.getInventory().clear(); + player.getInventory().setArmorContents(null); + } else { + if (data == -1) // data -1 means that all subtypes will be cleared + { + ItemStack stack = new ItemStack(type); + if (showExtended) { + sender.sendMessage(tl("inventoryClearingAllStack", stack.getType().toString().toLowerCase(Locale.ENGLISH), player.getDisplayName())); + } + player.getInventory().clear(type, data); + } else if (amount == -1) // amount -1 means all items will be cleared + { + ItemStack stack = new ItemStack(type, BASE_AMOUNT, data); + ItemStack removedStack = player.getInventory().removeItem(stack).get(0); + final int removedAmount = (BASE_AMOUNT - removedStack.getAmount()); + if (removedAmount > 0 || showExtended) { + sender.sendMessage(tl("inventoryClearingStack", removedAmount, stack.getType().toString().toLowerCase(Locale.ENGLISH), player.getDisplayName())); + } + } else { + if (amount < 0) { + amount = 1; + } + ItemStack stack = new ItemStack(type, amount, data); + if (player.getInventory().containsAtLeast(stack, amount)) { + sender.sendMessage(tl("inventoryClearingStack", amount, stack.getType().toString().toLowerCase(Locale.ENGLISH), player.getDisplayName())); + player.getInventory().removeItem(stack); + } else { + if (showExtended) { + sender.sendMessage(tl("inventoryClearFail", player.getDisplayName(), amount, stack.getType().toString().toLowerCase(Locale.ENGLISH))); + } + } + } + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandcompass.java b/Essentials/src/com/earth2me/essentials/commands/Commandcompass.java index 53dce03d1..24b6aa85f 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandcompass.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandcompass.java @@ -1,58 +1,39 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import org.bukkit.Server; +import static com.earth2me.essentials.I18n.tl; -public class Commandcompass extends EssentialsCommand -{ - public Commandcompass() - { - super("compass"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - final int bearing = (int)(user.getLocation().getYaw() + 180 + 360) % 360; - String dir; - 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(tl("compassBearing", dir, bearing)); - } +public class Commandcompass extends EssentialsCommand { + public Commandcompass() { + super("compass"); + } + + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + final int bearing = (int) (user.getLocation().getYaw() + 180 + 360) % 360; + String dir; + 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(tl("compassBearing", dir, bearing)); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandcondense.java b/Essentials/src/com/earth2me/essentials/commands/Commandcondense.java index fd0408890..b95c57a0d 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandcondense.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandcondense.java @@ -1,221 +1,181 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; -import java.util.*; -import org.bukkit.Material; -import org.bukkit.Server; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.Recipe; -import org.bukkit.inventory.ShapedRecipe; -import org.bukkit.inventory.ShapelessRecipe; import com.earth2me.essentials.ChargeException; import com.earth2me.essentials.Trade; import com.earth2me.essentials.Trade.OverflowType; import com.earth2me.essentials.User; import net.ess3.api.MaxMoneyException; +import org.bukkit.Material; +import org.bukkit.Server; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.Recipe; +import org.bukkit.inventory.ShapedRecipe; +import org.bukkit.inventory.ShapelessRecipe; + +import java.util.*; + +import static com.earth2me.essentials.I18n.tl; -public class Commandcondense extends EssentialsCommand -{ - public Commandcondense() - { - super("condense"); - } - private Map condenseList = new HashMap(); +public class Commandcondense extends EssentialsCommand { + public Commandcondense() { + super("condense"); + } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - List is = new ArrayList(); + private Map condenseList = new HashMap(); - boolean validateReverse = false; - if (args.length > 0) - { - is = ess.getItemDb().getMatching(user, args); - } - else - { - for (ItemStack stack : user.getBase().getInventory().getContents()) - { - if (stack == null || stack.getType() == Material.AIR) - { - continue; - } - is.add(stack); - } - validateReverse = true; - } + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + List is = new ArrayList(); - boolean didConvert = false; - for (final ItemStack itemStack : is) - { - if (condenseStack(user, itemStack, validateReverse)) - { - didConvert = true; - } - } - user.getBase().updateInventory(); + boolean validateReverse = false; + if (args.length > 0) { + is = ess.getItemDb().getMatching(user, args); + } else { + for (ItemStack stack : user.getBase().getInventory().getContents()) { + if (stack == null || stack.getType() == Material.AIR) { + continue; + } + is.add(stack); + } + validateReverse = true; + } - if (didConvert) - { - user.sendMessage(tl("itemsConverted")); - } - else - { - user.sendMessage(tl("itemsNotConverted")); - throw new NoChargeException(); - } - } + boolean didConvert = false; + for (final ItemStack itemStack : is) { + if (condenseStack(user, itemStack, validateReverse)) { + didConvert = true; + } + } + user.getBase().updateInventory(); - private boolean condenseStack(final User user, final ItemStack stack, final boolean validateReverse) throws ChargeException, MaxMoneyException - { - final SimpleRecipe condenseType = getCondenseType(stack); - if (condenseType != null) - { - final ItemStack input = condenseType.getInput(); - final ItemStack result = condenseType.getResult(); + if (didConvert) { + user.sendMessage(tl("itemsConverted")); + } else { + user.sendMessage(tl("itemsNotConverted")); + throw new NoChargeException(); + } + } - if (validateReverse) - { - boolean pass = false; - for (Recipe revRecipe : ess.getServer().getRecipesFor(input)) - { - if (getStackOnRecipeMatch(revRecipe, result) != null) - { - pass = true; - break; - } - } - if (!pass) - { - return false; - } - } + private boolean condenseStack(final User user, final ItemStack stack, final boolean validateReverse) throws ChargeException, MaxMoneyException { + final SimpleRecipe condenseType = getCondenseType(stack); + if (condenseType != null) { + final ItemStack input = condenseType.getInput(); + final ItemStack result = condenseType.getResult(); - int amount = 0; + if (validateReverse) { + boolean pass = false; + for (Recipe revRecipe : ess.getServer().getRecipesFor(input)) { + if (getStackOnRecipeMatch(revRecipe, result) != null) { + pass = true; + break; + } + } + if (!pass) { + return false; + } + } - for (final ItemStack contents : user.getBase().getInventory().getContents()) - { - if (contents != null && contents.isSimilar(stack)) - { - amount += contents.getAmount(); - } - } + int amount = 0; - int output = ((amount / input.getAmount()) * result.getAmount()); - amount -= amount % input.getAmount(); + for (final ItemStack contents : user.getBase().getInventory().getContents()) { + if (contents != null && contents.isSimilar(stack)) { + amount += contents.getAmount(); + } + } - if (amount > 0) - { - input.setAmount(amount); - result.setAmount(output); - final Trade remove = new Trade(input, ess); - final Trade add = new Trade(result, ess); - remove.charge(user); - add.pay(user, OverflowType.DROP); - return true; - } - } - return false; - } + int output = ((amount / input.getAmount()) * result.getAmount()); + amount -= amount % input.getAmount(); - private SimpleRecipe getCondenseType(final ItemStack stack) - { - if (condenseList.containsKey(stack)) - { - return condenseList.get(stack); - } + if (amount > 0) { + input.setAmount(amount); + result.setAmount(output); + final Trade remove = new Trade(input, ess); + final Trade add = new Trade(result, ess); + remove.charge(user); + add.pay(user, OverflowType.DROP); + return true; + } + } + return false; + } - final Iterator intr = ess.getServer().recipeIterator(); - while (intr.hasNext()) - { - final Recipe recipe = intr.next(); - final Collection recipeItems = getStackOnRecipeMatch(recipe, stack); + private SimpleRecipe getCondenseType(final ItemStack stack) { + if (condenseList.containsKey(stack)) { + return condenseList.get(stack); + } - if (recipeItems != null && (recipeItems.size() == 4 || recipeItems.size() == 9) - && (recipeItems.size() > recipe.getResult().getAmount())) - { - final ItemStack input = stack.clone(); - input.setAmount(recipeItems.size()); - final SimpleRecipe newRecipe = new SimpleRecipe(recipe.getResult(), input); - condenseList.put(stack, newRecipe); - return newRecipe; - } - } + final Iterator intr = ess.getServer().recipeIterator(); + while (intr.hasNext()) { + final Recipe recipe = intr.next(); + final Collection recipeItems = getStackOnRecipeMatch(recipe, stack); - condenseList.put(stack, null); - return null; - } + if (recipeItems != null && (recipeItems.size() == 4 || recipeItems.size() == 9) && (recipeItems.size() > recipe.getResult().getAmount())) { + final ItemStack input = stack.clone(); + input.setAmount(recipeItems.size()); + final SimpleRecipe newRecipe = new SimpleRecipe(recipe.getResult(), input); + condenseList.put(stack, newRecipe); + return newRecipe; + } + } - private Collection getStackOnRecipeMatch(final Recipe recipe, final ItemStack stack) - { - final Collection inputList; + condenseList.put(stack, null); + return null; + } - if (recipe instanceof ShapedRecipe) - { - ShapedRecipe sRecipe = (ShapedRecipe)recipe; - inputList = sRecipe.getIngredientMap().values(); - } - else if (recipe instanceof ShapelessRecipe) - { - ShapelessRecipe slRecipe = (ShapelessRecipe)recipe; - inputList = slRecipe.getIngredientList(); - } - else - { - return null; - } + private Collection getStackOnRecipeMatch(final Recipe recipe, final ItemStack stack) { + final Collection inputList; - boolean match = true; - Iterator iter = inputList.iterator(); - while (iter.hasNext()) - { - ItemStack inputSlot = iter.next(); - if (inputSlot == null) - { - iter.remove(); - continue; - } + if (recipe instanceof ShapedRecipe) { + ShapedRecipe sRecipe = (ShapedRecipe) recipe; + inputList = sRecipe.getIngredientMap().values(); + } else if (recipe instanceof ShapelessRecipe) { + ShapelessRecipe slRecipe = (ShapelessRecipe) recipe; + inputList = slRecipe.getIngredientList(); + } else { + return null; + } - if (inputSlot.getDurability() == Short.MAX_VALUE) - { - inputSlot.setDurability((short)0); - } - if (!inputSlot.isSimilar(stack)) - { - match = false; - } - } + boolean match = true; + Iterator iter = inputList.iterator(); + while (iter.hasNext()) { + ItemStack inputSlot = iter.next(); + if (inputSlot == null) { + iter.remove(); + continue; + } - if (match) - { - return inputList; - } - return null; - } + if (inputSlot.getDurability() == Short.MAX_VALUE) { + inputSlot.setDurability((short) 0); + } + if (!inputSlot.isSimilar(stack)) { + match = false; + } + } + + if (match) { + return inputList; + } + return null; + } - private class SimpleRecipe implements Recipe - { - private ItemStack result; - private ItemStack input; + private class SimpleRecipe implements Recipe { + private ItemStack result; + private ItemStack input; - private SimpleRecipe(ItemStack result, ItemStack input) - { - this.result = result; - this.input = input; - } + private SimpleRecipe(ItemStack result, ItemStack input) { + this.result = result; + this.input = input; + } - @Override - public ItemStack getResult() - { - return result.clone(); - } + @Override + public ItemStack getResult() { + return result.clone(); + } - public ItemStack getInput() - { - return input.clone(); - } - } + public ItemStack getInput() { + return input.clone(); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandcustomtext.java b/Essentials/src/com/earth2me/essentials/commands/Commandcustomtext.java index 8f08e3ce0..bd17a300f 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandcustomtext.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandcustomtext.java @@ -9,37 +9,30 @@ import com.earth2me.essentials.utils.NumberUtil; import org.bukkit.Server; -public class Commandcustomtext extends EssentialsCommand -{ - public Commandcustomtext() - { - super("customtext"); - } +public class Commandcustomtext extends EssentialsCommand { + public Commandcustomtext() { + super("customtext"); + } - @Override - protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (sender.isPlayer()) - { - ess.getUser(sender.getPlayer()).setDisplayNick(); - } - - final IText input = new TextInput(sender, "custom", true, ess); - final IText output = new KeywordReplacer(input, sender, ess); - final TextPager pager = new TextPager(output); - String chapter = commandLabel; - String page; + @Override + protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (sender.isPlayer()) { + ess.getUser(sender.getPlayer()).setDisplayNick(); + } - if (commandLabel.equalsIgnoreCase("customtext") && args.length > 0 && !NumberUtil.isInt(commandLabel)) - { - chapter = args[0]; - page = args.length > 1 ? args[1] : null; - } - else - { - page = args.length > 0 ? args[0] : null; - } - - pager.showPage(chapter, page, null, sender); - } + final IText input = new TextInput(sender, "custom", true, ess); + final IText output = new KeywordReplacer(input, sender, ess); + final TextPager pager = new TextPager(output); + String chapter = commandLabel; + String page; + + if (commandLabel.equalsIgnoreCase("customtext") && args.length > 0 && !NumberUtil.isInt(commandLabel)) { + chapter = args[0]; + page = args.length > 1 ? args[1] : null; + } else { + page = args.length > 0 ? args[0] : null; + } + + pager.showPage(chapter, page, null, sender); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanddelhome.java b/Essentials/src/com/earth2me/essentials/commands/Commanddelhome.java index 8459700a5..5ed07c186 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commanddelhome.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commanddelhome.java @@ -1,62 +1,51 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; -import java.util.Locale; import org.bukkit.Server; +import java.util.Locale; -public class Commanddelhome extends EssentialsCommand -{ - public Commanddelhome() - { - super("delhome"); - } +import static com.earth2me.essentials.I18n.tl; - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - User user = ess.getUser(sender.getPlayer()); - String name; - String[] expandedArg; +public class Commanddelhome extends EssentialsCommand { + public Commanddelhome() { + super("delhome"); + } - //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; - } + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, String[] args) throws Exception { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } - if (expandedArg.length > 1 && (user == null || user.isAuthorized("essentials.delhome.others"))) - { - user = getPlayer(server, expandedArg, 0, true, true); - name = expandedArg[1]; - } - else if (user == null) - { - throw new NotEnoughArgumentsException(); - } - else - { - name = expandedArg[0]; - } + User user = ess.getUser(sender.getPlayer()); + String name; + String[] expandedArg; - if (name.equalsIgnoreCase("bed")) - { - throw new Exception(tl("invalidHomeName")); - } + //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; + } - user.delHome(name.toLowerCase(Locale.ENGLISH)); - sender.sendMessage(tl("deleteHome", name)); - } + if (expandedArg.length > 1 && (user == null || user.isAuthorized("essentials.delhome.others"))) { + user = getPlayer(server, expandedArg, 0, true, true); + name = expandedArg[1]; + } else if (user == null) { + throw new NotEnoughArgumentsException(); + } else { + name = expandedArg[0]; + } + + if (name.equalsIgnoreCase("bed")) { + throw new Exception(tl("invalidHomeName")); + } + + user.delHome(name.toLowerCase(Locale.ENGLISH)); + sender.sendMessage(tl("deleteHome", name)); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanddeljail.java b/Essentials/src/com/earth2me/essentials/commands/Commanddeljail.java index 7b5937a09..8d4cb9825 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commanddeljail.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commanddeljail.java @@ -1,26 +1,23 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import org.bukkit.Server; +import static com.earth2me.essentials.I18n.tl; -public class Commanddeljail extends EssentialsCommand -{ - public Commanddeljail() - { - super("deljail"); - } - @Override - protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - - ess.getJails().removeJail(args[0]); - sender.sendMessage(tl("deleteJail", args[0])); - } +public class Commanddeljail extends EssentialsCommand { + public Commanddeljail() { + super("deljail"); + } + + @Override + protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } + + ess.getJails().removeJail(args[0]); + sender.sendMessage(tl("deleteJail", args[0])); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanddelwarp.java b/Essentials/src/com/earth2me/essentials/commands/Commanddelwarp.java index 4fbf5f91c..4b3b9102f 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commanddelwarp.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commanddelwarp.java @@ -1,26 +1,23 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import org.bukkit.Server; +import static com.earth2me.essentials.I18n.tl; -public class Commanddelwarp extends EssentialsCommand -{ - public Commanddelwarp() - { - super("delwarp"); - } - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - - ess.getWarps().removeWarp(args[0]); - sender.sendMessage(tl("deleteWarp", args[0])); - } +public class Commanddelwarp extends EssentialsCommand { + public Commanddelwarp() { + super("delwarp"); + } + + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } + + ess.getWarps().removeWarp(args[0]); + sender.sendMessage(tl("deleteWarp", args[0])); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanddepth.java b/Essentials/src/com/earth2me/essentials/commands/Commanddepth.java index b7d56b6a1..34aa53526 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commanddepth.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commanddepth.java @@ -1,32 +1,25 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import org.bukkit.Server; +import static com.earth2me.essentials.I18n.tl; -public class Commanddepth extends EssentialsCommand -{ - public Commanddepth() - { - super("depth"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - final int depth = user.getLocation().getBlockY() - 63; - if (depth > 0) - { - user.sendMessage(tl("depthAboveSea", depth)); - } - else if (depth < 0) - { - user.sendMessage(tl("depthBelowSea", (-depth))); - } - else - { - user.sendMessage(tl("depth")); - } - } +public class Commanddepth extends EssentialsCommand { + public Commanddepth() { + super("depth"); + } + + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + final int depth = user.getLocation().getBlockY() - 63; + if (depth > 0) { + user.sendMessage(tl("depthAboveSea", depth)); + } else if (depth < 0) { + user.sendMessage(tl("depthBelowSea", (-depth))); + } else { + user.sendMessage(tl("depth")); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandeco.java b/Essentials/src/com/earth2me/essentials/commands/Commandeco.java index f589dcfed..90c78a8c9 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandeco.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandeco.java @@ -2,123 +2,100 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.ChargeException; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.NumberUtil; -import java.math.BigDecimal; -import java.util.Locale; import net.ess3.api.MaxMoneyException; import org.bukkit.Server; +import java.math.BigDecimal; +import java.util.Locale; -public class Commandeco extends EssentialsLoopCommand -{ - Commandeco.EcoCommands cmd; - BigDecimal amount; - - public Commandeco() - { - super("eco"); - } - - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 2) - { - throw new NotEnoughArgumentsException(); - } - - BigDecimal startingBalance = ess.getSettings().getStartingBalance(); - - try - { - cmd = Commandeco.EcoCommands.valueOf(args[0].toUpperCase(Locale.ENGLISH)); - amount = (cmd == Commandeco.EcoCommands.RESET) ? startingBalance : new BigDecimal(args[2].replaceAll("[^0-9\\.]", "")); - } - catch (Exception ex) - { - throw new NotEnoughArgumentsException(ex); - } - - loopOfflinePlayers(server, sender, false, true, args[1], args); - - if (cmd == Commandeco.EcoCommands.RESET || cmd == Commandeco.EcoCommands.SET) - { - if (args[1].contentEquals("**")) - { - server.broadcastMessage(tl("resetBalAll", NumberUtil.displayCurrency(amount, ess))); - } - else if (args[1].contentEquals("*")) - { - server.broadcastMessage(tl("resetBal", NumberUtil.displayCurrency(amount, ess))); - } - } - } - - @Override - protected void updatePlayer(final Server server, final CommandSource sender, final User player, final String[] args) throws NotEnoughArgumentsException, ChargeException, MaxMoneyException - { - switch (cmd) - { - case GIVE: - player.giveMoney(amount, sender); - break; - - case TAKE: - take(amount, player, sender); - break; - - case RESET: - case SET: - set(amount, player, sender); - break; - } - } - - private void take(BigDecimal amount, final User player, final CommandSource sender) throws ChargeException - { - BigDecimal money = player.getMoney(); - BigDecimal minBalance = ess.getSettings().getMinMoney(); - if (money.subtract(amount).compareTo(minBalance) > 0) - { - player.takeMoney(amount, sender); - } - else if (sender == null) - { - try - { - player.setMoney(minBalance); - } - catch (MaxMoneyException ex) - { - // Take shouldn't be able to throw a max money exception - } - player.sendMessage(tl("takenFromAccount", NumberUtil.displayCurrency(player.getMoney(), ess))); - } - else - { - throw new ChargeException(tl("insufficientFunds")); - } - } - - private void set(BigDecimal amount, final User player, final CommandSource sender) throws MaxMoneyException - { - BigDecimal minBalance = ess.getSettings().getMinMoney(); - BigDecimal maxBalance = ess.getSettings().getMaxMoney(); - boolean underMinimum = (amount.compareTo(minBalance) < 0); - boolean aboveMax = (amount.compareTo(maxBalance) > 0); - player.setMoney(underMinimum ? minBalance : aboveMax ? maxBalance : amount); - player.sendMessage(tl("setBal", NumberUtil.displayCurrency(player.getMoney(), ess))); - if (sender != null) - { - sender.sendMessage(tl("setBalOthers", player.getDisplayName(), NumberUtil.displayCurrency(player.getMoney(), ess))); - } - } +import static com.earth2me.essentials.I18n.tl; - private enum EcoCommands - { - GIVE, TAKE, SET, RESET - } +public class Commandeco extends EssentialsLoopCommand { + Commandeco.EcoCommands cmd; + BigDecimal amount; + + public Commandeco() { + super("eco"); + } + + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 2) { + throw new NotEnoughArgumentsException(); + } + + BigDecimal startingBalance = ess.getSettings().getStartingBalance(); + + try { + cmd = Commandeco.EcoCommands.valueOf(args[0].toUpperCase(Locale.ENGLISH)); + amount = (cmd == Commandeco.EcoCommands.RESET) ? startingBalance : new BigDecimal(args[2].replaceAll("[^0-9\\.]", "")); + } catch (Exception ex) { + throw new NotEnoughArgumentsException(ex); + } + + loopOfflinePlayers(server, sender, false, true, args[1], args); + + if (cmd == Commandeco.EcoCommands.RESET || cmd == Commandeco.EcoCommands.SET) { + if (args[1].contentEquals("**")) { + server.broadcastMessage(tl("resetBalAll", NumberUtil.displayCurrency(amount, ess))); + } else if (args[1].contentEquals("*")) { + server.broadcastMessage(tl("resetBal", NumberUtil.displayCurrency(amount, ess))); + } + } + } + + @Override + protected void updatePlayer(final Server server, final CommandSource sender, final User player, final String[] args) throws NotEnoughArgumentsException, ChargeException, MaxMoneyException { + switch (cmd) { + case GIVE: + player.giveMoney(amount, sender); + break; + + case TAKE: + take(amount, player, sender); + break; + + case RESET: + case SET: + set(amount, player, sender); + break; + } + } + + private void take(BigDecimal amount, final User player, final CommandSource sender) throws ChargeException { + BigDecimal money = player.getMoney(); + BigDecimal minBalance = ess.getSettings().getMinMoney(); + if (money.subtract(amount).compareTo(minBalance) > 0) { + player.takeMoney(amount, sender); + } else if (sender == null) { + try { + player.setMoney(minBalance); + } catch (MaxMoneyException ex) { + // Take shouldn't be able to throw a max money exception + } + player.sendMessage(tl("takenFromAccount", NumberUtil.displayCurrency(player.getMoney(), ess))); + } else { + throw new ChargeException(tl("insufficientFunds")); + } + } + + private void set(BigDecimal amount, final User player, final CommandSource sender) throws MaxMoneyException { + BigDecimal minBalance = ess.getSettings().getMinMoney(); + BigDecimal maxBalance = ess.getSettings().getMaxMoney(); + boolean underMinimum = (amount.compareTo(minBalance) < 0); + boolean aboveMax = (amount.compareTo(maxBalance) > 0); + player.setMoney(underMinimum ? minBalance : aboveMax ? maxBalance : amount); + player.sendMessage(tl("setBal", NumberUtil.displayCurrency(player.getMoney(), ess))); + if (sender != null) { + sender.sendMessage(tl("setBalOthers", player.getDisplayName(), NumberUtil.displayCurrency(player.getMoney(), ess))); + } + } + + + private enum EcoCommands { + GIVE, TAKE, SET, RESET + } } \ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandenchant.java b/Essentials/src/com/earth2me/essentials/commands/Commandenchant.java index feb04e97b..c3416260f 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandenchant.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandenchant.java @@ -1,80 +1,68 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.Enchantments; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.MetaItemStack; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.StringUtil; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; import org.bukkit.Material; import org.bukkit.Server; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; -public class Commandenchant extends EssentialsCommand -{ - public Commandenchant() - { - super("enchant"); - } +import static com.earth2me.essentials.I18n.tl; - //TODO: Implement charge costs: final Trade charge = new Trade("enchant-" + enchantmentName, ess); - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - final ItemStack stack = user.getBase().getItemInHand(); - if (stack == null || stack.getType() == Material.AIR) - { - throw new Exception(tl("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) || (user.isAuthorized("essentials.enchantments." + enchantmentName) && entry.getValue().canEnchantItem(stack))) - { - enchantmentslist.add(entry.getKey()); - //enchantmentslist.add(enchantmentName); - } - } - throw new NotEnoughArgumentsException(tl("enchantments", StringUtil.joinList(enchantmentslist.toArray()))); - } - int level = -1; - if (args.length > 1) - { - try - { - level = Integer.parseInt(args[1]); - } - catch (NumberFormatException ex) - { - level = -1; - } - } +public class Commandenchant extends EssentialsCommand { + public Commandenchant() { + super("enchant"); + } - final boolean allowUnsafe = ess.getSettings().allowUnsafeEnchantments() && user.isAuthorized("essentials.enchantments.allowunsafe"); - - final MetaItemStack metaStack = new MetaItemStack(stack); - final Enchantment enchantment = metaStack.getEnchantment(user, args[0]); - metaStack.addEnchantment(user.getSource(), allowUnsafe, enchantment, level); - user.getBase().getInventory().setItemInHand(metaStack.getItemStack()); - - user.getBase().updateInventory(); - final String enchantmentName = enchantment.getName().toLowerCase(Locale.ENGLISH); - if (level == 0) - { - user.sendMessage(tl("enchantmentRemoved", enchantmentName.replace('_', ' '))); - } - else - { - user.sendMessage(tl("enchantmentApplied", enchantmentName.replace('_', ' '))); - } - } + //TODO: Implement charge costs: final Trade charge = new Trade("enchant-" + enchantmentName, ess); + @Override + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + final ItemStack stack = user.getBase().getItemInHand(); + if (stack == null || stack.getType() == Material.AIR) { + throw new Exception(tl("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) || (user.isAuthorized("essentials.enchantments." + enchantmentName) && entry.getValue().canEnchantItem(stack))) { + enchantmentslist.add(entry.getKey()); + //enchantmentslist.add(enchantmentName); + } + } + throw new NotEnoughArgumentsException(tl("enchantments", StringUtil.joinList(enchantmentslist.toArray()))); + } + + int level = -1; + if (args.length > 1) { + try { + level = Integer.parseInt(args[1]); + } catch (NumberFormatException ex) { + level = -1; + } + } + + final boolean allowUnsafe = ess.getSettings().allowUnsafeEnchantments() && user.isAuthorized("essentials.enchantments.allowunsafe"); + + final MetaItemStack metaStack = new MetaItemStack(stack); + final Enchantment enchantment = metaStack.getEnchantment(user, args[0]); + metaStack.addEnchantment(user.getSource(), allowUnsafe, enchantment, level); + user.getBase().getInventory().setItemInHand(metaStack.getItemStack()); + + user.getBase().updateInventory(); + final String enchantmentName = enchantment.getName().toLowerCase(Locale.ENGLISH); + if (level == 0) { + user.sendMessage(tl("enchantmentRemoved", enchantmentName.replace('_', ' '))); + } else { + user.sendMessage(tl("enchantmentApplied", enchantmentName.replace('_', ' '))); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandenderchest.java b/Essentials/src/com/earth2me/essentials/commands/Commandenderchest.java index 94f27c42e..52be32e53 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandenderchest.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandenderchest.java @@ -4,29 +4,23 @@ import com.earth2me.essentials.User; import org.bukkit.Server; -public class Commandenderchest extends EssentialsCommand -{ - public Commandenderchest() - { - super("enderchest"); - } +public class Commandenderchest extends EssentialsCommand { + public Commandenderchest() { + super("enderchest"); + } - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (args.length > 0 && user.isAuthorized("essentials.enderchest.others")) - { - final User invUser = getPlayer(server, user, args, 0); - user.getBase().closeInventory(); - user.getBase().openInventory(invUser.getBase().getEnderChest()); - user.setEnderSee(true); - } - else - { - user.getBase().closeInventory(); - user.getBase().openInventory(user.getBase().getEnderChest()); - user.setEnderSee(false); - } + @Override + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (args.length > 0 && user.isAuthorized("essentials.enderchest.others")) { + final User invUser = getPlayer(server, user, args, 0); + user.getBase().closeInventory(); + user.getBase().openInventory(invUser.getBase().getEnderChest()); + user.setEnderSee(true); + } else { + user.getBase().closeInventory(); + user.getBase().openInventory(user.getBase().getEnderChest()); + user.setEnderSee(false); + } - } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandessentials.java b/Essentials/src/com/earth2me/essentials/commands/Commandessentials.java index 54f409b8e..1fc454757 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandessentials.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandessentials.java @@ -2,381 +2,293 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.EssentialsUpgrade; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import com.earth2me.essentials.UserMap; import com.earth2me.essentials.metrics.Metrics; import com.earth2me.essentials.utils.DateUtil; import com.earth2me.essentials.utils.NumberUtil; import com.google.common.base.Charsets; -import java.io.IOException; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import java.util.UUID; import org.bukkit.Material; import org.bukkit.Server; import org.bukkit.Sound; import org.bukkit.block.Block; import org.bukkit.entity.Player; +import java.io.IOException; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.UUID; + +import static com.earth2me.essentials.I18n.tl; + // This command has 4 undocumented behaviours #EasterEgg -public class Commandessentials extends EssentialsCommand -{ - public Commandessentials() - { - super("essentials"); - } - private transient int taskid; - private final transient Map noteBlocks = new HashMap(); +public class Commandessentials extends EssentialsCommand { + public Commandessentials() { + super("essentials"); + } - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length == 0) - { - run_disabled(server, sender, commandLabel, args); - } - else if (args[0].equalsIgnoreCase("debug")) - { - run_debug(server, sender, commandLabel, args); - } - else if (args[0].equalsIgnoreCase("nya")) - { - run_nya(server, sender, commandLabel, args); - } - else if (args[0].equalsIgnoreCase("moo")) - { - run_moo(server, sender, commandLabel, args); - } - else if (args[0].equalsIgnoreCase("reset")) - { - run_reset(server, sender, commandLabel, args); - } - else if (args[0].equalsIgnoreCase("opt-out")) - { - run_optout(server, sender, commandLabel, args); - } - else if (args[0].equalsIgnoreCase("cleanup")) - { - run_cleanup(server, sender, commandLabel, args); - } - else if (args[0].equalsIgnoreCase("uuidconvert")) - { - run_uuidconvert(server, sender, commandLabel, args); - } - else if (args[0].equalsIgnoreCase("uuidtest")) - { - run_uuidtest(server, sender, commandLabel, args); - } - else - { - run_reload(server, sender, commandLabel, args); - } - } + private transient int taskid; + private final transient Map noteBlocks = new HashMap(); - //If you do not supply an argument this command will list 'overridden' commands. - private void run_disabled(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - sender.sendMessage("/ "); + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length == 0) { + run_disabled(server, sender, commandLabel, args); + } else if (args[0].equalsIgnoreCase("debug")) { + run_debug(server, sender, commandLabel, args); + } else if (args[0].equalsIgnoreCase("nya")) { + run_nya(server, sender, commandLabel, args); + } else if (args[0].equalsIgnoreCase("moo")) { + run_moo(server, sender, commandLabel, args); + } else if (args[0].equalsIgnoreCase("reset")) { + run_reset(server, sender, commandLabel, args); + } else if (args[0].equalsIgnoreCase("opt-out")) { + run_optout(server, sender, commandLabel, args); + } else if (args[0].equalsIgnoreCase("cleanup")) { + run_cleanup(server, sender, commandLabel, args); + } else if (args[0].equalsIgnoreCase("uuidconvert")) { + run_uuidconvert(server, sender, commandLabel, args); + } else if (args[0].equalsIgnoreCase("uuidtest")) { + run_uuidtest(server, sender, commandLabel, args); + } else { + run_reload(server, sender, commandLabel, args); + } + } - final StringBuilder disabledCommands = new StringBuilder(); - for (Map.Entry entry : ess.getAlternativeCommandsHandler().disabledCommands().entrySet()) - { - if (disabledCommands.length() > 0) - { - disabledCommands.append(", "); - } - disabledCommands.append(entry.getKey()).append(" => ").append(entry.getValue()); - } - if (disabledCommands.length() > 0) - { - sender.sendMessage(tl("blockList")); - sender.sendMessage(disabledCommands.toString()); - } - } + //If you do not supply an argument this command will list 'overridden' commands. + private void run_disabled(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + sender.sendMessage("/ "); - private void run_reset(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 2) - { - throw new Exception("/ reset "); - } - final User user = getPlayer(server, args, 1, true, true); - user.reset(); - sender.sendMessage("Reset Essentials userdata for player: " + user.getDisplayName()); - } + final StringBuilder disabledCommands = new StringBuilder(); + for (Map.Entry entry : ess.getAlternativeCommandsHandler().disabledCommands().entrySet()) { + if (disabledCommands.length() > 0) { + disabledCommands.append(", "); + } + disabledCommands.append(entry.getKey()).append(" => ").append(entry.getValue()); + } + if (disabledCommands.length() > 0) { + sender.sendMessage(tl("blockList")); + sender.sendMessage(disabledCommands.toString()); + } + } - private void run_debug(final Server server, final CommandSource 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_reset(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 2) { + throw new Exception("/ reset "); + } + final User user = getPlayer(server, args, 1, true, true); + user.reset(); + sender.sendMessage("Reset Essentials userdata for player: " + user.getDisplayName()); + } - private void run_reload(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - ess.reload(); - sender.sendMessage(tl("essentialsReload", ess.getDescription().getVersion())); - } + private void run_debug(final Server server, final CommandSource 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_nya(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - final Map noteMap = new HashMap(); - noteMap.put("1F#", 0.5f); - noteMap.put("1G", 0.53f); - noteMap.put("1G#", 0.56f); - noteMap.put("1A", 0.6f); - noteMap.put("1A#", 0.63f); - noteMap.put("1B", 0.67f); - noteMap.put("1C", 0.7f); - noteMap.put("1C#", 0.76f); - noteMap.put("1D", 0.8f); - noteMap.put("1D#", 0.84f); - noteMap.put("1E", 0.9f); - noteMap.put("1F", 0.94f); - noteMap.put("2F#", 1.0f); - noteMap.put("2G", 1.06f); - noteMap.put("2G#", 1.12f); - noteMap.put("2A", 1.18f); - noteMap.put("2A#", 1.26f); - noteMap.put("2B", 1.34f); - noteMap.put("2C", 1.42f); - noteMap.put("2C#", 1.5f); - noteMap.put("2D", 1.6f); - noteMap.put("2D#", 1.68f); - noteMap.put("2E", 1.78f); - noteMap.put("2F", 1.88f); - 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(","); - taskid = ess.scheduleSyncRepeatingTask(new Runnable() - { - int i = 0; + private void run_reload(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + ess.reload(); + sender.sendMessage(tl("essentialsReload", ess.getDescription().getVersion())); + } - @Override - public void run() - { - final String note = tune[i]; - i++; - if (i >= tune.length) - { - Commandessentials.this.stopTune(); - } - if (note == null || note.isEmpty()) - { - return; - } - for (Player onlinePlayer : ess.getOnlinePlayers()) - { - onlinePlayer.playSound(onlinePlayer.getLocation(), Sound.NOTE_PIANO, 1, noteMap.get(note)); - } - } - }, 20, 2); - } + private void run_nya(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + final Map noteMap = new HashMap(); + noteMap.put("1F#", 0.5f); + noteMap.put("1G", 0.53f); + noteMap.put("1G#", 0.56f); + noteMap.put("1A", 0.6f); + noteMap.put("1A#", 0.63f); + noteMap.put("1B", 0.67f); + noteMap.put("1C", 0.7f); + noteMap.put("1C#", 0.76f); + noteMap.put("1D", 0.8f); + noteMap.put("1D#", 0.84f); + noteMap.put("1E", 0.9f); + noteMap.put("1F", 0.94f); + noteMap.put("2F#", 1.0f); + noteMap.put("2G", 1.06f); + noteMap.put("2G#", 1.12f); + noteMap.put("2A", 1.18f); + noteMap.put("2A#", 1.26f); + noteMap.put("2B", 1.34f); + noteMap.put("2C", 1.42f); + noteMap.put("2C#", 1.5f); + noteMap.put("2D", 1.6f); + noteMap.put("2D#", 1.68f); + noteMap.put("2E", 1.78f); + noteMap.put("2F", 1.88f); + 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(","); + taskid = ess.scheduleSyncRepeatingTask(new Runnable() { + int i = 0; - private void stopTune() - { - ess.getScheduler().cancelTask(taskid); - for (Block block : noteBlocks.values()) - { - if (block.getType() == Material.NOTE_BLOCK) - { - block.setType(Material.AIR); - } - } - noteBlocks.clear(); - } - private final String[] consoleMoo = new String[] - { - " (__)", - " (oo)", - " /------\\/", - " / | ||", - " * /\\---/\\", - " ~~ ~~", - "....\"Have you mooed today?\"..." - }; - private final String[] playerMoo = new String[] - { - " (__)", - " (oo)", - " /------\\/", - " / | | |", - " * /\\---/\\", - " ~~ ~~", - "....\"Have you mooed today?\"..." - }; + @Override + public void run() { + final String note = tune[i]; + i++; + if (i >= tune.length) { + Commandessentials.this.stopTune(); + } + if (note == null || note.isEmpty()) { + return; + } + for (Player onlinePlayer : ess.getOnlinePlayers()) { + onlinePlayer.playSound(onlinePlayer.getLocation(), Sound.NOTE_PIANO, 1, noteMap.get(note)); + } + } + }, 20, 2); + } - private void run_moo(final Server server, final CommandSource sender, final String command, final String args[]) - { - if (args.length == 2 && args[1].equals("moo")) - { - for (String s : consoleMoo) - { - logger.info(s); - } - for (Player player : ess.getOnlinePlayers()) - { - player.sendMessage(playerMoo); - player.playSound(player.getLocation(), Sound.COW_IDLE, 1, 1.0f); - } - } - else - { - if (sender.isPlayer()) - { - sender.getSender().sendMessage(playerMoo); - final Player player = sender.getPlayer(); - player.playSound(player.getLocation(), Sound.COW_IDLE, 1, 1.0f); + private void stopTune() { + ess.getScheduler().cancelTask(taskid); + for (Block block : noteBlocks.values()) { + if (block.getType() == Material.NOTE_BLOCK) { + block.setType(Material.AIR); + } + } + noteBlocks.clear(); + } - } - else - { - sender.getSender().sendMessage(consoleMoo); - } - } - } + private final String[] consoleMoo = new String[]{" (__)", " (oo)", " /------\\/", " / | ||", " * /\\---/\\", " ~~ ~~", "....\"Have you mooed today?\"..."}; + private final String[] playerMoo = new String[]{" (__)", " (oo)", " /------\\/", " / | | |", " * /\\---/\\", " ~~ ~~", "....\"Have you mooed today?\"..."}; - private void run_optout(final Server server, final CommandSource 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") + " for all plugins."); - } - catch (IOException ex) - { - sender.sendMessage("Unable to modify 'plugins/PluginMetrics/config.yml': " + ex.getMessage()); - } - } + private void run_moo(final Server server, final CommandSource sender, final String command, final String args[]) { + if (args.length == 2 && args[1].equals("moo")) { + for (String s : consoleMoo) { + logger.info(s); + } + for (Player player : ess.getOnlinePlayers()) { + player.sendMessage(playerMoo); + player.playSound(player.getLocation(), Sound.COW_IDLE, 1, 1.0f); + } + } else { + if (sender.isPlayer()) { + sender.getSender().sendMessage(playerMoo); + final Player player = sender.getPlayer(); + player.playSound(player.getLocation(), Sound.COW_IDLE, 1, 1.0f); - private void run_cleanup(final Server server, final CommandSource sender, final String command, final String args[]) throws Exception - { - if (args.length < 2 || !NumberUtil.isInt(args[1])) - { - sender.sendMessage("This sub-command will delete users who havent logged in in the last days."); - sender.sendMessage("Optional parameters define the minium amount required to prevent deletion."); - sender.sendMessage("Unless you define larger default values, this command wil ignore people who have more than 0 money/homes."); - throw new Exception("/ cleanup [money] [homes]"); - } - sender.sendMessage(tl("cleaning")); + } else { + sender.getSender().sendMessage(consoleMoo); + } + } + } - final long daysArg = Long.parseLong(args[1]); - final double moneyArg = args.length >= 3 ? Double.parseDouble(args[2].replaceAll("[^0-9\\.]", "")) : 0; - final int homesArg = args.length >= 4 && NumberUtil.isInt(args[3]) ? Integer.parseInt(args[3]) : 0; - final UserMap userMap = ess.getUserMap(); + private void run_optout(final Server server, final CommandSource 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") + " for all plugins."); + } catch (IOException ex) { + sender.sendMessage("Unable to modify 'plugins/PluginMetrics/config.yml': " + ex.getMessage()); + } + } - ess.runTaskAsynchronously(new Runnable() - { - @Override - public void run() - { - Long currTime = System.currentTimeMillis(); - for (UUID u : userMap.getAllUniqueUsers()) - { - final User user = ess.getUserMap().getUser(u); - if (user == null) - { - continue; - } + private void run_cleanup(final Server server, final CommandSource sender, final String command, final String args[]) throws Exception { + if (args.length < 2 || !NumberUtil.isInt(args[1])) { + sender.sendMessage("This sub-command will delete users who havent logged in in the last days."); + sender.sendMessage("Optional parameters define the minium amount required to prevent deletion."); + sender.sendMessage("Unless you define larger default values, this command wil ignore people who have more than 0 money/homes."); + throw new Exception("/ cleanup [money] [homes]"); + } + sender.sendMessage(tl("cleaning")); - long lastLog = user.getLastLogout(); - if (lastLog == 0) - { - lastLog = user.getLastLogin(); - } - if (lastLog == 0) - { - user.setLastLogin(currTime); - } + final long daysArg = Long.parseLong(args[1]); + final double moneyArg = args.length >= 3 ? Double.parseDouble(args[2].replaceAll("[^0-9\\.]", "")) : 0; + final int homesArg = args.length >= 4 && NumberUtil.isInt(args[3]) ? Integer.parseInt(args[3]) : 0; + final UserMap userMap = ess.getUserMap(); - if (user.isNPC()) - { - continue; - } + ess.runTaskAsynchronously(new Runnable() { + @Override + public void run() { + Long currTime = System.currentTimeMillis(); + for (UUID u : userMap.getAllUniqueUsers()) { + final User user = ess.getUserMap().getUser(u); + if (user == null) { + continue; + } - long timeDiff = currTime - lastLog; - long milliDays = daysArg * 24L * 60L * 60L * 1000L; - int homeCount = user.getHomes().size(); - double moneyCount = user.getMoney().doubleValue(); + long lastLog = user.getLastLogout(); + if (lastLog == 0) { + lastLog = user.getLastLogin(); + } + if (lastLog == 0) { + user.setLastLogin(currTime); + } - if ((lastLog == 0) || (timeDiff < milliDays) - || (homeCount > homesArg) || (moneyCount > moneyArg)) - { - continue; - } + if (user.isNPC()) { + continue; + } - if (ess.getSettings().isDebug()) - { - ess.getLogger().info("Deleting user: " + user.getName() + " Money: " + moneyCount + " Homes: " + homeCount + " Last seen: " + DateUtil.formatDateDiff(lastLog)); - } + long timeDiff = currTime - lastLog; + long milliDays = daysArg * 24L * 60L * 60L * 1000L; + int homeCount = user.getHomes().size(); + double moneyCount = user.getMoney().doubleValue(); - user.reset(); - } - sender.sendMessage(tl("cleaned")); - } - }); + if ((lastLog == 0) || (timeDiff < milliDays) || (homeCount > homesArg) || (moneyCount > moneyArg)) { + continue; + } - } + if (ess.getSettings().isDebug()) { + ess.getLogger().info("Deleting user: " + user.getName() + " Money: " + moneyCount + " Homes: " + homeCount + " Last seen: " + DateUtil.formatDateDiff(lastLog)); + } - private void run_uuidconvert(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - sender.sendMessage("Starting Essentials UUID userdata conversion, this may lag the server."); + user.reset(); + } + sender.sendMessage(tl("cleaned")); + } + }); - Boolean ignoreUFCache = (args.length > 2 && args[1].toLowerCase(Locale.ENGLISH).contains("ignore")); - EssentialsUpgrade.uuidFileConvert(ess, ignoreUFCache); + } - sender.sendMessage("UUID conversion complete, check your server log for more information."); - } + private void run_uuidconvert(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + sender.sendMessage("Starting Essentials UUID userdata conversion, this may lag the server."); - private void run_uuidtest(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 2) - { - throw new Exception("/ uuidtest "); - } - String name = args[1]; - sender.sendMessage("Looking up UUID for " + name); + Boolean ignoreUFCache = (args.length > 2 && args[1].toLowerCase(Locale.ENGLISH).contains("ignore")); + EssentialsUpgrade.uuidFileConvert(ess, ignoreUFCache); - UUID onlineUUID = null; + sender.sendMessage("UUID conversion complete, check your server log for more information."); + } - for (Player player : ess.getOnlinePlayers()) - { - if (player.getName().equalsIgnoreCase(name)) - { - onlineUUID = player.getUniqueId(); - break; - } - } + private void run_uuidtest(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 2) { + throw new Exception("/ uuidtest "); + } + String name = args[1]; + sender.sendMessage("Looking up UUID for " + name); - UUID essUUID = ess.getUserMap().getUser(name).getConfigUUID(); + UUID onlineUUID = null; - org.bukkit.OfflinePlayer player = ess.getServer().getOfflinePlayer(name); - UUID bukkituuid = player.getUniqueId(); - sender.sendMessage("Bukkit Lookup: " + bukkituuid.toString()); + for (Player player : ess.getOnlinePlayers()) { + if (player.getName().equalsIgnoreCase(name)) { + onlineUUID = player.getUniqueId(); + break; + } + } - if (onlineUUID != null && onlineUUID != bukkituuid) - { - sender.sendMessage("Online player: " + onlineUUID.toString()); - } + UUID essUUID = ess.getUserMap().getUser(name).getConfigUUID(); - if (essUUID != null && essUUID != bukkituuid) - { - sender.sendMessage("Essentials config: " + essUUID.toString()); - } + org.bukkit.OfflinePlayer player = ess.getServer().getOfflinePlayer(name); + UUID bukkituuid = player.getUniqueId(); + sender.sendMessage("Bukkit Lookup: " + bukkituuid.toString()); - UUID npcuuid = UUID.nameUUIDFromBytes(("NPC:" + name).getBytes(Charsets.UTF_8)); - sender.sendMessage("NPC UUID: " + npcuuid.toString()); + if (onlineUUID != null && onlineUUID != bukkituuid) { + sender.sendMessage("Online player: " + onlineUUID.toString()); + } - UUID offlineuuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8)); - sender.sendMessage("Offline Mode UUID: " + offlineuuid.toString()); - } + if (essUUID != null && essUUID != bukkituuid) { + sender.sendMessage("Essentials config: " + essUUID.toString()); + } + + UUID npcuuid = UUID.nameUUIDFromBytes(("NPC:" + name).getBytes(Charsets.UTF_8)); + sender.sendMessage("NPC UUID: " + npcuuid.toString()); + + UUID offlineuuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8)); + sender.sendMessage("Offline Mode UUID: " + offlineuuid.toString()); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandexp.java b/Essentials/src/com/earth2me/essentials/commands/Commandexp.java index 3100c9708..c764d893c 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandexp.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandexp.java @@ -1,205 +1,149 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import com.earth2me.essentials.craftbukkit.SetExpFix; import com.earth2me.essentials.utils.NumberUtil; -import java.util.List; -import java.util.Locale; import org.bukkit.Server; import org.bukkit.entity.Player; +import java.util.List; +import java.util.Locale; -public class Commandexp extends EssentialsCommand -{ - public Commandexp() - { - super("exp"); - } +import static com.earth2me.essentials.I18n.tl; - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (args.length == 0) - { - showExp(user.getSource(), user); - } - else if (args.length > 1 && args[0].equalsIgnoreCase("set") && user.isAuthorized("essentials.exp.set")) - { - if (args.length == 3 && user.isAuthorized("essentials.exp.set.others")) - { - expMatch(server, user.getSource(), args[1], args[2], false); - } - else - { - setExp(user.getSource(), user, args[1], false); - } - } - else if (args.length > 1 && args[0].equalsIgnoreCase("give") && user.isAuthorized("essentials.exp.give")) - { - if (args.length == 3 && user.isAuthorized("essentials.exp.give.others")) - { - expMatch(server, user.getSource(), args[1], args[2], true); - } - else - { - setExp(user.getSource(), user, args[1], true); - } - } - else if (args[0].equalsIgnoreCase("show")) - { - if (args.length >= 2 && user.isAuthorized("essentials.exp.others")) - { - String match = args[1].trim(); - showMatch(server, user.getSource(), match); - } - else - { - showExp(user.getSource(), user); - } - } - else - { - if (args.length >= 1 && NumberUtil.isInt(args[0].toLowerCase(Locale.ENGLISH).replace("l", "")) && user.isAuthorized("essentials.exp.give")) - { - if (args.length >= 2 && user.isAuthorized("essentials.exp.give.others")) - { - expMatch(server, user.getSource(), args[1], args[0], true); - } - else - { - setExp(user.getSource(), user, args[0], true); - } - } - else if (args.length >= 1 && user.isAuthorized("essentials.exp.others")) - { - String match = args[0].trim(); - showMatch(server, user.getSource(), match); - } - else - { - showExp(user.getSource(), user); - } - } - } - @Override - public void run(final Server server, final CommandSource 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(server, sender, args[1], args[2], false); - } - else if (args.length > 2 && args[0].equalsIgnoreCase("give")) - { - expMatch(server, sender, args[1], args[2], true); - } - else - { - String match = args[0].trim(); - if (args.length >= 2 && NumberUtil.isInt(args[0].toLowerCase(Locale.ENGLISH).replace("l", ""))) - { - match = args[1].trim(); - expMatch(server, sender, match, args[0], true); - } - else if (args.length == 1) - { - match = args[0].trim(); - } - showMatch(server, sender, match); - } - } +public class Commandexp extends EssentialsCommand { + public Commandexp() { + super("exp"); + } - private void showMatch(final Server server, final CommandSource sender, final String match) throws PlayerNotFoundException - { - boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished(); - boolean foundUser = false; - final List matchedPlayers = server.matchPlayer(match); - for (Player matchPlayer : matchedPlayers) - { - final User player = ess.getUser(matchPlayer); - if (skipHidden && player.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(matchPlayer)) - { - continue; - } - foundUser = true; - showExp(sender, player); - } - if (!foundUser) - { - throw new PlayerNotFoundException(); - } - } + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (args.length == 0) { + showExp(user.getSource(), user); + } else if (args.length > 1 && args[0].equalsIgnoreCase("set") && user.isAuthorized("essentials.exp.set")) { + if (args.length == 3 && user.isAuthorized("essentials.exp.set.others")) { + expMatch(server, user.getSource(), args[1], args[2], false); + } else { + setExp(user.getSource(), user, args[1], false); + } + } else if (args.length > 1 && args[0].equalsIgnoreCase("give") && user.isAuthorized("essentials.exp.give")) { + if (args.length == 3 && user.isAuthorized("essentials.exp.give.others")) { + expMatch(server, user.getSource(), args[1], args[2], true); + } else { + setExp(user.getSource(), user, args[1], true); + } + } else if (args[0].equalsIgnoreCase("show")) { + if (args.length >= 2 && user.isAuthorized("essentials.exp.others")) { + String match = args[1].trim(); + showMatch(server, user.getSource(), match); + } else { + showExp(user.getSource(), user); + } + } else { + if (args.length >= 1 && NumberUtil.isInt(args[0].toLowerCase(Locale.ENGLISH).replace("l", "")) && user.isAuthorized("essentials.exp.give")) { + if (args.length >= 2 && user.isAuthorized("essentials.exp.give.others")) { + expMatch(server, user.getSource(), args[1], args[0], true); + } else { + setExp(user.getSource(), user, args[0], true); + } + } else if (args.length >= 1 && user.isAuthorized("essentials.exp.others")) { + String match = args[0].trim(); + showMatch(server, user.getSource(), match); + } else { + showExp(user.getSource(), user); + } + } + } - private void expMatch(final Server server, final CommandSource sender, final String match, String amount, final boolean give) throws NotEnoughArgumentsException, PlayerNotFoundException - { - boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished(); - boolean foundUser = false; - final List matchedPlayers = server.matchPlayer(match); - for (Player matchPlayer : matchedPlayers) - { - final User player = ess.getUser(matchPlayer); - if (skipHidden && player.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(matchPlayer)) - { - continue; - } - foundUser = true; - setExp(sender, player, amount, give); - } - if (!foundUser) - { - throw new PlayerNotFoundException(); - } - } + @Override + public void run(final Server server, final CommandSource 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(server, sender, args[1], args[2], false); + } else if (args.length > 2 && args[0].equalsIgnoreCase("give")) { + expMatch(server, sender, args[1], args[2], true); + } else { + String match = args[0].trim(); + if (args.length >= 2 && NumberUtil.isInt(args[0].toLowerCase(Locale.ENGLISH).replace("l", ""))) { + match = args[1].trim(); + expMatch(server, sender, match, args[0], true); + } else if (args.length == 1) { + match = args[0].trim(); + } + showMatch(server, sender, match); + } + } - private void showExp(final CommandSource sender, final User target) - { - sender.sendMessage(tl("exp", target.getDisplayName(), SetExpFix.getTotalExperience(target.getBase()), target.getBase().getLevel(), SetExpFix.getExpUntilNextLevel(target.getBase()))); - } + private void showMatch(final Server server, final CommandSource sender, final String match) throws PlayerNotFoundException { + boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished(); + boolean foundUser = false; + final List matchedPlayers = server.matchPlayer(match); + for (Player matchPlayer : matchedPlayers) { + final User player = ess.getUser(matchPlayer); + if (skipHidden && player.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(matchPlayer)) { + continue; + } + foundUser = true; + showExp(sender, player); + } + if (!foundUser) { + throw new PlayerNotFoundException(); + } + } - //TODO: Limit who can give negative exp? - private void setExp(final CommandSource sender, final User target, String strAmount, final boolean give) throws NotEnoughArgumentsException - { - long amount; - strAmount = strAmount.toLowerCase(Locale.ENGLISH); - if (strAmount.contains("l")) - { - strAmount = strAmount.replaceAll("l", ""); - int neededLevel = Integer.parseInt(strAmount); - if (give) - { - neededLevel += target.getBase().getLevel(); - } - amount = (long)SetExpFix.getExpToLevel(neededLevel); - SetExpFix.setTotalExperience(target.getBase(), 0); - } - else - { - amount = Long.parseLong(strAmount); - if (amount > Integer.MAX_VALUE || amount < Integer.MIN_VALUE) - { - throw new NotEnoughArgumentsException(); - } - } + private void expMatch(final Server server, final CommandSource sender, final String match, String amount, final boolean give) throws NotEnoughArgumentsException, PlayerNotFoundException { + boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished(); + boolean foundUser = false; + final List matchedPlayers = server.matchPlayer(match); + for (Player matchPlayer : matchedPlayers) { + final User player = ess.getUser(matchPlayer); + if (skipHidden && player.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(matchPlayer)) { + continue; + } + foundUser = true; + setExp(sender, player, amount, give); + } + if (!foundUser) { + throw new PlayerNotFoundException(); + } + } - if (give) - { - amount += SetExpFix.getTotalExperience(target.getBase()); - } - if (amount > Integer.MAX_VALUE) - { - amount = (long)Integer.MAX_VALUE; - } - if (amount < 0l) - { - amount = 0l; - } - SetExpFix.setTotalExperience(target.getBase(), (int)amount); - sender.sendMessage(tl("expSet", target.getDisplayName(), amount)); - } + private void showExp(final CommandSource sender, final User target) { + sender.sendMessage(tl("exp", target.getDisplayName(), SetExpFix.getTotalExperience(target.getBase()), target.getBase().getLevel(), SetExpFix.getExpUntilNextLevel(target.getBase()))); + } + + //TODO: Limit who can give negative exp? + private void setExp(final CommandSource sender, final User target, String strAmount, final boolean give) throws NotEnoughArgumentsException { + long amount; + strAmount = strAmount.toLowerCase(Locale.ENGLISH); + if (strAmount.contains("l")) { + strAmount = strAmount.replaceAll("l", ""); + int neededLevel = Integer.parseInt(strAmount); + if (give) { + neededLevel += target.getBase().getLevel(); + } + amount = (long) SetExpFix.getExpToLevel(neededLevel); + SetExpFix.setTotalExperience(target.getBase(), 0); + } else { + amount = Long.parseLong(strAmount); + if (amount > Integer.MAX_VALUE || amount < Integer.MIN_VALUE) { + throw new NotEnoughArgumentsException(); + } + } + + if (give) { + amount += SetExpFix.getTotalExperience(target.getBase()); + } + if (amount > Integer.MAX_VALUE) { + amount = (long) Integer.MAX_VALUE; + } + if (amount < 0l) { + amount = 0l; + } + SetExpFix.setTotalExperience(target.getBase(), (int) amount); + sender.sendMessage(tl("expSet", target.getDisplayName(), amount)); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandext.java b/Essentials/src/com/earth2me/essentials/commands/Commandext.java index 8cba548ad..f1d325a46 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandext.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandext.java @@ -1,52 +1,45 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import org.bukkit.Server; import org.bukkit.entity.Player; +import static com.earth2me.essentials.I18n.tl; -public class Commandext extends EssentialsLoopCommand -{ - public Commandext() - { - super("ext"); - } - @Override - protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } +public class Commandext extends EssentialsLoopCommand { + public Commandext() { + super("ext"); + } - loopOnlinePlayers(server, sender, true, true, args[0], null); - } + @Override + protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - extPlayer(user.getBase()); - user.sendMessage(tl("extinguish")); - return; - } + loopOnlinePlayers(server, sender, true, true, args[0], null); + } - loopOnlinePlayers(server, user.getSource(), true, true, args[0], null); - } + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + extPlayer(user.getBase()); + user.sendMessage(tl("extinguish")); + return; + } - @Override - protected void updatePlayer(final Server server, final CommandSource sender, final User player, final String[] args) - { - extPlayer(player.getBase()); - sender.sendMessage(tl("extinguishOthers", player.getDisplayName())); - } + loopOnlinePlayers(server, user.getSource(), true, true, args[0], null); + } - private void extPlayer(final Player player) - { - player.setFireTicks(0); - } + @Override + protected void updatePlayer(final Server server, final CommandSource sender, final User player, final String[] args) { + extPlayer(player.getBase()); + sender.sendMessage(tl("extinguishOthers", player.getDisplayName())); + } + + private void extPlayer(final Player player) { + player.setFireTicks(0); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandfeed.java b/Essentials/src/com/earth2me/essentials/commands/Commandfeed.java index 545475ed3..29cf1904e 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandfeed.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandfeed.java @@ -1,76 +1,64 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import org.bukkit.Server; import org.bukkit.entity.Player; import org.bukkit.event.entity.FoodLevelChangeEvent; +import static com.earth2me.essentials.I18n.tl; -public class Commandfeed extends EssentialsLoopCommand -{ - public Commandfeed() - { - super("feed"); - } - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (!user.isAuthorized("essentials.feed.cooldown.bypass")) - { - user.healCooldown(); - } +public class Commandfeed extends EssentialsLoopCommand { + public Commandfeed() { + super("feed"); + } - if (args.length > 0 && user.isAuthorized("essentials.feed.others")) - { - loopOnlinePlayers(server, user.getSource(), true, true, args[0], null); - return; - } + @Override + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (!user.isAuthorized("essentials.feed.cooldown.bypass")) { + user.healCooldown(); + } - feedPlayer(user.getBase()); - user.sendMessage(tl("feed")); - } + if (args.length > 0 && user.isAuthorized("essentials.feed.others")) { + loopOnlinePlayers(server, user.getSource(), true, true, args[0], null); + return; + } - @Override - protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } + feedPlayer(user.getBase()); + user.sendMessage(tl("feed")); + } - loopOnlinePlayers(server, sender, true, true, args[0], null); - } + @Override + protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } - @Override - protected void updatePlayer(final Server server, final CommandSource sender, final User player, final String[] args) throws PlayerExemptException - { - try - { - feedPlayer(player.getBase()); - sender.sendMessage(tl("feedOther", player.getDisplayName())); - } - catch (QuietAbortException e) - { - //Handle Quietly - } - } + loopOnlinePlayers(server, sender, true, true, args[0], null); + } - private void feedPlayer(final Player player) throws QuietAbortException - { - final int amount = 30; + @Override + protected void updatePlayer(final Server server, final CommandSource sender, final User player, final String[] args) throws PlayerExemptException { + try { + feedPlayer(player.getBase()); + sender.sendMessage(tl("feedOther", player.getDisplayName())); + } catch (QuietAbortException e) { + //Handle Quietly + } + } - final FoodLevelChangeEvent flce = new FoodLevelChangeEvent(player, amount); - ess.getServer().getPluginManager().callEvent(flce); - if (flce.isCancelled()) - { - throw new QuietAbortException(); - } + private void feedPlayer(final Player player) throws QuietAbortException { + final int amount = 30; - player.setFoodLevel(flce.getFoodLevel() > 20 ? 20 : flce.getFoodLevel()); - player.setSaturation(10); - player.setExhaustion(0F); - } + final FoodLevelChangeEvent flce = new FoodLevelChangeEvent(player, amount); + ess.getServer().getPluginManager().callEvent(flce); + if (flce.isCancelled()) { + throw new QuietAbortException(); + } + + player.setFoodLevel(flce.getFoodLevel() > 20 ? 20 : flce.getFoodLevel()); + player.setSaturation(10); + player.setExhaustion(0F); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandfireball.java b/Essentials/src/com/earth2me/essentials/commands/Commandfireball.java index d4759802a..bfdcdaf42 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandfireball.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandfireball.java @@ -6,53 +6,36 @@ import org.bukkit.entity.*; import org.bukkit.util.Vector; -public class Commandfireball extends EssentialsCommand -{ - public Commandfireball() - { - super("fireball"); - } +public class Commandfireball extends EssentialsCommand { + public Commandfireball() { + super("fireball"); + } - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - Class type = Fireball.class; - Projectile projectile; - int speed = 2; - if (args.length > 0) - { - if (args[0].equalsIgnoreCase("small")) - { - type = SmallFireball.class; - } - else if (args[0].equalsIgnoreCase("arrow")) - { - type = Arrow.class; - } - else if (args[0].equalsIgnoreCase("skull")) - { - type = WitherSkull.class; - } - else if (args[0].equalsIgnoreCase("egg")) - { - type = Egg.class; - } - else if(args[0].equalsIgnoreCase("snowball")) - { - type = Snowball.class; - } - else if(args[0].equalsIgnoreCase("expbottle")) - { - type = ThrownExpBottle.class; - } - else if(args[0].equalsIgnoreCase("large")) - { - type = LargeFireball.class; - } - } - final Vector direction = user.getBase().getEyeLocation().getDirection().multiply(speed); - projectile = (Projectile)user.getWorld().spawn(user.getBase().getEyeLocation().add(direction.getX(), direction.getY(), direction.getZ()), type); - projectile.setShooter(user.getBase()); - projectile.setVelocity(direction); - } + @Override + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + Class type = Fireball.class; + Projectile projectile; + int speed = 2; + if (args.length > 0) { + if (args[0].equalsIgnoreCase("small")) { + type = SmallFireball.class; + } else if (args[0].equalsIgnoreCase("arrow")) { + type = Arrow.class; + } else if (args[0].equalsIgnoreCase("skull")) { + type = WitherSkull.class; + } else if (args[0].equalsIgnoreCase("egg")) { + type = Egg.class; + } else if (args[0].equalsIgnoreCase("snowball")) { + type = Snowball.class; + } else if (args[0].equalsIgnoreCase("expbottle")) { + type = ThrownExpBottle.class; + } else if (args[0].equalsIgnoreCase("large")) { + type = LargeFireball.class; + } + } + final Vector direction = user.getBase().getEyeLocation().getDirection().multiply(speed); + projectile = (Projectile) user.getWorld().spawn(user.getBase().getEyeLocation().add(direction.getX(), direction.getY(), direction.getZ()), type); + projectile.setShooter(user.getBase()); + projectile.setVelocity(direction); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandfirework.java b/Essentials/src/com/earth2me/essentials/commands/Commandfirework.java index f154a28bf..3bcf08ab0 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandfirework.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandfirework.java @@ -1,10 +1,8 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.MetaItemStack; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.NumberUtil; -import java.util.regex.Pattern; import org.bukkit.FireworkEffect; import org.bukkit.Material; import org.bukkit.Server; @@ -14,6 +12,8 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.FireworkMeta; import org.bukkit.util.Vector; +import static com.earth2me.essentials.I18n.tl; + //This command has quite a complicated syntax, in theory it has 4 seperate syntaxes which are all variable: // //1: /firework clear - This clears all of the effects on a firework stack @@ -30,123 +30,87 @@ import org.bukkit.util.Vector; //4: Possible Shapes: star, ball, large, creeper, burst //4: Possible Effects trail, twinkle -public class Commandfirework extends EssentialsCommand -{ +public class Commandfirework extends EssentialsCommand { - public Commandfirework() - { - super("firework"); - } + public Commandfirework() { + super("firework"); + } - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - final ItemStack stack = user.getBase().getItemInHand(); - if (stack.getType() == Material.FIREWORK) - { - if (args.length > 0) - { - if (args[0].equalsIgnoreCase("clear")) - { - FireworkMeta fmeta = (FireworkMeta)stack.getItemMeta(); - fmeta.clearEffects(); - stack.setItemMeta(fmeta); - user.sendMessage(tl("fireworkEffectsCleared")); - } - else if (args.length > 1 && (args[0].equalsIgnoreCase("power") || (args[0].equalsIgnoreCase("p")))) - { - FireworkMeta fmeta = (FireworkMeta)stack.getItemMeta(); - try - { - int power = Integer.parseInt(args[1]); - fmeta.setPower(power > 3 ? 4 : power); - } - catch (NumberFormatException e) - { - throw new Exception(tl("invalidFireworkFormat", args[1], args[0])); - } - stack.setItemMeta(fmeta); - } - else if ((args[0].equalsIgnoreCase("fire") || (args[0].equalsIgnoreCase("f"))) - && user.isAuthorized("essentials.firework.fire")) - { - int amount = 1; - boolean direction = false; - if (args.length > 1) - { - if (NumberUtil.isInt(args[1])) - { - final int serverLimit = ess.getSettings().getSpawnMobLimit(); - amount = Integer.parseInt(args[1]); - if (amount > serverLimit) - { - amount = serverLimit; - user.sendMessage(tl("mobSpawnLimit")); - } - } - else - { - direction = true; - } - } - for (int i = 0; i < amount; i++) - { - Firework firework = (Firework)user.getWorld().spawnEntity(user.getLocation(), EntityType.FIREWORK); - FireworkMeta fmeta = (FireworkMeta)stack.getItemMeta(); - if (direction) - { - final Vector vector = user.getBase().getEyeLocation().getDirection().multiply(0.070); - if (fmeta.getPower() > 1) - { - fmeta.setPower(1); - } - firework.setVelocity(vector); - } - firework.setFireworkMeta(fmeta); - } - } - else - { - final MetaItemStack mStack = new MetaItemStack(stack); - for (String arg : args) - { - try - { - mStack.addFireworkMeta(user.getSource(), true, arg, ess); - } - catch (Exception e) - { - user.sendMessage(tl("fireworkSyntax")); - throw e; - } - } + @Override + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + final ItemStack stack = user.getBase().getItemInHand(); + if (stack.getType() == Material.FIREWORK) { + if (args.length > 0) { + if (args[0].equalsIgnoreCase("clear")) { + FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta(); + fmeta.clearEffects(); + stack.setItemMeta(fmeta); + user.sendMessage(tl("fireworkEffectsCleared")); + } else if (args.length > 1 && (args[0].equalsIgnoreCase("power") || (args[0].equalsIgnoreCase("p")))) { + FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta(); + try { + int power = Integer.parseInt(args[1]); + fmeta.setPower(power > 3 ? 4 : power); + } catch (NumberFormatException e) { + throw new Exception(tl("invalidFireworkFormat", args[1], args[0])); + } + stack.setItemMeta(fmeta); + } else if ((args[0].equalsIgnoreCase("fire") || (args[0].equalsIgnoreCase("f"))) && user.isAuthorized("essentials.firework.fire")) { + int amount = 1; + boolean direction = false; + if (args.length > 1) { + if (NumberUtil.isInt(args[1])) { + final int serverLimit = ess.getSettings().getSpawnMobLimit(); + amount = Integer.parseInt(args[1]); + if (amount > serverLimit) { + amount = serverLimit; + user.sendMessage(tl("mobSpawnLimit")); + } + } else { + direction = true; + } + } + for (int i = 0; i < amount; i++) { + Firework firework = (Firework) user.getWorld().spawnEntity(user.getLocation(), EntityType.FIREWORK); + FireworkMeta fmeta = (FireworkMeta) stack.getItemMeta(); + if (direction) { + final Vector vector = user.getBase().getEyeLocation().getDirection().multiply(0.070); + if (fmeta.getPower() > 1) { + fmeta.setPower(1); + } + firework.setVelocity(vector); + } + firework.setFireworkMeta(fmeta); + } + } else { + final MetaItemStack mStack = new MetaItemStack(stack); + for (String arg : args) { + try { + mStack.addFireworkMeta(user.getSource(), true, arg, ess); + } catch (Exception e) { + user.sendMessage(tl("fireworkSyntax")); + throw e; + } + } - if (mStack.isValidFirework()) - { - FireworkMeta fmeta = (FireworkMeta)mStack.getItemStack().getItemMeta(); - FireworkEffect effect = mStack.getFireworkBuilder().build(); - if (fmeta.getEffects().size() > 0 && !user.isAuthorized("essentials.firework.multiple")) - { - throw new Exception(tl("multipleCharges")); - } - fmeta.addEffect(effect); - stack.setItemMeta(fmeta); - } - else - { - user.sendMessage(tl("fireworkSyntax")); - throw new Exception(tl("fireworkColor")); - } - } - } - else - { - throw new NotEnoughArgumentsException(); - } - } - else - { - throw new Exception(tl("holdFirework")); - } - } + if (mStack.isValidFirework()) { + FireworkMeta fmeta = (FireworkMeta) mStack.getItemStack().getItemMeta(); + FireworkEffect effect = mStack.getFireworkBuilder().build(); + if (fmeta.getEffects().size() > 0 && !user.isAuthorized("essentials.firework.multiple")) { + throw new Exception(tl("multipleCharges")); + } + fmeta.addEffect(effect); + stack.setItemMeta(fmeta); + } else { + user.sendMessage(tl("fireworkSyntax")); + throw new Exception(tl("fireworkColor")); + } + } + } else { + throw new NotEnoughArgumentsException(); + } + } else { + throw new Exception(tl("holdFirework")); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandfly.java b/Essentials/src/com/earth2me/essentials/commands/Commandfly.java index 790d351ab..9b30e4ff9 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandfly.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandfly.java @@ -1,69 +1,54 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import org.bukkit.Server; +import static com.earth2me.essentials.I18n.tl; -public class Commandfly extends EssentialsToggleCommand -{ - public Commandfly() - { - super("fly", "essentials.fly.others"); - } - @Override - protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - toggleOtherPlayers(server, sender, args); - } +public class Commandfly extends EssentialsToggleCommand { + public Commandfly() { + super("fly", "essentials.fly.others"); + } - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (args.length == 1) - { - Boolean toggle = matchToggleArgument(args[0]); - if (toggle == null && user.isAuthorized(othersPermission)) - { - toggleOtherPlayers(server, user.getSource(), args); - } - else - { - togglePlayer(user.getSource(), user, toggle); - } - } - else if (args.length == 2 && user.isAuthorized(othersPermission)) - { - toggleOtherPlayers(server, user.getSource(), args); - } - else - { - togglePlayer(user.getSource(), user, null); - } - } + @Override + protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + toggleOtherPlayers(server, sender, args); + } - @Override - void togglePlayer(CommandSource sender, User user, Boolean enabled) - { - if (enabled == null) - { - enabled = !user.getBase().getAllowFlight(); - } + @Override + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (args.length == 1) { + Boolean toggle = matchToggleArgument(args[0]); + if (toggle == null && user.isAuthorized(othersPermission)) { + toggleOtherPlayers(server, user.getSource(), args); + } else { + togglePlayer(user.getSource(), user, toggle); + } + } else if (args.length == 2 && user.isAuthorized(othersPermission)) { + toggleOtherPlayers(server, user.getSource(), args); + } else { + togglePlayer(user.getSource(), user, null); + } + } - user.getBase().setFallDistance(0f); - user.getBase().setAllowFlight(enabled); - - if (!user.getBase().getAllowFlight()) - { - user.getBase().setFlying(false); - } + @Override + void togglePlayer(CommandSource sender, User user, Boolean enabled) { + if (enabled == null) { + enabled = !user.getBase().getAllowFlight(); + } - user.sendMessage(tl("flyMode", tl(enabled ? "enabled" : "disabled"), user.getDisplayName())); - if (!sender.isPlayer() || !sender.getPlayer().equals(user.getBase())) - { - sender.sendMessage(tl("flyMode", tl(enabled ? "enabled" : "disabled"), user.getDisplayName())); - } - } + user.getBase().setFallDistance(0f); + user.getBase().setAllowFlight(enabled); + + if (!user.getBase().getAllowFlight()) { + user.getBase().setFlying(false); + } + + user.sendMessage(tl("flyMode", tl(enabled ? "enabled" : "disabled"), user.getDisplayName())); + if (!sender.isPlayer() || !sender.getPlayer().equals(user.getBase())) { + sender.sendMessage(tl("flyMode", tl(enabled ? "enabled" : "disabled"), user.getDisplayName())); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandgamemode.java b/Essentials/src/com/earth2me/essentials/commands/Commandgamemode.java index 4b91d0582..d149278bd 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandgamemode.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandgamemode.java @@ -1,136 +1,100 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; -import java.util.List; -import java.util.Locale; import org.bukkit.GameMode; import org.bukkit.Server; import org.bukkit.entity.Player; +import java.util.List; +import java.util.Locale; -public class Commandgamemode extends EssentialsCommand -{ - public Commandgamemode() - { - super("gamemode"); - } +import static com.earth2me.essentials.I18n.tl; - @Override - protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - GameMode gameMode; - if (args.length == 0) - { - throw new NotEnoughArgumentsException(); - } - else if (args.length == 1) - { - gameMode = matchGameMode(commandLabel); - gamemodeOtherPlayers(server, sender, gameMode, args[0]); - } - else if (args.length == 2) - { - gameMode = matchGameMode(args[0].toLowerCase(Locale.ENGLISH)); - gamemodeOtherPlayers(server, sender, gameMode, args[1]); - } - } +public class Commandgamemode extends EssentialsCommand { + public Commandgamemode() { + super("gamemode"); + } - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - GameMode gameMode; - if (args.length == 0) - { - gameMode = matchGameMode(commandLabel); - } - else if (args.length > 1 && args[1].trim().length() > 2 && user.isAuthorized("essentials.gamemode.others")) - { - gameMode = matchGameMode(args[0].toLowerCase(Locale.ENGLISH)); - gamemodeOtherPlayers(server, user.getSource(), gameMode, args[1]); - return; - } - else - { - try - { - gameMode = matchGameMode(args[0].toLowerCase(Locale.ENGLISH)); - } - catch (NotEnoughArgumentsException e) - { - if (user.isAuthorized("essentials.gamemode.others")) - { - gameMode = matchGameMode(commandLabel); - gamemodeOtherPlayers(server, user.getSource(), gameMode, args[0]); - return; - } - throw new NotEnoughArgumentsException(); - } - } - if (gameMode == null) - { - gameMode = user.getBase().getGameMode() == GameMode.SURVIVAL ? GameMode.CREATIVE : user.getBase().getGameMode() == GameMode.CREATIVE ? GameMode.ADVENTURE : GameMode.SURVIVAL; - } - user.getBase().setGameMode(gameMode); - user.sendMessage(tl("gameMode", tl(user.getBase().getGameMode().toString().toLowerCase(Locale.ENGLISH)), user.getDisplayName())); - } + @Override + protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + GameMode gameMode; + if (args.length == 0) { + throw new NotEnoughArgumentsException(); + } else if (args.length == 1) { + gameMode = matchGameMode(commandLabel); + gamemodeOtherPlayers(server, sender, gameMode, args[0]); + } else if (args.length == 2) { + gameMode = matchGameMode(args[0].toLowerCase(Locale.ENGLISH)); + gamemodeOtherPlayers(server, sender, gameMode, args[1]); + } - private void gamemodeOtherPlayers(final Server server, final CommandSource sender, final GameMode gameMode, final String name) throws NotEnoughArgumentsException, PlayerNotFoundException - { - if (name.trim().length() < 2 || gameMode == null) - { - throw new NotEnoughArgumentsException(tl("gameModeInvalid")); - } + } - boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished(); - boolean foundUser = false; - final List matchedPlayers = server.matchPlayer(name); - for (Player matchPlayer : matchedPlayers) - { - final User player = ess.getUser(matchPlayer); - if (skipHidden && player.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(matchPlayer)) - { - continue; - } - foundUser = true; - player.getBase().setGameMode(gameMode); - sender.sendMessage(tl("gameMode", tl(player.getBase().getGameMode().toString().toLowerCase(Locale.ENGLISH)), player.getDisplayName())); - } - if (!foundUser) - { - throw new PlayerNotFoundException(); - } - } + @Override + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + GameMode gameMode; + if (args.length == 0) { + gameMode = matchGameMode(commandLabel); + } else if (args.length > 1 && args[1].trim().length() > 2 && user.isAuthorized("essentials.gamemode.others")) { + gameMode = matchGameMode(args[0].toLowerCase(Locale.ENGLISH)); + gamemodeOtherPlayers(server, user.getSource(), gameMode, args[1]); + return; + } else { + try { + gameMode = matchGameMode(args[0].toLowerCase(Locale.ENGLISH)); + } catch (NotEnoughArgumentsException e) { + if (user.isAuthorized("essentials.gamemode.others")) { + gameMode = matchGameMode(commandLabel); + gamemodeOtherPlayers(server, user.getSource(), gameMode, args[0]); + return; + } + throw new NotEnoughArgumentsException(); + } + } + if (gameMode == null) { + gameMode = user.getBase().getGameMode() == GameMode.SURVIVAL ? GameMode.CREATIVE : user.getBase().getGameMode() == GameMode.CREATIVE ? GameMode.ADVENTURE : GameMode.SURVIVAL; + } + user.getBase().setGameMode(gameMode); + user.sendMessage(tl("gameMode", tl(user.getBase().getGameMode().toString().toLowerCase(Locale.ENGLISH)), user.getDisplayName())); + } - private GameMode matchGameMode(String modeString) throws NotEnoughArgumentsException - { - GameMode mode = null; - if (modeString.equalsIgnoreCase("gmc") || modeString.equalsIgnoreCase("egmc") - || modeString.contains("creat") || modeString.equalsIgnoreCase("1") || modeString.equalsIgnoreCase("c")) - { - mode = GameMode.CREATIVE; - } - else if (modeString.equalsIgnoreCase("gms") || modeString.equalsIgnoreCase("egms") - || modeString.contains("survi") || modeString.equalsIgnoreCase("0") || modeString.equalsIgnoreCase("s")) - { - mode = GameMode.SURVIVAL; - } - else if (modeString.equalsIgnoreCase("gma") || modeString.equalsIgnoreCase("egma") - || modeString.contains("advent") || modeString.equalsIgnoreCase("2") || modeString.equalsIgnoreCase("a")) - { - mode = GameMode.ADVENTURE; - } - else if (modeString.equalsIgnoreCase("gmt") || modeString.equalsIgnoreCase("egmt") - || modeString.contains("toggle") || modeString.contains("cycle") || modeString.equalsIgnoreCase("t")) - { - mode = null; - } - else - { - throw new NotEnoughArgumentsException(); - } - return mode; - } + private void gamemodeOtherPlayers(final Server server, final CommandSource sender, final GameMode gameMode, final String name) throws NotEnoughArgumentsException, PlayerNotFoundException { + if (name.trim().length() < 2 || gameMode == null) { + throw new NotEnoughArgumentsException(tl("gameModeInvalid")); + } + + boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished(); + boolean foundUser = false; + final List matchedPlayers = server.matchPlayer(name); + for (Player matchPlayer : matchedPlayers) { + final User player = ess.getUser(matchPlayer); + if (skipHidden && player.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(matchPlayer)) { + continue; + } + foundUser = true; + player.getBase().setGameMode(gameMode); + sender.sendMessage(tl("gameMode", tl(player.getBase().getGameMode().toString().toLowerCase(Locale.ENGLISH)), player.getDisplayName())); + } + if (!foundUser) { + throw new PlayerNotFoundException(); + } + } + + private GameMode matchGameMode(String modeString) throws NotEnoughArgumentsException { + GameMode mode = null; + if (modeString.equalsIgnoreCase("gmc") || modeString.equalsIgnoreCase("egmc") || modeString.contains("creat") || modeString.equalsIgnoreCase("1") || modeString.equalsIgnoreCase("c")) { + mode = GameMode.CREATIVE; + } else if (modeString.equalsIgnoreCase("gms") || modeString.equalsIgnoreCase("egms") || modeString.contains("survi") || modeString.equalsIgnoreCase("0") || modeString.equalsIgnoreCase("s")) { + mode = GameMode.SURVIVAL; + } else if (modeString.equalsIgnoreCase("gma") || modeString.equalsIgnoreCase("egma") || modeString.contains("advent") || modeString.equalsIgnoreCase("2") || modeString.equalsIgnoreCase("a")) { + mode = GameMode.ADVENTURE; + } else if (modeString.equalsIgnoreCase("gmt") || modeString.equalsIgnoreCase("egmt") || modeString.contains("toggle") || modeString.contains("cycle") || modeString.equalsIgnoreCase("t")) { + mode = null; + } else { + throw new NotEnoughArgumentsException(); + } + return mode; + } } \ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandgc.java b/Essentials/src/com/earth2me/essentials/commands/Commandgc.java index db4432351..1d79213d1 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandgc.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandgc.java @@ -1,79 +1,63 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.utils.DateUtil; import com.earth2me.essentials.utils.NumberUtil; +import org.bukkit.*; + import java.lang.management.ManagementFactory; import java.util.List; import java.util.logging.Level; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Chunk; -import org.bukkit.Server; -import org.bukkit.World; + +import static com.earth2me.essentials.I18n.tl; -public class Commandgc extends EssentialsCommand -{ - public Commandgc() - { - super("gc"); - } +public class Commandgc extends EssentialsCommand { + public Commandgc() { + super("gc"); + } - @Override - protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - double tps = ess.getTimer().getAverageTPS(); - ChatColor color; - if (tps >= 18.0) - { - color = ChatColor.GREEN; - } - else if (tps >= 15.0) - { - color = ChatColor.YELLOW; - } - else - { - color = ChatColor.RED; - } + @Override + protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + double tps = ess.getTimer().getAverageTPS(); + ChatColor color; + if (tps >= 18.0) { + color = ChatColor.GREEN; + } else if (tps >= 15.0) { + color = ChatColor.YELLOW; + } else { + color = ChatColor.RED; + } - sender.sendMessage(tl("uptime", DateUtil.formatDateDiff(ManagementFactory.getRuntimeMXBean().getStartTime()))); - sender.sendMessage(tl("tps", "" + color + NumberUtil.formatDouble(tps))); - sender.sendMessage(tl("gcmax", (Runtime.getRuntime().maxMemory() / 1024 / 1024))); - sender.sendMessage(tl("gctotal", (Runtime.getRuntime().totalMemory() / 1024 / 1024))); - sender.sendMessage(tl("gcfree", (Runtime.getRuntime().freeMemory() / 1024 / 1024))); + sender.sendMessage(tl("uptime", DateUtil.formatDateDiff(ManagementFactory.getRuntimeMXBean().getStartTime()))); + sender.sendMessage(tl("tps", "" + color + NumberUtil.formatDouble(tps))); + sender.sendMessage(tl("gcmax", (Runtime.getRuntime().maxMemory() / 1024 / 1024))); + sender.sendMessage(tl("gctotal", (Runtime.getRuntime().totalMemory() / 1024 / 1024))); + sender.sendMessage(tl("gcfree", (Runtime.getRuntime().freeMemory() / 1024 / 1024))); - List worlds = server.getWorlds(); - for (World w : worlds) - { - String worldType = "World"; - switch (w.getEnvironment()) - { - case NETHER: - worldType = "Nether"; - break; - case THE_END: - worldType = "The End"; - break; - } + List worlds = server.getWorlds(); + for (World w : worlds) { + String worldType = "World"; + switch (w.getEnvironment()) { + case NETHER: + worldType = "Nether"; + break; + case THE_END: + worldType = "The End"; + break; + } - int tileEntities = 0; + int tileEntities = 0; - try - { - for (Chunk chunk : w.getLoadedChunks()) - { - tileEntities += chunk.getTileEntities().length; - } - } - catch (java.lang.ClassCastException ex) - { - Bukkit.getLogger().log(Level.SEVERE, "Corrupted chunk data on world " + w, ex); - } + try { + for (Chunk chunk : w.getLoadedChunks()) { + tileEntities += chunk.getTileEntities().length; + } + } catch (java.lang.ClassCastException ex) { + Bukkit.getLogger().log(Level.SEVERE, "Corrupted chunk data on world " + w, ex); + } - sender.sendMessage(tl("gcWorld", worldType, w.getName(), w.getLoadedChunks().length, w.getEntities().size(), tileEntities)); - } - } + sender.sendMessage(tl("gcWorld", worldType, w.getName(), w.getLoadedChunks().length, w.getEntities().size(), tileEntities)); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandgetpos.java b/Essentials/src/com/earth2me/essentials/commands/Commandgetpos.java index f76d28e03..c0a412320 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandgetpos.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandgetpos.java @@ -1,53 +1,46 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import org.bukkit.Location; import org.bukkit.Server; +import static com.earth2me.essentials.I18n.tl; -public class Commandgetpos extends EssentialsCommand -{ - public Commandgetpos() - { - super("getpos"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (args.length > 0 && user.isAuthorized("essentials.getpos.others")) - { - final User otherUser = getPlayer(server, user, args, 0); - outputPosition(user.getSource(), otherUser.getLocation(), user.getLocation()); - return; - } - outputPosition(user.getSource(), user.getLocation(), null); - } +public class Commandgetpos extends EssentialsCommand { + public Commandgetpos() { + super("getpos"); + } - @Override - protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - final User user = getPlayer(server, args, 0, true, false); - outputPosition(sender, user.getLocation(), null); - } + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (args.length > 0 && user.isAuthorized("essentials.getpos.others")) { + final User otherUser = getPlayer(server, user, args, 0); + outputPosition(user.getSource(), otherUser.getLocation(), user.getLocation()); + return; + } + outputPosition(user.getSource(), user.getLocation(), null); + } - private void outputPosition(final CommandSource sender, final Location coords, final Location distance) - { - sender.sendMessage(tl("currentWorld", coords.getWorld().getName())); - sender.sendMessage(tl("posX", coords.getBlockX())); - sender.sendMessage(tl("posY", coords.getBlockY())); - sender.sendMessage(tl("posZ", coords.getBlockZ())); - sender.sendMessage(tl("posYaw", (coords.getYaw() + 180 + 360) % 360)); - sender.sendMessage(tl("posPitch", coords.getPitch())); - if (distance != null && coords.getWorld().equals(distance.getWorld())) - { - sender.sendMessage(tl("distance", coords.distance(distance))); - } - } + @Override + protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } + final User user = getPlayer(server, args, 0, true, false); + outputPosition(sender, user.getLocation(), null); + } + + private void outputPosition(final CommandSource sender, final Location coords, final Location distance) { + sender.sendMessage(tl("currentWorld", coords.getWorld().getName())); + sender.sendMessage(tl("posX", coords.getBlockX())); + sender.sendMessage(tl("posY", coords.getBlockY())); + sender.sendMessage(tl("posZ", coords.getBlockZ())); + sender.sendMessage(tl("posYaw", (coords.getYaw() + 180 + 360) % 360)); + sender.sendMessage(tl("posPitch", coords.getPitch())); + if (distance != null && coords.getWorld().equals(distance.getWorld())) { + sender.sendMessage(tl("distance", coords.distance(distance))); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandgive.java b/Essentials/src/com/earth2me/essentials/commands/Commandgive.java index 8e8a6dfc4..8411103f1 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandgive.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandgive.java @@ -1,122 +1,94 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.MetaItemStack; import com.earth2me.essentials.User; import com.earth2me.essentials.craftbukkit.InventoryWorkaround; import com.earth2me.essentials.utils.NumberUtil; -import java.util.Locale; -import java.util.Map; import org.bukkit.Material; import org.bukkit.Server; import org.bukkit.inventory.ItemStack; +import java.util.Locale; +import java.util.Map; -public class Commandgive extends EssentialsCommand -{ - public Commandgive() - { - super("give"); - } +import static com.earth2me.essentials.I18n.tl; - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 2) - { - throw new NotEnoughArgumentsException(); - } - ItemStack stack = ess.getItemDb().get(args[1]); +public class Commandgive extends EssentialsCommand { + public Commandgive() { + super("give"); + } - final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""); - if (sender.isPlayer() - && (ess.getSettings().permissionBasedItemSpawn() - ? (!ess.getUser(sender.getPlayer()).isAuthorized("essentials.itemspawn.item-all") - && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.itemspawn.item-" + itemname) - && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.itemspawn.item-" + stack.getTypeId())) - : (!ess.getUser(sender.getPlayer()).isAuthorized("essentials.itemspawn.exempt") - && !ess.getUser(sender.getPlayer()).canSpawnItem(stack.getTypeId())))) - { - throw new Exception(tl("cantSpawnItem", itemname)); - } + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 2) { + throw new NotEnoughArgumentsException(); + } - final User giveTo = getPlayer(server, sender, args, 0); + ItemStack stack = ess.getItemDb().get(args[1]); - try - { - if (args.length > 3 && NumberUtil.isInt(args[2]) && NumberUtil.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])); - } - else if (ess.getSettings().getDefaultStackSize() > 0) - { - stack.setAmount(ess.getSettings().getDefaultStackSize()); - } - else if (ess.getSettings().getOversizedStackSize() > 0 && giveTo.isAuthorized("essentials.oversizedstacks")) - { - stack.setAmount(ess.getSettings().getOversizedStackSize()); - } - } - catch (NumberFormatException e) - { - throw new NotEnoughArgumentsException(); - } + final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""); + if (sender.isPlayer() && (ess.getSettings().permissionBasedItemSpawn() ? (!ess.getUser(sender.getPlayer()).isAuthorized("essentials.itemspawn.item-all") && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.itemspawn.item-" + itemname) && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.itemspawn.item-" + stack.getTypeId())) : (!ess.getUser(sender.getPlayer()).isAuthorized("essentials.itemspawn.exempt") && !ess.getUser(sender.getPlayer()).canSpawnItem(stack.getTypeId())))) { + throw new Exception(tl("cantSpawnItem", itemname)); + } - MetaItemStack metaStack = new MetaItemStack(stack); - if (!metaStack.canSpawn(ess)) - { - throw new Exception(tl("unableToSpawnItem", itemname)); - } + final User giveTo = getPlayer(server, sender, args, 0); - if (args.length > 3) - { - boolean allowUnsafe = ess.getSettings().allowUnsafeEnchantments(); - if (allowUnsafe && sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.enchantments.allowunsafe")) - { - allowUnsafe = false; - } + try { + if (args.length > 3 && NumberUtil.isInt(args[2]) && NumberUtil.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])); + } else if (ess.getSettings().getDefaultStackSize() > 0) { + stack.setAmount(ess.getSettings().getDefaultStackSize()); + } else if (ess.getSettings().getOversizedStackSize() > 0 && giveTo.isAuthorized("essentials.oversizedstacks")) { + stack.setAmount(ess.getSettings().getOversizedStackSize()); + } + } catch (NumberFormatException e) { + throw new NotEnoughArgumentsException(); + } - int metaStart = NumberUtil.isInt(args[3]) ? 4 : 3; + MetaItemStack metaStack = new MetaItemStack(stack); + if (!metaStack.canSpawn(ess)) { + throw new Exception(tl("unableToSpawnItem", itemname)); + } - if (args.length > metaStart) - { - metaStack.parseStringMeta(sender, allowUnsafe, args, metaStart, ess); - } + if (args.length > 3) { + boolean allowUnsafe = ess.getSettings().allowUnsafeEnchantments(); + if (allowUnsafe && sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.enchantments.allowunsafe")) { + allowUnsafe = false; + } - stack = metaStack.getItemStack(); - } + int metaStart = NumberUtil.isInt(args[3]) ? 4 : 3; - if (stack.getType() == Material.AIR) - { - throw new Exception(tl("cantSpawnItem", "Air")); - } + if (args.length > metaStart) { + metaStack.parseStringMeta(sender, allowUnsafe, args, metaStart, ess); + } - final String itemName = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace('_', ' '); - sender.sendMessage(tl("giveSpawn", stack.getAmount(), itemName, giveTo.getDisplayName())); + stack = metaStack.getItemStack(); + } - Map leftovers; + if (stack.getType() == Material.AIR) { + throw new Exception(tl("cantSpawnItem", "Air")); + } - if (giveTo.isAuthorized("essentials.oversizedstacks")) - { - leftovers = InventoryWorkaround.addOversizedItems(giveTo.getBase().getInventory(), ess.getSettings().getOversizedStackSize(), stack); - } - else - { - leftovers = InventoryWorkaround.addItems(giveTo.getBase().getInventory(), stack); - } + final String itemName = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace('_', ' '); + sender.sendMessage(tl("giveSpawn", stack.getAmount(), itemName, giveTo.getDisplayName())); - for (ItemStack item : leftovers.values()) - { - sender.sendMessage(tl("giveSpawnFailure", item.getAmount(), itemName, giveTo.getDisplayName())); - } + Map leftovers; - giveTo.getBase().updateInventory(); - } + if (giveTo.isAuthorized("essentials.oversizedstacks")) { + leftovers = InventoryWorkaround.addOversizedItems(giveTo.getBase().getInventory(), ess.getSettings().getOversizedStackSize(), stack); + } else { + leftovers = InventoryWorkaround.addItems(giveTo.getBase().getInventory(), stack); + } + + for (ItemStack item : leftovers.values()) { + sender.sendMessage(tl("giveSpawnFailure", item.getAmount(), itemName, giveTo.getDisplayName())); + } + + giveTo.getBase().updateInventory(); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandgod.java b/Essentials/src/com/earth2me/essentials/commands/Commandgod.java index b758f6493..5e156476f 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandgod.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandgod.java @@ -1,76 +1,60 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import net.ess3.api.events.GodStatusChangeEvent; import org.bukkit.Server; +import static com.earth2me.essentials.I18n.tl; -public class Commandgod extends EssentialsToggleCommand -{ - public Commandgod() - { - super("god", "essentials.god.others"); - } - @Override - protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - toggleOtherPlayers(server, sender, args); - } +public class Commandgod extends EssentialsToggleCommand { + public Commandgod() { + super("god", "essentials.god.others"); + } - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (args.length == 1) - { - Boolean toggle = matchToggleArgument(args[0]); - if (toggle == null && user.isAuthorized(othersPermission)) - { - toggleOtherPlayers(server, user.getSource(), args); - } - else - { - togglePlayer(user.getSource(), user, toggle); - } - } - else if (args.length == 2 && user.isAuthorized(othersPermission)) - { - toggleOtherPlayers(server, user.getSource(), args); - } - else - { - togglePlayer(user.getSource(), user, null); - } - } + @Override + protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + toggleOtherPlayers(server, sender, args); + } - @Override - void togglePlayer(CommandSource sender, User user, Boolean enabled) - { - if (enabled == null) - { - enabled = !user.isGodModeEnabled(); - } + @Override + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (args.length == 1) { + Boolean toggle = matchToggleArgument(args[0]); + if (toggle == null && user.isAuthorized(othersPermission)) { + toggleOtherPlayers(server, user.getSource(), args); + } else { + togglePlayer(user.getSource(), user, toggle); + } + } else if (args.length == 2 && user.isAuthorized(othersPermission)) { + toggleOtherPlayers(server, user.getSource(), args); + } else { + togglePlayer(user.getSource(), user, null); + } + } - final User controller = sender.isPlayer() ? ess.getUser(sender.getPlayer()) : null; - final GodStatusChangeEvent godEvent = new GodStatusChangeEvent(controller, user, enabled); - ess.getServer().getPluginManager().callEvent(godEvent); - if (!godEvent.isCancelled()) - { - user.setGodModeEnabled(enabled); + @Override + void togglePlayer(CommandSource sender, User user, Boolean enabled) { + if (enabled == null) { + enabled = !user.isGodModeEnabled(); + } - if (enabled && user.getBase().getHealth() != 0) - { - user.getBase().setHealth(user.getBase().getMaxHealth()); - user.getBase().setFoodLevel(20); - } + final User controller = sender.isPlayer() ? ess.getUser(sender.getPlayer()) : null; + final GodStatusChangeEvent godEvent = new GodStatusChangeEvent(controller, user, enabled); + ess.getServer().getPluginManager().callEvent(godEvent); + if (!godEvent.isCancelled()) { + user.setGodModeEnabled(enabled); - user.sendMessage(tl("godMode", enabled ? tl("enabled") : tl("disabled"))); - if (!sender.isPlayer() || !sender.getPlayer().equals(user.getBase())) - { - sender.sendMessage(tl("godMode", tl(enabled ? "godEnabledFor" : "godDisabledFor", user.getDisplayName()))); - } - } - } + if (enabled && user.getBase().getHealth() != 0) { + user.getBase().setHealth(user.getBase().getMaxHealth()); + user.getBase().setFoodLevel(20); + } + + user.sendMessage(tl("godMode", enabled ? tl("enabled") : tl("disabled"))); + if (!sender.isPlayer() || !sender.getPlayer().equals(user.getBase())) { + sender.sendMessage(tl("godMode", tl(enabled ? "godEnabledFor" : "godDisabledFor", user.getDisplayName()))); + } + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandhat.java b/Essentials/src/com/earth2me/essentials/commands/Commandhat.java index 4f042ba60..969526485 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandhat.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandhat.java @@ -1,6 +1,5 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import com.earth2me.essentials.craftbukkit.InventoryWorkaround; import org.bukkit.Material; @@ -8,55 +7,42 @@ import org.bukkit.Server; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; +import static com.earth2me.essentials.I18n.tl; -public class Commandhat extends EssentialsCommand -{ - public Commandhat() - { - super("hat"); - } - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (args.length > 0 && (args[0].contains("rem") || args[0].contains("off") || args[0].equalsIgnoreCase("0"))) - { - final PlayerInventory inv = user.getBase().getInventory(); - final ItemStack head = inv.getHelmet(); - if (head == null || head.getType() == Material.AIR) - { - user.sendMessage(tl("hatEmpty")); - } - else - { - final ItemStack air = new ItemStack(Material.AIR); - inv.setHelmet(air); - InventoryWorkaround.addItems(user.getBase().getInventory(), head); - user.sendMessage(tl("hatRemoved")); - } - } - else - { - if (user.getBase().getItemInHand().getType() != Material.AIR) - { - final ItemStack hand = user.getBase().getItemInHand(); - if (hand.getType().getMaxDurability() == 0) - { - final PlayerInventory inv = user.getBase().getInventory(); - final ItemStack head = inv.getHelmet(); - inv.setHelmet(hand); - inv.setItemInHand(head); - user.sendMessage(tl("hatPlaced")); - } - else - { - user.sendMessage(tl("hatArmor")); - } - } - else - { - user.sendMessage(tl("hatFail")); - } - } - } +public class Commandhat extends EssentialsCommand { + public Commandhat() { + super("hat"); + } + + @Override + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (args.length > 0 && (args[0].contains("rem") || args[0].contains("off") || args[0].equalsIgnoreCase("0"))) { + final PlayerInventory inv = user.getBase().getInventory(); + final ItemStack head = inv.getHelmet(); + if (head == null || head.getType() == Material.AIR) { + user.sendMessage(tl("hatEmpty")); + } else { + final ItemStack air = new ItemStack(Material.AIR); + inv.setHelmet(air); + InventoryWorkaround.addItems(user.getBase().getInventory(), head); + user.sendMessage(tl("hatRemoved")); + } + } else { + if (user.getBase().getItemInHand().getType() != Material.AIR) { + final ItemStack hand = user.getBase().getItemInHand(); + if (hand.getType().getMaxDurability() == 0) { + final PlayerInventory inv = user.getBase().getInventory(); + final ItemStack head = inv.getHelmet(); + inv.setHelmet(hand); + inv.setItemInHand(head); + user.sendMessage(tl("hatPlaced")); + } else { + user.sendMessage(tl("hatArmor")); + } + } else { + user.sendMessage(tl("hatFail")); + } + } + } } \ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandheal.java b/Essentials/src/com/earth2me/essentials/commands/Commandheal.java index 6890af09f..e089fce02 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandheal.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandheal.java @@ -1,7 +1,6 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import org.bukkit.Server; import org.bukkit.entity.Player; @@ -9,86 +8,72 @@ import org.bukkit.event.entity.EntityRegainHealthEvent; import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason; import org.bukkit.potion.PotionEffect; +import static com.earth2me.essentials.I18n.tl; -public class Commandheal extends EssentialsLoopCommand -{ - public Commandheal() - { - super("heal"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (!user.isAuthorized("essentials.heal.cooldown.bypass")) - { - user.healCooldown(); - } +public class Commandheal extends EssentialsLoopCommand { + public Commandheal() { + super("heal"); + } - if (args.length > 0 && user.isAuthorized("essentials.heal.others")) - { - loopOnlinePlayers(server, user.getSource(), true, true, args[0], null); - return; - } + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (!user.isAuthorized("essentials.heal.cooldown.bypass")) { + user.healCooldown(); + } - healPlayer(user); - } + if (args.length > 0 && user.isAuthorized("essentials.heal.others")) { + loopOnlinePlayers(server, user.getSource(), true, true, args[0], null); + return; + } - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } + healPlayer(user); + } - loopOnlinePlayers(server, sender, true, true, args[0], null); - } + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } - @Override - protected void updatePlayer(final Server server, final CommandSource sender, final User player, final String[] args) throws PlayerExemptException - { - try - { - healPlayer(player); - sender.sendMessage(tl("healOther", player.getDisplayName())); - } - catch (QuietAbortException e) - { - //Handle Quietly - } - } + loopOnlinePlayers(server, sender, true, true, args[0], null); + } - private void healPlayer(final User user) throws PlayerExemptException, QuietAbortException - { - final Player player = user.getBase(); + @Override + protected void updatePlayer(final Server server, final CommandSource sender, final User player, final String[] args) throws PlayerExemptException { + try { + healPlayer(player); + sender.sendMessage(tl("healOther", player.getDisplayName())); + } catch (QuietAbortException e) { + //Handle Quietly + } + } - if (player.getHealth() == 0) - { - throw new PlayerExemptException(tl("healDead")); - } + private void healPlayer(final User user) throws PlayerExemptException, QuietAbortException { + final Player player = user.getBase(); - final double amount = player.getMaxHealth() - player.getHealth(); - final EntityRegainHealthEvent erhe = new EntityRegainHealthEvent(player, amount, RegainReason.CUSTOM); - ess.getServer().getPluginManager().callEvent(erhe); - if (erhe.isCancelled()) - { - throw new QuietAbortException(); - } + if (player.getHealth() == 0) { + throw new PlayerExemptException(tl("healDead")); + } - double newAmount = player.getHealth() + erhe.getAmount(); - if (newAmount > player.getMaxHealth()) - { - newAmount = player.getMaxHealth(); - } + final double amount = player.getMaxHealth() - player.getHealth(); + final EntityRegainHealthEvent erhe = new EntityRegainHealthEvent(player, amount, RegainReason.CUSTOM); + ess.getServer().getPluginManager().callEvent(erhe); + if (erhe.isCancelled()) { + throw new QuietAbortException(); + } - player.setHealth(newAmount); - player.setFoodLevel(20); - player.setFireTicks(0); - user.sendMessage(tl("heal")); - for (PotionEffect effect : player.getActivePotionEffects()) - { - player.removePotionEffect(effect.getType()); - } - } + double newAmount = player.getHealth() + erhe.getAmount(); + if (newAmount > player.getMaxHealth()) { + newAmount = player.getMaxHealth(); + } + + player.setHealth(newAmount); + player.setFoodLevel(20); + player.setFireTicks(0); + user.sendMessage(tl("heal")); + for (PotionEffect effect : player.getActivePotionEffects()) { + player.removePotionEffect(effect.getType()); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandhelp.java b/Essentials/src/com/earth2me/essentials/commands/Commandhelp.java index d037c3c79..b2fb5d1f0 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandhelp.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandhelp.java @@ -1,60 +1,51 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import com.earth2me.essentials.textreader.*; import com.earth2me.essentials.utils.NumberUtil; -import java.util.Locale; import org.bukkit.Server; +import java.util.Locale; -public class Commandhelp extends EssentialsCommand -{ - public Commandhelp() - { - super("help"); - } +import static com.earth2me.essentials.I18n.tl; - @Override - protected void run(final Server server, final User 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.getSource(), "help", false, ess); - if (input.getLines().isEmpty()) - { - if (NumberUtil.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 - { - user.setDisplayNick(); - output = new KeywordReplacer(input, user.getSource(), ess); - } - final TextPager pager = new TextPager(output); - pager.showPage(pageStr, chapterPageStr, command, user.getSource()); - } +public class Commandhelp extends EssentialsCommand { + public Commandhelp() { + super("help"); + } - @Override - protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - sender.sendMessage(tl("helpConsole")); - } + @Override + protected void run(final Server server, final User 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.getSource(), "help", false, ess); + + if (input.getLines().isEmpty()) { + if (NumberUtil.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 { + user.setDisplayNick(); + output = new KeywordReplacer(input, user.getSource(), ess); + } + final TextPager pager = new TextPager(output); + pager.showPage(pageStr, chapterPageStr, command, user.getSource()); + } + + @Override + protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + sender.sendMessage(tl("helpConsole")); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandhelpop.java b/Essentials/src/com/earth2me/essentials/commands/Commandhelpop.java index b83b5b695..ae42d0c02 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandhelpop.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandhelpop.java @@ -2,46 +2,41 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.Console; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.FormatUtil; -import java.util.logging.Level; import org.bukkit.Server; +import java.util.logging.Level; -public class Commandhelpop extends EssentialsCommand -{ - public Commandhelpop() - { - super("helpop"); - } +import static com.earth2me.essentials.I18n.tl; - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - user.setDisplayNick(); - final String message = sendMessage(server, user.getSource(), user.getDisplayName(), args); - if (!user.isAuthorized("essentials.helpop.receive")) - { - user.sendMessage(message); - } - } - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - sendMessage(server, sender, Console.NAME, args); - } +public class Commandhelpop extends EssentialsCommand { + public Commandhelpop() { + super("helpop"); + } - private String sendMessage(final Server server, final CommandSource sender, final String from, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - final String message = tl("helpOp", from, FormatUtil.stripFormat(getFinalArg(args, 0))); - server.getLogger().log(Level.INFO, message); - ess.broadcastMessage("essentials.helpop.receive", message); - return message; - } + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + user.setDisplayNick(); + final String message = sendMessage(server, user.getSource(), user.getDisplayName(), args); + if (!user.isAuthorized("essentials.helpop.receive")) { + user.sendMessage(message); + } + } + + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + sendMessage(server, sender, Console.NAME, args); + } + + private String sendMessage(final Server server, final CommandSource sender, final String from, final String[] args) throws Exception { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } + final String message = tl("helpOp", from, FormatUtil.stripFormat(getFinalArg(args, 0))); + server.getLogger().log(Level.INFO, message); + ess.broadcastMessage("essentials.helpop.receive", message); + return message; + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandhome.java b/Essentials/src/com/earth2me/essentials/commands/Commandhome.java index 62b0c4161..36905c48a 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandhome.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandhome.java @@ -1,129 +1,97 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.Trade; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.StringUtil; -import java.util.List; -import java.util.Locale; import org.bukkit.Location; import org.bukkit.Server; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; +import java.util.List; +import java.util.Locale; -public class Commandhome extends EssentialsCommand -{ - public Commandhome() - { - super("home"); - } +import static com.earth2me.essentials.I18n.tl; - // This method contains an undocumented translation parameters #EasterEgg - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - final Trade charge = new Trade(this.getName(), ess); - User player = user; - String homeName = ""; - String[] nameParts; - if (args.length > 0) - { - nameParts = args[0].split(":"); - if (nameParts[0].length() == args[0].length() || !user.isAuthorized("essentials.home.others")) - { - homeName = nameParts[0]; - } - else - { - player = getPlayer(server, nameParts, 0, true, true); - if (nameParts.length > 1) - { - homeName = nameParts[1]; - } - } - } - try - { - if ("bed".equalsIgnoreCase(homeName) && user.isAuthorized("essentials.home.bed")) - { - final Location bed = player.getBase().getBedSpawnLocation(); - if (bed != null) - { - user.getTeleport().teleport(bed, charge, TeleportCause.COMMAND); - throw new NoChargeException(); - } - else - { - throw new Exception(tl("bedMissing")); - } - } - goHome(user, player, homeName.toLowerCase(Locale.ENGLISH), charge); - } - catch (NotEnoughArgumentsException e) - { - Location bed = player.getBase().getBedSpawnLocation(); - final List homes = player.getHomes(); - if (homes.isEmpty() && player.equals(user)) - { - user.getTeleport().respawn(charge, TeleportCause.COMMAND); - } - else if (homes.isEmpty()) - { - throw new Exception(tl("noHomeSetPlayer")); - } - else if (homes.size() == 1 && player.equals(user)) - { - goHome(user, player, homes.get(0), charge); - } - else - { - final int count = homes.size(); - if (user.isAuthorized("essentials.home.bed")) - { - if (bed != null) - { - homes.add(tl("bed")); - } - else - { - homes.add(tl("bedNull")); - } - } - user.sendMessage(tl("homes", StringUtil.joinList(homes), count, getHomeLimit(player))); - } - } - throw new NoChargeException(); - } - private String getHomeLimit(final User player) - { - if (!player.getBase().isOnline()) - { - return "?"; - } - if (player.isAuthorized("essentials.sethome.multiple.unlimited")) - { - return "*"; - } - return Integer.toString(ess.getSettings().getHomeLimit(player)); - } +public class Commandhome extends EssentialsCommand { + public Commandhome() { + super("home"); + } - private void goHome(final User user, final User player, final String home, final Trade charge) throws Exception - { - if (home.length() < 1) - { - throw new NotEnoughArgumentsException(); - } - final Location loc = player.getHome(home); - if (loc == null) - { - throw new NotEnoughArgumentsException(); - } - if (user.getWorld() != loc.getWorld() && ess.getSettings().isWorldHomePermissions() - && !user.isAuthorized("essentials.worlds." + loc.getWorld().getName())) - { - throw new Exception(tl("noPerm", "essentials.worlds." + loc.getWorld().getName())); - } - user.getTeleport().teleport(loc, charge, TeleportCause.COMMAND); - } + // This method contains an undocumented translation parameters #EasterEgg + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + final Trade charge = new Trade(this.getName(), ess); + User player = user; + String homeName = ""; + String[] nameParts; + if (args.length > 0) { + nameParts = args[0].split(":"); + if (nameParts[0].length() == args[0].length() || !user.isAuthorized("essentials.home.others")) { + homeName = nameParts[0]; + } else { + player = getPlayer(server, nameParts, 0, true, true); + if (nameParts.length > 1) { + homeName = nameParts[1]; + } + } + } + try { + if ("bed".equalsIgnoreCase(homeName) && user.isAuthorized("essentials.home.bed")) { + final Location bed = player.getBase().getBedSpawnLocation(); + if (bed != null) { + user.getTeleport().teleport(bed, charge, TeleportCause.COMMAND); + throw new NoChargeException(); + } else { + throw new Exception(tl("bedMissing")); + } + } + goHome(user, player, homeName.toLowerCase(Locale.ENGLISH), charge); + } catch (NotEnoughArgumentsException e) { + Location bed = player.getBase().getBedSpawnLocation(); + final List homes = player.getHomes(); + if (homes.isEmpty() && player.equals(user)) { + user.getTeleport().respawn(charge, TeleportCause.COMMAND); + } else if (homes.isEmpty()) { + throw new Exception(tl("noHomeSetPlayer")); + } else if (homes.size() == 1 && player.equals(user)) { + goHome(user, player, homes.get(0), charge); + } else { + final int count = homes.size(); + if (user.isAuthorized("essentials.home.bed")) { + if (bed != null) { + homes.add(tl("bed")); + } else { + homes.add(tl("bedNull")); + } + } + user.sendMessage(tl("homes", StringUtil.joinList(homes), count, getHomeLimit(player))); + } + } + throw new NoChargeException(); + } + + private String getHomeLimit(final User player) { + if (!player.getBase().isOnline()) { + return "?"; + } + if (player.isAuthorized("essentials.sethome.multiple.unlimited")) { + return "*"; + } + return Integer.toString(ess.getSettings().getHomeLimit(player)); + } + + private void goHome(final User user, final User player, final String home, final Trade charge) throws Exception { + if (home.length() < 1) { + throw new NotEnoughArgumentsException(); + } + final Location loc = player.getHome(home); + if (loc == null) { + throw new NotEnoughArgumentsException(); + } + if (user.getWorld() != loc.getWorld() && ess.getSettings().isWorldHomePermissions() && !user.isAuthorized("essentials.worlds." + loc.getWorld().getName())) { + throw new Exception(tl("noPerm", "essentials.worlds." + loc.getWorld().getName())); + } + user.getTeleport().teleport(loc, charge, TeleportCause.COMMAND); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandignore.java b/Essentials/src/com/earth2me/essentials/commands/Commandignore.java index c5bc21d46..cf53c6ed4 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandignore.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandignore.java @@ -1,58 +1,44 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import org.bukkit.Server; +import static com.earth2me.essentials.I18n.tl; -public class Commandignore extends EssentialsCommand -{ - public Commandignore() - { - super("ignore"); - } - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - StringBuilder sb = new StringBuilder(); - for (String s : user._getIgnoredPlayers()) - { - sb.append(s).append(" "); - } - String ignoredList = sb.toString().trim(); - user.sendMessage(ignoredList.length() > 0 ? tl("ignoredList", ignoredList) : tl("noIgnored")); - } - else - { - User player; - try - { - player = getPlayer(server, args, 0, true, true); - } - catch (PlayerNotFoundException ex) - { - player = ess.getOfflineUser(args[0]); - } - if (player == null) - { - throw new PlayerNotFoundException(); - } - if (player.isIgnoreExempt()) { - user.sendMessage(tl("ignoreExempt")); - } - else if (user.isIgnoredPlayer(player)) - { - user.setIgnoredPlayer(player, false); - user.sendMessage(tl("unignorePlayer", player.getName())); - } - else - { - user.setIgnoredPlayer(player, true); - user.sendMessage(tl("ignorePlayer", player.getName())); - } - } - } +public class Commandignore extends EssentialsCommand { + public Commandignore() { + super("ignore"); + } + + @Override + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + StringBuilder sb = new StringBuilder(); + for (String s : user._getIgnoredPlayers()) { + sb.append(s).append(" "); + } + String ignoredList = sb.toString().trim(); + user.sendMessage(ignoredList.length() > 0 ? tl("ignoredList", ignoredList) : tl("noIgnored")); + } else { + User player; + try { + player = getPlayer(server, args, 0, true, true); + } catch (PlayerNotFoundException ex) { + player = ess.getOfflineUser(args[0]); + } + if (player == null) { + throw new PlayerNotFoundException(); + } + if (player.isIgnoreExempt()) { + user.sendMessage(tl("ignoreExempt")); + } else if (user.isIgnoredPlayer(player)) { + user.setIgnoredPlayer(player, false); + user.sendMessage(tl("unignorePlayer", player.getName())); + } else { + user.setIgnoredPlayer(player, true); + user.sendMessage(tl("ignorePlayer", player.getName())); + } + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandinfo.java b/Essentials/src/com/earth2me/essentials/commands/Commandinfo.java index 2ee915f7c..a50d1471b 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandinfo.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandinfo.java @@ -8,24 +8,20 @@ import com.earth2me.essentials.textreader.TextPager; import org.bukkit.Server; -public class Commandinfo extends EssentialsCommand -{ - public Commandinfo() - { - super("info"); - } +public class Commandinfo extends EssentialsCommand { + public Commandinfo() { + super("info"); + } - @Override - protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (sender.isPlayer()) - { - ess.getUser(sender.getPlayer()).setDisplayNick(); - } - - 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); - } + @Override + protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (sender.isPlayer()) { + ess.getUser(sender.getPlayer()).setDisplayNick(); + } + + 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 index f1800eb8e..c04e87857 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandinvsee.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandinvsee.java @@ -5,36 +5,29 @@ import org.bukkit.Server; import org.bukkit.inventory.Inventory; -public class Commandinvsee extends EssentialsCommand -{ - public Commandinvsee() - { - super("invsee"); - } +public class Commandinvsee extends EssentialsCommand { + public Commandinvsee() { + super("invsee"); + } - //This method has a hidden param, which if given will display the equip slots. #easteregg - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } + //This method has a hidden param, which if given will display the equip slots. #easteregg + @Override + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } - final User invUser = getPlayer(server, user, args, 0); - Inventory inv; + final User invUser = getPlayer(server, user, args, 0); + Inventory inv; - if (args.length > 1 && user.isAuthorized("essentials.invsee.equip")) - { - inv = server.createInventory(invUser.getBase(), 9, "Equipped"); - inv.setContents(invUser.getBase().getInventory().getArmorContents()); - } - else - { - inv = invUser.getBase().getInventory(); - } - user.getBase().closeInventory(); - user.getBase().openInventory(inv); - user.setInvSee(true); - } + if (args.length > 1 && user.isAuthorized("essentials.invsee.equip")) { + inv = server.createInventory(invUser.getBase(), 9, "Equipped"); + inv.setContents(invUser.getBase().getInventory().getArmorContents()); + } else { + inv = invUser.getBase().getInventory(); + } + user.getBase().closeInventory(); + user.getBase().openInventory(inv); + user.setInvSee(true); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanditem.java b/Essentials/src/com/earth2me/essentials/commands/Commanditem.java index 97d818172..9f5461316 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commanditem.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commanditem.java @@ -1,86 +1,65 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.MetaItemStack; import com.earth2me.essentials.User; import com.earth2me.essentials.craftbukkit.InventoryWorkaround; -import java.util.Locale; import org.bukkit.Material; import org.bukkit.Server; import org.bukkit.inventory.ItemStack; +import java.util.Locale; -public class Commanditem extends EssentialsCommand -{ - public Commanditem() - { - super("item"); - } - - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - ItemStack stack = ess.getItemDb().get(args[0]); - - final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""); - if (ess.getSettings().permissionBasedItemSpawn() - ? (!user.isAuthorized("essentials.itemspawn.item-all") - && !user.isAuthorized("essentials.itemspawn.item-" + itemname) - && !user.isAuthorized("essentials.itemspawn.item-" + stack.getTypeId())) - : (!user.isAuthorized("essentials.itemspawn.exempt") - && !user.canSpawnItem(stack.getTypeId()))) - { - throw new Exception(tl("cantSpawnItem", itemname)); - } - try - { - if (args.length > 1 && Integer.parseInt(args[1]) > 0) - { - stack.setAmount(Integer.parseInt(args[1])); - } - else if (ess.getSettings().getDefaultStackSize() > 0) - { - stack.setAmount(ess.getSettings().getDefaultStackSize()); - } - else if (ess.getSettings().getOversizedStackSize() > 0 && user.isAuthorized("essentials.oversizedstacks")) - { - stack.setAmount(ess.getSettings().getOversizedStackSize()); - } - } - catch (NumberFormatException e) - { - throw new NotEnoughArgumentsException(); - } - if (args.length > 2) - { - MetaItemStack metaStack = new MetaItemStack(stack); - final boolean allowUnsafe = ess.getSettings().allowUnsafeEnchantments() && user.isAuthorized("essentials.enchantments.allowunsafe"); - - metaStack.parseStringMeta(user.getSource(), allowUnsafe, args, 2, ess); - - stack = metaStack.getItemStack(); - } +import static com.earth2me.essentials.I18n.tl; - if (stack.getType() == Material.AIR) - { - throw new Exception(tl("cantSpawnItem", "Air")); - } +public class Commanditem extends EssentialsCommand { + public Commanditem() { + super("item"); + } - final String displayName = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace('_', ' '); - user.sendMessage(tl("itemSpawn", stack.getAmount(), displayName)); - if (user.isAuthorized("essentials.oversizedstacks")) - { - InventoryWorkaround.addOversizedItems(user.getBase().getInventory(), ess.getSettings().getOversizedStackSize(), stack); - } - else - { - InventoryWorkaround.addItems(user.getBase().getInventory(), stack); - } - user.getBase().updateInventory(); - } + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } + ItemStack stack = ess.getItemDb().get(args[0]); + + final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""); + if (ess.getSettings().permissionBasedItemSpawn() ? (!user.isAuthorized("essentials.itemspawn.item-all") && !user.isAuthorized("essentials.itemspawn.item-" + itemname) && !user.isAuthorized("essentials.itemspawn.item-" + stack.getTypeId())) : (!user.isAuthorized("essentials.itemspawn.exempt") && !user.canSpawnItem(stack.getTypeId()))) { + throw new Exception(tl("cantSpawnItem", itemname)); + } + try { + if (args.length > 1 && Integer.parseInt(args[1]) > 0) { + stack.setAmount(Integer.parseInt(args[1])); + } else if (ess.getSettings().getDefaultStackSize() > 0) { + stack.setAmount(ess.getSettings().getDefaultStackSize()); + } else if (ess.getSettings().getOversizedStackSize() > 0 && user.isAuthorized("essentials.oversizedstacks")) { + stack.setAmount(ess.getSettings().getOversizedStackSize()); + } + } catch (NumberFormatException e) { + throw new NotEnoughArgumentsException(); + } + if (args.length > 2) { + MetaItemStack metaStack = new MetaItemStack(stack); + final boolean allowUnsafe = ess.getSettings().allowUnsafeEnchantments() && user.isAuthorized("essentials.enchantments.allowunsafe"); + + metaStack.parseStringMeta(user.getSource(), allowUnsafe, args, 2, ess); + + stack = metaStack.getItemStack(); + } + + + if (stack.getType() == Material.AIR) { + throw new Exception(tl("cantSpawnItem", "Air")); + } + + final String displayName = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace('_', ' '); + user.sendMessage(tl("itemSpawn", stack.getAmount(), displayName)); + if (user.isAuthorized("essentials.oversizedstacks")) { + InventoryWorkaround.addOversizedItems(user.getBase().getInventory(), ess.getSettings().getOversizedStackSize(), stack); + } else { + InventoryWorkaround.addItems(user.getBase().getInventory(), stack); + } + user.getBase().updateInventory(); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commanditemdb.java b/Essentials/src/com/earth2me/essentials/commands/Commanditemdb.java index 02ea1c637..064f37dfa 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commanditemdb.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commanditemdb.java @@ -1,55 +1,45 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import org.bukkit.Material; import org.bukkit.Server; import org.bukkit.inventory.ItemStack; +import static com.earth2me.essentials.I18n.tl; -public class Commanditemdb extends EssentialsCommand -{ - public Commanditemdb() - { - super("itemdb"); - } - @Override - protected void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception - { - ItemStack itemStack = null; - boolean itemHeld = false; - if (args.length < 1) - { - if (sender.isPlayer()) - { - itemHeld = true; - itemStack = sender.getPlayer().getItemInHand(); - } - if (itemStack == null) - { - throw new NotEnoughArgumentsException(); - } - } - else - { - itemStack = ess.getItemDb().get(args[0]); - } - sender.sendMessage(tl("itemType", itemStack.getType().toString(), itemStack.getTypeId() + ":" + Integer.toString(itemStack.getDurability()))); +public class Commanditemdb extends EssentialsCommand { + public Commanditemdb() { + super("itemdb"); + } - if (itemHeld && itemStack.getType() != Material.AIR) - { - int maxuses = itemStack.getType().getMaxDurability(); - int durability = ((maxuses + 1) - itemStack.getDurability()); - if (maxuses != 0) - { - sender.sendMessage(tl("durability", Integer.toString(durability))); - } - } - final String itemNameList = ess.getItemDb().names(itemStack); - if (itemNameList != null) - { - sender.sendMessage(tl("itemNames", ess.getItemDb().names(itemStack))); - } - } + @Override + protected void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception { + ItemStack itemStack = null; + boolean itemHeld = false; + if (args.length < 1) { + if (sender.isPlayer()) { + itemHeld = true; + itemStack = sender.getPlayer().getItemInHand(); + } + if (itemStack == null) { + throw new NotEnoughArgumentsException(); + } + } else { + itemStack = ess.getItemDb().get(args[0]); + } + sender.sendMessage(tl("itemType", itemStack.getType().toString(), itemStack.getTypeId() + ":" + Integer.toString(itemStack.getDurability()))); + + if (itemHeld && itemStack.getType() != Material.AIR) { + int maxuses = itemStack.getType().getMaxDurability(); + int durability = ((maxuses + 1) - itemStack.getDurability()); + if (maxuses != 0) { + sender.sendMessage(tl("durability", Integer.toString(durability))); + } + } + final String itemNameList = ess.getItemDb().names(itemStack); + if (itemNameList != null) { + sender.sendMessage(tl("itemNames", ess.getItemDb().names(itemStack))); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandjails.java b/Essentials/src/com/earth2me/essentials/commands/Commandjails.java index 5fe61032d..3ee469712 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandjails.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandjails.java @@ -5,16 +5,13 @@ import com.earth2me.essentials.utils.StringUtil; import org.bukkit.Server; -public class Commandjails extends EssentialsCommand -{ - public Commandjails() - { - super("jails"); - } +public class Commandjails extends EssentialsCommand { + public Commandjails() { + super("jails"); + } - @Override - protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - sender.sendMessage("§7" + StringUtil.joinList(" ", ess.getJails().getList())); - } + @Override + protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + sender.sendMessage("§7" + StringUtil.joinList(" ", ess.getJails().getList())); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandjump.java b/Essentials/src/com/earth2me/essentials/commands/Commandjump.java index 228df82b0..613d8c759 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandjump.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandjump.java @@ -1,6 +1,5 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.Trade; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.LocationUtil; @@ -8,50 +7,42 @@ import org.bukkit.Location; import org.bukkit.Server; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; +import static com.earth2me.essentials.I18n.tl; + // This method contains an undocumented sub command #EasterEgg -public class Commandjump extends EssentialsCommand -{ - public Commandjump() - { - super("jump"); - } +public class Commandjump extends EssentialsCommand { + public Commandjump() { + super("jump"); + } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (args.length > 0 && args[0].contains("lock") && user.isAuthorized("essentials.jump.lock")) - { - if (user.isFlyClickJump()) - { - user.setRightClickJump(false); - user.sendMessage("Flying wizard mode disabled"); - } - else - { - user.setRightClickJump(true); - user.sendMessage("Enabling flying wizard mode"); - } - return; - } + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (args.length > 0 && args[0].contains("lock") && user.isAuthorized("essentials.jump.lock")) { + if (user.isFlyClickJump()) { + user.setRightClickJump(false); + user.sendMessage("Flying wizard mode disabled"); + } else { + user.setRightClickJump(true); + user.sendMessage("Enabling flying wizard mode"); + } + return; + } - Location loc; - final Location cloc = user.getLocation(); + Location loc; + final Location cloc = user.getLocation(); - try - { - loc = LocationUtil.getTarget(user.getBase()); - loc.setYaw(cloc.getYaw()); - loc.setPitch(cloc.getPitch()); - loc.setY(loc.getY() + 1); - } - catch (NullPointerException ex) - { - throw new Exception(tl("jumpError"), ex); - } + try { + loc = LocationUtil.getTarget(user.getBase()); + loc.setYaw(cloc.getYaw()); + loc.setPitch(cloc.getPitch()); + loc.setY(loc.getY() + 1); + } catch (NullPointerException ex) { + throw new Exception(tl("jumpError"), ex); + } - final Trade charge = new Trade(this.getName(), ess); - charge.isAffordableFor(user); - user.getTeleport().teleport(loc, charge, TeleportCause.COMMAND); - throw new NoChargeException(); - } + final Trade charge = new Trade(this.getName(), 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 index f4c2bdaca..c87c3c2a0 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandkick.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandkick.java @@ -2,50 +2,45 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.Console; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.FormatUtil; -import java.util.logging.Level; import org.bukkit.Server; +import java.util.logging.Level; -public class Commandkick extends EssentialsCommand -{ - public Commandkick() - { - super("kick"); - } +import static com.earth2me.essentials.I18n.tl; - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - final User target = getPlayer(server, args, 0, true, false); - if (sender.isPlayer()) - { - User user = ess.getUser(sender.getPlayer()); - if (target.isHidden(sender.getPlayer()) && !user.canInteractVanished() && !sender.getPlayer().canSee(target.getBase())) - { - throw new PlayerNotFoundException(); - } +public class Commandkick extends EssentialsCommand { + public Commandkick() { + super("kick"); + } - if (target.isAuthorized("essentials.kick.exempt")) - { - throw new Exception(tl("kickExempt")); - } - } + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } - String kickReason = args.length > 1 ? getFinalArg(args, 1) : tl("kickDefault"); - kickReason = FormatUtil.replaceFormat(kickReason.replace("\\n", "\n").replace("|", "\n")); + final User target = getPlayer(server, args, 0, true, false); + if (sender.isPlayer()) { + User user = ess.getUser(sender.getPlayer()); + if (target.isHidden(sender.getPlayer()) && !user.canInteractVanished() && !sender.getPlayer().canSee(target.getBase())) { + throw new PlayerNotFoundException(); + } - target.getBase().kickPlayer(kickReason); - final String senderName = sender.isPlayer() ? sender.getPlayer().getDisplayName() : Console.NAME; + if (target.isAuthorized("essentials.kick.exempt")) { + throw new Exception(tl("kickExempt")); + } + } - server.getLogger().log(Level.INFO, tl("playerKicked", senderName, target.getName(), kickReason)); - ess.broadcastMessage("essentials.kick.notify", tl("playerKicked", senderName, target.getName(), kickReason)); - } + String kickReason = args.length > 1 ? getFinalArg(args, 1) : tl("kickDefault"); + kickReason = FormatUtil.replaceFormat(kickReason.replace("\\n", "\n").replace("|", "\n")); + + target.getBase().kickPlayer(kickReason); + final String senderName = sender.isPlayer() ? sender.getPlayer().getDisplayName() : Console.NAME; + + server.getLogger().log(Level.INFO, tl("playerKicked", senderName, target.getName(), kickReason)); + ess.broadcastMessage("essentials.kick.notify", tl("playerKicked", senderName, target.getName(), kickReason)); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandkickall.java b/Essentials/src/com/earth2me/essentials/commands/Commandkickall.java index 745da13e3..5c96af2c2 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandkickall.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandkickall.java @@ -1,32 +1,28 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.utils.FormatUtil; import org.bukkit.Server; import org.bukkit.entity.Player; +import static com.earth2me.essentials.I18n.tl; -public class Commandkickall extends EssentialsCommand -{ - public Commandkickall() - { - super("kickall"); - } - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - String kickReason = args.length > 0 ? getFinalArg(args, 0) : tl("kickDefault"); - kickReason = FormatUtil.replaceFormat(kickReason.replace("\\n", "\n").replace("|", "\n")); +public class Commandkickall extends EssentialsCommand { + public Commandkickall() { + super("kickall"); + } - for (Player onlinePlayer : ess.getOnlinePlayers()) - { - if (!sender.isPlayer() || !onlinePlayer.getName().equalsIgnoreCase(sender.getPlayer().getName())) - { - onlinePlayer.kickPlayer(kickReason); - } - } - sender.sendMessage(tl("kickedAll")); - } + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + String kickReason = args.length > 0 ? getFinalArg(args, 0) : tl("kickDefault"); + kickReason = FormatUtil.replaceFormat(kickReason.replace("\\n", "\n").replace("|", "\n")); + + for (Player onlinePlayer : ess.getOnlinePlayers()) { + if (!sender.isPlayer() || !onlinePlayer.getName().equalsIgnoreCase(sender.getPlayer().getName())) { + onlinePlayer.kickPlayer(kickReason); + } + } + sender.sendMessage(tl("kickedAll")); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandkill.java b/Essentials/src/com/earth2me/essentials/commands/Commandkill.java index 6c4062371..0409208b8 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandkill.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandkill.java @@ -1,52 +1,45 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import org.bukkit.Server; import org.bukkit.entity.Player; import org.bukkit.event.entity.EntityDamageEvent; +import static com.earth2me.essentials.I18n.tl; -public class Commandkill extends EssentialsLoopCommand -{ - public Commandkill() - { - super("kill"); - } - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } +public class Commandkill extends EssentialsLoopCommand { + public Commandkill() { + super("kill"); + } - loopOnlinePlayers(server, sender, true, true, args[0], null); - } + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } - @Override - protected void updatePlayer(final Server server, final CommandSource sender, final User user, final String[] args) throws PlayerExemptException - { - final Player matchPlayer = user.getBase(); - if (sender.isPlayer() && user.isAuthorized("essentials.kill.exempt") && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.kill.force")) - { - throw new PlayerExemptException(tl("killExempt", matchPlayer.getDisplayName())); - } - final EntityDamageEvent ede = new EntityDamageEvent(matchPlayer, sender.isPlayer() && sender.getPlayer().getName().equals(matchPlayer.getName()) ? EntityDamageEvent.DamageCause.SUICIDE : EntityDamageEvent.DamageCause.CUSTOM, Short.MAX_VALUE); - server.getPluginManager().callEvent(ede); - if (ede.isCancelled() && sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.kill.force")) - { - return; - } - matchPlayer.damage(Short.MAX_VALUE); + loopOnlinePlayers(server, sender, true, true, args[0], null); + } - if (matchPlayer.getHealth() > 0) - { - matchPlayer.setHealth(0); - } + @Override + protected void updatePlayer(final Server server, final CommandSource sender, final User user, final String[] args) throws PlayerExemptException { + final Player matchPlayer = user.getBase(); + if (sender.isPlayer() && user.isAuthorized("essentials.kill.exempt") && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.kill.force")) { + throw new PlayerExemptException(tl("killExempt", matchPlayer.getDisplayName())); + } + final EntityDamageEvent ede = new EntityDamageEvent(matchPlayer, sender.isPlayer() && sender.getPlayer().getName().equals(matchPlayer.getName()) ? EntityDamageEvent.DamageCause.SUICIDE : EntityDamageEvent.DamageCause.CUSTOM, Short.MAX_VALUE); + server.getPluginManager().callEvent(ede); + if (ede.isCancelled() && sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.kill.force")) { + return; + } + matchPlayer.damage(Short.MAX_VALUE); - sender.sendMessage(tl("kill", matchPlayer.getDisplayName())); - } + if (matchPlayer.getHealth() > 0) { + matchPlayer.setHealth(0); + } + + sender.sendMessage(tl("kill", matchPlayer.getDisplayName())); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandkit.java b/Essentials/src/com/earth2me/essentials/commands/Commandkit.java index aa3f21d3b..ef8e73eb6 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandkit.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandkit.java @@ -1,125 +1,102 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.Kit; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.StringUtil; +import org.bukkit.Server; + import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.logging.Level; -import org.bukkit.Server; + +import static com.earth2me.essentials.I18n.tl; -public class Commandkit extends EssentialsCommand -{ - public Commandkit() - { - super("kit"); - } - - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - final String kitList = Kit.listKits(ess, user); - user.sendMessage(kitList.length() > 0 ? tl("kits", kitList) : tl("noKits")); - throw new NoChargeException(); - } - else if (args.length > 1 && user.isAuthorized("essentials.kit.others")) - { - final User userTo = getPlayer(server, user, args, 1); - final String kitNames = StringUtil.sanitizeString(args[0].toLowerCase(Locale.ENGLISH)).trim(); - giveKits(userTo, user, kitNames); - } - else - { - final String kitNames = StringUtil.sanitizeString(args[0].toLowerCase(Locale.ENGLISH)).trim(); - giveKits(user, user, kitNames); - } - } - - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 2) - { - final String kitList = Kit.listKits(ess, null); - sender.sendMessage(kitList.length() > 0 ? tl("kits", kitList) : tl("noKits")); - throw new NoChargeException(); - } - else - { - final User userTo = getPlayer(server, args, 1, true, false); - final String[] kits = args[0].toLowerCase(Locale.ENGLISH).split(","); - - for (final String kitName : kits) - { - final Kit kit = new Kit(kitName, ess); - kit.expandItems(userTo); - - sender.sendMessage(tl("kitGiveTo", kitName, userTo.getDisplayName())); - userTo.sendMessage(tl("kitReceive", kitName)); - } - } - } - - private void giveKits(final User userTo, final User userFrom, final String kitNames) throws Exception - { - if (kitNames.isEmpty()) - { - throw new Exception(tl("kitNotFound")); - } - String[] kitList = kitNames.split(","); - - List kits = new ArrayList(); - - for (final String kitName : kitList) - { - if (kitName.isEmpty()) - { - throw new Exception(tl("kitNotFound")); - } - - Kit kit = new Kit(kitName, ess); - kit.checkPerms(userFrom); - kit.checkDelay(userFrom); - kit.checkAffordable(userFrom); - kits.add(kit); - } - - for (final Kit kit : kits) - { - try - { - - kit.checkDelay(userFrom); - kit.checkAffordable(userFrom); - kit.setTime(userFrom); - kit.expandItems(userTo); - kit.chargeUser(userTo); - - if (!userFrom.equals(userTo)) - { - userFrom.sendMessage(tl("kitGiveTo", kit.getName(), userTo.getDisplayName())); - } - - userTo.sendMessage(tl("kitReceive", kit.getName())); - - } - catch (NoChargeException ex) - { - if (ess.getSettings().isDebug()) - { - ess.getLogger().log(Level.INFO, "Soft kit error, abort spawning " + kit.getName(), ex); - } - } - catch (Exception ex) - { - ess.showError(userFrom.getSource(), ex, "\\ kit: " + kit.getName()); - } - } - } +public class Commandkit extends EssentialsCommand { + public Commandkit() { + super("kit"); + } + + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + final String kitList = Kit.listKits(ess, user); + user.sendMessage(kitList.length() > 0 ? tl("kits", kitList) : tl("noKits")); + throw new NoChargeException(); + } else if (args.length > 1 && user.isAuthorized("essentials.kit.others")) { + final User userTo = getPlayer(server, user, args, 1); + final String kitNames = StringUtil.sanitizeString(args[0].toLowerCase(Locale.ENGLISH)).trim(); + giveKits(userTo, user, kitNames); + } else { + final String kitNames = StringUtil.sanitizeString(args[0].toLowerCase(Locale.ENGLISH)).trim(); + giveKits(user, user, kitNames); + } + } + + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 2) { + final String kitList = Kit.listKits(ess, null); + sender.sendMessage(kitList.length() > 0 ? tl("kits", kitList) : tl("noKits")); + throw new NoChargeException(); + } else { + final User userTo = getPlayer(server, args, 1, true, false); + final String[] kits = args[0].toLowerCase(Locale.ENGLISH).split(","); + + for (final String kitName : kits) { + final Kit kit = new Kit(kitName, ess); + kit.expandItems(userTo); + + sender.sendMessage(tl("kitGiveTo", kitName, userTo.getDisplayName())); + userTo.sendMessage(tl("kitReceive", kitName)); + } + } + } + + private void giveKits(final User userTo, final User userFrom, final String kitNames) throws Exception { + if (kitNames.isEmpty()) { + throw new Exception(tl("kitNotFound")); + } + String[] kitList = kitNames.split(","); + + List kits = new ArrayList(); + + for (final String kitName : kitList) { + if (kitName.isEmpty()) { + throw new Exception(tl("kitNotFound")); + } + + Kit kit = new Kit(kitName, ess); + kit.checkPerms(userFrom); + kit.checkDelay(userFrom); + kit.checkAffordable(userFrom); + kits.add(kit); + } + + for (final Kit kit : kits) { + try { + + kit.checkDelay(userFrom); + kit.checkAffordable(userFrom); + kit.setTime(userFrom); + kit.expandItems(userTo); + kit.chargeUser(userTo); + + if (!userFrom.equals(userTo)) { + userFrom.sendMessage(tl("kitGiveTo", kit.getName(), userTo.getDisplayName())); + } + + userTo.sendMessage(tl("kitReceive", kit.getName())); + + } catch (NoChargeException ex) { + if (ess.getSettings().isDebug()) { + ess.getLogger().log(Level.INFO, "Soft kit error, abort spawning " + kit.getName(), ex); + } + } catch (Exception ex) { + ess.showError(userFrom.getSource(), ex, "\\ kit: " + kit.getName()); + } + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandkittycannon.java b/Essentials/src/com/earth2me/essentials/commands/Commandkittycannon.java index 507e1d7d3..77260ee34 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandkittycannon.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandkittycannon.java @@ -2,47 +2,42 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.Mob; import com.earth2me.essentials.User; -import java.util.Random; import org.bukkit.Location; import org.bukkit.Server; import org.bukkit.entity.Ocelot; +import java.util.Random; + // This command is not documented on the wiki #EasterEgg -public class Commandkittycannon extends EssentialsCommand -{ - private static final Random random = new Random(); +public class Commandkittycannon extends EssentialsCommand { + private static final Random random = new Random(); - public Commandkittycannon() - { - super("kittycannon"); - } + public Commandkittycannon() { + super("kittycannon"); + } - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - final Mob cat = Mob.OCELOT; - final Ocelot ocelot = (Ocelot)cat.spawn(user.getWorld(), server, user.getBase().getEyeLocation()); - if (ocelot == null) - { - return; - } - final int i = random.nextInt(Ocelot.Type.values().length); - ocelot.setCatType(Ocelot.Type.values()[i]); - ocelot.setTamed(true); - ocelot.setBaby(); - ocelot.setVelocity(user.getBase().getEyeLocation().getDirection().multiply(2)); + @Override + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + final Mob cat = Mob.OCELOT; + final Ocelot ocelot = (Ocelot) cat.spawn(user.getWorld(), server, user.getBase().getEyeLocation()); + if (ocelot == null) { + return; + } + final int i = random.nextInt(Ocelot.Type.values().length); + ocelot.setCatType(Ocelot.Type.values()[i]); + ocelot.setTamed(true); + ocelot.setBaby(); + ocelot.setVelocity(user.getBase().getEyeLocation().getDirection().multiply(2)); - class KittyCannonExplodeTask implements Runnable - { - @Override - public void run() - { - final Location loc = ocelot.getLocation(); - ocelot.remove(); - loc.getWorld().createExplosion(loc, 0F); - } - } - ess.scheduleSyncDelayedTask(new KittyCannonExplodeTask(), 20); + class KittyCannonExplodeTask implements Runnable { + @Override + public void run() { + final Location loc = ocelot.getLocation(); + ocelot.remove(); + loc.getWorld().createExplosion(loc, 0F); + } + } + ess.scheduleSyncDelayedTask(new KittyCannonExplodeTask(), 20); - } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandlightning.java b/Essentials/src/com/earth2me/essentials/commands/Commandlightning.java index 75e3c0579..98920e377 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandlightning.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandlightning.java @@ -1,61 +1,50 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import org.bukkit.Server; import org.bukkit.entity.LightningStrike; +import static com.earth2me.essentials.I18n.tl; -public class Commandlightning extends EssentialsLoopCommand -{ - int power = 5; - public Commandlightning() - { - super("lightning"); - } +public class Commandlightning extends EssentialsLoopCommand { + int power = 5; - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - User user; - if (sender.isPlayer()) - { - user = ess.getUser(sender.getPlayer()); - if ((args.length < 1 || user != null && !user.isAuthorized("essentials.lightning.others"))) - { - user.getWorld().strikeLightning(user.getBase().getTargetBlock(null, 600).getLocation()); - return; - } - } + public Commandlightning() { + super("lightning"); + } - if (args.length > 1) - { - try - { - power = Integer.parseInt(args[1]); - } - catch (NumberFormatException ex) - { - } - } - loopOnlinePlayers(server, sender, true, true, args[0], null); - } + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + User user; + if (sender.isPlayer()) { + user = ess.getUser(sender.getPlayer()); + if ((args.length < 1 || user != null && !user.isAuthorized("essentials.lightning.others"))) { + user.getWorld().strikeLightning(user.getBase().getTargetBlock(null, 600).getLocation()); + return; + } + } - @Override - protected void updatePlayer(final Server server, final CommandSource sender, final User matchUser, final String[] args) - { - sender.sendMessage(tl("lightningUse", matchUser.getDisplayName())); - final LightningStrike strike = matchUser.getBase().getWorld().strikeLightningEffect(matchUser.getBase().getLocation()); + if (args.length > 1) { + try { + power = Integer.parseInt(args[1]); + } catch (NumberFormatException ex) { + } + } + loopOnlinePlayers(server, sender, true, true, args[0], null); + } - if (!matchUser.isGodModeEnabled()) - { - matchUser.getBase().damage(power, strike); - } - if (ess.getSettings().warnOnSmite()) - { - matchUser.sendMessage(tl("lightningSmited")); - } - } + @Override + protected void updatePlayer(final Server server, final CommandSource sender, final User matchUser, final String[] args) { + sender.sendMessage(tl("lightningUse", matchUser.getDisplayName())); + final LightningStrike strike = matchUser.getBase().getWorld().strikeLightningEffect(matchUser.getBase().getLocation()); + + if (!matchUser.isGodModeEnabled()) { + matchUser.getBase().damage(power, strike); + } + if (ess.getSettings().warnOnSmite()) { + matchUser.sendMessage(tl("lightningSmited")); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandlist.java b/Essentials/src/com/earth2me/essentials/commands/Commandlist.java index bb5475721..56ae8f1d1 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandlist.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandlist.java @@ -1,139 +1,118 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.PlayerList; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.FormatUtil; import com.earth2me.essentials.utils.NumberUtil; -import java.util.*; import org.bukkit.Server; +import java.util.*; -public class Commandlist extends EssentialsCommand -{ - public Commandlist() - { - super("list"); - } +import static com.earth2me.essentials.I18n.tl; - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - boolean showHidden = true; - User user = null; - if (sender.isPlayer()) - { - user = ess.getUser(sender.getPlayer()); - showHidden = user.isAuthorized("essentials.list.hidden") || user.canInteractVanished(); - } - sender.sendMessage(PlayerList.listSummary(ess, user, showHidden)); - final Map> playerList = PlayerList.getPlayerLists(ess, user, showHidden); - if (args.length > 0) - { - sender.sendMessage(PlayerList.listGroupUsers(ess, playerList, args[0].toLowerCase())); - } - else - { - sendGroupedList(sender, commandLabel, playerList); - } - } +public class Commandlist extends EssentialsCommand { + public Commandlist() { + super("list"); + } - // Output the standard /list output, when no group is specified - private void sendGroupedList(CommandSource sender, String commandLabel, Map> playerList) - { - final Set configGroups = ess.getSettings().getListGroupConfig().keySet(); - final List asterisk = new ArrayList(); + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + boolean showHidden = true; + User user = null; + if (sender.isPlayer()) { + user = ess.getUser(sender.getPlayer()); + showHidden = user.isAuthorized("essentials.list.hidden") || user.canInteractVanished(); + } + sender.sendMessage(PlayerList.listSummary(ess, user, showHidden)); + final Map> playerList = PlayerList.getPlayerLists(ess, user, showHidden); - // Loop through the custom defined groups and display them - for (String oConfigGroup : configGroups) - { - String groupValue = ess.getSettings().getListGroupConfig().get(oConfigGroup).toString().trim(); - String configGroup = oConfigGroup.toLowerCase(); + if (args.length > 0) { + sender.sendMessage(PlayerList.listGroupUsers(ess, playerList, args[0].toLowerCase())); + } else { + sendGroupedList(sender, commandLabel, playerList); + } + } - // If the group value is an asterisk, then skip it, and handle it later - if (groupValue.equals("*")) - { - asterisk.add(oConfigGroup); - continue; - } + // Output the standard /list output, when no group is specified + private void sendGroupedList(CommandSource sender, String commandLabel, Map> playerList) { + final Set configGroups = ess.getSettings().getListGroupConfig().keySet(); + final List asterisk = new ArrayList(); - // If the group value is hidden, we don't need to display it - if (groupValue.equalsIgnoreCase("hidden")) - { - playerList.remove(configGroup); - continue; - } + // Loop through the custom defined groups and display them + for (String oConfigGroup : configGroups) { + String groupValue = ess.getSettings().getListGroupConfig().get(oConfigGroup).toString().trim(); + String configGroup = oConfigGroup.toLowerCase(); - List outputUserList = new ArrayList(); - final List matchedList = playerList.get(configGroup); + // If the group value is an asterisk, then skip it, and handle it later + if (groupValue.equals("*")) { + asterisk.add(oConfigGroup); + continue; + } - // If the group value is an int, then we might need to truncate it - if (NumberUtil.isInt(groupValue)) - { - if (matchedList != null && !matchedList.isEmpty()) - { - playerList.remove(configGroup); - outputUserList.addAll(matchedList); - int limit = Integer.parseInt(groupValue); - if (matchedList.size() > limit) - { - sender.sendMessage(PlayerList.outputFormat(oConfigGroup, tl("groupNumber", matchedList.size(), commandLabel, FormatUtil.stripFormat(configGroup)))); - } - else - { - sender.sendMessage(PlayerList.outputFormat(oConfigGroup, PlayerList.listUsers(ess, outputUserList, ", "))); - } - continue; - } - } + // If the group value is hidden, we don't need to display it + if (groupValue.equalsIgnoreCase("hidden")) { + playerList.remove(configGroup); + continue; + } - outputUserList = PlayerList.getMergedList(ess, playerList, configGroup); + List outputUserList = new ArrayList(); + final List matchedList = playerList.get(configGroup); - // If we have no users, than we don't need to continue parsing this group - if (outputUserList == null || outputUserList.isEmpty()) - { - continue; - } + // If the group value is an int, then we might need to truncate it + if (NumberUtil.isInt(groupValue)) { + if (matchedList != null && !matchedList.isEmpty()) { + playerList.remove(configGroup); + outputUserList.addAll(matchedList); + int limit = Integer.parseInt(groupValue); + if (matchedList.size() > limit) { + sender.sendMessage(PlayerList.outputFormat(oConfigGroup, tl("groupNumber", matchedList.size(), commandLabel, FormatUtil.stripFormat(configGroup)))); + } else { + sender.sendMessage(PlayerList.outputFormat(oConfigGroup, PlayerList.listUsers(ess, outputUserList, ", "))); + } + continue; + } + } - sender.sendMessage(PlayerList.outputFormat(oConfigGroup, PlayerList.listUsers(ess, outputUserList, ", "))); - } + outputUserList = PlayerList.getMergedList(ess, playerList, configGroup); - String[] onlineGroups = playerList.keySet().toArray(new String[0]); - Arrays.sort(onlineGroups, String.CASE_INSENSITIVE_ORDER); + // If we have no users, than we don't need to continue parsing this group + if (outputUserList == null || outputUserList.isEmpty()) { + continue; + } - // If we have an asterisk group, then merge all remaining groups - if (!asterisk.isEmpty()) - { - List asteriskUsers = new ArrayList(); - for (String onlineGroup : onlineGroups) - { - asteriskUsers.addAll(playerList.get(onlineGroup)); - } - for (String key : asterisk) - { - playerList.put(key, asteriskUsers); - } - onlineGroups = asterisk.toArray(new String[0]); - } + sender.sendMessage(PlayerList.outputFormat(oConfigGroup, PlayerList.listUsers(ess, outputUserList, ", "))); + } - // If we have any groups remaining after the custom groups loop through and display them - for (String onlineGroup : onlineGroups) - { - List users = playerList.get(onlineGroup); - String groupName = asterisk.isEmpty() ? users.get(0).getGroup() : onlineGroup; + String[] onlineGroups = playerList.keySet().toArray(new String[0]); + Arrays.sort(onlineGroups, String.CASE_INSENSITIVE_ORDER); - if (ess.getPermissionsHandler().getName().equals("ConfigPermissions")) - { - groupName = tl("connectedPlayers"); - } - if (users == null || users.isEmpty()) - { - continue; - } + // If we have an asterisk group, then merge all remaining groups + if (!asterisk.isEmpty()) { + List asteriskUsers = new ArrayList(); + for (String onlineGroup : onlineGroups) { + asteriskUsers.addAll(playerList.get(onlineGroup)); + } + for (String key : asterisk) { + playerList.put(key, asteriskUsers); + } + onlineGroups = asterisk.toArray(new String[0]); + } - sender.sendMessage(PlayerList.outputFormat(groupName, PlayerList.listUsers(ess, users, ", "))); - } - } + // If we have any groups remaining after the custom groups loop through and display them + for (String onlineGroup : onlineGroups) { + List users = playerList.get(onlineGroup); + String groupName = asterisk.isEmpty() ? users.get(0).getGroup() : onlineGroup; + + if (ess.getPermissionsHandler().getName().equals("ConfigPermissions")) { + groupName = tl("connectedPlayers"); + } + if (users == null || users.isEmpty()) { + continue; + } + + sender.sendMessage(PlayerList.outputFormat(groupName, PlayerList.listUsers(ess, users, ", "))); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandmail.java b/Essentials/src/com/earth2me/essentials/commands/Commandmail.java index 0e4869df5..f4bdb40cf 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandmail.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandmail.java @@ -1,177 +1,143 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import com.earth2me.essentials.textreader.IText; import com.earth2me.essentials.textreader.SimpleTextInput; -import com.earth2me.essentials.textreader.SimpleTextPager; import com.earth2me.essentials.textreader.TextPager; import com.earth2me.essentials.utils.FormatUtil; import com.earth2me.essentials.utils.StringUtil; import org.bukkit.Server; import java.util.List; - import java.util.UUID; - -public class Commandmail extends EssentialsCommand -{ - private static int mailsPerMinute = 0; - private static long timestamp = 0; - - public Commandmail() - { - super("mail"); - } - - //TODO: Tidy this up / TL these errors. - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (args.length >= 1 && "read".equalsIgnoreCase(args[0])) - { - final List mail = user.getMails(); - if (mail.isEmpty()) - { - user.sendMessage(tl("noMail")); - throw new NoChargeException(); - } - - IText input = new SimpleTextInput(mail); - final TextPager pager = new TextPager(input); - pager.showPage(args.length > 1 ? args[1] : null, null, commandLabel + " " + args[0], user.getSource()); - - user.sendMessage(tl("mailClear")); - return; - } - if (args.length >= 3 && "send".equalsIgnoreCase(args[0])) - { - if (!user.isAuthorized("essentials.mail.send")) - { - throw new Exception(tl("noPerm", "essentials.mail.send")); - } - - if (user.isMuted()) - { - throw new Exception(tl("voiceSilenced")); - } - - User u = getPlayer(server, args[1], true, true); - if (u == null) - { - throw new Exception(tl("playerNeverOnServer", args[1])); - } - - final String mail = tl("mailFormat", user.getName(), StringUtil.sanitizeString(FormatUtil.stripFormat(getFinalArg(args, 2)))); - if (mail.length() > 1000) - { - throw new Exception(tl("mailTooLong")); - } - - if (!u.isIgnoredPlayer(user)) - { - if (Math.abs(System.currentTimeMillis() - timestamp) > 60000) - { - timestamp = System.currentTimeMillis(); - mailsPerMinute = 0; - } - mailsPerMinute++; - if (mailsPerMinute > ess.getSettings().getMailsPerMinute()) - { - throw new Exception(tl("mailDelay", ess.getSettings().getMailsPerMinute())); - } - u.addMail(tl("mailMessage", mail)); - } - - user.sendMessage(tl("mailSentTo", u.getDisplayName(), u.getName())); - user.sendMessage(mail); - return; - } - if (args.length > 1 && "sendall".equalsIgnoreCase(args[0])) - { - if (!user.isAuthorized("essentials.mail.sendall")) - { - throw new Exception(tl("noPerm", "essentials.mail.sendall")); - } - ess.runTaskAsynchronously(new SendAll(tl("mailFormat", user.getName(), FormatUtil.stripFormat(getFinalArg(args, 1))))); - user.sendMessage(tl("mailSent")); - return; - } - if (args.length >= 1 && "clear".equalsIgnoreCase(args[0])) - { - user.setMails(null); - user.sendMessage(tl("mailCleared")); - return; - } - throw new NotEnoughArgumentsException(); - } - - @Override - protected void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception - { - if (args.length >= 1 && "read".equalsIgnoreCase(args[0])) - { - throw new Exception(tl("onlyPlayers", commandLabel + " read")); - } - else if (args.length >= 1 && "clear".equalsIgnoreCase(args[0])) - { - throw new Exception(tl("onlyPlayers", commandLabel + " clear")); - } - else if (args.length >= 3 && "send".equalsIgnoreCase(args[0])) - { - User u = getPlayer(server, args[1], true, true); - if (u == null) - { - throw new Exception(tl("playerNeverOnServer", args[1])); - } - u.addMail(tl("mailFormat", "Server", getFinalArg(args, 2))); - sender.sendMessage(tl("mailSent")); - return; - } - else if (args.length >= 2 && "sendall".equalsIgnoreCase(args[0])) - { - ess.runTaskAsynchronously(new SendAll(tl("mailFormat", "Server", getFinalArg(args, 1)))); - sender.sendMessage(tl("mailSent")); - return; - } - else if (args.length >= 2) - { - //allow sending from console without "send" argument, since it's the only thing the console can do - User u = getPlayer(server, args[0], true, true); - if (u == null) - { - throw new Exception(tl("playerNeverOnServer", args[0])); - } - u.addMail(tl("mailFormat", "Server", getFinalArg(args, 1))); - sender.sendMessage(tl("mailSent")); - return; - } - throw new NotEnoughArgumentsException(); - } +import static com.earth2me.essentials.I18n.tl; - private class SendAll implements Runnable - { - String message; +public class Commandmail extends EssentialsCommand { + private static int mailsPerMinute = 0; + private static long timestamp = 0; - public SendAll(String message) - { - this.message = message; - } + public Commandmail() { + super("mail"); + } - @Override - public void run() - { - for (UUID userid : ess.getUserMap().getAllUniqueUsers()) - { - User user = ess.getUserMap().getUser(userid); - if (user != null) - { - user.addMail(message); - } - } - } - } + //TODO: Tidy this up / TL these errors. + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (args.length >= 1 && "read".equalsIgnoreCase(args[0])) { + final List mail = user.getMails(); + if (mail.isEmpty()) { + user.sendMessage(tl("noMail")); + throw new NoChargeException(); + } + + IText input = new SimpleTextInput(mail); + final TextPager pager = new TextPager(input); + pager.showPage(args.length > 1 ? args[1] : null, null, commandLabel + " " + args[0], user.getSource()); + + user.sendMessage(tl("mailClear")); + return; + } + if (args.length >= 3 && "send".equalsIgnoreCase(args[0])) { + if (!user.isAuthorized("essentials.mail.send")) { + throw new Exception(tl("noPerm", "essentials.mail.send")); + } + + if (user.isMuted()) { + throw new Exception(tl("voiceSilenced")); + } + + User u = getPlayer(server, args[1], true, true); + if (u == null) { + throw new Exception(tl("playerNeverOnServer", args[1])); + } + + final String mail = tl("mailFormat", user.getName(), StringUtil.sanitizeString(FormatUtil.stripFormat(getFinalArg(args, 2)))); + if (mail.length() > 1000) { + throw new Exception(tl("mailTooLong")); + } + + if (!u.isIgnoredPlayer(user)) { + if (Math.abs(System.currentTimeMillis() - timestamp) > 60000) { + timestamp = System.currentTimeMillis(); + mailsPerMinute = 0; + } + mailsPerMinute++; + if (mailsPerMinute > ess.getSettings().getMailsPerMinute()) { + throw new Exception(tl("mailDelay", ess.getSettings().getMailsPerMinute())); + } + u.addMail(tl("mailMessage", mail)); + } + + user.sendMessage(tl("mailSentTo", u.getDisplayName(), u.getName())); + user.sendMessage(mail); + return; + } + if (args.length > 1 && "sendall".equalsIgnoreCase(args[0])) { + if (!user.isAuthorized("essentials.mail.sendall")) { + throw new Exception(tl("noPerm", "essentials.mail.sendall")); + } + ess.runTaskAsynchronously(new SendAll(tl("mailFormat", user.getName(), FormatUtil.stripFormat(getFinalArg(args, 1))))); + user.sendMessage(tl("mailSent")); + return; + } + if (args.length >= 1 && "clear".equalsIgnoreCase(args[0])) { + user.setMails(null); + user.sendMessage(tl("mailCleared")); + return; + } + throw new NotEnoughArgumentsException(); + } + + @Override + protected void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception { + if (args.length >= 1 && "read".equalsIgnoreCase(args[0])) { + throw new Exception(tl("onlyPlayers", commandLabel + " read")); + } else if (args.length >= 1 && "clear".equalsIgnoreCase(args[0])) { + throw new Exception(tl("onlyPlayers", commandLabel + " clear")); + } else if (args.length >= 3 && "send".equalsIgnoreCase(args[0])) { + User u = getPlayer(server, args[1], true, true); + if (u == null) { + throw new Exception(tl("playerNeverOnServer", args[1])); + } + u.addMail(tl("mailFormat", "Server", getFinalArg(args, 2))); + sender.sendMessage(tl("mailSent")); + return; + } else if (args.length >= 2 && "sendall".equalsIgnoreCase(args[0])) { + ess.runTaskAsynchronously(new SendAll(tl("mailFormat", "Server", getFinalArg(args, 1)))); + sender.sendMessage(tl("mailSent")); + return; + } else if (args.length >= 2) { + //allow sending from console without "send" argument, since it's the only thing the console can do + User u = getPlayer(server, args[0], true, true); + if (u == null) { + throw new Exception(tl("playerNeverOnServer", args[0])); + } + u.addMail(tl("mailFormat", "Server", getFinalArg(args, 1))); + sender.sendMessage(tl("mailSent")); + return; + } + throw new NotEnoughArgumentsException(); + } + + + private class SendAll implements Runnable { + String message; + + public SendAll(String message) { + this.message = message; + } + + @Override + public void run() { + for (UUID userid : ess.getUserMap().getAllUniqueUsers()) { + User user = ess.getUserMap().getUser(userid); + if (user != null) { + user.addMail(message); + } + } + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandme.java b/Essentials/src/com/earth2me/essentials/commands/Commandme.java index 6dadd0a9c..773bf9c7a 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandme.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandme.java @@ -1,50 +1,44 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.FormatUtil; import org.bukkit.Server; +import static com.earth2me.essentials.I18n.tl; -public class Commandme extends EssentialsCommand -{ - public Commandme() - { - super("me"); - } - @Override - public void run(Server server, User user, String commandLabel, String[] args) throws Exception - { - if (user.isMuted()) - { - throw new Exception(tl("voiceSilenced")); - } +public class Commandme extends EssentialsCommand { + public Commandme() { + super("me"); + } - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } + @Override + public void run(Server server, User user, String commandLabel, String[] args) throws Exception { + if (user.isMuted()) { + throw new Exception(tl("voiceSilenced")); + } - String message = getFinalArg(args, 0); - message = FormatUtil.formatMessage(user, "essentials.chat", message); + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } - user.setDisplayNick(); - ess.broadcastMessage(user, tl("action", user.getDisplayName(), message)); - } + String message = getFinalArg(args, 0); + message = FormatUtil.formatMessage(user, "essentials.chat", message); - @Override - public void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } + user.setDisplayNick(); + ess.broadcastMessage(user, tl("action", user.getDisplayName(), message)); + } - String message = getFinalArg(args, 0); - message = FormatUtil.replaceFormat(message); + @Override + public void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } - ess.getServer().broadcastMessage(tl("action", "@", message)); - } + String message = getFinalArg(args, 0); + message = FormatUtil.replaceFormat(message); + + ess.getServer().broadcastMessage(tl("action", "@", message)); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandmore.java b/Essentials/src/com/earth2me/essentials/commands/Commandmore.java index f0fa43efc..3a08a4966 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandmore.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandmore.java @@ -1,50 +1,37 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; -import java.util.Locale; import org.bukkit.Server; import org.bukkit.inventory.ItemStack; +import java.util.Locale; -public class Commandmore extends EssentialsCommand -{ - public Commandmore() - { - super("more"); - } +import static com.earth2me.essentials.I18n.tl; - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - final ItemStack stack = user.getBase().getItemInHand(); - if (stack == null) - { - throw new Exception(tl("cantSpawnItem", "Air")); - } - if (stack.getAmount() >= ((user.isAuthorized("essentials.oversizedstacks")) - ? ess.getSettings().getOversizedStackSize() : stack.getMaxStackSize())) - { - throw new Exception(tl("fullStack")); - } - final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""); - if (ess.getSettings().permissionBasedItemSpawn() - ? (!user.isAuthorized("essentials.itemspawn.item-all") - && !user.isAuthorized("essentials.itemspawn.item-" + itemname) - && !user.isAuthorized("essentials.itemspawn.item-" + stack.getTypeId())) - : (!user.isAuthorized("essentials.itemspawn.exempt") - && !user.canSpawnItem(stack.getTypeId()))) - { - throw new Exception(tl("cantSpawnItem", itemname)); - } - if (user.isAuthorized("essentials.oversizedstacks")) - { - stack.setAmount(ess.getSettings().getOversizedStackSize()); - } - else - { - stack.setAmount(stack.getMaxStackSize()); - } - user.getBase().updateInventory(); - } + +public class Commandmore extends EssentialsCommand { + public Commandmore() { + super("more"); + } + + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + final ItemStack stack = user.getBase().getItemInHand(); + if (stack == null) { + throw new Exception(tl("cantSpawnItem", "Air")); + } + if (stack.getAmount() >= ((user.isAuthorized("essentials.oversizedstacks")) ? ess.getSettings().getOversizedStackSize() : stack.getMaxStackSize())) { + throw new Exception(tl("fullStack")); + } + final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""); + if (ess.getSettings().permissionBasedItemSpawn() ? (!user.isAuthorized("essentials.itemspawn.item-all") && !user.isAuthorized("essentials.itemspawn.item-" + itemname) && !user.isAuthorized("essentials.itemspawn.item-" + stack.getTypeId())) : (!user.isAuthorized("essentials.itemspawn.exempt") && !user.canSpawnItem(stack.getTypeId()))) { + throw new Exception(tl("cantSpawnItem", itemname)); + } + if (user.isAuthorized("essentials.oversizedstacks")) { + stack.setAmount(ess.getSettings().getOversizedStackSize()); + } else { + stack.setAmount(stack.getMaxStackSize()); + } + user.getBase().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 index 58c8da669..56ab6b5bb 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandmotd.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandmotd.java @@ -8,24 +8,20 @@ import com.earth2me.essentials.textreader.TextPager; import org.bukkit.Server; -public class Commandmotd extends EssentialsCommand -{ - public Commandmotd() - { - super("motd"); - } +public class Commandmotd extends EssentialsCommand { + public Commandmotd() { + super("motd"); + } - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (sender.isPlayer()) - { - ess.getUser(sender.getPlayer()).setDisplayNick(); - } - - 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); - } + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (sender.isPlayer()) { + ess.getUser(sender.getPlayer()).setDisplayNick(); + } + + 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 index 642742730..ff2daa8c2 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandmsg.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandmsg.java @@ -2,85 +2,73 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.Console; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.IReplyTo; import com.earth2me.essentials.User; -import static com.earth2me.essentials.commands.EssentialsCommand.getFinalArg; import com.earth2me.essentials.utils.FormatUtil; import org.bukkit.Server; import org.bukkit.command.CommandSender; +import static com.earth2me.essentials.I18n.tl; -public class Commandmsg extends EssentialsLoopCommand -{ - final String translatedMe = tl("me"); - public Commandmsg() - { - super("msg"); - } +public class Commandmsg extends EssentialsLoopCommand { + final String translatedMe = tl("me"); - @Override - public void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception - { - if (args.length < 2 || args[0].trim().length() < 2 || args[1].trim().isEmpty()) - { - throw new NotEnoughArgumentsException(); - } + public Commandmsg() { + super("msg"); + } - String message = getFinalArg(args, 1); - boolean canWildcard; - if (sender.isPlayer()) - { - User user = ess.getUser(sender.getPlayer()); - if (user.isMuted()) - { - throw new Exception(tl("voiceSilenced")); - } - message = FormatUtil.formatMessage(user, "essentials.msg", message); - canWildcard = user.isAuthorized("essentials.msg.multiple"); - } - else - { - message = FormatUtil.replaceFormat(message); - canWildcard = true; - } + @Override + public void run(Server server, CommandSource sender, String commandLabel, String[] args) throws Exception { + if (args.length < 2 || args[0].trim().length() < 2 || args[1].trim().isEmpty()) { + throw new NotEnoughArgumentsException(); + } - if (args[0].equalsIgnoreCase(Console.NAME)) - { - final IReplyTo replyTo = sender.isPlayer() ? ess.getUser(sender.getPlayer()) : Console.getConsoleReplyTo(); - final String senderName = sender.isPlayer() ? sender.getPlayer().getDisplayName() : Console.NAME; - - sender.sendMessage(tl("msgFormat", translatedMe, Console.NAME, message)); - CommandSender cs = Console.getCommandSender(server); - cs.sendMessage(tl("msgFormat", senderName, translatedMe, message)); - replyTo.setReplyTo(new CommandSource(cs)); - Console.getConsoleReplyTo().setReplyTo(sender); - return; - } + String message = getFinalArg(args, 1); + boolean canWildcard; + if (sender.isPlayer()) { + User user = ess.getUser(sender.getPlayer()); + if (user.isMuted()) { + throw new Exception(tl("voiceSilenced")); + } + message = FormatUtil.formatMessage(user, "essentials.msg", message); + canWildcard = user.isAuthorized("essentials.msg.multiple"); + } else { + message = FormatUtil.replaceFormat(message); + canWildcard = true; + } - loopOnlinePlayers(server, sender, canWildcard, canWildcard, args[0], new String[]{message}); - } + if (args[0].equalsIgnoreCase(Console.NAME)) { + final IReplyTo replyTo = sender.isPlayer() ? ess.getUser(sender.getPlayer()) : Console.getConsoleReplyTo(); + final String senderName = sender.isPlayer() ? sender.getPlayer().getDisplayName() : Console.NAME; - @Override - protected void updatePlayer(final Server server, final CommandSource sender, final User matchedUser, final String[] args) - { - final IReplyTo replyTo = sender.isPlayer() ? ess.getUser(sender.getPlayer()) : Console.getConsoleReplyTo(); - final String senderName = sender.isPlayer() ? sender.getPlayer().getDisplayName() : Console.NAME; + sender.sendMessage(tl("msgFormat", translatedMe, Console.NAME, message)); + CommandSender cs = Console.getCommandSender(server); + cs.sendMessage(tl("msgFormat", senderName, translatedMe, message)); + replyTo.setReplyTo(new CommandSource(cs)); + Console.getConsoleReplyTo().setReplyTo(sender); + return; + } - if (matchedUser.isAfk()) - { - sender.sendMessage(tl("userAFK", matchedUser.getDisplayName())); - } + loopOnlinePlayers(server, sender, canWildcard, canWildcard, args[0], new String[]{message}); + } - sender.sendMessage(tl("msgFormat", translatedMe, matchedUser.getDisplayName(), args[0])); - if (sender.isPlayer() && matchedUser.isIgnoredPlayer(ess.getUser(sender.getPlayer()))) - { - return; - } + @Override + protected void updatePlayer(final Server server, final CommandSource sender, final User matchedUser, final String[] args) { + final IReplyTo replyTo = sender.isPlayer() ? ess.getUser(sender.getPlayer()) : Console.getConsoleReplyTo(); + final String senderName = sender.isPlayer() ? sender.getPlayer().getDisplayName() : Console.NAME; - matchedUser.sendMessage(tl("msgFormat", senderName, translatedMe, args[0])); - replyTo.setReplyTo(matchedUser.getSource()); - matchedUser.setReplyTo(sender); - } + if (matchedUser.isAfk()) { + sender.sendMessage(tl("userAFK", matchedUser.getDisplayName())); + } + + sender.sendMessage(tl("msgFormat", translatedMe, matchedUser.getDisplayName(), args[0])); + if (sender.isPlayer() && matchedUser.isIgnoredPlayer(ess.getUser(sender.getPlayer()))) { + return; + } + + matchedUser.sendMessage(tl("msgFormat", senderName, translatedMe, args[0])); + replyTo.setReplyTo(matchedUser.getSource()); + matchedUser.setReplyTo(sender); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandmute.java b/Essentials/src/com/earth2me/essentials/commands/Commandmute.java index fc44bc20c..b13b74359 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandmute.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandmute.java @@ -1,95 +1,75 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.OfflinePlayer; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.DateUtil; -import java.util.logging.Level; import org.bukkit.Server; +import java.util.logging.Level; -public class Commandmute extends EssentialsCommand -{ - public Commandmute() - { - super("mute"); - } +import static com.earth2me.essentials.I18n.tl; - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - boolean nomatch = false; - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - User user; - try - { - user = getPlayer(server, args, 0, true, true); - } - catch (PlayerNotFoundException e) - { - nomatch = true; - user = ess.getUser(new OfflinePlayer(args[0], ess.getServer())); - } - if (!user.getBase().isOnline()) - { - if (sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.mute.offline")) - { - throw new Exception(tl("muteExemptOffline")); - } - } - else - { - if (user.isAuthorized("essentials.mute.exempt") && sender.isPlayer()) - { - throw new Exception(tl("muteExempt")); - } - } - long muteTimestamp = 0; +public class Commandmute extends EssentialsCommand { + public Commandmute() { + super("mute"); + } - if (args.length > 1) - { - final String time = getFinalArg(args, 1); - muteTimestamp = DateUtil.parseDateDiff(time, true); - user.setMuted(true); - } - else - { - user.setMuted(!user.getMuted()); - } - user.setMuteTimeout(muteTimestamp); - final boolean muted = user.getMuted(); - String muteTime = DateUtil.formatDateDiff(muteTimestamp); + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + boolean nomatch = false; + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } + User user; + try { + user = getPlayer(server, args, 0, true, true); + } catch (PlayerNotFoundException e) { + nomatch = true; + user = ess.getUser(new OfflinePlayer(args[0], ess.getServer())); + } + if (!user.getBase().isOnline()) { + if (sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.mute.offline")) { + throw new Exception(tl("muteExemptOffline")); + } + } else { + if (user.isAuthorized("essentials.mute.exempt") && sender.isPlayer()) { + throw new Exception(tl("muteExempt")); + } + } - if (nomatch) - { - sender.sendMessage(tl("userUnknown", user.getName())); - } + long muteTimestamp = 0; - if (muted) - { - if (muteTimestamp > 0) - { - sender.sendMessage(tl("mutedPlayerFor", user.getDisplayName(), muteTime)); - user.sendMessage(tl("playerMutedFor", muteTime)); - } - else - { - sender.sendMessage(tl("mutedPlayer", user.getDisplayName())); - user.sendMessage(tl("playerMuted")); - } - final String message = tl("muteNotify", sender.getSender().getName(), user.getName(), muteTime); - server.getLogger().log(Level.INFO, message); - ess.broadcastMessage("essentials.mute.notify", message); - } - else - { - sender.sendMessage(tl("unmutedPlayer", user.getDisplayName())); - user.sendMessage(tl("playerUnmuted")); - } - } + if (args.length > 1) { + final String time = getFinalArg(args, 1); + muteTimestamp = DateUtil.parseDateDiff(time, true); + user.setMuted(true); + } else { + user.setMuted(!user.getMuted()); + } + user.setMuteTimeout(muteTimestamp); + final boolean muted = user.getMuted(); + String muteTime = DateUtil.formatDateDiff(muteTimestamp); + + if (nomatch) { + sender.sendMessage(tl("userUnknown", user.getName())); + } + + if (muted) { + if (muteTimestamp > 0) { + sender.sendMessage(tl("mutedPlayerFor", user.getDisplayName(), muteTime)); + user.sendMessage(tl("playerMutedFor", muteTime)); + } else { + sender.sendMessage(tl("mutedPlayer", user.getDisplayName())); + user.sendMessage(tl("playerMuted")); + } + final String message = tl("muteNotify", sender.getSender().getName(), user.getName(), muteTime); + server.getLogger().log(Level.INFO, message); + ess.broadcastMessage("essentials.mute.notify", message); + } else { + sender.sendMessage(tl("unmutedPlayer", user.getDisplayName())); + user.sendMessage(tl("playerUnmuted")); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandnear.java b/Essentials/src/com/earth2me/essentials/commands/Commandnear.java index a31c220ca..3c57e45ec 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandnear.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandnear.java @@ -1,129 +1,100 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import org.bukkit.Location; import org.bukkit.Server; import org.bukkit.World; -import org.bukkit.entity.Player; + +import static com.earth2me.essentials.I18n.tl; -public class Commandnear extends EssentialsCommand -{ - public Commandnear() - { - super("near"); - } +public class Commandnear extends EssentialsCommand { + public Commandnear() { + super("near"); + } - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - long maxRadius = ess.getSettings().getChatRadius(); - - if (maxRadius == 0) - { - maxRadius = 200; - } - - long radius = maxRadius; - - User otherUser = null; + @Override + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + long maxRadius = ess.getSettings().getChatRadius(); - if (args.length > 0) - { - try - { - radius = Long.parseLong(args[0]); - } - catch (NumberFormatException e) - { - try - { - otherUser = getPlayer(server, user, args, 0); - } - catch (Exception ex) - { - } - } - if (args.length > 1 && otherUser != null) - { - try - { - radius = Long.parseLong(args[1]); - } - catch (NumberFormatException e) - { - } - } - } - - radius = Math.abs(radius); - - if (radius > maxRadius && !user.isAuthorized("essentials.near.maxexempt")) - { - user.sendMessage(tl("radiusTooBig", maxRadius)); - radius = maxRadius; - } - - if (otherUser == null || !user.isAuthorized("essentials.near.others")) - { - otherUser = user; - } - user.sendMessage(tl("nearbyPlayers", getLocal(server, otherUser, radius))); - } + if (maxRadius == 0) { + maxRadius = 200; + } - @Override - protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length == 0) - { - throw new NotEnoughArgumentsException(); - } - final User otherUser = getPlayer(server, args, 0, true, false); - long radius = 200; - if (args.length > 1) - { - try - { - radius = Long.parseLong(args[1]); - } - catch (NumberFormatException e) - { - } - } - sender.sendMessage(tl("nearbyPlayers", getLocal(server, otherUser, radius))); - } + long radius = maxRadius; - private String getLocal(final Server server, final User user, final long radius) - { - final Location loc = user.getLocation(); - final World world = loc.getWorld(); - final StringBuilder output = new StringBuilder(); - final long radiusSquared = radius * radius; - boolean showHidden = user.canInteractVanished(); + User otherUser = null; - for (User player: ess.getOnlineUsers()) - { - if (!player.equals(user) && (!player.isHidden(user.getBase()) || showHidden || user.getBase().canSee(player.getBase()))) - { - final Location playerLoc = player.getLocation(); - if (playerLoc.getWorld() != world) - { - continue; - } + if (args.length > 0) { + try { + radius = Long.parseLong(args[0]); + } catch (NumberFormatException e) { + try { + otherUser = getPlayer(server, user, args, 0); + } catch (Exception ex) { + } + } + if (args.length > 1 && otherUser != null) { + try { + radius = Long.parseLong(args[1]); + } catch (NumberFormatException e) { + } + } + } - 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() : tl("none"); - } + radius = Math.abs(radius); + + if (radius > maxRadius && !user.isAuthorized("essentials.near.maxexempt")) { + user.sendMessage(tl("radiusTooBig", maxRadius)); + radius = maxRadius; + } + + if (otherUser == null || !user.isAuthorized("essentials.near.others")) { + otherUser = user; + } + user.sendMessage(tl("nearbyPlayers", getLocal(server, otherUser, radius))); + } + + @Override + protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length == 0) { + throw new NotEnoughArgumentsException(); + } + final User otherUser = getPlayer(server, args, 0, true, false); + long radius = 200; + if (args.length > 1) { + try { + radius = Long.parseLong(args[1]); + } catch (NumberFormatException e) { + } + } + sender.sendMessage(tl("nearbyPlayers", getLocal(server, otherUser, radius))); + } + + private String getLocal(final Server server, final User user, final long radius) { + final Location loc = user.getLocation(); + final World world = loc.getWorld(); + final StringBuilder output = new StringBuilder(); + final long radiusSquared = radius * radius; + boolean showHidden = user.canInteractVanished(); + + for (User player : ess.getOnlineUsers()) { + if (!player.equals(user) && (!player.isHidden(user.getBase()) || showHidden || user.getBase().canSee(player.getBase()))) { + 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() : tl("none"); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandnick.java b/Essentials/src/com/earth2me/essentials/commands/Commandnick.java index fb8914fe4..f8c6e5c5d 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandnick.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandnick.java @@ -1,143 +1,111 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.FormatUtil; -import java.util.Locale; import net.ess3.api.events.NickChangeEvent; import org.bukkit.Server; import org.bukkit.entity.Player; +import java.util.Locale; -public class Commandnick extends EssentialsLoopCommand -{ - public Commandnick() - { - super("nick"); - } +import static com.earth2me.essentials.I18n.tl; - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - if (!ess.getSettings().changeDisplayName()) - { - throw new Exception(tl("nickDisplayName")); - } - if (args.length > 1 && user.isAuthorized("essentials.nick.others")) - { - final String[] nickname = formatNickname(user, args[1]).split(" "); - loopOfflinePlayers(server, user.getSource(), false, true, args[0], nickname); - user.sendMessage(tl("nickChanged")); - } - else - { - final String[] nickname = formatNickname(user, args[0]).split(" "); - updatePlayer(server, user.getSource(), user, nickname); - } - } +public class Commandnick extends EssentialsLoopCommand { + public Commandnick() { + super("nick"); + } - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 2) - { - throw new NotEnoughArgumentsException(); - } - if (!ess.getSettings().changeDisplayName()) - { - throw new Exception(tl("nickDisplayName")); - } - final String[] nickname = formatNickname(null, args[1]).split(" "); - loopOfflinePlayers(server, sender, false, true, args[0], nickname); - sender.sendMessage(tl("nickChanged")); - } + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } + if (!ess.getSettings().changeDisplayName()) { + throw new Exception(tl("nickDisplayName")); + } - @Override - protected void updatePlayer(final Server server, final CommandSource sender, final User target, final String[] args) throws NotEnoughArgumentsException - { - final String nick = args[0]; - if (target.getName().equalsIgnoreCase(nick)) - { - String oldName = target.getDisplayName(); - setNickname(server, sender, target, nick); - if (!target.getDisplayName().equalsIgnoreCase(oldName)) - { - target.sendMessage(tl("nickNoMore")); - } - target.sendMessage(tl("nickSet", target.getDisplayName())); - } - else if ("off".equalsIgnoreCase(nick)) - { - setNickname(server, sender, target, null); - target.sendMessage(tl("nickNoMore")); - } - else if (nickInUse(server, target, nick)) - { - throw new NotEnoughArgumentsException(tl("nickInUse")); - } - else - { - setNickname(server, sender, target, nick); - target.sendMessage(tl("nickSet", target.getDisplayName())); - } - } + if (args.length > 1 && user.isAuthorized("essentials.nick.others")) { + final String[] nickname = formatNickname(user, args[1]).split(" "); + loopOfflinePlayers(server, user.getSource(), false, true, args[0], nickname); + user.sendMessage(tl("nickChanged")); + } else { + final String[] nickname = formatNickname(user, args[0]).split(" "); + updatePlayer(server, user.getSource(), user, nickname); + } + } - private String formatNickname(final User user, final String nick) throws Exception - { - String newNick = user == null ? FormatUtil.replaceFormat(nick) : FormatUtil.formatString(user, "essentials.nick", nick); - if (!newNick.matches("^[a-zA-Z_0-9\u00a7]+$")) - { - throw new Exception(tl("nickNamesAlpha")); - } - else if (newNick.length() > ess.getSettings().getMaxNickLength()) - { - throw new Exception(tl("nickTooLong")); - } - else if (FormatUtil.stripFormat(newNick).length() < 1) - { - throw new Exception(tl("nickNamesAlpha")); - } - return newNick; - } + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 2) { + throw new NotEnoughArgumentsException(); + } + if (!ess.getSettings().changeDisplayName()) { + throw new Exception(tl("nickDisplayName")); + } + final String[] nickname = formatNickname(null, args[1]).split(" "); + loopOfflinePlayers(server, sender, false, true, args[0], nickname); + sender.sendMessage(tl("nickChanged")); + } - private boolean nickInUse(final Server server, final User target, String nick) - { - final String lowerNick = FormatUtil.stripFormat(nick.toLowerCase(Locale.ENGLISH)); - for (final Player onlinePlayer : ess.getOnlinePlayers()) - { - if (target.getBase().getName().equals(onlinePlayer.getName())) - { - continue; - } - final String matchNick = FormatUtil.stripFormat(onlinePlayer.getDisplayName().replace(ess.getSettings().getNicknamePrefix(), "")); - if (lowerNick.equals(matchNick.toLowerCase(Locale.ENGLISH)) - || lowerNick.equals(onlinePlayer.getName().toLowerCase(Locale.ENGLISH))) - { - return true; - } - } - if (ess.getUser(lowerNick) != null && ess.getUser(lowerNick) != target) - { - return true; - } - return false; - } + @Override + protected void updatePlayer(final Server server, final CommandSource sender, final User target, final String[] args) throws NotEnoughArgumentsException { + final String nick = args[0]; + if (target.getName().equalsIgnoreCase(nick)) { + String oldName = target.getDisplayName(); + setNickname(server, sender, target, nick); + if (!target.getDisplayName().equalsIgnoreCase(oldName)) { + target.sendMessage(tl("nickNoMore")); + } + target.sendMessage(tl("nickSet", target.getDisplayName())); + } else if ("off".equalsIgnoreCase(nick)) { + setNickname(server, sender, target, null); + target.sendMessage(tl("nickNoMore")); + } else if (nickInUse(server, target, nick)) { + throw new NotEnoughArgumentsException(tl("nickInUse")); + } else { + setNickname(server, sender, target, nick); + target.sendMessage(tl("nickSet", target.getDisplayName())); + } + } - private void setNickname(final Server server, final CommandSource sender, final User target, final String nickname) - { - final User controller = sender.isPlayer() ? ess.getUser(sender.getPlayer()) : null; - final NickChangeEvent nickEvent = new NickChangeEvent(controller, target, nickname); - server.getPluginManager().callEvent(nickEvent); - if (!nickEvent.isCancelled()) - { - target.setNickname(nickname); - target.setDisplayNick(); - } - } + private String formatNickname(final User user, final String nick) throws Exception { + String newNick = user == null ? FormatUtil.replaceFormat(nick) : FormatUtil.formatString(user, "essentials.nick", nick); + if (!newNick.matches("^[a-zA-Z_0-9\u00a7]+$")) { + throw new Exception(tl("nickNamesAlpha")); + } else if (newNick.length() > ess.getSettings().getMaxNickLength()) { + throw new Exception(tl("nickTooLong")); + } else if (FormatUtil.stripFormat(newNick).length() < 1) { + throw new Exception(tl("nickNamesAlpha")); + } + return newNick; + } + + private boolean nickInUse(final Server server, final User target, String nick) { + final String lowerNick = FormatUtil.stripFormat(nick.toLowerCase(Locale.ENGLISH)); + for (final Player onlinePlayer : ess.getOnlinePlayers()) { + if (target.getBase().getName().equals(onlinePlayer.getName())) { + continue; + } + final String matchNick = FormatUtil.stripFormat(onlinePlayer.getDisplayName().replace(ess.getSettings().getNicknamePrefix(), "")); + if (lowerNick.equals(matchNick.toLowerCase(Locale.ENGLISH)) || lowerNick.equals(onlinePlayer.getName().toLowerCase(Locale.ENGLISH))) { + return true; + } + } + if (ess.getUser(lowerNick) != null && ess.getUser(lowerNick) != target) { + return true; + } + return false; + } + + private void setNickname(final Server server, final CommandSource sender, final User target, final String nickname) { + final User controller = sender.isPlayer() ? ess.getUser(sender.getPlayer()) : null; + final NickChangeEvent nickEvent = new NickChangeEvent(controller, target, nickname); + server.getPluginManager().callEvent(nickEvent); + if (!nickEvent.isCancelled()) { + target.setNickname(nickname); + target.setDisplayNick(); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandnuke.java b/Essentials/src/com/earth2me/essentials/commands/Commandnuke.java index e82c46c8d..83e464656 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandnuke.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandnuke.java @@ -1,59 +1,50 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; -import java.util.ArrayList; -import java.util.Collection; import org.bukkit.Location; import org.bukkit.Server; import org.bukkit.World; import org.bukkit.entity.Player; import org.bukkit.entity.TNTPrimed; +import java.util.ArrayList; +import java.util.Collection; -public class Commandnuke extends EssentialsCommand -{ - public Commandnuke() - { - super("nuke"); - } +import static com.earth2me.essentials.I18n.tl; - @Override - protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws NoSuchFieldException, NotEnoughArgumentsException - { - Collection targets; - if (args.length > 0) - { - targets = new ArrayList(); - int pos = 0; - for (String arg : args) - { - targets.add(getPlayer(server, sender, args, pos).getBase()); - pos++; - } - } - else - { - targets = ess.getOnlinePlayers(); - } - ess.getTNTListener().enable(); - for (Player player : targets) - { - if (player == null) - { - continue; - } - player.sendMessage(tl("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.getHighestBlockYAt(loc) + 64, loc.getBlockZ() + z); - final TNTPrimed tnt = world.spawn(tntloc, TNTPrimed.class); - } - } - } - } + +public class Commandnuke extends EssentialsCommand { + public Commandnuke() { + super("nuke"); + } + + @Override + protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws NoSuchFieldException, NotEnoughArgumentsException { + Collection targets; + if (args.length > 0) { + targets = new ArrayList(); + int pos = 0; + for (String arg : args) { + targets.add(getPlayer(server, sender, args, pos).getBase()); + pos++; + } + } else { + targets = ess.getOnlinePlayers(); + } + ess.getTNTListener().enable(); + for (Player player : targets) { + if (player == null) { + continue; + } + player.sendMessage(tl("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.getHighestBlockYAt(loc) + 64, 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 index a83df4ac7..9de9e35d5 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandpay.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandpay.java @@ -2,54 +2,47 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.ChargeException; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.Trade; import com.earth2me.essentials.User; -import java.math.BigDecimal; import net.ess3.api.MaxMoneyException; import org.bukkit.Server; +import java.math.BigDecimal; -public class Commandpay extends EssentialsLoopCommand -{ - BigDecimal amount; +import static com.earth2me.essentials.I18n.tl; - public Commandpay() - { - super("pay"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 2) - { - throw new NotEnoughArgumentsException(); - } +public class Commandpay extends EssentialsLoopCommand { + BigDecimal amount; - String stringAmount = args[1].replaceAll("[^0-9\\.]", ""); + public Commandpay() { + super("pay"); + } - if (stringAmount.length() < 1) - { - throw new NotEnoughArgumentsException(); - } + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (args.length < 2) { + throw new NotEnoughArgumentsException(); + } - amount = new BigDecimal(stringAmount); - loopOnlinePlayers(server, user.getSource(), false, user.isAuthorized("essentials.pay.multiple"), args[0], args); - } + String stringAmount = args[1].replaceAll("[^0-9\\.]", ""); - @Override - protected void updatePlayer(final Server server, final CommandSource sender, final User player, final String[] args) throws ChargeException - { - User user = ess.getUser(sender.getPlayer()); - try - { - user.payUser(player, amount); - Trade.log("Command", "Pay", "Player", user.getName(), new Trade(amount, ess), player.getName(), new Trade(amount, ess), user.getLocation(), ess); - } - catch (MaxMoneyException ex) - { - sender.sendMessage(tl("maxMoney")); - } - } + if (stringAmount.length() < 1) { + throw new NotEnoughArgumentsException(); + } + + amount = new BigDecimal(stringAmount); + loopOnlinePlayers(server, user.getSource(), false, user.isAuthorized("essentials.pay.multiple"), args[0], args); + } + + @Override + protected void updatePlayer(final Server server, final CommandSource sender, final User player, final String[] args) throws ChargeException { + User user = ess.getUser(sender.getPlayer()); + try { + user.payUser(player, amount); + Trade.log("Command", "Pay", "Player", user.getName(), new Trade(amount, ess), player.getName(), new Trade(amount, ess), user.getLocation(), ess); + } catch (MaxMoneyException ex) { + sender.sendMessage(tl("maxMoney")); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandping.java b/Essentials/src/com/earth2me/essentials/commands/Commandping.java index 1535ad6a2..dba0ff327 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandping.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandping.java @@ -1,29 +1,24 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.utils.FormatUtil; import org.bukkit.Server; +import static com.earth2me.essentials.I18n.tl; + // This command can be used to echo messages to the users screen, mostly useless but also an #EasterEgg -public class Commandping extends EssentialsCommand -{ - public Commandping() - { - super("ping"); - } +public class Commandping extends EssentialsCommand { + public Commandping() { + super("ping"); + } - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { - sender.sendMessage(tl("pong")); - } - else - { - sender.sendMessage(FormatUtil.replaceFormat(getFinalArg(args, 0))); - } - } + sender.sendMessage(tl("pong")); + } else { + sender.sendMessage(FormatUtil.replaceFormat(getFinalArg(args, 0))); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandpotion.java b/Essentials/src/com/earth2me/essentials/commands/Commandpotion.java index 108644649..5db524300 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandpotion.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandpotion.java @@ -1,14 +1,9 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.MetaItemStack; import com.earth2me.essentials.Potions; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.StringUtil; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; import org.bukkit.Material; import org.bukkit.Server; import org.bukkit.inventory.ItemStack; @@ -16,78 +11,63 @@ import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; -public class Commandpotion extends EssentialsCommand -{ - public Commandpotion() - { - super("potion"); - } +import static com.earth2me.essentials.I18n.tl; - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - final ItemStack stack = user.getBase().getItemInHand(); - if (args.length == 0) - { - final Set potionslist = new TreeSet(); - for (Map.Entry entry : Potions.entrySet()) - { - final String potionName = entry.getValue().getName().toLowerCase(Locale.ENGLISH); - if (potionslist.contains(potionName) || (user.isAuthorized("essentials.potion." + potionName))) - { - potionslist.add(entry.getKey()); - } - } - throw new NotEnoughArgumentsException(tl("potions", StringUtil.joinList(potionslist.toArray()))); - } +public class Commandpotion extends EssentialsCommand { + public Commandpotion() { + super("potion"); + } - if (stack.getType() == Material.POTION) - { - PotionMeta pmeta = (PotionMeta)stack.getItemMeta(); - if (args.length > 0) - { - if (args[0].equalsIgnoreCase("clear")) - { - pmeta.clearCustomEffects(); - stack.setItemMeta(pmeta); - } - else if (args[0].equalsIgnoreCase("apply") && user.isAuthorized("essentials.potion.apply")) - { - for (PotionEffect effect : pmeta.getCustomEffects()) - { - effect.apply(user.getBase()); - } - } - else if (args.length < 3) - { - throw new NotEnoughArgumentsException(); - } - else - { - final MetaItemStack mStack = new MetaItemStack(stack); - for (String arg : args) - { - mStack.addPotionMeta(user.getSource(), true, arg, ess); - } - if (mStack.completePotion()) - { - pmeta = (PotionMeta)mStack.getItemStack().getItemMeta(); - stack.setItemMeta(pmeta); - } - else - { - user.sendMessage(tl("invalidPotion")); - throw new NotEnoughArgumentsException(); - } - } - } + @Override + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + final ItemStack stack = user.getBase().getItemInHand(); - } - else - { - throw new Exception(tl("holdPotion")); - } - } + if (args.length == 0) { + final Set potionslist = new TreeSet(); + for (Map.Entry entry : Potions.entrySet()) { + final String potionName = entry.getValue().getName().toLowerCase(Locale.ENGLISH); + if (potionslist.contains(potionName) || (user.isAuthorized("essentials.potion." + potionName))) { + potionslist.add(entry.getKey()); + } + } + throw new NotEnoughArgumentsException(tl("potions", StringUtil.joinList(potionslist.toArray()))); + } + + if (stack.getType() == Material.POTION) { + PotionMeta pmeta = (PotionMeta) stack.getItemMeta(); + if (args.length > 0) { + if (args[0].equalsIgnoreCase("clear")) { + pmeta.clearCustomEffects(); + stack.setItemMeta(pmeta); + } else if (args[0].equalsIgnoreCase("apply") && user.isAuthorized("essentials.potion.apply")) { + for (PotionEffect effect : pmeta.getCustomEffects()) { + effect.apply(user.getBase()); + } + } else if (args.length < 3) { + throw new NotEnoughArgumentsException(); + } else { + final MetaItemStack mStack = new MetaItemStack(stack); + for (String arg : args) { + mStack.addPotionMeta(user.getSource(), true, arg, ess); + } + if (mStack.completePotion()) { + pmeta = (PotionMeta) mStack.getItemStack().getItemMeta(); + stack.setItemMeta(pmeta); + } else { + user.sendMessage(tl("invalidPotion")); + throw new NotEnoughArgumentsException(); + } + } + } + + } else { + throw new Exception(tl("holdPotion")); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandpowertool.java b/Essentials/src/com/earth2me/essentials/commands/Commandpowertool.java index 9c951395c..73bd48e49 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandpowertool.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandpowertool.java @@ -1,130 +1,105 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.StringUtil; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; import org.bukkit.Material; import org.bukkit.Server; import org.bukkit.inventory.ItemStack; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; -public class Commandpowertool extends EssentialsCommand -{ - public Commandpowertool() - { - super("powertool"); - } +import static com.earth2me.essentials.I18n.tl; - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - final String command = getFinalArg(args, 0); - final ItemStack itemStack = user.getBase().getItemInHand(); - powertool(server, user.getSource(), user, commandLabel, itemStack, command); - } - @Override - protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 3) //running from console means inserting a player and item before the standard syntax - { - throw new Exception("When running from console, usage is: /" + commandLabel + " "); - } +public class Commandpowertool extends EssentialsCommand { + public Commandpowertool() { + super("powertool"); + } - final User user = getPlayer(server, args, 0, true, true); - final ItemStack itemStack = ess.getItemDb().get(args[1]); - final String command = getFinalArg(args, 2); - powertool(server, sender, user, commandLabel, itemStack, command); - } + @Override + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + final String command = getFinalArg(args, 0); + final ItemStack itemStack = user.getBase().getItemInHand(); + powertool(server, user.getSource(), user, commandLabel, itemStack, command); + } - protected void powertool(final Server server, final CommandSource sender, final User user, final String commandLabel, final ItemStack itemStack, String command) throws Exception - { - // check to see if this is a clear all command - if (command != null && command.equalsIgnoreCase("d:")) - { - user.clearAllPowertools(); - sender.sendMessage(tl("powerToolClearAll")); - return; - } + @Override + protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 3) //running from console means inserting a player and item before the standard syntax + { + throw new Exception("When running from console, usage is: /" + commandLabel + " "); + } - if (itemStack == null || itemStack.getType() == Material.AIR) - { - throw new Exception(tl("powerToolAir")); - } + final User user = getPlayer(server, args, 0, true, true); + final ItemStack itemStack = ess.getItemDb().get(args[1]); + final String command = getFinalArg(args, 2); + powertool(server, sender, user, commandLabel, itemStack, command); + } - final String itemName = itemStack.getType().toString().toLowerCase(Locale.ENGLISH).replaceAll("_", " "); - List powertools = user.getPowertool(itemStack); - if (command != null && !command.isEmpty()) - { - if (command.equalsIgnoreCase("l:")) - { - if (powertools == null || powertools.isEmpty()) - { - throw new Exception(tl("powerToolListEmpty", itemName)); - } - else - { - sender.sendMessage(tl("powerToolList", StringUtil.joinList(powertools), itemName)); - } - throw new NoChargeException(); - } - if (command.startsWith("r:")) - { - command = command.substring(2); - if (!powertools.contains(command)) - { - throw new Exception(tl("powerToolNoSuchCommandAssigned", command, itemName)); - } + protected void powertool(final Server server, final CommandSource sender, final User user, final String commandLabel, final ItemStack itemStack, String command) throws Exception { + // check to see if this is a clear all command + if (command != null && command.equalsIgnoreCase("d:")) { + user.clearAllPowertools(); + sender.sendMessage(tl("powerToolClearAll")); + return; + } - powertools.remove(command); - sender.sendMessage(tl("powerToolRemove", command, itemName)); - } - else - { - if (command.startsWith("a:")) - { - if (sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.powertool.append")) - { - throw new Exception(tl("noPerm", "essentials.powertool.append")); - } - command = command.substring(2); - if (powertools.contains(command)) - { - throw new Exception(tl("powerToolAlreadySet", command, itemName)); - } - } - else if (powertools != null && !powertools.isEmpty()) - { - // Replace all commands with this one - powertools.clear(); - } - else - { - powertools = new ArrayList(); - } + if (itemStack == null || itemStack.getType() == Material.AIR) { + throw new Exception(tl("powerToolAir")); + } - powertools.add(command); - sender.sendMessage(tl("powerToolAttach", StringUtil.joinList(powertools), itemName)); - } - } - else - { - if (powertools != null) - { - powertools.clear(); - } - sender.sendMessage(tl("powerToolRemoveAll", itemName)); - } + final String itemName = itemStack.getType().toString().toLowerCase(Locale.ENGLISH).replaceAll("_", " "); + List powertools = user.getPowertool(itemStack); + if (command != null && !command.isEmpty()) { + if (command.equalsIgnoreCase("l:")) { + if (powertools == null || powertools.isEmpty()) { + throw new Exception(tl("powerToolListEmpty", itemName)); + } else { + sender.sendMessage(tl("powerToolList", StringUtil.joinList(powertools), itemName)); + } + throw new NoChargeException(); + } + if (command.startsWith("r:")) { + command = command.substring(2); + if (!powertools.contains(command)) { + throw new Exception(tl("powerToolNoSuchCommandAssigned", command, itemName)); + } - if (!user.arePowerToolsEnabled()) - { - user.setPowerToolsEnabled(true); - user.sendMessage(tl("powerToolsEnabled")); - } - user.setPowertool(itemStack, powertools); - } + powertools.remove(command); + sender.sendMessage(tl("powerToolRemove", command, itemName)); + } else { + if (command.startsWith("a:")) { + if (sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.powertool.append")) { + throw new Exception(tl("noPerm", "essentials.powertool.append")); + } + command = command.substring(2); + if (powertools.contains(command)) { + throw new Exception(tl("powerToolAlreadySet", command, itemName)); + } + } else if (powertools != null && !powertools.isEmpty()) { + // Replace all commands with this one + powertools.clear(); + } else { + powertools = new ArrayList(); + } + + powertools.add(command); + sender.sendMessage(tl("powerToolAttach", StringUtil.joinList(powertools), itemName)); + } + } else { + if (powertools != null) { + powertools.clear(); + } + sender.sendMessage(tl("powerToolRemoveAll", itemName)); + } + + if (!user.arePowerToolsEnabled()) { + user.setPowerToolsEnabled(true); + user.sendMessage(tl("powerToolsEnabled")); + } + user.setPowertool(itemStack, powertools); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandpowertooltoggle.java b/Essentials/src/com/earth2me/essentials/commands/Commandpowertooltoggle.java index a71f3887d..fadf3fa47 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandpowertooltoggle.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandpowertooltoggle.java @@ -1,27 +1,22 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import org.bukkit.Server; +import static com.earth2me.essentials.I18n.tl; -public class Commandpowertooltoggle extends EssentialsCommand -{ - public Commandpowertooltoggle() - { - super("powertooltoggle"); - } - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (!user.hasPowerTools()) - { - user.sendMessage(tl("noPowerTools")); - return; - } - user.sendMessage(user.togglePowerToolsEnabled() - ? tl("powerToolsEnabled") - : tl("powerToolsDisabled")); - } +public class Commandpowertooltoggle extends EssentialsCommand { + public Commandpowertooltoggle() { + super("powertooltoggle"); + } + + @Override + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (!user.hasPowerTools()) { + user.sendMessage(tl("noPowerTools")); + return; + } + user.sendMessage(user.togglePowerToolsEnabled() ? tl("powerToolsEnabled") : tl("powerToolsDisabled")); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandptime.java b/Essentials/src/com/earth2me/essentials/commands/Commandptime.java index edb16d5d7..acc5360c7 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandptime.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandptime.java @@ -1,246 +1,194 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.DescParseTickFormat; -import java.util.*; import org.bukkit.Server; import org.bukkit.World; import org.bukkit.entity.Player; +import java.util.*; -public class Commandptime extends EssentialsCommand -{ - private static final Set getAliases = new HashSet(); +import static com.earth2me.essentials.I18n.tl; - static - { - getAliases.add("get"); - getAliases.add("list"); - getAliases.add("show"); - getAliases.add("display"); - } - public Commandptime() - { - super("ptime"); - } +public class Commandptime extends EssentialsCommand { + private static final Set getAliases = new HashSet(); - @Override - public void run(final Server server, final CommandSource 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(server, sender, userSelector); + static { + getAliases.add("get"); + getAliases.add("list"); + getAliases.add("show"); + getAliases.add("display"); + } - // If no arguments we are reading the time - if (args.length == 0) - { - getUsersTime(sender, users); - return; - } + public Commandptime() { + super("ptime"); + } - if (sender.isPlayer()) - { - User user = ess.getUser(sender.getPlayer()); - if (user != null && (!users.contains(user) || users.size() > 1) && !user.isAuthorized("essentials.ptime.others")) - { - user.sendMessage(tl("pTimeOthersPermission")); - return; - } - } + @Override + public void run(final Server server, final CommandSource 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(server, sender, userSelector); - 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 no arguments we are reading the time + if (args.length == 0) { + getUsersTime(sender, users); + return; + } - 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); - } - } + if (sender.isPlayer()) { + User user = ess.getUser(sender.getPlayer()); + if (user != null && (!users.contains(user) || users.size() > 1) && !user.isAuthorized("essentials.ptime.others")) { + user.sendMessage(tl("pTimeOthersPermission")); + return; + } + } - setUsersTime(sender, users, ticks, relative); - } + 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); + } - /** - * Used to get the time and inform - */ - private void getUsersTime(final CommandSource sender, final Collection users) - { - if (users.size() > 1) - { - sender.sendMessage(tl("pTimePlayers")); - } + 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); + } + } - for (User user : users) - { - if (user.getBase().getPlayerTimeOffset() == 0) - { - sender.sendMessage(tl("pTimeNormal", user.getName())); - } - else - { - String time = DescParseTickFormat.format(user.getBase().getPlayerTime()); - if (!user.getBase().isPlayerTimeRelative()) - { - sender.sendMessage(tl("pTimeCurrentFixed", user.getName(), time)); - } - else - { - sender.sendMessage(tl("pTimeCurrent", user.getName(), time)); - } - } - } - } + setUsersTime(sender, users, ticks, relative); + } - /** - * Used to set the time and inform of the change - */ - private void setUsersTime(final CommandSource sender, final Collection users, final Long ticks, Boolean relative) - { - // Update the time - if (ticks == null) - { - // Reset - for (User user : users) - { - user.getBase().resetPlayerTime(); - } - } - else - { - // Set - for (User user : users) - { - final World world = user.getWorld(); - long time = user.getBase().getPlayerTime(); - time -= time % 24000; - time += 24000 + ticks; - if (relative) - { - time -= world.getTime(); - } - user.getBase().setPlayerTime(time, relative); - } - } + /** + * Used to get the time and inform + */ + private void getUsersTime(final CommandSource sender, final Collection users) { + if (users.size() > 1) { + sender.sendMessage(tl("pTimePlayers")); + } - final StringBuilder msg = new StringBuilder(); - for (User user : users) - { - if (msg.length() > 0) - { - msg.append(", "); - } + for (User user : users) { + if (user.getBase().getPlayerTimeOffset() == 0) { + sender.sendMessage(tl("pTimeNormal", user.getName())); + } else { + String time = DescParseTickFormat.format(user.getBase().getPlayerTime()); + if (!user.getBase().isPlayerTimeRelative()) { + sender.sendMessage(tl("pTimeCurrentFixed", user.getName(), time)); + } else { + sender.sendMessage(tl("pTimeCurrent", user.getName(), time)); + } + } + } + } - msg.append(user.getName()); - } + /** + * Used to set the time and inform of the change + */ + private void setUsersTime(final CommandSource sender, final Collection users, final Long ticks, Boolean relative) { + // Update the time + if (ticks == null) { + // Reset + for (User user : users) { + user.getBase().resetPlayerTime(); + } + } else { + // Set + for (User user : users) { + final World world = user.getWorld(); + long time = user.getBase().getPlayerTime(); + time -= time % 24000; + time += 24000 + ticks; + if (relative) { + time -= world.getTime(); + } + user.getBase().setPlayerTime(time, relative); + } + } - // Inform the sender of the change - if (ticks == null) - { - sender.sendMessage(tl("pTimeReset", msg.toString())); - } - else - { - String time = DescParseTickFormat.format(ticks); - if (!relative) - { - sender.sendMessage(tl("pTimeSetFixed", time, msg.toString())); - } - else - { - sender.sendMessage(tl("pTimeSet", time, msg.toString())); - } - } - } + final StringBuilder msg = new StringBuilder(); + for (User user : users) { + if (msg.length() > 0) { + msg.append(", "); + } - /** - * Used to parse an argument of the type "users(s) selector" - */ - private Set getUsers(final Server server, final CommandSource sender, final String selector) throws Exception - { - final Set users = new TreeSet(new UserNameComparator()); - // If there is no selector we want the sender itself. Or all users if sender isn't a user. - if (selector == null) - { - if (sender.isPlayer()) - { - final User user = ess.getUser(sender.getPlayer()); - users.add(user); - } - else - { - for (User user : ess.getOnlineUsers()) - { - users.add(user); - } - } - return users; - } + msg.append(user.getName()); + } - // Try to find the user with name = selector - User user = null; - final List matchedPlayers = server.matchPlayer(selector); - if (!matchedPlayers.isEmpty()) - { - user = ess.getUser(matchedPlayers.get(0)); - } + // Inform the sender of the change + if (ticks == null) { + sender.sendMessage(tl("pTimeReset", msg.toString())); + } else { + String time = DescParseTickFormat.format(ticks); + if (!relative) { + sender.sendMessage(tl("pTimeSetFixed", time, msg.toString())); + } else { + sender.sendMessage(tl("pTimeSet", time, msg.toString())); + } + } + } - if (user != null) - { - users.add(user); - } - // If that fails, Is the argument something like "*" or "all"? - else if (selector.equalsIgnoreCase("*") || selector.equalsIgnoreCase("all")) - { - for (User u : ess.getOnlineUsers()) - { - users.add(u); - } - } - // We failed to understand the world target... - else - { - throw new PlayerNotFoundException(); - } + /** + * Used to parse an argument of the type "users(s) selector" + */ + private Set getUsers(final Server server, final CommandSource sender, final String selector) throws Exception { + final Set users = new TreeSet(new UserNameComparator()); + // If there is no selector we want the sender itself. Or all users if sender isn't a user. + if (selector == null) { + if (sender.isPlayer()) { + final User user = ess.getUser(sender.getPlayer()); + users.add(user); + } else { + for (User user : ess.getOnlineUsers()) { + users.add(user); + } + } + return users; + } - return users; - } + // Try to find the user with name = selector + User 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 (User u : ess.getOnlineUsers()) { + users.add(u); + } + } + // We failed to understand the world target... + else { + throw new PlayerNotFoundException(); + } + + return users; + } } -class UserNameComparator implements Comparator -{ - @Override - public int compare(User a, User b) - { - return a.getName().compareTo(b.getName()); - } +class UserNameComparator implements Comparator { + @Override + public int compare(User a, User b) { + return a.getName().compareTo(b.getName()); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandpweather.java b/Essentials/src/com/earth2me/essentials/commands/Commandpweather.java index 69e0295dc..6784011ea 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandpweather.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandpweather.java @@ -1,186 +1,153 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; -import java.util.*; import org.bukkit.Server; import org.bukkit.WeatherType; import org.bukkit.entity.Player; +import java.util.*; -public class Commandpweather extends EssentialsCommand -{ - public static final Set getAliases = new HashSet(); - public static final Map weatherAliases = new HashMap(); +import static com.earth2me.essentials.I18n.tl; - static - { - getAliases.add("get"); - getAliases.add("list"); - getAliases.add("show"); - getAliases.add("display"); - weatherAliases.put("sun", WeatherType.CLEAR); - weatherAliases.put("clear", WeatherType.CLEAR); - weatherAliases.put("storm", WeatherType.DOWNFALL); - weatherAliases.put("thunder", WeatherType.DOWNFALL); - } - public Commandpweather() - { - super("pweather"); - } +public class Commandpweather extends EssentialsCommand { + public static final Set getAliases = new HashSet(); + public static final Map weatherAliases = new HashMap(); - @Override - public void run(final Server server, final CommandSource 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(server, sender, userSelector); + static { + getAliases.add("get"); + getAliases.add("list"); + getAliases.add("show"); + getAliases.add("display"); + weatherAliases.put("sun", WeatherType.CLEAR); + weatherAliases.put("clear", WeatherType.CLEAR); + weatherAliases.put("storm", WeatherType.DOWNFALL); + weatherAliases.put("thunder", WeatherType.DOWNFALL); + } - if (args.length == 0) - { - getUsersWeather(sender, users); - return; - } + public Commandpweather() { + super("pweather"); + } - if (getAliases.contains(args[0])) - { - getUsersWeather(sender, users); - return; - } + @Override + public void run(final Server server, final CommandSource 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(server, sender, userSelector); - if (sender.isPlayer()) - { - User user = ess.getUser(sender.getPlayer()); - if (user != null && (!users.contains(user) || users.size() > 1) && !user.isAuthorized("essentials.pweather.others")) - { - user.sendMessage(tl("pWeatherOthersPermission")); - return; - } - } + if (args.length == 0) { + getUsersWeather(sender, users); + return; + } - setUsersWeather(sender, users, args[0].toLowerCase()); - } + if (getAliases.contains(args[0])) { + getUsersWeather(sender, users); + return; + } - /** - * Used to get the time and inform - */ - private void getUsersWeather(final CommandSource sender, final Collection users) - { - if (users.size() > 1) - { - sender.sendMessage(tl("pWeatherPlayers")); - } + if (sender.isPlayer()) { + User user = ess.getUser(sender.getPlayer()); + if (user != null && (!users.contains(user) || users.size() > 1) && !user.isAuthorized("essentials.pweather.others")) { + user.sendMessage(tl("pWeatherOthersPermission")); + return; + } + } - for (User user : users) - { - if (user.getBase().getPlayerWeather() == null) - { - sender.sendMessage(tl("pWeatherNormal", user.getName())); - } - else - { - sender.sendMessage(tl("pWeatherCurrent", user.getName(), user.getBase().getPlayerWeather().toString().toLowerCase(Locale.ENGLISH))); - } - } - } + setUsersWeather(sender, users, args[0].toLowerCase()); + } - /** - * Used to set the time and inform of the change - */ - private void setUsersWeather(final CommandSource sender, final Collection users, final String weatherType) throws Exception - { + /** + * Used to get the time and inform + */ + private void getUsersWeather(final CommandSource sender, final Collection users) { + if (users.size() > 1) { + sender.sendMessage(tl("pWeatherPlayers")); + } - final StringBuilder msg = new StringBuilder(); - for (User user : users) - { - if (msg.length() > 0) - { - msg.append(", "); - } + for (User user : users) { + if (user.getBase().getPlayerWeather() == null) { + sender.sendMessage(tl("pWeatherNormal", user.getName())); + } else { + sender.sendMessage(tl("pWeatherCurrent", user.getName(), user.getBase().getPlayerWeather().toString().toLowerCase(Locale.ENGLISH))); + } + } + } - msg.append(user.getName()); - } + /** + * Used to set the time and inform of the change + */ + private void setUsersWeather(final CommandSource sender, final Collection users, final String weatherType) throws Exception { - if (weatherType.equalsIgnoreCase("reset")) - { - for (User user : users) - { - user.getBase().resetPlayerWeather(); - } + final StringBuilder msg = new StringBuilder(); + for (User user : users) { + if (msg.length() > 0) { + msg.append(", "); + } - sender.sendMessage(tl("pWeatherReset", msg)); - } - else - { - if (!weatherAliases.containsKey(weatherType)) - { - throw new NotEnoughArgumentsException(tl("pWeatherInvalidAlias")); - } + msg.append(user.getName()); + } - for (User user : users) - { - user.getBase().setPlayerWeather(weatherAliases.get(weatherType)); - } - sender.sendMessage(tl("pWeatherSet", weatherType, msg.toString())); - } - } + if (weatherType.equalsIgnoreCase("reset")) { + for (User user : users) { + user.getBase().resetPlayerWeather(); + } - /** - * Used to parse an argument of the type "users(s) selector" - */ - private Set getUsers(final Server server, final CommandSource sender, final String selector) throws Exception - { - final Set users = new TreeSet(new UserNameComparator()); - // If there is no selector we want the sender itself. Or all users if sender isn't a user. - if (selector == null) - { - if (sender.isPlayer()) - { - final User user = ess.getUser(sender.getPlayer()); - users.add(user); - } - else - { - for (User user : ess.getOnlineUsers()) - { - users.add(user); - } - } - return users; - } + sender.sendMessage(tl("pWeatherReset", msg)); + } else { + if (!weatherAliases.containsKey(weatherType)) { + throw new NotEnoughArgumentsException(tl("pWeatherInvalidAlias")); + } - // Try to find the user with name = selector - User user = null; - final List matchedPlayers = server.matchPlayer(selector); - if (!matchedPlayers.isEmpty()) - { - user = ess.getUser(matchedPlayers.get(0)); - } + for (User user : users) { + user.getBase().setPlayerWeather(weatherAliases.get(weatherType)); + } + sender.sendMessage(tl("pWeatherSet", weatherType, msg.toString())); + } + } - if (user != null) - { - users.add(user); - } - // If that fails, Is the argument something like "*" or "all"? - else if (selector.equalsIgnoreCase("*") || selector.equalsIgnoreCase("all")) - { - for (User u : ess.getOnlineUsers()) - { - users.add(u); - } - } - // We failed to understand the world target... - else - { - throw new PlayerNotFoundException(); - } + /** + * Used to parse an argument of the type "users(s) selector" + */ + private Set getUsers(final Server server, final CommandSource sender, final String selector) throws Exception { + final Set users = new TreeSet(new UserNameComparator()); + // If there is no selector we want the sender itself. Or all users if sender isn't a user. + if (selector == null) { + if (sender.isPlayer()) { + final User user = ess.getUser(sender.getPlayer()); + users.add(user); + } else { + for (User user : ess.getOnlineUsers()) { + users.add(user); + } + } + return users; + } - return users; - } + // Try to find the user with name = selector + User 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 (User u : ess.getOnlineUsers()) { + users.add(u); + } + } + // We failed to understand the world target... + else { + throw new PlayerNotFoundException(); + } + + return users; + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandr.java b/Essentials/src/com/earth2me/essentials/commands/Commandr.java index b79d10f1e..2f2dd1318 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandr.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandr.java @@ -2,76 +2,63 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.Console; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.IReplyTo; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.FormatUtil; import org.bukkit.Server; +import static com.earth2me.essentials.I18n.tl; -public class Commandr extends EssentialsCommand -{ - public Commandr() - { - super("r"); - } - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } +public class Commandr extends EssentialsCommand { + public Commandr() { + super("r"); + } - String message = getFinalArg(args, 0); - IReplyTo replyTo; - String senderName; + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } - if (sender.isPlayer()) - { - User user = ess.getUser(sender.getPlayer()); - message = FormatUtil.formatMessage(user, "essentials.msg", message); - replyTo = user; - senderName = user.getDisplayName(); - } - else - { - message = FormatUtil.replaceFormat(message); - replyTo = Console.getConsoleReplyTo(); - senderName = Console.NAME; - } + String message = getFinalArg(args, 0); + IReplyTo replyTo; + String senderName; - final CommandSource target = replyTo.getReplyTo(); + if (sender.isPlayer()) { + User user = ess.getUser(sender.getPlayer()); + message = FormatUtil.formatMessage(user, "essentials.msg", message); + replyTo = user; + senderName = user.getDisplayName(); + } else { + message = FormatUtil.replaceFormat(message); + replyTo = Console.getConsoleReplyTo(); + senderName = Console.NAME; + } - if (target == null || (target.isPlayer() && !target.getPlayer().isOnline())) - { - throw new Exception(tl("foreverAlone")); - } + final CommandSource target = replyTo.getReplyTo(); - final String targetName = target.isPlayer() ? target.getPlayer().getDisplayName() : Console.NAME; + if (target == null || (target.isPlayer() && !target.getPlayer().isOnline())) { + throw new Exception(tl("foreverAlone")); + } - sender.sendMessage(tl("msgFormat", tl("me"), targetName, message)); - if (target.isPlayer()) - { - User player = ess.getUser(target.getPlayer()); - if (sender.isPlayer() && player.isIgnoredPlayer(ess.getUser(sender.getPlayer()))) - { - return; - } - } - target.sendMessage(tl("msgFormat", senderName, tl("me"), message)); - replyTo.setReplyTo(target); - if (target != sender) - { - if (target.isPlayer()) - { - ess.getUser(target.getPlayer()).setReplyTo(sender); - } - else - { - Console.getConsoleReplyTo().setReplyTo(sender); - } - } - } + final String targetName = target.isPlayer() ? target.getPlayer().getDisplayName() : Console.NAME; + + sender.sendMessage(tl("msgFormat", tl("me"), targetName, message)); + if (target.isPlayer()) { + User player = ess.getUser(target.getPlayer()); + if (sender.isPlayer() && player.isIgnoredPlayer(ess.getUser(sender.getPlayer()))) { + return; + } + } + target.sendMessage(tl("msgFormat", senderName, tl("me"), message)); + replyTo.setReplyTo(target); + if (target != sender) { + if (target.isPlayer()) { + ess.getUser(target.getPlayer()).setReplyTo(sender); + } else { + Console.getConsoleReplyTo().setReplyTo(sender); + } + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandrealname.java b/Essentials/src/com/earth2me/essentials/commands/Commandrealname.java index 55cdadbfb..4e4d1d67b 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandrealname.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandrealname.java @@ -1,48 +1,41 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.FormatUtil; -import java.util.Locale; import org.bukkit.Server; -import org.bukkit.entity.Player; + +import java.util.Locale; + +import static com.earth2me.essentials.I18n.tl; -public class Commandrealname extends EssentialsCommand -{ - public Commandrealname() - { - super("realname"); - } +public class Commandrealname extends EssentialsCommand { + public Commandrealname() { + super("realname"); + } - @Override - protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - final String whois = args[0].toLowerCase(Locale.ENGLISH); - boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished(); - boolean foundUser = false; - for (User u: ess.getOnlineUsers()) - { - if (skipHidden && u.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(u.getBase())) - { - continue; - } - u.setDisplayNick(); - final String displayName = FormatUtil.stripFormat(u.getDisplayName()).toLowerCase(Locale.ENGLISH); - if (displayName.contains(whois)) - { - foundUser = true; - sender.sendMessage(u.getDisplayName() + " " + tl("is") + " " + u.getName()); - } - } - if (!foundUser) - { - throw new PlayerNotFoundException(); - } - } + @Override + protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } + final String whois = args[0].toLowerCase(Locale.ENGLISH); + boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished(); + boolean foundUser = false; + for (User u : ess.getOnlineUsers()) { + if (skipHidden && u.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(u.getBase())) { + continue; + } + u.setDisplayNick(); + final String displayName = FormatUtil.stripFormat(u.getDisplayName()).toLowerCase(Locale.ENGLISH); + if (displayName.contains(whois)) { + foundUser = true; + sender.sendMessage(u.getDisplayName() + " " + tl("is") + " " + u.getName()); + } + } + if (!foundUser) { + throw new PlayerNotFoundException(); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandrecipe.java b/Essentials/src/com/earth2me/essentials/commands/Commandrecipe.java index ec4fa896f..5df59efc9 100755 --- a/Essentials/src/com/earth2me/essentials/commands/Commandrecipe.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandrecipe.java @@ -1,202 +1,161 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.NumberUtil; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; import org.bukkit.Material; import org.bukkit.Server; import org.bukkit.inventory.*; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; -public class Commandrecipe extends EssentialsCommand -{ - public Commandrecipe() - { - super("recipe"); - } +import static com.earth2me.essentials.I18n.tl; - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - final ItemStack itemType = ess.getItemDb().get(args[0]); - int recipeNo = 0; +public class Commandrecipe extends EssentialsCommand { + public Commandrecipe() { + super("recipe"); + } - if (args.length > 1) - { - if (NumberUtil.isInt(args[1])) - { - recipeNo = Integer.parseInt(args[1]) - 1; - } - else - { - throw new Exception(tl("invalidNumber")); - } - } + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } - final List recipesOfType = ess.getServer().getRecipesFor(itemType); - if (recipesOfType.size() < 1) - { - throw new Exception(tl("recipeNone", getMaterialName(itemType))); - } + final ItemStack itemType = ess.getItemDb().get(args[0]); + int recipeNo = 0; - if (recipeNo < 0 || recipeNo >= recipesOfType.size()) - { - throw new Exception(tl("recipeBadIndex")); - } + if (args.length > 1) { + if (NumberUtil.isInt(args[1])) { + recipeNo = Integer.parseInt(args[1]) - 1; + } else { + throw new Exception(tl("invalidNumber")); + } + } - final Recipe selectedRecipe = recipesOfType.get(recipeNo); - sender.sendMessage(tl("recipe", getMaterialName(itemType), recipeNo + 1, recipesOfType.size())); + final List recipesOfType = ess.getServer().getRecipesFor(itemType); + if (recipesOfType.size() < 1) { + throw new Exception(tl("recipeNone", getMaterialName(itemType))); + } - if (selectedRecipe instanceof FurnaceRecipe) - { - furnaceRecipe(sender, (FurnaceRecipe)selectedRecipe); - } - else if (selectedRecipe instanceof ShapedRecipe) - { - shapedRecipe(sender, (ShapedRecipe)selectedRecipe, sender.isPlayer()); - } - else if (selectedRecipe instanceof ShapelessRecipe) - { - if (recipesOfType.size() == 1 && itemType.getType() == Material.FIREWORK) - { - ShapelessRecipe shapelessRecipe = new ShapelessRecipe(itemType); - shapelessRecipe.addIngredient(Material.SULPHUR); - shapelessRecipe.addIngredient(Material.PAPER); - shapelessRecipe.addIngredient(Material.FIREWORK_CHARGE); - shapelessRecipe(sender, shapelessRecipe, sender.isPlayer()); - } - else - { - shapelessRecipe(sender, (ShapelessRecipe)selectedRecipe, sender.isPlayer()); - } - } + if (recipeNo < 0 || recipeNo >= recipesOfType.size()) { + throw new Exception(tl("recipeBadIndex")); + } - if (recipesOfType.size() > 1 && args.length == 1) - { - sender.sendMessage(tl("recipeMore", commandLabel, args[0], getMaterialName(itemType))); - } - } + final Recipe selectedRecipe = recipesOfType.get(recipeNo); + sender.sendMessage(tl("recipe", getMaterialName(itemType), recipeNo + 1, recipesOfType.size())); - public void furnaceRecipe(final CommandSource sender, final FurnaceRecipe recipe) - { - sender.sendMessage(tl("recipeFurnace", getMaterialName(recipe.getInput()))); - } + if (selectedRecipe instanceof FurnaceRecipe) { + furnaceRecipe(sender, (FurnaceRecipe) selectedRecipe); + } else if (selectedRecipe instanceof ShapedRecipe) { + shapedRecipe(sender, (ShapedRecipe) selectedRecipe, sender.isPlayer()); + } else if (selectedRecipe instanceof ShapelessRecipe) { + if (recipesOfType.size() == 1 && itemType.getType() == Material.FIREWORK) { + ShapelessRecipe shapelessRecipe = new ShapelessRecipe(itemType); + shapelessRecipe.addIngredient(Material.SULPHUR); + shapelessRecipe.addIngredient(Material.PAPER); + shapelessRecipe.addIngredient(Material.FIREWORK_CHARGE); + shapelessRecipe(sender, shapelessRecipe, sender.isPlayer()); + } else { + shapelessRecipe(sender, (ShapelessRecipe) selectedRecipe, sender.isPlayer()); + } + } - public void shapedRecipe(final CommandSource sender, final ShapedRecipe recipe, final boolean showWindow) - { - final Map recipeMap = recipe.getIngredientMap(); + if (recipesOfType.size() > 1 && args.length == 1) { + sender.sendMessage(tl("recipeMore", commandLabel, args[0], getMaterialName(itemType))); + } + } - if (showWindow) - { - final User user = ess.getUser(sender.getPlayer()); - user.getBase().closeInventory(); - user.setRecipeSee(true); - final InventoryView view = user.getBase().openWorkbench(null, true); - final String[] recipeShape = recipe.getShape(); - final Map ingredientMap = recipe.getIngredientMap(); - for (int j = 0; j < recipeShape.length; j++) - { - for (int k = 0; k < recipeShape[j].length(); k++) - { - final ItemStack item = ingredientMap.get(recipeShape[j].toCharArray()[k]); - if (item == null) - { - continue; - } - item.setAmount(0); - view.getTopInventory().setItem(j * 3 + k + 1, item); - } - } - } - else - { - final HashMap colorMap = new HashMap(); - int i = 1; - for (Character c : "abcdefghi".toCharArray()) - { - ItemStack item = recipeMap.get(c); - if (!colorMap.containsKey(item == null ? null : item.getType())) - { - colorMap.put(item == null ? null : item.getType(), String.valueOf(i++)); - } - } - final Material[][] materials = new Material[3][3]; - for (int j = 0; j < recipe.getShape().length; j++) - { - for (int k = 0; k < recipe.getShape()[j].length(); k++) - { - ItemStack item = recipe.getIngredientMap().get(recipe.getShape()[j].toCharArray()[k]); - materials[j][k] = item == null ? null : item.getType(); - } - } - sender.sendMessage(tl("recipeGrid", colorMap.get(materials[0][0]), colorMap.get(materials[0][1]), colorMap.get(materials[0][2]))); - sender.sendMessage(tl("recipeGrid", colorMap.get(materials[1][0]), colorMap.get(materials[1][1]), colorMap.get(materials[1][2]))); - sender.sendMessage(tl("recipeGrid", colorMap.get(materials[2][0]), colorMap.get(materials[2][1]), colorMap.get(materials[2][2]))); + public void furnaceRecipe(final CommandSource sender, final FurnaceRecipe recipe) { + sender.sendMessage(tl("recipeFurnace", getMaterialName(recipe.getInput()))); + } - StringBuilder s = new StringBuilder(); - for (Material items : colorMap.keySet().toArray(new Material[colorMap.size()])) - { - s.append(tl("recipeGridItem", colorMap.get(items), getMaterialName(items))); - } - sender.sendMessage(tl("recipeWhere", s.toString())); - } - } + public void shapedRecipe(final CommandSource sender, final ShapedRecipe recipe, final boolean showWindow) { + final Map recipeMap = recipe.getIngredientMap(); - public void shapelessRecipe(final CommandSource sender, final ShapelessRecipe recipe, final boolean showWindow) - { - final List ingredients = recipe.getIngredientList(); - if (showWindow) - { - final User user = ess.getUser(sender.getPlayer()); - user.setRecipeSee(true); - final InventoryView view = user.getBase().openWorkbench(null, true); - for (int i = 0; i < ingredients.size(); i++) - { - view.setItem(i + 1, ingredients.get(i)); - } + if (showWindow) { + final User user = ess.getUser(sender.getPlayer()); + user.getBase().closeInventory(); + user.setRecipeSee(true); + final InventoryView view = user.getBase().openWorkbench(null, true); + final String[] recipeShape = recipe.getShape(); + final Map ingredientMap = recipe.getIngredientMap(); + for (int j = 0; j < recipeShape.length; j++) { + for (int k = 0; k < recipeShape[j].length(); k++) { + final ItemStack item = ingredientMap.get(recipeShape[j].toCharArray()[k]); + if (item == null) { + continue; + } + item.setAmount(0); + view.getTopInventory().setItem(j * 3 + k + 1, item); + } + } + } else { + final HashMap colorMap = new HashMap(); + int i = 1; + for (Character c : "abcdefghi".toCharArray()) { + ItemStack item = recipeMap.get(c); + if (!colorMap.containsKey(item == null ? null : item.getType())) { + colorMap.put(item == null ? null : item.getType(), String.valueOf(i++)); + } + } + final Material[][] materials = new Material[3][3]; + for (int j = 0; j < recipe.getShape().length; j++) { + for (int k = 0; k < recipe.getShape()[j].length(); k++) { + ItemStack item = recipe.getIngredientMap().get(recipe.getShape()[j].toCharArray()[k]); + materials[j][k] = item == null ? null : item.getType(); + } + } + sender.sendMessage(tl("recipeGrid", colorMap.get(materials[0][0]), colorMap.get(materials[0][1]), colorMap.get(materials[0][2]))); + sender.sendMessage(tl("recipeGrid", colorMap.get(materials[1][0]), colorMap.get(materials[1][1]), colorMap.get(materials[1][2]))); + sender.sendMessage(tl("recipeGrid", colorMap.get(materials[2][0]), colorMap.get(materials[2][1]), colorMap.get(materials[2][2]))); - } - else - { - StringBuilder s = new StringBuilder(); - for (int i = 0; i < ingredients.size(); i++) - { - s.append(getMaterialName(ingredients.get(i))); - if (i != ingredients.size() - 1) - { - s.append(","); - } - s.append(" "); - } - sender.sendMessage(tl("recipeShapeless", s.toString())); - } - } + StringBuilder s = new StringBuilder(); + for (Material items : colorMap.keySet().toArray(new Material[colorMap.size()])) { + s.append(tl("recipeGridItem", colorMap.get(items), getMaterialName(items))); + } + sender.sendMessage(tl("recipeWhere", s.toString())); + } + } - public String getMaterialName(final ItemStack stack) - { - if (stack == null) - { - return tl("recipeNothing"); - } - return getMaterialName(stack.getType()); - } + public void shapelessRecipe(final CommandSource sender, final ShapelessRecipe recipe, final boolean showWindow) { + final List ingredients = recipe.getIngredientList(); + if (showWindow) { + final User user = ess.getUser(sender.getPlayer()); + user.setRecipeSee(true); + final InventoryView view = user.getBase().openWorkbench(null, true); + for (int i = 0; i < ingredients.size(); i++) { + view.setItem(i + 1, ingredients.get(i)); + } - public String getMaterialName(final Material type) - { - if (type == null) - { - return tl("recipeNothing"); - } - return type.toString().replace("_", " ").toLowerCase(Locale.ENGLISH); - } + } else { + StringBuilder s = new StringBuilder(); + for (int i = 0; i < ingredients.size(); i++) { + s.append(getMaterialName(ingredients.get(i))); + if (i != ingredients.size() - 1) { + s.append(","); + } + s.append(" "); + } + sender.sendMessage(tl("recipeShapeless", s.toString())); + } + } + + public String getMaterialName(final ItemStack stack) { + if (stack == null) { + return tl("recipeNothing"); + } + return getMaterialName(stack.getType()); + } + + public String getMaterialName(final Material type) { + if (type == null) { + return tl("recipeNothing"); + } + return type.toString().replace("_", " ").toLowerCase(Locale.ENGLISH); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandremove.java b/Essentials/src/com/earth2me/essentials/commands/Commandremove.java index ef9d3c6af..617d53087 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandremove.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandremove.java @@ -1,326 +1,267 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.Mob; import com.earth2me.essentials.User; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; import org.bukkit.Chunk; import org.bukkit.Server; import org.bukkit.World; import org.bukkit.entity.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +import static com.earth2me.essentials.I18n.tl; + // This could be rewritten in a simpler form if we made a mapping of all Entity names to their types (which would also provide possible mod support) -public class Commandremove extends EssentialsCommand -{ - public Commandremove() - { - super("remove"); - } +public class Commandremove extends EssentialsCommand { + public Commandremove() { + super("remove"); + } - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - World world = user.getWorld(); - int radius = 0; - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - if (args.length >= 2) - { - try - { - radius = Integer.parseInt(args[1]); - } - catch (NumberFormatException e) - { - world = ess.getWorld(args[1]); - } - } - if (args.length >= 3) - { - // This is to prevent breaking the old syntax - radius = 0; - world = ess.getWorld(args[2]); - } - parseCommand(server, user.getSource(), args, world, radius); + @Override + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + World world = user.getWorld(); + int radius = 0; + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } + if (args.length >= 2) { + try { + radius = Integer.parseInt(args[1]); + } catch (NumberFormatException e) { + world = ess.getWorld(args[1]); + } + } + if (args.length >= 3) { + // This is to prevent breaking the old syntax + radius = 0; + world = ess.getWorld(args[2]); + } + parseCommand(server, user.getSource(), args, world, radius); - } + } - @Override - protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 2) - { - throw new NotEnoughArgumentsException(); - } - World world = ess.getWorld(args[1]); - parseCommand(server, sender, args, world, 0); - } + @Override + protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 2) { + throw new NotEnoughArgumentsException(); + } + World world = ess.getWorld(args[1]); + parseCommand(server, sender, args, world, 0); + } - private void parseCommand(Server server, CommandSource sender, String[] args, World world, int radius) throws Exception - { - List types = new ArrayList(); - List customTypes = new ArrayList(); + private void parseCommand(Server server, CommandSource sender, String[] args, World world, int radius) throws Exception { + List types = new ArrayList(); + List customTypes = new ArrayList(); - if (world == null) - { - throw new Exception(tl("invalidWorld")); - } + if (world == null) { + throw new Exception(tl("invalidWorld")); + } - if (args[0].contentEquals("*") || args[0].contentEquals("all")) - { - types.add(0, "ALL"); - } - else - { - for (String entityType : args[0].split(",")) - { - ToRemove toRemove; - try - { - toRemove = ToRemove.valueOf(entityType.toUpperCase(Locale.ENGLISH)); - } - catch (Exception e) - { - try - { - toRemove = ToRemove.valueOf(entityType.concat("S").toUpperCase(Locale.ENGLISH)); - } - catch (Exception ee) - { - toRemove = ToRemove.CUSTOM; - customTypes.add(entityType); - } - } - types.add(toRemove.toString()); - } - } - removeHandler(sender, types, customTypes, world, radius); - } + if (args[0].contentEquals("*") || args[0].contentEquals("all")) { + types.add(0, "ALL"); + } else { + for (String entityType : args[0].split(",")) { + ToRemove toRemove; + try { + toRemove = ToRemove.valueOf(entityType.toUpperCase(Locale.ENGLISH)); + } catch (Exception e) { + try { + toRemove = ToRemove.valueOf(entityType.concat("S").toUpperCase(Locale.ENGLISH)); + } catch (Exception ee) { + toRemove = ToRemove.CUSTOM; + customTypes.add(entityType); + } + } + types.add(toRemove.toString()); + } + } + removeHandler(sender, types, customTypes, world, radius); + } - private void removeHandler(CommandSource sender, List types, List customTypes, World world, int radius) - { - int removed = 0; - if (radius > 0) - { - radius *= radius; - } + private void removeHandler(CommandSource sender, List types, List customTypes, World world, int radius) { + int removed = 0; + if (radius > 0) { + radius *= radius; + } - ArrayList removeTypes = new ArrayList(); - ArrayList customRemoveTypes = new ArrayList(); + ArrayList removeTypes = new ArrayList(); + ArrayList customRemoveTypes = new ArrayList(); - for (String s : types) - { - removeTypes.add(ToRemove.valueOf(s)); - } + for (String s : types) { + removeTypes.add(ToRemove.valueOf(s)); + } - boolean warnUser = false; + boolean warnUser = false; - for (String s : customTypes) - { - Mob mobType = Mob.fromName(s); - if (mobType == null) - { - warnUser = true; - } - else - { - customRemoveTypes.add(mobType); - } - } + for (String s : customTypes) { + Mob mobType = Mob.fromName(s); + if (mobType == null) { + warnUser = true; + } else { + customRemoveTypes.add(mobType); + } + } - if (warnUser) - { - sender.sendMessage(tl("invalidMob")); - } + if (warnUser) { + sender.sendMessage(tl("invalidMob")); + } - for (Chunk chunk : world.getLoadedChunks()) - { - for (Entity e : chunk.getEntities()) - { - if (radius > 0) - { - if (sender.getPlayer().getLocation().distanceSquared(e.getLocation()) > radius) - { - continue; - } - } - if (e instanceof HumanEntity) - { - continue; - } + for (Chunk chunk : world.getLoadedChunks()) { + for (Entity e : chunk.getEntities()) { + if (radius > 0) { + if (sender.getPlayer().getLocation().distanceSquared(e.getLocation()) > radius) { + continue; + } + } + if (e instanceof HumanEntity) { + continue; + } - for (ToRemove toRemove : removeTypes) - { + for (ToRemove toRemove : removeTypes) { - // We should skip any TAMED animals unless we are specifially targetting them. - if (e instanceof Tameable && ((Tameable)e).isTamed() - && !removeTypes.contains(ToRemove.TAMED)) - { - continue; - } + // We should skip any TAMED animals unless we are specifially targetting them. + if (e instanceof Tameable && ((Tameable) e).isTamed() && !removeTypes.contains(ToRemove.TAMED)) { + continue; + } - // We should skip any NAMED animals unless we are specifially targetting them. - if (e instanceof LivingEntity && ((LivingEntity)e).getCustomName() != null - && !removeTypes.contains(ToRemove.NAMED)) - { - continue; - } + // We should skip any NAMED animals unless we are specifially targetting them. + if (e instanceof LivingEntity && ((LivingEntity) e).getCustomName() != null && !removeTypes.contains(ToRemove.NAMED)) { + continue; + } - switch (toRemove) - { - case TAMED: - if (e instanceof Tameable && ((Tameable)e).isTamed()) - { - e.remove(); - removed++; - } - break; - case NAMED: - if (e instanceof LivingEntity && ((LivingEntity)e).getCustomName() != null) - { - e.remove(); - removed++; - } - break; - case DROPS: - if (e instanceof Item) - { - e.remove(); - removed++; - } - break; - case ARROWS: - if (e instanceof Projectile) - { - e.remove(); - removed++; - } - break; - case BOATS: - if (e instanceof Boat) - { - e.remove(); - removed++; - } - break; - case MINECARTS: - if (e instanceof Minecart) - { - e.remove(); - removed++; - } - break; - case XP: - if (e instanceof ExperienceOrb) - { - e.remove(); - removed++; - } - break; - case PAINTINGS: - if (e instanceof Painting) - { - e.remove(); - removed++; - } - break; - case ITEMFRAMES: - if (e instanceof ItemFrame) - { - e.remove(); - removed++; - } - break; - case ENDERCRYSTALS: - if (e instanceof EnderCrystal) - { - e.remove(); - removed++; - } - break; - case AMBIENT: - if (e instanceof Flying) - { - e.remove(); - removed++; - } - break; - case HOSTILE: - case MONSTERS: - if (e instanceof Monster || e instanceof ComplexLivingEntity || e instanceof Flying || e instanceof Slime) - { - e.remove(); - removed++; - } - break; - case PASSIVE: - case ANIMALS: - if (e instanceof Animals || e instanceof NPC || e instanceof Snowman || e instanceof WaterMob || e instanceof Ambient) - { - e.remove(); - removed++; - } - break; - case MOBS: - if (e instanceof Animals || e instanceof NPC || e instanceof Snowman || e instanceof WaterMob - || e instanceof Monster || e instanceof ComplexLivingEntity || e instanceof Flying || e instanceof Slime || e instanceof Ambient) - { - e.remove(); - removed++; - } - break; - case ENTITIES: - case ALL: - if (e instanceof Entity) - { - e.remove(); - removed++; - } - break; - case CUSTOM: - for (Mob type : customRemoveTypes) - { - if (e.getType() == type.getType()) - { - e.remove(); - removed++; - } - } - break; - } - } - } - } - sender.sendMessage(tl("removed", removed)); - } + switch (toRemove) { + case TAMED: + if (e instanceof Tameable && ((Tameable) e).isTamed()) { + e.remove(); + removed++; + } + break; + case NAMED: + if (e instanceof LivingEntity && ((LivingEntity) e).getCustomName() != null) { + e.remove(); + removed++; + } + break; + case DROPS: + if (e instanceof Item) { + e.remove(); + removed++; + } + break; + case ARROWS: + if (e instanceof Projectile) { + e.remove(); + removed++; + } + break; + case BOATS: + if (e instanceof Boat) { + e.remove(); + removed++; + } + break; + case MINECARTS: + if (e instanceof Minecart) { + e.remove(); + removed++; + } + break; + case XP: + if (e instanceof ExperienceOrb) { + e.remove(); + removed++; + } + break; + case PAINTINGS: + if (e instanceof Painting) { + e.remove(); + removed++; + } + break; + case ITEMFRAMES: + if (e instanceof ItemFrame) { + e.remove(); + removed++; + } + break; + case ENDERCRYSTALS: + if (e instanceof EnderCrystal) { + e.remove(); + removed++; + } + break; + case AMBIENT: + if (e instanceof Flying) { + e.remove(); + removed++; + } + break; + case HOSTILE: + case MONSTERS: + if (e instanceof Monster || e instanceof ComplexLivingEntity || e instanceof Flying || e instanceof Slime) { + e.remove(); + removed++; + } + break; + case PASSIVE: + case ANIMALS: + if (e instanceof Animals || e instanceof NPC || e instanceof Snowman || e instanceof WaterMob || e instanceof Ambient) { + e.remove(); + removed++; + } + break; + case MOBS: + if (e instanceof Animals || e instanceof NPC || e instanceof Snowman || e instanceof WaterMob || e instanceof Monster || e instanceof ComplexLivingEntity || e instanceof Flying || e instanceof Slime || e instanceof Ambient) { + e.remove(); + removed++; + } + break; + case ENTITIES: + case ALL: + if (e instanceof Entity) { + e.remove(); + removed++; + } + break; + case CUSTOM: + for (Mob type : customRemoveTypes) { + if (e.getType() == type.getType()) { + e.remove(); + removed++; + } + } + break; + } + } + } + } + sender.sendMessage(tl("removed", removed)); + } - private enum ToRemove - { - DROPS, - ARROWS, - BOATS, - MINECARTS, - XP, - PAINTINGS, - ITEMFRAMES, - ENDERCRYSTALS, - HOSTILE, - MONSTERS, - PASSIVE, - ANIMALS, - AMBIENT, - MOBS, - ENTITIES, - ALL, - CUSTOM, - TAMED, - NAMED - } + private enum ToRemove { + DROPS, + ARROWS, + BOATS, + MINECARTS, + XP, + PAINTINGS, + ITEMFRAMES, + ENDERCRYSTALS, + HOSTILE, + MONSTERS, + PASSIVE, + ANIMALS, + AMBIENT, + MOBS, + ENTITIES, + ALL, + CUSTOM, + TAMED, + NAMED + } } \ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandrepair.java b/Essentials/src/com/earth2me/essentials/commands/Commandrepair.java index f0b503d2d..601f7e983 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandrepair.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandrepair.java @@ -1,151 +1,119 @@ package com.earth2me.essentials.commands; -import com.earth2me.essentials.*; -import static com.earth2me.essentials.I18n.tl; +import com.earth2me.essentials.ChargeException; +import com.earth2me.essentials.Trade; +import com.earth2me.essentials.User; import com.earth2me.essentials.utils.StringUtil; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; import net.ess3.api.IUser; import org.bukkit.Material; import org.bukkit.Server; import org.bukkit.inventory.ItemStack; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; -public class Commandrepair extends EssentialsCommand -{ - public Commandrepair() - { - super("repair"); - } +import static com.earth2me.essentials.I18n.tl; - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1 || args[0].equalsIgnoreCase("hand") || !user.isAuthorized("essentials.repair.all")) - { - repairHand(user); - } - else if (args[0].equalsIgnoreCase("all")) - { - final Trade charge = new Trade("repair-all", ess); - charge.isAffordableFor(user); - repairAll(user); - charge.charge(user); - } - else - { - throw new NotEnoughArgumentsException(); - } - } - public void repairHand(User user) throws Exception - { - final ItemStack item = user.getBase().getItemInHand(); - if (item == null || item.getType().isBlock() || item.getDurability() == 0) - { - throw new Exception(tl("repairInvalidType")); - } +public class Commandrepair extends EssentialsCommand { + public Commandrepair() { + super("repair"); + } - if (!item.getEnchantments().isEmpty() - && !ess.getSettings().getRepairEnchanted() - && !user.isAuthorized("essentials.repair.enchanted")) - { - throw new Exception(tl("repairEnchanted")); - } + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1 || args[0].equalsIgnoreCase("hand") || !user.isAuthorized("essentials.repair.all")) { + repairHand(user); + } else if (args[0].equalsIgnoreCase("all")) { + final Trade charge = new Trade("repair-all", ess); + charge.isAffordableFor(user); + repairAll(user); + charge.charge(user); + } else { + throw new NotEnoughArgumentsException(); + } + } - final String itemName = item.getType().toString().toLowerCase(Locale.ENGLISH); - final Trade charge = new Trade("repair-" + itemName.replace('_', '-'), new Trade("repair-" + item.getTypeId(), new Trade("repair-item", ess), ess), ess); + public void repairHand(User user) throws Exception { + final ItemStack item = user.getBase().getItemInHand(); + if (item == null || item.getType().isBlock() || item.getDurability() == 0) { + throw new Exception(tl("repairInvalidType")); + } - charge.isAffordableFor(user); + if (!item.getEnchantments().isEmpty() && !ess.getSettings().getRepairEnchanted() && !user.isAuthorized("essentials.repair.enchanted")) { + throw new Exception(tl("repairEnchanted")); + } - repairItem(item); + final String itemName = item.getType().toString().toLowerCase(Locale.ENGLISH); + final Trade charge = new Trade("repair-" + itemName.replace('_', '-'), new Trade("repair-" + item.getTypeId(), new Trade("repair-item", ess), ess), ess); - charge.charge(user); - user.getBase().updateInventory(); - user.sendMessage(tl("repair", itemName.replace('_', ' '))); - } + charge.isAffordableFor(user); - public void repairAll(User user) throws Exception - { - final List repaired = new ArrayList(); - repairItems(user.getBase().getInventory().getContents(), user, repaired); + repairItem(item); - if (user.isAuthorized("essentials.repair.armor")) - { - repairItems(user.getBase().getInventory().getArmorContents(), user, repaired); - } - - user.getBase().updateInventory(); - if (repaired.isEmpty()) - { - throw new Exception(tl("repairNone")); - } - else - { - user.sendMessage(tl("repair", StringUtil.joinList(repaired))); - } - } + charge.charge(user); + user.getBase().updateInventory(); + user.sendMessage(tl("repair", itemName.replace('_', ' '))); + } - private void repairItem(final ItemStack item) throws Exception - { - final Material material = Material.getMaterial(item.getTypeId()); - if (material.isBlock() || material.getMaxDurability() < 1) - { - throw new Exception(tl("repairInvalidType")); - } + public void repairAll(User user) throws Exception { + final List repaired = new ArrayList(); + repairItems(user.getBase().getInventory().getContents(), user, repaired); - if (item.getDurability() == 0) - { - throw new Exception(tl("repairAlreadyFixed")); - } + if (user.isAuthorized("essentials.repair.armor")) { + repairItems(user.getBase().getInventory().getArmorContents(), user, repaired); + } - item.setDurability((short)0); - } + user.getBase().updateInventory(); + if (repaired.isEmpty()) { + throw new Exception(tl("repairNone")); + } else { + user.sendMessage(tl("repair", StringUtil.joinList(repaired))); + } + } - private void repairItems(final ItemStack[] items, final IUser user, final List repaired) - { - for (ItemStack item : items) - { - if (item == null || item.getType().isBlock() || item.getDurability() == 0) - { - continue; - } - final String itemName = item.getType().toString().toLowerCase(Locale.ENGLISH); - final Trade charge = new Trade("repair-" + itemName.replace('_', '-'), new Trade("repair-" + item.getTypeId(), new Trade("repair-item", ess), ess), ess); - try - { - charge.isAffordableFor(user); - } - catch (ChargeException ex) - { - user.sendMessage(ex.getMessage()); - continue; - } - if (!item.getEnchantments().isEmpty() - && !ess.getSettings().getRepairEnchanted() - && !user.isAuthorized("essentials.repair.enchanted")) - { - continue; - } + private void repairItem(final ItemStack item) throws Exception { + final Material material = Material.getMaterial(item.getTypeId()); + if (material.isBlock() || material.getMaxDurability() < 1) { + throw new Exception(tl("repairInvalidType")); + } - try - { - repairItem(item); - } - catch (Exception e) - { - continue; - } - try - { - charge.charge(user); - } - catch (ChargeException ex) - { - user.sendMessage(ex.getMessage()); - } - repaired.add(itemName.replace('_', ' ')); - } - } + if (item.getDurability() == 0) { + throw new Exception(tl("repairAlreadyFixed")); + } + + item.setDurability((short) 0); + } + + private void repairItems(final ItemStack[] items, final IUser user, final List repaired) { + for (ItemStack item : items) { + if (item == null || item.getType().isBlock() || item.getDurability() == 0) { + continue; + } + final String itemName = item.getType().toString().toLowerCase(Locale.ENGLISH); + final Trade charge = new Trade("repair-" + itemName.replace('_', '-'), new Trade("repair-" + item.getTypeId(), new Trade("repair-item", ess), ess), ess); + try { + charge.isAffordableFor(user); + } catch (ChargeException ex) { + user.sendMessage(ex.getMessage()); + continue; + } + if (!item.getEnchantments().isEmpty() && !ess.getSettings().getRepairEnchanted() && !user.isAuthorized("essentials.repair.enchanted")) { + 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 index f9a109a51..01a1af616 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandrules.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandrules.java @@ -8,24 +8,20 @@ import com.earth2me.essentials.textreader.TextPager; import org.bukkit.Server; -public class Commandrules extends EssentialsCommand -{ - public Commandrules() - { - super("rules"); - } +public class Commandrules extends EssentialsCommand { + public Commandrules() { + super("rules"); + } - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (sender.isPlayer()) - { - ess.getUser(sender.getPlayer()).setDisplayNick(); - } - - 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, commandLabel, sender); - } + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (sender.isPlayer()) { + ess.getUser(sender.getPlayer()).setDisplayNick(); + } + + 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, commandLabel, sender); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandseen.java b/Essentials/src/com/earth2me/essentials/commands/Commandseen.java index fd4ad69b1..dadd71e86 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandseen.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandseen.java @@ -1,237 +1,184 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import com.earth2me.essentials.UserMap; import com.earth2me.essentials.craftbukkit.BanLookup; import com.earth2me.essentials.utils.DateUtil; import com.earth2me.essentials.utils.FormatUtil; import com.earth2me.essentials.utils.StringUtil; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import org.bukkit.BanList; -import java.util.UUID; import org.bukkit.BanEntry; +import org.bukkit.BanList; import org.bukkit.Location; import org.bukkit.Server; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.UUID; -public class Commandseen extends EssentialsCommand -{ - public Commandseen() - { - super("seen"); - } +import static com.earth2me.essentials.I18n.tl; - @Override - protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - seen(server, sender, args, true, true, true); - } - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - seen(server, user.getSource(), args, user.isAuthorized("essentials.seen.banreason"), user.isAuthorized("essentials.seen.extra"), user.isAuthorized("essentials.seen.ipsearch")); - } +public class Commandseen extends EssentialsCommand { + public Commandseen() { + super("seen"); + } - protected void seen(final Server server, final CommandSource sender, final String[] args, final boolean showBan, final boolean extra, final boolean ipLookup) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - User player = ess.getOfflineUser(args[0]); - if (player == null) - { - if (ipLookup && FormatUtil.validIP(args[0])) - { - seenIP(server, sender, args[0]); - return; - } - else if (ess.getServer().getBanList(BanList.Type.IP).isBanned(args[0])) - { - sender.sendMessage(tl("isIpBanned", args[0])); - return; - } - else if (BanLookup.isBanned(ess, args[0])) - { - sender.sendMessage(tl("whoisBanned", showBan ? BanLookup.getBanEntry(ess, args[0]).getReason() : tl("true"))); - return; - } - else - { - try - { - player = getPlayer(server, sender, args, 0); - } - catch (NoSuchFieldException e) - { - throw new PlayerNotFoundException(); - } - } - } - if (player.getBase().isOnline() && canInteractWith(sender, player)) - { - seenOnline(server, sender, player, showBan, extra); - } - else - { - seenOffline(server, sender, player, showBan, extra); - } + @Override + protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + seen(server, sender, args, true, true, true); + } - } + @Override + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + seen(server, user.getSource(), args, user.isAuthorized("essentials.seen.banreason"), user.isAuthorized("essentials.seen.extra"), user.isAuthorized("essentials.seen.ipsearch")); + } - private void seenOnline(final Server server, final CommandSource sender, final User user, final boolean showBan, final boolean extra) throws Exception - { + protected void seen(final Server server, final CommandSource sender, final String[] args, final boolean showBan, final boolean extra, final boolean ipLookup) throws Exception { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } + User player = ess.getOfflineUser(args[0]); + if (player == null) { + if (ipLookup && FormatUtil.validIP(args[0])) { + seenIP(server, sender, args[0]); + return; + } else if (ess.getServer().getBanList(BanList.Type.IP).isBanned(args[0])) { + sender.sendMessage(tl("isIpBanned", args[0])); + return; + } else if (BanLookup.isBanned(ess, args[0])) { + sender.sendMessage(tl("whoisBanned", showBan ? BanLookup.getBanEntry(ess, args[0]).getReason() : tl("true"))); + return; + } else { + try { + player = getPlayer(server, sender, args, 0); + } catch (NoSuchFieldException e) { + throw new PlayerNotFoundException(); + } + } + } + if (player.getBase().isOnline() && canInteractWith(sender, player)) { + seenOnline(server, sender, player, showBan, extra); + } else { + seenOffline(server, sender, player, showBan, extra); + } - user.setDisplayNick(); - sender.sendMessage(tl("seenOnline", user.getDisplayName(), DateUtil.formatDateDiff(user.getLastLogin()))); + } - if (ess.getSettings().isDebug()) - { - ess.getLogger().info("UUID: " + user.getBase().getUniqueId().toString()); - } + private void seenOnline(final Server server, final CommandSource sender, final User user, final boolean showBan, final boolean extra) throws Exception { - List history = ess.getUserMap().getUserHistory(user.getBase().getUniqueId()); - if (history != null && history.size() > 1) - { - sender.sendMessage(tl("seenAccounts", StringUtil.joinListSkip(", ", user.getName(), history))); - } + user.setDisplayNick(); + sender.sendMessage(tl("seenOnline", user.getDisplayName(), DateUtil.formatDateDiff(user.getLastLogin()))); - if (user.isAfk()) - { - sender.sendMessage(tl("whoisAFK", tl("true"))); - } - if (user.isJailed()) - { - sender.sendMessage(tl("whoisJail", (user.getJailTimeout() > 0 - ? DateUtil.formatDateDiff(user.getJailTimeout()) - : tl("true")))); - } - if (user.isMuted()) - { - sender.sendMessage(tl("whoisMuted", (user.getMuteTimeout() > 0 - ? DateUtil.formatDateDiff(user.getMuteTimeout()) - : tl("true")))); - } - final String location = user.getGeoLocation(); - if (location != null && (!(sender.isPlayer()) || ess.getUser(sender.getPlayer()).isAuthorized("essentials.geoip.show"))) - { - sender.sendMessage(tl("whoisGeoLocation", location)); - } - if (extra) - { - sender.sendMessage(tl("whoisIPAddress", user.getBase().getAddress().getAddress().toString())); - } - } + if (ess.getSettings().isDebug()) { + ess.getLogger().info("UUID: " + user.getBase().getUniqueId().toString()); + } - private void seenOffline(final Server server, final CommandSource sender, User user, final boolean showBan, final boolean extra) throws Exception - { - user.setDisplayNick(); - if (user.getLastLogout() > 0) - { - sender.sendMessage(tl("seenOffline", user.getName(), DateUtil.formatDateDiff(user.getLastLogout()))); - } - else - { - sender.sendMessage(tl("userUnknown", user.getName())); - } + List history = ess.getUserMap().getUserHistory(user.getBase().getUniqueId()); + if (history != null && history.size() > 1) { + sender.sendMessage(tl("seenAccounts", StringUtil.joinListSkip(", ", user.getName(), history))); + } - if (ess.getSettings().isDebug()) - { - ess.getLogger().info("UUID: " + user.getBase().getUniqueId().toString()); - } + if (user.isAfk()) { + sender.sendMessage(tl("whoisAFK", tl("true"))); + } + if (user.isJailed()) { + sender.sendMessage(tl("whoisJail", (user.getJailTimeout() > 0 ? DateUtil.formatDateDiff(user.getJailTimeout()) : tl("true")))); + } + if (user.isMuted()) { + sender.sendMessage(tl("whoisMuted", (user.getMuteTimeout() > 0 ? DateUtil.formatDateDiff(user.getMuteTimeout()) : tl("true")))); + } + final String location = user.getGeoLocation(); + if (location != null && (!(sender.isPlayer()) || ess.getUser(sender.getPlayer()).isAuthorized("essentials.geoip.show"))) { + sender.sendMessage(tl("whoisGeoLocation", location)); + } + if (extra) { + sender.sendMessage(tl("whoisIPAddress", user.getBase().getAddress().getAddress().toString())); + } + } - List history = ess.getUserMap().getUserHistory(user.getBase().getUniqueId()); - if (history != null && history.size() > 1) - { - sender.sendMessage(tl("seenAccounts", StringUtil.joinListSkip(", ", user.getName(), history))); - } + private void seenOffline(final Server server, final CommandSource sender, User user, final boolean showBan, final boolean extra) throws Exception { + user.setDisplayNick(); + if (user.getLastLogout() > 0) { + sender.sendMessage(tl("seenOffline", user.getName(), DateUtil.formatDateDiff(user.getLastLogout()))); + } else { + sender.sendMessage(tl("userUnknown", user.getName())); + } - if (BanLookup.isBanned(ess, user)) - { - final BanEntry banEntry = BanLookup.getBanEntry(ess, user.getName()); - final String reason = showBan ? banEntry.getReason() : tl("true"); - sender.sendMessage(tl("whoisBanned", reason)); - if (banEntry.getExpiration() != null) - { - Date expiry = banEntry.getExpiration(); - String expireString = tl("now"); - if (expiry.after(new Date())) - { - expireString = DateUtil.formatDateDiff(expiry.getTime()); - } - sender.sendMessage(tl("whoisTempBanned", expireString)); - } - } + if (ess.getSettings().isDebug()) { + ess.getLogger().info("UUID: " + user.getBase().getUniqueId().toString()); + } - final String location = user.getGeoLocation(); - if (location != null && (!(sender.isPlayer()) || ess.getUser(sender.getPlayer()).isAuthorized("essentials.geoip.show"))) - { - sender.sendMessage(tl("whoisGeoLocation", location)); - } - if (extra) - { - if (!user.getLastLoginAddress().isEmpty()) - { - sender.sendMessage(tl("whoisIPAddress", user.getLastLoginAddress())); - } - final Location loc = user.getLogoutLocation(); - if (loc != null) - { - sender.sendMessage(tl("whoisLocation", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); - } - } - } + List history = ess.getUserMap().getUserHistory(user.getBase().getUniqueId()); + if (history != null && history.size() > 1) { + sender.sendMessage(tl("seenAccounts", StringUtil.joinListSkip(", ", user.getName(), history))); + } - private void seenIP(final Server server, final CommandSource sender, final String ipAddress) throws Exception - { - final UserMap userMap = ess.getUserMap(); + if (BanLookup.isBanned(ess, user)) { + final BanEntry banEntry = BanLookup.getBanEntry(ess, user.getName()); + final String reason = showBan ? banEntry.getReason() : tl("true"); + sender.sendMessage(tl("whoisBanned", reason)); + if (banEntry.getExpiration() != null) { + Date expiry = banEntry.getExpiration(); + String expireString = tl("now"); + if (expiry.after(new Date())) { + expireString = DateUtil.formatDateDiff(expiry.getTime()); + } + sender.sendMessage(tl("whoisTempBanned", expireString)); + } + } - if (ess.getServer().getBanList(BanList.Type.IP).isBanned(ipAddress)) - { - sender.sendMessage(tl("isIpBanned", ipAddress)); - } + final String location = user.getGeoLocation(); + if (location != null && (!(sender.isPlayer()) || ess.getUser(sender.getPlayer()).isAuthorized("essentials.geoip.show"))) { + sender.sendMessage(tl("whoisGeoLocation", location)); + } + if (extra) { + if (!user.getLastLoginAddress().isEmpty()) { + sender.sendMessage(tl("whoisIPAddress", user.getLastLoginAddress())); + } + final Location loc = user.getLogoutLocation(); + if (loc != null) { + sender.sendMessage(tl("whoisLocation", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); + } + } + } - sender.sendMessage(tl("runningPlayerMatch", ipAddress)); + private void seenIP(final Server server, final CommandSource sender, final String ipAddress) throws Exception { + final UserMap userMap = ess.getUserMap(); - ess.runTaskAsynchronously(new Runnable() - { - @Override - public void run() - { - final List matches = new ArrayList(); - for (final UUID u : userMap.getAllUniqueUsers()) - { - final User user = ess.getUserMap().getUser(u); - if (user == null) - { - continue; - } + if (ess.getServer().getBanList(BanList.Type.IP).isBanned(ipAddress)) { + sender.sendMessage(tl("isIpBanned", ipAddress)); + } - final String uIPAddress = user.getLastLoginAddress(); + sender.sendMessage(tl("runningPlayerMatch", ipAddress)); - if (!uIPAddress.isEmpty() && uIPAddress.equalsIgnoreCase(ipAddress)) - { - matches.add(user.getName()); - } - } + ess.runTaskAsynchronously(new Runnable() { + @Override + public void run() { + final List matches = new ArrayList(); + for (final UUID u : userMap.getAllUniqueUsers()) { + final User user = ess.getUserMap().getUser(u); + if (user == null) { + continue; + } - if (matches.size() > 0) - { - sender.sendMessage(tl("matchingIPAddress")); - sender.sendMessage(StringUtil.joinList(matches)); - } - else - { - sender.sendMessage(tl("noMatchingPlayers")); - } + final String uIPAddress = user.getLastLoginAddress(); - } - }); + if (!uIPAddress.isEmpty() && uIPAddress.equalsIgnoreCase(ipAddress)) { + matches.add(user.getName()); + } + } - } + if (matches.size() > 0) { + sender.sendMessage(tl("matchingIPAddress")); + sender.sendMessage(StringUtil.joinList(matches)); + } else { + sender.sendMessage(tl("noMatchingPlayers")); + } + + } + }); + + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsell.java b/Essentials/src/com/earth2me/essentials/commands/Commandsell.java index aa5eea125..5390e2b7f 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsell.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsell.java @@ -1,111 +1,93 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.Trade; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.NumberUtil; +import org.bukkit.Server; +import org.bukkit.inventory.ItemStack; + import java.math.BigDecimal; import java.util.List; import java.util.Locale; import java.util.logging.Level; -import org.bukkit.Server; -import org.bukkit.inventory.ItemStack; + +import static com.earth2me.essentials.I18n.tl; -public class Commandsell extends EssentialsCommand -{ - public Commandsell() - { - super("sell"); - } +public class Commandsell extends EssentialsCommand { + public Commandsell() { + super("sell"); + } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - BigDecimal totalWorth = BigDecimal.ZERO; - String type = ""; - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - List is = ess.getItemDb().getMatching(user, args); - int count = 0; + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + BigDecimal totalWorth = BigDecimal.ZERO; + String type = ""; + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } + List is = ess.getItemDb().getMatching(user, args); + int count = 0; - boolean isBulk = is.size() > 1; + boolean isBulk = is.size() > 1; - for (ItemStack stack : is) - { - try - { - if (stack.getAmount() > 0) - { - totalWorth = totalWorth.add(sellItem(user, stack, args, isBulk)); - stack = stack.clone(); - count++; - for (ItemStack zeroStack : is) - { - if (zeroStack.isSimilar(stack)) - { - zeroStack.setAmount(0); - } - } - } - } - catch (Exception e) - { - if (!isBulk) - { - throw e; - } - } - } - if (count != 1) - { - if (args[0].equalsIgnoreCase("blocks")) - { - user.sendMessage(tl("totalWorthBlocks", type, NumberUtil.displayCurrency(totalWorth, ess))); - } - else - { - user.sendMessage(tl("totalWorthAll", type, NumberUtil.displayCurrency(totalWorth, ess))); - } - } - } + for (ItemStack stack : is) { + try { + if (stack.getAmount() > 0) { + totalWorth = totalWorth.add(sellItem(user, stack, args, isBulk)); + stack = stack.clone(); + count++; + for (ItemStack zeroStack : is) { + if (zeroStack.isSimilar(stack)) { + zeroStack.setAmount(0); + } + } + } + } catch (Exception e) { + if (!isBulk) { + throw e; + } + } + } + if (count != 1) { + if (args[0].equalsIgnoreCase("blocks")) { + user.sendMessage(tl("totalWorthBlocks", type, NumberUtil.displayCurrency(totalWorth, ess))); + } else { + user.sendMessage(tl("totalWorthAll", type, NumberUtil.displayCurrency(totalWorth, ess))); + } + } + } - private BigDecimal sellItem(User user, ItemStack is, String[] args, boolean isBulkSell) throws Exception - { - int amount = ess.getWorth().getAmount(ess, user, is, args, isBulkSell); - BigDecimal worth = ess.getWorth().getPrice(is); + private BigDecimal sellItem(User user, ItemStack is, String[] args, boolean isBulkSell) throws Exception { + int amount = ess.getWorth().getAmount(ess, user, is, args, isBulkSell); + BigDecimal worth = ess.getWorth().getPrice(is); - if (worth == null) - { - throw new Exception(tl("itemCannotBeSold")); - } + if (worth == null) { + throw new Exception(tl("itemCannotBeSold")); + } - if (amount <= 0) - { - if (!isBulkSell) { - user.sendMessage(tl("itemSold", NumberUtil.displayCurrency(BigDecimal.ZERO, ess), BigDecimal.ZERO, is.getType().toString().toLowerCase(Locale.ENGLISH), NumberUtil.displayCurrency(worth, ess))); - } - return BigDecimal.ZERO; - } - - BigDecimal result = worth.multiply(BigDecimal.valueOf(amount)); + if (amount <= 0) { + if (!isBulkSell) { + user.sendMessage(tl("itemSold", NumberUtil.displayCurrency(BigDecimal.ZERO, ess), BigDecimal.ZERO, is.getType().toString().toLowerCase(Locale.ENGLISH), NumberUtil.displayCurrency(worth, ess))); + } + return BigDecimal.ZERO; + } - //TODO: Prices for Enchantments - final ItemStack ris = is.clone(); - ris.setAmount(amount); - if (!user.getBase().getInventory().containsAtLeast(ris, amount)) - { - // This should never happen. - throw new IllegalStateException("Trying to remove more items than are available."); - } - user.getBase().getInventory().removeItem(ris); - user.getBase().updateInventory(); - Trade.log("Command", "Sell", "Item", user.getName(), new Trade(ris, ess), user.getName(), new Trade(result, ess), user.getLocation(), ess); - user.giveMoney(result); - user.sendMessage(tl("itemSold", NumberUtil.displayCurrency(result, ess), amount, is.getType().toString().toLowerCase(Locale.ENGLISH), NumberUtil.displayCurrency(worth, ess))); - logger.log(Level.INFO, tl("itemSoldConsole", user.getDisplayName(), is.getType().toString().toLowerCase(Locale.ENGLISH), NumberUtil.displayCurrency(result, ess), amount, NumberUtil.displayCurrency(worth, ess))); - return result; - } + BigDecimal result = worth.multiply(BigDecimal.valueOf(amount)); + + //TODO: Prices for Enchantments + final ItemStack ris = is.clone(); + ris.setAmount(amount); + if (!user.getBase().getInventory().containsAtLeast(ris, amount)) { + // This should never happen. + throw new IllegalStateException("Trying to remove more items than are available."); + } + user.getBase().getInventory().removeItem(ris); + user.getBase().updateInventory(); + Trade.log("Command", "Sell", "Item", user.getName(), new Trade(ris, ess), user.getName(), new Trade(result, ess), user.getLocation(), ess); + user.giveMoney(result); + user.sendMessage(tl("itemSold", NumberUtil.displayCurrency(result, ess), amount, is.getType().toString().toLowerCase(Locale.ENGLISH), NumberUtil.displayCurrency(worth, ess))); + logger.log(Level.INFO, tl("itemSoldConsole", user.getDisplayName(), is.getType().toString().toLowerCase(Locale.ENGLISH), NumberUtil.displayCurrency(result, ess), amount, NumberUtil.displayCurrency(worth, ess))); + return result; + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsethome.java b/Essentials/src/com/earth2me/essentials/commands/Commandsethome.java index 866a15c1e..dd91bf612 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsethome.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsethome.java @@ -1,91 +1,75 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.LocationUtil; import com.earth2me.essentials.utils.NumberUtil; -import java.util.Locale; import org.bukkit.Location; import org.bukkit.Server; +import java.util.Locale; -public class Commandsethome extends EssentialsCommand -{ - public Commandsethome() - { - super("sethome"); - } +import static com.earth2me.essentials.I18n.tl; - @Override - public void run(final Server server, final User user, final String commandLabel, String[] args) throws Exception - { - User usersHome = user; - String name = "home"; - final Location location = user.getLocation(); - 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; - } +public class Commandsethome extends EssentialsCommand { + public Commandsethome() { + super("sethome"); + } - if (args.length < 2) - { - name = args[0].toLowerCase(Locale.ENGLISH); - } - else - { - name = args[1].toLowerCase(Locale.ENGLISH); - if (user.isAuthorized("essentials.sethome.others")) - { - usersHome = getPlayer(server, args[0], true, true); - if (usersHome == null) - { - throw new PlayerNotFoundException(); - } - } - } - } - if (checkHomeLimit(user, usersHome, name)) - { - name = "home"; - } - if ("bed".equals(name) || NumberUtil.isInt(name)) - { - throw new NoSuchFieldException(tl("invalidHomeName")); - } + @Override + public void run(final Server server, final User user, final String commandLabel, String[] args) throws Exception { + User usersHome = user; + String name = "home"; + final Location location = user.getLocation(); - if (!ess.getSettings().isTeleportSafetyEnabled() && LocationUtil.isBlockUnsafeForUser(usersHome, location.getWorld(), location.getBlockX(), location.getBlockY(), location.getBlockZ())) - { - throw new Exception(tl("unsafeTeleportDestination", location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ())); - } + 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; + } - usersHome.setHome(name, location); - user.sendMessage(tl("homeSet", user.getLocation().getWorld().getName(), user.getLocation().getBlockX(), user.getLocation().getBlockY(), user.getLocation().getBlockZ(), name)); + if (args.length < 2) { + name = args[0].toLowerCase(Locale.ENGLISH); + } else { + name = args[1].toLowerCase(Locale.ENGLISH); + if (user.isAuthorized("essentials.sethome.others")) { + usersHome = getPlayer(server, args[0], true, true); + if (usersHome == null) { + throw new PlayerNotFoundException(); + } + } + } + } + if (checkHomeLimit(user, usersHome, name)) { + name = "home"; + } + if ("bed".equals(name) || NumberUtil.isInt(name)) { + throw new NoSuchFieldException(tl("invalidHomeName")); + } - } + if (!ess.getSettings().isTeleportSafetyEnabled() && LocationUtil.isBlockUnsafeForUser(usersHome, location.getWorld(), location.getBlockX(), location.getBlockY(), location.getBlockZ())) { + throw new Exception(tl("unsafeTeleportDestination", location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ())); + } - private boolean checkHomeLimit(final User user, final User usersHome, String name) throws Exception - { - if (!user.isAuthorized("essentials.sethome.multiple.unlimited")) - { - int limit = ess.getSettings().getHomeLimit(user); - if (usersHome.getHomes().size() == limit && usersHome.getHomes().contains(name)) - { - return false; - } - if (usersHome.getHomes().size() >= limit) - { - throw new Exception(tl("maxHomes", ess.getSettings().getHomeLimit(user))); - } - if (limit == 1) - { - return true; - } - } - return false; - } + usersHome.setHome(name, location); + user.sendMessage(tl("homeSet", user.getLocation().getWorld().getName(), user.getLocation().getBlockX(), user.getLocation().getBlockY(), user.getLocation().getBlockZ(), name)); + + } + + private boolean checkHomeLimit(final User user, final User usersHome, String name) throws Exception { + if (!user.isAuthorized("essentials.sethome.multiple.unlimited")) { + int limit = ess.getSettings().getHomeLimit(user); + if (usersHome.getHomes().size() == limit && usersHome.getHomes().contains(name)) { + return false; + } + if (usersHome.getHomes().size() >= limit) { + throw new Exception(tl("maxHomes", ess.getSettings().getHomeLimit(user))); + } + if (limit == 1) { + return true; + } + } + return false; + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsetjail.java b/Essentials/src/com/earth2me/essentials/commands/Commandsetjail.java index 9cf89bfaf..dbf3059e5 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsetjail.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsetjail.java @@ -1,27 +1,24 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.StringUtil; import org.bukkit.Server; +import static com.earth2me.essentials.I18n.tl; -public class Commandsetjail extends EssentialsCommand -{ - public Commandsetjail() - { - super("setjail"); - } - @Override - public void run(final Server server, final User 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(tl("jailSet", StringUtil.sanitizeString(args[0]))); +public class Commandsetjail extends EssentialsCommand { + public Commandsetjail() { + super("setjail"); + } - } + @Override + public void run(final Server server, final User 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(tl("jailSet", StringUtil.sanitizeString(args[0]))); + + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsetwarp.java b/Essentials/src/com/earth2me/essentials/commands/Commandsetwarp.java index b0fa51caf..d3dc74f97 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsetwarp.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsetwarp.java @@ -1,6 +1,5 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import com.earth2me.essentials.api.IWarps; import com.earth2me.essentials.utils.NumberUtil; @@ -9,50 +8,39 @@ import net.ess3.api.InvalidWorldException; import org.bukkit.Location; import org.bukkit.Server; +import static com.earth2me.essentials.I18n.tl; -public class Commandsetwarp extends EssentialsCommand -{ - public Commandsetwarp() - { - super("setwarp"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } +public class Commandsetwarp extends EssentialsCommand { + public Commandsetwarp() { + super("setwarp"); + } - if (NumberUtil.isInt(args[0]) || args[0].isEmpty()) - { - throw new NoSuchFieldException(tl("invalidWarpName")); - } + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } - final Location loc = user.getLocation(); - final IWarps warps = ess.getWarps(); - Location warpLoc = null; + if (NumberUtil.isInt(args[0]) || args[0].isEmpty()) { + throw new NoSuchFieldException(tl("invalidWarpName")); + } - try - { - warpLoc = warps.getWarp(args[0]); - } - catch (WarpNotFoundException ex) - { - } - catch (InvalidWorldException ex) - { - } + final Location loc = user.getLocation(); + final IWarps warps = ess.getWarps(); + Location warpLoc = null; - if (warpLoc == null || user.isAuthorized("essentials.warp.overwrite." + StringUtil.safeString(args[0]))) - { - warps.setWarp(args[0], loc); - } - else - { - throw new Exception(tl("warpOverwrite")); - } - user.sendMessage(tl("warpSet", args[0])); - } + try { + warpLoc = warps.getWarp(args[0]); + } catch (WarpNotFoundException ex) { + } catch (InvalidWorldException ex) { + } + + if (warpLoc == null || user.isAuthorized("essentials.warp.overwrite." + StringUtil.safeString(args[0]))) { + warps.setWarp(args[0], loc); + } else { + throw new Exception(tl("warpOverwrite")); + } + user.sendMessage(tl("warpSet", args[0])); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsetworth.java b/Essentials/src/com/earth2me/essentials/commands/Commandsetworth.java index 3a0e6b5ea..d88b01695 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsetworth.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsetworth.java @@ -1,55 +1,47 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import org.bukkit.Server; import org.bukkit.inventory.ItemStack; +import static com.earth2me.essentials.I18n.tl; -public class Commandsetworth extends EssentialsCommand -{ - public Commandsetworth() - { - super("setworth"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } +public class Commandsetworth extends EssentialsCommand { + public Commandsetworth() { + super("setworth"); + } - ItemStack stack; - String price; + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } - if (args.length == 1) - { - stack = user.getBase().getInventory().getItemInHand(); - price = args[0]; - } - else - { - stack = ess.getItemDb().get(args[0]); - price = args[1]; - } + ItemStack stack; + String price; - ess.getWorth().setPrice(stack, Double.parseDouble(price)); - user.sendMessage(tl("worthSet")); - } + if (args.length == 1) { + stack = user.getBase().getInventory().getItemInHand(); + price = args[0]; + } else { + stack = ess.getItemDb().get(args[0]); + price = args[1]; + } - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 2) - { - throw new NotEnoughArgumentsException(); - } + ess.getWorth().setPrice(stack, Double.parseDouble(price)); + user.sendMessage(tl("worthSet")); + } - ItemStack stack = ess.getItemDb().get(args[0]); - ess.getWorth().setPrice(stack, Double.parseDouble(args[1])); - sender.sendMessage(tl("worthSet")); - } + @Override + public void run(final Server server, final CommandSource 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(tl("worthSet")); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandskull.java b/Essentials/src/com/earth2me/essentials/commands/Commandskull.java index 4f00e991f..8ccbd0853 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandskull.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandskull.java @@ -1,6 +1,5 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import com.earth2me.essentials.craftbukkit.InventoryWorkaround; import org.bukkit.Material; @@ -8,62 +7,55 @@ import org.bukkit.Server; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.SkullMeta; -public class Commandskull extends EssentialsCommand -{ - public Commandskull() - { - super("skull"); - } - - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - String owner; +import static com.earth2me.essentials.I18n.tl; - if (args.length > 0 && user.isAuthorized("essentials.skull.others")) { - if (!args[0].matches("^[A-Za-z0-9_]+$")) { - throw new IllegalArgumentException(tl("alphaNames")); - } - owner = args[0]; - } - else { - owner = user.getName(); - } +public class Commandskull extends EssentialsCommand { + public Commandskull() { + super("skull"); + } - ItemStack itemSkull = user.getBase().getItemInHand(); - SkullMeta metaSkull = null; - boolean spawn = false; + @Override + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + String owner; - if (itemSkull != null && itemSkull.getType() == Material.SKULL_ITEM && itemSkull.getDurability() == 3) { - metaSkull = (SkullMeta) itemSkull.getItemMeta(); - } - else if (user.isAuthorized("essentials.skull.spawn")) - { - itemSkull = new ItemStack(Material.SKULL_ITEM, 1, (byte) 3); - metaSkull = (SkullMeta) itemSkull.getItemMeta(); - spawn = true; - } - else { - throw new Exception(tl("invalidSkull")); - } + if (args.length > 0 && user.isAuthorized("essentials.skull.others")) { + if (!args[0].matches("^[A-Za-z0-9_]+$")) { + throw new IllegalArgumentException(tl("alphaNames")); + } + owner = args[0]; + } else { + owner = user.getName(); + } - if (metaSkull.hasOwner() && !user.isAuthorized("essentials.skull.modify")) - { - throw new Exception(tl("noPermissionSkull")); - } + ItemStack itemSkull = user.getBase().getItemInHand(); + SkullMeta metaSkull = null; + boolean spawn = false; - metaSkull.setDisplayName("§fSkull of " + owner); - metaSkull.setOwner(owner); + if (itemSkull != null && itemSkull.getType() == Material.SKULL_ITEM && itemSkull.getDurability() == 3) { + metaSkull = (SkullMeta) itemSkull.getItemMeta(); + } else if (user.isAuthorized("essentials.skull.spawn")) { + itemSkull = new ItemStack(Material.SKULL_ITEM, 1, (byte) 3); + metaSkull = (SkullMeta) itemSkull.getItemMeta(); + spawn = true; + } else { + throw new Exception(tl("invalidSkull")); + } - itemSkull.setItemMeta(metaSkull); + if (metaSkull.hasOwner() && !user.isAuthorized("essentials.skull.modify")) { + throw new Exception(tl("noPermissionSkull")); + } - if (spawn) { - InventoryWorkaround.addItems(user.getBase().getInventory(), itemSkull); - user.sendMessage(tl("givenSkull", owner)); - } - else { - user.sendMessage(tl("skullChanged", owner)); - } - } + metaSkull.setDisplayName("§fSkull of " + owner); + metaSkull.setOwner(owner); + + itemSkull.setItemMeta(metaSkull); + + if (spawn) { + InventoryWorkaround.addItems(user.getBase().getInventory(), itemSkull); + user.sendMessage(tl("givenSkull", owner)); + } else { + user.sendMessage(tl("skullChanged", owner)); + } + } } \ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsocialspy.java b/Essentials/src/com/earth2me/essentials/commands/Commandsocialspy.java index 8b2339637..53777483a 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsocialspy.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsocialspy.java @@ -1,64 +1,50 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import org.bukkit.Server; - -public class Commandsocialspy extends EssentialsToggleCommand -{ - public Commandsocialspy() - { - super("socialspy", "essentials.socialspy.others"); - } - - @Override - protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - toggleOtherPlayers(server, sender, args); - } - - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (args.length == 1) - { - Boolean toggle = matchToggleArgument(args[0]); - if (toggle == null && user.isAuthorized(othersPermission)) - { - toggleOtherPlayers(server, user.getSource(), args); - } - else - { - togglePlayer(user.getSource(), user, toggle); - } - } - else if (args.length == 2 && user.isAuthorized(othersPermission)) - { - toggleOtherPlayers(server, user.getSource(), args); - } - else - { - togglePlayer(user.getSource(), user, null); - } - } - - @Override - void togglePlayer(CommandSource sender, User user, Boolean enabled) throws NotEnoughArgumentsException - { - if (enabled == null) - { - enabled = !user.isSocialSpyEnabled(); - } - - user.setSocialSpyEnabled(enabled); +import static com.earth2me.essentials.I18n.tl; - user.sendMessage(tl("socialSpy", user.getDisplayName(), enabled ? tl("enabled") : tl("disabled"))); - if (!sender.isPlayer() || !sender.getPlayer().equals(user.getBase())) - { - sender.sendMessage(tl("socialSpy", user.getDisplayName(), enabled ? tl("enabled") : tl("disabled"))); - } - } +public class Commandsocialspy extends EssentialsToggleCommand { + public Commandsocialspy() { + super("socialspy", "essentials.socialspy.others"); + } + + @Override + protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + toggleOtherPlayers(server, sender, args); + } + + @Override + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (args.length == 1) { + Boolean toggle = matchToggleArgument(args[0]); + if (toggle == null && user.isAuthorized(othersPermission)) { + toggleOtherPlayers(server, user.getSource(), args); + } else { + togglePlayer(user.getSource(), user, toggle); + } + } else if (args.length == 2 && user.isAuthorized(othersPermission)) { + toggleOtherPlayers(server, user.getSource(), args); + } else { + togglePlayer(user.getSource(), user, null); + } + } + + @Override + void togglePlayer(CommandSource sender, User user, Boolean enabled) throws NotEnoughArgumentsException { + if (enabled == null) { + enabled = !user.isSocialSpyEnabled(); + } + + user.setSocialSpyEnabled(enabled); + + + user.sendMessage(tl("socialSpy", user.getDisplayName(), enabled ? tl("enabled") : tl("disabled"))); + if (!sender.isPlayer() || !sender.getPlayer().equals(user.getBase())) { + sender.sendMessage(tl("socialSpy", user.getDisplayName(), enabled ? tl("enabled") : tl("disabled"))); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandspawner.java b/Essentials/src/com/earth2me/essentials/commands/Commandspawner.java index 96c871c4c..33704ece1 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandspawner.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandspawner.java @@ -1,79 +1,68 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.Mob; import com.earth2me.essentials.Trade; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.LocationUtil; import com.earth2me.essentials.utils.NumberUtil; import com.earth2me.essentials.utils.StringUtil; -import java.util.Locale; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Server; import org.bukkit.block.CreatureSpawner; +import java.util.Locale; -public class Commandspawner extends EssentialsCommand -{ - public Commandspawner() - { - super("spawner"); - } +import static com.earth2me.essentials.I18n.tl; - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1 || args[0].length() < 2) - { - throw new NotEnoughArgumentsException(tl("mobsAvailable", StringUtil.joinList(Mob.getMobList()))); - } - final Location target = LocationUtil.getTarget(user.getBase()); - if (target == null || target.getBlock().getType() != Material.MOB_SPAWNER) - { - throw new Exception(tl("mobSpawnTarget")); - } +public class Commandspawner extends EssentialsCommand { + public Commandspawner() { + super("spawner"); + } - String name = args[0]; - int delay = 0; + @Override + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1 || args[0].length() < 2) { + throw new NotEnoughArgumentsException(tl("mobsAvailable", StringUtil.joinList(Mob.getMobList()))); + } - Mob mob = null; - mob = Mob.fromName(name); - if (mob == null) - { - throw new Exception(tl("invalidMob")); - } - if (ess.getSettings().getProtectPreventSpawn(mob.getType().toString().toLowerCase(Locale.ENGLISH))) - { - throw new Exception(tl("disabledToSpawnMob")); - } - if (!user.isAuthorized("essentials.spawner." + mob.name.toLowerCase(Locale.ENGLISH))) - { - throw new Exception(tl("noPermToSpawnMob")); - } - if (args.length > 1) - { - if (NumberUtil.isInt(args[1])) - { - delay = Integer.parseInt(args[1]); - } - } - final Trade charge = new Trade("spawner-" + mob.name.toLowerCase(Locale.ENGLISH), ess); - charge.isAffordableFor(user); - try - { - CreatureSpawner spawner = (CreatureSpawner)target.getBlock().getState(); - spawner.setSpawnedType(mob.getType()); - spawner.setDelay(delay); - spawner.update(); - } - catch (Throwable ex) - { - throw new Exception(tl("mobSpawnError"), ex); - } - charge.charge(user); - user.sendMessage(tl("setSpawner", mob.name)); + final Location target = LocationUtil.getTarget(user.getBase()); + if (target == null || target.getBlock().getType() != Material.MOB_SPAWNER) { + throw new Exception(tl("mobSpawnTarget")); + } - } + String name = args[0]; + int delay = 0; + + Mob mob = null; + mob = Mob.fromName(name); + if (mob == null) { + throw new Exception(tl("invalidMob")); + } + if (ess.getSettings().getProtectPreventSpawn(mob.getType().toString().toLowerCase(Locale.ENGLISH))) { + throw new Exception(tl("disabledToSpawnMob")); + } + if (!user.isAuthorized("essentials.spawner." + mob.name.toLowerCase(Locale.ENGLISH))) { + throw new Exception(tl("noPermToSpawnMob")); + } + if (args.length > 1) { + if (NumberUtil.isInt(args[1])) { + delay = Integer.parseInt(args[1]); + } + } + final Trade charge = new Trade("spawner-" + mob.name.toLowerCase(Locale.ENGLISH), ess); + charge.isAffordableFor(user); + try { + CreatureSpawner spawner = (CreatureSpawner) target.getBlock().getState(); + spawner.setSpawnedType(mob.getType()); + spawner.setDelay(delay); + spawner.update(); + } catch (Throwable ex) { + throw new Exception(tl("mobSpawnError"), ex); + } + charge.charge(user); + user.sendMessage(tl("setSpawner", mob.name)); + + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandspawnmob.java b/Essentials/src/com/earth2me/essentials/commands/Commandspawnmob.java index 2626d9dad..b8f3c4002 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandspawnmob.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandspawnmob.java @@ -1,69 +1,62 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.Mob; import com.earth2me.essentials.SpawnMob; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.StringUtil; -import java.util.List; import org.bukkit.Server; +import java.util.List; -public class Commandspawnmob extends EssentialsCommand -{ - public Commandspawnmob() - { - super("spawnmob"); - } - - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - final String mobList = SpawnMob.mobList(user); - throw new NotEnoughArgumentsException(tl("mobsAvailable", mobList)); - } - - List mobParts = SpawnMob.mobParts(args[0]); - List mobData = SpawnMob.mobData(args[0]); - - int mobCount = 1; - if (args.length >= 2) - { - mobCount = Integer.parseInt(args[1]); - } - - if (mobParts.size() > 1 && !user.isAuthorized("essentials.spawnmob.stack")) - { - throw new Exception(tl("cannotStackMob")); - } - - if (args.length >= 3) - { - final User target = getPlayer(ess.getServer(), user, args, 2); - SpawnMob.spawnmob(ess, server, user.getSource(), target, mobParts, mobData, mobCount); - return; - } - - SpawnMob.spawnmob(ess, server, user, mobParts, mobData, mobCount); - } - - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 3) - { - final String mobList = StringUtil.joinList(Mob.getMobList()); - throw new NotEnoughArgumentsException(tl("mobsAvailable", mobList)); - } - - List mobParts = SpawnMob.mobParts(args[0]); - List mobData = SpawnMob.mobData(args[0]); - int mobCount = Integer.parseInt(args[1]); - - final User target = getPlayer(ess.getServer(), args, 2, true, false); - SpawnMob.spawnmob(ess, server, sender, target, mobParts, mobData, mobCount); - } +import static com.earth2me.essentials.I18n.tl; + + +public class Commandspawnmob extends EssentialsCommand { + public Commandspawnmob() { + super("spawnmob"); + } + + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + final String mobList = SpawnMob.mobList(user); + throw new NotEnoughArgumentsException(tl("mobsAvailable", mobList)); + } + + List mobParts = SpawnMob.mobParts(args[0]); + List mobData = SpawnMob.mobData(args[0]); + + int mobCount = 1; + if (args.length >= 2) { + mobCount = Integer.parseInt(args[1]); + } + + if (mobParts.size() > 1 && !user.isAuthorized("essentials.spawnmob.stack")) { + throw new Exception(tl("cannotStackMob")); + } + + if (args.length >= 3) { + final User target = getPlayer(ess.getServer(), user, args, 2); + SpawnMob.spawnmob(ess, server, user.getSource(), target, mobParts, mobData, mobCount); + return; + } + + SpawnMob.spawnmob(ess, server, user, mobParts, mobData, mobCount); + } + + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 3) { + final String mobList = StringUtil.joinList(Mob.getMobList()); + throw new NotEnoughArgumentsException(tl("mobsAvailable", mobList)); + } + + List mobParts = SpawnMob.mobParts(args[0]); + List mobData = SpawnMob.mobData(args[0]); + int mobCount = Integer.parseInt(args[1]); + + final User target = getPlayer(ess.getServer(), args, 2, true, false); + SpawnMob.spawnmob(ess, server, sender, target, mobParts, mobData, mobCount); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandspeed.java b/Essentials/src/com/earth2me/essentials/commands/Commandspeed.java index 620f43956..00ce1c07b 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandspeed.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandspeed.java @@ -1,178 +1,136 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; -import java.util.List; import org.bukkit.Server; import org.bukkit.entity.Player; +import java.util.List; -public class Commandspeed extends EssentialsCommand -{ - public Commandspeed() - { - super("speed"); - } +import static com.earth2me.essentials.I18n.tl; - @Override - protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 2) - { - throw new NotEnoughArgumentsException(); - } - final boolean isFly = isFlyMode(args[0]); - final float speed = getMoveSpeed(args[1]); - speedOtherPlayers(server, sender, isFly, true, speed, args[2]); - } - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } +public class Commandspeed extends EssentialsCommand { + public Commandspeed() { + super("speed"); + } - boolean isFly; - float speed; - boolean isBypass = user.isAuthorized("essentials.speed.bypass"); - if (args.length == 1) - { - isFly = flyPermCheck(user, user.getBase().isFlying()); - speed = getMoveSpeed(args[0]); - } - else - { - isFly = flyPermCheck(user, isFlyMode(args[0])); - speed = getMoveSpeed(args[1]); - if (args.length > 2 && user.isAuthorized("essentials.speed.others")) - { - if (args[2].trim().length() < 2) - { - throw new PlayerNotFoundException(); - } - speedOtherPlayers(server, user.getSource(), isFly, isBypass, speed, args[2]); - return; - } - } + @Override + protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 2) { + throw new NotEnoughArgumentsException(); + } + final boolean isFly = isFlyMode(args[0]); + final float speed = getMoveSpeed(args[1]); + speedOtherPlayers(server, sender, isFly, true, speed, args[2]); + } - if (isFly) - { - user.getBase().setFlySpeed(getRealMoveSpeed(speed, isFly, isBypass)); - user.sendMessage(tl("moveSpeed", tl("flying"), speed, user.getDisplayName())); - } - else - { - user.getBase().setWalkSpeed(getRealMoveSpeed(speed, isFly, isBypass)); - user.sendMessage(tl("moveSpeed", tl("walking"), speed, user.getDisplayName())); - } - } + @Override + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } - private void speedOtherPlayers(final Server server, final CommandSource sender, final boolean isFly, final boolean isBypass, final float speed, final String name) throws PlayerNotFoundException - { - boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished(); - boolean foundUser = false; - final List matchedPlayers = server.matchPlayer(name); - for (Player matchPlayer : matchedPlayers) - { - final User player = ess.getUser(matchPlayer); - if (skipHidden && player.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(matchPlayer)) - { - continue; - } - foundUser = true; - if (isFly) - { - matchPlayer.setFlySpeed(getRealMoveSpeed(speed, isFly, isBypass)); - sender.sendMessage(tl("moveSpeed", tl("flying"), speed, matchPlayer.getDisplayName())); - } - else - { - matchPlayer.setWalkSpeed(getRealMoveSpeed(speed, isFly, isBypass)); - sender.sendMessage(tl("moveSpeed", tl("walking"), speed, matchPlayer.getDisplayName())); - } - } - if (!foundUser) - { - throw new PlayerNotFoundException(); - } - } + boolean isFly; + float speed; + boolean isBypass = user.isAuthorized("essentials.speed.bypass"); + if (args.length == 1) { + isFly = flyPermCheck(user, user.getBase().isFlying()); + speed = getMoveSpeed(args[0]); + } else { + isFly = flyPermCheck(user, isFlyMode(args[0])); + speed = getMoveSpeed(args[1]); + if (args.length > 2 && user.isAuthorized("essentials.speed.others")) { + if (args[2].trim().length() < 2) { + throw new PlayerNotFoundException(); + } + speedOtherPlayers(server, user.getSource(), isFly, isBypass, speed, args[2]); + return; + } + } - private Boolean flyPermCheck(User user, boolean input) throws Exception - { - boolean canFly = user.isAuthorized("essentials.speed.fly"); - boolean canWalk = user.isAuthorized("essentials.speed.walk"); - if (input && canFly || !input && canWalk || !canFly && !canWalk) - { - return input; - } - else if (canWalk) - { - return false; - } - return true; - } + if (isFly) { + user.getBase().setFlySpeed(getRealMoveSpeed(speed, isFly, isBypass)); + user.sendMessage(tl("moveSpeed", tl("flying"), speed, user.getDisplayName())); + } else { + user.getBase().setWalkSpeed(getRealMoveSpeed(speed, isFly, isBypass)); + user.sendMessage(tl("moveSpeed", tl("walking"), speed, user.getDisplayName())); + } + } - private boolean isFlyMode(final String modeString) throws NotEnoughArgumentsException - { - boolean isFlyMode; - if (modeString.contains("fly") || modeString.equalsIgnoreCase("f")) - { - isFlyMode = true; - } - else if (modeString.contains("walk") || modeString.contains("run") - || modeString.equalsIgnoreCase("w") || modeString.equalsIgnoreCase("r")) - { - isFlyMode = false; - } - else - { - throw new NotEnoughArgumentsException(); - } - return isFlyMode; - } + private void speedOtherPlayers(final Server server, final CommandSource sender, final boolean isFly, final boolean isBypass, final float speed, final String name) throws PlayerNotFoundException { + boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished(); + boolean foundUser = false; + final List matchedPlayers = server.matchPlayer(name); + for (Player matchPlayer : matchedPlayers) { + final User player = ess.getUser(matchPlayer); + if (skipHidden && player.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(matchPlayer)) { + continue; + } + foundUser = true; + if (isFly) { + matchPlayer.setFlySpeed(getRealMoveSpeed(speed, isFly, isBypass)); + sender.sendMessage(tl("moveSpeed", tl("flying"), speed, matchPlayer.getDisplayName())); + } else { + matchPlayer.setWalkSpeed(getRealMoveSpeed(speed, isFly, isBypass)); + sender.sendMessage(tl("moveSpeed", tl("walking"), speed, matchPlayer.getDisplayName())); + } + } + if (!foundUser) { + throw new PlayerNotFoundException(); + } + } - private float getMoveSpeed(final String moveSpeed) throws NotEnoughArgumentsException - { - float userSpeed; - try - { - userSpeed = Float.parseFloat(moveSpeed); - if (userSpeed > 10f) - { - userSpeed = 10f; - } - else if (userSpeed < 0.0001f) - { - userSpeed = 0.0001f; - } - } - catch (NumberFormatException e) - { - throw new NotEnoughArgumentsException(); - } - return userSpeed; - } + private Boolean flyPermCheck(User user, boolean input) throws Exception { + boolean canFly = user.isAuthorized("essentials.speed.fly"); + boolean canWalk = user.isAuthorized("essentials.speed.walk"); + if (input && canFly || !input && canWalk || !canFly && !canWalk) { + return input; + } else if (canWalk) { + return false; + } + return true; + } - private float getRealMoveSpeed(final float userSpeed, final boolean isFly, final boolean isBypass) - { - final float defaultSpeed = isFly ? 0.1f : 0.2f; - float maxSpeed = 1f; - if (!isBypass) - { - maxSpeed = (float)(isFly ? ess.getSettings().getMaxFlySpeed() : ess.getSettings().getMaxWalkSpeed()); - } + private boolean isFlyMode(final String modeString) throws NotEnoughArgumentsException { + boolean isFlyMode; + if (modeString.contains("fly") || modeString.equalsIgnoreCase("f")) { + isFlyMode = true; + } else if (modeString.contains("walk") || modeString.contains("run") || modeString.equalsIgnoreCase("w") || modeString.equalsIgnoreCase("r")) { + isFlyMode = false; + } else { + throw new NotEnoughArgumentsException(); + } + return isFlyMode; + } - if (userSpeed < 1f) - { - return defaultSpeed * userSpeed; - } - else - { - float ratio = ((userSpeed - 1) / 9) * (maxSpeed - defaultSpeed); - return ratio + defaultSpeed; - } - } + private float getMoveSpeed(final String moveSpeed) throws NotEnoughArgumentsException { + float userSpeed; + try { + userSpeed = Float.parseFloat(moveSpeed); + if (userSpeed > 10f) { + userSpeed = 10f; + } else if (userSpeed < 0.0001f) { + userSpeed = 0.0001f; + } + } catch (NumberFormatException e) { + throw new NotEnoughArgumentsException(); + } + return userSpeed; + } + + private float getRealMoveSpeed(final float userSpeed, final boolean isFly, final boolean isBypass) { + final float defaultSpeed = isFly ? 0.1f : 0.2f; + float maxSpeed = 1f; + if (!isBypass) { + maxSpeed = (float) (isFly ? ess.getSettings().getMaxFlySpeed() : ess.getSettings().getMaxWalkSpeed()); + } + + if (userSpeed < 1f) { + return defaultSpeed * userSpeed; + } else { + float ratio = ((userSpeed - 1) / 9) * (maxSpeed - defaultSpeed); + return ratio + defaultSpeed; + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsudo.java b/Essentials/src/com/earth2me/essentials/commands/Commandsudo.java index 9c9bb2df9..0d4614f78 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsudo.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsudo.java @@ -1,72 +1,61 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; -import java.util.Locale; -import java.util.logging.Logger; import org.bukkit.Server; +import java.util.Locale; +import java.util.logging.Logger; -public class Commandsudo extends EssentialsCommand -{ - public Commandsudo() - { - super("sudo"); - } - private static final Logger LOGGER = Logger.getLogger("Essentials"); +import static com.earth2me.essentials.I18n.tl; - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 2) - { - throw new NotEnoughArgumentsException(); - } - final User user = getPlayer(server, sender, args, 0); - if (args[1].toLowerCase(Locale.ENGLISH).startsWith("c:")) - { - if (user.isAuthorized("essentials.sudo.exempt") && sender.isPlayer()) - { - throw new Exception(tl("sudoExempt")); - } - user.getBase().chat(getFinalArg(args, 1).substring(2)); - return; - } - final String[] arguments = new String[args.length - 1]; - if (arguments.length > 0) - { - System.arraycopy(args, 1, arguments, 0, args.length - 1); - } +public class Commandsudo extends EssentialsCommand { + public Commandsudo() { + super("sudo"); + } - if (user.isAuthorized("essentials.sudo.exempt") && sender.isPlayer()) - { - throw new Exception(tl("sudoExempt")); - } + private static final Logger LOGGER = Logger.getLogger("Essentials"); - final String command = getFinalArg(arguments, 0); + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 2) { + throw new NotEnoughArgumentsException(); + } - sender.sendMessage(tl("sudoRun", user.getDisplayName(), command, "")); + final User user = getPlayer(server, sender, args, 0); + if (args[1].toLowerCase(Locale.ENGLISH).startsWith("c:")) { + if (user.isAuthorized("essentials.sudo.exempt") && sender.isPlayer()) { + throw new Exception(tl("sudoExempt")); + } + user.getBase().chat(getFinalArg(args, 1).substring(2)); + return; + } + final String[] arguments = new String[args.length - 1]; + if (arguments.length > 0) { + System.arraycopy(args, 1, arguments, 0, args.length - 1); + } - if (command != null && command.length() > 0) - { - class SudoCommandTask implements Runnable - { - @Override - public void run() - { - try - { - ess.getServer().dispatchCommand(user.getBase(), command); - } - catch (Exception e) - { - sender.sendMessage(tl("errorCallingCommand", command)); - } - } - } - ess.scheduleSyncDelayedTask(new SudoCommandTask()); - } - } + if (user.isAuthorized("essentials.sudo.exempt") && sender.isPlayer()) { + throw new Exception(tl("sudoExempt")); + } + + final String command = getFinalArg(arguments, 0); + + sender.sendMessage(tl("sudoRun", user.getDisplayName(), command, "")); + + if (command != null && command.length() > 0) { + class SudoCommandTask implements Runnable { + @Override + public void run() { + try { + ess.getServer().dispatchCommand(user.getBase(), command); + } catch (Exception e) { + sender.sendMessage(tl("errorCallingCommand", command)); + } + } + } + ess.scheduleSyncDelayedTask(new SudoCommandTask()); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsuicide.java b/Essentials/src/com/earth2me/essentials/commands/Commandsuicide.java index fdd9e0bbb..414ee7b72 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsuicide.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsuicide.java @@ -1,30 +1,27 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import org.bukkit.Server; import org.bukkit.event.entity.EntityDamageEvent; +import static com.earth2me.essentials.I18n.tl; -public class Commandsuicide extends EssentialsCommand -{ - public Commandsuicide() - { - super("suicide"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - EntityDamageEvent ede = new EntityDamageEvent(user.getBase(), EntityDamageEvent.DamageCause.SUICIDE, Short.MAX_VALUE); - server.getPluginManager().callEvent(ede); - user.getBase().damage(Short.MAX_VALUE); - if (user.getBase().getHealth() > 0) - { - user.getBase().setHealth(0); - } - user.sendMessage(tl("suicideMessage")); - user.setDisplayNick(); - ess.broadcastMessage(user, tl("suicideSuccess", user.getDisplayName())); - } +public class Commandsuicide extends EssentialsCommand { + public Commandsuicide() { + super("suicide"); + } + + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + EntityDamageEvent ede = new EntityDamageEvent(user.getBase(), EntityDamageEvent.DamageCause.SUICIDE, Short.MAX_VALUE); + server.getPluginManager().callEvent(ede); + user.getBase().damage(Short.MAX_VALUE); + if (user.getBase().getHealth() > 0) { + user.getBase().setHealth(0); + } + user.sendMessage(tl("suicideMessage")); + user.setDisplayNick(); + ess.broadcastMessage(user, tl("suicideSuccess", user.getDisplayName())); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtempban.java b/Essentials/src/com/earth2me/essentials/commands/Commandtempban.java index da8af1a13..f11df2ff6 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtempban.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtempban.java @@ -2,74 +2,63 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.Console; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.DateUtil; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.logging.Level; import org.bukkit.BanList; import org.bukkit.Server; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.logging.Level; -public class Commandtempban extends EssentialsCommand -{ - public Commandtempban() - { - super("tempban"); - } +import static com.earth2me.essentials.I18n.tl; - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 2) - { - throw new NotEnoughArgumentsException(); - } - final User user = getPlayer(server, args, 0, true, true); - if (!user.getBase().isOnline()) - { - if (sender.isPlayer() - && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.tempban.offline")) - { - sender.sendMessage(tl("tempbanExemptOffline")); - return; - } - } - else - { - if (user.isAuthorized("essentials.tempban.exempt") && sender.isPlayer()) - { - sender.sendMessage(tl("tempbanExempt")); - return; - } - } - final String time = getFinalArg(args, 1); - final long banTimestamp = DateUtil.parseDateDiff(time, true); - String banReason = DateUtil.removeTimePattern(time); - final long maxBanLength = ess.getSettings().getMaxTempban() * 1000; - if (maxBanLength > 0 && ((banTimestamp - GregorianCalendar.getInstance().getTimeInMillis()) > maxBanLength) - && sender.isPlayer() && !(ess.getUser(sender.getPlayer()).isAuthorized("essentials.tempban.unlimited"))) - { - sender.sendMessage(tl("oversizedTempban")); - throw new NoChargeException(); - } +public class Commandtempban extends EssentialsCommand { + public Commandtempban() { + super("tempban"); + } - if (banReason.length() < 2) - { - banReason = tl("defaultBanReason"); - } + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 2) { + throw new NotEnoughArgumentsException(); + } + final User user = getPlayer(server, args, 0, true, true); + if (!user.getBase().isOnline()) { + if (sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.tempban.offline")) { + sender.sendMessage(tl("tempbanExemptOffline")); + return; + } + } else { + if (user.isAuthorized("essentials.tempban.exempt") && sender.isPlayer()) { + sender.sendMessage(tl("tempbanExempt")); + return; + } + } + final String time = getFinalArg(args, 1); + final long banTimestamp = DateUtil.parseDateDiff(time, true); + String banReason = DateUtil.removeTimePattern(time); - final String senderName = sender.isPlayer() ? sender.getPlayer().getDisplayName() : Console.NAME; - ess.getServer().getBanList(BanList.Type.NAME).addBan(user.getName(), banReason, new Date(banTimestamp), senderName); - final String expiry = DateUtil.formatDateDiff(banTimestamp); + final long maxBanLength = ess.getSettings().getMaxTempban() * 1000; + if (maxBanLength > 0 && ((banTimestamp - GregorianCalendar.getInstance().getTimeInMillis()) > maxBanLength) && sender.isPlayer() && !(ess.getUser(sender.getPlayer()).isAuthorized("essentials.tempban.unlimited"))) { + sender.sendMessage(tl("oversizedTempban")); + throw new NoChargeException(); + } - final String banDisplay = tl("tempBanned", expiry, senderName, banReason); - user.getBase().kickPlayer(banDisplay); + if (banReason.length() < 2) { + banReason = tl("defaultBanReason"); + } - final String message = tl("playerTempBanned", senderName, user.getName(), expiry, banReason); - server.getLogger().log(Level.INFO, message); - ess.broadcastMessage("essentials.ban.notify", message); - } + final String senderName = sender.isPlayer() ? sender.getPlayer().getDisplayName() : Console.NAME; + ess.getServer().getBanList(BanList.Type.NAME).addBan(user.getName(), banReason, new Date(banTimestamp), senderName); + final String expiry = DateUtil.formatDateDiff(banTimestamp); + + final String banDisplay = tl("tempBanned", expiry, senderName, banReason); + user.getBase().kickPlayer(banDisplay); + + final String message = tl("playerTempBanned", senderName, user.getName(), expiry, banReason); + server.getLogger().log(Level.INFO, message); + ess.broadcastMessage("essentials.ban.notify", message); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandthunder.java b/Essentials/src/com/earth2me/essentials/commands/Commandthunder.java index 25deb69c0..7f8197599 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandthunder.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandthunder.java @@ -1,41 +1,35 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import org.bukkit.Server; import org.bukkit.World; +import static com.earth2me.essentials.I18n.tl; -public class Commandthunder extends EssentialsCommand -{ - public Commandthunder() - { - super("thunder"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } +public class Commandthunder extends EssentialsCommand { + public Commandthunder() { + super("thunder"); + } - final World world = user.getWorld(); - final boolean setThunder = args[0].equalsIgnoreCase("true"); - if (args.length > 1) - { + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } - world.setThundering(setThunder ? true : false); - world.setThunderDuration(Integer.parseInt(args[1]) * 20); - user.sendMessage(tl("thunderDuration", (setThunder ? tl("enabled") : tl("disabled")), Integer.parseInt(args[1]))); + final World world = user.getWorld(); + final boolean setThunder = args[0].equalsIgnoreCase("true"); + if (args.length > 1) { - } - else - { - world.setThundering(setThunder ? true : false); - user.sendMessage(tl("thunder", setThunder ? tl("enabled") : tl("disabled"))); - } + world.setThundering(setThunder ? true : false); + world.setThunderDuration(Integer.parseInt(args[1]) * 20); + user.sendMessage(tl("thunderDuration", (setThunder ? tl("enabled") : tl("disabled")), Integer.parseInt(args[1]))); - } + } else { + world.setThundering(setThunder ? true : false); + user.sendMessage(tl("thunder", setThunder ? tl("enabled") : tl("disabled"))); + } + + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtime.java b/Essentials/src/com/earth2me/essentials/commands/Commandtime.java index 2d456073a..1fb94d763 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtime.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtime.java @@ -1,187 +1,153 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.DescParseTickFormat; import com.earth2me.essentials.utils.NumberUtil; -import java.util.*; import org.bukkit.Server; import org.bukkit.World; +import java.util.*; -public class Commandtime extends EssentialsCommand -{ - public Commandtime() - { - super("time"); - } +import static com.earth2me.essentials.I18n.tl; - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - boolean add = false; - final List argList = new ArrayList(Arrays.asList(args)); - if (argList.remove("set") && !argList.isEmpty() && NumberUtil.isInt(argList.get(0))) - { - argList.set(0, argList.get(0) + "t"); - } - if (argList.remove("add") && !argList.isEmpty() && NumberUtil.isInt(argList.get(0))) - { - add = true; - argList.set(0, argList.get(0) + "t"); - } - 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(server, sender, worldSelector); - final String setTime; +public class Commandtime extends EssentialsCommand { + public Commandtime() { + super("time"); + } - // If no arguments we are reading the time - if (validArgs.length == 0) - { - if (commandLabel.equalsIgnoreCase("day") || commandLabel.equalsIgnoreCase("eday")) - { - setTime = "day"; - } - else if (commandLabel.equalsIgnoreCase("night") || commandLabel.equalsIgnoreCase("enight")) - { - setTime = "night"; - } - else - { - getWorldsTime(sender, worlds); - throw new NoChargeException(); - } - } - else - { - setTime = validArgs[0]; - } + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + boolean add = false; + final List argList = new ArrayList(Arrays.asList(args)); + if (argList.remove("set") && !argList.isEmpty() && NumberUtil.isInt(argList.get(0))) { + argList.set(0, argList.get(0) + "t"); + } + if (argList.remove("add") && !argList.isEmpty() && NumberUtil.isInt(argList.get(0))) { + add = true; + argList.set(0, argList.get(0) + "t"); + } + final String[] validArgs = argList.toArray(new String[0]); - final User user = ess.getUser(sender.getPlayer()); - if (user != null && !user.isAuthorized("essentials.time.set")) - { - throw new Exception(tl("timeSetPermission")); - } + // Which World(s) are we interested in? + String worldSelector = null; + if (validArgs.length == 2) { + worldSelector = validArgs[1]; + } + final Set worlds = getWorlds(server, sender, worldSelector); + final String setTime; - // Parse the target time int ticks from args[0] - long ticks; - try - { - ticks = DescParseTickFormat.parse(setTime); - } - catch (NumberFormatException e) - { - throw new NotEnoughArgumentsException(e); - } + // If no arguments we are reading the time + if (validArgs.length == 0) { + if (commandLabel.equalsIgnoreCase("day") || commandLabel.equalsIgnoreCase("eday")) { + setTime = "day"; + } else if (commandLabel.equalsIgnoreCase("night") || commandLabel.equalsIgnoreCase("enight")) { + setTime = "night"; + } else { + getWorldsTime(sender, worlds); + throw new NoChargeException(); + } + } else { + setTime = validArgs[0]; + } - setWorldsTime(sender, worlds, ticks, add); - } + final User user = ess.getUser(sender.getPlayer()); + if (user != null && !user.isAuthorized("essentials.time.set")) { + throw new Exception(tl("timeSetPermission")); + } - /** - * Used to get the time and inform - */ - private void getWorldsTime(final CommandSource sender, final Collection worlds) - { - if (worlds.size() == 1) - { - final Iterator iter = worlds.iterator(); - sender.sendMessage(DescParseTickFormat.format(iter.next().getTime())); - return; - } + // Parse the target time int ticks from args[0] + long ticks; + try { + ticks = DescParseTickFormat.parse(setTime); + } catch (NumberFormatException e) { + throw new NotEnoughArgumentsException(e); + } - for (World world : worlds) - { - sender.sendMessage(tl("timeWorldCurrent", world.getName(), DescParseTickFormat.format(world.getTime()))); - } - } + setWorldsTime(sender, worlds, ticks, add); + } - /** - * Used to set the time and inform of the change - */ - private void setWorldsTime(final CommandSource sender, final Collection worlds, final long ticks, final boolean add) - { - // Update the time - for (World world : worlds) - { - long time = world.getTime(); - if (!add) - { - time -= time % 24000; - } - world.setTime(time + (add ? 0 : 24000) + ticks); - } + /** + * Used to get the time and inform + */ + private void getWorldsTime(final CommandSource sender, final Collection worlds) { + if (worlds.size() == 1) { + final Iterator iter = worlds.iterator(); + sender.sendMessage(DescParseTickFormat.format(iter.next().getTime())); + return; + } - final StringBuilder output = new StringBuilder(); - for (World world : worlds) - { - if (output.length() > 0) - { - output.append(", "); - } + for (World world : worlds) { + sender.sendMessage(tl("timeWorldCurrent", world.getName(), DescParseTickFormat.format(world.getTime()))); + } + } - output.append(world.getName()); - } + /** + * Used to set the time and inform of the change + */ + private void setWorldsTime(final CommandSource sender, final Collection worlds, final long ticks, final boolean add) { + // Update the time + for (World world : worlds) { + long time = world.getTime(); + if (!add) { + time -= time % 24000; + } + world.setTime(time + (add ? 0 : 24000) + ticks); + } - sender.sendMessage(tl("timeWorldSet", DescParseTickFormat.format(ticks), output.toString())); - } + final StringBuilder output = new StringBuilder(); + for (World world : worlds) { + if (output.length() > 0) { + output.append(", "); + } - /** - * Used to parse an argument of the type "world(s) selector" - */ - private Set getWorlds(final Server server, final CommandSource sender, final String selector) throws Exception - { - final Set worlds = new TreeSet(new WorldNameComparator()); + output.append(world.getName()); + } - // 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) - { - if (sender.isPlayer()) - { + sender.sendMessage(tl("timeWorldSet", DescParseTickFormat.format(ticks), output.toString())); + } - final User user = ess.getUser(sender.getPlayer()); - worlds.add(user.getWorld()); - } - else - { - worlds.addAll(server.getWorlds()); - } - return worlds; - } + /** + * Used to parse an argument of the type "world(s) selector" + */ + private Set getWorlds(final Server server, final CommandSource sender, final String selector) throws Exception { + final Set worlds = new TreeSet(new WorldNameComparator()); - // 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(tl("invalidWorld")); - } + // 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) { + if (sender.isPlayer()) { - return worlds; - } + final User user = ess.getUser(sender.getPlayer()); + worlds.add(user.getWorld()); + } else { + worlds.addAll(server.getWorlds()); + } + 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(tl("invalidWorld")); + } + + return worlds; + } } -class WorldNameComparator implements Comparator -{ - @Override - public int compare(final World a, final World b) - { - return a.getName().compareTo(b.getName()); - } +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 index 8d67a21d0..481744348 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtogglejail.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtogglejail.java @@ -1,104 +1,83 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.DateUtil; import org.bukkit.Server; +import static com.earth2me.essentials.I18n.tl; -public class Commandtogglejail extends EssentialsCommand -{ - public Commandtogglejail() - { - super("togglejail"); - } - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } +public class Commandtogglejail extends EssentialsCommand { + public Commandtogglejail() { + super("togglejail"); + } - final User player = getPlayer(server, args, 0, true, true); + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } - if (args.length >= 2 && !player.isJailed()) - { - if (!player.getBase().isOnline()) - { - if (sender.isPlayer() - && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.togglejail.offline")) - { - sender.sendMessage(tl("mayNotJailOffline")); - return; - } - } - else - { - if (player.isAuthorized("essentials.jail.exempt")) - { - sender.sendMessage(tl("mayNotJail")); - return; - } - } - if (player.getBase().isOnline()) - { - ess.getJails().sendToJail(player, args[1]); - } - else - { - // Check if jail exists - ess.getJails().getJail(args[1]); - } - player.setJailed(true); - player.sendMessage(tl("userJailed")); - player.setJail(null); - player.setJail(args[1]); - long timeDiff = 0; - if (args.length > 2) - { - final String time = getFinalArg(args, 2); - timeDiff = DateUtil.parseDateDiff(time, true); - player.setJailTimeout(timeDiff); - } - sender.sendMessage((timeDiff > 0 - ? tl("playerJailedFor", player.getName(), DateUtil.formatDateDiff(timeDiff)) - : tl("playerJailed", player.getName()))); - return; - } + final User player = getPlayer(server, args, 0, true, true); - if (args.length >= 2 && player.isJailed() && !args[1].equalsIgnoreCase(player.getJail())) - { - sender.sendMessage(tl("jailAlreadyIncarcerated", player.getJail())); - return; - } + if (args.length >= 2 && !player.isJailed()) { + if (!player.getBase().isOnline()) { + if (sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.togglejail.offline")) { + sender.sendMessage(tl("mayNotJailOffline")); + return; + } + } else { + if (player.isAuthorized("essentials.jail.exempt")) { + sender.sendMessage(tl("mayNotJail")); + return; + } + } + if (player.getBase().isOnline()) { + ess.getJails().sendToJail(player, args[1]); + } else { + // Check if jail exists + ess.getJails().getJail(args[1]); + } + player.setJailed(true); + player.sendMessage(tl("userJailed")); + player.setJail(null); + player.setJail(args[1]); + long timeDiff = 0; + if (args.length > 2) { + final String time = getFinalArg(args, 2); + timeDiff = DateUtil.parseDateDiff(time, true); + player.setJailTimeout(timeDiff); + } + sender.sendMessage((timeDiff > 0 ? tl("playerJailedFor", player.getName(), DateUtil.formatDateDiff(timeDiff)) : tl("playerJailed", player.getName()))); + return; + } - if (args.length >= 2 && player.isJailed() && args[1].equalsIgnoreCase(player.getJail())) - { - final String time = getFinalArg(args, 2); - final long timeDiff = DateUtil.parseDateDiff(time, true); - player.setJailTimeout(timeDiff); - sender.sendMessage(tl("jailSentenceExtended", DateUtil.formatDateDiff(timeDiff))); - return; - } + if (args.length >= 2 && player.isJailed() && !args[1].equalsIgnoreCase(player.getJail())) { + sender.sendMessage(tl("jailAlreadyIncarcerated", player.getJail())); + return; + } - if (args.length == 1 || (args.length == 2 && args[1].equalsIgnoreCase(player.getJail()))) - { - if (!player.isJailed()) - { - throw new NotEnoughArgumentsException(); - } - player.setJailed(false); - player.setJailTimeout(0); - player.sendMessage(tl("jailReleasedPlayerNotify")); - player.setJail(null); - if (player.getBase().isOnline()) - { - player.getTeleport().back(); - } - sender.sendMessage(tl("jailReleased", player.getName())); - } - } + if (args.length >= 2 && player.isJailed() && args[1].equalsIgnoreCase(player.getJail())) { + final String time = getFinalArg(args, 2); + final long timeDiff = DateUtil.parseDateDiff(time, true); + player.setJailTimeout(timeDiff); + sender.sendMessage(tl("jailSentenceExtended", DateUtil.formatDateDiff(timeDiff))); + return; + } + + if (args.length == 1 || (args.length == 2 && args[1].equalsIgnoreCase(player.getJail()))) { + if (!player.isJailed()) { + throw new NotEnoughArgumentsException(); + } + player.setJailed(false); + player.setJailTimeout(0); + player.sendMessage(tl("jailReleasedPlayerNotify")); + player.setJail(null); + if (player.getBase().isOnline()) { + player.getTeleport().back(); + } + sender.sendMessage(tl("jailReleased", player.getName())); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtop.java b/Essentials/src/com/earth2me/essentials/commands/Commandtop.java index d41646f2d..6b60d2de6 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtop.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtop.java @@ -1,6 +1,5 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.Trade; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.LocationUtil; @@ -8,24 +7,23 @@ import org.bukkit.Location; import org.bukkit.Server; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; +import static com.earth2me.essentials.I18n.tl; -public class Commandtop extends EssentialsCommand -{ - public Commandtop() - { - super("top"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - final int topX = user.getLocation().getBlockX(); - final int topZ = user.getLocation().getBlockZ(); - final float pitch = user.getLocation().getPitch(); - final float yaw = user.getLocation().getYaw(); - final Location loc = LocationUtil.getSafeDestination(new Location(user.getWorld(), topX, user.getWorld().getMaxHeight(), topZ, yaw, pitch)); - user.getTeleport().teleport(loc, new Trade(this.getName(), ess), TeleportCause.COMMAND); - user.sendMessage(tl("teleportTop", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); - - } +public class Commandtop extends EssentialsCommand { + public Commandtop() { + super("top"); + } + + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + final int topX = user.getLocation().getBlockX(); + final int topZ = user.getLocation().getBlockZ(); + final float pitch = user.getLocation().getPitch(); + final float yaw = user.getLocation().getYaw(); + final Location loc = LocationUtil.getSafeDestination(new Location(user.getWorld(), topX, user.getWorld().getMaxHeight(), topZ, yaw, pitch)); + user.getTeleport().teleport(loc, new Trade(this.getName(), ess), TeleportCause.COMMAND); + user.sendMessage(tl("teleportTop", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); + + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtp.java b/Essentials/src/com/earth2me/essentials/commands/Commandtp.java index ee3938804..36bc8ec63 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtp.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtp.java @@ -2,145 +2,120 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.Console; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.Trade; import com.earth2me.essentials.User; import org.bukkit.Location; import org.bukkit.Server; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; +import static com.earth2me.essentials.I18n.tl; -public class Commandtp extends EssentialsCommand -{ - public Commandtp() - { - super("tp"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - switch (args.length) - { - case 0: - throw new NotEnoughArgumentsException(); +public class Commandtp extends EssentialsCommand { + public Commandtp() { + super("tp"); + } - case 1: - final User player = getPlayer(server, user, args, 0); - if (!player.isTeleportEnabled()) - { - throw new Exception(tl("teleportDisabled", player.getDisplayName())); - } - if (user.getWorld() != player.getWorld() && ess.getSettings().isWorldTeleportPermissions() - && !user.isAuthorized("essentials.worlds." + player.getWorld().getName())) - { - throw new Exception(tl("noPerm", "essentials.worlds." + player.getWorld().getName())); - } - final Trade charge = new Trade(this.getName(), ess); - charge.isAffordableFor(user); - user.getTeleport().teleport(player.getBase(), charge, TeleportCause.COMMAND); - throw new NoChargeException(); - case 3: - if (!user.isAuthorized("essentials.tp.position")) - { - throw new Exception(tl("noPerm", "essentials.tp.position")); - } - final double x2 = args[0].startsWith("~") ? user.getLocation().getX() + Integer.parseInt(args[0].substring(1)) : Integer.parseInt(args[0]); - final double y2 = args[1].startsWith("~") ? user.getLocation().getY() + Integer.parseInt(args[1].substring(1)) : Integer.parseInt(args[1]); - final double z2 = args[2].startsWith("~") ? user.getLocation().getZ() + Integer.parseInt(args[2].substring(1)) : Integer.parseInt(args[2]); - if (x2 > 30000000 || y2 > 30000000 || z2 > 30000000 || x2 < -30000000 || y2 < -30000000 || z2 < -30000000) - { - throw new NotEnoughArgumentsException(tl("teleportInvalidLocation")); - } - final Location locpos = new Location(user.getWorld(), x2, y2, z2, user.getLocation().getYaw(), user.getLocation().getPitch()); - user.getTeleport().now(locpos, false, TeleportCause.COMMAND); - user.sendMessage(tl("teleporting", locpos.getWorld().getName(), locpos.getBlockX(), locpos.getBlockY(), locpos.getBlockZ())); - break; - case 4: - if (!user.isAuthorized("essentials.tp.others")) - { - throw new Exception(tl("noPerm", "essentials.tp.others")); - } - if (!user.isAuthorized("essentials.tp.position")) - { - throw new Exception(tl("noPerm", "essentials.tp.position")); - } - final User target2 = getPlayer(server, user, args, 0); - final double x = args[1].startsWith("~") ? target2.getLocation().getX() + Integer.parseInt(args[1].substring(1)) : Integer.parseInt(args[1]); - final double y = args[2].startsWith("~") ? target2.getLocation().getY() + Integer.parseInt(args[2].substring(1)) : Integer.parseInt(args[2]); - final double z = args[3].startsWith("~") ? target2.getLocation().getZ() + Integer.parseInt(args[3].substring(1)) : Integer.parseInt(args[3]); - if (x > 30000000 || y > 30000000 || z > 30000000 || x < -30000000 || y < -30000000 || z < -30000000) - { - throw new NotEnoughArgumentsException(tl("teleportInvalidLocation")); - } - final Location locposother = new Location(target2.getWorld(), x, y, z, target2.getLocation().getYaw(), target2.getLocation().getPitch()); - if (!target2.isTeleportEnabled()) - { - throw new Exception(tl("teleportDisabled", target2.getDisplayName())); - } - user.sendMessage(tl("teleporting", locposother.getWorld().getName(), locposother.getBlockX(), locposother.getBlockY(), locposother.getBlockZ())); - target2.getTeleport().now(locposother, false, TeleportCause.COMMAND); - target2.sendMessage(tl("teleporting", locposother.getWorld().getName(), locposother.getBlockX(), locposother.getBlockY(), locposother.getBlockZ())); - break; - case 2: - default: - if (!user.isAuthorized("essentials.tp.others")) - { - throw new Exception(tl("noPerm", "essentials.tp.others")); - } - final User target = getPlayer(server, user, args, 0); - final User toPlayer = getPlayer(server, user, args, 1); - if (!target.isTeleportEnabled()) - { - throw new Exception(tl("teleportDisabled", target.getDisplayName())); - } - if (!toPlayer.isTeleportEnabled()) - { - throw new Exception(tl("teleportDisabled", toPlayer.getDisplayName())); - } - if (target.getWorld() != toPlayer.getWorld() && ess.getSettings().isWorldTeleportPermissions() - && !user.isAuthorized("essentials.worlds." + toPlayer.getWorld().getName())) - { - throw new Exception(tl("noPerm", "essentials.worlds." + toPlayer.getWorld().getName())); - } - target.sendMessage(tl("teleportAtoB", user.getDisplayName(), toPlayer.getDisplayName())); - target.getTeleport().now(toPlayer.getBase(), false, TeleportCause.COMMAND); - break; - } - } + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + switch (args.length) { + case 0: + throw new NotEnoughArgumentsException(); - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 2) - { - throw new NotEnoughArgumentsException(); - } + case 1: + final User player = getPlayer(server, user, args, 0); + if (!player.isTeleportEnabled()) { + throw new Exception(tl("teleportDisabled", player.getDisplayName())); + } + if (user.getWorld() != player.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + player.getWorld().getName())) { + throw new Exception(tl("noPerm", "essentials.worlds." + player.getWorld().getName())); + } + final Trade charge = new Trade(this.getName(), ess); + charge.isAffordableFor(user); + user.getTeleport().teleport(player.getBase(), charge, TeleportCause.COMMAND); + throw new NoChargeException(); + case 3: + if (!user.isAuthorized("essentials.tp.position")) { + throw new Exception(tl("noPerm", "essentials.tp.position")); + } + final double x2 = args[0].startsWith("~") ? user.getLocation().getX() + Integer.parseInt(args[0].substring(1)) : Integer.parseInt(args[0]); + final double y2 = args[1].startsWith("~") ? user.getLocation().getY() + Integer.parseInt(args[1].substring(1)) : Integer.parseInt(args[1]); + final double z2 = args[2].startsWith("~") ? user.getLocation().getZ() + Integer.parseInt(args[2].substring(1)) : Integer.parseInt(args[2]); + if (x2 > 30000000 || y2 > 30000000 || z2 > 30000000 || x2 < -30000000 || y2 < -30000000 || z2 < -30000000) { + throw new NotEnoughArgumentsException(tl("teleportInvalidLocation")); + } + final Location locpos = new Location(user.getWorld(), x2, y2, z2, user.getLocation().getYaw(), user.getLocation().getPitch()); + user.getTeleport().now(locpos, false, TeleportCause.COMMAND); + user.sendMessage(tl("teleporting", locpos.getWorld().getName(), locpos.getBlockX(), locpos.getBlockY(), locpos.getBlockZ())); + break; + case 4: + if (!user.isAuthorized("essentials.tp.others")) { + throw new Exception(tl("noPerm", "essentials.tp.others")); + } + if (!user.isAuthorized("essentials.tp.position")) { + throw new Exception(tl("noPerm", "essentials.tp.position")); + } + final User target2 = getPlayer(server, user, args, 0); + final double x = args[1].startsWith("~") ? target2.getLocation().getX() + Integer.parseInt(args[1].substring(1)) : Integer.parseInt(args[1]); + final double y = args[2].startsWith("~") ? target2.getLocation().getY() + Integer.parseInt(args[2].substring(1)) : Integer.parseInt(args[2]); + final double z = args[3].startsWith("~") ? target2.getLocation().getZ() + Integer.parseInt(args[3].substring(1)) : Integer.parseInt(args[3]); + if (x > 30000000 || y > 30000000 || z > 30000000 || x < -30000000 || y < -30000000 || z < -30000000) { + throw new NotEnoughArgumentsException(tl("teleportInvalidLocation")); + } + final Location locposother = new Location(target2.getWorld(), x, y, z, target2.getLocation().getYaw(), target2.getLocation().getPitch()); + if (!target2.isTeleportEnabled()) { + throw new Exception(tl("teleportDisabled", target2.getDisplayName())); + } + user.sendMessage(tl("teleporting", locposother.getWorld().getName(), locposother.getBlockX(), locposother.getBlockY(), locposother.getBlockZ())); + target2.getTeleport().now(locposother, false, TeleportCause.COMMAND); + target2.sendMessage(tl("teleporting", locposother.getWorld().getName(), locposother.getBlockX(), locposother.getBlockY(), locposother.getBlockZ())); + break; + case 2: + default: + if (!user.isAuthorized("essentials.tp.others")) { + throw new Exception(tl("noPerm", "essentials.tp.others")); + } + final User target = getPlayer(server, user, args, 0); + final User toPlayer = getPlayer(server, user, args, 1); + if (!target.isTeleportEnabled()) { + throw new Exception(tl("teleportDisabled", target.getDisplayName())); + } + if (!toPlayer.isTeleportEnabled()) { + throw new Exception(tl("teleportDisabled", toPlayer.getDisplayName())); + } + if (target.getWorld() != toPlayer.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + toPlayer.getWorld().getName())) { + throw new Exception(tl("noPerm", "essentials.worlds." + toPlayer.getWorld().getName())); + } + target.sendMessage(tl("teleportAtoB", user.getDisplayName(), toPlayer.getDisplayName())); + target.getTeleport().now(toPlayer.getBase(), false, TeleportCause.COMMAND); + break; + } + } - final User target = getPlayer(server, args, 0, true, false); - if (args.length == 2) - { - final User toPlayer = getPlayer(server, args, 1, true, false); - target.sendMessage(tl("teleportAtoB", Console.NAME, toPlayer.getDisplayName())); - target.getTeleport().now(toPlayer.getBase(), false, TeleportCause.COMMAND); - } - else if (args.length > 3) - { - final double x = args[1].startsWith("~") ? target.getLocation().getX() + Integer.parseInt(args[1].substring(1)) : Integer.parseInt(args[1]); - final double y = args[2].startsWith("~") ? target.getLocation().getY() + Integer.parseInt(args[2].substring(1)) : Integer.parseInt(args[2]); - final double z = args[3].startsWith("~") ? target.getLocation().getZ() + Integer.parseInt(args[3].substring(1)) : Integer.parseInt(args[3]); - if (x > 30000000 || y > 30000000 || z > 30000000 || x < -30000000 || y < -30000000 || z < -30000000) - { - throw new NotEnoughArgumentsException(tl("teleportInvalidLocation")); - } - final Location loc = new Location(target.getWorld(), x, y, z, target.getLocation().getYaw(), target.getLocation().getPitch()); - sender.sendMessage(tl("teleporting", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); - target.getTeleport().now(loc, false, TeleportCause.COMMAND); - target.sendMessage(tl("teleporting", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); - } - else - { - throw new NotEnoughArgumentsException(); - } - } + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 2) { + throw new NotEnoughArgumentsException(); + } + + final User target = getPlayer(server, args, 0, true, false); + if (args.length == 2) { + final User toPlayer = getPlayer(server, args, 1, true, false); + target.sendMessage(tl("teleportAtoB", Console.NAME, toPlayer.getDisplayName())); + target.getTeleport().now(toPlayer.getBase(), false, TeleportCause.COMMAND); + } else if (args.length > 3) { + final double x = args[1].startsWith("~") ? target.getLocation().getX() + Integer.parseInt(args[1].substring(1)) : Integer.parseInt(args[1]); + final double y = args[2].startsWith("~") ? target.getLocation().getY() + Integer.parseInt(args[2].substring(1)) : Integer.parseInt(args[2]); + final double z = args[3].startsWith("~") ? target.getLocation().getZ() + Integer.parseInt(args[3].substring(1)) : Integer.parseInt(args[3]); + if (x > 30000000 || y > 30000000 || z > 30000000 || x < -30000000 || y < -30000000 || z < -30000000) { + throw new NotEnoughArgumentsException(tl("teleportInvalidLocation")); + } + final Location loc = new Location(target.getWorld(), x, y, z, target.getLocation().getYaw(), target.getLocation().getPitch()); + sender.sendMessage(tl("teleporting", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); + target.getTeleport().now(loc, false, TeleportCause.COMMAND); + target.sendMessage(tl("teleporting", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); + } else { + throw new NotEnoughArgumentsException(); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpa.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpa.java index 94dd672bb..9dbb27998 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpa.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpa.java @@ -1,50 +1,41 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import org.bukkit.Server; +import static com.earth2me.essentials.I18n.tl; -public class Commandtpa extends EssentialsCommand -{ - public Commandtpa() - { - super("tpa"); - } - @Override - public void run(Server server, User user, String commandLabel, String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } +public class Commandtpa extends EssentialsCommand { + public Commandtpa() { + super("tpa"); + } - User player = getPlayer(server, user, args, 0); - if (user.getName().equalsIgnoreCase(player.getName())) - { - throw new NotEnoughArgumentsException(); - } - if (!player.isTeleportEnabled()) - { - throw new Exception(tl("teleportDisabled", player.getDisplayName())); - } - if (user.getWorld() != player.getWorld() && ess.getSettings().isWorldTeleportPermissions() - && !user.isAuthorized("essentials.worlds." + player.getWorld().getName())) - { - throw new Exception(tl("noPerm", "essentials.worlds." + player.getWorld().getName())); - } - if (!player.isIgnoredPlayer(user)) - { - player.requestTeleport(user, false); - player.sendMessage(tl("teleportRequest", user.getDisplayName())); - player.sendMessage(tl("typeTpaccept")); - player.sendMessage(tl("typeTpdeny")); - if (ess.getSettings().getTpaAcceptCancellation() != 0) - { - player.sendMessage(tl("teleportRequestTimeoutInfo", ess.getSettings().getTpaAcceptCancellation())); - } - } - user.sendMessage(tl("requestSent", player.getDisplayName())); - } + @Override + public void run(Server server, User user, String commandLabel, String[] args) throws Exception { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } + + User player = getPlayer(server, user, args, 0); + if (user.getName().equalsIgnoreCase(player.getName())) { + throw new NotEnoughArgumentsException(); + } + if (!player.isTeleportEnabled()) { + throw new Exception(tl("teleportDisabled", player.getDisplayName())); + } + if (user.getWorld() != player.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + player.getWorld().getName())) { + throw new Exception(tl("noPerm", "essentials.worlds." + player.getWorld().getName())); + } + if (!player.isIgnoredPlayer(user)) { + player.requestTeleport(user, false); + player.sendMessage(tl("teleportRequest", user.getDisplayName())); + player.sendMessage(tl("typeTpaccept")); + player.sendMessage(tl("typeTpdeny")); + if (ess.getSettings().getTpaAcceptCancellation() != 0) { + player.sendMessage(tl("teleportRequestTimeoutInfo", ess.getSettings().getTpaAcceptCancellation())); + } + } + user.sendMessage(tl("requestSent", player.getDisplayName())); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpaall.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpaall.java index 4cbd9603b..81f6797f6 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpaall.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpaall.java @@ -1,69 +1,53 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import org.bukkit.Server; -import org.bukkit.entity.Player; + +import static com.earth2me.essentials.I18n.tl; -public class Commandtpaall extends EssentialsCommand -{ - public Commandtpaall() - { - super("tpaall"); - } +public class Commandtpaall extends EssentialsCommand { + public Commandtpaall() { + super("tpaall"); + } - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - if (sender.isPlayer()) - { - teleportAAllPlayers(server, sender, ess.getUser(sender.getPlayer())); - return; - } - throw new NotEnoughArgumentsException(); - } + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + if (sender.isPlayer()) { + teleportAAllPlayers(server, sender, ess.getUser(sender.getPlayer())); + return; + } + throw new NotEnoughArgumentsException(); + } - final User target = getPlayer(server, sender, args, 0); - teleportAAllPlayers(server, sender, target); - } + final User target = getPlayer(server, sender, args, 0); + teleportAAllPlayers(server, sender, target); + } - private void teleportAAllPlayers(final Server server, final CommandSource sender, final User target) - { - sender.sendMessage(tl("teleportAAll")); - for (User player : ess.getOnlineUsers()) - { - if (target == player) - { - continue; - } - if (!player.isTeleportEnabled()) - { - continue; - } - if (sender.equals(target.getBase()) - && target.getWorld() != player.getWorld() && ess.getSettings().isWorldTeleportPermissions() - && !target.isAuthorized("essentials.worlds." + target.getWorld().getName())) - { - continue; - } - try - { - player.requestTeleport(target, true); - player.sendMessage(tl("teleportHereRequest", target.getDisplayName())); - player.sendMessage(tl("typeTpaccept")); - if (ess.getSettings().getTpaAcceptCancellation() != 0) - { - player.sendMessage(tl("teleportRequestTimeoutInfo", ess.getSettings().getTpaAcceptCancellation())); - } - } - catch (Exception ex) - { - ess.showError(sender, ex, getName()); - } - } - } + private void teleportAAllPlayers(final Server server, final CommandSource sender, final User target) { + sender.sendMessage(tl("teleportAAll")); + for (User player : ess.getOnlineUsers()) { + if (target == player) { + continue; + } + if (!player.isTeleportEnabled()) { + continue; + } + if (sender.equals(target.getBase()) && target.getWorld() != player.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !target.isAuthorized("essentials.worlds." + target.getWorld().getName())) { + continue; + } + try { + player.requestTeleport(target, true); + player.sendMessage(tl("teleportHereRequest", target.getDisplayName())); + player.sendMessage(tl("typeTpaccept")); + if (ess.getSettings().getTpaAcceptCancellation() != 0) { + player.sendMessage(tl("teleportRequestTimeoutInfo", ess.getSettings().getTpaAcceptCancellation())); + } + } catch (Exception ex) { + ess.showError(sender, ex, getName()); + } + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java index ed56a6275..ff486f1c1 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpaccept.java @@ -1,88 +1,68 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.Trade; import com.earth2me.essentials.User; import org.bukkit.Location; import org.bukkit.Server; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; +import static com.earth2me.essentials.I18n.tl; -public class Commandtpaccept extends EssentialsCommand -{ - public Commandtpaccept() - { - super("tpaccept"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - final User requester; - try - { - requester = ess.getUser(user.getTeleportRequest()); - } - catch (Exception ex) - { - throw new Exception(tl("noPendingRequest")); - } +public class Commandtpaccept extends EssentialsCommand { + public Commandtpaccept() { + super("tpaccept"); + } - if (!requester.getBase().isOnline()) - { - throw new Exception(tl("noPendingRequest")); - } + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + final User requester; + try { + requester = ess.getUser(user.getTeleportRequest()); + } catch (Exception ex) { + throw new Exception(tl("noPendingRequest")); + } - if (user.isTpRequestHere() && ((!requester.isAuthorized("essentials.tpahere") && !requester.isAuthorized("essentials.tpaall")) - || (user.getWorld() != requester.getWorld() && ess.getSettings().isWorldTeleportPermissions() - && !user.isAuthorized("essentials.worlds." + user.getWorld().getName())))) - { - throw new Exception(tl("noPendingRequest")); - } + if (!requester.getBase().isOnline()) { + throw new Exception(tl("noPendingRequest")); + } - if (!user.isTpRequestHere() && (!requester.isAuthorized("essentials.tpa") - || (user.getWorld() != requester.getWorld() && ess.getSettings().isWorldTeleportPermissions() - && !user.isAuthorized("essentials.worlds." + requester.getWorld().getName())))) - { - throw new Exception(tl("noPendingRequest")); - } + if (user.isTpRequestHere() && ((!requester.isAuthorized("essentials.tpahere") && !requester.isAuthorized("essentials.tpaall")) || (user.getWorld() != requester.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + user.getWorld().getName())))) { + throw new Exception(tl("noPendingRequest")); + } - if (args.length > 0 && !requester.getName().contains(args[0])) - { - throw new Exception(tl("noPendingRequest")); - } + if (!user.isTpRequestHere() && (!requester.isAuthorized("essentials.tpa") || (user.getWorld() != requester.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + requester.getWorld().getName())))) { + throw new Exception(tl("noPendingRequest")); + } - long timeout = ess.getSettings().getTpaAcceptCancellation(); - if (timeout != 0 && (System.currentTimeMillis() - user.getTeleportRequestTime()) / 1000 > timeout) - { - user.requestTeleport(null, false); - throw new Exception(tl("requestTimedOut")); - } + if (args.length > 0 && !requester.getName().contains(args[0])) { + throw new Exception(tl("noPendingRequest")); + } - final Trade charge = new Trade(this.getName(), ess); - user.sendMessage(tl("requestAccepted")); - requester.sendMessage(tl("requestAcceptedFrom", user.getDisplayName())); + long timeout = ess.getSettings().getTpaAcceptCancellation(); + if (timeout != 0 && (System.currentTimeMillis() - user.getTeleportRequestTime()) / 1000 > timeout) { + user.requestTeleport(null, false); + throw new Exception(tl("requestTimedOut")); + } - try - { - if (user.isTpRequestHere()) - { - final Location loc = user.getTpRequestLocation(); - requester.getTeleport().teleportPlayer(user, user.getTpRequestLocation(), charge, TeleportCause.COMMAND); - requester.sendMessage(tl("teleporting", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); - } - else - { - requester.getTeleport().teleport(user.getBase(), charge, TeleportCause.COMMAND); - } - } - catch (Exception ex) - { - user.sendMessage(tl("pendingTeleportCancelled")); - ess.showError(requester.getSource(), ex, commandLabel); - } - user.requestTeleport(null, false); - throw new NoChargeException(); - } + final Trade charge = new Trade(this.getName(), ess); + user.sendMessage(tl("requestAccepted")); + requester.sendMessage(tl("requestAcceptedFrom", user.getDisplayName())); + + try { + if (user.isTpRequestHere()) { + final Location loc = user.getTpRequestLocation(); + requester.getTeleport().teleportPlayer(user, user.getTpRequestLocation(), charge, TeleportCause.COMMAND); + requester.sendMessage(tl("teleporting", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); + } else { + requester.getTeleport().teleport(user.getBase(), charge, TeleportCause.COMMAND); + } + } catch (Exception ex) { + user.sendMessage(tl("pendingTeleportCancelled")); + ess.showError(requester.getSource(), ex, commandLabel); + } + user.requestTeleport(null, false); + throw new NoChargeException(); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpahere.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpahere.java index d0d3e47fd..6ca44f170 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpahere.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpahere.java @@ -1,50 +1,41 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import org.bukkit.Server; +import static com.earth2me.essentials.I18n.tl; -public class Commandtpahere extends EssentialsCommand -{ - public Commandtpahere() - { - super("tpahere"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } +public class Commandtpahere extends EssentialsCommand { + public Commandtpahere() { + super("tpahere"); + } - final User player = getPlayer(server, user, args, 0); - if (user.getName().equalsIgnoreCase(player.getName())) - { - throw new NotEnoughArgumentsException(); - } - if (!player.isTeleportEnabled()) - { - throw new Exception(tl("teleportDisabled", player.getDisplayName())); - } - if (user.getWorld() != player.getWorld() && ess.getSettings().isWorldTeleportPermissions() - && !user.isAuthorized("essentials.worlds." + user.getWorld().getName())) - { - throw new Exception(tl("noPerm", "essentials.worlds." + user.getWorld().getName())); - } - if (!player.isIgnoredPlayer(user)) - { - player.requestTeleport(user, true); - player.sendMessage(tl("teleportHereRequest", user.getDisplayName())); - player.sendMessage(tl("typeTpaccept")); - player.sendMessage(tl("typeTpdeny")); - if (ess.getSettings().getTpaAcceptCancellation() != 0) - { - player.sendMessage(tl("teleportRequestTimeoutInfo", ess.getSettings().getTpaAcceptCancellation())); - } - } - user.sendMessage(tl("requestSent", player.getDisplayName())); - } + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } + + final User player = getPlayer(server, user, args, 0); + if (user.getName().equalsIgnoreCase(player.getName())) { + throw new NotEnoughArgumentsException(); + } + if (!player.isTeleportEnabled()) { + throw new Exception(tl("teleportDisabled", player.getDisplayName())); + } + if (user.getWorld() != player.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + user.getWorld().getName())) { + throw new Exception(tl("noPerm", "essentials.worlds." + user.getWorld().getName())); + } + if (!player.isIgnoredPlayer(user)) { + player.requestTeleport(user, true); + player.sendMessage(tl("teleportHereRequest", user.getDisplayName())); + player.sendMessage(tl("typeTpaccept")); + player.sendMessage(tl("typeTpdeny")); + if (ess.getSettings().getTpaAcceptCancellation() != 0) { + player.sendMessage(tl("teleportRequestTimeoutInfo", ess.getSettings().getTpaAcceptCancellation())); + } + } + user.sendMessage(tl("requestSent", player.getDisplayName())); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpall.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpall.java index c850fad2e..beec5d3f9 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpall.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpall.java @@ -1,62 +1,48 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import org.bukkit.Location; import org.bukkit.Server; -import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; +import static com.earth2me.essentials.I18n.tl; -public class Commandtpall extends EssentialsCommand -{ - public Commandtpall() - { - super("tpall"); - } - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - if (sender.isPlayer()) - { - teleportAllPlayers(server, sender, ess.getUser(sender.getPlayer())); - return; - } - throw new NotEnoughArgumentsException(); - } +public class Commandtpall extends EssentialsCommand { + public Commandtpall() { + super("tpall"); + } - final User target = getPlayer(server, sender, args, 0); - teleportAllPlayers(server, sender, target); - } + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + if (sender.isPlayer()) { + teleportAllPlayers(server, sender, ess.getUser(sender.getPlayer())); + return; + } + throw new NotEnoughArgumentsException(); + } - private void teleportAllPlayers(Server server, CommandSource sender, User target) - { - sender.sendMessage(tl("teleportAll")); - final Location loc = target.getLocation(); - for (User player : ess.getOnlineUsers()) - { - if (target == player) - { - continue; - } - if (sender.equals(target.getBase()) - && target.getWorld() != player.getWorld() && ess.getSettings().isWorldTeleportPermissions() - && !target.isAuthorized("essentials.worlds." + target.getWorld().getName())) - { - continue; - } - try - { - player.getTeleport().now(loc, false, TeleportCause.COMMAND); - } - catch (Exception ex) - { - ess.showError(sender, ex, getName()); - } - } - } + final User target = getPlayer(server, sender, args, 0); + teleportAllPlayers(server, sender, target); + } + + private void teleportAllPlayers(Server server, CommandSource sender, User target) { + sender.sendMessage(tl("teleportAll")); + final Location loc = target.getLocation(); + for (User player : ess.getOnlineUsers()) { + if (target == player) { + continue; + } + if (sender.equals(target.getBase()) && target.getWorld() != player.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !target.isAuthorized("essentials.worlds." + target.getWorld().getName())) { + continue; + } + try { + player.getTeleport().now(loc, false, TeleportCause.COMMAND); + } catch (Exception ex) { + ess.showError(sender, ex, getName()); + } + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpdeny.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpdeny.java index c0dfde446..454738df3 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpdeny.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpdeny.java @@ -1,28 +1,25 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import org.bukkit.Server; +import static com.earth2me.essentials.I18n.tl; -public class Commandtpdeny extends EssentialsCommand -{ - public Commandtpdeny() - { - super("tpdeny"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - final User player = ess.getUser(user.getTeleportRequest()); - if (player == null) - { - throw new Exception(tl("noPendingRequest")); - } +public class Commandtpdeny extends EssentialsCommand { + public Commandtpdeny() { + super("tpdeny"); + } - user.sendMessage(tl("requestDenied")); - player.sendMessage(tl("requestDeniedFrom", user.getDisplayName())); - user.requestTeleport(null, false); - } + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + final User player = ess.getUser(user.getTeleportRequest()); + if (player == null) { + throw new Exception(tl("noPendingRequest")); + } + + user.sendMessage(tl("requestDenied")); + player.sendMessage(tl("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 index ec792b289..cdef58c36 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtphere.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtphere.java @@ -1,33 +1,28 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.Trade; import com.earth2me.essentials.User; import org.bukkit.Server; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; +import static com.earth2me.essentials.I18n.tl; -public class Commandtphere extends EssentialsCommand -{ - public Commandtphere() - { - super("tphere"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - final User player = getPlayer(server, user, args, 0); - if (!player.isTeleportEnabled()) - { - throw new Exception(tl("teleportDisabled", player.getDisplayName())); - } - if (user.getWorld() != player.getWorld() && ess.getSettings().isWorldTeleportPermissions() - && !user.isAuthorized("essentials.worlds." + user.getWorld().getName())) - { - throw new Exception(tl("noPerm", "essentials.worlds." + user.getWorld().getName())); - } - user.getTeleport().teleportPlayer(player, user.getBase(), new Trade(this.getName(), ess), TeleportCause.COMMAND); - throw new NoChargeException(); - } +public class Commandtphere extends EssentialsCommand { + public Commandtphere() { + super("tphere"); + } + + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + final User player = getPlayer(server, user, args, 0); + if (!player.isTeleportEnabled()) { + throw new Exception(tl("teleportDisabled", player.getDisplayName())); + } + if (user.getWorld() != player.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + user.getWorld().getName())) { + throw new Exception(tl("noPerm", "essentials.worlds." + user.getWorld().getName())); + } + user.getTeleport().teleportPlayer(player, user.getBase(), new Trade(this.getName(), ess), TeleportCause.COMMAND); + throw new NoChargeException(); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtpo.java b/Essentials/src/com/earth2me/essentials/commands/Commandtpo.java index 0befdfc3b..5a57da674 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpo.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpo.java @@ -1,53 +1,45 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import org.bukkit.Server; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; +import static com.earth2me.essentials.I18n.tl; -public class Commandtpo extends EssentialsCommand -{ - public Commandtpo() - { - super("tpo"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - switch (args.length) - { - case 0: - throw new NotEnoughArgumentsException(); +public class Commandtpo extends EssentialsCommand { + public Commandtpo() { + super("tpo"); + } - case 1: - final User player = getPlayer(server, user, args, 0); - if (user.getWorld() != player.getWorld() && ess.getSettings().isWorldTeleportPermissions() - && !user.isAuthorized("essentials.worlds." + player.getWorld().getName())) - { - throw new Exception(tl("noPerm", "essentials.worlds." + player.getWorld().getName())); - } - user.getTeleport().now(player.getBase(), false, TeleportCause.COMMAND); - break; + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + switch (args.length) { + case 0: + throw new NotEnoughArgumentsException(); - default: - if (!user.isAuthorized("essentials.tp.others")) - { - throw new Exception(tl("noPerm", "essentials.tp.others")); - } - final User target = getPlayer(server, user, args, 0); - final User toPlayer = getPlayer(server, user, args, 1); + case 1: + final User player = getPlayer(server, user, args, 0); + if (user.getWorld() != player.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + player.getWorld().getName())) { + throw new Exception(tl("noPerm", "essentials.worlds." + player.getWorld().getName())); + } + user.getTeleport().now(player.getBase(), false, TeleportCause.COMMAND); + break; - if (target.getWorld() != toPlayer.getWorld() && ess.getSettings().isWorldTeleportPermissions() - && !user.isAuthorized("essentials.worlds." + toPlayer.getWorld().getName())) - { - throw new Exception(tl("noPerm", "essentials.worlds." + toPlayer.getWorld().getName())); - } + default: + if (!user.isAuthorized("essentials.tp.others")) { + throw new Exception(tl("noPerm", "essentials.tp.others")); + } + final User target = getPlayer(server, user, args, 0); + final User toPlayer = getPlayer(server, user, args, 1); - target.getTeleport().now(toPlayer.getBase(), false, TeleportCause.COMMAND); - target.sendMessage(tl("teleportAtoB", user.getDisplayName(), toPlayer.getDisplayName())); - break; - } - } + if (target.getWorld() != toPlayer.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + toPlayer.getWorld().getName())) { + throw new Exception(tl("noPerm", "essentials.worlds." + toPlayer.getWorld().getName())); + } + + target.getTeleport().now(toPlayer.getBase(), false, TeleportCause.COMMAND); + target.sendMessage(tl("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 index bb0d924eb..66125fb36 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtpohere.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtpohere.java @@ -1,36 +1,31 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import org.bukkit.Server; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; +import static com.earth2me.essentials.I18n.tl; -public class Commandtpohere extends EssentialsCommand -{ - public Commandtpohere() - { - super("tpohere"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } +public class Commandtpohere extends EssentialsCommand { + public Commandtpohere() { + super("tpohere"); + } - //Just basically the old tphere command - final User player = getPlayer(server, user, args, 0); + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } - if (user.getWorld() != player.getWorld() && ess.getSettings().isWorldTeleportPermissions() - && !user.isAuthorized("essentials.worlds." + user.getWorld().getName())) - { - throw new Exception(tl("noPerm", "essentials.worlds." + user.getWorld().getName())); - } + //Just basically the old tphere command + final User player = getPlayer(server, user, args, 0); - // Verify permission - player.getTeleport().now(user.getBase(), false, TeleportCause.COMMAND); - } + if (user.getWorld() != player.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + user.getWorld().getName())) { + throw new Exception(tl("noPerm", "essentials.worlds." + user.getWorld().getName())); + } + + // Verify permission + player.getTeleport().now(user.getBase(), false, TeleportCause.COMMAND); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtppos.java b/Essentials/src/com/earth2me/essentials/commands/Commandtppos.java index 0d48acc59..a6cec30e9 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtppos.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtppos.java @@ -1,80 +1,69 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.Trade; import com.earth2me.essentials.User; import org.bukkit.Location; import org.bukkit.Server; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; +import static com.earth2me.essentials.I18n.tl; -public class Commandtppos extends EssentialsCommand -{ - public Commandtppos() - { - super("tppos"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 3) - { - throw new NotEnoughArgumentsException(); - } +public class Commandtppos extends EssentialsCommand { + public Commandtppos() { + super("tppos"); + } - final double x = args[0].startsWith("~") ? user.getLocation().getX() + Integer.parseInt(args[0].substring(1)) : Integer.parseInt(args[0]); - final double y = args[1].startsWith("~") ? user.getLocation().getY() + Integer.parseInt(args[1].substring(1)) : Integer.parseInt(args[1]); - final double z = args[2].startsWith("~") ? user.getLocation().getZ() + Integer.parseInt(args[2].substring(1)) : Integer.parseInt(args[2]); - final Location loc = new Location(user.getWorld(), x, y, z, user.getLocation().getYaw(), user.getLocation().getPitch()); - if (args.length > 3) - { - loc.setYaw((Float.parseFloat(args[3]) + 180 + 360) % 360); - } - if (args.length > 4) - { - loc.setPitch(Float.parseFloat(args[4])); - } - if (x > 30000000 || y > 30000000 || z > 30000000 || x < -30000000 || y < -30000000 || z < -30000000) - { - throw new NotEnoughArgumentsException(tl("teleportInvalidLocation")); - } - final Trade charge = new Trade(this.getName(), ess); - charge.isAffordableFor(user); - user.sendMessage(tl("teleporting", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); - user.getTeleport().teleport(loc, charge, TeleportCause.COMMAND); - throw new NoChargeException(); - } + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (args.length < 3) { + throw new NotEnoughArgumentsException(); + } - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 4) - { - throw new NotEnoughArgumentsException(); - } + final double x = args[0].startsWith("~") ? user.getLocation().getX() + Integer.parseInt(args[0].substring(1)) : Integer.parseInt(args[0]); + final double y = args[1].startsWith("~") ? user.getLocation().getY() + Integer.parseInt(args[1].substring(1)) : Integer.parseInt(args[1]); + final double z = args[2].startsWith("~") ? user.getLocation().getZ() + Integer.parseInt(args[2].substring(1)) : Integer.parseInt(args[2]); + final Location loc = new Location(user.getWorld(), x, y, z, user.getLocation().getYaw(), user.getLocation().getPitch()); + if (args.length > 3) { + loc.setYaw((Float.parseFloat(args[3]) + 180 + 360) % 360); + } + if (args.length > 4) { + loc.setPitch(Float.parseFloat(args[4])); + } + if (x > 30000000 || y > 30000000 || z > 30000000 || x < -30000000 || y < -30000000 || z < -30000000) { + throw new NotEnoughArgumentsException(tl("teleportInvalidLocation")); + } + final Trade charge = new Trade(this.getName(), ess); + charge.isAffordableFor(user); + user.sendMessage(tl("teleporting", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); + user.getTeleport().teleport(loc, charge, TeleportCause.COMMAND); + throw new NoChargeException(); + } - User user = getPlayer(server, args, 0, true, false); - final double x = args[1].startsWith("~") ? user.getLocation().getX() + Integer.parseInt(args[1].substring(1)) : Integer.parseInt(args[1]); - final double y = args[2].startsWith("~") ? user.getLocation().getY() + Integer.parseInt(args[2].substring(1)) : Integer.parseInt(args[2]); - final double z = args[3].startsWith("~") ? user.getLocation().getZ() + Integer.parseInt(args[3].substring(1)) : Integer.parseInt(args[3]); - final Location loc = new Location(user.getWorld(), x, y, z, user.getLocation().getYaw(), user.getLocation().getPitch()); - if (args.length > 4) - { - loc.setYaw((Float.parseFloat(args[4]) + 180 + 360) % 360); - } - if (args.length > 5) - { - loc.setPitch(Float.parseFloat(args[5])); - } - if (x > 30000000 || y > 30000000 || z > 30000000 || x < -30000000 || y < -30000000 || z < -30000000) - { - throw new NotEnoughArgumentsException(tl("teleportInvalidLocation")); - } - sender.sendMessage(tl("teleporting", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); - user.sendMessage(tl("teleporting", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); - user.getTeleport().teleport(loc, null, TeleportCause.COMMAND); + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 4) { + throw new NotEnoughArgumentsException(); + } - } + User user = getPlayer(server, args, 0, true, false); + final double x = args[1].startsWith("~") ? user.getLocation().getX() + Integer.parseInt(args[1].substring(1)) : Integer.parseInt(args[1]); + final double y = args[2].startsWith("~") ? user.getLocation().getY() + Integer.parseInt(args[2].substring(1)) : Integer.parseInt(args[2]); + final double z = args[3].startsWith("~") ? user.getLocation().getZ() + Integer.parseInt(args[3].substring(1)) : Integer.parseInt(args[3]); + final Location loc = new Location(user.getWorld(), x, y, z, user.getLocation().getYaw(), user.getLocation().getPitch()); + if (args.length > 4) { + loc.setYaw((Float.parseFloat(args[4]) + 180 + 360) % 360); + } + if (args.length > 5) { + loc.setPitch(Float.parseFloat(args[5])); + } + if (x > 30000000 || y > 30000000 || z > 30000000 || x < -30000000 || y < -30000000 || z < -30000000) { + throw new NotEnoughArgumentsException(tl("teleportInvalidLocation")); + } + sender.sendMessage(tl("teleporting", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); + user.sendMessage(tl("teleporting", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); + user.getTeleport().teleport(loc, null, TeleportCause.COMMAND); + + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtptoggle.java b/Essentials/src/com/earth2me/essentials/commands/Commandtptoggle.java index 3bc02b02e..9ba5b5191 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtptoggle.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtptoggle.java @@ -1,63 +1,49 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import org.bukkit.Server; +import static com.earth2me.essentials.I18n.tl; -public class Commandtptoggle extends EssentialsToggleCommand -{ - public Commandtptoggle() - { - super("tptoggle", "essentials.tptoggle.others"); - } - @Override - protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - toggleOtherPlayers(server, sender, args); - } +public class Commandtptoggle extends EssentialsToggleCommand { + public Commandtptoggle() { + super("tptoggle", "essentials.tptoggle.others"); + } - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (args.length == 1) - { - Boolean toggle = matchToggleArgument(args[0]); - if (toggle == null && user.isAuthorized(othersPermission)) - { - toggleOtherPlayers(server, user.getSource(), args); - } - else - { - togglePlayer(user.getSource(), user, toggle); - } - } - else if (args.length == 2 && user.isAuthorized(othersPermission)) - { - toggleOtherPlayers(server, user.getSource(), args); - } - else - { - togglePlayer(user.getSource(), user, null); - } - } + @Override + protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + toggleOtherPlayers(server, sender, args); + } - @Override - void togglePlayer(CommandSource sender, User user, Boolean enabled) - { - if (enabled == null) - { - enabled = !user.isTeleportEnabled(); - } + @Override + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (args.length == 1) { + Boolean toggle = matchToggleArgument(args[0]); + if (toggle == null && user.isAuthorized(othersPermission)) { + toggleOtherPlayers(server, user.getSource(), args); + } else { + togglePlayer(user.getSource(), user, toggle); + } + } else if (args.length == 2 && user.isAuthorized(othersPermission)) { + toggleOtherPlayers(server, user.getSource(), args); + } else { + togglePlayer(user.getSource(), user, null); + } + } - user.setTeleportEnabled(enabled); + @Override + void togglePlayer(CommandSource sender, User user, Boolean enabled) { + if (enabled == null) { + enabled = !user.isTeleportEnabled(); + } - user.sendMessage(enabled ? tl("teleportationEnabled") : tl("teleportationDisabled")); - if (!sender.isPlayer() || !sender.getPlayer().equals(user.getBase())) - { - sender.sendMessage(enabled ? tl("teleportationEnabledFor", user.getDisplayName()) : tl("teleportationDisabledFor", user.getDisplayName())); - } - } + user.setTeleportEnabled(enabled); + + user.sendMessage(enabled ? tl("teleportationEnabled") : tl("teleportationDisabled")); + if (!sender.isPlayer() || !sender.getPlayer().equals(user.getBase())) { + sender.sendMessage(enabled ? tl("teleportationEnabledFor", user.getDisplayName()) : tl("teleportationDisabledFor", user.getDisplayName())); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandtree.java b/Essentials/src/com/earth2me/essentials/commands/Commandtree.java index 1a50e8f55..c5d9c3cdc 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandtree.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandtree.java @@ -1,91 +1,61 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.Essentials; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.LocationUtil; import org.bukkit.Location; import org.bukkit.Server; import org.bukkit.TreeType; +import static com.earth2me.essentials.I18n.tl; -public class Commandtree extends EssentialsCommand -{ - public Commandtree() - { - super("tree"); - } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - TreeType tree = TreeType.BIRCH; - try // update check - { - 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 if (args[0].equalsIgnoreCase("acacia")) - { - tree = TreeType.ACACIA; - } - else if (args[0].equalsIgnoreCase("darkoak")) - { - tree = TreeType.DARK_OAK; - } - else - { - throw new NotEnoughArgumentsException(); - } - } - catch (java.lang.NoSuchFieldError e) - { - Essentials.wrongVersion(); - } +public class Commandtree extends EssentialsCommand { + public Commandtree() { + super("tree"); + } - final Location loc = LocationUtil.getTarget(user.getBase()); - final Location safeLocation = LocationUtil.getSafeDestination(loc); - final boolean success = user.getWorld().generateTree(safeLocation, tree); - if (success) - { - user.sendMessage(tl("treeSpawned")); - } - else - { - user.sendMessage(tl("treeFailure")); - } - } + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + TreeType tree = TreeType.BIRCH; + try // update check + { + 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 if (args[0].equalsIgnoreCase("acacia")) { + tree = TreeType.ACACIA; + } else if (args[0].equalsIgnoreCase("darkoak")) { + tree = TreeType.DARK_OAK; + } else { + throw new NotEnoughArgumentsException(); + } + } catch (java.lang.NoSuchFieldError e) { + Essentials.wrongVersion(); + } + + final Location loc = LocationUtil.getTarget(user.getBase()); + final Location safeLocation = LocationUtil.getSafeDestination(loc); + final boolean success = user.getWorld().generateTree(safeLocation, tree); + if (success) { + user.sendMessage(tl("treeSpawned")); + } else { + user.sendMessage(tl("treeFailure")); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandunban.java b/Essentials/src/com/earth2me/essentials/commands/Commandunban.java index b4cb70bf5..ba763b44f 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandunban.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandunban.java @@ -2,50 +2,43 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.Console; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; -import java.util.logging.Level; import org.bukkit.BanList; -import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.Server; +import java.util.logging.Level; -public class Commandunban extends EssentialsCommand -{ - public Commandunban() - { - super("unban"); - } +import static com.earth2me.essentials.I18n.tl; - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - String name; - try - { - final User user = getPlayer(server, args, 0, true, true); - name = user.getName(); - ess.getServer().getBanList(BanList.Type.NAME).pardon(name); - } - catch (NoSuchFieldException e) - { - final OfflinePlayer player = server.getOfflinePlayer(args[0]); - name = player.getName(); - if (!player.isBanned()) - { - throw new Exception(tl("playerNotFound"), e); - } - ess.getServer().getBanList(BanList.Type.NAME).pardon(name); - } - final String senderName = sender.isPlayer() ? sender.getPlayer().getDisplayName() : Console.NAME; - server.getLogger().log(Level.INFO, tl("playerUnbanned", senderName, name)); +public class Commandunban extends EssentialsCommand { + public Commandunban() { + super("unban"); + } - ess.broadcastMessage("essentials.ban.notify", tl("playerUnbanned", senderName, name)); - } + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } + String name; + try { + final User user = getPlayer(server, args, 0, true, true); + name = user.getName(); + ess.getServer().getBanList(BanList.Type.NAME).pardon(name); + } catch (NoSuchFieldException e) { + final OfflinePlayer player = server.getOfflinePlayer(args[0]); + name = player.getName(); + if (!player.isBanned()) { + throw new Exception(tl("playerNotFound"), e); + } + ess.getServer().getBanList(BanList.Type.NAME).pardon(name); + } + + final String senderName = sender.isPlayer() ? sender.getPlayer().getDisplayName() : Console.NAME; + server.getLogger().log(Level.INFO, tl("playerUnbanned", senderName, name)); + + ess.broadcastMessage("essentials.ban.notify", tl("playerUnbanned", senderName, name)); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandunbanip.java b/Essentials/src/com/earth2me/essentials/commands/Commandunbanip.java index 9157a3274..a96eb3595 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandunbanip.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandunbanip.java @@ -2,58 +2,48 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.Console; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.FormatUtil; -import java.util.logging.Level; import org.bukkit.BanList; -import org.bukkit.Bukkit; import org.bukkit.Server; +import java.util.logging.Level; -public class Commandunbanip extends EssentialsCommand -{ - public Commandunbanip() - { - super("unbanip"); - } - - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - - String ipAddress; - if (FormatUtil.validIP(args[0])) - { - ipAddress = args[0]; - } - else - { - try - { - User player = getPlayer(server, args, 0, true, true); - ipAddress = player.getLastLoginAddress(); - } - catch (PlayerNotFoundException ex) - { - ipAddress = args[0]; - } - } - - if (ipAddress.isEmpty()) - { - throw new PlayerNotFoundException(); - } +import static com.earth2me.essentials.I18n.tl; - ess.getServer().getBanList(BanList.Type.IP).pardon(ipAddress); - final String senderName = sender.isPlayer() ? sender.getPlayer().getDisplayName() : Console.NAME; - server.getLogger().log(Level.INFO, tl("playerUnbanIpAddress", senderName, ipAddress)); +public class Commandunbanip extends EssentialsCommand { + public Commandunbanip() { + super("unbanip"); + } - ess.broadcastMessage("essentials.ban.notify", tl("playerUnbanIpAddress", senderName, ipAddress)); - } + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } + + String ipAddress; + if (FormatUtil.validIP(args[0])) { + ipAddress = args[0]; + } else { + try { + User player = getPlayer(server, args, 0, true, true); + ipAddress = player.getLastLoginAddress(); + } catch (PlayerNotFoundException ex) { + ipAddress = args[0]; + } + } + + if (ipAddress.isEmpty()) { + throw new PlayerNotFoundException(); + } + + + ess.getServer().getBanList(BanList.Type.IP).pardon(ipAddress); + final String senderName = sender.isPlayer() ? sender.getPlayer().getDisplayName() : Console.NAME; + server.getLogger().log(Level.INFO, tl("playerUnbanIpAddress", senderName, ipAddress)); + + ess.broadcastMessage("essentials.ban.notify", tl("playerUnbanIpAddress", senderName, ipAddress)); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandunlimited.java b/Essentials/src/com/earth2me/essentials/commands/Commandunlimited.java index c07f900b8..158da4bc1 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandunlimited.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandunlimited.java @@ -1,120 +1,96 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; -import java.util.List; -import java.util.Locale; import org.bukkit.Material; import org.bukkit.Server; import org.bukkit.inventory.ItemStack; +import java.util.List; +import java.util.Locale; -public class Commandunlimited extends EssentialsCommand -{ - public Commandunlimited() - { - super("unlimited"); - } +import static com.earth2me.essentials.I18n.tl; - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - User target = user; +public class Commandunlimited extends EssentialsCommand { + public Commandunlimited() { + super("unlimited"); + } - if (args.length > 1 && user.isAuthorized("essentials.unlimited.others")) - { - target = getPlayer(server, user, args, 1); - } + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } - if (args[0].equalsIgnoreCase("list")) - { - final String list = getList(target); - user.sendMessage(list); - } - else if (args[0].equalsIgnoreCase("clear")) - { - final List itemList = target.getUnlimited(); + User target = user; - int index = 0; - while (itemList.size() > index) - { - final Integer item = itemList.get(index); - if (toggleUnlimited(user, target, item.toString()) == false) - { - index++; - } - } - } - else - { - toggleUnlimited(user, target, args[0]); - } - } + if (args.length > 1 && user.isAuthorized("essentials.unlimited.others")) { + target = getPlayer(server, user, args, 1); + } - private String getList(final User target) - { - final StringBuilder output = new StringBuilder(); - output.append(tl("unlimitedItems")).append(" "); - boolean first = true; - final List items = target.getUnlimited(); - if (items.isEmpty()) - { - output.append(tl("none")); - } - for (Integer integer : items) - { - if (!first) - { - output.append(", "); - } - first = false; - final String matname = Material.getMaterial(integer).toString().toLowerCase(Locale.ENGLISH).replace("_", ""); - output.append(matname); - } + if (args[0].equalsIgnoreCase("list")) { + final String list = getList(target); + user.sendMessage(list); + } else if (args[0].equalsIgnoreCase("clear")) { + final List itemList = target.getUnlimited(); - return output.toString(); - } + int index = 0; + while (itemList.size() > index) { + final Integer item = itemList.get(index); + if (toggleUnlimited(user, target, item.toString()) == false) { + index++; + } + } + } else { + toggleUnlimited(user, target, args[0]); + } + } - private Boolean toggleUnlimited(final User user, final User target, final String item) throws Exception - { - final ItemStack stack = ess.getItemDb().get(item, 1); - stack.setAmount(Math.min(stack.getType().getMaxStackSize(), 2)); + private String getList(final User target) { + final StringBuilder output = new StringBuilder(); + output.append(tl("unlimitedItems")).append(" "); + boolean first = true; + final List items = target.getUnlimited(); + if (items.isEmpty()) { + output.append(tl("none")); + } + for (Integer integer : items) { + if (!first) { + output.append(", "); + } + first = false; + final String matname = Material.getMaterial(integer).toString().toLowerCase(Locale.ENGLISH).replace("_", ""); + output.append(matname); + } - final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""); - if (ess.getSettings().permissionBasedItemSpawn() - && (!user.isAuthorized("essentials.unlimited.item-all") - && !user.isAuthorized("essentials.unlimited.item-" + itemname) - && !user.isAuthorized("essentials.unlimited.item-" + stack.getTypeId()) - && !((stack.getType() == Material.WATER_BUCKET || stack.getType() == Material.LAVA_BUCKET) - && user.isAuthorized("essentials.unlimited.item-bucket")))) - { - throw new Exception(tl("unlimitedItemPermission", itemname)); - } + return output.toString(); + } - String message = "disableUnlimited"; - boolean enableUnlimited = false; - if (!target.hasUnlimited(stack)) - { - message = "enableUnlimited"; - enableUnlimited = true; - if (!target.getBase().getInventory().containsAtLeast(stack, stack.getAmount())) - { - target.getBase().getInventory().addItem(stack); - } - } + private Boolean toggleUnlimited(final User user, final User target, final String item) throws Exception { + final ItemStack stack = ess.getItemDb().get(item, 1); + stack.setAmount(Math.min(stack.getType().getMaxStackSize(), 2)); - if (user != target) - { - user.sendMessage(tl(message, itemname, target.getDisplayName())); - } - target.sendMessage(tl(message, itemname, target.getDisplayName())); - target.setUnlimited(stack, enableUnlimited); + final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""); + if (ess.getSettings().permissionBasedItemSpawn() && (!user.isAuthorized("essentials.unlimited.item-all") && !user.isAuthorized("essentials.unlimited.item-" + itemname) && !user.isAuthorized("essentials.unlimited.item-" + stack.getTypeId()) && !((stack.getType() == Material.WATER_BUCKET || stack.getType() == Material.LAVA_BUCKET) && user.isAuthorized("essentials.unlimited.item-bucket")))) { + throw new Exception(tl("unlimitedItemPermission", itemname)); + } - return true; - } + String message = "disableUnlimited"; + boolean enableUnlimited = false; + if (!target.hasUnlimited(stack)) { + message = "enableUnlimited"; + enableUnlimited = true; + if (!target.getBase().getInventory().containsAtLeast(stack, stack.getAmount())) { + target.getBase().getInventory().addItem(stack); + } + } + + if (user != target) { + user.sendMessage(tl(message, itemname, target.getDisplayName())); + } + target.sendMessage(tl(message, itemname, target.getDisplayName())); + target.setUnlimited(stack, enableUnlimited); + + return true; + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandvanish.java b/Essentials/src/com/earth2me/essentials/commands/Commandvanish.java index fd2bd6d92..e3d54145d 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandvanish.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandvanish.java @@ -1,67 +1,52 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import org.bukkit.Server; +import static com.earth2me.essentials.I18n.tl; -public class Commandvanish extends EssentialsToggleCommand -{ - public Commandvanish() - { - super("vanish", "essentials.vanish.others"); - } - @Override - protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - toggleOtherPlayers(server, sender, args); - } +public class Commandvanish extends EssentialsToggleCommand { + public Commandvanish() { + super("vanish", "essentials.vanish.others"); + } - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (args.length == 1) - { - Boolean toggle = matchToggleArgument(args[0]); - if (toggle == null && user.isAuthorized(othersPermission)) - { - toggleOtherPlayers(server, user.getSource(), args); - } - else - { - togglePlayer(user.getSource(), user, toggle); - } - } - else if (args.length == 2 && user.isAuthorized(othersPermission)) - { - toggleOtherPlayers(server, user.getSource(), args); - } - else - { - togglePlayer(user.getSource(), user, null); - } - } + @Override + protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + toggleOtherPlayers(server, sender, args); + } - @Override - void togglePlayer(CommandSource sender, User user, Boolean enabled) throws NotEnoughArgumentsException - { - if (enabled == null) - { - enabled = !user.isVanished(); - } + @Override + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (args.length == 1) { + Boolean toggle = matchToggleArgument(args[0]); + if (toggle == null && user.isAuthorized(othersPermission)) { + toggleOtherPlayers(server, user.getSource(), args); + } else { + togglePlayer(user.getSource(), user, toggle); + } + } else if (args.length == 2 && user.isAuthorized(othersPermission)) { + toggleOtherPlayers(server, user.getSource(), args); + } else { + togglePlayer(user.getSource(), user, null); + } + } - user.setVanished(enabled); - user.sendMessage(tl("vanish", user.getDisplayName(), enabled ? tl("enabled") : tl("disabled"))); + @Override + void togglePlayer(CommandSource sender, User user, Boolean enabled) throws NotEnoughArgumentsException { + if (enabled == null) { + enabled = !user.isVanished(); + } - if (enabled == true) - { - user.sendMessage(tl("vanished")); - } - if (!sender.isPlayer() || !sender.getPlayer().equals(user.getBase())) - { - sender.sendMessage(tl("vanish", user.getDisplayName(), enabled ? tl("enabled") : tl("disabled"))); - } - } + user.setVanished(enabled); + user.sendMessage(tl("vanish", user.getDisplayName(), enabled ? tl("enabled") : tl("disabled"))); + + if (enabled == true) { + user.sendMessage(tl("vanished")); + } + if (!sender.isPlayer() || !sender.getPlayer().equals(user.getBase())) { + sender.sendMessage(tl("vanish", user.getDisplayName(), enabled ? tl("enabled") : tl("disabled"))); + } + } } \ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandwarp.java b/Essentials/src/com/earth2me/essentials/commands/Commandwarp.java index 8c2e88a4a..06d016973 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandwarp.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandwarp.java @@ -1,132 +1,113 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.Trade; import com.earth2me.essentials.User; import com.earth2me.essentials.api.IWarps; import com.earth2me.essentials.utils.NumberUtil; import com.earth2me.essentials.utils.StringUtil; +import net.ess3.api.IUser; +import org.bukkit.Server; +import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; + import java.math.BigDecimal; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Locale; -import net.ess3.api.IUser; -import org.bukkit.Server; -import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; + +import static com.earth2me.essentials.I18n.tl; -public class Commandwarp extends EssentialsCommand -{ - private static final int WARPS_PER_PAGE = 20; +public class Commandwarp extends EssentialsCommand { + private static final int WARPS_PER_PAGE = 20; - public Commandwarp() - { - super("warp"); - } + public Commandwarp() { + super("warp"); + } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - if (args.length == 0 || args[0].matches("[0-9]+")) - { - if (!user.isAuthorized("essentials.warp.list")) - { - throw new Exception(tl("warpListPermission")); - } - warpList(user.getSource(), args, user); - throw new NoChargeException(); - } - if (args.length > 0) - { - //TODO: Remove 'otherplayers' permission. - User otherUser = null; - if (args.length == 2 && (user.isAuthorized("essentials.warp.otherplayers") || user.isAuthorized("essentials.warp.others"))) - { - otherUser = getPlayer(server, user, args, 1); - warpUser(user, otherUser, args[0]); - throw new NoChargeException(); - } - warpUser(user, user, args[0]); - throw new NoChargeException(); - } - } + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + if (args.length == 0 || args[0].matches("[0-9]+")) { + if (!user.isAuthorized("essentials.warp.list")) { + throw new Exception(tl("warpListPermission")); + } + warpList(user.getSource(), args, user); + throw new NoChargeException(); + } + if (args.length > 0) { + //TODO: Remove 'otherplayers' permission. + User otherUser = null; + if (args.length == 2 && (user.isAuthorized("essentials.warp.otherplayers") || user.isAuthorized("essentials.warp.others"))) { + otherUser = getPlayer(server, user, args, 1); + warpUser(user, otherUser, args[0]); + throw new NoChargeException(); + } + warpUser(user, user, args[0]); + throw new NoChargeException(); + } + } - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 2 || NumberUtil.isInt(args[0])) - { - warpList(sender, args, null); - throw new NoChargeException(); - } - User otherUser = getPlayer(server, args, 1, true, false); - otherUser.getTeleport().warp(otherUser, args[0], null, TeleportCause.COMMAND); - throw new NoChargeException(); + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 2 || NumberUtil.isInt(args[0])) { + warpList(sender, args, null); + throw new NoChargeException(); + } + User otherUser = getPlayer(server, args, 1, true, false); + otherUser.getTeleport().warp(otherUser, args[0], null, TeleportCause.COMMAND); + throw new NoChargeException(); - } + } - //TODO: Use one of the new text classes, like /help ? - private void warpList(final CommandSource sender, final String[] args, final IUser user) throws Exception - { - final IWarps warps = ess.getWarps(); - final List warpNameList = new ArrayList(warps.getList()); + //TODO: Use one of the new text classes, like /help ? + private void warpList(final CommandSource sender, final String[] args, final IUser user) throws Exception { + final IWarps warps = ess.getWarps(); + final List warpNameList = new ArrayList(warps.getList()); - if (user != null) - { - final Iterator iterator = warpNameList.iterator(); - while (iterator.hasNext()) - { - final String warpName = iterator.next(); - if (ess.getSettings().getPerWarpPermission() && !user.isAuthorized("essentials.warps." + warpName)) - { - iterator.remove(); - } - } - } - if (warpNameList.isEmpty()) - { - throw new Exception(tl("noWarpsDefined")); - } - int page = 1; - if (args.length > 0 && NumberUtil.isInt(args[0])) - { - page = Integer.parseInt(args[0]); - } + if (user != null) { + final Iterator iterator = warpNameList.iterator(); + while (iterator.hasNext()) { + final String warpName = iterator.next(); + if (ess.getSettings().getPerWarpPermission() && !user.isAuthorized("essentials.warps." + warpName)) { + iterator.remove(); + } + } + } + if (warpNameList.isEmpty()) { + throw new Exception(tl("noWarpsDefined")); + } + int page = 1; + if (args.length > 0 && NumberUtil.isInt(args[0])) { + page = Integer.parseInt(args[0]); + } - final int maxPages = (int)Math.ceil(warpNameList.size() / (double)WARPS_PER_PAGE); + final int maxPages = (int) Math.ceil(warpNameList.size() / (double) WARPS_PER_PAGE); - if (page > maxPages) - { - page = maxPages; - } + if (page > maxPages) { + page = maxPages; + } - final int warpPage = (page - 1) * WARPS_PER_PAGE; - final String warpList = StringUtil.joinList(warpNameList.subList(warpPage, warpPage + Math.min(warpNameList.size() - warpPage, WARPS_PER_PAGE))); + final int warpPage = (page - 1) * WARPS_PER_PAGE; + final String warpList = StringUtil.joinList(warpNameList.subList(warpPage, warpPage + Math.min(warpNameList.size() - warpPage, WARPS_PER_PAGE))); - if (warpNameList.size() > WARPS_PER_PAGE) - { - sender.sendMessage(tl("warpsCount", warpNameList.size(), page, maxPages)); - sender.sendMessage(tl("warpList", warpList)); - } - else - { - sender.sendMessage(tl("warps", warpList)); - } - } + if (warpNameList.size() > WARPS_PER_PAGE) { + sender.sendMessage(tl("warpsCount", warpNameList.size(), page, maxPages)); + sender.sendMessage(tl("warpList", warpList)); + } else { + sender.sendMessage(tl("warps", warpList)); + } + } - private void warpUser(final User owner, final User user, final String name) throws Exception - { - final Trade chargeWarp = new Trade("warp-" + name.toLowerCase(Locale.ENGLISH).replace('_', '-'), ess); - final Trade chargeCmd = new Trade(this.getName(), ess); - final BigDecimal fullCharge = chargeWarp.getCommandCost(user).add(chargeCmd.getCommandCost(user)); - final Trade charge = new Trade(fullCharge, ess); - charge.isAffordableFor(owner); - if (ess.getSettings().getPerWarpPermission() && !owner.isAuthorized("essentials.warps." + name)) - { - throw new Exception(tl("warpUsePermission")); - } - owner.getTeleport().warp(user, name, charge, TeleportCause.COMMAND); - } + private void warpUser(final User owner, final User user, final String name) throws Exception { + final Trade chargeWarp = new Trade("warp-" + name.toLowerCase(Locale.ENGLISH).replace('_', '-'), ess); + final Trade chargeCmd = new Trade(this.getName(), ess); + final BigDecimal fullCharge = chargeWarp.getCommandCost(user).add(chargeCmd.getCommandCost(user)); + final Trade charge = new Trade(fullCharge, ess); + charge.isAffordableFor(owner); + if (ess.getSettings().getPerWarpPermission() && !owner.isAuthorized("essentials.warps." + name)) { + throw new Exception(tl("warpUsePermission")); + } + owner.getTeleport().warp(user, name, charge, TeleportCause.COMMAND); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandweather.java b/Essentials/src/com/earth2me/essentials/commands/Commandweather.java index 0b7ae924f..068ee85f7 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandweather.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandweather.java @@ -1,92 +1,65 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import org.bukkit.Server; import org.bukkit.World; +import static com.earth2me.essentials.I18n.tl; -public class Commandweather extends EssentialsCommand -{ - public Commandweather() - { - super("weather"); - } - //TODO: Remove duplication - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - final boolean isStorm; - if (args.length < 1) - { - if (commandLabel.equalsIgnoreCase("sun") || commandLabel.equalsIgnoreCase("esun")) - { - isStorm = false; - } - else if (commandLabel.equalsIgnoreCase("storm") || commandLabel.equalsIgnoreCase("estorm") - || commandLabel.equalsIgnoreCase("rain") || commandLabel.equalsIgnoreCase("erain")) - { - isStorm = true; - } - else - { - throw new NotEnoughArgumentsException(); - } - } - else - { - isStorm = args[0].equalsIgnoreCase("storm"); - } - final World world = user.getWorld(); - if (args.length > 1) - { +public class Commandweather extends EssentialsCommand { + public Commandweather() { + super("weather"); + } - world.setStorm(isStorm); - world.setWeatherDuration(Integer.parseInt(args[1]) * 20); - user.sendMessage(isStorm - ? tl("weatherStormFor", world.getName(), args[1]) - : tl("weatherSunFor", world.getName(), args[1])); - } - else - { - world.setStorm(isStorm); - user.sendMessage(isStorm - ? tl("weatherStorm", world.getName()) - : tl("weatherSun", world.getName())); - } - } + //TODO: Remove duplication + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + final boolean isStorm; + if (args.length < 1) { + if (commandLabel.equalsIgnoreCase("sun") || commandLabel.equalsIgnoreCase("esun")) { + isStorm = false; + } else if (commandLabel.equalsIgnoreCase("storm") || commandLabel.equalsIgnoreCase("estorm") || commandLabel.equalsIgnoreCase("rain") || commandLabel.equalsIgnoreCase("erain")) { + isStorm = true; + } else { + throw new NotEnoughArgumentsException(); + } + } else { + isStorm = args[0].equalsIgnoreCase("storm"); + } + final World world = user.getWorld(); + if (args.length > 1) { - @Override - protected void run(final Server server, final CommandSource 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: /" + commandLabel + " [duration]"); - } + world.setStorm(isStorm); + world.setWeatherDuration(Integer.parseInt(args[1]) * 20); + user.sendMessage(isStorm ? tl("weatherStormFor", world.getName(), args[1]) : tl("weatherSunFor", world.getName(), args[1])); + } else { + world.setStorm(isStorm); + user.sendMessage(isStorm ? tl("weatherStorm", world.getName()) : tl("weatherSun", world.getName())); + } + } - final boolean isStorm = args[1].equalsIgnoreCase("storm"); - final World world = server.getWorld(args[0]); - if (world == null) - { - throw new Exception(tl("weatherInvalidWorld", args[0])); - } - if (args.length > 2) - { + @Override + protected void run(final Server server, final CommandSource 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: /" + commandLabel + " [duration]"); + } - world.setStorm(isStorm); - world.setWeatherDuration(Integer.parseInt(args[2]) * 20); - sender.sendMessage(isStorm - ? tl("weatherStormFor", world.getName(), args[2]) - : tl("weatherSunFor", world.getName(), args[2])); - } - else - { - world.setStorm(isStorm); - sender.sendMessage(isStorm - ? tl("weatherStorm", world.getName()) - : tl("weatherSun", world.getName())); - } - } + final boolean isStorm = args[1].equalsIgnoreCase("storm"); + final World world = server.getWorld(args[0]); + if (world == null) { + throw new Exception(tl("weatherInvalidWorld", args[0])); + } + if (args.length > 2) { + + world.setStorm(isStorm); + world.setWeatherDuration(Integer.parseInt(args[2]) * 20); + sender.sendMessage(isStorm ? tl("weatherStormFor", world.getName(), args[2]) : tl("weatherSunFor", world.getName(), args[2])); + } else { + world.setStorm(isStorm); + sender.sendMessage(isStorm ? tl("weatherStorm", world.getName()) : tl("weatherSun", world.getName())); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandwhois.java b/Essentials/src/com/earth2me/essentials/commands/Commandwhois.java index a22bd4870..a7d87d948 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandwhois.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandwhois.java @@ -1,65 +1,52 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import com.earth2me.essentials.craftbukkit.SetExpFix; import com.earth2me.essentials.utils.DateUtil; import com.earth2me.essentials.utils.NumberUtil; -import java.util.Locale; import org.bukkit.Server; +import java.util.Locale; -public class Commandwhois extends EssentialsCommand -{ - public Commandwhois() - { - super("whois"); - } +import static com.earth2me.essentials.I18n.tl; - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } - User user = getPlayer(server, sender, args, 0); +public class Commandwhois extends EssentialsCommand { + public Commandwhois() { + super("whois"); + } - sender.sendMessage(tl("whoisTop", user.getName())); - user.setDisplayNick(); - sender.sendMessage(tl("whoisNick", user.getDisplayName())); - sender.sendMessage(tl("whoisHealth", user.getBase().getHealth())); - sender.sendMessage(tl("whoisHunger", user.getBase().getFoodLevel(), user.getBase().getSaturation())); - sender.sendMessage(tl("whoisExp", SetExpFix.getTotalExperience(user.getBase()), user.getBase().getLevel())); - sender.sendMessage(tl("whoisLocation", user.getLocation().getWorld().getName(), user.getLocation().getBlockX(), user.getLocation().getBlockY(), user.getLocation().getBlockZ())); - if (!ess.getSettings().isEcoDisabled()) - { - sender.sendMessage(tl("whoisMoney", NumberUtil.displayCurrency(user.getMoney(), ess))); - } - sender.sendMessage(tl("whoisIPAddress", user.getBase().getAddress().getAddress().toString())); - final String location = user.getGeoLocation(); - if (location != null - && (sender.isPlayer() ? ess.getUser(sender.getPlayer()).isAuthorized("essentials.geoip.show") : true)) - { - sender.sendMessage(tl("whoisGeoLocation", location)); - } - sender.sendMessage(tl("whoisGamemode", tl(user.getBase().getGameMode().toString().toLowerCase(Locale.ENGLISH)))); - sender.sendMessage(tl("whoisGod", (user.isGodModeEnabled() ? tl("true") : tl("false")))); - sender.sendMessage(tl("whoisOp", (user.getBase().isOp() ? tl("true") : tl("false")))); - sender.sendMessage(tl("whoisFly", user.getBase().getAllowFlight() ? tl("true") : tl("false"), user.getBase().isFlying() ? tl("flying") : tl("notFlying"))); - sender.sendMessage(tl("whoisAFK", (user.isAfk() ? tl("true") : tl("false")))); - sender.sendMessage(tl("whoisJail", (user.isJailed() - ? user.getJailTimeout() > 0 - ? DateUtil.formatDateDiff(user.getJailTimeout()) - : tl("true") - : tl("false")))); - sender.sendMessage(tl("whoisMuted", (user.isMuted() - ? user.getMuteTimeout() > 0 - ? DateUtil.formatDateDiff(user.getMuteTimeout()) - : tl("true") - : tl("false")))); + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } - } + User user = getPlayer(server, sender, args, 0); + + sender.sendMessage(tl("whoisTop", user.getName())); + user.setDisplayNick(); + sender.sendMessage(tl("whoisNick", user.getDisplayName())); + sender.sendMessage(tl("whoisHealth", user.getBase().getHealth())); + sender.sendMessage(tl("whoisHunger", user.getBase().getFoodLevel(), user.getBase().getSaturation())); + sender.sendMessage(tl("whoisExp", SetExpFix.getTotalExperience(user.getBase()), user.getBase().getLevel())); + sender.sendMessage(tl("whoisLocation", user.getLocation().getWorld().getName(), user.getLocation().getBlockX(), user.getLocation().getBlockY(), user.getLocation().getBlockZ())); + if (!ess.getSettings().isEcoDisabled()) { + sender.sendMessage(tl("whoisMoney", NumberUtil.displayCurrency(user.getMoney(), ess))); + } + sender.sendMessage(tl("whoisIPAddress", user.getBase().getAddress().getAddress().toString())); + final String location = user.getGeoLocation(); + if (location != null && (sender.isPlayer() ? ess.getUser(sender.getPlayer()).isAuthorized("essentials.geoip.show") : true)) { + sender.sendMessage(tl("whoisGeoLocation", location)); + } + sender.sendMessage(tl("whoisGamemode", tl(user.getBase().getGameMode().toString().toLowerCase(Locale.ENGLISH)))); + sender.sendMessage(tl("whoisGod", (user.isGodModeEnabled() ? tl("true") : tl("false")))); + sender.sendMessage(tl("whoisOp", (user.getBase().isOp() ? tl("true") : tl("false")))); + sender.sendMessage(tl("whoisFly", user.getBase().getAllowFlight() ? tl("true") : tl("false"), user.getBase().isFlying() ? tl("flying") : tl("notFlying"))); + sender.sendMessage(tl("whoisAFK", (user.isAfk() ? tl("true") : tl("false")))); + sender.sendMessage(tl("whoisJail", (user.isJailed() ? user.getJailTimeout() > 0 ? DateUtil.formatDateDiff(user.getJailTimeout()) : tl("true") : tl("false")))); + sender.sendMessage(tl("whoisMuted", (user.isMuted() ? user.getMuteTimeout() > 0 ? DateUtil.formatDateDiff(user.getMuteTimeout()) : tl("true") : tl("false")))); + + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandworkbench.java b/Essentials/src/com/earth2me/essentials/commands/Commandworkbench.java index 61b0f19f4..47d2efc49 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandworkbench.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandworkbench.java @@ -4,17 +4,14 @@ import com.earth2me.essentials.User; import org.bukkit.Server; -public class Commandworkbench extends EssentialsCommand -{ - public Commandworkbench() - { - super("workbench"); - } +public class Commandworkbench extends EssentialsCommand { + public Commandworkbench() { + super("workbench"); + } - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - user.getBase().openWorkbench(null, true); - } + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + user.getBase().openWorkbench(null, true); + } } \ No newline at end of file diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandworld.java b/Essentials/src/com/earth2me/essentials/commands/Commandworld.java index 1a6d3ea7b..66042a71b 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandworld.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandworld.java @@ -1,84 +1,70 @@ package com.earth2me.essentials.commands; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.Trade; import com.earth2me.essentials.User; -import java.util.List; import org.bukkit.Location; import org.bukkit.Server; import org.bukkit.World; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; +import java.util.List; -public class Commandworld extends EssentialsCommand -{ - public Commandworld() - { - super("world"); - } +import static com.earth2me.essentials.I18n.tl; - @Override - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - World world; - if (args.length < 1) - { - World nether = null; +public class Commandworld extends EssentialsCommand { + public Commandworld() { + super("world"); + } - final List worlds = server.getWorlds(); + @Override + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + World world; - 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(tl("invalidWorld")); - user.sendMessage(tl("possibleWorlds", server.getWorlds().size() - 1)); - user.sendMessage(tl("typeWorldName")); - throw new NoChargeException(); - } - } + if (args.length < 1) { + World nether = null; - if (ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + world.getName())) - { - throw new Exception(tl("noPerm", "essentials.worlds." + world.getName())); - } + final List worlds = server.getWorlds(); - 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; - } + 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(tl("invalidWorld")); + user.sendMessage(tl("possibleWorlds", server.getWorlds().size() - 1)); + user.sendMessage(tl("typeWorldName")); + throw new NoChargeException(); + } + } - final Location loc = user.getLocation(); - final Location target = new Location(world, loc.getBlockX() * factor + .5, loc.getBlockY(), loc.getBlockZ() * factor + .5); + if (ess.getSettings().isWorldTeleportPermissions() && !user.isAuthorized("essentials.worlds." + world.getName())) { + throw new Exception(tl("noPerm", "essentials.worlds." + world.getName())); + } - final Trade charge = new Trade(this.getName(), ess); - charge.isAffordableFor(user); - user.getTeleport().teleport(target, charge, TeleportCause.COMMAND); - 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(this.getName(), 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 index 648eb4139..7ed8598ad 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandworth.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandworth.java @@ -1,137 +1,101 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.NumberUtil; -import java.math.BigDecimal; -import java.util.List; -import java.util.Locale; import org.bukkit.Server; import org.bukkit.inventory.ItemStack; +import java.math.BigDecimal; +import java.util.List; +import java.util.Locale; -public class Commandworth extends EssentialsCommand -{ - public Commandworth() - { - super("worth"); - } +import static com.earth2me.essentials.I18n.tl; - @Override - public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - BigDecimal totalWorth = BigDecimal.ZERO; - String type = ""; - List is = ess.getItemDb().getMatching(user, args); - int count = 0; +public class Commandworth extends EssentialsCommand { + public Commandworth() { + super("worth"); + } - boolean isBulk = is.size() > 1; + @Override + public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + BigDecimal totalWorth = BigDecimal.ZERO; + String type = ""; - for (ItemStack stack : is) - { - try - { - if (stack.getAmount() > 0) - { - totalWorth = totalWorth.add(itemWorth(user.getSource(), user, stack, args)); - stack = stack.clone(); - count++; - for (ItemStack zeroStack : is) - { - if (zeroStack.isSimilar(stack)) - { - zeroStack.setAmount(0); - } - } - } + List is = ess.getItemDb().getMatching(user, args); + int count = 0; - } - catch (Exception e) - { - if (!isBulk) - { - throw e; - } - } - } - if (count > 1) - { - if (args.length > 0 && args[0].equalsIgnoreCase("blocks")) - { - user.sendMessage(tl("totalSellableBlocks", type, NumberUtil.displayCurrency(totalWorth, ess))); - } - else - { - user.sendMessage(tl("totalSellableAll", type, NumberUtil.displayCurrency(totalWorth, ess))); - } - } - } + boolean isBulk = is.size() > 1; - @Override - public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - if (args.length < 1) - { - throw new NotEnoughArgumentsException(); - } + for (ItemStack stack : is) { + try { + if (stack.getAmount() > 0) { + totalWorth = totalWorth.add(itemWorth(user.getSource(), user, stack, args)); + stack = stack.clone(); + count++; + for (ItemStack zeroStack : is) { + if (zeroStack.isSimilar(stack)) { + zeroStack.setAmount(0); + } + } + } - ItemStack stack = ess.getItemDb().get(args[0]); + } catch (Exception e) { + if (!isBulk) { + throw e; + } + } + } + if (count > 1) { + if (args.length > 0 && args[0].equalsIgnoreCase("blocks")) { + user.sendMessage(tl("totalSellableBlocks", type, NumberUtil.displayCurrency(totalWorth, ess))); + } else { + user.sendMessage(tl("totalSellableAll", type, NumberUtil.displayCurrency(totalWorth, ess))); + } + } + } - itemWorth(sender, null, stack, args); - } + @Override + public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + if (args.length < 1) { + throw new NotEnoughArgumentsException(); + } - private BigDecimal itemWorth(CommandSource sender, User user, ItemStack is, String[] args) throws Exception - { - int amount = 1; - if (user == null) - { - if (args.length > 1) - { - try - { - amount = Integer.parseInt(args[1].replaceAll("[^0-9]", "")); - } - catch (NumberFormatException ex) - { - throw new NotEnoughArgumentsException(ex); - } + ItemStack stack = ess.getItemDb().get(args[0]); - } - } - else - { - amount = ess.getWorth().getAmount(ess, user, is, args, true); - } + itemWorth(sender, null, stack, args); + } - BigDecimal worth = ess.getWorth().getPrice(is); + private BigDecimal itemWorth(CommandSource sender, User user, ItemStack is, String[] args) throws Exception { + int amount = 1; + if (user == null) { + if (args.length > 1) { + try { + amount = Integer.parseInt(args[1].replaceAll("[^0-9]", "")); + } catch (NumberFormatException ex) { + throw new NotEnoughArgumentsException(ex); + } - if (worth == null) - { - throw new Exception(tl("itemCannotBeSold")); - } + } + } else { + amount = ess.getWorth().getAmount(ess, user, is, args, true); + } - if (amount < 0) - { - amount = 0; - } + BigDecimal worth = ess.getWorth().getPrice(is); - BigDecimal result = worth.multiply(BigDecimal.valueOf(amount)); + if (worth == null) { + throw new Exception(tl("itemCannotBeSold")); + } - sender.sendMessage(is.getDurability() != 0 - ? tl("worthMeta", - is.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""), - is.getDurability(), - NumberUtil.displayCurrency(result, ess), - amount, - NumberUtil.displayCurrency(worth, ess)) - : tl("worth", - is.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""), - NumberUtil.displayCurrency(result, ess), - amount, - NumberUtil.displayCurrency(worth, ess))); + if (amount < 0) { + amount = 0; + } - return result; - } + BigDecimal result = worth.multiply(BigDecimal.valueOf(amount)); + + sender.sendMessage(is.getDurability() != 0 ? tl("worthMeta", is.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""), is.getDurability(), NumberUtil.displayCurrency(result, ess), amount, NumberUtil.displayCurrency(worth, ess)) : tl("worth", is.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", ""), NumberUtil.displayCurrency(result, ess), amount, NumberUtil.displayCurrency(worth, ess))); + + return result; + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java b/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java index bfd1843be..048c51a2f 100644 --- a/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java +++ b/Essentials/src/com/earth2me/essentials/commands/EssentialsCommand.java @@ -1,243 +1,197 @@ package com.earth2me.essentials.commands; -import com.earth2me.essentials.*; -import static com.earth2me.essentials.I18n.tl; +import com.earth2me.essentials.CommandSource; +import com.earth2me.essentials.IEssentialsModule; +import com.earth2me.essentials.Trade; +import com.earth2me.essentials.User; import com.earth2me.essentials.utils.FormatUtil; -import java.util.List; -import java.util.Locale; -import java.util.UUID; -import java.util.logging.Logger; import net.ess3.api.IEssentials; import org.bukkit.Server; import org.bukkit.command.Command; import org.bukkit.entity.Player; +import java.util.List; +import java.util.Locale; +import java.util.UUID; +import java.util.logging.Logger; -public abstract class EssentialsCommand implements IEssentialsCommand -{ - private final transient String name; - protected transient IEssentials ess; - protected transient IEssentialsModule module; - protected static final Logger logger = Logger.getLogger("Essentials"); +import static com.earth2me.essentials.I18n.tl; - protected EssentialsCommand(final String name) - { - this.name = name; - } - @Override - public void setEssentials(final IEssentials ess) - { - this.ess = ess; - } +public abstract class EssentialsCommand implements IEssentialsCommand { + private final transient String name; + protected transient IEssentials ess; + protected transient IEssentialsModule module; + protected static final Logger logger = Logger.getLogger("Essentials"); - @Override - public void setEssentialsModule(final IEssentialsModule module) - { - this.module = module; - } + protected EssentialsCommand(final String name) { + this.name = name; + } - @Override - public String getName() - { - return name; - } + @Override + public void setEssentials(final IEssentials ess) { + this.ess = ess; + } - // Get online players - only show vanished if source has permission - protected User getPlayer(final Server server, final CommandSource sender, final String[] args, final int pos) throws PlayerNotFoundException, NotEnoughArgumentsException - { - if (sender.isPlayer()) - { - User user = ess.getUser(sender.getPlayer()); - return getPlayer(server, user, args, pos); - } - return getPlayer(server, args, pos, true, false); - } + @Override + public void setEssentialsModule(final IEssentialsModule module) { + this.module = module; + } - // Get online players - only show vanished if source has permission - protected User getPlayer(final Server server, final CommandSource sender, final String searchTerm) throws PlayerNotFoundException, NotEnoughArgumentsException - { - if (sender.isPlayer()) - { - User user = ess.getUser(sender.getPlayer()); - return getPlayer(server, user, searchTerm, user.canInteractVanished(), false); - } - return getPlayer(server, searchTerm, true, false); - } + @Override + public String getName() { + return name; + } - // Get online players - only show vanished if source has permission - protected User getPlayer(final Server server, final User user, final String[] args, final int pos) throws PlayerNotFoundException, NotEnoughArgumentsException - { - return getPlayer(server, user, args, pos, user.canInteractVanished(), false); - } + // Get online players - only show vanished if source has permission + protected User getPlayer(final Server server, final CommandSource sender, final String[] args, final int pos) throws PlayerNotFoundException, NotEnoughArgumentsException { + if (sender.isPlayer()) { + User user = ess.getUser(sender.getPlayer()); + return getPlayer(server, user, args, pos); + } + return getPlayer(server, args, pos, true, false); + } - // Get online or offline players, this method allows for raw access - protected User getPlayer(final Server server, final String[] args, final int pos, boolean getHidden, final boolean getOffline) throws PlayerNotFoundException, NotEnoughArgumentsException - { - return getPlayer(server, null, args, pos, getHidden, getOffline); - } + // Get online players - only show vanished if source has permission + protected User getPlayer(final Server server, final CommandSource sender, final String searchTerm) throws PlayerNotFoundException, NotEnoughArgumentsException { + if (sender.isPlayer()) { + User user = ess.getUser(sender.getPlayer()); + return getPlayer(server, user, searchTerm, user.canInteractVanished(), false); + } + return getPlayer(server, searchTerm, true, false); + } - private User getPlayer(final Server server, final User sourceUser, final String[] args, final int pos, boolean getHidden, final boolean getOffline) throws PlayerNotFoundException, NotEnoughArgumentsException - { - if (args.length <= pos) - { - throw new NotEnoughArgumentsException(); - } - if (args[pos].isEmpty()) - { - throw new PlayerNotFoundException(); - } - return getPlayer(server, sourceUser, args[pos], getHidden, getOffline); - } + // Get online players - only show vanished if source has permission + protected User getPlayer(final Server server, final User user, final String[] args, final int pos) throws PlayerNotFoundException, NotEnoughArgumentsException { + return getPlayer(server, user, args, pos, user.canInteractVanished(), false); + } - // Get online or offline players, this method allows for raw access - protected User getPlayer(final Server server, final String searchTerm, boolean getHidden, final boolean getOffline) throws PlayerNotFoundException - { - return getPlayer(server, null, searchTerm, getHidden, getOffline); - } + // Get online or offline players, this method allows for raw access + protected User getPlayer(final Server server, final String[] args, final int pos, boolean getHidden, final boolean getOffline) throws PlayerNotFoundException, NotEnoughArgumentsException { + return getPlayer(server, null, args, pos, getHidden, getOffline); + } - private User getPlayer(final Server server, final User sourceUser, final String searchTerm, boolean getHidden, final boolean getOffline) throws PlayerNotFoundException - { - final User user; - Player exPlayer; + private User getPlayer(final Server server, final User sourceUser, final String[] args, final int pos, boolean getHidden, final boolean getOffline) throws PlayerNotFoundException, NotEnoughArgumentsException { + if (args.length <= pos) { + throw new NotEnoughArgumentsException(); + } + if (args[pos].isEmpty()) { + throw new PlayerNotFoundException(); + } + return getPlayer(server, sourceUser, args[pos], getHidden, getOffline); + } - try - { - exPlayer = server.getPlayer(UUID.fromString(searchTerm)); - } - catch (IllegalArgumentException ex) - { - exPlayer = server.getPlayer(searchTerm); - } + // Get online or offline players, this method allows for raw access + protected User getPlayer(final Server server, final String searchTerm, boolean getHidden, final boolean getOffline) throws PlayerNotFoundException { + return getPlayer(server, null, searchTerm, getHidden, getOffline); + } - if (exPlayer != null) - { - user = ess.getUser(exPlayer); - } - else - { - user = ess.getUser(searchTerm); - } + private User getPlayer(final Server server, final User sourceUser, final String searchTerm, boolean getHidden, final boolean getOffline) throws PlayerNotFoundException { + final User user; + Player exPlayer; - if (user != null) - { - if (!getOffline && !user.getBase().isOnline()) - { - throw new PlayerNotFoundException(); - } + try { + exPlayer = server.getPlayer(UUID.fromString(searchTerm)); + } catch (IllegalArgumentException ex) { + exPlayer = server.getPlayer(searchTerm); + } - if (getHidden || canInteractWith(sourceUser, user)) - { - return user; - } - throw new PlayerNotFoundException(); - } - final List matches = server.matchPlayer(searchTerm); + if (exPlayer != null) { + user = ess.getUser(exPlayer); + } else { + user = ess.getUser(searchTerm); + } - if (matches.isEmpty()) - { - final String matchText = searchTerm.toLowerCase(Locale.ENGLISH); - for (User userMatch : ess.getOnlineUsers()) - { - if (getHidden || canInteractWith(sourceUser, userMatch)) - { - final String displayName = FormatUtil.stripFormat(userMatch.getDisplayName()).toLowerCase(Locale.ENGLISH); - if (displayName.contains(matchText)) - { - return userMatch; - } - } - } - } - else - { - for (Player player : matches) - { - final User userMatch = ess.getUser(player); - if (userMatch.getDisplayName().startsWith(searchTerm) && (getHidden || canInteractWith(sourceUser, userMatch))) - { - return userMatch; - } - } - final User userMatch = ess.getUser(matches.get(0)); - if (getHidden || canInteractWith(sourceUser, userMatch)) - { - return userMatch; - } - } - throw new PlayerNotFoundException(); - } + if (user != null) { + if (!getOffline && !user.getBase().isOnline()) { + throw new PlayerNotFoundException(); + } - @Override - public final void run(final Server server, - final User user, - final String commandLabel, - final Command cmd, - final String[] args) throws Exception - { - final Trade charge = new Trade(this.getName(), ess); - charge.isAffordableFor(user); - run(server, user, commandLabel, args); - charge.charge(user); - } + if (getHidden || canInteractWith(sourceUser, user)) { + return user; + } + throw new PlayerNotFoundException(); + } + final List matches = server.matchPlayer(searchTerm); - protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception - { - run(server, user.getSource(), commandLabel, args); - } + if (matches.isEmpty()) { + final String matchText = searchTerm.toLowerCase(Locale.ENGLISH); + for (User userMatch : ess.getOnlineUsers()) { + if (getHidden || canInteractWith(sourceUser, userMatch)) { + final String displayName = FormatUtil.stripFormat(userMatch.getDisplayName()).toLowerCase(Locale.ENGLISH); + if (displayName.contains(matchText)) { + return userMatch; + } + } + } + } else { + for (Player player : matches) { + final User userMatch = ess.getUser(player); + if (userMatch.getDisplayName().startsWith(searchTerm) && (getHidden || canInteractWith(sourceUser, userMatch))) { + return userMatch; + } + } + final User userMatch = ess.getUser(matches.get(0)); + if (getHidden || canInteractWith(sourceUser, userMatch)) { + return userMatch; + } + } + throw new PlayerNotFoundException(); + } - @Override - public final void run(final Server server, final CommandSource sender, final String commandLabel, final Command cmd, final String[] args) throws Exception - { - run(server, sender, commandLabel, args); - } + @Override + public final void run(final Server server, final User user, final String commandLabel, final Command cmd, final String[] args) throws Exception { + final Trade charge = new Trade(this.getName(), ess); + charge.isAffordableFor(user); + run(server, user, commandLabel, args); + charge.charge(user); + } - protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception - { - throw new Exception(tl("onlyPlayers", commandLabel)); - } + protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { + run(server, user.getSource(), commandLabel, args); + } - 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 final void run(final Server server, final CommandSource sender, final String commandLabel, final Command cmd, final String[] args) throws Exception { + run(server, sender, commandLabel, args); + } - boolean canInteractWith(CommandSource interactor, User interactee) - { - if (interactor == null) - { - return !interactee.isHidden(); - } + protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { + throw new Exception(tl("onlyPlayers", commandLabel)); + } - if (interactor.isPlayer()) - { - return canInteractWith(ess.getUser(interactor.getPlayer()), interactee); - } + 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(); + } - return true; // console - } + boolean canInteractWith(CommandSource interactor, User interactee) { + if (interactor == null) { + return !interactee.isHidden(); + } - private static boolean canInteractWith(User interactor, User interactee) - { - if (interactor == null) - { - return !interactee.isHidden(); - } + if (interactor.isPlayer()) { + return canInteractWith(ess.getUser(interactor.getPlayer()), interactee); + } - if (interactor.equals(interactee)) - { - return true; - } + return true; // console + } - return interactor.getBase().canSee(interactee.getBase()); - } + private static boolean canInteractWith(User interactor, User interactee) { + if (interactor == null) { + return !interactee.isHidden(); + } + + if (interactor.equals(interactee)) { + return true; + } + + return interactor.getBase().canSee(interactee.getBase()); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/EssentialsLoopCommand.java b/Essentials/src/com/earth2me/essentials/commands/EssentialsLoopCommand.java index ccb297f14..ed3444149 100644 --- a/Essentials/src/com/earth2me/essentials/commands/EssentialsLoopCommand.java +++ b/Essentials/src/com/earth2me/essentials/commands/EssentialsLoopCommand.java @@ -4,146 +4,108 @@ import com.earth2me.essentials.ChargeException; import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.FormatUtil; -import java.util.List; -import java.util.Locale; -import java.util.UUID; import net.ess3.api.MaxMoneyException; import org.bukkit.Server; import org.bukkit.entity.Player; +import java.util.List; +import java.util.Locale; +import java.util.UUID; -public abstract class EssentialsLoopCommand extends EssentialsCommand -{ - public EssentialsLoopCommand(String command) - { - super(command); - } - protected void loopOfflinePlayers(final Server server, final CommandSource sender, final boolean multipleStringMatches, boolean matchWildcards, final String searchTerm, final String[] commandArgs) - throws PlayerNotFoundException, NotEnoughArgumentsException, PlayerExemptException, ChargeException, MaxMoneyException - { - if (searchTerm.isEmpty()) - { - throw new PlayerNotFoundException(); - } +public abstract class EssentialsLoopCommand extends EssentialsCommand { + public EssentialsLoopCommand(String command) { + super(command); + } - if (matchWildcards && searchTerm.contentEquals("**")) - { - for (UUID sUser : ess.getUserMap().getAllUniqueUsers()) - { - final User matchedUser = ess.getUser(sUser); - updatePlayer(server, sender, matchedUser, commandArgs); - } - } - else if (matchWildcards && searchTerm.contentEquals("*")) - { - boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished(); - for (User onlineUser : ess.getOnlineUsers()) - { - if (skipHidden && onlineUser.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(onlineUser.getBase())) - { - continue; - } - updatePlayer(server, sender, onlineUser, commandArgs); - } - } - else if (multipleStringMatches) - { - if (searchTerm.trim().length() < 3) - { - throw new PlayerNotFoundException(); - } - final List matchedPlayers = server.matchPlayer(searchTerm); - if (matchedPlayers.isEmpty()) - { - final User matchedUser = getPlayer(server, searchTerm, true, true); - updatePlayer(server, sender, matchedUser, commandArgs); - } - for (Player matchPlayer : matchedPlayers) - { - final User matchedUser = ess.getUser(matchPlayer); - updatePlayer(server, sender, matchedUser, commandArgs); - } - } - else - { - final User user = getPlayer(server, searchTerm, true, true); - updatePlayer(server, sender, user, commandArgs); - } - } + protected void loopOfflinePlayers(final Server server, final CommandSource sender, final boolean multipleStringMatches, boolean matchWildcards, final String searchTerm, final String[] commandArgs) throws PlayerNotFoundException, NotEnoughArgumentsException, PlayerExemptException, ChargeException, MaxMoneyException { + if (searchTerm.isEmpty()) { + throw new PlayerNotFoundException(); + } - protected void loopOnlinePlayers(final Server server, final CommandSource sender, final boolean multipleStringMatches, boolean matchWildcards, final String searchTerm, final String[] commandArgs) - throws PlayerNotFoundException, NotEnoughArgumentsException, PlayerExemptException, ChargeException, MaxMoneyException - { - if (searchTerm.isEmpty()) - { - throw new PlayerNotFoundException(); - } + if (matchWildcards && searchTerm.contentEquals("**")) { + for (UUID sUser : ess.getUserMap().getAllUniqueUsers()) { + final User matchedUser = ess.getUser(sUser); + updatePlayer(server, sender, matchedUser, commandArgs); + } + } else if (matchWildcards && searchTerm.contentEquals("*")) { + boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished(); + for (User onlineUser : ess.getOnlineUsers()) { + if (skipHidden && onlineUser.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(onlineUser.getBase())) { + continue; + } + updatePlayer(server, sender, onlineUser, commandArgs); + } + } else if (multipleStringMatches) { + if (searchTerm.trim().length() < 3) { + throw new PlayerNotFoundException(); + } + final List matchedPlayers = server.matchPlayer(searchTerm); + if (matchedPlayers.isEmpty()) { + final User matchedUser = getPlayer(server, searchTerm, true, true); + updatePlayer(server, sender, matchedUser, commandArgs); + } + for (Player matchPlayer : matchedPlayers) { + final User matchedUser = ess.getUser(matchPlayer); + updatePlayer(server, sender, matchedUser, commandArgs); + } + } else { + final User user = getPlayer(server, searchTerm, true, true); + updatePlayer(server, sender, user, commandArgs); + } + } - boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished(); + protected void loopOnlinePlayers(final Server server, final CommandSource sender, final boolean multipleStringMatches, boolean matchWildcards, final String searchTerm, final String[] commandArgs) throws PlayerNotFoundException, NotEnoughArgumentsException, PlayerExemptException, ChargeException, MaxMoneyException { + if (searchTerm.isEmpty()) { + throw new PlayerNotFoundException(); + } - if (matchWildcards && (searchTerm.contentEquals("**") || searchTerm.contentEquals("*"))) - { - for (User onlineUser : ess.getOnlineUsers()) - { - if (skipHidden && onlineUser.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(onlineUser.getBase())) - { - continue; - } - updatePlayer(server, sender, onlineUser, commandArgs); - } - } - else if (multipleStringMatches) - { - if (searchTerm.trim().length() < 2) - { - throw new PlayerNotFoundException(); - } - boolean foundUser = false; - final List matchedPlayers = server.matchPlayer(searchTerm); + boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished(); - if (matchedPlayers.isEmpty()) - { - final String matchText = searchTerm.toLowerCase(Locale.ENGLISH); - for (User player : ess.getOnlineUsers()) - { - if (skipHidden && player.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(player.getBase())) - { - continue; - } - final String displayName = FormatUtil.stripFormat(player.getDisplayName()).toLowerCase(Locale.ENGLISH); - if (displayName.contains(matchText)) - { - foundUser = true; - updatePlayer(server, sender, player, commandArgs); - } - } - } - else - { - for (Player matchPlayer : matchedPlayers) - { - final User player = ess.getUser(matchPlayer); - if (skipHidden && player.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(matchPlayer)) - { - continue; - } - foundUser = true; - updatePlayer(server, sender, player, commandArgs); - } - } - if (!foundUser) - { - throw new PlayerNotFoundException(); - } - } - else - { - final User player = getPlayer(server, sender, searchTerm); - updatePlayer(server, sender, player, commandArgs); - } - } + if (matchWildcards && (searchTerm.contentEquals("**") || searchTerm.contentEquals("*"))) { + for (User onlineUser : ess.getOnlineUsers()) { + if (skipHidden && onlineUser.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(onlineUser.getBase())) { + continue; + } + updatePlayer(server, sender, onlineUser, commandArgs); + } + } else if (multipleStringMatches) { + if (searchTerm.trim().length() < 2) { + throw new PlayerNotFoundException(); + } + boolean foundUser = false; + final List matchedPlayers = server.matchPlayer(searchTerm); - protected abstract void updatePlayer(Server server, CommandSource sender, User user, String[] args) - throws NotEnoughArgumentsException, PlayerExemptException, ChargeException, MaxMoneyException; + if (matchedPlayers.isEmpty()) { + final String matchText = searchTerm.toLowerCase(Locale.ENGLISH); + for (User player : ess.getOnlineUsers()) { + if (skipHidden && player.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(player.getBase())) { + continue; + } + final String displayName = FormatUtil.stripFormat(player.getDisplayName()).toLowerCase(Locale.ENGLISH); + if (displayName.contains(matchText)) { + foundUser = true; + updatePlayer(server, sender, player, commandArgs); + } + } + } else { + for (Player matchPlayer : matchedPlayers) { + final User player = ess.getUser(matchPlayer); + if (skipHidden && player.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(matchPlayer)) { + continue; + } + foundUser = true; + updatePlayer(server, sender, player, commandArgs); + } + } + if (!foundUser) { + throw new PlayerNotFoundException(); + } + } else { + final User player = getPlayer(server, sender, searchTerm); + updatePlayer(server, sender, player, commandArgs); + } + } + + protected abstract void updatePlayer(Server server, CommandSource sender, User user, String[] args) throws NotEnoughArgumentsException, PlayerExemptException, ChargeException, MaxMoneyException; } diff --git a/Essentials/src/com/earth2me/essentials/commands/EssentialsToggleCommand.java b/Essentials/src/com/earth2me/essentials/commands/EssentialsToggleCommand.java index deed20a13..a88f18b9d 100644 --- a/Essentials/src/com/earth2me/essentials/commands/EssentialsToggleCommand.java +++ b/Essentials/src/com/earth2me/essentials/commands/EssentialsToggleCommand.java @@ -2,75 +2,59 @@ package com.earth2me.essentials.commands; import com.earth2me.essentials.CommandSource; import com.earth2me.essentials.User; -import java.util.List; import org.bukkit.Server; import org.bukkit.entity.Player; +import java.util.List; -public abstract class EssentialsToggleCommand extends EssentialsCommand -{ - String othersPermission; - public EssentialsToggleCommand(String command, String othersPermission) - { - super(command); - this.othersPermission = othersPermission; - } +public abstract class EssentialsToggleCommand extends EssentialsCommand { + String othersPermission; - protected Boolean matchToggleArgument(final String arg) - { - if (arg.equalsIgnoreCase("on") || arg.startsWith("ena") || arg.equalsIgnoreCase("1")) - { - return true; - } - else if (arg.equalsIgnoreCase("off") || arg.startsWith("dis") || arg.equalsIgnoreCase("0")) - { - return false; - } - return null; - } + public EssentialsToggleCommand(String command, String othersPermission) { + super(command); + this.othersPermission = othersPermission; + } - protected void toggleOtherPlayers(final Server server, final CommandSource sender, final String[] args) throws PlayerNotFoundException, NotEnoughArgumentsException - { - if (args.length < 1 || args[0].trim().length() < 2) - { - throw new PlayerNotFoundException(); - } + protected Boolean matchToggleArgument(final String arg) { + if (arg.equalsIgnoreCase("on") || arg.startsWith("ena") || arg.equalsIgnoreCase("1")) { + return true; + } else if (arg.equalsIgnoreCase("off") || arg.startsWith("dis") || arg.equalsIgnoreCase("0")) { + return false; + } + return null; + } - boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished(); - boolean foundUser = false; - final List matchedPlayers = server.matchPlayer(args[0]); - for (Player matchPlayer : matchedPlayers) - { - final User player = ess.getUser(matchPlayer); - if (skipHidden && player.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(matchPlayer)) - { - continue; - } - foundUser = true; - if (args.length > 1) - { - Boolean toggle = matchToggleArgument(args[1]); - if (toggle == true) - { - togglePlayer(sender, player, true); - } - else - { - togglePlayer(sender, player, false); - } - } - else - { - togglePlayer(sender, player, null); - } - } - if (!foundUser) - { - throw new PlayerNotFoundException(); - } - } + protected void toggleOtherPlayers(final Server server, final CommandSource sender, final String[] args) throws PlayerNotFoundException, NotEnoughArgumentsException { + if (args.length < 1 || args[0].trim().length() < 2) { + throw new PlayerNotFoundException(); + } - // Make sure when implementing this method that all 3 Boolean states are handled, 'null' should toggle the existing state. - abstract void togglePlayer(CommandSource sender, User user, Boolean enabled) throws NotEnoughArgumentsException; + boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished(); + boolean foundUser = false; + final List matchedPlayers = server.matchPlayer(args[0]); + for (Player matchPlayer : matchedPlayers) { + final User player = ess.getUser(matchPlayer); + if (skipHidden && player.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(matchPlayer)) { + continue; + } + foundUser = true; + if (args.length > 1) { + Boolean toggle = matchToggleArgument(args[1]); + if (toggle == true) { + togglePlayer(sender, player, true); + } else { + togglePlayer(sender, player, false); + } + } else { + togglePlayer(sender, player, null); + } + } + if (!foundUser) { + throw new PlayerNotFoundException(); + } + } + + // Make sure when implementing this method that all 3 Boolean states are handled, 'null' should toggle the existing state. + abstract void togglePlayer(CommandSource sender, User user, Boolean enabled) throws NotEnoughArgumentsException; } diff --git a/Essentials/src/com/earth2me/essentials/commands/IEssentialsCommand.java b/Essentials/src/com/earth2me/essentials/commands/IEssentialsCommand.java index 1eb241888..247adf6da 100644 --- a/Essentials/src/com/earth2me/essentials/commands/IEssentialsCommand.java +++ b/Essentials/src/com/earth2me/essentials/commands/IEssentialsCommand.java @@ -8,17 +8,14 @@ import org.bukkit.Server; import org.bukkit.command.Command; -public interface IEssentialsCommand -{ - String getName(); +public interface IEssentialsCommand { + String getName(); - void run(Server server, User user, String commandLabel, Command cmd, String[] args) - throws Exception; + void run(Server server, User user, String commandLabel, Command cmd, String[] args) throws Exception; - void run(Server server, CommandSource sender, String commandLabel, Command cmd, String[] args) - throws Exception; + void run(Server server, CommandSource sender, String commandLabel, Command cmd, String[] args) throws Exception; - void setEssentials(IEssentials ess); + void setEssentials(IEssentials ess); - void setEssentialsModule(IEssentialsModule module); + void setEssentialsModule(IEssentialsModule module); } diff --git a/Essentials/src/com/earth2me/essentials/commands/NoChargeException.java b/Essentials/src/com/earth2me/essentials/commands/NoChargeException.java index bb0088792..c29f520bf 100644 --- a/Essentials/src/com/earth2me/essentials/commands/NoChargeException.java +++ b/Essentials/src/com/earth2me/essentials/commands/NoChargeException.java @@ -1,10 +1,8 @@ package com.earth2me.essentials.commands; -public class NoChargeException extends Exception -{ - public NoChargeException() - { - super("Will charge later"); - } +public class NoChargeException extends Exception { + public NoChargeException() { + super("Will charge later"); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/NotEnoughArgumentsException.java b/Essentials/src/com/earth2me/essentials/commands/NotEnoughArgumentsException.java index 0c47b9893..1978833e1 100644 --- a/Essentials/src/com/earth2me/essentials/commands/NotEnoughArgumentsException.java +++ b/Essentials/src/com/earth2me/essentials/commands/NotEnoughArgumentsException.java @@ -1,20 +1,16 @@ package com.earth2me.essentials.commands; -public class NotEnoughArgumentsException extends Exception -{ - public NotEnoughArgumentsException() - { - super(""); - } +public class NotEnoughArgumentsException extends Exception { + public NotEnoughArgumentsException() { + super(""); + } - public NotEnoughArgumentsException(final String string) - { - super(string); - } + public NotEnoughArgumentsException(final String string) { + super(string); + } - public NotEnoughArgumentsException(final Throwable ex) - { - super("", ex); - } + public NotEnoughArgumentsException(final Throwable ex) { + super("", ex); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/PlayerExemptException.java b/Essentials/src/com/earth2me/essentials/commands/PlayerExemptException.java index a916402aa..e95a4247c 100644 --- a/Essentials/src/com/earth2me/essentials/commands/PlayerExemptException.java +++ b/Essentials/src/com/earth2me/essentials/commands/PlayerExemptException.java @@ -1,9 +1,7 @@ package com.earth2me.essentials.commands; -public class PlayerExemptException extends NoSuchFieldException -{ - public PlayerExemptException(String message) - { - super(message); - } +public class PlayerExemptException extends NoSuchFieldException { + public PlayerExemptException(String message) { + super(message); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/PlayerNotFoundException.java b/Essentials/src/com/earth2me/essentials/commands/PlayerNotFoundException.java index 1f5a00fbd..21b130f5d 100644 --- a/Essentials/src/com/earth2me/essentials/commands/PlayerNotFoundException.java +++ b/Essentials/src/com/earth2me/essentials/commands/PlayerNotFoundException.java @@ -2,10 +2,8 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n.tl; -public class PlayerNotFoundException extends NoSuchFieldException -{ - public PlayerNotFoundException() - { - super(tl("playerNotFound")); - } +public class PlayerNotFoundException extends NoSuchFieldException { + public PlayerNotFoundException() { + super(tl("playerNotFound")); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/QuietAbortException.java b/Essentials/src/com/earth2me/essentials/commands/QuietAbortException.java index 2667ef0d3..397610c43 100644 --- a/Essentials/src/com/earth2me/essentials/commands/QuietAbortException.java +++ b/Essentials/src/com/earth2me/essentials/commands/QuietAbortException.java @@ -1,15 +1,12 @@ package com.earth2me.essentials.commands; -public class QuietAbortException extends Exception -{ - public QuietAbortException() - { - super(); - } +public class QuietAbortException extends Exception { + public QuietAbortException() { + super(); + } - public QuietAbortException(String message) - { - super(message); - } + public QuietAbortException(String message) { + super(message); + } } diff --git a/Essentials/src/com/earth2me/essentials/commands/WarpNotFoundException.java b/Essentials/src/com/earth2me/essentials/commands/WarpNotFoundException.java index 38573bfda..c6e4cdbf6 100644 --- a/Essentials/src/com/earth2me/essentials/commands/WarpNotFoundException.java +++ b/Essentials/src/com/earth2me/essentials/commands/WarpNotFoundException.java @@ -2,15 +2,12 @@ package com.earth2me.essentials.commands; import static com.earth2me.essentials.I18n.tl; -public class WarpNotFoundException extends Exception -{ - public WarpNotFoundException() - { - super(tl("warpNotExist")); - } - - public WarpNotFoundException(String message) - { - super(message); - } +public class WarpNotFoundException extends Exception { + public WarpNotFoundException() { + super(tl("warpNotExist")); + } + + public WarpNotFoundException(String message) { + super(message); + } } diff --git a/Essentials/src/com/earth2me/essentials/craftbukkit/BanLookup.java b/Essentials/src/com/earth2me/essentials/craftbukkit/BanLookup.java index e5d26667d..b20cded7d 100644 --- a/Essentials/src/com/earth2me/essentials/craftbukkit/BanLookup.java +++ b/Essentials/src/com/earth2me/essentials/craftbukkit/BanLookup.java @@ -1,36 +1,30 @@ package com.earth2me.essentials.craftbukkit; import com.earth2me.essentials.User; -import java.util.Iterator; -import java.util.Set; import net.ess3.api.IEssentials; import org.bukkit.BanEntry; import org.bukkit.BanList; +import java.util.Set; -public class BanLookup -{ - public static Boolean isBanned(IEssentials ess, User user) - { - return isBanned(ess, user.getName()); - } - public static Boolean isBanned(IEssentials ess, String name) - { - return getBanEntry(ess, name) != null; - } - - public static BanEntry getBanEntry(IEssentials ess, String name) - { - Set benteries = ess.getServer().getBanList(BanList.Type.NAME).getBanEntries(); - for (BanEntry banEnt : benteries) - { - if (banEnt.getTarget().equals(name)) - { - return banEnt; - } - } - return null; - } - +public class BanLookup { + public static Boolean isBanned(IEssentials ess, User user) { + return isBanned(ess, user.getName()); + } + + public static Boolean isBanned(IEssentials ess, String name) { + return getBanEntry(ess, name) != null; + } + + public static BanEntry getBanEntry(IEssentials ess, String name) { + Set benteries = ess.getServer().getBanList(BanList.Type.NAME).getBanEntries(); + for (BanEntry banEnt : benteries) { + if (banEnt.getTarget().equals(name)) { + return banEnt; + } + } + return null; + } + } diff --git a/Essentials/src/com/earth2me/essentials/craftbukkit/FakeWorld.java b/Essentials/src/com/earth2me/essentials/craftbukkit/FakeWorld.java index df7a237fa..7aebe31b6 100644 --- a/Essentials/src/com/earth2me/essentials/craftbukkit/FakeWorld.java +++ b/Essentials/src/com/earth2me/essentials/craftbukkit/FakeWorld.java @@ -1,10 +1,5 @@ package com.earth2me.essentials.craftbukkit; -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; @@ -16,729 +11,614 @@ 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() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @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 lctn, EntityType et) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isChunkInUse(int x, int z) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public FallingBlock spawnFallingBlock(Location location, Material material, byte data) throws IllegalArgumentException - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public FallingBlock spawnFallingBlock(Location location, int blockId, byte blockData) throws IllegalArgumentException - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void playSound(Location arg0, Sound arg1, float arg2, float arg3) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getAmbientSpawnLimit() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setAmbientSpawnLimit(int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public String[] getGameRules() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public String getGameRuleValue(String string) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean setGameRuleValue(String string, String string1) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isGameRule(String string) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean createExplosion(double d, double d1, double d2, float f, boolean bln, boolean bln1) - { - throw new UnsupportedOperationException("Not supported yet."); - } +import java.io.File; +import java.util.Collection; +import java.util.List; +import java.util.Set; +import java.util.UUID; + + +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() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @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 lctn, EntityType et) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isChunkInUse(int x, int z) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public FallingBlock spawnFallingBlock(Location location, Material material, byte data) throws IllegalArgumentException { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public FallingBlock spawnFallingBlock(Location location, int blockId, byte blockData) throws IllegalArgumentException { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void playSound(Location arg0, Sound arg1, float arg2, float arg3) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int getAmbientSpawnLimit() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setAmbientSpawnLimit(int i) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public String[] getGameRules() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public String getGameRuleValue(String string) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean setGameRuleValue(String string, String string1) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isGameRule(String string) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean createExplosion(double d, double d1, double d2, float f, boolean bln, boolean bln1) { + throw new UnsupportedOperationException("Not supported yet."); + } } diff --git a/Essentials/src/com/earth2me/essentials/craftbukkit/InventoryWorkaround.java b/Essentials/src/com/earth2me/essentials/craftbukkit/InventoryWorkaround.java index ac83645b0..713d69b36 100644 --- a/Essentials/src/com/earth2me/essentials/craftbukkit/InventoryWorkaround.java +++ b/Essentials/src/com/earth2me/essentials/craftbukkit/InventoryWorkaround.java @@ -1,162 +1,135 @@ package com.earth2me.essentials.craftbukkit; -import java.util.HashMap; -import java.util.Map; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; +import java.util.HashMap; +import java.util.Map; + /* * This class can be removed when https://github.com/Bukkit/CraftBukkit/pull/193 is accepted to CraftBukkit */ -public final class InventoryWorkaround -{ - private InventoryWorkaround() - { - } +public final class InventoryWorkaround { + private InventoryWorkaround() { + } - private static int firstPartial(final Inventory inventory, final ItemStack item, final int maxAmount) - { - if (item == null) - { - return -1; - } - final ItemStack[] stacks = inventory.getContents(); - for (int i = 0; i < stacks.length; i++) - { - final ItemStack cItem = stacks[i]; - if (cItem != null && cItem.getAmount() < maxAmount && cItem.isSimilar(item)) - { - return i; - } - } - return -1; - } + private static int firstPartial(final Inventory inventory, final ItemStack item, final int maxAmount) { + if (item == null) { + return -1; + } + final ItemStack[] stacks = inventory.getContents(); + for (int i = 0; i < stacks.length; i++) { + final ItemStack cItem = stacks[i]; + if (cItem != null && cItem.getAmount() < maxAmount && cItem.isSimilar(item)) { + return i; + } + } + return -1; + } - // Returns what it couldnt store - // This will will abort if it couldn't store all items - public static Map addAllItems(final Inventory inventory, final ItemStack... items) - { - final Inventory fakeInventory = Bukkit.getServer().createInventory(null, inventory.getType()); - fakeInventory.setContents(inventory.getContents()); - Map overFlow = addItems(fakeInventory, items); - if (overFlow.isEmpty()) - { - addItems(inventory, items); - return null; - } - return addItems(fakeInventory, items); - } + // Returns what it couldnt store + // This will will abort if it couldn't store all items + public static Map addAllItems(final Inventory inventory, final ItemStack... items) { + final Inventory fakeInventory = Bukkit.getServer().createInventory(null, inventory.getType()); + fakeInventory.setContents(inventory.getContents()); + Map overFlow = addItems(fakeInventory, items); + if (overFlow.isEmpty()) { + addItems(inventory, items); + return null; + } + return addItems(fakeInventory, items); + } - // Returns what it couldnt store - public static Map addItems(final Inventory inventory, final ItemStack... items) - { - return addOversizedItems(inventory, 0, items); - } + // Returns what it couldnt store + public static Map addItems(final Inventory inventory, final ItemStack... items) { + return addOversizedItems(inventory, 0, items); + } - // Returns what it couldnt store - // Set oversizedStack to below normal stack size to disable oversized stacks - public static Map addOversizedItems(final Inventory inventory, final int oversizedStacks, final ItemStack... items) - { - final Map leftover = new HashMap(); + // Returns what it couldnt store + // Set oversizedStack to below normal stack size to disable oversized stacks + public static Map addOversizedItems(final Inventory inventory, 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 - + * TODO: some optimization - Create a 'firstPartial' with a 'fromIndex' - Record the lastPartial per Material - * Cache firstEmpty result */ - // combine items + // combine items - final ItemStack[] combined = new ItemStack[items.length]; - for (ItemStack item : items) - { - if (item == null || item.getAmount() < 1) - { - continue; - } - for (int j = 0; j < combined.length; j++) - { - if (combined[j] == null) - { - combined[j] = item.clone(); - break; - } - if (combined[j].isSimilar(item)) - { - combined[j].setAmount(combined[j].getAmount() + item.getAmount()); - break; - } - } - } + final ItemStack[] combined = new ItemStack[items.length]; + for (ItemStack item : items) { + if (item == null || item.getAmount() < 1) { + continue; + } + for (int j = 0; j < combined.length; j++) { + if (combined[j] == null) { + combined[j] = item.clone(); + break; + } + if (combined[j].isSimilar(item)) { + combined[j].setAmount(combined[j].getAmount() + item.getAmount()); + break; + } + } + } - for (int i = 0; i < combined.length; i++) - { - final ItemStack item = combined[i]; - if (item == null || item.getType() == Material.AIR) - { - continue; - } + for (int i = 0; i < combined.length; i++) { + final ItemStack item = combined[i]; + if (item == null || item.getType() == Material.AIR) { + 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(inventory, item, maxAmount); + 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(inventory, item, maxAmount); - // Drat! no partial stack - if (firstPartial == -1) - { - // Find a free spot! - final int firstFree = inventory.firstEmpty(); + // Drat! no partial stack + if (firstPartial == -1) { + // Find a free spot! + final int firstFree = inventory.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); - inventory.setItem(firstFree, stack); - item.setAmount(item.getAmount() - maxAmount); - } - else - { - // Just store it - inventory.setItem(firstFree, item); - break; - } - } - } - else - { - // So, apparently it might only partially fit, well lets do just that - final ItemStack partialItem = inventory.getItem(firstPartial); + 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); + inventory.setItem(firstFree, stack); + item.setAmount(item.getAmount() - maxAmount); + } else { + // Just store it + inventory.setItem(firstFree, item); + break; + } + } + } else { + // So, apparently it might only partially fit, well lets do just that + final ItemStack partialItem = inventory.getItem(firstPartial); - final int amount = item.getAmount(); - final int partialAmount = partialItem.getAmount(); + final int amount = item.getAmount(); + final int partialAmount = partialItem.getAmount(); - // Check if it fully fits - if (amount + partialAmount <= maxAmount) - { - partialItem.setAmount(amount + partialAmount); - break; - } + // 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; - } + // It fits partially + partialItem.setAmount(maxAmount); + item.setAmount(amount + partialAmount - maxAmount); + } + } + } + return leftover; + } } diff --git a/Essentials/src/com/earth2me/essentials/craftbukkit/SetExpFix.java b/Essentials/src/com/earth2me/essentials/craftbukkit/SetExpFix.java index e484ebfe1..ad398f796 100644 --- a/Essentials/src/com/earth2me/essentials/craftbukkit/SetExpFix.java +++ b/Essentials/src/com/earth2me/essentials/craftbukkit/SetExpFix.java @@ -3,100 +3,82 @@ 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); +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 = getExpAtLevel(player); - amount -= expToLevel; - if (amount >= 0) - { - // give until next level - player.giveExp(expToLevel); - } - else - { - // give the rest - amount += expToLevel; - player.giveExp(amount); - amount = 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 = getExpAtLevel(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 getExpAtLevel(final Player player) - { - return getExpAtLevel(player.getLevel()); - } + private static int getExpAtLevel(final Player player) { + return getExpAtLevel(player.getLevel()); + } - public static int getExpAtLevel(final int level) - { - if (level > 29) - { - return 62 + (level - 30) * 7; - } - if (level > 15) - { - return 17 + (level - 15) * 3; - } - return 17; - } - - public static int getExpToLevel(final int level) - { - int currentLevel = 0; - int exp = 0; + public static int getExpAtLevel(final int level) { + if (level > 29) { + return 62 + (level - 30) * 7; + } + if (level > 15) { + return 17 + (level - 15) * 3; + } + return 17; + } - while (currentLevel < level) - { - exp += getExpAtLevel(currentLevel); - currentLevel++; - } - if (exp < 0) - { - exp = Integer.MAX_VALUE; - } - return exp; - } + public static int getExpToLevel(final int level) { + int currentLevel = 0; + int exp = 0; - //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(getExpAtLevel(player) * player.getExp()); - int currentLevel = player.getLevel(); + while (currentLevel < level) { + exp += getExpAtLevel(currentLevel); + currentLevel++; + } + if (exp < 0) { + exp = Integer.MAX_VALUE; + } + return exp; + } - while (currentLevel > 0) - { - currentLevel--; - exp += getExpAtLevel(currentLevel); - } - if (exp < 0) - { - exp = Integer.MAX_VALUE; - } - return exp; - } - - public static int getExpUntilNextLevel(final Player player) - { - int exp = (int)Math.round(getExpAtLevel(player) * player.getExp()); - int nextLevel = player.getLevel(); - return getExpAtLevel(nextLevel) - exp; - } + //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(getExpAtLevel(player) * player.getExp()); + int currentLevel = player.getLevel(); + + while (currentLevel > 0) { + currentLevel--; + exp += getExpAtLevel(currentLevel); + } + if (exp < 0) { + exp = Integer.MAX_VALUE; + } + return exp; + } + + public static int getExpUntilNextLevel(final Player player) { + int exp = (int) Math.round(getExpAtLevel(player) * player.getExp()); + int nextLevel = player.getLevel(); + return getExpAtLevel(nextLevel) - exp; + } } diff --git a/Essentials/src/com/earth2me/essentials/metrics/Metrics.java b/Essentials/src/com/earth2me/essentials/metrics/Metrics.java index 07229f091..2bee196d5 100644 --- a/Essentials/src/com/earth2me/essentials/metrics/Metrics.java +++ b/Essentials/src/com/earth2me/essentials/metrics/Metrics.java @@ -25,6 +25,13 @@ package com.earth2me.essentials.metrics; */ import com.earth2me.essentials.IEssentials; +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; +import org.bukkit.scheduler.BukkitTask; + import java.io.*; import java.net.Proxy; import java.net.URL; @@ -33,815 +40,706 @@ import java.net.URLEncoder; import java.util.*; import java.util.logging.Level; import java.util.zip.GZIPOutputStream; -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; -import org.bukkit.scheduler.BukkitTask; - -public class Metrics -{ - - /** - * The current revision number - */ - private static final int REVISION = 7; - - /** - * The base url of the metrics domain - */ - private static final String BASE_URL = "http://report-metrics.essentials3.net"; - - /** - * The url used to report a server's status - */ - private static final String REPORT_URL = "/plugin/%s"; - - /** - * Interval of time to ping (in minutes) - */ - private static final int PING_INTERVAL = 15; - - /** - * 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 plugin configuration file - */ - private final YamlConfiguration configuration; - - /** - * The plugin configuration file - */ - private final File configurationFile; - - /** - * Unique server id - */ - private final String guid; - - /** - * Debug mode - */ - private final boolean debug; - - /** - * Lock for synchronization - */ - private final Object optOutLock = new Object(); - - /** - * The scheduled task - */ - private volatile BukkitTask task = null; - - public Metrics(final Plugin plugin) throws IOException - { - if (plugin == null) - { - throw new IllegalArgumentException("Plugin cannot be null"); - } - - this.plugin = plugin; - - // load the config - configurationFile = getConfigFile(); - configuration = YamlConfiguration.loadConfiguration(configurationFile); - - // add some defaults - configuration.addDefault("opt-out", false); - configuration.addDefault("guid", UUID.randomUUID().toString()); - configuration.addDefault("debug", false); - - // Do we need to create the file? - if (configuration.get("guid", null) == null) - { - configuration.options().header("http://mcstats.org").copyDefaults(true); - configuration.save(configurationFile); - } - - // Load the guid then - guid = configuration.getString("guid"); - debug = configuration.getBoolean("debug", false); - } - - /** - * 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 The name of the graph - * @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; - } - - /** - * Add a Graph object to BukkitMetrics that represents data for the plugin that should be sent to the backend - * - * @param graph The name of the graph - */ - public void addGraph(final Graph graph) - { - if (graph == null) - { - throw new IllegalArgumentException("Graph cannot be null"); - } - - graphs.add(graph); - } - - /** - * 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; - } - - // Is metrics already running? - if (task != null) - { - return; - } - - // Begin hitting the server with glorious data - task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(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() && task != null) - { - task.cancel(); - task = null; - // Tell all plotters to stop gathering information. - for (Graph graph : graphs) - { - graph.onOptOut(); - } - } - } - - // 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) - { - if (debug) - { - Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage()); - } - } - } - }, 0, PING_INTERVAL * 1200); - } - } - - /** - * Has the server owner denied plugin metrics? - * - * @return true if metrics should be opted out of it - */ - public boolean isOptOut() - { - synchronized (optOutLock) - { - try - { - // Reload the metrics file - configuration.load(getConfigFile()); - } - catch (IOException ex) - { - if (debug) - { - Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); - } - return true; - } - catch (InvalidConfigurationException ex) - { - if (debug) - { - 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 java.io.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 (task == null) - { - start(); - } - } - } - - /** - * Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task. - * - * @throws java.io.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); - configuration.save(configurationFile); - } - - // Disable Task, if it is running - if (task != null) - { - task.cancel(); - task = null; - } - } - } - - /** - * Gets the File object of the config file that should be used to store data such as the GUID and opt-out status - * - * @return the File object for the config file - */ - public File getConfigFile() - { - // I believe the easiest way to get the base folder (e.g craftbukkit set via -P) for plugins to use - // is to abuse the plugin object we already have - // plugin.getDataFolder() => base/plugins/PluginA/ - // pluginsFolder => base/plugins/ - // The base is not necessarily relative to the startup directory. - File pluginsFolder = plugin.getDataFolder().getParentFile(); - - // return => base/plugins/PluginMetrics/config.yml - return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml"); - } - - /** - * Generic method that posts a plugin to the metrics website - */ - private void postPlugin(final boolean isPing) throws IOException - { - // Server software specific section - PluginDescriptionFile description = plugin.getDescription(); - String pluginName = description.getName(); - boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE if online mode is enabled - String pluginVersion = description.getVersion(); - String serverVersion = Bukkit.getVersion(); - int playersOnline = ((IEssentials)plugin).getOnlinePlayers().size(); - - // END server software specific section -- all code below does not use any code outside of this class / Java - - // Construct the post data - StringBuilder json = new StringBuilder(1024); - json.append('{'); - - // The plugin's description file containg all of the plugin data such as name, version, author, etc - appendJSONPair(json, "guid", guid); - appendJSONPair(json, "plugin_version", pluginVersion); - appendJSONPair(json, "server_version", serverVersion); - appendJSONPair(json, "players_online", Integer.toString(playersOnline)); - - // New data as of R6 - String osname = System.getProperty("os.name"); - String osarch = System.getProperty("os.arch"); - String osversion = System.getProperty("os.version"); - String java_version = System.getProperty("java.version"); - int coreCount = Runtime.getRuntime().availableProcessors(); - - // normalize os arch .. amd64 -> x86_64 - if (osarch.equals("amd64")) - { - osarch = "x86_64"; - } - - appendJSONPair(json, "osname", osname); - appendJSONPair(json, "osarch", osarch); - appendJSONPair(json, "osversion", osversion); - appendJSONPair(json, "cores", Integer.toString(coreCount)); - appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0"); - appendJSONPair(json, "java_version", java_version); - - // If we're pinging, append it - if (isPing) - { - appendJSONPair(json, "ping", "1"); - } - - if (graphs.size() > 0) - { - synchronized (graphs) - { - json.append(','); - json.append('"'); - json.append("graphs"); - json.append('"'); - json.append(':'); - json.append('{'); - - boolean firstGraph = true; - - final Iterator iter = graphs.iterator(); - - while (iter.hasNext()) - { - Graph graph = iter.next(); - - StringBuilder graphJson = new StringBuilder(); - graphJson.append('{'); - - for (Plotter plotter : graph.getPlotters()) - { - appendJSONPair(graphJson, plotter.getColumnName(), Integer.toString(plotter.getValue())); - } - - graphJson.append('}'); - - if (!firstGraph) - { - json.append(','); - } - - json.append(escapeJSON(graph.getName())); - json.append(':'); - json.append(graphJson); - - firstGraph = false; - } - - json.append('}'); - } - } - - // close json - json.append('}'); - - // Create the url - URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName))); - - // 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(); - } - - - byte[] uncompressed = json.toString().getBytes(); - byte[] compressed = gzip(json.toString()); - - // Headers - connection.addRequestProperty("User-Agent", "MCStats/" + REVISION); - connection.addRequestProperty("Content-Type", "application/json"); - connection.addRequestProperty("Content-Encoding", "gzip"); - connection.addRequestProperty("Content-Length", Integer.toString(compressed.length)); - connection.addRequestProperty("Accept", "application/json"); - connection.addRequestProperty("Connection", "close"); - - connection.setDoOutput(true); - - if (debug) - { - System.out.println("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" + compressed.length); - } - - // Write the data - OutputStream os = connection.getOutputStream(); - os.write(compressed); - os.flush(); - - // Now read the response - final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); - String response = reader.readLine(); - - // close resources - os.close(); - reader.close(); - - if (response == null || response.startsWith("ERR") || response.startsWith("7")) - { - if (response == null) - { - response = "null"; - } - else if (response.startsWith("7")) - { - response = response.substring(response.startsWith("7,") ? 2 : 1); - } - - throw new IOException(response); - } - else - { - // Is this the first update this hour? - if (response.equals("1") || response.contains("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(); - } - } - } - } - } - } - - /** - * GZip compress a string of bytes - * - * @param input - * @return - */ - public static byte[] gzip(String input) - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - GZIPOutputStream gzos = null; - - try - { - gzos = new GZIPOutputStream(baos); - gzos.write(input.getBytes("UTF-8")); - } - catch (IOException e) - { - e.printStackTrace(); - } - finally - { - if (gzos != null) - { - try - { - gzos.close(); - } - catch (IOException ignore) - { - } - } - } - - return baos.toByteArray(); - } - - /** - * Check if mineshafter is present. If it is, we need to bypass it to send POST requests - * - * @return true if mineshafter is installed on the server - */ - private boolean isMineshafterPresent() - { - try - { - Class.forName("mineshafter.MineServer"); - return true; - } - catch (Exception e) - { - return false; - } - } - - /** - * Appends a json encoded key/value pair to the given string builder. - * - * @param json - * @param key - * @param value - * @throws UnsupportedEncodingException - */ - private static void appendJSONPair(StringBuilder json, String key, String value) throws UnsupportedEncodingException - { - boolean isValueNumeric; - - try - { - Double.parseDouble(value); - isValueNumeric = true; - } - catch (NumberFormatException e) - { - isValueNumeric = false; - } - - if (json.charAt(json.length() - 1) != '{') - { - json.append(','); - } - - json.append(escapeJSON(key)); - json.append(':'); - - if (isValueNumeric) - { - json.append(value); - } - else - { - json.append(escapeJSON(value)); - } - } - - /** - * Escape a string to create a valid JSON string - * - * @param text - * @return - */ - private static String escapeJSON(String text) - { - StringBuilder builder = new StringBuilder(); - - builder.append('"'); - for (int index = 0; index < text.length(); index++) - { - char chr = text.charAt(index); - - switch (chr) - { - case '"': - case '\\': - builder.append('\\'); - builder.append(chr); - break; - case '\b': - builder.append("\\b"); - break; - case '\t': - builder.append("\\t"); - break; - case '\n': - builder.append("\\n"); - break; - case '\r': - builder.append("\\r"); - break; - default: - if (chr < ' ') - { - String t = "000" + Integer.toHexString(chr); - builder.append("\\u" + t.substring(t.length() - 4)); - } - else - { - builder.append(chr); - } - break; - } - } - builder.append('"'); - - return builder.toString(); - } - - /** - * Encode text as UTF-8 - * - * @param text the text to encode - * @return the encoded text, as UTF-8 - */ - private static String urlEncode(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 the Graph's name - */ - public String getName() - { - return name; - } - - /** - * Add a plotter to the graph, which will be used to plot entries - * - * @param plotter the plotter to add to the graph - */ - public void addPlotter(final Plotter plotter) - { - plotters.add(plotter); - } - - /** - * Remove a plotter from the graph - * - * @param plotter the plotter to remove from the graph - */ - public void removePlotter(final Plotter plotter) - { - plotters.remove(plotter); - } - - /** - * Gets an unmodifiable set of the plotter objects in the graph - * - * @return an unmodifiable {@link java.util.Set} of the plotter objects - */ - 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); - } - - /** - * Called when the server owner decides to opt-out of BukkitMetrics while the server is running. - */ - protected void onOptOut() - { - } - } - - - /** - * 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 the name of the plotter to use, which will show up on the website - */ - public Plotter(final String name) - { - this.name = name; - } - - /** - * Get the current value for the plotted point. Since this function defers to an external function it may or may - * not return immediately thus cannot be guaranteed to be thread friendly or safe. This function can be called - * from any thread so care should be taken when accessing resources that need to be synchronized. - * - * @return the current value for the point to be plotted. - */ - 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(); - } - - @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(); - } - } + +public class Metrics { + + /** + * The current revision number + */ + private static final int REVISION = 7; + + /** + * The base url of the metrics domain + */ + private static final String BASE_URL = "http://report-metrics.essentials3.net"; + + /** + * The url used to report a server's status + */ + private static final String REPORT_URL = "/plugin/%s"; + + /** + * Interval of time to ping (in minutes) + */ + private static final int PING_INTERVAL = 15; + + /** + * 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 plugin configuration file + */ + private final YamlConfiguration configuration; + + /** + * The plugin configuration file + */ + private final File configurationFile; + + /** + * Unique server id + */ + private final String guid; + + /** + * Debug mode + */ + private final boolean debug; + + /** + * Lock for synchronization + */ + private final Object optOutLock = new Object(); + + /** + * The scheduled task + */ + private volatile BukkitTask task = null; + + public Metrics(final Plugin plugin) throws IOException { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } + + this.plugin = plugin; + + // load the config + configurationFile = getConfigFile(); + configuration = YamlConfiguration.loadConfiguration(configurationFile); + + // add some defaults + configuration.addDefault("opt-out", false); + configuration.addDefault("guid", UUID.randomUUID().toString()); + configuration.addDefault("debug", false); + + // Do we need to create the file? + if (configuration.get("guid", null) == null) { + configuration.options().header("http://mcstats.org").copyDefaults(true); + configuration.save(configurationFile); + } + + // Load the guid then + guid = configuration.getString("guid"); + debug = configuration.getBoolean("debug", false); + } + + /** + * 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 The name of the graph + * + * @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; + } + + /** + * Add a Graph object to BukkitMetrics that represents data for the plugin that should be sent to the backend + * + * @param graph The name of the graph + */ + public void addGraph(final Graph graph) { + if (graph == null) { + throw new IllegalArgumentException("Graph cannot be null"); + } + + graphs.add(graph); + } + + /** + * 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; + } + + // Is metrics already running? + if (task != null) { + return; + } + + // Begin hitting the server with glorious data + task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(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() && task != null) { + task.cancel(); + task = null; + // Tell all plotters to stop gathering information. + for (Graph graph : graphs) { + graph.onOptOut(); + } + } + } + + // 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) { + if (debug) { + Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage()); + } + } + } + }, 0, PING_INTERVAL * 1200); + } + } + + /** + * Has the server owner denied plugin metrics? + * + * @return true if metrics should be opted out of it + */ + public boolean isOptOut() { + synchronized (optOutLock) { + try { + // Reload the metrics file + configuration.load(getConfigFile()); + } catch (IOException ex) { + if (debug) { + Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); + } + return true; + } catch (InvalidConfigurationException ex) { + if (debug) { + 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 java.io.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 (task == null) { + start(); + } + } + } + + /** + * Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task. + * + * @throws java.io.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); + configuration.save(configurationFile); + } + + // Disable Task, if it is running + if (task != null) { + task.cancel(); + task = null; + } + } + } + + /** + * Gets the File object of the config file that should be used to store data such as the GUID and opt-out status + * + * @return the File object for the config file + */ + public File getConfigFile() { + // I believe the easiest way to get the base folder (e.g craftbukkit set via -P) for plugins to use + // is to abuse the plugin object we already have + // plugin.getDataFolder() => base/plugins/PluginA/ + // pluginsFolder => base/plugins/ + // The base is not necessarily relative to the startup directory. + File pluginsFolder = plugin.getDataFolder().getParentFile(); + + // return => base/plugins/PluginMetrics/config.yml + return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml"); + } + + /** + * Generic method that posts a plugin to the metrics website + */ + private void postPlugin(final boolean isPing) throws IOException { + // Server software specific section + PluginDescriptionFile description = plugin.getDescription(); + String pluginName = description.getName(); + boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE if online mode is enabled + String pluginVersion = description.getVersion(); + String serverVersion = Bukkit.getVersion(); + int playersOnline = ((IEssentials) plugin).getOnlinePlayers().size(); + + // END server software specific section -- all code below does not use any code outside of this class / Java + + // Construct the post data + StringBuilder json = new StringBuilder(1024); + json.append('{'); + + // The plugin's description file containg all of the plugin data such as name, version, author, etc + appendJSONPair(json, "guid", guid); + appendJSONPair(json, "plugin_version", pluginVersion); + appendJSONPair(json, "server_version", serverVersion); + appendJSONPair(json, "players_online", Integer.toString(playersOnline)); + + // New data as of R6 + String osname = System.getProperty("os.name"); + String osarch = System.getProperty("os.arch"); + String osversion = System.getProperty("os.version"); + String java_version = System.getProperty("java.version"); + int coreCount = Runtime.getRuntime().availableProcessors(); + + // normalize os arch .. amd64 -> x86_64 + if (osarch.equals("amd64")) { + osarch = "x86_64"; + } + + appendJSONPair(json, "osname", osname); + appendJSONPair(json, "osarch", osarch); + appendJSONPair(json, "osversion", osversion); + appendJSONPair(json, "cores", Integer.toString(coreCount)); + appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0"); + appendJSONPair(json, "java_version", java_version); + + // If we're pinging, append it + if (isPing) { + appendJSONPair(json, "ping", "1"); + } + + if (graphs.size() > 0) { + synchronized (graphs) { + json.append(','); + json.append('"'); + json.append("graphs"); + json.append('"'); + json.append(':'); + json.append('{'); + + boolean firstGraph = true; + + final Iterator iter = graphs.iterator(); + + while (iter.hasNext()) { + Graph graph = iter.next(); + + StringBuilder graphJson = new StringBuilder(); + graphJson.append('{'); + + for (Plotter plotter : graph.getPlotters()) { + appendJSONPair(graphJson, plotter.getColumnName(), Integer.toString(plotter.getValue())); + } + + graphJson.append('}'); + + if (!firstGraph) { + json.append(','); + } + + json.append(escapeJSON(graph.getName())); + json.append(':'); + json.append(graphJson); + + firstGraph = false; + } + + json.append('}'); + } + } + + // close json + json.append('}'); + + // Create the url + URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName))); + + // 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(); + } + + + byte[] uncompressed = json.toString().getBytes(); + byte[] compressed = gzip(json.toString()); + + // Headers + connection.addRequestProperty("User-Agent", "MCStats/" + REVISION); + connection.addRequestProperty("Content-Type", "application/json"); + connection.addRequestProperty("Content-Encoding", "gzip"); + connection.addRequestProperty("Content-Length", Integer.toString(compressed.length)); + connection.addRequestProperty("Accept", "application/json"); + connection.addRequestProperty("Connection", "close"); + + connection.setDoOutput(true); + + if (debug) { + System.out.println("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" + compressed.length); + } + + // Write the data + OutputStream os = connection.getOutputStream(); + os.write(compressed); + os.flush(); + + // Now read the response + final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); + String response = reader.readLine(); + + // close resources + os.close(); + reader.close(); + + if (response == null || response.startsWith("ERR") || response.startsWith("7")) { + if (response == null) { + response = "null"; + } else if (response.startsWith("7")) { + response = response.substring(response.startsWith("7,") ? 2 : 1); + } + + throw new IOException(response); + } else { + // Is this the first update this hour? + if (response.equals("1") || response.contains("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(); + } + } + } + } + } + } + + /** + * GZip compress a string of bytes + * + * @param input + * + * @return + */ + public static byte[] gzip(String input) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + GZIPOutputStream gzos = null; + + try { + gzos = new GZIPOutputStream(baos); + gzos.write(input.getBytes("UTF-8")); + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (gzos != null) { + try { + gzos.close(); + } catch (IOException ignore) { + } + } + } + + return baos.toByteArray(); + } + + /** + * Check if mineshafter is present. If it is, we need to bypass it to send POST requests + * + * @return true if mineshafter is installed on the server + */ + private boolean isMineshafterPresent() { + try { + Class.forName("mineshafter.MineServer"); + return true; + } catch (Exception e) { + return false; + } + } + + /** + * Appends a json encoded key/value pair to the given string builder. + * + * @param json + * @param key + * @param value + * + * @throws UnsupportedEncodingException + */ + private static void appendJSONPair(StringBuilder json, String key, String value) throws UnsupportedEncodingException { + boolean isValueNumeric; + + try { + Double.parseDouble(value); + isValueNumeric = true; + } catch (NumberFormatException e) { + isValueNumeric = false; + } + + if (json.charAt(json.length() - 1) != '{') { + json.append(','); + } + + json.append(escapeJSON(key)); + json.append(':'); + + if (isValueNumeric) { + json.append(value); + } else { + json.append(escapeJSON(value)); + } + } + + /** + * Escape a string to create a valid JSON string + * + * @param text + * + * @return + */ + private static String escapeJSON(String text) { + StringBuilder builder = new StringBuilder(); + + builder.append('"'); + for (int index = 0; index < text.length(); index++) { + char chr = text.charAt(index); + + switch (chr) { + case '"': + case '\\': + builder.append('\\'); + builder.append(chr); + break; + case '\b': + builder.append("\\b"); + break; + case '\t': + builder.append("\\t"); + break; + case '\n': + builder.append("\\n"); + break; + case '\r': + builder.append("\\r"); + break; + default: + if (chr < ' ') { + String t = "000" + Integer.toHexString(chr); + builder.append("\\u" + t.substring(t.length() - 4)); + } else { + builder.append(chr); + } + break; + } + } + builder.append('"'); + + return builder.toString(); + } + + /** + * Encode text as UTF-8 + * + * @param text the text to encode + * + * @return the encoded text, as UTF-8 + */ + private static String urlEncode(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 the Graph's name + */ + public String getName() { + return name; + } + + /** + * Add a plotter to the graph, which will be used to plot entries + * + * @param plotter the plotter to add to the graph + */ + public void addPlotter(final Plotter plotter) { + plotters.add(plotter); + } + + /** + * Remove a plotter from the graph + * + * @param plotter the plotter to remove from the graph + */ + public void removePlotter(final Plotter plotter) { + plotters.remove(plotter); + } + + /** + * Gets an unmodifiable set of the plotter objects in the graph + * + * @return an unmodifiable {@link java.util.Set} of the plotter objects + */ + 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); + } + + /** + * Called when the server owner decides to opt-out of BukkitMetrics while the server is running. + */ + protected void onOptOut() { + } + } + + + /** + * 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 the name of the plotter to use, which will show up on the website + */ + public Plotter(final String name) { + this.name = name; + } + + /** + * Get the current value for the plotted point. Since this function defers to an external function it may or may + * not return immediately thus cannot be guaranteed to be thread friendly or safe. This function can be called + * from any thread so care should be taken when accessing resources that need to be synchronized. + * + * @return the current value for the point to be plotted. + */ + 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(); + } + + @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 index 2edbf1a80..1a6a54ec3 100644 --- a/Essentials/src/com/earth2me/essentials/metrics/MetricsListener.java +++ b/Essentials/src/com/earth2me/essentials/metrics/MetricsListener.java @@ -1,7 +1,6 @@ package com.earth2me.essentials.metrics; import com.earth2me.essentials.User; -import java.util.logging.Level; import net.ess3.api.IEssentials; import org.bukkit.Server; import org.bukkit.event.EventHandler; @@ -9,31 +8,29 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; +import java.util.logging.Level; -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; - } +public class MetricsListener implements Listener { + private final transient Server server; + private final transient IEssentials ess; + private final transient MetricsStarter starter; - @EventHandler(priority = EventPriority.MONITOR) - public void onPlayerJoin(final PlayerJoinEvent event) - { - final User 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, disabling metrics for all plugins, run /essentials opt-out"); - ess.getLogger().log(Level.INFO, "[Metrics] Admin join - Starting 5 minute opt-out period."); - ess.getSettings().setMetricsEnabled(true); - ess.runTaskLaterAsynchronously(starter, 5 * 1200); - } - } + 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 User 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, disabling metrics for all plugins, run /essentials opt-out"); + ess.getLogger().log(Level.INFO, "[Metrics] Admin join - Starting 5 minute opt-out period."); + ess.getSettings().setMetricsEnabled(true); + ess.runTaskLaterAsynchronously(starter, 5 * 1200); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/metrics/MetricsStarter.java b/Essentials/src/com/earth2me/essentials/metrics/MetricsStarter.java index 0ce162217..fcd6ad00e 100644 --- a/Essentials/src/com/earth2me/essentials/metrics/MetricsStarter.java +++ b/Essentials/src/com/earth2me/essentials/metrics/MetricsStarter.java @@ -5,238 +5,190 @@ import com.earth2me.essentials.metrics.Metrics.Plotter; import com.earth2me.essentials.register.payment.Method; import com.earth2me.essentials.register.payment.methods.VaultEco; import com.earth2me.essentials.signs.EssentialsSign; -import java.util.Locale; -import java.util.logging.Level; import net.ess3.api.IEssentials; import org.bukkit.configuration.ConfigurationSection; - -public class MetricsStarter implements Runnable -{ - private final IEssentials ess; - private transient Boolean start; +import java.util.Locale; +import java.util.logging.Level; - private enum Modules - { - Essentials, - EssentialsAntiBuild, - EssentialsAntiCheat, - EssentialsChat, - EssentialsSpawn, - EssentialsProtect, - EssentialsGeoIP, - EssentialsXMPP - }; - - public MetricsStarter(final IEssentials plugin) - { - ess = plugin; - try - { - - final Metrics metrics = new Metrics(ess); - ess.setMetrics(metrics); - - if (!metrics.isOptOut()) - { - if (ess.getSettings().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, disabling metrics for all plugins, 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() - { - ConfigurationSection kits = ess.getSettings().getKits(); - if (kits == null) - { - return 0; - } - return kits.getKeys(false).size(); - } - }); - featureGraph.addPlotter(new Plotter("Warps") - { - @Override - public int getValue() - { - return ess.getWarps().getCount(); - } - }); - - final Graph enabledGraph = metrics.createGraph("EnabledFeatures"); - enabledGraph.addPlotter(new SimplePlotter("Total")); - final String BKcommand = ess.getSettings().getBackupCommand(); - if (BKcommand != null && !"".equals(BKcommand)) - { - enabledGraph.addPlotter(new SimplePlotter("Backup")); - } - if (ess.getJails().getCount() > 0) - { - enabledGraph.addPlotter(new SimplePlotter("Jails")); - } - if (ess.getSettings().getKits() != null && ess.getSettings().getKits().getKeys(false).size() > 0) - { - enabledGraph.addPlotter(new SimplePlotter("Kits")); - } - if (ess.getWarps().getCount() > 0) - { - enabledGraph.addPlotter(new SimplePlotter("Warps")); - } - if (ess.getSettings().getTeleportCooldown() > 0) - { - enabledGraph.addPlotter(new SimplePlotter("TeleportCooldown")); - } - if (ess.getSettings().getTeleportDelay() > 0) - { - enabledGraph.addPlotter(new SimplePlotter("TeleportDelay")); - } - if (!ess.getSettings().areSignsDisabled()) - { - enabledGraph.addPlotter(new SimplePlotter("Signs")); - } - if (ess.getSettings().getAutoAfk() > 0) - { - enabledGraph.addPlotter(new SimplePlotter("AutoAFK")); - } - if (ess.getSettings().changePlayerListName()) - { - enabledGraph.addPlotter(new SimplePlotter("PlayerListName")); - } - if (ess.getSettings().getOperatorColor() != null) - { - enabledGraph.addPlotter(new SimplePlotter("OpColour")); - } - 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)); - } - depGraph.addPlotter(new SimplePlotter(ess.getPermissionsHandler().getName())); - - final Graph signGraph = metrics.createGraph("Signs"); - for (EssentialsSign sign : ess.getSettings().enabledSigns()) - { - signGraph.addPlotter(new SimplePlotter(sign.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; - } +public class MetricsStarter implements Runnable { + private final IEssentials ess; + private transient Boolean start; - private class SimplePlotter extends Plotter - { - public SimplePlotter(final String name) - { - super(name); - } + private enum Modules { + Essentials, + EssentialsAntiBuild, + EssentialsAntiCheat, + EssentialsChat, + EssentialsSpawn, + EssentialsProtect, + EssentialsGeoIP, + EssentialsXMPP + } - @Override - public int getValue() - { - return 1; - } - } + ; + + public MetricsStarter(final IEssentials plugin) { + ess = plugin; + try { + + final Metrics metrics = new Metrics(ess); + ess.setMetrics(metrics); + + if (!metrics.isOptOut()) { + if (ess.getSettings().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, disabling metrics for all plugins, 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() { + ConfigurationSection kits = ess.getSettings().getKits(); + if (kits == null) { + return 0; + } + return kits.getKeys(false).size(); + } + }); + featureGraph.addPlotter(new Plotter("Warps") { + @Override + public int getValue() { + return ess.getWarps().getCount(); + } + }); + + final Graph enabledGraph = metrics.createGraph("EnabledFeatures"); + enabledGraph.addPlotter(new SimplePlotter("Total")); + final String BKcommand = ess.getSettings().getBackupCommand(); + if (BKcommand != null && !"".equals(BKcommand)) { + enabledGraph.addPlotter(new SimplePlotter("Backup")); + } + if (ess.getJails().getCount() > 0) { + enabledGraph.addPlotter(new SimplePlotter("Jails")); + } + if (ess.getSettings().getKits() != null && ess.getSettings().getKits().getKeys(false).size() > 0) { + enabledGraph.addPlotter(new SimplePlotter("Kits")); + } + if (ess.getWarps().getCount() > 0) { + enabledGraph.addPlotter(new SimplePlotter("Warps")); + } + if (ess.getSettings().getTeleportCooldown() > 0) { + enabledGraph.addPlotter(new SimplePlotter("TeleportCooldown")); + } + if (ess.getSettings().getTeleportDelay() > 0) { + enabledGraph.addPlotter(new SimplePlotter("TeleportDelay")); + } + if (!ess.getSettings().areSignsDisabled()) { + enabledGraph.addPlotter(new SimplePlotter("Signs")); + } + if (ess.getSettings().getAutoAfk() > 0) { + enabledGraph.addPlotter(new SimplePlotter("AutoAFK")); + } + if (ess.getSettings().changePlayerListName()) { + enabledGraph.addPlotter(new SimplePlotter("PlayerListName")); + } + if (ess.getSettings().getOperatorColor() != null) { + enabledGraph.addPlotter(new SimplePlotter("OpColour")); + } + 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)); + } + depGraph.addPlotter(new SimplePlotter(ess.getPermissionsHandler().getName())); + + final Graph signGraph = metrics.createGraph("Signs"); + for (EssentialsSign sign : ess.getSettings().enabledSigns()) { + signGraph.addPlotter(new SimplePlotter(sign.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; + } + } } diff --git a/Essentials/src/com/earth2me/essentials/perm/BPermissions2Handler.java b/Essentials/src/com/earth2me/essentials/perm/BPermissions2Handler.java index 791ffbe92..067909078 100644 --- a/Essentials/src/com/earth2me/essentials/perm/BPermissions2Handler.java +++ b/Essentials/src/com/earth2me/essentials/perm/BPermissions2Handler.java @@ -2,58 +2,50 @@ package com.earth2me.essentials.perm; import de.bananaco.bpermissions.api.ApiLayer; import de.bananaco.bpermissions.api.util.CalculableType; -import java.util.Arrays; -import java.util.List; import org.bukkit.entity.Player; +import java.util.Arrays; +import java.util.List; -public class BPermissions2Handler extends SuperpermsHandler -{ - public BPermissions2Handler() - { - - } - @Override - public String getGroup(final Player base) - { - final List groups = getGroups(base); - if (groups == null || groups.isEmpty()) - { - return null; - } - return groups.get(0); - } +public class BPermissions2Handler extends SuperpermsHandler { + public BPermissions2Handler() { - @Override - public List getGroups(final Player base) - { - final String[] groups = ApiLayer.getGroups(base.getWorld().getName(), CalculableType.USER, base.getName()); - return Arrays.asList(groups); - } + } - @Override - public boolean inGroup(final Player base, final String group) - { - return ApiLayer.hasGroupRecursive(base.getWorld().getName(), CalculableType.USER, base.getName(), group); - } + @Override + public String getGroup(final Player base) { + final List groups = getGroups(base); + if (groups == null || groups.isEmpty()) { + return null; + } + return groups.get(0); + } - @Override - public boolean canBuild(final Player base, final String group) - { - return hasPermission(base, "bPermissions.build"); - } + @Override + public List getGroups(final Player base) { + final String[] groups = ApiLayer.getGroups(base.getWorld().getName(), CalculableType.USER, base.getName()); + return Arrays.asList(groups); + } - @Override - public String getPrefix(final Player base) - { - return ApiLayer.getValue(base.getWorld().getName(), CalculableType.USER, base.getName(), "prefix"); - } + @Override + public boolean inGroup(final Player base, final String group) { + return ApiLayer.hasGroupRecursive(base.getWorld().getName(), CalculableType.USER, base.getName(), group); + } - @Override - public String getSuffix(final Player base) - { - return ApiLayer.getValue(base.getWorld().getName(), CalculableType.USER, base.getName(), "suffix"); - } + @Override + public boolean canBuild(final Player base, final String group) { + return hasPermission(base, "bPermissions.build"); + } + + @Override + public String getPrefix(final Player base) { + return ApiLayer.getValue(base.getWorld().getName(), CalculableType.USER, base.getName(), "prefix"); + } + + @Override + public String getSuffix(final Player base) { + return ApiLayer.getValue(base.getWorld().getName(), CalculableType.USER, base.getName(), "suffix"); + } } diff --git a/Essentials/src/com/earth2me/essentials/perm/ConfigPermissionsHandler.java b/Essentials/src/com/earth2me/essentials/perm/ConfigPermissionsHandler.java index d77af5ce1..b1e0e23d9 100644 --- a/Essentials/src/com/earth2me/essentials/perm/ConfigPermissionsHandler.java +++ b/Essentials/src/com/earth2me/essentials/perm/ConfigPermissionsHandler.java @@ -5,26 +5,22 @@ import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; -public class ConfigPermissionsHandler extends SuperpermsHandler -{ - private final transient IEssentials ess; +public class ConfigPermissionsHandler extends SuperpermsHandler { + private final transient IEssentials ess; - public ConfigPermissionsHandler(final Plugin ess) - { - this.ess = (IEssentials)ess; - } + public ConfigPermissionsHandler(final Plugin ess) { + this.ess = (IEssentials) ess; + } - @Override - public boolean canBuild(final Player base, final String group) - { - return true; - } + @Override + public boolean canBuild(final Player base, final String group) { + return true; + } - @Override - public boolean hasPermission(final Player base, final String node) - { - final String[] cmds = node.split("\\.", 2); - return ess.getSettings().isPlayerCommand(cmds[cmds.length - 1]) || super.hasPermission(base, node); - } + @Override + public boolean hasPermission(final Player base, final String node) { + final String[] cmds = node.split("\\.", 2); + return ess.getSettings().isPlayerCommand(cmds[cmds.length - 1]) || super.hasPermission(base, node); + } } diff --git a/Essentials/src/com/earth2me/essentials/perm/GroupManagerHandler.java b/Essentials/src/com/earth2me/essentials/perm/GroupManagerHandler.java index 83dd1a846..84894c79f 100644 --- a/Essentials/src/com/earth2me/essentials/perm/GroupManagerHandler.java +++ b/Essentials/src/com/earth2me/essentials/perm/GroupManagerHandler.java @@ -1,114 +1,94 @@ package com.earth2me.essentials.perm; -import java.util.Arrays; -import java.util.List; import org.anjocaido.groupmanager.GroupManager; import org.anjocaido.groupmanager.dataholder.worlds.WorldsHolder; import org.anjocaido.groupmanager.permissions.AnjoPermissionsHandler; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; +import java.util.Arrays; +import java.util.List; -public class GroupManagerHandler implements IPermissionsHandler -{ - private final transient GroupManager groupManager; - public GroupManagerHandler(final Plugin permissionsPlugin) - { - groupManager = ((GroupManager)permissionsPlugin); - } +public class GroupManagerHandler implements IPermissionsHandler { + private final transient GroupManager groupManager; - @Override - public String getGroup(final Player base) - { - final AnjoPermissionsHandler handler = getHandler(base); - if (handler == null) - { - return null; - } - return handler.getGroup(base.getName()); - } + public GroupManagerHandler(final Plugin permissionsPlugin) { + groupManager = ((GroupManager) permissionsPlugin); + } - @Override - public List getGroups(final Player base) - { - final AnjoPermissionsHandler handler = getHandler(base); - if (handler == null) - { - return null; - } - return Arrays.asList(handler.getGroups(base.getName())); - } + @Override + public String getGroup(final Player base) { + final AnjoPermissionsHandler handler = getHandler(base); + if (handler == null) { + return null; + } + return handler.getGroup(base.getName()); + } - @Override - public boolean canBuild(final Player base, final String group) - { - final AnjoPermissionsHandler handler = getHandler(base); - if (handler == null) - { - return false; - } - return handler.canUserBuild(base.getName()); - } + @Override + public List getGroups(final Player base) { + final AnjoPermissionsHandler handler = getHandler(base); + if (handler == null) { + return null; + } + return Arrays.asList(handler.getGroups(base.getName())); + } - @Override - public boolean inGroup(final Player base, final String group) - { - AnjoPermissionsHandler handler = getHandler(base); - if (handler == null) - { - return false; - } - return handler.inGroup(base.getName(), group); - } + @Override + public boolean canBuild(final Player base, final String group) { + final AnjoPermissionsHandler handler = getHandler(base); + if (handler == null) { + return false; + } + return handler.canUserBuild(base.getName()); + } - @Override - public boolean hasPermission(final Player base, final String node) - { - AnjoPermissionsHandler handler = getHandler(base); - if (handler == null) - { - return false; - } - return handler.has(base, node); - } + @Override + public boolean inGroup(final Player base, final String group) { + AnjoPermissionsHandler handler = getHandler(base); + if (handler == null) { + return false; + } + return handler.inGroup(base.getName(), group); + } - @Override - public String getPrefix(final Player base) - { - AnjoPermissionsHandler handler = getHandler(base); - if (handler == null) - { - return null; - } - return handler.getUserPrefix(base.getName()); - } + @Override + public boolean hasPermission(final Player base, final String node) { + AnjoPermissionsHandler handler = getHandler(base); + if (handler == null) { + return false; + } + return handler.has(base, node); + } - @Override - public String getSuffix(final Player base) - { - AnjoPermissionsHandler handler = getHandler(base); - if (handler == null) - { - return null; - } - return handler.getUserSuffix(base.getName()); - } + @Override + public String getPrefix(final Player base) { + AnjoPermissionsHandler handler = getHandler(base); + if (handler == null) { + return null; + } + return handler.getUserPrefix(base.getName()); + } - private AnjoPermissionsHandler getHandler(final Player base) - { - final WorldsHolder holder = groupManager.getWorldsHolder(); - if (holder == null) - { - return null; - } - try - { - return holder.getWorldPermissions(base); - } - catch (NullPointerException ex) - { - return null; - } - } + @Override + public String getSuffix(final Player base) { + AnjoPermissionsHandler handler = getHandler(base); + if (handler == null) { + return null; + } + return handler.getUserSuffix(base.getName()); + } + + private AnjoPermissionsHandler getHandler(final Player base) { + final WorldsHolder holder = groupManager.getWorldsHolder(); + if (holder == null) { + return null; + } + try { + return holder.getWorldPermissions(base); + } catch (NullPointerException ex) { + return null; + } + } } diff --git a/Essentials/src/com/earth2me/essentials/perm/IPermissionsHandler.java b/Essentials/src/com/earth2me/essentials/perm/IPermissionsHandler.java index 27af48e8c..f926d16c2 100644 --- a/Essentials/src/com/earth2me/essentials/perm/IPermissionsHandler.java +++ b/Essentials/src/com/earth2me/essentials/perm/IPermissionsHandler.java @@ -1,22 +1,22 @@ package com.earth2me.essentials.perm; -import java.util.List; import org.bukkit.entity.Player; +import java.util.List; -public interface IPermissionsHandler -{ - String getGroup(Player base); - List getGroups(Player base); +public interface IPermissionsHandler { + String getGroup(Player base); - boolean canBuild(Player base, String group); + List getGroups(Player base); - boolean inGroup(Player base, String group); + boolean canBuild(Player base, String group); - boolean hasPermission(Player base, String node); + boolean inGroup(Player base, String group); - String getPrefix(Player base); + boolean hasPermission(Player base, String node); - String getSuffix(Player base); + String getPrefix(Player base); + + String getSuffix(Player base); } diff --git a/Essentials/src/com/earth2me/essentials/perm/NullPermissionsHandler.java b/Essentials/src/com/earth2me/essentials/perm/NullPermissionsHandler.java index b51aeb055..fdda7b8ec 100644 --- a/Essentials/src/com/earth2me/essentials/perm/NullPermissionsHandler.java +++ b/Essentials/src/com/earth2me/essentials/perm/NullPermissionsHandler.java @@ -1,51 +1,44 @@ package com.earth2me.essentials.perm; +import org.bukkit.entity.Player; + import java.util.Collections; import java.util.List; -import org.bukkit.entity.Player; -public class NullPermissionsHandler implements IPermissionsHandler -{ - @Override - public String getGroup(final Player base) - { - return null; - } +public class NullPermissionsHandler implements IPermissionsHandler { + @Override + public String getGroup(final Player base) { + return null; + } - @Override - public List getGroups(final Player base) - { - return Collections.emptyList(); - } + @Override + public List getGroups(final Player base) { + return Collections.emptyList(); + } - @Override - public boolean canBuild(final Player base, final String group) - { - return false; - } + @Override + public boolean canBuild(final Player base, final String group) { + return false; + } - @Override - public boolean inGroup(final Player base, final String group) - { - return false; - } + @Override + public boolean inGroup(final Player base, final String group) { + return false; + } - @Override - public boolean hasPermission(final Player base, final String node) - { - return false; - } + @Override + public boolean hasPermission(final Player base, final String node) { + return false; + } - @Override - public String getPrefix(final Player base) - { - return null; - } + @Override + public String getPrefix(final Player base) { + return null; + } - @Override - public String getSuffix(final Player base) - { - return null; - } + @Override + public String getSuffix(final Player base) { + return null; + } } diff --git a/Essentials/src/com/earth2me/essentials/perm/PermissionsBukkitHandler.java b/Essentials/src/com/earth2me/essentials/perm/PermissionsBukkitHandler.java index 908ce78f3..ae29b85a8 100644 --- a/Essentials/src/com/earth2me/essentials/perm/PermissionsBukkitHandler.java +++ b/Essentials/src/com/earth2me/essentials/perm/PermissionsBukkitHandler.java @@ -3,76 +3,64 @@ package com.earth2me.essentials.perm; import com.platymuus.bukkit.permissions.Group; import com.platymuus.bukkit.permissions.PermissionInfo; import com.platymuus.bukkit.permissions.PermissionsPlugin; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; -public class PermissionsBukkitHandler extends SuperpermsHandler -{ - private final transient PermissionsPlugin plugin; - public PermissionsBukkitHandler(final Plugin plugin) - { - this.plugin = (PermissionsPlugin)plugin; - } +public class PermissionsBukkitHandler extends SuperpermsHandler { + private final transient PermissionsPlugin plugin; - @Override - public String getGroup(final Player base) - { - final List groups = getPBGroups(base); - if (groups == null || groups.isEmpty()) - { - return null; - } - return groups.get(0).getName(); - } + public PermissionsBukkitHandler(final Plugin plugin) { + this.plugin = (PermissionsPlugin) plugin; + } - @Override - public List getGroups(final Player base) - { - final List groups = getPBGroups(base); - if (groups.size() == 1) - { - return Collections.singletonList(groups.get(0).getName()); - } - final List groupNames = new ArrayList(groups.size()); - for (Group group : groups) - { - groupNames.add(group.getName()); - } - return groupNames; - } + @Override + public String getGroup(final Player base) { + final List groups = getPBGroups(base); + if (groups == null || groups.isEmpty()) { + return null; + } + return groups.get(0).getName(); + } - private List getPBGroups(final Player base) - { - final PermissionInfo info = plugin.getPlayerInfo(base.getName()); - if (info == null) - { - return Collections.emptyList(); - } - final List groups = info.getGroups(); - if (groups == null || groups.isEmpty()) - { - return Collections.emptyList(); - } - return groups; - } + @Override + public List getGroups(final Player base) { + final List groups = getPBGroups(base); + if (groups.size() == 1) { + return Collections.singletonList(groups.get(0).getName()); + } + final List groupNames = new ArrayList(groups.size()); + for (Group group : groups) { + groupNames.add(group.getName()); + } + return groupNames; + } - @Override - public boolean inGroup(final Player base, final String group) - { - final List groups = getPBGroups(base); - for (Group group1 : groups) - { - if (group1.getName().equalsIgnoreCase(group)) - { - return true; - } - } - return false; - } + private List getPBGroups(final Player base) { + final PermissionInfo info = plugin.getPlayerInfo(base.getName()); + if (info == null) { + return Collections.emptyList(); + } + final List groups = info.getGroups(); + if (groups == null || groups.isEmpty()) { + return Collections.emptyList(); + } + return groups; + } + + @Override + public boolean inGroup(final Player base, final String group) { + final List groups = getPBGroups(base); + for (Group group1 : groups) { + if (group1.getName().equalsIgnoreCase(group)) { + return true; + } + } + return false; + } } diff --git a/Essentials/src/com/earth2me/essentials/perm/PermissionsExHandler.java b/Essentials/src/com/earth2me/essentials/perm/PermissionsExHandler.java index e61dfc30b..0173bb387 100644 --- a/Essentials/src/com/earth2me/essentials/perm/PermissionsExHandler.java +++ b/Essentials/src/com/earth2me/essentials/perm/PermissionsExHandler.java @@ -1,108 +1,92 @@ package com.earth2me.essentials.perm; -import java.util.Arrays; -import java.util.List; import org.bukkit.entity.Player; import ru.tehkode.permissions.PermissionManager; import ru.tehkode.permissions.PermissionUser; import ru.tehkode.permissions.bukkit.PermissionsEx; +import java.util.Arrays; +import java.util.List; -public class PermissionsExHandler extends SuperpermsHandler -{ - private final transient PermissionManager manager; - public PermissionsExHandler() - { - manager = PermissionsEx.getPermissionManager(); - } +public class PermissionsExHandler extends SuperpermsHandler { + private final transient PermissionManager manager; - @Override - public String getGroup(final Player base) - { - final PermissionUser user = manager.getUser(base.getName()); - if (user == null) - { - return null; - } + public PermissionsExHandler() { + manager = PermissionsEx.getPermissionManager(); + } - String[] groupsNames = user.getGroupsNames(); - if (groupsNames == null || groupsNames.length == 0) - { - return null; - } + @Override + public String getGroup(final Player base) { + final PermissionUser user = manager.getUser(base.getName()); + if (user == null) { + return null; + } - return groupsNames[0]; - } + String[] groupsNames = user.getGroupsNames(); + if (groupsNames == null || groupsNames.length == 0) { + return null; + } - @Override - public List getGroups(final Player base) - { - final PermissionUser user = manager.getUser(base.getName()); - if (user == null) - { - return null; - } - - String[] groupsNames = user.getGroupsNames(); - if (groupsNames == null) - { - return null; - } - - return Arrays.asList(groupsNames); - } + return groupsNames[0]; + } - @Override - public boolean canBuild(final Player base, final String group) - { - final PermissionUser user = manager.getUser(base.getName()); - if (user == null) - { - return false; - } + @Override + public List getGroups(final Player base) { + final PermissionUser user = manager.getUser(base.getName()); + if (user == null) { + return null; + } - return user.getOptionBoolean("build", base.getWorld().getName(), false); - } + String[] groupsNames = user.getGroupsNames(); + if (groupsNames == null) { + return null; + } - @Override - public boolean inGroup(final Player base, final String group) - { - final PermissionUser user = manager.getUser(base.getName()); - if (user == null) - { - return false; - } + return Arrays.asList(groupsNames); + } - return user.inGroup(group); - } + @Override + public boolean canBuild(final Player base, final String group) { + final PermissionUser user = manager.getUser(base.getName()); + if (user == null) { + return false; + } - @Override - public boolean hasPermission(final Player base, final String node) - { - return super.hasPermission(base, node); - } + return user.getOptionBoolean("build", base.getWorld().getName(), false); + } - @Override - public String getPrefix(final Player base) - { - final PermissionUser user = manager.getUser(base.getName()); - if (user == null) - { - return null; - } - return user.getPrefix(base.getWorld().getName()); - } + @Override + public boolean inGroup(final Player base, final String group) { + final PermissionUser user = manager.getUser(base.getName()); + if (user == null) { + return false; + } - @Override - public String getSuffix(final Player base) - { - final PermissionUser user = manager.getUser(base.getName()); - if (user == null) - { - return null; - } + return user.inGroup(group); + } - return user.getSuffix(base.getWorld().getName()); - } + @Override + public boolean hasPermission(final Player base, final String node) { + return super.hasPermission(base, node); + } + + @Override + public String getPrefix(final Player base) { + final PermissionUser user = manager.getUser(base.getName()); + if (user == null) { + return null; + } + return user.getPrefix(base.getWorld().getName()); + } + + @Override + public String getSuffix(final Player base) { + final PermissionUser user = manager.getUser(base.getName()); + if (user == null) { + return null; + } + + return user.getSuffix(base.getWorld().getName()); + } } diff --git a/Essentials/src/com/earth2me/essentials/perm/PermissionsHandler.java b/Essentials/src/com/earth2me/essentials/perm/PermissionsHandler.java index f92027afa..399125763 100644 --- a/Essentials/src/com/earth2me/essentials/perm/PermissionsHandler.java +++ b/Essentials/src/com/earth2me/essentials/perm/PermissionsHandler.java @@ -1,229 +1,191 @@ package com.earth2me.essentials.perm; import com.earth2me.essentials.Essentials; -import java.util.Collections; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; +import java.util.Collections; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; -public class PermissionsHandler implements IPermissionsHandler -{ - private transient IPermissionsHandler handler = new NullPermissionsHandler(); - private transient String defaultGroup = "default"; - private final transient Essentials ess; - private static final Logger LOGGER = Logger.getLogger("Essentials"); - private transient boolean useSuperperms = false; - public PermissionsHandler(final Essentials plugin) - { - this.ess = plugin; - } +public class PermissionsHandler implements IPermissionsHandler { + private transient IPermissionsHandler handler = new NullPermissionsHandler(); + private transient String defaultGroup = "default"; + private final transient Essentials ess; + private static final Logger LOGGER = Logger.getLogger("Essentials"); + private transient boolean useSuperperms = false; - public PermissionsHandler(final Essentials plugin, final boolean useSuperperms) - { - this.ess = plugin; - this.useSuperperms = useSuperperms; - } + public PermissionsHandler(final Essentials plugin) { + this.ess = plugin; + } - public PermissionsHandler(final Essentials plugin, final String defaultGroup) - { - this.ess = plugin; - this.defaultGroup = defaultGroup; - } + public PermissionsHandler(final Essentials plugin, final boolean useSuperperms) { + this.ess = plugin; + this.useSuperperms = useSuperperms; + } - @Override - public String getGroup(final Player base) - { - final long start = System.nanoTime(); - String group = handler.getGroup(base); - if (group == null) - { - group = defaultGroup; - } - checkPermLag(start); - return group; - } + public PermissionsHandler(final Essentials plugin, final String defaultGroup) { + this.ess = plugin; + this.defaultGroup = defaultGroup; + } - @Override - public List getGroups(final Player base) - { - final long start = System.nanoTime(); - List groups = handler.getGroups(base); - if (groups == null || groups.isEmpty()) - { - groups = Collections.singletonList(defaultGroup); - } - checkPermLag(start); - return Collections.unmodifiableList(groups); - } + @Override + public String getGroup(final Player base) { + final long start = System.nanoTime(); + String group = handler.getGroup(base); + if (group == null) { + group = defaultGroup; + } + checkPermLag(start); + return group; + } - @Override - public boolean canBuild(final Player base, final String group) - { - return handler.canBuild(base, group); - } + @Override + public List getGroups(final Player base) { + final long start = System.nanoTime(); + List groups = handler.getGroups(base); + if (groups == null || groups.isEmpty()) { + groups = Collections.singletonList(defaultGroup); + } + checkPermLag(start); + return Collections.unmodifiableList(groups); + } - @Override - public boolean inGroup(final Player base, final String group) - { - final long start = System.nanoTime(); - final boolean result = handler.inGroup(base, group); - checkPermLag(start); - return result; - } + @Override + public boolean canBuild(final Player base, final String group) { + return handler.canBuild(base, group); + } - @Override - public boolean hasPermission(final Player base, final String node) - { - return handler.hasPermission(base, node); - } + @Override + public boolean inGroup(final Player base, final String group) { + final long start = System.nanoTime(); + final boolean result = handler.inGroup(base, group); + checkPermLag(start); + return result; + } - @Override - public String getPrefix(final Player base) - { - final long start = System.nanoTime(); - String prefix = handler.getPrefix(base); - if (prefix == null) - { - prefix = ""; - } - checkPermLag(start); - return prefix; - } + @Override + public boolean hasPermission(final Player base, final String node) { + return handler.hasPermission(base, node); + } - @Override - public String getSuffix(final Player base) - { - final long start = System.nanoTime(); - String suffix = handler.getSuffix(base); - if (suffix == null) - { - suffix = ""; - } - checkPermLag(start); - return suffix; - } + @Override + public String getPrefix(final Player base) { + final long start = System.nanoTime(); + String prefix = handler.getPrefix(base); + if (prefix == null) { + prefix = ""; + } + checkPermLag(start); + return prefix; + } - public void checkPermissions() - { - final PluginManager pluginManager = ess.getServer().getPluginManager(); + @Override + public String getSuffix(final Player base) { + final long start = System.nanoTime(); + String suffix = handler.getSuffix(base); + if (suffix == null) { + suffix = ""; + } + checkPermLag(start); + return suffix; + } - final Plugin permExPlugin = pluginManager.getPlugin("PermissionsEx"); - if (permExPlugin != null && permExPlugin.isEnabled()) - { - if (!(handler instanceof PermissionsExHandler)) - { - LOGGER.log(Level.INFO, "Essentials: Using PermissionsEx based permissions."); - handler = new PermissionsExHandler(); - } - return; - } + public void checkPermissions() { + final PluginManager pluginManager = ess.getServer().getPluginManager(); - final Plugin GMplugin = pluginManager.getPlugin("GroupManager"); - if (GMplugin != null && GMplugin.isEnabled()) - { - if (!(handler instanceof GroupManagerHandler)) - { - LOGGER.log(Level.INFO, "Essentials: Using GroupManager based permissions."); - handler = new GroupManagerHandler(GMplugin); - } - return; - } + final Plugin permExPlugin = pluginManager.getPlugin("PermissionsEx"); + if (permExPlugin != null && permExPlugin.isEnabled()) { + if (!(handler instanceof PermissionsExHandler)) { + LOGGER.log(Level.INFO, "Essentials: Using PermissionsEx based permissions."); + handler = new PermissionsExHandler(); + } + return; + } - final Plugin permBukkitPlugin = pluginManager.getPlugin("PermissionsBukkit"); - if (permBukkitPlugin != null && permBukkitPlugin.isEnabled()) - { - if (!(handler instanceof PermissionsBukkitHandler)) - { - LOGGER.log(Level.INFO, "Essentials: Using PermissionsBukkit based permissions."); - handler = new PermissionsBukkitHandler(permBukkitPlugin); - } - return; - } + final Plugin GMplugin = pluginManager.getPlugin("GroupManager"); + if (GMplugin != null && GMplugin.isEnabled()) { + if (!(handler instanceof GroupManagerHandler)) { + LOGGER.log(Level.INFO, "Essentials: Using GroupManager based permissions."); + handler = new GroupManagerHandler(GMplugin); + } + return; + } - final Plugin simplyPermsPlugin = pluginManager.getPlugin("SimplyPerms"); - if (simplyPermsPlugin != null && simplyPermsPlugin.isEnabled()) - { - if (!(handler instanceof SimplyPermsHandler)) - { - LOGGER.log(Level.INFO, "Essentials: Using SimplyPerms based permissions."); - handler = new SimplyPermsHandler(simplyPermsPlugin); - } - return; - } + final Plugin permBukkitPlugin = pluginManager.getPlugin("PermissionsBukkit"); + if (permBukkitPlugin != null && permBukkitPlugin.isEnabled()) { + if (!(handler instanceof PermissionsBukkitHandler)) { + LOGGER.log(Level.INFO, "Essentials: Using PermissionsBukkit based permissions."); + handler = new PermissionsBukkitHandler(permBukkitPlugin); + } + return; + } - final Plugin privPlugin = pluginManager.getPlugin("Privileges"); - if (privPlugin != null && privPlugin.isEnabled()) - { - if (!(handler instanceof PrivilegesHandler)) - { - LOGGER.log(Level.INFO, "Essentials: Using Privileges based permissions."); - handler = new PrivilegesHandler(privPlugin); - } - return; - } + final Plugin simplyPermsPlugin = pluginManager.getPlugin("SimplyPerms"); + if (simplyPermsPlugin != null && simplyPermsPlugin.isEnabled()) { + if (!(handler instanceof SimplyPermsHandler)) { + LOGGER.log(Level.INFO, "Essentials: Using SimplyPerms based permissions."); + handler = new SimplyPermsHandler(simplyPermsPlugin); + } + return; + } - final Plugin bPermPlugin = pluginManager.getPlugin("bPermissions"); - if (bPermPlugin != null && bPermPlugin.isEnabled()) - { - if (!(handler instanceof BPermissions2Handler)) - { - LOGGER.log(Level.INFO, "Essentials: Using bPermissions2 based permissions."); - handler = new BPermissions2Handler(); - } - return; - } + final Plugin privPlugin = pluginManager.getPlugin("Privileges"); + if (privPlugin != null && privPlugin.isEnabled()) { + if (!(handler instanceof PrivilegesHandler)) { + LOGGER.log(Level.INFO, "Essentials: Using Privileges based permissions."); + handler = new PrivilegesHandler(privPlugin); + } + return; + } - final Plugin zPermsPlugin = pluginManager.getPlugin("zPermissions"); - if (zPermsPlugin != null && zPermsPlugin.isEnabled()) - { - if (!(handler instanceof ZPermissionsHandler)) - { - LOGGER.log(Level.INFO, "Essentials: Using zPermissions based permissions."); - handler = new ZPermissionsHandler(ess); - } - return; - } + final Plugin bPermPlugin = pluginManager.getPlugin("bPermissions"); + if (bPermPlugin != null && bPermPlugin.isEnabled()) { + if (!(handler instanceof BPermissions2Handler)) { + LOGGER.log(Level.INFO, "Essentials: Using bPermissions2 based permissions."); + handler = new BPermissions2Handler(); + } + return; + } - if (useSuperperms) - { - if (!(handler instanceof SuperpermsHandler)) - { - LOGGER.log(Level.INFO, "Essentials: Using superperms based permissions."); - handler = new SuperpermsHandler(); - } - } - else - { - if (!(handler instanceof ConfigPermissionsHandler)) - { - LOGGER.log(Level.INFO, "Essentials: Using config file enhanced permissions."); - LOGGER.log(Level.INFO, "Permissions listed in as player-commands will be given to all users."); - handler = new ConfigPermissionsHandler(ess); - } - } - } + final Plugin zPermsPlugin = pluginManager.getPlugin("zPermissions"); + if (zPermsPlugin != null && zPermsPlugin.isEnabled()) { + if (!(handler instanceof ZPermissionsHandler)) { + LOGGER.log(Level.INFO, "Essentials: Using zPermissions based permissions."); + handler = new ZPermissionsHandler(ess); + } + return; + } - public void setUseSuperperms(final boolean useSuperperms) - { - this.useSuperperms = useSuperperms; - } + if (useSuperperms) { + if (!(handler instanceof SuperpermsHandler)) { + LOGGER.log(Level.INFO, "Essentials: Using superperms based permissions."); + handler = new SuperpermsHandler(); + } + } else { + if (!(handler instanceof ConfigPermissionsHandler)) { + LOGGER.log(Level.INFO, "Essentials: Using config file enhanced permissions."); + LOGGER.log(Level.INFO, "Permissions listed in as player-commands will be given to all users."); + handler = new ConfigPermissionsHandler(ess); + } + } + } - public String getName() - { - return handler.getClass().getSimpleName().replace("Handler", ""); - } + public void setUseSuperperms(final boolean useSuperperms) { + this.useSuperperms = useSuperperms; + } - private void checkPermLag(long start) - { - final long elapsed = System.nanoTime() - start; - if (elapsed > ess.getSettings().getPermissionsLagWarning()) - { - ess.getLogger().log(Level.INFO, "Lag Notice - Slow Permissions System (" + getName() + ") Response - Request took over {0}ms!", elapsed / 1000000.0); - } - } + public String getName() { + return handler.getClass().getSimpleName().replace("Handler", ""); + } + + private void checkPermLag(long start) { + final long elapsed = System.nanoTime() - start; + if (elapsed > ess.getSettings().getPermissionsLagWarning()) { + ess.getLogger().log(Level.INFO, "Lag Notice - Slow Permissions System (" + getName() + ") Response - Request took over {0}ms!", elapsed / 1000000.0); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/perm/PrivilegesHandler.java b/Essentials/src/com/earth2me/essentials/perm/PrivilegesHandler.java index 03db3502b..43adbbb2d 100644 --- a/Essentials/src/com/earth2me/essentials/perm/PrivilegesHandler.java +++ b/Essentials/src/com/earth2me/essentials/perm/PrivilegesHandler.java @@ -1,61 +1,53 @@ package com.earth2me.essentials.perm; -import java.util.ArrayList; -import java.util.List; import net.krinsoft.privileges.Privileges; import net.krinsoft.privileges.groups.Group; import net.krinsoft.privileges.groups.GroupManager; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; -public class PrivilegesHandler extends SuperpermsHandler -{ - private final transient Privileges plugin; - private final GroupManager manager; +import java.util.ArrayList; +import java.util.List; - public PrivilegesHandler(final Plugin plugin) - { - this.plugin = (Privileges) plugin; - this.manager = this.plugin.getGroupManager(); - } +public class PrivilegesHandler extends SuperpermsHandler { + private final transient Privileges plugin; + private final GroupManager manager; - @Override - public String getGroup(final Player base) - { - Group group = manager.getGroup(base); - if (group == null) - { - return null; - } - return group.getName(); - } + public PrivilegesHandler(final Plugin plugin) { + this.plugin = (Privileges) plugin; + this.manager = this.plugin.getGroupManager(); + } - @Override - public List getGroups(final Player base) - { - Group group = manager.getGroup(base); - if (group == null) - { - return new ArrayList(); - } - return group.getGroupTree(); - } + @Override + public String getGroup(final Player base) { + Group group = manager.getGroup(base); + if (group == null) { + return null; + } + return group.getName(); + } - @Override - public boolean inGroup(final Player base, final String group) - { - Group pGroup = manager.getGroup(base); - if (pGroup == null) - { - return false; - } - return pGroup.isMemberOf(group); - } + @Override + public List getGroups(final Player base) { + Group group = manager.getGroup(base); + if (group == null) { + return new ArrayList(); + } + return group.getGroupTree(); + } - @Override - public boolean canBuild(Player base, String group) - { - return hasPermission(base, "privileges.build"); - } + @Override + public boolean inGroup(final Player base, final String group) { + Group pGroup = manager.getGroup(base); + if (pGroup == null) { + return false; + } + return pGroup.isMemberOf(group); + } + + @Override + public boolean canBuild(Player base, String group) { + return hasPermission(base, "privileges.build"); + } } diff --git a/Essentials/src/com/earth2me/essentials/perm/SimplyPermsHandler.java b/Essentials/src/com/earth2me/essentials/perm/SimplyPermsHandler.java index 093a1551f..f8c935482 100644 --- a/Essentials/src/com/earth2me/essentials/perm/SimplyPermsHandler.java +++ b/Essentials/src/com/earth2me/essentials/perm/SimplyPermsHandler.java @@ -1,56 +1,48 @@ package com.earth2me.essentials.perm; -import java.util.List; import net.crystalyx.bukkit.simplyperms.SimplyAPI; import net.crystalyx.bukkit.simplyperms.SimplyPlugin; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; -public class SimplyPermsHandler extends SuperpermsHandler -{ +import java.util.List; - private final transient SimplyAPI api; +public class SimplyPermsHandler extends SuperpermsHandler { - public SimplyPermsHandler(final Plugin plugin) - { - this.api = ((SimplyPlugin) plugin).getAPI(); - } + private final transient SimplyAPI api; - @Override - public String getGroup(final Player base) - { - final List groups = api.getPlayerGroups(base.getName()); - if (groups == null || groups.isEmpty()) - { - return null; - } - return groups.get(0); - } + public SimplyPermsHandler(final Plugin plugin) { + this.api = ((SimplyPlugin) plugin).getAPI(); + } - @Override - public List getGroups(final Player base) - { - return api.getPlayerGroups(base.getName()); - } + @Override + public String getGroup(final Player base) { + final List groups = api.getPlayerGroups(base.getName()); + if (groups == null || groups.isEmpty()) { + return null; + } + return groups.get(0); + } - @Override - public boolean inGroup(final Player base, final String group) - { - final List groups = api.getPlayerGroups(base.getName()); - for (String group1 : groups) - { - if (group1.equalsIgnoreCase(group)) - { - return true; - } - } - return false; - } + @Override + public List getGroups(final Player base) { + return api.getPlayerGroups(base.getName()); + } - @Override - public boolean canBuild(Player base, String group) - { - return hasPermission(base, "permissions.allow.build"); - } + @Override + public boolean inGroup(final Player base, final String group) { + final List groups = api.getPlayerGroups(base.getName()); + for (String group1 : groups) { + if (group1.equalsIgnoreCase(group)) { + return true; + } + } + return false; + } + + @Override + public boolean canBuild(Player base, String group) { + return hasPermission(base, "permissions.allow.build"); + } } diff --git a/Essentials/src/com/earth2me/essentials/perm/SuperpermsHandler.java b/Essentials/src/com/earth2me/essentials/perm/SuperpermsHandler.java index 0b4b93058..b12a2a7cc 100644 --- a/Essentials/src/com/earth2me/essentials/perm/SuperpermsHandler.java +++ b/Essentials/src/com/earth2me/essentials/perm/SuperpermsHandler.java @@ -1,67 +1,57 @@ package com.earth2me.essentials.perm; -import java.util.List; import org.bukkit.entity.Player; +import java.util.List; -public class SuperpermsHandler implements IPermissionsHandler -{ - @Override - public String getGroup(final Player base) - { - return null; - } - @Override - public List getGroups(final Player base) - { - return null; - } +public class SuperpermsHandler implements IPermissionsHandler { + @Override + public String getGroup(final Player base) { + return null; + } - @Override - public boolean canBuild(final Player base, final String group) - { - return false; - } + @Override + public List getGroups(final Player base) { + return null; + } - @Override - public boolean inGroup(final Player base, final String group) - { - return hasPermission(base, "group." + group); - } + @Override + public boolean canBuild(final Player base, final String group) { + return false; + } - @Override - public boolean hasPermission(final Player base, String node) - { - String permCheck = node; - int index; - while (true) - { - if (base.isPermissionSet(permCheck)) - { - return base.hasPermission(permCheck); - } - - index = node.lastIndexOf('.'); - if (index < 1) - { - return base.hasPermission("*"); - } + @Override + public boolean inGroup(final Player base, final String group) { + return hasPermission(base, "group." + group); + } - node = node.substring(0, index); - permCheck = node + ".*"; - } - } + @Override + public boolean hasPermission(final Player base, String node) { + String permCheck = node; + int index; + while (true) { + if (base.isPermissionSet(permCheck)) { + return base.hasPermission(permCheck); + } - @Override - public String getPrefix(final Player base) - { - return null; - } + index = node.lastIndexOf('.'); + if (index < 1) { + return base.hasPermission("*"); + } - @Override - public String getSuffix(final Player base) - { - return null; - } + node = node.substring(0, index); + permCheck = node + ".*"; + } + } + + @Override + public String getPrefix(final Player base) { + return null; + } + + @Override + public String getSuffix(final Player base) { + return null; + } } diff --git a/Essentials/src/com/earth2me/essentials/perm/ZPermissionsHandler.java b/Essentials/src/com/earth2me/essentials/perm/ZPermissionsHandler.java index 6be67b3fe..36bee89c0 100644 --- a/Essentials/src/com/earth2me/essentials/perm/ZPermissionsHandler.java +++ b/Essentials/src/com/earth2me/essentials/perm/ZPermissionsHandler.java @@ -1,8 +1,5 @@ package com.earth2me.essentials.perm; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -11,175 +8,130 @@ import org.bukkit.event.server.ServiceRegisterEvent; import org.bukkit.plugin.Plugin; import org.tyrannyofheaven.bukkit.zPermissions.ZPermissionsService; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; -public class ZPermissionsHandler extends SuperpermsHandler implements Listener -{ - private ZPermissionsService service = null; - private boolean hasGetPlayerPrimaryGroup = false; // This is a post-1.0 addition - public ZPermissionsHandler(Plugin plugin) - { - acquireZPermissionsService(); - if (!isReady()) - { - // Shouldn't get to this point, since caller checks if zPerms - // is enabled. But for the sake of correctness... - Bukkit.getPluginManager().registerEvents(this, plugin); - } - } +public class ZPermissionsHandler extends SuperpermsHandler implements Listener { + private ZPermissionsService service = null; + private boolean hasGetPlayerPrimaryGroup = false; // This is a post-1.0 addition - @EventHandler - public void onServiceRegister(ServiceRegisterEvent event) - { - if (ZPermissionsService.class.equals(event.getProvider().getService())) - { - acquireZPermissionsService(); - } - } + public ZPermissionsHandler(Plugin plugin) { + acquireZPermissionsService(); + if (!isReady()) { + // Shouldn't get to this point, since caller checks if zPerms + // is enabled. But for the sake of correctness... + Bukkit.getPluginManager().registerEvents(this, plugin); + } + } - @Override - public String getGroup(Player base) - { - if (!isReady()) - { - return super.getGroup(base); - } - else - { - return getPrimaryGroup(base.getName()); - } - } + @EventHandler + public void onServiceRegister(ServiceRegisterEvent event) { + if (ZPermissionsService.class.equals(event.getProvider().getService())) { + acquireZPermissionsService(); + } + } - @Override - public List getGroups(Player base) - { - if (!isReady()) - { - return super.getGroups(base); - } - else - { - return new ArrayList(service.getPlayerGroups(base.getName())); - } - } + @Override + public String getGroup(Player base) { + if (!isReady()) { + return super.getGroup(base); + } else { + return getPrimaryGroup(base.getName()); + } + } - @Override - public boolean inGroup(Player base, String group) - { - if (!isReady()) - { - return super.inGroup(base, group); - } - else - { - Set groups = service.getPlayerGroups(base.getName()); - for (String test : groups) - { - if (test.equalsIgnoreCase(group)) - { - return true; - } - } - return false; - } - } + @Override + public List getGroups(Player base) { + if (!isReady()) { + return super.getGroups(base); + } else { + return new ArrayList(service.getPlayerGroups(base.getName())); + } + } - @Override - public String getPrefix(Player base) - { - if (!isReady()) - { - return super.getPrefix(base); - } - else - { - return getPrefixSuffix(base, "prefix"); - } - } + @Override + public boolean inGroup(Player base, String group) { + if (!isReady()) { + return super.inGroup(base, group); + } else { + Set groups = service.getPlayerGroups(base.getName()); + for (String test : groups) { + if (test.equalsIgnoreCase(group)) { + return true; + } + } + return false; + } + } - @Override - public String getSuffix(Player base) - { - if (!isReady()) - { - return super.getSuffix(base); - } - else - { - return getPrefixSuffix(base, "suffix"); - } - } + @Override + public String getPrefix(Player base) { + if (!isReady()) { + return super.getPrefix(base); + } else { + return getPrefixSuffix(base, "prefix"); + } + } - private String getPrefixSuffix(Player base, String metadataName) - { - String playerPrefixSuffix; - try - { - playerPrefixSuffix = service.getPlayerMetadata(base.getName(), metadataName, String.class); - } - catch (IllegalStateException e) - { - // User error. They set prefix to a non-string. - playerPrefixSuffix = null; - } - if (playerPrefixSuffix == null) - { - // Try prefix/suffix of their "primary group" - try - { - return service.getGroupMetadata(getPrimaryGroup(base.getName()), metadataName, String.class); - } - catch (IllegalStateException e) - { - // User error, again - return null; - } - } - else - { - return playerPrefixSuffix; - } - } + @Override + public String getSuffix(Player base) { + if (!isReady()) { + return super.getSuffix(base); + } else { + return getPrefixSuffix(base, "suffix"); + } + } - private void acquireZPermissionsService() - { - service = Bukkit.getServicesManager().load(ZPermissionsService.class); - if (isReady()) - { - // getPlayerPrimaryGroup(String) was added in an unreleased version - // Check if it exists. - try - { - service.getClass().getMethod("getPlayerPrimaryGroup", String.class); - hasGetPlayerPrimaryGroup = true; - } - catch (NoSuchMethodException e) - { - hasGetPlayerPrimaryGroup = false; - } - catch (SecurityException e) - { - hasGetPlayerPrimaryGroup = false; - } - } - } + private String getPrefixSuffix(Player base, String metadataName) { + String playerPrefixSuffix; + try { + playerPrefixSuffix = service.getPlayerMetadata(base.getName(), metadataName, String.class); + } catch (IllegalStateException e) { + // User error. They set prefix to a non-string. + playerPrefixSuffix = null; + } + if (playerPrefixSuffix == null) { + // Try prefix/suffix of their "primary group" + try { + return service.getGroupMetadata(getPrimaryGroup(base.getName()), metadataName, String.class); + } catch (IllegalStateException e) { + // User error, again + return null; + } + } else { + return playerPrefixSuffix; + } + } - private boolean isReady() - { - return service != null; - } + private void acquireZPermissionsService() { + service = Bukkit.getServicesManager().load(ZPermissionsService.class); + if (isReady()) { + // getPlayerPrimaryGroup(String) was added in an unreleased version + // Check if it exists. + try { + service.getClass().getMethod("getPlayerPrimaryGroup", String.class); + hasGetPlayerPrimaryGroup = true; + } catch (NoSuchMethodException e) { + hasGetPlayerPrimaryGroup = false; + } catch (SecurityException e) { + hasGetPlayerPrimaryGroup = false; + } + } + } - private String getPrimaryGroup(String playerName) - { - if (hasGetPlayerPrimaryGroup) - { - return service.getPlayerPrimaryGroup(playerName); - } - else - { - // Fall back to using highest-weight assigned group - List groups = service.getPlayerAssignedGroups(playerName); - return groups.get(0); - } - } + private boolean isReady() { + return service != null; + } + + private String getPrimaryGroup(String playerName) { + if (hasGetPlayerPrimaryGroup) { + return service.getPlayerPrimaryGroup(playerName); + } else { + // Fall back to using highest-weight assigned group + List groups = service.getPlayerAssignedGroups(playerName); + return groups.get(0); + } + } } diff --git a/Essentials/src/com/earth2me/essentials/register/payment/Method.java b/Essentials/src/com/earth2me/essentials/register/payment/Method.java index c4c9d401a..41ad59070 100644 --- a/Essentials/src/com/earth2me/essentials/register/payment/Method.java +++ b/Essentials/src/com/earth2me/essentials/register/payment/Method.java @@ -10,208 +10,213 @@ import org.bukkit.plugin.Plugin; * @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(); +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 name of this method. + * + * @return String Plugin name. + */ + public String getName(); - /** - * Returns the actual version of this method. - * - * @return String Plugin version. - */ - public String getVersion(); + /** + * Returns the reported name of this method. + * + * @return String Plugin name. + */ + public String getLongName(); - /** - * 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(); + /** + * Returns the actual version of this method. + * + * @return String Plugin version. + */ + public String getVersion(); - /** - * Formats amounts into this payment methods style of currency display. - * - * @param amount Double - * @return String - Formatted Currency Display. - */ - public String format(double amount); + /** + * 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(); - /** - * Allows the verification of bank API existence in this payment method. - * - * @return boolean - */ - public boolean hasBanks(); + /** + * Formats amounts into this payment methods style of currency display. + * + * @param amount Double + * + * @return String - Formatted Currency Display. + */ + public String format(double amount); - /** - * Determines the existence of a bank via name. - * - * @param bank Bank name - * @return boolean - * @see #hasBanks - */ - public boolean hasBank(String bank); + /** + * Allows the verification of bank API existence in this payment method. + * + * @return boolean + */ + public boolean hasBanks(); - /** - * Determines the existence of an account via name. - * - * @param name Account name - * @return boolean - */ - public boolean hasAccount(String name); + /** + * Determines the existence of a bank via name. + * + * @param bank Bank name + * + * @return boolean + * + * @see #hasBanks + */ + public boolean hasBank(String bank); - /** - * 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); + /** + * Determines the existence of an account via name. + * + * @param name Account name + * + * @return boolean + */ + public boolean hasAccount(String name); - /** - * Forces an account creation - * - * @param name Account name - * @return boolean - */ - public boolean createAccount(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 - * @param balance Initial account balance - * @return boolean - */ - public boolean createAccount(String name, Double balance); + /** + * Forces an account creation + * + * @param name Account name + * + * @return boolean + */ + public boolean createAccount(String name); - /** - * Returns a MethodAccount class for an account name. - * - * @param name Account name - * @return MethodAccount or Null - */ - public MethodAccount getAccount(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 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); + /** + * Returns a MethodAccount class for an account name. + * + * @param name Account name + * + * @return MethodAccount or Null + */ + public MethodAccount getAccount(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); + /** + * 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); - /** - * Set Plugin data. - * - * @param plugin Plugin - */ - public void setPlugin(Plugin plugin); + /** + * 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(); + /** + * Contains Calculator and Balance functions for Accounts. + */ + public interface MethodAccount { + public double balance(); - public boolean set(double amount); + public boolean set(double amount); - public boolean add(double amount); + public boolean add(double amount); - public boolean subtract(double amount); + public boolean subtract(double amount); - public boolean multiply(double amount); + public boolean multiply(double amount); - public boolean divide(double amount); + public boolean divide(double amount); - public boolean hasEnough(double amount); + public boolean hasEnough(double amount); - public boolean hasOver(double amount); + public boolean hasOver(double amount); - public boolean hasUnder(double amount); + public boolean hasUnder(double amount); - public boolean isNegative(); + public boolean isNegative(); - public boolean remove(); + public boolean remove(); - @Override - public String toString(); - } + @Override + public String toString(); + } - /** - * Contains Calculator and Balance functions for Bank Accounts. - */ - public interface MethodBankAccount - { - public double balance(); + /** + * Contains Calculator and Balance functions for Bank Accounts. + */ + public interface MethodBankAccount { + public double balance(); - public String getBankName(); + public String getBankName(); - public int getBankId(); + public int getBankId(); - public boolean set(double amount); + public boolean set(double amount); - public boolean add(double amount); + public boolean add(double amount); - public boolean subtract(double amount); + public boolean subtract(double amount); - public boolean multiply(double amount); + public boolean multiply(double amount); - public boolean divide(double amount); + public boolean divide(double amount); - public boolean hasEnough(double amount); + public boolean hasEnough(double amount); - public boolean hasOver(double amount); + public boolean hasOver(double amount); - public boolean hasUnder(double amount); + public boolean hasUnder(double amount); - public boolean isNegative(); + public boolean isNegative(); - public boolean remove(); + public boolean remove(); - @Override - public String toString(); - } + @Override + public String toString(); + } } diff --git a/Essentials/src/com/earth2me/essentials/register/payment/Methods.java b/Essentials/src/com/earth2me/essentials/register/payment/Methods.java index 3ba5393b1..3cfa6b630 100644 --- a/Essentials/src/com/earth2me/essentials/register/payment/Methods.java +++ b/Essentials/src/com/earth2me/essentials/register/payment/Methods.java @@ -1,21 +1,21 @@ package com.earth2me.essentials.register.payment; -import java.util.HashSet; -import java.util.Set; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; +import java.util.HashSet; +import java.util.Set; + /** - * The - * Methods initializes Methods that utilize the Method interface based on a "first come, first served" + * 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:
@@ -25,270 +25,226 @@ import org.bukkit.plugin.PluginManager;
  * @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 final Set Methods = new HashSet();
-	private static final Set Dependencies = new HashSet();
-	private static final Set Attachables = new HashSet();
+public class Methods {
+    private static String version = null;
+    private static boolean self = false;
+    private static Method Method = null;
+    private static String preferred = "";
+    private static final Set Methods = new HashSet();
+    private static final Set Dependencies = new HashSet();
+    private static final Set Attachables = new HashSet();
 
-	static
-	{
-		_init();
-	}
+    static {
+        _init();
+    }
 
-	/**
-	 * Implement all methods along with their respective name & class.
-	 */
-	private static void _init()
-	{
-		addMethod("iConomy", new com.earth2me.essentials.register.payment.methods.iCo6());
-		addMethod("iConomy", new com.earth2me.essentials.register.payment.methods.iCo5());
-		addMethod("BOSEconomy", new com.earth2me.essentials.register.payment.methods.BOSE7());
-		addMethod("Currency", new com.earth2me.essentials.register.payment.methods.MCUR());
-		Dependencies.add("MultiCurrency");
-		addMethod("Vault", new com.earth2me.essentials.register.payment.methods.VaultEco());
-	}
+    /**
+     * Implement all methods along with their respective name & class.
+     */
+    private static void _init() {
+        addMethod("iConomy", new com.earth2me.essentials.register.payment.methods.iCo6());
+        addMethod("iConomy", new com.earth2me.essentials.register.payment.methods.iCo5());
+        addMethod("BOSEconomy", new com.earth2me.essentials.register.payment.methods.BOSE7());
+        addMethod("Currency", new com.earth2me.essentials.register.payment.methods.MCUR());
+        Dependencies.add("MultiCurrency");
+        addMethod("Vault", new com.earth2me.essentials.register.payment.methods.VaultEco());
+    }
 
-	/**
-	 * Used by the plugin to setup version
-	 *
-	 * @param v version
-	 */
-	public static void setVersion(String v)
-	{
-		version = v;
-	}
+    /**
+     * 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 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;
-	}
+    /**
+     * 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;
-	}
+    /**
+     * 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;
-			}
-		}
+    /**
+     * 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;
-	}
+        return null;
+    }
 
-	private static void addMethod(String name, Method method)
-	{
-		Dependencies.add(name);
-		Methods.add(method);
-	}
+    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);
-	}
+    /**
+     * 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;
-		}
+    /**
+     * 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;
-		}
+        if (self) {
+            self = false;
+            return false;
+        }
 
-		int count = 0;
-		boolean match = false;
-		Plugin plugin = null;
+        int count = 0;
+        boolean match = false;
+        Plugin plugin = null;
 
-		for (String name : getDependencies())
-		{
-			if (hasMethod())
-			{
-				break;
-			}
+        for (String name : getDependencies()) {
+            if (hasMethod()) {
+                break;
+            }
 
-			plugin = manager.getPlugin(name);
-			if (plugin == null || !plugin.isEnabled())
-			{
-				continue;
-			}
+            plugin = manager.getPlugin(name);
+            if (plugin == null || !plugin.isEnabled()) {
+                continue;
+            }
 
-			Method current = createMethod(plugin);
-			if (current == null)
-			{
-				continue;
-			}
+            Method current = createMethod(plugin);
+            if (current == null) {
+                continue;
+            }
 
-			if (preferred.isEmpty())
-			{
-				Method = current;
-			}
-			else
-			{
-				Attachables.add(current);
-			}
-		}
+            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 (!preferred.isEmpty()) {
+            do {
+                if (hasMethod()) {
+                    match = true;
+                } else {
+                    for (Method attached : Attachables) {
+                        if (attached == null) {
+                            continue;
+                        }
 
-						if (hasMethod())
-						{
-							match = true;
-							break;
-						}
+                        if (hasMethod()) {
+                            match = true;
+                            break;
+                        }
 
-						if (preferred.isEmpty())
-						{
-							Method = attached;
-						}
+                        if (preferred.isEmpty()) {
+                            Method = attached;
+                        }
 
-						if (count == 0)
-						{
-							if (preferred.equalsIgnoreCase(attached.getName()))
-							{
-								Method = attached;
-							}
-							else
-							{
-								Method = attached;
-							}
-						}
-					}
+                        if (count == 0) {
+                            if (preferred.equalsIgnoreCase(attached.getName())) {
+                                Method = attached;
+                            } else {
+                                Method = attached;
+                            }
+                        }
+                    }
 
-					count++;
-				}
-			}
-			while (!match);
-		}
+                    count++;
+                }
+            } while (!match);
+        }
 
-		return hasMethod();
-	}
+        return hasMethod();
+    }
 
-	/**
-	 * Sets the preferred economy
-	 *
-	 * @return
-	 * boolean
-	 */
-	public static boolean setPreferred(String check)
-	{
-		if (getDependencies().contains(check))
-		{
-			preferred = check;
-			return true;
-		}
+    /**
+     * Sets the preferred economy
+     *
+     * @return boolean
+     */
+    public static boolean setPreferred(String check) {
+        if (getDependencies().contains(check)) {
+            preferred = check;
+            return true;
+        }
 
-		return false;
-	}
+        return false;
+    }
 
-	/**
-	 * Grab the existing and initialized (hopefully) Method Class.
-	 *
-	 * @return
-	 * Method or
-	 * Null
-	 */
-	public static Method getMethod()
-	{
-		return Method;
-	}
+    /**
+     * 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;
-		}
+    /**
+     * 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;
-		}
+        if (Method.isCompatible(method)) {
+            Method = null;
+        }
 
-		return (Method == null);
-	}
+        return (Method == null);
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/register/payment/methods/BOSE7.java b/Essentials/src/com/earth2me/essentials/register/payment/methods/BOSE7.java
index a554548ea..5616d2d95 100644
--- a/Essentials/src/com/earth2me/essentials/register/payment/methods/BOSE7.java
+++ b/Essentials/src/com/earth2me/essentials/register/payment/methods/BOSE7.java
@@ -10,314 +10,262 @@ import org.bukkit.plugin.Plugin;
  *
  * @author Acrobot
  * @author Nijikokun  (@nijikokun) @copyright (c) 2011 @license AOL license
- * 
+ *         
  */
-public class BOSE7 implements Method
-{
-	private BOSEconomy BOSEconomy;
+public class BOSE7 implements Method {
+    private BOSEconomy BOSEconomy;
 
-	@Override
-	public BOSEconomy getPlugin()
-	{
-		return this.BOSEconomy;
-	}
+    @Override
+    public BOSEconomy getPlugin() {
+        return this.BOSEconomy;
+    }
 
-	@Override
-	public String getName()
-	{
-		return "BOSEconomy";
-	}
+    @Override
+    public String getName() {
+        return "BOSEconomy";
+    }
 
-	@Override
-	public String getLongName()
-	{
-		return getName();
-	}
+    @Override
+    public String getLongName() {
+        return getName();
+    }
 
-	@Override
-	public String getVersion()
-	{
-		return "0.7.0";
-	}
+    @Override
+    public String getVersion() {
+        return "0.7.0";
+    }
 
-	@Override
-	public int fractionalDigits()
-	{
-		return this.BOSEconomy.getFractionalDigits();
-	}
+    @Override
+    public int fractionalDigits() {
+        return this.BOSEconomy.getFractionalDigits();
+    }
 
-	@Override
-	public String format(double amount)
-	{
-		String currency = this.BOSEconomy.getMoneyNamePlural();
+    @Override
+    public String format(double amount) {
+        String currency = this.BOSEconomy.getMoneyNamePlural();
 
-		if (amount == 1)
-		{
-			currency = this.BOSEconomy.getMoneyName();
-		}
+        if (amount == 1) {
+            currency = this.BOSEconomy.getMoneyName();
+        }
 
-		return amount + " " + currency;
-	}
+        return amount + " " + currency;
+    }
 
-	@Override
-	public boolean hasBanks()
-	{
-		return true;
-	}
+    @Override
+    public boolean hasBanks() {
+        return true;
+    }
 
-	@Override
-	public boolean hasBank(String bank)
-	{
-		return this.BOSEconomy.bankExists(bank);
-	}
+    @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 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 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;
-		}
+    @Override
+    public boolean createAccount(String name) {
+        if (hasAccount(name)) {
+            return false;
+        }
 
-		this.BOSEconomy.registerPlayer(name);
-		return true;
-	}
+        this.BOSEconomy.registerPlayer(name);
+        return true;
+    }
 
-	@Override
-	public boolean createAccount(String name, Double balance)
-	{
-		if (hasAccount(name))
-		{
-			return false;
-		}
+    @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;
-	}
+        this.BOSEconomy.registerPlayer(name);
+        this.BOSEconomy.setPlayerMoney(name, balance, false);
+        return true;
+    }
 
-	@Override
-	public MethodAccount getAccount(String name)
-	{
-		if (!hasAccount(name))
-		{
-			return null;
-		}
+    @Override
+    public MethodAccount getAccount(String name) {
+        if (!hasAccount(name)) {
+            return null;
+        }
 
-		return new BOSEAccount(name, this.BOSEconomy);
-	}
+        return new BOSEAccount(name, this.BOSEconomy);
+    }
 
-	@Override
-	public MethodBankAccount getBankAccount(String bank, String name)
-	{
-		if (!hasBankAccount(bank, name))
-		{
-			return null;
-		}
+    @Override
+    public MethodBankAccount getBankAccount(String bank, String name) {
+        if (!hasBankAccount(bank, name)) {
+            return null;
+        }
 
-		return new BOSEBankAccount(bank, BOSEconomy);
-	}
+        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 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;
-	}
+    @Override
+    public void setPlugin(Plugin plugin) {
+        BOSEconomy = (BOSEconomy) plugin;
+    }
 
 
-	public class BOSEAccount implements MethodAccount
-	{
-		private final String name;
-		private final BOSEconomy BOSEconomy;
+    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;
-		}
+        public BOSEAccount(String name, BOSEconomy bOSEconomy) {
+            this.name = name;
+            this.BOSEconomy = bOSEconomy;
+        }
 
-		@Override
-		public double balance()
-		{
-			return this.BOSEconomy.getPlayerMoneyDouble(this.name);
-		}
+        @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 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 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 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 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 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 hasEnough(double amount) {
+            return (this.balance() >= amount);
+        }
 
-		@Override
-		public boolean hasOver(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 hasUnder(double amount) {
+            return (this.balance() < amount);
+        }
 
-		@Override
-		public boolean isNegative()
-		{
-			return (this.balance() < 0);
-		}
+        @Override
+        public boolean isNegative() {
+            return (this.balance() < 0);
+        }
 
-		@Override
-		public boolean remove()
-		{
-			return false;
-		}
-	}
+        @Override
+        public boolean remove() {
+            return false;
+        }
+    }
 
 
-	public class BOSEBankAccount implements MethodBankAccount
-	{
-		private final String bank;
-		private final BOSEconomy BOSEconomy;
+    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;
-		}
+        public BOSEBankAccount(String bank, BOSEconomy bOSEconomy) {
+            this.bank = bank;
+            this.BOSEconomy = bOSEconomy;
+        }
 
-		@Override
-		public String getBankName()
-		{
-			return this.bank;
-		}
+        @Override
+        public String getBankName() {
+            return this.bank;
+        }
 
-		@Override
-		public int getBankId()
-		{
-			return -1;
-		}
+        @Override
+        public int getBankId() {
+            return -1;
+        }
 
-		@Override
-		public double balance()
-		{
-			return this.BOSEconomy.getBankMoneyDouble(bank);
-		}
+        @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 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 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 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 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 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 hasEnough(double amount) {
+            return (this.balance() >= amount);
+        }
 
-		@Override
-		public boolean hasOver(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 hasUnder(double amount) {
+            return (this.balance() < amount);
+        }
 
-		@Override
-		public boolean isNegative()
-		{
-			return (this.balance() < 0);
-		}
+        @Override
+        public boolean isNegative() {
+            return (this.balance() < 0);
+        }
 
-		@Override
-		public boolean remove()
-		{
-			return this.BOSEconomy.removeBank(bank);
-		}
-	}
+        @Override
+        public boolean remove() {
+            return this.BOSEconomy.removeBank(bank);
+        }
+    }
 }
\ No newline at end of file
diff --git a/Essentials/src/com/earth2me/essentials/register/payment/methods/MCUR.java b/Essentials/src/com/earth2me/essentials/register/payment/methods/MCUR.java
index efcb20fb9..b470051b6 100644
--- a/Essentials/src/com/earth2me/essentials/register/payment/methods/MCUR.java
+++ b/Essentials/src/com/earth2me/essentials/register/payment/methods/MCUR.java
@@ -11,185 +11,153 @@ import org.bukkit.plugin.Plugin;
  *
  * @author Acrobot @copyright (c) 2011 @license AOL license 
  */
-public class MCUR implements Method
-{
-	private Currency currencyList;
+public class MCUR implements Method {
+    private Currency currencyList;
 
-	@Override
-	public Object getPlugin()
-	{
-		return this.currencyList;
-	}
+    @Override
+    public Object getPlugin() {
+        return this.currencyList;
+    }
 
-	@Override
-	public String getName()
-	{
-		return "MultiCurrency";
-	}
+    @Override
+    public String getName() {
+        return "MultiCurrency";
+    }
 
-	@Override
-	public String getLongName()
-	{
-		return getName();
-	}
+    @Override
+    public String getLongName() {
+        return getName();
+    }
 
-	@Override
-	public String getVersion()
-	{
-		return "0.09";
-	}
+    @Override
+    public String getVersion() {
+        return "0.09";
+    }
 
-	@Override
-	public int fractionalDigits()
-	{
-		return -1;
-	}
+    @Override
+    public int fractionalDigits() {
+        return -1;
+    }
 
-	@Override
-	public String format(double amount)
-	{
-		return amount + " Currency";
-	}
+    @Override
+    public String format(double amount) {
+        return amount + " Currency";
+    }
 
-	@Override
-	public boolean hasBanks()
-	{
-		return false;
-	}
+    @Override
+    public boolean hasBanks() {
+        return false;
+    }
 
-	@Override
-	public boolean hasBank(String bank)
-	{
-		return false;
-	}
+    @Override
+    public boolean hasBank(String bank) {
+        return false;
+    }
 
-	@Override
-	public boolean hasAccount(String name)
-	{
-		return true;
-	}
+    @Override
+    public boolean hasAccount(String name) {
+        return true;
+    }
 
-	@Override
-	public boolean hasBankAccount(String bank, String name)
-	{
-		return false;
-	}
+    @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) {
+        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 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 MethodAccount getAccount(String name) {
+        return new MCurrencyAccount(name);
+    }
 
-	@Override
-	public MethodBankAccount getBankAccount(String bank, String name)
-	{
-		return null;
-	}
+    @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 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;
-	}
+    @Override
+    public void setPlugin(Plugin plugin) {
+        currencyList = (Currency) plugin;
+    }
 
 
-	public class MCurrencyAccount implements MethodAccount
-	{
-		private final String name;
+    public class MCurrencyAccount implements MethodAccount {
+        private final String name;
 
-		public MCurrencyAccount(String name)
-		{
-			this.name = name;
-		}
+        public MCurrencyAccount(String name) {
+            this.name = name;
+        }
 
-		@Override
-		public double balance()
-		{
-			return CurrencyList.getValue((String)CurrencyList.maxCurrency(name)[0], 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 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 add(double amount) {
+            return CurrencyList.add(name, amount);
+        }
 
-		@Override
-		public boolean subtract(double amount)
-		{
-			return CurrencyList.subtract(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 multiply(double amount) {
+            return CurrencyList.multiply(name, amount);
+        }
 
-		@Override
-		public boolean divide(double amount)
-		{
-			return CurrencyList.divide(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 hasEnough(double amount) {
+            return CurrencyList.hasEnough(name, amount);
+        }
 
-		@Override
-		public boolean hasOver(double amount)
-		{
-			return CurrencyList.hasOver(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 hasUnder(double amount) {
+            return CurrencyList.hasUnder(name, amount);
+        }
 
-		@Override
-		public boolean isNegative()
-		{
-			return CurrencyList.isNegative(name);
-		}
+        @Override
+        public boolean isNegative() {
+            return CurrencyList.isNegative(name);
+        }
 
-		@Override
-		public boolean remove()
-		{
-			return CurrencyList.remove(name);
-		}
-	}
+        @Override
+        public boolean remove() {
+            return CurrencyList.remove(name);
+        }
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/register/payment/methods/VaultEco.java b/Essentials/src/com/earth2me/essentials/register/payment/methods/VaultEco.java
index b1863c487..b7833d8c1 100644
--- a/Essentials/src/com/earth2me/essentials/register/payment/methods/VaultEco.java
+++ b/Essentials/src/com/earth2me/essentials/register/payment/methods/VaultEco.java
@@ -7,341 +7,279 @@ import org.bukkit.plugin.Plugin;
 import org.bukkit.plugin.RegisteredServiceProvider;
 
 
-public class VaultEco implements Method
-{
-	private Vault vault;
-	private Economy economy;
+public class VaultEco implements Method {
+    private Vault vault;
+    private Economy economy;
 
-	@Override
-	public Vault getPlugin()
-	{
-		return this.vault;
-	}
+    @Override
+    public Vault getPlugin() {
+        return this.vault;
+    }
 
-	@Override
-	public boolean createAccount(String name, Double amount)
-	{
-		if (hasAccount(name))
-		{
-			return false;
-		}
+    @Override
+    public boolean createAccount(String name, Double amount) {
+        if (hasAccount(name)) {
+            return false;
+        }
 
-		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 getName() {
+        return this.vault.getDescription().getName();
+    }
 
-	@Override
-	public String getVersion()
-	{
-		return this.vault.getDescription().getVersion();
-	}
+    public String getEconomy() {
+        return economy == null ? "NoEco" : economy.getName();
+    }
 
-	@Override
-	public int fractionalDigits()
-	{
-		return 0;
-	}
+    @Override
+    public String getLongName() {
+        return getName().concat(" - Economy: ").concat(getEconomy());
+    }
 
-	@Override
-	public String format(double amount)
-	{
-		return this.economy.format(amount);
-	}
+    @Override
+    public String getVersion() {
+        return this.vault.getDescription().getVersion();
+    }
 
-	@Override
-	public boolean hasBanks()
-	{
-		return this.economy.hasBankSupport();
-	}
+    @Override
+    public int fractionalDigits() {
+        return 0;
+    }
 
-	@Override
-	public boolean hasBank(String bank)
-	{
-		return this.economy.getBanks().contains(bank);
-	}
+    @Override
+    public String format(double amount) {
+        return this.economy.format(amount);
+    }
 
-	@Override
-	public boolean hasAccount(String name)
-	{
-		return this.economy.hasAccount(name);
-	}
+    @Override
+    public boolean hasBanks() {
+        return this.economy.hasBankSupport();
+    }
 
-	@Override
-	public boolean hasBankAccount(String bank, String name)
-	{
-		return this.economy.isBankOwner(bank, name).transactionSuccess()
-			   || this.economy.isBankMember(bank, name).transactionSuccess();
-	}
+    @Override
+    public boolean hasBank(String bank) {
+        return this.economy.getBanks().contains(bank);
+    }
 
-	@Override
-	public boolean createAccount(String name)
-	{
-		return this.economy.createBank(name, "").transactionSuccess();
-	}
+    @Override
+    public boolean hasAccount(String name) {
+        return this.economy.hasAccount(name);
+    }
 
-	public boolean createAccount(String name, double balance)
-	{
-		if (!this.economy.createBank(name, "").transactionSuccess())
-		{
-			return false;
-		}
-		return this.economy.bankDeposit(name, balance).transactionSuccess();
-	}
+    @Override
+    public boolean hasBankAccount(String bank, String name) {
+        return this.economy.isBankOwner(bank, name).transactionSuccess() || this.economy.isBankMember(bank, name).transactionSuccess();
+    }
 
-	@Override
-	public MethodAccount getAccount(String name)
-	{
-		if (!hasAccount(name))
-		{
-			return null;
-		}
+    @Override
+    public boolean createAccount(String name) {
+        return this.economy.createBank(name, "").transactionSuccess();
+    }
 
-		return new VaultAccount(name, this.economy);
-	}
+    public boolean createAccount(String name, double balance) {
+        if (!this.economy.createBank(name, "").transactionSuccess()) {
+            return false;
+        }
+        return this.economy.bankDeposit(name, balance).transactionSuccess();
+    }
 
-	@Override
-	public MethodBankAccount getBankAccount(String bank, String name)
-	{
-		if (!hasBankAccount(bank, name))
-		{
-			return null;
-		}
+    @Override
+    public MethodAccount getAccount(String name) {
+        if (!hasAccount(name)) {
+            return null;
+        }
 
-		return new VaultBankAccount(bank, economy);
-	}
+        return new VaultAccount(name, this.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 MethodBankAccount getBankAccount(String bank, String name) {
+        if (!hasBankAccount(bank, name)) {
+            return null;
+        }
 
-	@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();
-		}
-	}
+        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 class VaultAccount implements MethodAccount {
+        private final String name;
+        private final Economy economy;
 
-		public VaultAccount(String name, Economy economy)
-		{
-			this.name = name;
-			this.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 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 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 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 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 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 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 hasEnough(double amount) {
+            return (this.balance() >= amount);
+        }
 
-		@Override
-		public boolean hasOver(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 hasUnder(double amount) {
+            return (this.balance() < amount);
+        }
 
-		@Override
-		public boolean isNegative()
-		{
-			return (this.balance() < 0);
-		}
+        @Override
+        public boolean isNegative() {
+            return (this.balance() < 0);
+        }
 
-		@Override
-		public boolean remove()
-		{
-			return this.set(0.0);
-		}
-	}
+        @Override
+        public boolean remove() {
+            return this.set(0.0);
+        }
+    }
 
 
-	public class VaultBankAccount implements MethodBankAccount
-	{
-		private final String bank;
-		private final Economy economy;
+    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;
-		}
+        public VaultBankAccount(String bank, Economy economy) {
+            this.bank = bank;
+            this.economy = economy;
+        }
 
-		@Override
-		public String getBankName()
-		{
-			return this.bank;
-		}
+        @Override
+        public String getBankName() {
+            return this.bank;
+        }
 
-		@Override
-		public int getBankId()
-		{
-			return -1;
-		}
+        @Override
+        public int getBankId() {
+            return -1;
+        }
 
-		@Override
-		public double balance()
-		{
-			return this.economy.bankBalance(this.bank).balance;
-		}
+        @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 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 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 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 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 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 hasEnough(double amount) {
+            return (this.balance() >= amount);
+        }
 
-		@Override
-		public boolean hasOver(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 hasUnder(double amount) {
+            return (this.balance() < amount);
+        }
 
-		@Override
-		public boolean isNegative()
-		{
-			return (this.balance() < 0);
-		}
+        @Override
+        public boolean isNegative() {
+            return (this.balance() < 0);
+        }
 
-		@Override
-		public boolean remove()
-		{
-			return this.set(0.0);
-		}
-	}
+        @Override
+        public boolean remove() {
+            return this.set(0.0);
+        }
+    }
 }
\ No newline at end of file
diff --git a/Essentials/src/com/earth2me/essentials/register/payment/methods/iCo5.java b/Essentials/src/com/earth2me/essentials/register/payment/methods/iCo5.java
index 75f052846..8a5dd6428 100644
--- a/Essentials/src/com/earth2me/essentials/register/payment/methods/iCo5.java
+++ b/Essentials/src/com/earth2me/essentials/register/payment/methods/iCo5.java
@@ -13,364 +13,300 @@ 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;
+public class iCo5 implements Method {
+    private iConomy iConomy;
 
-	@Override
-	public iConomy getPlugin()
-	{
-		return this.iConomy;
-	}
+    @Override
+    public iConomy getPlugin() {
+        return this.iConomy;
+    }
 
-	@Override
-	public String getName()
-	{
-		return "iConomy";
-	}
+    @Override
+    public String getName() {
+        return "iConomy";
+    }
 
-	@Override
-	public String getLongName()
-	{
-		return getName();
-	}
+    @Override
+    public String getLongName() {
+        return getName();
+    }
 
-	@Override
-	public String getVersion()
-	{
-		return "5";
-	}
+    @Override
+    public String getVersion() {
+        return "5";
+    }
 
-	@Override
-	public int fractionalDigits()
-	{
-		return 2;
-	}
+    @Override
+    public int fractionalDigits() {
+        return 2;
+    }
 
-	@Override
-	public String format(double amount)
-	{
-		return com.iConomy.iConomy.format(amount);
-	}
+    @Override
+    public String format(double amount) {
+        return com.iConomy.iConomy.format(amount);
+    }
 
-	@Override
-	public boolean hasBanks()
-	{
-		return Constants.Banking;
-	}
+    @Override
+    public boolean hasBanks() {
+        return Constants.Banking;
+    }
 
-	@Override
-	public boolean hasBank(String bank)
-	{
-		return (hasBanks()) && com.iConomy.iConomy.Banks.exists(bank);
-	}
+    @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 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 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;
-		}
+    @Override
+    public boolean createAccount(String name) {
+        if (hasAccount(name)) {
+            return false;
+        }
 
-		return com.iConomy.iConomy.Accounts.create(name);
-	}
+        return com.iConomy.iConomy.Accounts.create(name);
+    }
 
-	@Override
-	public boolean createAccount(String name, Double balance)
-	{
-		if (hasAccount(name))
-		{
-			return false;
-		}
+    @Override
+    public boolean createAccount(String name, Double balance) {
+        if (hasAccount(name)) {
+            return false;
+        }
 
-		if (!com.iConomy.iConomy.Accounts.create(name))
-		{
-			return false;
-		}
+        if (!com.iConomy.iConomy.Accounts.create(name)) {
+            return false;
+        }
 
-		getAccount(name).set(balance);
+        getAccount(name).set(balance);
 
-		return true;
-	}
+        return true;
+    }
 
-	@Override
-	public MethodAccount getAccount(String name)
-	{
-		return new iCoAccount(com.iConomy.iConomy.getAccount(name));
-	}
+    @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 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 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;
-	}
+    @Override
+    public void setPlugin(Plugin plugin) {
+        iConomy = (iConomy) plugin;
+    }
 
 
-	public class iCoAccount implements MethodAccount
-	{
-		private final Account account;
-		private final Holdings holdings;
+    public class iCoAccount implements MethodAccount {
+        private final Account account;
+        private final Holdings holdings;
 
-		public iCoAccount(Account account)
-		{
-			this.account = account;
-			this.holdings = account.getHoldings();
-		}
+        public iCoAccount(Account account) {
+            this.account = account;
+            this.holdings = account.getHoldings();
+        }
 
-		public Account getiCoAccount()
-		{
-			return account;
-		}
+        public Account getiCoAccount() {
+            return account;
+        }
 
-		@Override
-		public double balance()
-		{
-			return this.holdings.balance();
-		}
+        @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 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 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 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 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 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 hasEnough(double amount) {
+            return this.holdings.hasEnough(amount);
+        }
 
-		@Override
-		public boolean hasOver(double amount)
-		{
-			return this.holdings.hasOver(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 hasUnder(double amount) {
+            return this.holdings.hasUnder(amount);
+        }
 
-		@Override
-		public boolean isNegative()
-		{
-			return this.holdings.isNegative();
-		}
+        @Override
+        public boolean isNegative() {
+            return this.holdings.isNegative();
+        }
 
-		@Override
-		public boolean remove()
-		{
-			if (this.account == null)
-			{
-				return false;
-			}
-			this.account.remove();
-			return true;
-		}
-	}
+        @Override
+        public boolean remove() {
+            if (this.account == null) {
+                return false;
+            }
+            this.account.remove();
+            return true;
+        }
+    }
 
 
-	public class iCoBankAccount implements MethodBankAccount
-	{
-		private final BankAccount account;
-		private final Holdings holdings;
+    public class iCoBankAccount implements MethodBankAccount {
+        private final BankAccount account;
+        private final Holdings holdings;
 
-		public iCoBankAccount(BankAccount account)
-		{
-			this.account = account;
-			this.holdings = account.getHoldings();
-		}
+        public iCoBankAccount(BankAccount account) {
+            this.account = account;
+            this.holdings = account.getHoldings();
+        }
 
-		public BankAccount getiCoBankAccount()
-		{
-			return account;
-		}
+        public BankAccount getiCoBankAccount() {
+            return account;
+        }
 
-		@Override
-		public String getBankName()
-		{
-			return this.account.getBankName();
-		}
+        @Override
+        public String getBankName() {
+            return this.account.getBankName();
+        }
 
-		@Override
-		public int getBankId()
-		{
-			return this.account.getBankId();
-		}
+        @Override
+        public int getBankId() {
+            return this.account.getBankId();
+        }
 
-		@Override
-		public double balance()
-		{
-			return this.holdings.balance();
-		}
+        @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 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 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 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 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 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 hasEnough(double amount) {
+            return this.holdings.hasEnough(amount);
+        }
 
-		@Override
-		public boolean hasOver(double amount)
-		{
-			return this.holdings.hasOver(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 hasUnder(double amount) {
+            return this.holdings.hasUnder(amount);
+        }
 
-		@Override
-		public boolean isNegative()
-		{
-			return this.holdings.isNegative();
-		}
+        @Override
+        public boolean isNegative() {
+            return this.holdings.isNegative();
+        }
 
-		@Override
-		public boolean remove()
-		{
-			if (this.account == null)
-			{
-				return false;
-			}
-			this.account.remove();
-			return true;
-		}
-	}
+        @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/register/payment/methods/iCo6.java b/Essentials/src/com/earth2me/essentials/register/payment/methods/iCo6.java
index bf0c1c60a..0c099a782 100644
--- a/Essentials/src/com/earth2me/essentials/register/payment/methods/iCo6.java
+++ b/Essentials/src/com/earth2me/essentials/register/payment/methods/iCo6.java
@@ -12,231 +12,190 @@ 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;
+public class iCo6 implements Method {
+    private iConomy iConomy;
 
-	@Override
-	public iConomy getPlugin()
-	{
-		return this.iConomy;
-	}
+    @Override
+    public iConomy getPlugin() {
+        return this.iConomy;
+    }
 
-	@Override
-	public String getName()
-	{
-		return "iConomy";
-	}
+    @Override
+    public String getName() {
+        return "iConomy";
+    }
 
-	@Override
-	public String getLongName()
-	{
-		return getName();
-	}
+    @Override
+    public String getLongName() {
+        return getName();
+    }
 
-	@Override
-	public String getVersion()
-	{
-		return "6";
-	}
+    @Override
+    public String getVersion() {
+        return "6";
+    }
 
-	@Override
-	public int fractionalDigits()
-	{
-		return 2;
-	}
+    @Override
+    public int fractionalDigits() {
+        return 2;
+    }
 
-	@Override
-	public String format(double amount)
-	{
-		return com.iCo6.iConomy.format(amount);
-	}
+    @Override
+    public String format(double amount) {
+        return com.iCo6.iConomy.format(amount);
+    }
 
-	@Override
-	public boolean hasBanks()
-	{
-		return false;
-	}
+    @Override
+    public boolean hasBanks() {
+        return false;
+    }
 
-	@Override
-	public boolean hasBank(String bank)
-	{
-		return false;
-	}
+    @Override
+    public boolean hasBank(String bank) {
+        return false;
+    }
 
-	@Override
-	public boolean hasAccount(String name)
-	{
-		return (new Accounts()).exists(name);
-	}
+    @Override
+    public boolean hasAccount(String name) {
+        return (new Accounts()).exists(name);
+    }
 
-	@Override
-	public boolean hasBankAccount(String bank, String name)
-	{
-		return false;
-	}
+    @Override
+    public boolean hasBankAccount(String bank, String name) {
+        return false;
+    }
 
-	@Override
-	public boolean createAccount(String name)
-	{
-		if (hasAccount(name))
-		{
-			return false;
-		}
+    @Override
+    public boolean createAccount(String name) {
+        if (hasAccount(name)) {
+            return false;
+        }
 
-		return (new Accounts()).create(name);
-	}
+        return (new Accounts()).create(name);
+    }
 
-	@Override
-	public boolean createAccount(String name, Double balance)
-	{
-		if (hasAccount(name))
-		{
-			return false;
-		}
+    @Override
+    public boolean createAccount(String name, Double balance) {
+        if (hasAccount(name)) {
+            return false;
+        }
 
-		return (new Accounts()).create(name, balance);
-	}
+        return (new Accounts()).create(name, balance);
+    }
 
-	@Override
-	public MethodAccount getAccount(String name)
-	{
-		return new iCoAccount((new Accounts()).get(name));
-	}
+    @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 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 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;
-	}
+    @Override
+    public void setPlugin(Plugin plugin) {
+        iConomy = (iConomy) plugin;
+    }
 
 
-	public class iCoAccount implements MethodAccount
-	{
-		private final Account account;
-		private final Holdings holdings;
+    public class iCoAccount implements MethodAccount {
+        private final Account account;
+        private final Holdings holdings;
 
-		public iCoAccount(Account account)
-		{
-			this.account = account;
-			this.holdings = account.getHoldings();
-		}
+        public iCoAccount(Account account) {
+            this.account = account;
+            this.holdings = account.getHoldings();
+        }
 
-		public Account getiCoAccount()
-		{
-			return account;
-		}
+        public Account getiCoAccount() {
+            return account;
+        }
 
-		@Override
-		public double balance()
-		{
-			return this.holdings.getBalance();
-		}
+        @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 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 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 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 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 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 hasEnough(double amount) {
+            return this.holdings.hasEnough(amount);
+        }
 
-		@Override
-		public boolean hasOver(double amount)
-		{
-			return this.holdings.hasOver(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 hasUnder(double amount) {
+            return this.holdings.hasUnder(amount);
+        }
 
-		@Override
-		public boolean isNegative()
-		{
-			return this.holdings.isNegative();
-		}
+        @Override
+        public boolean isNegative() {
+            return this.holdings.isNegative();
+        }
 
-		@Override
-		public boolean remove()
-		{
-			if (this.account == null)
-			{
-				return false;
-			}
-			this.account.remove();
-			return true;
-		}
-	}
+        @Override
+        public boolean remove() {
+            if (this.account == null) {
+                return false;
+            }
+            this.account.remove();
+            return true;
+        }
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/settings/Jails.java b/Essentials/src/com/earth2me/essentials/settings/Jails.java
index 4f9b79197..311a75f82 100644
--- a/Essentials/src/com/earth2me/essentials/settings/Jails.java
+++ b/Essentials/src/com/earth2me/essentials/settings/Jails.java
@@ -2,17 +2,15 @@ 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.Location;
 
+import java.util.HashMap;
+import java.util.Map;
 
-@Data
-@EqualsAndHashCode(callSuper = false)
-public class Jails implements StorageObject
-{
-	@MapValueType(Location.class)
-	private Map jails = new HashMap();
+
+@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/Spawns.java b/Essentials/src/com/earth2me/essentials/settings/Spawns.java
index a0afa450c..0ece0f2bf 100644
--- a/Essentials/src/com/earth2me/essentials/settings/Spawns.java
+++ b/Essentials/src/com/earth2me/essentials/settings/Spawns.java
@@ -2,17 +2,15 @@ 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.Location;
 
+import java.util.HashMap;
+import java.util.Map;
 
-@Data
-@EqualsAndHashCode(callSuper = false)
-public class Spawns implements StorageObject
-{
-	@MapValueType(Location.class)
-	private Map spawns = new HashMap();
+
+@Data @EqualsAndHashCode(callSuper = false) public class Spawns implements StorageObject {
+    @MapValueType(Location.class)
+    private Map spawns = new HashMap();
 }
diff --git a/Essentials/src/com/earth2me/essentials/signs/EssentialsSign.java b/Essentials/src/com/earth2me/essentials/signs/EssentialsSign.java
index 6231bbc09..c19b5ad1a 100644
--- a/Essentials/src/com/earth2me/essentials/signs/EssentialsSign.java
+++ b/Essentials/src/com/earth2me/essentials/signs/EssentialsSign.java
@@ -1,12 +1,7 @@
 package com.earth2me.essentials.signs;
 
 import com.earth2me.essentials.*;
-import static com.earth2me.essentials.I18n.tl;
 import com.earth2me.essentials.utils.NumberUtil;
-import java.math.BigDecimal;
-import java.util.HashSet;
-import java.util.Locale;
-import java.util.Set;
 import net.ess3.api.IEssentials;
 import net.ess3.api.MaxMoneyException;
 import net.ess3.api.events.SignBreakEvent;
@@ -20,615 +15,478 @@ 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 static final BigDecimal MINTRANSACTION = new BigDecimal("0.01");
-	protected transient final String signName;
-
-	public EssentialsSign(final String signName)
-	{
-		this.signName = signName;
-	}
-
-	protected final boolean onSignCreate(final SignChangeEvent event, final IEssentials ess)
-	{
-		final ISign sign = new EventSign(event);
-		final User user = ess.getUser(event.getPlayer());
-		if (!(user.isAuthorized("essentials.signs." + signName.toLowerCase(Locale.ENGLISH) + ".create")
-			  || user.isAuthorized("essentials.signs.create." + signName.toLowerCase(Locale.ENGLISH))))
-		{
-			// 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, tl("signFormatFail", this.signName));
-
-		final SignCreateEvent signEvent = new SignCreateEvent(sign, this, user);
-		ess.getServer().getPluginManager().callEvent(signEvent);
-		if (signEvent.isCancelled())
-		{
-			return false;
-		}
-
-		try
-		{
-			final boolean ret = onSignCreate(sign, user, getUsername(user), ess);
-			if (ret)
-			{
-				sign.setLine(0, getSuccessName());
-			}
-			return ret;
-		}
-		catch (ChargeException ex)
-		{
-			showError(ess, user.getSource(), ex, signName);
-		}
-		catch (SignException ex)
-		{
-			showError(ess, user.getSource(), ex, signName);
-		}
-		// Return true, so the player sees the wrong sign.
-		return true;
-	}
-
-	public String getSuccessName()
-	{
-		return tl("signFormatSuccess", this.signName);
-	}
-
-	public String getTemplateName()
-	{
-		return tl("signFormatTemplate", this.signName);
-	}
-
-	public String getName()
-	{
-		return this.signName;
-	}
-
-	public String getUsername(final User user)
-	{
-		return user.getName().substring(0, user.getName().length() > 13 ? 13 : user.getName().length());
-	}
-
-	protected final boolean onSignInteract(final Block block, final Player player, final IEssentials ess)
-	{
-		final ISign sign = new BlockSign(block);
-		final User user = ess.getUser(player);
-		if (user.checkSignThrottle())
-		{
-			return false;
-		}
-		try
-		{
-			if (user.getBase().isDead() || !(user.isAuthorized("essentials.signs." + signName.toLowerCase(Locale.ENGLISH) + ".use")
-								   || user.isAuthorized("essentials.signs.use." + signName.toLowerCase(Locale.ENGLISH))))
-			{
-				return false;
-			}
-
-			final SignInteractEvent signEvent = new SignInteractEvent(sign, this, user);
-			ess.getServer().getPluginManager().callEvent(signEvent);
-			if (signEvent.isCancelled())
-			{
-				return false;
-			}
-
-			return onSignInteract(sign, user, getUsername(user), ess);
-		}
-		catch (ChargeException ex)
-		{
-			showError(ess, user.getSource(), ex, signName);
-			return false;
-		}
-		catch (Exception ex)
-		{
-			showError(ess, user.getSource(), ex, signName);
-			return false;
-		}
-	}
-
-	protected final boolean onSignBreak(final Block block, final Player player, final IEssentials ess) throws MaxMoneyException
-	{
-		final ISign sign = new BlockSign(block);
-		final User user = ess.getUser(player);
-		try
-		{
-			if (!(user.isAuthorized("essentials.signs." + signName.toLowerCase(Locale.ENGLISH) + ".break")
-				  || user.isAuthorized("essentials.signs.break." + signName.toLowerCase(Locale.ENGLISH))))
-			{
-				return false;
-			}
-
-			final SignBreakEvent signEvent = new SignBreakEvent(sign, this, user);
-			ess.getServer().getPluginManager().callEvent(signEvent);
-			if (signEvent.isCancelled())
-			{
-				return false;
-			}
-
-			return onSignBreak(sign, user, getUsername(user), ess);
-		}
-		catch (SignException ex)
-		{
-			showError(ess, user.getSource(), ex, signName);
-			return false;
-		}
-	}
-
-	protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException
-	{
-		return true;
-	}
-
-	protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException, MaxMoneyException
-	{
-		return true;
-	}
-
-	protected boolean onSignBreak(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, MaxMoneyException
-	{
-		return true;
-	}
-
-	protected final boolean onBlockPlace(final Block block, final Player player, final IEssentials ess)
-	{
-		User user = ess.getUser(player);
-		try
-		{
-			return onBlockPlace(block, user, getUsername(user), ess);
-		}
-		catch (ChargeException ex)
-		{
-			showError(ess, user.getSource(), ex, signName);
-		}
-		catch (SignException ex)
-		{
-			showError(ess, user.getSource(), ex, signName);
-		}
-		return false;
-	}
-
-	protected final boolean onBlockInteract(final Block block, final Player player, final IEssentials ess)
-	{
-		User user = ess.getUser(player);
-		try
-		{
-			return onBlockInteract(block, user, getUsername(user), ess);
-		}
-		catch (ChargeException ex)
-		{
-			showError(ess, user.getSource(), ex, signName);
-		}
-		catch (SignException ex)
-		{
-			showError(ess, user.getSource(), ex, signName);
-		}
-		return false;
-	}
-
-	protected final boolean onBlockBreak(final Block block, final Player player, final IEssentials ess) throws MaxMoneyException
-	{
-		User user = ess.getUser(player);
-		try
-		{
-			return onBlockBreak(block, user, getUsername(user), ess);
-		}
-		catch (SignException ex)
-		{
-			showError(ess, user.getSource(), ex, signName);
-		}
-		return false;
-	}
-
-	protected boolean onBlockBreak(final Block block, final IEssentials ess)
-	{
-		return true;
-	}
-
-	protected boolean onBlockExplode(final Block block, final IEssentials ess)
-	{
-		return true;
-	}
-
-	protected boolean onBlockBurn(final Block block, final IEssentials ess)
-	{
-		return true;
-	}
-
-	protected boolean onBlockIgnite(final Block block, final IEssentials ess)
-	{
-		return true;
-	}
-
-	protected boolean onBlockPush(final Block block, final IEssentials ess)
-	{
-		return true;
-	}
-
-	protected 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)
-			{
-				try
-				{
-					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;
-					}
-				}
-				catch (NullPointerException ex)
-				{
-					// Sometimes signs enter a state of being semi broken, having no text or state data, usually while burning.
-				}
-			}
-		}
-		return false;
-	}
-
-	public static boolean isValidSign(final ISign sign)
-	{
-		return sign.getLine(0).matches("§1\\[.*\\]");
-	}
-
-	protected boolean onBlockPlace(final Block block, final User player, final String username, final IEssentials ess) throws SignException, ChargeException
-	{
-		return true;
-	}
-
-	protected boolean onBlockInteract(final Block block, final User player, final String username, final IEssentials ess) throws SignException, ChargeException
-	{
-		return true;
-	}
-
-	protected boolean onBlockBreak(final Block block, final User player, final String username, final IEssentials ess) throws SignException, MaxMoneyException
-	{
-		return true;
-	}
-
-	public Set getBlocks()
-	{
-		return EMPTY_SET;
-	}
-
-	public boolean areHeavyEventRequired()
-	{
-		return false;
-	}
-
-	private String getSignText(final ISign sign, final int lineNumber)
-	{
-		return sign.getLine(lineNumber).trim();
-	}
-
-	protected final void validateTrade(final ISign sign, final int index, final IEssentials ess) throws SignException
-	{
-		final String line = getSignText(sign, index);
-		if (line.isEmpty())
-		{
-			return;
-		}
-		final Trade trade = getTrade(sign, index, 0, ess);
-		final BigDecimal money = trade.getMoney();
-		if (money != null)
-		{
-			sign.setLine(index, NumberUtil.shortCurrency(money, ess));
-		}
-	}
-
-	protected final void validateTrade(final ISign sign, final int amountIndex, final int itemIndex,
-									   final User player, final IEssentials ess) throws SignException
-	{
-		final String itemType = getSignText(sign, itemIndex);
-		if (itemType.equalsIgnoreCase("exp") || itemType.equalsIgnoreCase("xp"))
-		{
-			int amount = getIntegerPositive(getSignText(sign, amountIndex));
-			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, itemType);
-	}
-
-	protected final Trade getTrade(final ISign sign, final int amountIndex, final int itemIndex,
-								   final User player, final IEssentials ess) throws SignException
-	{
-		final String itemType = getSignText(sign, itemIndex);
-		if (itemType.equalsIgnoreCase("exp") || itemType.equalsIgnoreCase("xp"))
-		{
-			final int amount = getIntegerPositive(getSignText(sign, amountIndex));
-			return new Trade(amount, ess);
-		}
-		final ItemStack item = getItemStack(itemType, 1, ess);
-		final int amount = Math.min(getIntegerPositive(getSignText(sign, amountIndex)), item.getType().getMaxStackSize() * player.getBase().getInventory().getSize());
-		if (item.getType() == Material.AIR || amount < 1)
-		{
-			throw new SignException(tl("moreThanZero"));
-		}
-		item.setAmount(amount);
-		return new Trade(item, ess);
-	}
-
-	protected final void validateInteger(final ISign sign, final int index) throws SignException
-	{
-		final String line = getSignText(sign, index);
-		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(tl("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 ItemStack getItemMeta(final ItemStack item, final String meta, final IEssentials ess) throws SignException
-	{
-		ItemStack stack = item;
-		try
-		{
-			if (!meta.isEmpty())
-			{
-				MetaItemStack metaStack = new MetaItemStack(stack);
-				final boolean allowUnsafe = ess.getSettings().allowUnsafeEnchantments();
-				metaStack.addStringMeta(null, allowUnsafe, meta, ess);
-				stack = metaStack.getItemStack();
-			}
-		}
-		catch (Exception ex)
-		{
-			throw new SignException(ex.getMessage(), ex);
-		}
-		return stack;
-	}
-
-	protected final BigDecimal getMoney(final String line) throws SignException
-	{
-		final boolean isMoney = line.matches("^[^0-9-\\.][\\.0-9]+$");
-		return isMoney ? getBigDecimalPositive(line.substring(1)) : null;
-	}
-
-	protected final BigDecimal getBigDecimalPositive(final String line) throws SignException
-	{
-		final BigDecimal quantity = getBigDecimal(line);
-		if (quantity.compareTo(MINTRANSACTION) < 0)
-		{
-			throw new SignException(tl("moreThanZero"));
-		}
-		return quantity;
-	}
-
-	protected final BigDecimal getBigDecimal(final String line) throws SignException
-	{
-		try
-		{
-			return new BigDecimal(line);
-		}
-		catch (ArithmeticException ex)
-		{
-			throw new SignException(ex.getMessage(), ex);
-		}
-		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 = getSignText(sign, index);
-		if (line.isEmpty())
-		{
-			return new Trade(signName.toLowerCase(Locale.ENGLISH) + "sign", ess);
-		}
-
-		final BigDecimal money = getMoney(line);
-		if (money == null)
-		{
-			final String[] split = line.split("[ :]+", 2);
-			if (split.length != 2)
-			{
-				throw new SignException(tl("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");
-				sign.updateSign();
-				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);
-		}
-	}
-
-	private void showError(final IEssentials ess, final CommandSource sender, final Throwable exception, final String signName)
-	{
-		ess.showError(sender, exception, "\\ sign: " + signName);
-	}
-
-
-	static class EventSign implements ISign
-	{
-		private final transient SignChangeEvent event;
-		private final transient Block block;
-		private final transient Sign sign;
-
-		EventSign(final SignChangeEvent event)
-		{
-			this.event = event;
-			this.block = event.getBlock();
-			this.sign = (Sign)block.getState();
-		}
-
-		@Override
-		public final String getLine(final int index)
-		{
-			StringBuilder builder = new StringBuilder();
-			for (char c : event.getLine(index).toCharArray())
-			{
-				if (c < 0xF700 || c > 0xF747)
-				{
-					builder.append(c);
-				}
-			}
-			return builder.toString();
-			//return event.getLine(index); // Above code can be removed and replaced with this line when https://github.com/Bukkit/Bukkit/pull/982 is merged.
-		}
-
-		@Override
-		public final void setLine(final int index, final String text)
-		{
-			event.setLine(index, text);
-			sign.setLine(index, text);
-			updateSign();
-		}
-
-		@Override
-		public Block getBlock()
-		{
-			return block;
-		}
-
-		@Override
-		public void updateSign()
-		{
-			sign.update();
-		}
-	}
-
-
-	static class BlockSign implements ISign
-	{
-		private final transient Sign sign;
-		private final transient Block block;
-
-		BlockSign(final Block block)
-		{
-			this.block = block;
-			this.sign = (Sign)block.getState();
-		}
-
-		@Override
-		public final String getLine(final int index)
-		{
-			StringBuilder builder = new StringBuilder();
-			for (char c : sign.getLine(index).toCharArray())
-			{
-				if (c < 0xF700 || c > 0xF747)
-				{
-					builder.append(c);
-				}
-			}
-			return builder.toString();
-			//return event.getLine(index); // Above code can be removed and replaced with this line when https://github.com/Bukkit/Bukkit/pull/982 is merged.
-		}
-
-		@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
-	{
-		public String getLine(final int index);
-
-		public void setLine(final int index, final String text);
-
-		public Block getBlock();
-
-		public void updateSign();
-	}
+import java.math.BigDecimal;
+import java.util.HashSet;
+import java.util.Locale;
+import java.util.Set;
+
+import static com.earth2me.essentials.I18n.tl;
+
+
+public class EssentialsSign {
+    private static final Set EMPTY_SET = new HashSet();
+    protected static final BigDecimal MINTRANSACTION = new BigDecimal("0.01");
+    protected transient final String signName;
+
+    public EssentialsSign(final String signName) {
+        this.signName = signName;
+    }
+
+    protected final boolean onSignCreate(final SignChangeEvent event, final IEssentials ess) {
+        final ISign sign = new EventSign(event);
+        final User user = ess.getUser(event.getPlayer());
+        if (!(user.isAuthorized("essentials.signs." + signName.toLowerCase(Locale.ENGLISH) + ".create") || user.isAuthorized("essentials.signs.create." + signName.toLowerCase(Locale.ENGLISH)))) {
+            // 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, tl("signFormatFail", this.signName));
+
+        final SignCreateEvent signEvent = new SignCreateEvent(sign, this, user);
+        ess.getServer().getPluginManager().callEvent(signEvent);
+        if (signEvent.isCancelled()) {
+            return false;
+        }
+
+        try {
+            final boolean ret = onSignCreate(sign, user, getUsername(user), ess);
+            if (ret) {
+                sign.setLine(0, getSuccessName());
+            }
+            return ret;
+        } catch (ChargeException ex) {
+            showError(ess, user.getSource(), ex, signName);
+        } catch (SignException ex) {
+            showError(ess, user.getSource(), ex, signName);
+        }
+        // Return true, so the player sees the wrong sign.
+        return true;
+    }
+
+    public String getSuccessName() {
+        return tl("signFormatSuccess", this.signName);
+    }
+
+    public String getTemplateName() {
+        return tl("signFormatTemplate", this.signName);
+    }
+
+    public String getName() {
+        return this.signName;
+    }
+
+    public String getUsername(final User user) {
+        return user.getName().substring(0, user.getName().length() > 13 ? 13 : user.getName().length());
+    }
+
+    protected final boolean onSignInteract(final Block block, final Player player, final IEssentials ess) {
+        final ISign sign = new BlockSign(block);
+        final User user = ess.getUser(player);
+        if (user.checkSignThrottle()) {
+            return false;
+        }
+        try {
+            if (user.getBase().isDead() || !(user.isAuthorized("essentials.signs." + signName.toLowerCase(Locale.ENGLISH) + ".use") || user.isAuthorized("essentials.signs.use." + signName.toLowerCase(Locale.ENGLISH)))) {
+                return false;
+            }
+
+            final SignInteractEvent signEvent = new SignInteractEvent(sign, this, user);
+            ess.getServer().getPluginManager().callEvent(signEvent);
+            if (signEvent.isCancelled()) {
+                return false;
+            }
+
+            return onSignInteract(sign, user, getUsername(user), ess);
+        } catch (ChargeException ex) {
+            showError(ess, user.getSource(), ex, signName);
+            return false;
+        } catch (Exception ex) {
+            showError(ess, user.getSource(), ex, signName);
+            return false;
+        }
+    }
+
+    protected final boolean onSignBreak(final Block block, final Player player, final IEssentials ess) throws MaxMoneyException {
+        final ISign sign = new BlockSign(block);
+        final User user = ess.getUser(player);
+        try {
+            if (!(user.isAuthorized("essentials.signs." + signName.toLowerCase(Locale.ENGLISH) + ".break") || user.isAuthorized("essentials.signs.break." + signName.toLowerCase(Locale.ENGLISH)))) {
+                return false;
+            }
+
+            final SignBreakEvent signEvent = new SignBreakEvent(sign, this, user);
+            ess.getServer().getPluginManager().callEvent(signEvent);
+            if (signEvent.isCancelled()) {
+                return false;
+            }
+
+            return onSignBreak(sign, user, getUsername(user), ess);
+        } catch (SignException ex) {
+            showError(ess, user.getSource(), ex, signName);
+            return false;
+        }
+    }
+
+    protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException {
+        return true;
+    }
+
+    protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException, MaxMoneyException {
+        return true;
+    }
+
+    protected boolean onSignBreak(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, MaxMoneyException {
+        return true;
+    }
+
+    protected final boolean onBlockPlace(final Block block, final Player player, final IEssentials ess) {
+        User user = ess.getUser(player);
+        try {
+            return onBlockPlace(block, user, getUsername(user), ess);
+        } catch (ChargeException ex) {
+            showError(ess, user.getSource(), ex, signName);
+        } catch (SignException ex) {
+            showError(ess, user.getSource(), ex, signName);
+        }
+        return false;
+    }
+
+    protected final boolean onBlockInteract(final Block block, final Player player, final IEssentials ess) {
+        User user = ess.getUser(player);
+        try {
+            return onBlockInteract(block, user, getUsername(user), ess);
+        } catch (ChargeException ex) {
+            showError(ess, user.getSource(), ex, signName);
+        } catch (SignException ex) {
+            showError(ess, user.getSource(), ex, signName);
+        }
+        return false;
+    }
+
+    protected final boolean onBlockBreak(final Block block, final Player player, final IEssentials ess) throws MaxMoneyException {
+        User user = ess.getUser(player);
+        try {
+            return onBlockBreak(block, user, getUsername(user), ess);
+        } catch (SignException ex) {
+            showError(ess, user.getSource(), ex, signName);
+        }
+        return false;
+    }
+
+    protected boolean onBlockBreak(final Block block, final IEssentials ess) {
+        return true;
+    }
+
+    protected boolean onBlockExplode(final Block block, final IEssentials ess) {
+        return true;
+    }
+
+    protected boolean onBlockBurn(final Block block, final IEssentials ess) {
+        return true;
+    }
+
+    protected boolean onBlockIgnite(final Block block, final IEssentials ess) {
+        return true;
+    }
+
+    protected boolean onBlockPush(final Block block, final IEssentials ess) {
+        return true;
+    }
+
+    protected 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) {
+                try {
+                    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;
+                    }
+                } catch (NullPointerException ex) {
+                    // Sometimes signs enter a state of being semi broken, having no text or state data, usually while burning.
+                }
+            }
+        }
+        return false;
+    }
+
+    public static boolean isValidSign(final ISign sign) {
+        return sign.getLine(0).matches("§1\\[.*\\]");
+    }
+
+    protected boolean onBlockPlace(final Block block, final User player, final String username, final IEssentials ess) throws SignException, ChargeException {
+        return true;
+    }
+
+    protected boolean onBlockInteract(final Block block, final User player, final String username, final IEssentials ess) throws SignException, ChargeException {
+        return true;
+    }
+
+    protected boolean onBlockBreak(final Block block, final User player, final String username, final IEssentials ess) throws SignException, MaxMoneyException {
+        return true;
+    }
+
+    public Set getBlocks() {
+        return EMPTY_SET;
+    }
+
+    public boolean areHeavyEventRequired() {
+        return false;
+    }
+
+    private String getSignText(final ISign sign, final int lineNumber) {
+        return sign.getLine(lineNumber).trim();
+    }
+
+    protected final void validateTrade(final ISign sign, final int index, final IEssentials ess) throws SignException {
+        final String line = getSignText(sign, index);
+        if (line.isEmpty()) {
+            return;
+        }
+        final Trade trade = getTrade(sign, index, 0, ess);
+        final BigDecimal money = trade.getMoney();
+        if (money != null) {
+            sign.setLine(index, NumberUtil.shortCurrency(money, ess));
+        }
+    }
+
+    protected final void validateTrade(final ISign sign, final int amountIndex, final int itemIndex, final User player, final IEssentials ess) throws SignException {
+        final String itemType = getSignText(sign, itemIndex);
+        if (itemType.equalsIgnoreCase("exp") || itemType.equalsIgnoreCase("xp")) {
+            int amount = getIntegerPositive(getSignText(sign, amountIndex));
+            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, itemType);
+    }
+
+    protected final Trade getTrade(final ISign sign, final int amountIndex, final int itemIndex, final User player, final IEssentials ess) throws SignException {
+        final String itemType = getSignText(sign, itemIndex);
+        if (itemType.equalsIgnoreCase("exp") || itemType.equalsIgnoreCase("xp")) {
+            final int amount = getIntegerPositive(getSignText(sign, amountIndex));
+            return new Trade(amount, ess);
+        }
+        final ItemStack item = getItemStack(itemType, 1, ess);
+        final int amount = Math.min(getIntegerPositive(getSignText(sign, amountIndex)), item.getType().getMaxStackSize() * player.getBase().getInventory().getSize());
+        if (item.getType() == Material.AIR || amount < 1) {
+            throw new SignException(tl("moreThanZero"));
+        }
+        item.setAmount(amount);
+        return new Trade(item, ess);
+    }
+
+    protected final void validateInteger(final ISign sign, final int index) throws SignException {
+        final String line = getSignText(sign, index);
+        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(tl("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 ItemStack getItemMeta(final ItemStack item, final String meta, final IEssentials ess) throws SignException {
+        ItemStack stack = item;
+        try {
+            if (!meta.isEmpty()) {
+                MetaItemStack metaStack = new MetaItemStack(stack);
+                final boolean allowUnsafe = ess.getSettings().allowUnsafeEnchantments();
+                metaStack.addStringMeta(null, allowUnsafe, meta, ess);
+                stack = metaStack.getItemStack();
+            }
+        } catch (Exception ex) {
+            throw new SignException(ex.getMessage(), ex);
+        }
+        return stack;
+    }
+
+    protected final BigDecimal getMoney(final String line) throws SignException {
+        final boolean isMoney = line.matches("^[^0-9-\\.][\\.0-9]+$");
+        return isMoney ? getBigDecimalPositive(line.substring(1)) : null;
+    }
+
+    protected final BigDecimal getBigDecimalPositive(final String line) throws SignException {
+        final BigDecimal quantity = getBigDecimal(line);
+        if (quantity.compareTo(MINTRANSACTION) < 0) {
+            throw new SignException(tl("moreThanZero"));
+        }
+        return quantity;
+    }
+
+    protected final BigDecimal getBigDecimal(final String line) throws SignException {
+        try {
+            return new BigDecimal(line);
+        } catch (ArithmeticException ex) {
+            throw new SignException(ex.getMessage(), ex);
+        } 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 = getSignText(sign, index);
+        if (line.isEmpty()) {
+            return new Trade(signName.toLowerCase(Locale.ENGLISH) + "sign", ess);
+        }
+
+        final BigDecimal money = getMoney(line);
+        if (money == null) {
+            final String[] split = line.split("[ :]+", 2);
+            if (split.length != 2) {
+                throw new SignException(tl("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");
+                sign.updateSign();
+                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);
+        }
+    }
+
+    private void showError(final IEssentials ess, final CommandSource sender, final Throwable exception, final String signName) {
+        ess.showError(sender, exception, "\\ sign: " + signName);
+    }
+
+
+    static class EventSign implements ISign {
+        private final transient SignChangeEvent event;
+        private final transient Block block;
+        private final transient Sign sign;
+
+        EventSign(final SignChangeEvent event) {
+            this.event = event;
+            this.block = event.getBlock();
+            this.sign = (Sign) block.getState();
+        }
+
+        @Override
+        public final String getLine(final int index) {
+            StringBuilder builder = new StringBuilder();
+            for (char c : event.getLine(index).toCharArray()) {
+                if (c < 0xF700 || c > 0xF747) {
+                    builder.append(c);
+                }
+            }
+            return builder.toString();
+            //return event.getLine(index); // Above code can be removed and replaced with this line when https://github.com/Bukkit/Bukkit/pull/982 is merged.
+        }
+
+        @Override
+        public final void setLine(final int index, final String text) {
+            event.setLine(index, text);
+            sign.setLine(index, text);
+            updateSign();
+        }
+
+        @Override
+        public Block getBlock() {
+            return block;
+        }
+
+        @Override
+        public void updateSign() {
+            sign.update();
+        }
+    }
+
+
+    static class BlockSign implements ISign {
+        private final transient Sign sign;
+        private final transient Block block;
+
+        BlockSign(final Block block) {
+            this.block = block;
+            this.sign = (Sign) block.getState();
+        }
+
+        @Override
+        public final String getLine(final int index) {
+            StringBuilder builder = new StringBuilder();
+            for (char c : sign.getLine(index).toCharArray()) {
+                if (c < 0xF700 || c > 0xF747) {
+                    builder.append(c);
+                }
+            }
+            return builder.toString();
+            //return event.getLine(index); // Above code can be removed and replaced with this line when https://github.com/Bukkit/Bukkit/pull/982 is merged.
+        }
+
+        @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 {
+        public String getLine(final int index);
+
+        public void setLine(final int index, final String text);
+
+        public Block getBlock();
+
+        public void updateSign();
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/signs/SignBalance.java b/Essentials/src/com/earth2me/essentials/signs/SignBalance.java
index bd5b10f09..6b9201499 100644
--- a/Essentials/src/com/earth2me/essentials/signs/SignBalance.java
+++ b/Essentials/src/com/earth2me/essentials/signs/SignBalance.java
@@ -1,22 +1,20 @@
 package com.earth2me.essentials.signs;
 
-import static com.earth2me.essentials.I18n.tl;
 import com.earth2me.essentials.User;
 import com.earth2me.essentials.utils.NumberUtil;
 import net.ess3.api.IEssentials;
 
+import static com.earth2me.essentials.I18n.tl;
 
-public class SignBalance extends EssentialsSign
-{
-	public SignBalance()
-	{
-		super("Balance");
-	}
 
-	@Override
-	protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException
-	{
-		player.sendMessage(tl("balance", NumberUtil.displayCurrency(player.getMoney(), ess)));
-		return true;
-	}
+public class SignBalance extends EssentialsSign {
+    public SignBalance() {
+        super("Balance");
+    }
+
+    @Override
+    protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException {
+        player.sendMessage(tl("balance", NumberUtil.displayCurrency(player.getMoney(), ess)));
+        return true;
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/signs/SignBlockListener.java b/Essentials/src/com/earth2me/essentials/signs/SignBlockListener.java
index 9b4e87d93..02bd6b6b2 100644
--- a/Essentials/src/com/earth2me/essentials/signs/SignBlockListener.java
+++ b/Essentials/src/com/earth2me/essentials/signs/SignBlockListener.java
@@ -2,8 +2,6 @@ package com.earth2me.essentials.signs;
 
 import com.earth2me.essentials.User;
 import com.earth2me.essentials.utils.FormatUtil;
-import java.util.logging.Level;
-import java.util.logging.Logger;
 import net.ess3.api.IEssentials;
 import net.ess3.api.MaxMoneyException;
 import org.bukkit.Material;
@@ -15,290 +13,211 @@ import org.bukkit.event.EventPriority;
 import org.bukkit.event.Listener;
 import org.bukkit.event.block.*;
 
+import java.util.logging.Level;
+import java.util.logging.Logger;
 
-public class SignBlockListener implements Listener
-{
-	private static final Logger LOGGER = Logger.getLogger("Essentials");
-	private static final Material WALL_SIGN = Material.WALL_SIGN;
-	private static final Material SIGN_POST = Material.SIGN_POST;
-	private final transient IEssentials ess;
 
-	public SignBlockListener(IEssentials ess)
-	{
-		this.ess = ess;
-	}
+public class SignBlockListener implements Listener {
+    private static final Logger LOGGER = Logger.getLogger("Essentials");
+    private static final Material WALL_SIGN = Material.WALL_SIGN;
+    private static final Material SIGN_POST = Material.SIGN_POST;
+    private final transient IEssentials ess;
 
-	@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
-	public void onSignBlockBreak(final BlockBreakEvent event)
-	{
-		if (ess.getSettings().areSignsDisabled())
-		{
-			event.getHandlers().unregister(this);
-			return;
-		}
-		try
-		{
-			if (protectSignsAndBlocks(event.getBlock(), event.getPlayer()))
-			{
-				event.setCancelled(true);
-			}
-		}
-		catch (MaxMoneyException ex)
-		{
-			event.setCancelled(true);
-		}
-	}
+    public SignBlockListener(IEssentials ess) {
+        this.ess = ess;
+    }
 
-	public boolean protectSignsAndBlocks(final Block block, final Player player) throws MaxMoneyException
-	{
-		// 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;
-		}
+    @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
+    public void onSignBlockBreak(final BlockBreakEvent event) {
+        if (ess.getSettings().areSignsDisabled()) {
+            event.getHandlers().unregister(this);
+            return;
+        }
+        try {
+            if (protectSignsAndBlocks(event.getBlock(), event.getPlayer())) {
+                event.setCancelled(true);
+            }
+        } catch (MaxMoneyException ex) {
+            event.setCancelled(true);
+        }
+    }
 
-		final Material mat = block.getType();
-		if (mat == SIGN_POST || mat == WALL_SIGN)
-		{
-			final Sign csign = (Sign)block.getState();
+    public boolean protectSignsAndBlocks(final Block block, final Player player) throws MaxMoneyException {
+        // 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 : ess.getSettings().enabledSigns())
-			{
-				if (csign.getLine(0).equalsIgnoreCase(sign.getSuccessName())
-					&& !sign.onSignBreak(block, player, ess))
-				{
-					return true;
-				}
-			}
-		}
+        final Material mat = block.getType();
+        if (mat == SIGN_POST || mat == WALL_SIGN) {
+            final Sign csign = (Sign) block.getState();
 
-		for (EssentialsSign sign : ess.getSettings().enabledSigns())
-		{
-			if (sign.areHeavyEventRequired() && sign.getBlocks().contains(block.getType())
-				&& !sign.onBlockBreak(block, player, ess))
-			{
-				LOGGER.log(Level.INFO, "A block was protected by a sign.");
-				return true;
-			}
-		}
-		return false;
-	}
+            for (EssentialsSign sign : ess.getSettings().enabledSigns()) {
+                if (csign.getLine(0).equalsIgnoreCase(sign.getSuccessName()) && !sign.onSignBreak(block, player, ess)) {
+                    return true;
+                }
+            }
+        }
 
-	@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
-	public void onSignSignChange2(final SignChangeEvent event)
-	{
-		if (ess.getSettings().areSignsDisabled())
-		{
-			event.getHandlers().unregister(this);
-			return;
-		}
-		User user = ess.getUser(event.getPlayer());
+        for (EssentialsSign sign : ess.getSettings().enabledSigns()) {
+            if (sign.areHeavyEventRequired() && sign.getBlocks().contains(block.getType()) && !sign.onBlockBreak(block, player, ess)) {
+                LOGGER.log(Level.INFO, "A block was protected by a sign.");
+                return true;
+            }
+        }
+        return false;
+    }
 
-		for (int i = 0; i < 4; i++)
-		{
-			event.setLine(i, FormatUtil.formatString(user, "essentials.signs", event.getLine(i)));
-		}
+    @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
+    public void onSignSignChange2(final SignChangeEvent event) {
+        if (ess.getSettings().areSignsDisabled()) {
+            event.getHandlers().unregister(this);
+            return;
+        }
+        User user = ess.getUser(event.getPlayer());
 
-		final String topLine = event.getLine(0);
-		//We loop through all sign types here to prevent clashes with preexisting signs later
-		for (Signs signs : Signs.values())
-		{
-			final EssentialsSign sign = signs.getSign();
-			if (topLine.equalsIgnoreCase(sign.getSuccessName()))
-			{
-				event.setLine(0, FormatUtil.stripFormat(topLine));
-			}
-		}
-	}
+        for (int i = 0; i < 4; i++) {
+            event.setLine(i, FormatUtil.formatString(user, "essentials.signs", event.getLine(i)));
+        }
 
-	@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
-	public void onSignSignChange(final SignChangeEvent event)
-	{
-		if (ess.getSettings().areSignsDisabled())
-		{
-			event.getHandlers().unregister(this);
-			return;
-		}
+        final String topLine = event.getLine(0);
+        //We loop through all sign types here to prevent clashes with preexisting signs later
+        for (Signs signs : Signs.values()) {
+            final EssentialsSign sign = signs.getSign();
+            if (topLine.equalsIgnoreCase(sign.getSuccessName())) {
+                event.setLine(0, FormatUtil.stripFormat(topLine));
+            }
+        }
+    }
 
-		for (EssentialsSign sign : ess.getSettings().enabledSigns())
-		{
-			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.HIGHEST, ignoreCancelled = true)
+    public void onSignSignChange(final SignChangeEvent event) {
+        if (ess.getSettings().areSignsDisabled()) {
+            event.getHandlers().unregister(this);
+            return;
+        }
 
-	@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
-	public void onSignBlockPlace(final BlockPlaceEvent event)
-	{
-		if (ess.getSettings().areSignsDisabled())
-		{
-			event.getHandlers().unregister(this);
-			return;
-		}
+        for (EssentialsSign sign : ess.getSettings().enabledSigns()) {
+            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;
+            }
+        }
+    }
 
-		final Block against = event.getBlockAgainst();
-		if ((against.getType() == WALL_SIGN
-			 || against.getType() == SIGN_POST)
-			&& EssentialsSign.isValidSign(new EssentialsSign.BlockSign(against)))
-		{
-			event.setCancelled(true);
-			return;
-		}
-		final Block block = event.getBlock();
-		if (block.getType() == WALL_SIGN
-			|| block.getType() == SIGN_POST)
-		{
-			return;
-		}
-		for (EssentialsSign sign : ess.getSettings().enabledSigns())
-		{
-			if (sign.areHeavyEventRequired() && sign.getBlocks().contains(block.getType())
-				&& !sign.onBlockPlace(block, event.getPlayer(), ess))
-			{
-				event.setCancelled(true);
-				return;
-			}
-		}
-	}
+    @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
+    public void onSignBlockPlace(final BlockPlaceEvent event) {
+        if (ess.getSettings().areSignsDisabled()) {
+            event.getHandlers().unregister(this);
+            return;
+        }
 
-	@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
-	public void onSignBlockBurn(final BlockBurnEvent event)
-	{
-		if (ess.getSettings().areSignsDisabled())
-		{
-			event.getHandlers().unregister(this);
-			return;
-		}
+        final Block against = event.getBlockAgainst();
+        if ((against.getType() == WALL_SIGN || against.getType() == SIGN_POST) && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(against))) {
+            event.setCancelled(true);
+            return;
+        }
+        final Block block = event.getBlock();
+        if (block.getType() == WALL_SIGN || block.getType() == SIGN_POST) {
+            return;
+        }
+        for (EssentialsSign sign : ess.getSettings().enabledSigns()) {
+            if (sign.areHeavyEventRequired() && sign.getBlocks().contains(block.getType()) && !sign.onBlockPlace(block, event.getPlayer(), ess)) {
+                event.setCancelled(true);
+                return;
+            }
+        }
+    }
 
-		final Block block = event.getBlock();
-		if (((block.getType() == WALL_SIGN
-			  || block.getType() == SIGN_POST)
-			 && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(block)))
-			|| EssentialsSign.checkIfBlockBreaksSigns(block))
-		{
-			event.setCancelled(true);
-			return;
-		}
-		for (EssentialsSign sign : ess.getSettings().enabledSigns())
-		{
-			if (sign.areHeavyEventRequired() && sign.getBlocks().contains(block.getType())
-				&& !sign.onBlockBurn(block, ess))
-			{
-				event.setCancelled(true);
-				return;
-			}
-		}
-	}
+    @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
+    public void onSignBlockBurn(final BlockBurnEvent event) {
+        if (ess.getSettings().areSignsDisabled()) {
+            event.getHandlers().unregister(this);
+            return;
+        }
 
-	@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
-	public void onSignBlockIgnite(final BlockIgniteEvent event)
-	{
-		if (ess.getSettings().areSignsDisabled())
-		{
-			event.getHandlers().unregister(this);
-			return;
-		}
+        final Block block = event.getBlock();
+        if (((block.getType() == WALL_SIGN || block.getType() == SIGN_POST) && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(block))) || EssentialsSign.checkIfBlockBreaksSigns(block)) {
+            event.setCancelled(true);
+            return;
+        }
+        for (EssentialsSign sign : ess.getSettings().enabledSigns()) {
+            if (sign.areHeavyEventRequired() && sign.getBlocks().contains(block.getType()) && !sign.onBlockBurn(block, ess)) {
+                event.setCancelled(true);
+                return;
+            }
+        }
+    }
 
-		final Block block = event.getBlock();
-		if (((block.getType() == WALL_SIGN
-			  || block.getType() == SIGN_POST)
-			 && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(block)))
-			|| EssentialsSign.checkIfBlockBreaksSigns(block))
-		{
-			event.setCancelled(true);
-			return;
-		}
-		for (EssentialsSign sign : ess.getSettings().enabledSigns())
-		{
-			if (sign.areHeavyEventRequired() && sign.getBlocks().contains(block.getType())
-				&& !sign.onBlockIgnite(block, ess))
-			{
-				event.setCancelled(true);
-				return;
-			}
-		}
-	}
+    @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
+    public void onSignBlockIgnite(final BlockIgniteEvent event) {
+        if (ess.getSettings().areSignsDisabled()) {
+            event.getHandlers().unregister(this);
+            return;
+        }
 
-	@EventHandler(priority = EventPriority.LOW)
-	public void onSignBlockPistonExtend(final BlockPistonExtendEvent event)
-	{
-		if (ess.getSettings().areSignsDisabled())
-		{
-			event.getHandlers().unregister(this);
-			return;
-		}
+        final Block block = event.getBlock();
+        if (((block.getType() == WALL_SIGN || block.getType() == SIGN_POST) && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(block))) || EssentialsSign.checkIfBlockBreaksSigns(block)) {
+            event.setCancelled(true);
+            return;
+        }
+        for (EssentialsSign sign : ess.getSettings().enabledSigns()) {
+            if (sign.areHeavyEventRequired() && sign.getBlocks().contains(block.getType()) && !sign.onBlockIgnite(block, ess)) {
+                event.setCancelled(true);
+                return;
+            }
+        }
+    }
 
-		for (Block block : event.getBlocks())
-		{
-			if (((block.getType() == WALL_SIGN
-				  || block.getType() == SIGN_POST)
-				 && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(block)))
-				|| EssentialsSign.checkIfBlockBreaksSigns(block))
-			{
-				event.setCancelled(true);
-				return;
-			}
-			for (EssentialsSign sign : ess.getSettings().enabledSigns())
-			{
-				if (sign.areHeavyEventRequired() && sign.getBlocks().contains(block.getType())
-					&& !sign.onBlockPush(block, ess))
-				{
-					event.setCancelled(true);
-					return;
-				}
-			}
-		}
-	}
+    @EventHandler(priority = EventPriority.LOW)
+    public void onSignBlockPistonExtend(final BlockPistonExtendEvent event) {
+        if (ess.getSettings().areSignsDisabled()) {
+            event.getHandlers().unregister(this);
+            return;
+        }
 
-	@EventHandler(priority = EventPriority.LOW)
-	public void onSignBlockPistonRetract(final BlockPistonRetractEvent event)
-	{
-		if (ess.getSettings().areSignsDisabled())
-		{
-			event.getHandlers().unregister(this);
-			return;
-		}
+        for (Block block : event.getBlocks()) {
+            if (((block.getType() == WALL_SIGN || block.getType() == SIGN_POST) && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(block))) || EssentialsSign.checkIfBlockBreaksSigns(block)) {
+                event.setCancelled(true);
+                return;
+            }
+            for (EssentialsSign sign : ess.getSettings().enabledSigns()) {
+                if (sign.areHeavyEventRequired() && sign.getBlocks().contains(block.getType()) && !sign.onBlockPush(block, ess)) {
+                    event.setCancelled(true);
+                    return;
+                }
+            }
+        }
+    }
 
-		if (event.isSticky())
-		{
-			final Block pistonBaseBlock = event.getBlock();
-			final Block[] affectedBlocks = new Block[]
-			{
-				pistonBaseBlock,
-				pistonBaseBlock.getRelative(event.getDirection()),
-				event.getRetractLocation().getBlock()
-			};
+    @EventHandler(priority = EventPriority.LOW)
+    public void onSignBlockPistonRetract(final BlockPistonRetractEvent event) {
+        if (ess.getSettings().areSignsDisabled()) {
+            event.getHandlers().unregister(this);
+            return;
+        }
 
-			for (Block block : affectedBlocks)
-			{
-				if (((block.getType() == WALL_SIGN
-					  || block.getType() == SIGN_POST)
-					 && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(block)))
-					|| EssentialsSign.checkIfBlockBreaksSigns(block))
-				{
-					event.setCancelled(true);
-					return;
-				}
-				for (EssentialsSign sign : ess.getSettings().enabledSigns())
-				{
-					if (sign.areHeavyEventRequired() && sign.getBlocks().contains(block.getType())
-						&& !sign.onBlockPush(block, ess))
-					{
-						event.setCancelled(true);
-						return;
-					}
-				}
-			}
-		}
-	}
+        if (event.isSticky()) {
+            final Block pistonBaseBlock = event.getBlock();
+            final Block[] affectedBlocks = new Block[]{pistonBaseBlock, pistonBaseBlock.getRelative(event.getDirection()), event.getRetractLocation().getBlock()};
+
+            for (Block block : affectedBlocks) {
+                if (((block.getType() == WALL_SIGN || block.getType() == SIGN_POST) && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(block))) || EssentialsSign.checkIfBlockBreaksSigns(block)) {
+                    event.setCancelled(true);
+                    return;
+                }
+                for (EssentialsSign sign : ess.getSettings().enabledSigns()) {
+                    if (sign.areHeavyEventRequired() && sign.getBlocks().contains(block.getType()) && !sign.onBlockPush(block, ess)) {
+                        event.setCancelled(true);
+                        return;
+                    }
+                }
+            }
+        }
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/signs/SignBuy.java b/Essentials/src/com/earth2me/essentials/signs/SignBuy.java
index 13c7799c7..c2d51afe3 100644
--- a/Essentials/src/com/earth2me/essentials/signs/SignBuy.java
+++ b/Essentials/src/com/earth2me/essentials/signs/SignBuy.java
@@ -7,33 +7,28 @@ import net.ess3.api.IEssentials;
 import net.ess3.api.MaxMoneyException;
 
 
-public class SignBuy extends EssentialsSign
-{
-	public SignBuy()
-	{
-		super("Buy");
-	}
+public class SignBuy extends EssentialsSign {
+    public SignBuy() {
+        super("Buy");
+    }
 
-	@Override
-	protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException
-	{
-		validateTrade(sign, 1, 2, player, ess);
-		validateTrade(sign, 3, ess);
-		return true;
-	}
+    @Override
+    protected boolean onSignCreate(final ISign sign, final User 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 User player, final String username, final IEssentials ess) throws SignException, ChargeException, MaxMoneyException
-	{
-		final Trade items = getTrade(sign, 1, 2, player, ess);
-		final Trade charge = getTrade(sign, 3, ess);
-		charge.isAffordableFor(player);
-		if (!items.pay(player))
-		{
-			throw new ChargeException("Inventory full"); //TODO: TL
-		}
-		charge.charge(player);
-		Trade.log("Sign", "Buy", "Interact", username, charge, username, items, sign.getBlock().getLocation(), ess);
-		return true;
-	}
+    @Override
+    protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException, MaxMoneyException {
+        final Trade items = getTrade(sign, 1, 2, player, ess);
+        final Trade charge = getTrade(sign, 3, ess);
+        charge.isAffordableFor(player);
+        if (!items.pay(player)) {
+            throw new ChargeException("Inventory full"); //TODO: TL
+        }
+        charge.charge(player);
+        Trade.log("Sign", "Buy", "Interact", username, charge, username, items, sign.getBlock().getLocation(), ess);
+        return true;
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/signs/SignDisposal.java b/Essentials/src/com/earth2me/essentials/signs/SignDisposal.java
index 981f5499d..7ede34ec9 100644
--- a/Essentials/src/com/earth2me/essentials/signs/SignDisposal.java
+++ b/Essentials/src/com/earth2me/essentials/signs/SignDisposal.java
@@ -4,17 +4,14 @@ import com.earth2me.essentials.User;
 import net.ess3.api.IEssentials;
 
 
-public class SignDisposal extends EssentialsSign
-{
-	public SignDisposal()
-	{
-		super("Disposal");
-	}
+public class SignDisposal extends EssentialsSign {
+    public SignDisposal() {
+        super("Disposal");
+    }
 
-	@Override
-	protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess)
-	{
-		player.getBase().openInventory(ess.getServer().createInventory(player.getBase(), 36, "Disposal"));
-		return true;
-	}
+    @Override
+    protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) {
+        player.getBase().openInventory(ess.getServer().createInventory(player.getBase(), 36, "Disposal"));
+        return true;
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/signs/SignEnchant.java b/Essentials/src/com/earth2me/essentials/signs/SignEnchant.java
index 89cfa30e9..9e62c47e9 100644
--- a/Essentials/src/com/earth2me/essentials/signs/SignEnchant.java
+++ b/Essentials/src/com/earth2me/essentials/signs/SignEnchant.java
@@ -1,160 +1,122 @@
 package com.earth2me.essentials.signs;
 
-import com.earth2me.essentials.*;
-import static com.earth2me.essentials.I18n.tl;
-import java.util.Locale;
+import com.earth2me.essentials.ChargeException;
+import com.earth2me.essentials.Enchantments;
+import com.earth2me.essentials.Trade;
+import com.earth2me.essentials.User;
 import net.ess3.api.IEssentials;
 import org.bukkit.enchantments.Enchantment;
 import org.bukkit.inventory.ItemStack;
 
+import java.util.Locale;
 
-public class SignEnchant extends EssentialsSign
-{
-	public SignEnchant()
-	{
-		super("Enchant");
-	}
+import static com.earth2me.essentials.I18n.tl;
 
-	@Override
-	protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException
-	{
-		final ItemStack stack;
-		try
-		{
-			stack = sign.getLine(1).equals("*") || sign.getLine(1).equalsIgnoreCase("any") ? null : getItemStack(sign.getLine(1), 1, ess);
-		}
-		catch (SignException e)
-		{
-			sign.setLine(1, "§c");
-			throw e;
-		}
-		final String[] enchantLevel = sign.getLine(2).split(":");
-		if (enchantLevel.length != 2)
-		{
-			sign.setLine(2, "§c");
-			throw new SignException(tl("invalidSignLine", 3));
-		}
-		final Enchantment enchantment = Enchantments.getByName(enchantLevel[0]);
-		if (enchantment == null)
-		{
-			sign.setLine(2, "§c");
-			throw new SignException(tl("enchantmentNotFound"));
-		}
-		int level;
-		try
-		{
-			level = Integer.parseInt(enchantLevel[1]);
-		}
-		catch (NumberFormatException ex)
-		{
-			sign.setLine(2, "§c");
-			throw new SignException(ex.getMessage(), ex);
-		}
-		final boolean allowUnsafe = ess.getSettings().allowUnsafeEnchantments() 
-									&& player.isAuthorized("essentials.enchantments.allowunsafe") && player.isAuthorized("essentials.signs.enchant.allowunsafe");
-		if (level < 0 || (!allowUnsafe && level > enchantment.getMaxLevel()))
-		{
-			level = enchantment.getMaxLevel();
-			sign.setLine(2, enchantLevel[0] + ":" + level);
-		}
-		try
-		{
-			if (stack != null)
-			{
-				if (allowUnsafe)
-				{
-					stack.addUnsafeEnchantment(enchantment, level);
-				}
-				else
-				{
-					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, User 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);
-		final Trade charge = getTrade(sign, 3, ess);
-		charge.isAffordableFor(player);
-		final String[] enchantLevel = sign.getLine(2).split(":");
-		if (enchantLevel.length != 2)
-		{
-			throw new SignException(tl("invalidSignLine", 3));
-		}
-		final Enchantment enchantment = Enchantments.getByName(enchantLevel[0]);
-		if (enchantment == null)
-		{
-			throw new SignException(tl("enchantmentNotFound"));
-		}
-		int level;
-		try
-		{
-			level = Integer.parseInt(enchantLevel[1]);
-		}
-		catch (NumberFormatException ex)
-		{
-			level = enchantment.getMaxLevel();
-		}
+public class SignEnchant extends EssentialsSign {
+    public SignEnchant() {
+        super("Enchant");
+    }
 
-		final ItemStack playerHand = player.getBase().getItemInHand();
-		if (playerHand == null
-			|| playerHand.getAmount() != 1
-			|| (playerHand.containsEnchantment(enchantment)
-				&& playerHand.getEnchantmentLevel(enchantment) == level))
-		{
-			throw new SignException(tl("missingItems", 1, sign.getLine(1)));
-		}
-		if (search != null && playerHand.getType() != search.getType())
-		{
-			throw new SignException(tl("missingItems", 1, search.getType().toString().toLowerCase(Locale.ENGLISH).replace('_', ' ')));
-		}
+    @Override
+    protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException {
+        final ItemStack stack;
+        try {
+            stack = sign.getLine(1).equals("*") || sign.getLine(1).equalsIgnoreCase("any") ? null : getItemStack(sign.getLine(1), 1, ess);
+        } catch (SignException e) {
+            sign.setLine(1, "§c");
+            throw e;
+        }
+        final String[] enchantLevel = sign.getLine(2).split(":");
+        if (enchantLevel.length != 2) {
+            sign.setLine(2, "§c");
+            throw new SignException(tl("invalidSignLine", 3));
+        }
+        final Enchantment enchantment = Enchantments.getByName(enchantLevel[0]);
+        if (enchantment == null) {
+            sign.setLine(2, "§c");
+            throw new SignException(tl("enchantmentNotFound"));
+        }
+        int level;
+        try {
+            level = Integer.parseInt(enchantLevel[1]);
+        } catch (NumberFormatException ex) {
+            sign.setLine(2, "§c");
+            throw new SignException(ex.getMessage(), ex);
+        }
+        final boolean allowUnsafe = ess.getSettings().allowUnsafeEnchantments() && player.isAuthorized("essentials.enchantments.allowunsafe") && player.isAuthorized("essentials.signs.enchant.allowunsafe");
+        if (level < 0 || (!allowUnsafe && level > enchantment.getMaxLevel())) {
+            level = enchantment.getMaxLevel();
+            sign.setLine(2, enchantLevel[0] + ":" + level);
+        }
+        try {
+            if (stack != null) {
+                if (allowUnsafe) {
+                    stack.addUnsafeEnchantment(enchantment, level);
+                } else {
+                    stack.addEnchantment(enchantment, level);
+                }
+            }
+        } catch (Throwable ex) {
+            throw new SignException(ex.getMessage(), ex);
+        }
+        getTrade(sign, 3, ess);
+        return true;
+    }
 
-		final ItemStack toEnchant = playerHand;
-		try
-		{
-			if (level == 0)
-			{
-				toEnchant.removeEnchantment(enchantment);
-			}
-			else
-			{
-				if (ess.getSettings().allowUnsafeEnchantments() && player.isAuthorized("essentials.signs.enchant.allowunsafe"))
-				{
-					toEnchant.addUnsafeEnchantment(enchantment, level);
-				}
-				else
-				{
-					toEnchant.addEnchantment(enchantment, level);
-				}
-			}
-		}
-		catch (Exception ex)
-		{
-			throw new SignException(ex.getMessage(), ex);
-		}
+    @Override
+    protected boolean onSignInteract(ISign sign, User 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);
+        final Trade charge = getTrade(sign, 3, ess);
+        charge.isAffordableFor(player);
+        final String[] enchantLevel = sign.getLine(2).split(":");
+        if (enchantLevel.length != 2) {
+            throw new SignException(tl("invalidSignLine", 3));
+        }
+        final Enchantment enchantment = Enchantments.getByName(enchantLevel[0]);
+        if (enchantment == null) {
+            throw new SignException(tl("enchantmentNotFound"));
+        }
+        int level;
+        try {
+            level = Integer.parseInt(enchantLevel[1]);
+        } catch (NumberFormatException ex) {
+            level = enchantment.getMaxLevel();
+        }
 
-		final String enchantmentName = enchantment.getName().toLowerCase(Locale.ENGLISH);
-		if (level == 0)
-		{
-			player.sendMessage(tl("enchantmentRemoved", enchantmentName.replace('_', ' ')));
-		}
-		else
-		{
-			player.sendMessage(tl("enchantmentApplied", enchantmentName.replace('_', ' ')));
-		}
+        final ItemStack playerHand = player.getBase().getItemInHand();
+        if (playerHand == null || playerHand.getAmount() != 1 || (playerHand.containsEnchantment(enchantment) && playerHand.getEnchantmentLevel(enchantment) == level)) {
+            throw new SignException(tl("missingItems", 1, sign.getLine(1)));
+        }
+        if (search != null && playerHand.getType() != search.getType()) {
+            throw new SignException(tl("missingItems", 1, search.getType().toString().toLowerCase(Locale.ENGLISH).replace('_', ' ')));
+        }
 
-		charge.charge(player);
-		Trade.log("Sign", "Enchant", "Interact", username, charge, username, charge, sign.getBlock().getLocation(), ess);
-		player.getBase().updateInventory();
-		return true;
-	}
+        final ItemStack toEnchant = playerHand;
+        try {
+            if (level == 0) {
+                toEnchant.removeEnchantment(enchantment);
+            } else {
+                if (ess.getSettings().allowUnsafeEnchantments() && player.isAuthorized("essentials.signs.enchant.allowunsafe")) {
+                    toEnchant.addUnsafeEnchantment(enchantment, level);
+                } else {
+                    toEnchant.addEnchantment(enchantment, level);
+                }
+            }
+        } catch (Exception ex) {
+            throw new SignException(ex.getMessage(), ex);
+        }
+
+        final String enchantmentName = enchantment.getName().toLowerCase(Locale.ENGLISH);
+        if (level == 0) {
+            player.sendMessage(tl("enchantmentRemoved", enchantmentName.replace('_', ' ')));
+        } else {
+            player.sendMessage(tl("enchantmentApplied", enchantmentName.replace('_', ' ')));
+        }
+
+        charge.charge(player);
+        Trade.log("Sign", "Enchant", "Interact", username, charge, username, charge, sign.getBlock().getLocation(), ess);
+        player.getBase().updateInventory();
+        return true;
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/signs/SignEntityListener.java b/Essentials/src/com/earth2me/essentials/signs/SignEntityListener.java
index d6753a943..65aa2fc0e 100644
--- a/Essentials/src/com/earth2me/essentials/signs/SignEntityListener.java
+++ b/Essentials/src/com/earth2me/essentials/signs/SignEntityListener.java
@@ -10,71 +10,51 @@ import org.bukkit.event.entity.EntityChangeBlockEvent;
 import org.bukkit.event.entity.EntityExplodeEvent;
 
 
-public class SignEntityListener implements Listener
-{
-	private final transient IEssentials ess;
+public class SignEntityListener implements Listener {
+    private final transient IEssentials ess;
 
-	public SignEntityListener(final IEssentials ess)
-	{
-		this.ess = ess;
-	}
+    public SignEntityListener(final IEssentials ess) {
+        this.ess = ess;
+    }
 
-	@EventHandler(priority = EventPriority.LOW)
-	public void onSignEntityExplode(final EntityExplodeEvent event)
-	{
-		if (ess.getSettings().areSignsDisabled())
-		{
-			event.getHandlers().unregister(this);
-			return;
-		}
-		
-		for (Block block : event.blockList())
-		{
-			if (((block.getType() == Material.WALL_SIGN
-				  || block.getType() == Material.SIGN_POST)
-				 && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(block)))
-				|| EssentialsSign.checkIfBlockBreaksSigns(block))
-			{
-				event.setCancelled(true);
-				return;
-			}
-			for (EssentialsSign sign : ess.getSettings().enabledSigns())
-			{
-				if (sign.areHeavyEventRequired() && sign.getBlocks().contains(block.getType()))
-				{
-					event.setCancelled(!sign.onBlockExplode(block, ess));
-					return;
-				}
-			}
-		}
-	}
+    @EventHandler(priority = EventPriority.LOW)
+    public void onSignEntityExplode(final EntityExplodeEvent event) {
+        if (ess.getSettings().areSignsDisabled()) {
+            event.getHandlers().unregister(this);
+            return;
+        }
 
-	@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
-	public void onSignEntityChangeBlock(final EntityChangeBlockEvent event)
-	{
-		if (ess.getSettings().areSignsDisabled())
-		{
-			event.getHandlers().unregister(this);
-			return;
-		}
+        for (Block block : event.blockList()) {
+            if (((block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST) && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(block))) || EssentialsSign.checkIfBlockBreaksSigns(block)) {
+                event.setCancelled(true);
+                return;
+            }
+            for (EssentialsSign sign : ess.getSettings().enabledSigns()) {
+                if (sign.areHeavyEventRequired() && sign.getBlocks().contains(block.getType())) {
+                    event.setCancelled(!sign.onBlockExplode(block, ess));
+                    return;
+                }
+            }
+        }
+    }
 
-		final Block block = event.getBlock();
-		if (((block.getType() == Material.WALL_SIGN
-			  || block.getType() == Material.SIGN_POST)
-			 && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(block)))
-			|| EssentialsSign.checkIfBlockBreaksSigns(block))
-		{
-			event.setCancelled(true);
-			return;
-		}
-		for (EssentialsSign sign : ess.getSettings().enabledSigns())
-		{
-			if (sign.areHeavyEventRequired() && sign.getBlocks().contains(block.getType())
-				&& !sign.onBlockBreak(block, ess))
-			{
-				event.setCancelled(true);
-				return;
-			}
-		}
-	}
+    @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
+    public void onSignEntityChangeBlock(final EntityChangeBlockEvent event) {
+        if (ess.getSettings().areSignsDisabled()) {
+            event.getHandlers().unregister(this);
+            return;
+        }
+
+        final Block block = event.getBlock();
+        if (((block.getType() == Material.WALL_SIGN || block.getType() == Material.SIGN_POST) && EssentialsSign.isValidSign(new EssentialsSign.BlockSign(block))) || EssentialsSign.checkIfBlockBreaksSigns(block)) {
+            event.setCancelled(true);
+            return;
+        }
+        for (EssentialsSign sign : ess.getSettings().enabledSigns()) {
+            if (sign.areHeavyEventRequired() && sign.getBlocks().contains(block.getType()) && !sign.onBlockBreak(block, ess)) {
+                event.setCancelled(true);
+                return;
+            }
+        }
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/signs/SignException.java b/Essentials/src/com/earth2me/essentials/signs/SignException.java
index 9c9ab44a2..2a00f8270 100644
--- a/Essentials/src/com/earth2me/essentials/signs/SignException.java
+++ b/Essentials/src/com/earth2me/essentials/signs/SignException.java
@@ -1,15 +1,12 @@
 package com.earth2me.essentials.signs;
 
 
-public class SignException extends Exception
-{
-	public SignException(final String message)
-	{
-		super(message);
-	}
+public class SignException extends Exception {
+    public SignException(final String message) {
+        super(message);
+    }
 
-	public SignException(final String message, final Throwable throwable)
-	{
-		super(message, throwable);
-	}
+    public SignException(final String message, final Throwable throwable) {
+        super(message, throwable);
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/signs/SignFree.java b/Essentials/src/com/earth2me/essentials/signs/SignFree.java
index 9771d4868..617d29e01 100644
--- a/Essentials/src/com/earth2me/essentials/signs/SignFree.java
+++ b/Essentials/src/com/earth2me/essentials/signs/SignFree.java
@@ -1,6 +1,5 @@
 package com.earth2me.essentials.signs;
 
-import static com.earth2me.essentials.I18n.tl;
 import com.earth2me.essentials.Trade;
 import com.earth2me.essentials.User;
 import net.ess3.api.IEssentials;
@@ -9,54 +8,49 @@ import org.bukkit.inventory.Inventory;
 import org.bukkit.inventory.ItemStack;
 import org.bukkit.inventory.meta.ItemMeta;
 
+import static com.earth2me.essentials.I18n.tl;
 
-public class SignFree extends EssentialsSign
-{
-	public SignFree()
-	{
-		super("Free");
-	}
 
-	@Override
-	protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException
-	{
-		try {
-			ItemStack item = getItemStack(sign.getLine(1), 1, ess);
-			item = getItemMeta(item, sign.getLine(2), ess);
-			item = getItemMeta(item, sign.getLine(3), ess);
-		}
-		catch (SignException ex)
-		{
-			sign.setLine(1, "§c");
-			throw new SignException(ex.getMessage(), ex);
-		}
-		return true;
-	}
+public class SignFree extends EssentialsSign {
+    public SignFree() {
+        super("Free");
+    }
 
-	@Override
-	protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException
-	{		
-		ItemStack itemStack = getItemStack(sign.getLine(1), 1, ess);		
-		itemStack = getItemMeta(itemStack, sign.getLine(2), ess);		
-		final ItemStack item = getItemMeta(itemStack, sign.getLine(3), ess);		
-		
-		if (item.getType() == Material.AIR)
-		{
-			throw new SignException(tl("cantSpawnItem", "Air"));
-		}
+    @Override
+    protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException {
+        try {
+            ItemStack item = getItemStack(sign.getLine(1), 1, ess);
+            item = getItemMeta(item, sign.getLine(2), ess);
+            item = getItemMeta(item, sign.getLine(3), ess);
+        } catch (SignException ex) {
+            sign.setLine(1, "§c");
+            throw new SignException(ex.getMessage(), ex);
+        }
+        return true;
+    }
 
-		item.setAmount(item.getType().getMaxStackSize());
-		
-		ItemMeta meta = item.getItemMeta();
-			
-		final String displayName = meta.hasDisplayName() ? meta.getDisplayName() : item.getType().toString();
-				
-		Inventory invent = ess.getServer().createInventory(player.getBase(), 36, displayName);
-		for (int i = 0; i < 36; i++) {
-			invent.addItem(item);
-		}
-		player.getBase().openInventory(invent);
-		Trade.log("Sign", "Free", "Interact", username, null, username, new Trade(item, ess), sign.getBlock().getLocation(), ess);
-		return true;
-	}
+    @Override
+    protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException {
+        ItemStack itemStack = getItemStack(sign.getLine(1), 1, ess);
+        itemStack = getItemMeta(itemStack, sign.getLine(2), ess);
+        final ItemStack item = getItemMeta(itemStack, sign.getLine(3), ess);
+
+        if (item.getType() == Material.AIR) {
+            throw new SignException(tl("cantSpawnItem", "Air"));
+        }
+
+        item.setAmount(item.getType().getMaxStackSize());
+
+        ItemMeta meta = item.getItemMeta();
+
+        final String displayName = meta.hasDisplayName() ? meta.getDisplayName() : item.getType().toString();
+
+        Inventory invent = ess.getServer().createInventory(player.getBase(), 36, displayName);
+        for (int i = 0; i < 36; i++) {
+            invent.addItem(item);
+        }
+        player.getBase().openInventory(invent);
+        Trade.log("Sign", "Free", "Interact", username, null, username, new Trade(item, ess), sign.getBlock().getLocation(), ess);
+        return true;
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/signs/SignGameMode.java b/Essentials/src/com/earth2me/essentials/signs/SignGameMode.java
index 51580f7de..05db6c661 100644
--- a/Essentials/src/com/earth2me/essentials/signs/SignGameMode.java
+++ b/Essentials/src/com/earth2me/essentials/signs/SignGameMode.java
@@ -1,73 +1,61 @@
 package com.earth2me.essentials.signs;
 
 import com.earth2me.essentials.ChargeException;
-import static com.earth2me.essentials.I18n.tl;
 import com.earth2me.essentials.Trade;
 import com.earth2me.essentials.User;
-import java.util.Locale;
 import net.ess3.api.IEssentials;
 import org.bukkit.GameMode;
 import org.bukkit.entity.Player;
 
+import java.util.Locale;
 
-public class SignGameMode extends EssentialsSign
-{
-	public SignGameMode()
-	{
-		super("GameMode");
-	}
+import static com.earth2me.essentials.I18n.tl;
 
-	@Override
-	protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException
-	{
-		final String gamemode = sign.getLine(1);
-		if (gamemode.isEmpty())
-		{
-			sign.setLine(1, "Survival");
-		}
 
-		validateTrade(sign, 2, ess);
+public class SignGameMode extends EssentialsSign {
+    public SignGameMode() {
+        super("GameMode");
+    }
 
-		return true;
-	}
+    @Override
+    protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException {
+        final String gamemode = sign.getLine(1);
+        if (gamemode.isEmpty()) {
+            sign.setLine(1, "Survival");
+        }
 
-	@Override
-	protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException
-	{
-		final Trade charge = getTrade(sign, 2, ess);
-		final String mode = sign.getLine(1).trim();
+        validateTrade(sign, 2, ess);
 
-		if (mode.isEmpty())
-		{
-			throw new SignException(tl("invalidSignLine", 2));
-		}
+        return true;
+    }
 
-		charge.isAffordableFor(player);
+    @Override
+    protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException {
+        final Trade charge = getTrade(sign, 2, ess);
+        final String mode = sign.getLine(1).trim();
 
-		performSetMode(mode.toLowerCase(Locale.ENGLISH), player.getBase());
-		player.sendMessage(tl("gameMode", tl(player.getBase().getGameMode().toString().toLowerCase(Locale.ENGLISH)), player.getDisplayName()));
-		Trade.log("Sign", "gameMode", "Interact", username, null, username, charge, sign.getBlock().getLocation(), ess);
-		charge.charge(player);
-		return true;
-	}
+        if (mode.isEmpty()) {
+            throw new SignException(tl("invalidSignLine", 2));
+        }
 
-	private void performSetMode(String mode, Player player) throws SignException
-	{
-		if (mode.contains("survi") || mode.equalsIgnoreCase("0"))
-		{
-			player.setGameMode(GameMode.SURVIVAL);
-		}
-		else if (mode.contains("creat") || mode.equalsIgnoreCase("1"))
-		{
-			player.setGameMode(GameMode.CREATIVE);
-		}
-		else if (mode.contains("advent") || mode.equalsIgnoreCase("2"))
-		{
-			player.setGameMode(GameMode.ADVENTURE);
-		}
-		else
-		{
-			throw new SignException(tl("invalidSignLine", 2));
-		}
-	}
+        charge.isAffordableFor(player);
+
+        performSetMode(mode.toLowerCase(Locale.ENGLISH), player.getBase());
+        player.sendMessage(tl("gameMode", tl(player.getBase().getGameMode().toString().toLowerCase(Locale.ENGLISH)), player.getDisplayName()));
+        Trade.log("Sign", "gameMode", "Interact", username, null, username, charge, sign.getBlock().getLocation(), ess);
+        charge.charge(player);
+        return true;
+    }
+
+    private void performSetMode(String mode, Player player) throws SignException {
+        if (mode.contains("survi") || mode.equalsIgnoreCase("0")) {
+            player.setGameMode(GameMode.SURVIVAL);
+        } else if (mode.contains("creat") || mode.equalsIgnoreCase("1")) {
+            player.setGameMode(GameMode.CREATIVE);
+        } else if (mode.contains("advent") || mode.equalsIgnoreCase("2")) {
+            player.setGameMode(GameMode.ADVENTURE);
+        } else {
+            throw new SignException(tl("invalidSignLine", 2));
+        }
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/signs/SignHeal.java b/Essentials/src/com/earth2me/essentials/signs/SignHeal.java
index 9f19d2968..a299e2214 100644
--- a/Essentials/src/com/earth2me/essentials/signs/SignHeal.java
+++ b/Essentials/src/com/earth2me/essentials/signs/SignHeal.java
@@ -1,41 +1,37 @@
 package com.earth2me.essentials.signs;
 
 import com.earth2me.essentials.ChargeException;
-import static com.earth2me.essentials.I18n.tl;
 import com.earth2me.essentials.Trade;
 import com.earth2me.essentials.User;
 import net.ess3.api.IEssentials;
 
+import static com.earth2me.essentials.I18n.tl;
 
-public class SignHeal extends EssentialsSign
-{
-	public SignHeal()
-	{
-		super("Heal");
-	}
 
-	@Override
-	protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException
-	{
-		validateTrade(sign, 1, ess);
-		return true;
-	}
+public class SignHeal extends EssentialsSign {
+    public SignHeal() {
+        super("Heal");
+    }
 
-	@Override
-	protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException
-	{
-		if (player.getBase().getHealth() == 0)
-		{
-			throw new SignException(tl("healDead"));
-		}
-		final Trade charge = getTrade(sign, 1, ess);
-		charge.isAffordableFor(player);
-		player.getBase().setHealth(20);
-		player.getBase().setFoodLevel(20);
-		player.getBase().setFireTicks(0);
-		player.sendMessage(tl("youAreHealed"));
-		charge.charge(player);
-		Trade.log("Sign", "Heal", "Interact", username, null, username, charge, sign.getBlock().getLocation(), ess);
-		return true;
-	}
+    @Override
+    protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException {
+        validateTrade(sign, 1, ess);
+        return true;
+    }
+
+    @Override
+    protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException {
+        if (player.getBase().getHealth() == 0) {
+            throw new SignException(tl("healDead"));
+        }
+        final Trade charge = getTrade(sign, 1, ess);
+        charge.isAffordableFor(player);
+        player.getBase().setHealth(20);
+        player.getBase().setFoodLevel(20);
+        player.getBase().setFireTicks(0);
+        player.sendMessage(tl("youAreHealed"));
+        charge.charge(player);
+        Trade.log("Sign", "Heal", "Interact", username, null, username, charge, sign.getBlock().getLocation(), ess);
+        return true;
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/signs/SignInfo.java b/Essentials/src/com/earth2me/essentials/signs/SignInfo.java
index d890b521d..c5df803bd 100644
--- a/Essentials/src/com/earth2me/essentials/signs/SignInfo.java
+++ b/Essentials/src/com/earth2me/essentials/signs/SignInfo.java
@@ -7,50 +7,44 @@ import com.earth2me.essentials.textreader.IText;
 import com.earth2me.essentials.textreader.KeywordReplacer;
 import com.earth2me.essentials.textreader.TextInput;
 import com.earth2me.essentials.textreader.TextPager;
-import java.io.IOException;
 import net.ess3.api.IEssentials;
 
+import java.io.IOException;
 
-public class SignInfo extends EssentialsSign
-{
-	public SignInfo()
-	{
-		super("Info");
-	}
 
-	@Override
-	protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException
-	{
-		validateTrade(sign, 3, ess);
-		return true;
-	}
+public class SignInfo extends EssentialsSign {
+    public SignInfo() {
+        super("Info");
+    }
 
-	@Override
-	protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException
-	{
-		final Trade charge = getTrade(sign, 3, ess);
-		charge.isAffordableFor(player);
+    @Override
+    protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException {
+        validateTrade(sign, 3, ess);
+        return true;
+    }
 
-		String chapter = sign.getLine(1);
-		String page = sign.getLine(2);
+    @Override
+    protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException {
+        final Trade charge = getTrade(sign, 3, ess);
+        charge.isAffordableFor(player);
 
-		final IText input;
-		try
-		{
-			player.setDisplayNick();
-			input = new TextInput(player.getSource(), "info", true, ess);
-			final IText output = new KeywordReplacer(input, player.getSource(), ess);
-			final TextPager pager = new TextPager(output);
-			pager.showPage(chapter, page, null, player.getSource());
+        String chapter = sign.getLine(1);
+        String page = sign.getLine(2);
 
-		}
-		catch (IOException ex)
-		{
-			throw new SignException(ex.getMessage(), ex);
-		}
+        final IText input;
+        try {
+            player.setDisplayNick();
+            input = new TextInput(player.getSource(), "info", true, ess);
+            final IText output = new KeywordReplacer(input, player.getSource(), ess);
+            final TextPager pager = new TextPager(output);
+            pager.showPage(chapter, page, null, player.getSource());
 
-		charge.charge(player);
-		Trade.log("Sign", "Info", "Interact", username, null, username, charge, sign.getBlock().getLocation(), ess);
-		return true;
-	}
+        } catch (IOException ex) {
+            throw new SignException(ex.getMessage(), ex);
+        }
+
+        charge.charge(player);
+        Trade.log("Sign", "Info", "Interact", username, null, username, charge, sign.getBlock().getLocation(), ess);
+        return true;
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/signs/SignKit.java b/Essentials/src/com/earth2me/essentials/signs/SignKit.java
index c956ef104..d47110d97 100644
--- a/Essentials/src/com/earth2me/essentials/signs/SignKit.java
+++ b/Essentials/src/com/earth2me/essentials/signs/SignKit.java
@@ -1,90 +1,72 @@
 package com.earth2me.essentials.signs;
 
-import com.earth2me.essentials.*;
-import static com.earth2me.essentials.I18n.tl;
+import com.earth2me.essentials.ChargeException;
+import com.earth2me.essentials.Kit;
+import com.earth2me.essentials.Trade;
+import com.earth2me.essentials.User;
 import com.earth2me.essentials.commands.NoChargeException;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
 import net.ess3.api.IEssentials;
 
+import java.util.Locale;
 
-public class SignKit extends EssentialsSign
-{
-	public SignKit()
-	{
-		super("Kit");
-	}
+import static com.earth2me.essentials.I18n.tl;
 
-	@Override
-	protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException
-	{
-		validateTrade(sign, 3, ess);
 
-		final String kitName = sign.getLine(1).toLowerCase(Locale.ENGLISH).trim();
+public class SignKit extends EssentialsSign {
+    public SignKit() {
+        super("Kit");
+    }
 
-		if (kitName.isEmpty())
-		{
-			sign.setLine(1, "§dKit name!");
-			return false;
-		}
-		else
-		{
-			try
-			{
-				ess.getSettings().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 onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException {
+        validateTrade(sign, 3, ess);
 
-	@Override
-	protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException
-	{
-		final String kitName = sign.getLine(1).toLowerCase(Locale.ENGLISH).trim();
-		final String group = sign.getLine(2).trim();
-		if ((!group.isEmpty() && ("§2Everyone".equals(group) || player.inGroup(group)))
-			|| (group.isEmpty() && (player.isAuthorized("essentials.kits." + kitName))))
-		{
-			final Trade charge = getTrade(sign, 3, ess);
-			charge.isAffordableFor(player);
-			try
-			{
-				final Kit kit = new Kit(kitName, ess);
-				kit.checkDelay(player);
-				kit.setTime(player);
-				kit.expandItems(player);
+        final String kitName = sign.getLine(1).toLowerCase(Locale.ENGLISH).trim();
 
-				charge.charge(player);
-				Trade.log("Sign", "Kit", "Interact", username, null, username, charge, sign.getBlock().getLocation(), ess);
-			}
-			catch (NoChargeException ex)
-			{
-				return false;
-			}
-			catch (Exception ex)
-			{
-				throw new SignException(ex.getMessage(), ex);
-			}
-			return true;
-		}
-		else
-		{
-			if (group.isEmpty()) {
-				throw new SignException(tl("noKitPermission", "essentials.kits." + kitName));
-			}
-			else {
-				throw new SignException(tl("noKitGroup", group));
-			}
-		}
-	}
+        if (kitName.isEmpty()) {
+            sign.setLine(1, "§dKit name!");
+            return false;
+        } else {
+            try {
+                ess.getSettings().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 User player, final String username, final IEssentials ess) throws SignException, ChargeException {
+        final String kitName = sign.getLine(1).toLowerCase(Locale.ENGLISH).trim();
+        final String group = sign.getLine(2).trim();
+        if ((!group.isEmpty() && ("§2Everyone".equals(group) || player.inGroup(group))) || (group.isEmpty() && (player.isAuthorized("essentials.kits." + kitName)))) {
+            final Trade charge = getTrade(sign, 3, ess);
+            charge.isAffordableFor(player);
+            try {
+                final Kit kit = new Kit(kitName, ess);
+                kit.checkDelay(player);
+                kit.setTime(player);
+                kit.expandItems(player);
+
+                charge.charge(player);
+                Trade.log("Sign", "Kit", "Interact", username, null, username, charge, sign.getBlock().getLocation(), ess);
+            } catch (NoChargeException ex) {
+                return false;
+            } catch (Exception ex) {
+                throw new SignException(ex.getMessage(), ex);
+            }
+            return true;
+        } else {
+            if (group.isEmpty()) {
+                throw new SignException(tl("noKitPermission", "essentials.kits." + kitName));
+            } else {
+                throw new SignException(tl("noKitGroup", group));
+            }
+        }
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/signs/SignMail.java b/Essentials/src/com/earth2me/essentials/signs/SignMail.java
index 85f150eca..a20572a04 100644
--- a/Essentials/src/com/earth2me/essentials/signs/SignMail.java
+++ b/Essentials/src/com/earth2me/essentials/signs/SignMail.java
@@ -1,32 +1,29 @@
 package com.earth2me.essentials.signs;
 
-import static com.earth2me.essentials.I18n.tl;
 import com.earth2me.essentials.User;
-import java.util.List;
 import net.ess3.api.IEssentials;
 
+import java.util.List;
 
-public class SignMail extends EssentialsSign
-{
-	public SignMail()
-	{
-		super("Mail");
-	}
+import static com.earth2me.essentials.I18n.tl;
 
-	@Override
-	protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException
-	{
-		final List mail = player.getMails();
-		if (mail.isEmpty())
-		{
-			player.sendMessage(tl("noNewMail"));
-			return false;
-		}
-		for (String s : mail)
-		{
-			player.sendMessage(s);
-		}
-		player.sendMessage(tl("markMailAsRead"));
-		return true;
-	}
+
+public class SignMail extends EssentialsSign {
+    public SignMail() {
+        super("Mail");
+    }
+
+    @Override
+    protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException {
+        final List mail = player.getMails();
+        if (mail.isEmpty()) {
+            player.sendMessage(tl("noNewMail"));
+            return false;
+        }
+        for (String s : mail) {
+            player.sendMessage(s);
+        }
+        player.sendMessage(tl("markMailAsRead"));
+        return true;
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/signs/SignPlayerListener.java b/Essentials/src/com/earth2me/essentials/signs/SignPlayerListener.java
index 042c5003f..ebb4613bc 100644
--- a/Essentials/src/com/earth2me/essentials/signs/SignPlayerListener.java
+++ b/Essentials/src/com/earth2me/essentials/signs/SignPlayerListener.java
@@ -1,6 +1,5 @@
 package com.earth2me.essentials.signs;
 
-import java.util.logging.Level;
 import net.ess3.api.IEssentials;
 import org.bukkit.Material;
 import org.bukkit.block.Block;
@@ -11,83 +10,64 @@ import org.bukkit.event.Listener;
 import org.bukkit.event.block.Action;
 import org.bukkit.event.player.PlayerInteractEvent;
 
+import java.util.logging.Level;
 
-public class SignPlayerListener implements Listener
-{
-	private final transient IEssentials ess;
 
-	public SignPlayerListener(final IEssentials ess)
-	{
-		this.ess = ess;
-	}
+public class SignPlayerListener implements Listener {
+    private final transient IEssentials ess;
 
-	//This following code below listens to cancelled events to fix a bukkit issue
-	//Right clicking signs with a block in hand, can now fire cancelled events.
-	//This is because when the block place is cancelled (for example not enough space for the block to be placed),
-	//the event will be marked as cancelled, thus preventing 30% of sign purchases.
-	@EventHandler(priority = EventPriority.LOW)
-	public void onSignPlayerInteract(final PlayerInteractEvent event)
-	{
-		if (ess.getSettings().areSignsDisabled())
-		{
-			event.getHandlers().unregister(this);
-			return;
-		}
-		if (event.getAction() != Action.RIGHT_CLICK_BLOCK && event.getAction() != Action.RIGHT_CLICK_AIR)
-		{
-			return;
-		}
-		final Block block;
-		if (event.isCancelled() && event.getAction() == Action.RIGHT_CLICK_AIR)
-		{
-			Block targetBlock = null;
-			try
-			{
-				targetBlock = event.getPlayer().getTargetBlock(null, 5);
-			}
-			catch (IllegalStateException ex)
-			{
-				if (ess.getSettings().isDebug())
-				{
-					ess.getLogger().log(Level.WARNING, ex.getMessage(), ex);
-				}
-			}
-			block = targetBlock;
-		}
-		else
-		{
-			block = event.getClickedBlock();
-		}
-		if (block == null)
-		{
-			return;
-		}
+    public SignPlayerListener(final IEssentials ess) {
+        this.ess = ess;
+    }
 
-		final Material mat = block.getType();
-		if (mat == Material.SIGN_POST || mat == Material.WALL_SIGN)
-		{
-			final String csign = ((Sign)block.getState()).getLine(0);
-			for (EssentialsSign sign : ess.getSettings().enabledSigns())
-			{
-				if (csign.equalsIgnoreCase(sign.getSuccessName()))
-				{
-					sign.onSignInteract(block, event.getPlayer(), ess);
-					event.setCancelled(true);
-					return;
-				}
-			}
-		}
-		else
-		{
-			for (EssentialsSign sign : ess.getSettings().enabledSigns())
-			{
-				if (sign.areHeavyEventRequired() && sign.getBlocks().contains(block.getType())
-					&& !sign.onBlockInteract(block, event.getPlayer(), ess))
-				{
-					event.setCancelled(true);
-					return;
-				}
-			}
-		}
-	}
+    //This following code below listens to cancelled events to fix a bukkit issue
+    //Right clicking signs with a block in hand, can now fire cancelled events.
+    //This is because when the block place is cancelled (for example not enough space for the block to be placed),
+    //the event will be marked as cancelled, thus preventing 30% of sign purchases.
+    @EventHandler(priority = EventPriority.LOW)
+    public void onSignPlayerInteract(final PlayerInteractEvent event) {
+        if (ess.getSettings().areSignsDisabled()) {
+            event.getHandlers().unregister(this);
+            return;
+        }
+        if (event.getAction() != Action.RIGHT_CLICK_BLOCK && event.getAction() != Action.RIGHT_CLICK_AIR) {
+            return;
+        }
+        final Block block;
+        if (event.isCancelled() && event.getAction() == Action.RIGHT_CLICK_AIR) {
+            Block targetBlock = null;
+            try {
+                targetBlock = event.getPlayer().getTargetBlock(null, 5);
+            } catch (IllegalStateException ex) {
+                if (ess.getSettings().isDebug()) {
+                    ess.getLogger().log(Level.WARNING, ex.getMessage(), ex);
+                }
+            }
+            block = targetBlock;
+        } else {
+            block = event.getClickedBlock();
+        }
+        if (block == null) {
+            return;
+        }
+
+        final Material mat = block.getType();
+        if (mat == Material.SIGN_POST || mat == Material.WALL_SIGN) {
+            final String csign = ((Sign) block.getState()).getLine(0);
+            for (EssentialsSign sign : ess.getSettings().enabledSigns()) {
+                if (csign.equalsIgnoreCase(sign.getSuccessName())) {
+                    sign.onSignInteract(block, event.getPlayer(), ess);
+                    event.setCancelled(true);
+                    return;
+                }
+            }
+        } else {
+            for (EssentialsSign sign : ess.getSettings().enabledSigns()) {
+                if (sign.areHeavyEventRequired() && sign.getBlocks().contains(block.getType()) && !sign.onBlockInteract(block, event.getPlayer(), ess)) {
+                    event.setCancelled(true);
+                    return;
+                }
+            }
+        }
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/signs/SignProtection.java b/Essentials/src/com/earth2me/essentials/signs/SignProtection.java
index 501782968..b39b41498 100644
--- a/Essentials/src/com/earth2me/essentials/signs/SignProtection.java
+++ b/Essentials/src/com/earth2me/essentials/signs/SignProtection.java
@@ -1,10 +1,10 @@
 package com.earth2me.essentials.signs;
 
-import com.earth2me.essentials.*;
-import static com.earth2me.essentials.I18n.tl;
+import com.earth2me.essentials.ChargeException;
+import com.earth2me.essentials.Trade;
 import com.earth2me.essentials.Trade.OverflowType;
+import com.earth2me.essentials.User;
 import com.earth2me.essentials.utils.FormatUtil;
-import java.util.*;
 import net.ess3.api.IEssentials;
 import net.ess3.api.MaxMoneyException;
 import org.bukkit.Location;
@@ -14,343 +14,270 @@ import org.bukkit.block.BlockFace;
 import org.bukkit.block.Sign;
 import org.bukkit.inventory.ItemStack;
 
+import java.util.*;
+
+import static com.earth2me.essentials.I18n.tl;
+
 
 @Deprecated // This sign will be removed soon
-public class SignProtection extends EssentialsSign
-{
-	private final transient Set protectedBlocks = EnumSet.noneOf(Material.class);
+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);
-	}
+    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 User 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);
-			if (state == SignProtectionState.NOSIGN || state == SignProtectionState.OWNER
-				|| player.isAuthorized("essentials.signs.protection.override"))
-			{
-				sign.setLine(3, "§1" + username);
-				return true;
-			}
-		}
-		player.sendMessage(tl("signProtectInvalidLocation"));
-		return false;
-	}
+    @Override
+    protected boolean onSignCreate(final ISign sign, final User 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);
+            if (state == SignProtectionState.NOSIGN || state == SignProtectionState.OWNER || player.isAuthorized("essentials.signs.protection.override")) {
+                sign.setLine(3, "§1" + username);
+                return true;
+            }
+        }
+        player.sendMessage(tl("signProtectInvalidLocation"));
+        return false;
+    }
 
-	@Override
-	protected boolean onSignBreak(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException
-	{
-		final SignProtectionState state = checkProtectionSign(sign, player, username);
-		return state == SignProtectionState.OWNER;
-	}
+    @Override
+    protected boolean onSignBreak(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException {
+        final SignProtectionState state = checkProtectionSign(sign, player, username);
+        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()))
-				{
-					//TODO: What?
-				}
-			}
-			if (protectedBlocks.contains(b.getType()))
-			{
-				return true;
-			}
-		}
-		return false;
-	}
+    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())) {
+                    //TODO: What?
+                }
+            }
+            if (protectedBlocks.contains(b.getType())) {
+                return true;
+            }
+        }
+        return false;
+    }
 
-	private void checkIfSignsAreBroken(final Block block, final User player, final String username, final IEssentials ess) throws MaxMoneyException
-	{
-		final Map signs = getConnectedSigns(block, player, username, false);
-		for (Map.Entry entry : signs.entrySet())
-		{
-			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, OverflowType.DROP);
-				}
-			}
-		}
-	}
+    private void checkIfSignsAreBroken(final Block block, final User player, final String username, final IEssentials ess) throws MaxMoneyException {
+        final Map signs = getConnectedSigns(block, player, username, false);
+        for (Map.Entry entry : signs.entrySet()) {
+            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, OverflowType.DROP);
+                }
+            }
+        }
+    }
 
-	private Map getConnectedSigns(final Block block, final User user, final String username, boolean secure)
-	{
-		final Map signs = new HashMap();
-		getConnectedSigns(block, signs, user, username, secure ? 4 : 2);
-		return signs;
-	}
+    private Map getConnectedSigns(final Block block, final User user, final String username, boolean secure) {
+        final Map signs = new HashMap();
+        getConnectedSigns(block, signs, user, username, secure ? 4 : 2);
+        return signs;
+    }
 
-	private void getConnectedSigns(final Block block, final Map signs, final User user, final String username, final int depth)
-	{
-		final Block[] faces = getAdjacentBlocks(block);
-		for (Block b : faces)
-		{
-			final Location loc = b.getLocation();
-			if (signs.containsKey(loc))
-			{
-				continue;
-			}
-			final SignProtectionState check = checkProtectionSign(b, user, username);
-			signs.put(loc, check);
+    private void getConnectedSigns(final Block block, final Map signs, final User user, final String username, final int depth) {
+        final Block[] faces = getAdjacentBlocks(block);
+        for (Block b : faces) {
+            final Location loc = b.getLocation();
+            if (signs.containsKey(loc)) {
+                continue;
+            }
+            final SignProtectionState check = checkProtectionSign(b, user, username);
+            signs.put(loc, check);
 
-			if (protectedBlocks.contains(b.getType()) && depth > 0)
-			{
-				getConnectedSigns(b, signs, user, username, depth - 1);
-			}
-		}
-	}
+            if (protectedBlocks.contains(b.getType()) && depth > 0) {
+                getConnectedSigns(b, signs, user, username, depth - 1);
+            }
+        }
+    }
 
-	private SignProtectionState checkProtectionSign(final Block block, final User user, final String username)
-	{
-		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);
-			}
-		}
-		return SignProtectionState.NOSIGN;
-	}
+    private SignProtectionState checkProtectionSign(final Block block, final User user, final String username) {
+        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);
+            }
+        }
+        return SignProtectionState.NOSIGN;
+    }
 
-	private SignProtectionState checkProtectionSign(final ISign sign, final User user, final String username)
-	{
-		if (user == null || username == null)
-		{
-			return SignProtectionState.NOT_ALLOWED;
-		}
-		if (user.isAuthorized("essentials.signs.protection.override"))
-		{
-			return SignProtectionState.OWNER;
-		}
-		if (FormatUtil.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(")") && user.inGroup(line.substring(1, line.length() - 1)))
-			{
-				return SignProtectionState.ALLOWED;
-			}
-			else if (line.equalsIgnoreCase(username))
-			{
-				return SignProtectionState.ALLOWED;
-			}
-		}
-		return SignProtectionState.NOT_ALLOWED;
-	}
+    private SignProtectionState checkProtectionSign(final ISign sign, final User user, final String username) {
+        if (user == null || username == null) {
+            return SignProtectionState.NOT_ALLOWED;
+        }
+        if (user.isAuthorized("essentials.signs.protection.override")) {
+            return SignProtectionState.OWNER;
+        }
+        if (FormatUtil.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(")") && user.inGroup(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)
-				};
-	}
+    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 User user, final String username, boolean secure)
-	{
-		final Map signs = getConnectedSigns(block, user, username, secure);
-		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 SignProtectionState isBlockProtected(final Block block, final User user, final String username, boolean secure) {
+        final Map signs = getConnectedSigns(block, user, username, secure);
+        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);
+    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;
-	}
+                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
+    public Set getBlocks() {
+        return protectedBlocks;
+    }
 
-	@Override
-	public boolean areHeavyEventRequired()
-	{
-		return true;
-	}
+    @Override
+    public boolean areHeavyEventRequired() {
+        return true;
+    }
 
-	@Override
-	protected boolean onBlockPlace(final Block block, final User player, final String username, final IEssentials ess) throws SignException
-	{
-		for (Block adjBlock : getAdjacentBlocks(block))
-		{
-			final SignProtectionState state = isBlockProtected(adjBlock, player, username, true);
+    @Override
+    protected boolean onBlockPlace(final Block block, final User player, final String username, final IEssentials ess) throws SignException {
+        for (Block adjBlock : getAdjacentBlocks(block)) {
+            final SignProtectionState state = isBlockProtected(adjBlock, player, username, true);
 
-			if ((state == SignProtectionState.ALLOWED || state == SignProtectionState.NOT_ALLOWED)
-				&& !player.isAuthorized("essentials.signs.protection.override"))
-			{
-				player.sendMessage(tl("noPlacePermission", block.getType().toString().toLowerCase(Locale.ENGLISH)));
-				return false;
-			}
-		}
-		return true;
+            if ((state == SignProtectionState.ALLOWED || state == SignProtectionState.NOT_ALLOWED) && !player.isAuthorized("essentials.signs.protection.override")) {
+                player.sendMessage(tl("noPlacePermission", block.getType().toString().toLowerCase(Locale.ENGLISH)));
+                return false;
+            }
+        }
+        return true;
 
-	}
+    }
 
-	@Override
-	protected boolean onBlockInteract(final Block block, final User player, final String username, final IEssentials ess) throws SignException
-	{
-		final SignProtectionState state = isBlockProtected(block, player, username, false);
+    @Override
+    protected boolean onBlockInteract(final Block block, final User player, final String username, final IEssentials ess) throws SignException {
+        final SignProtectionState state = isBlockProtected(block, player, username, false);
 
-		if (state == SignProtectionState.OWNER || state == SignProtectionState.NOSIGN || state == SignProtectionState.ALLOWED)
-		{
-			return true;
-		}
+        if (state == SignProtectionState.OWNER || state == SignProtectionState.NOSIGN || state == SignProtectionState.ALLOWED) {
+            return true;
+        }
 
-		if (state == SignProtectionState.NOT_ALLOWED
-			&& player.isAuthorized("essentials.signs.protection.override"))
-		{
-			return true;
-		}
+        if (state == SignProtectionState.NOT_ALLOWED && player.isAuthorized("essentials.signs.protection.override")) {
+            return true;
+        }
 
 
-		player.sendMessage(tl("noAccessPermission", block.getType().toString().toLowerCase(Locale.ENGLISH)));
-		return false;
-	}
+        player.sendMessage(tl("noAccessPermission", block.getType().toString().toLowerCase(Locale.ENGLISH)));
+        return false;
+    }
 
-	@Override
-	protected boolean onBlockBreak(final Block block, final User player, final String username, final IEssentials ess) throws SignException, MaxMoneyException
-	{
-		final SignProtectionState state = isBlockProtected(block, player, username, false);
+    @Override
+    protected boolean onBlockBreak(final Block block, final User player, final String username, final IEssentials ess) throws SignException, MaxMoneyException {
+        final SignProtectionState state = isBlockProtected(block, player, username, false);
 
-		if (state == SignProtectionState.OWNER || state == SignProtectionState.NOSIGN)
-		{
-			checkIfSignsAreBroken(block, player, username, ess);
-			return true;
-		}
+        if (state == SignProtectionState.OWNER || state == SignProtectionState.NOSIGN) {
+            checkIfSignsAreBroken(block, player, username, ess);
+            return true;
+        }
 
-		if ((state == SignProtectionState.ALLOWED || state == SignProtectionState.NOT_ALLOWED)
-			&& player.isAuthorized("essentials.signs.protection.override"))
-		{
-			checkIfSignsAreBroken(block, player, username, ess);
-			return true;
-		}
+        if ((state == SignProtectionState.ALLOWED || state == SignProtectionState.NOT_ALLOWED) && player.isAuthorized("essentials.signs.protection.override")) {
+            checkIfSignsAreBroken(block, player, username, ess);
+            return true;
+        }
 
 
-		player.sendMessage(tl("noDestroyPermission", block.getType().toString().toLowerCase(Locale.ENGLISH)));
-		return false;
-	}
+        player.sendMessage(tl("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);
+    @Override
+    public boolean onBlockBreak(final Block block, final IEssentials ess) {
+        final SignProtectionState state = isBlockProtected(block, null, null, false);
 
-		return state == SignProtectionState.NOSIGN;
-	}
+        return state == SignProtectionState.NOSIGN;
+    }
 
-	@Override
-	public boolean onBlockExplode(final Block block, final IEssentials ess)
-	{
-		final SignProtectionState state = isBlockProtected(block, null, null, false);
+    @Override
+    public boolean onBlockExplode(final Block block, final IEssentials ess) {
+        final SignProtectionState state = isBlockProtected(block, null, null, false);
 
-		return state == SignProtectionState.NOSIGN;
-	}
+        return state == SignProtectionState.NOSIGN;
+    }
 
-	@Override
-	public boolean onBlockBurn(final Block block, final IEssentials ess)
-	{
-		final SignProtectionState state = isBlockProtected(block, null, null, false);
+    @Override
+    public boolean onBlockBurn(final Block block, final IEssentials ess) {
+        final SignProtectionState state = isBlockProtected(block, null, null, false);
 
-		return state == SignProtectionState.NOSIGN;
-	}
+        return state == SignProtectionState.NOSIGN;
+    }
 
-	@Override
-	public boolean onBlockIgnite(final Block block, final IEssentials ess)
-	{
-		final SignProtectionState state = isBlockProtected(block, null, null, false);
+    @Override
+    public boolean onBlockIgnite(final Block block, final IEssentials ess) {
+        final SignProtectionState state = isBlockProtected(block, null, null, false);
 
-		return state == SignProtectionState.NOSIGN;
-	}
+        return state == SignProtectionState.NOSIGN;
+    }
 
-	@Override
-	public boolean onBlockPush(final Block block, final IEssentials ess)
-	{
-		final SignProtectionState state = isBlockProtected(block, null, null, false);
+    @Override
+    public boolean onBlockPush(final Block block, final IEssentials ess) {
+        final SignProtectionState state = isBlockProtected(block, null, null, false);
 
-		return state == SignProtectionState.NOSIGN;
-	}
+        return state == SignProtectionState.NOSIGN;
+    }
 
-	public enum SignProtectionState
-	{
-		NOT_ALLOWED, ALLOWED, NOSIGN, OWNER
-	}
+    public enum SignProtectionState {
+        NOT_ALLOWED, ALLOWED, NOSIGN, OWNER
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/signs/SignRepair.java b/Essentials/src/com/earth2me/essentials/signs/SignRepair.java
index 91c4a4314..3b028db27 100644
--- a/Essentials/src/com/earth2me/essentials/signs/SignRepair.java
+++ b/Essentials/src/com/earth2me/essentials/signs/SignRepair.java
@@ -1,70 +1,56 @@
 package com.earth2me.essentials.signs;
 
 import com.earth2me.essentials.ChargeException;
-import static com.earth2me.essentials.I18n.tl;
 import com.earth2me.essentials.Trade;
 import com.earth2me.essentials.User;
 import com.earth2me.essentials.commands.Commandrepair;
 import com.earth2me.essentials.commands.NotEnoughArgumentsException;
 import net.ess3.api.IEssentials;
 
+import static com.earth2me.essentials.I18n.tl;
 
-public class SignRepair extends EssentialsSign
-{
-	public SignRepair()
-	{
-		super("Repair");
-	}
 
-	@Override
-	protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException
-	{
-		final String repairTarget = sign.getLine(1);
-		if (repairTarget.isEmpty())
-		{
-			sign.setLine(1, "Hand");
-		}
-		else if (!repairTarget.equalsIgnoreCase("all") && !repairTarget.equalsIgnoreCase("hand"))
-		{
-			sign.setLine(1, "§c");
-			throw new SignException(tl("invalidSignLine", 2));
-		}
-		validateTrade(sign, 2, ess);
-		return true;
-	}
+public class SignRepair extends EssentialsSign {
+    public SignRepair() {
+        super("Repair");
+    }
 
-	@Override
-	protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException
-	{
-		final Trade charge = getTrade(sign, 2, ess);
-		charge.isAffordableFor(player);
+    @Override
+    protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException {
+        final String repairTarget = sign.getLine(1);
+        if (repairTarget.isEmpty()) {
+            sign.setLine(1, "Hand");
+        } else if (!repairTarget.equalsIgnoreCase("all") && !repairTarget.equalsIgnoreCase("hand")) {
+            sign.setLine(1, "§c");
+            throw new SignException(tl("invalidSignLine", 2));
+        }
+        validateTrade(sign, 2, ess);
+        return true;
+    }
 
-		Commandrepair command = new Commandrepair();
-		command.setEssentials(ess);
+    @Override
+    protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException {
+        final Trade charge = getTrade(sign, 2, ess);
+        charge.isAffordableFor(player);
 
-		try
-		{
-			if (sign.getLine(1).equalsIgnoreCase("hand"))
-			{
-				command.repairHand(player);
-			}
-			else if (sign.getLine(1).equalsIgnoreCase("all"))
-			{
-				command.repairAll(player);
-			}
-			else
-			{
-				throw new NotEnoughArgumentsException();
-			}
+        Commandrepair command = new Commandrepair();
+        command.setEssentials(ess);
 
-		}
-		catch (Exception ex)
-		{
-			throw new SignException(ex.getMessage(), ex);
-		}
+        try {
+            if (sign.getLine(1).equalsIgnoreCase("hand")) {
+                command.repairHand(player);
+            } else if (sign.getLine(1).equalsIgnoreCase("all")) {
+                command.repairAll(player);
+            } else {
+                throw new NotEnoughArgumentsException();
+            }
 
-		charge.charge(player);
-		Trade.log("Sign", "Repair", "Interact", username, null, username, charge, sign.getBlock().getLocation(), ess);
-		return true;
-	}
+        } catch (Exception ex) {
+            throw new SignException(ex.getMessage(), ex);
+        }
+
+        charge.charge(player);
+        Trade.log("Sign", "Repair", "Interact", username, null, username, charge, sign.getBlock().getLocation(), ess);
+        return true;
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/signs/SignSell.java b/Essentials/src/com/earth2me/essentials/signs/SignSell.java
index 45fee196e..55a17870f 100644
--- a/Essentials/src/com/earth2me/essentials/signs/SignSell.java
+++ b/Essentials/src/com/earth2me/essentials/signs/SignSell.java
@@ -8,30 +8,26 @@ import net.ess3.api.IEssentials;
 import net.ess3.api.MaxMoneyException;
 
 
-public class SignSell extends EssentialsSign
-{
-	public SignSell()
-	{
-		super("Sell");
-	}
+public class SignSell extends EssentialsSign {
+    public SignSell() {
+        super("Sell");
+    }
 
-	@Override
-	protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException
-	{
-		validateTrade(sign, 1, 2, player, ess);
-		validateTrade(sign, 3, ess);
-		return true;
-	}
+    @Override
+    protected boolean onSignCreate(final ISign sign, final User 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 User player, final String username, final IEssentials ess) throws SignException, ChargeException, MaxMoneyException
-	{
-		final Trade charge = getTrade(sign, 1, 2, player, ess);
-		final Trade money = getTrade(sign, 3, ess);
-		charge.isAffordableFor(player);
-		money.pay(player, OverflowType.DROP);
-		charge.charge(player);
-		Trade.log("Sign", "Sell", "Interact", username, charge, username, money, sign.getBlock().getLocation(), ess);
-		return true;
-	}
+    @Override
+    protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException, MaxMoneyException {
+        final Trade charge = getTrade(sign, 1, 2, player, ess);
+        final Trade money = getTrade(sign, 3, ess);
+        charge.isAffordableFor(player);
+        money.pay(player, OverflowType.DROP);
+        charge.charge(player);
+        Trade.log("Sign", "Sell", "Interact", username, charge, username, money, sign.getBlock().getLocation(), ess);
+        return true;
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/signs/SignSpawnmob.java b/Essentials/src/com/earth2me/essentials/signs/SignSpawnmob.java
index 4916d131b..5a7f81643 100644
--- a/Essentials/src/com/earth2me/essentials/signs/SignSpawnmob.java
+++ b/Essentials/src/com/earth2me/essentials/signs/SignSpawnmob.java
@@ -1,44 +1,41 @@
 package com.earth2me.essentials.signs;
 
-import com.earth2me.essentials.*;
-import java.util.List;
+import com.earth2me.essentials.ChargeException;
+import com.earth2me.essentials.SpawnMob;
+import com.earth2me.essentials.Trade;
+import com.earth2me.essentials.User;
 import net.ess3.api.IEssentials;
 
+import java.util.List;
 
-public class SignSpawnmob extends EssentialsSign
-{
-	public SignSpawnmob()
-	{
-		super("Spawnmob");
-	}
 
-	@Override
-	protected boolean onSignCreate(ISign sign, User player, String username, IEssentials ess) throws SignException, ChargeException
-	{
-		validateInteger(sign, 1);
-		validateTrade(sign, 3, ess);
-		return true;
-	}
+public class SignSpawnmob extends EssentialsSign {
+    public SignSpawnmob() {
+        super("Spawnmob");
+    }
 
-	@Override
-	protected boolean onSignInteract(ISign sign, User player, String username, IEssentials ess) throws SignException, ChargeException
-	{
-		final Trade charge = getTrade(sign, 3, ess);
-		charge.isAffordableFor(player);
+    @Override
+    protected boolean onSignCreate(ISign sign, User player, String username, IEssentials ess) throws SignException, ChargeException {
+        validateInteger(sign, 1);
+        validateTrade(sign, 3, ess);
+        return true;
+    }
 
-		try
-		{
-			List mobParts = SpawnMob.mobParts(sign.getLine(2));
-			List mobData = SpawnMob.mobData(sign.getLine(2));
-			SpawnMob.spawnmob(ess, ess.getServer(), player.getSource(), player, mobParts, mobData, Integer.parseInt(sign.getLine(1)));
-		}
-		catch (Exception ex)
-		{
-			throw new SignException(ex.getMessage(), ex);
-		}
+    @Override
+    protected boolean onSignInteract(ISign sign, User player, String username, IEssentials ess) throws SignException, ChargeException {
+        final Trade charge = getTrade(sign, 3, ess);
+        charge.isAffordableFor(player);
 
-		charge.charge(player);
-		Trade.log("Sign", "Spawnmob", "Interact", username, null, username, charge, sign.getBlock().getLocation(), ess);
-		return true;
-	}
+        try {
+            List mobParts = SpawnMob.mobParts(sign.getLine(2));
+            List mobData = SpawnMob.mobData(sign.getLine(2));
+            SpawnMob.spawnmob(ess, ess.getServer(), player.getSource(), player, mobParts, mobData, Integer.parseInt(sign.getLine(1)));
+        } catch (Exception ex) {
+            throw new SignException(ex.getMessage(), ex);
+        }
+
+        charge.charge(player);
+        Trade.log("Sign", "Spawnmob", "Interact", username, null, username, charge, sign.getBlock().getLocation(), ess);
+        return true;
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/signs/SignTime.java b/Essentials/src/com/earth2me/essentials/signs/SignTime.java
index 2f6390f7a..9cdcb9d3c 100644
--- a/Essentials/src/com/earth2me/essentials/signs/SignTime.java
+++ b/Essentials/src/com/earth2me/essentials/signs/SignTime.java
@@ -1,59 +1,52 @@
 package com.earth2me.essentials.signs;
 
 import com.earth2me.essentials.ChargeException;
-import static com.earth2me.essentials.I18n.tl;
 import com.earth2me.essentials.Trade;
 import com.earth2me.essentials.User;
 import net.ess3.api.IEssentials;
 
+import static com.earth2me.essentials.I18n.tl;
 
-public class SignTime extends EssentialsSign
-{
-	public SignTime()
-	{
-		super("Time");
-	}
 
-	@Override
-	protected boolean onSignCreate(final ISign sign, final User 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(tl("onlyDayNight"));
-	}
+public class SignTime extends EssentialsSign {
+    public SignTime() {
+        super("Time");
+    }
 
-	@Override
-	protected boolean onSignInteract(final ISign sign, final User 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);
-			Trade.log("Sign", "TimeDay", "Interact", username, null, username, charge, sign.getBlock().getLocation(), ess);
-			return true;
-		}
-		if ("§2Night".equalsIgnoreCase(timeString))
-		{
-			player.getWorld().setTime(time + 37700);
-			charge.charge(player);
-			Trade.log("Sign", "TimeNight", "Interact", username, null, username, charge, sign.getBlock().getLocation(), ess);
-			return true;
-		}
-		throw new SignException(tl("onlyDayNight"));
-	}
+    @Override
+    protected boolean onSignCreate(final ISign sign, final User 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(tl("onlyDayNight"));
+    }
+
+    @Override
+    protected boolean onSignInteract(final ISign sign, final User 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);
+            Trade.log("Sign", "TimeDay", "Interact", username, null, username, charge, sign.getBlock().getLocation(), ess);
+            return true;
+        }
+        if ("§2Night".equalsIgnoreCase(timeString)) {
+            player.getWorld().setTime(time + 37700);
+            charge.charge(player);
+            Trade.log("Sign", "TimeNight", "Interact", username, null, username, charge, sign.getBlock().getLocation(), ess);
+            return true;
+        }
+        throw new SignException(tl("onlyDayNight"));
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/signs/SignTrade.java b/Essentials/src/com/earth2me/essentials/signs/SignTrade.java
index 59910cb4d..4b8015b5d 100644
--- a/Essentials/src/com/earth2me/essentials/signs/SignTrade.java
+++ b/Essentials/src/com/earth2me/essentials/signs/SignTrade.java
@@ -1,442 +1,357 @@
 package com.earth2me.essentials.signs;
 
-import com.earth2me.essentials.*;
-import static com.earth2me.essentials.I18n.tl;
+import com.earth2me.essentials.ChargeException;
+import com.earth2me.essentials.Trade;
 import com.earth2me.essentials.Trade.OverflowType;
 import com.earth2me.essentials.Trade.TradeType;
+import com.earth2me.essentials.User;
 import com.earth2me.essentials.utils.NumberUtil;
-import java.math.BigDecimal;
-import java.util.Map;
 import net.ess3.api.IEssentials;
 import net.ess3.api.MaxMoneyException;
 import org.bukkit.Material;
 import org.bukkit.inventory.ItemStack;
 
+import java.math.BigDecimal;
+import java.util.Map;
+
+import static com.earth2me.essentials.I18n.tl;
+
 //TODO: TL exceptions
-public class SignTrade extends EssentialsSign
-{
-	public SignTrade()
-	{
-		super("Trade");
-	}
+public class SignTrade extends EssentialsSign {
+    public SignTrade() {
+        super("Trade");
+    }
 
-	@Override
-	protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException
-	{
-		validateTrade(sign, 1, false, ess);
-		validateTrade(sign, 2, true, ess);
-		final Trade trade = getTrade(sign, 2, AmountType.ROUNDED, true, ess);
-		final Trade charge = getTrade(sign, 1, AmountType.ROUNDED, false, ess);
-		if (trade.getType() == charge.getType()
-			&& (trade.getType() != TradeType.ITEM || trade.getItemStack().isSimilar(charge.getItemStack())))
-		{
-			throw new SignException("You cannot trade for the same item type.");
-		}
-		trade.isAffordableFor(player);
-		sign.setLine(3, "§8" + username);
-		trade.charge(player);
-		Trade.log("Sign", "Trade", "Create", username, trade, username, null, sign.getBlock().getLocation(), ess);
-		return true;
-	}
+    @Override
+    protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException {
+        validateTrade(sign, 1, false, ess);
+        validateTrade(sign, 2, true, ess);
+        final Trade trade = getTrade(sign, 2, AmountType.ROUNDED, true, ess);
+        final Trade charge = getTrade(sign, 1, AmountType.ROUNDED, false, ess);
+        if (trade.getType() == charge.getType() && (trade.getType() != TradeType.ITEM || trade.getItemStack().isSimilar(charge.getItemStack()))) {
+            throw new SignException("You cannot trade for the same item type.");
+        }
+        trade.isAffordableFor(player);
+        sign.setLine(3, "§8" + username);
+        trade.charge(player);
+        Trade.log("Sign", "Trade", "Create", username, trade, username, null, sign.getBlock().getLocation(), ess);
+        return true;
+    }
 
-	@Override
-	protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException, MaxMoneyException
-	{
-		if (sign.getLine(3).substring(2).equalsIgnoreCase(username))
-		{
-			final Trade store = rechargeSign(sign, ess, player);
-			Trade stored;
-			try
-			{
-				stored = getTrade(sign, 1, AmountType.TOTAL, true, ess);
-				subtractAmount(sign, 1, stored, ess);
+    @Override
+    protected boolean onSignInteract(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, ChargeException, MaxMoneyException {
+        if (sign.getLine(3).substring(2).equalsIgnoreCase(username)) {
+            final Trade store = rechargeSign(sign, ess, player);
+            Trade stored;
+            try {
+                stored = getTrade(sign, 1, AmountType.TOTAL, true, ess);
+                subtractAmount(sign, 1, stored, ess);
 
-				Map withdraw = stored.pay(player, OverflowType.RETURN);
+                Map withdraw = stored.pay(player, OverflowType.RETURN);
 
-				if (withdraw == null)
-				{
-					Trade.log("Sign", "Trade", "Withdraw", username, store, username, null, sign.getBlock().getLocation(), ess);
-				}
-				else
-				{
-					setAmount(sign, 1, BigDecimal.valueOf(withdraw.get(0).getAmount()), ess);
-					Trade.log("Sign", "Trade", "Withdraw", username, stored, username, new Trade(withdraw.get(0), ess), sign.getBlock().getLocation(), ess);
-				}
-			}
-			catch (SignException e)
-			{
-				if (store == null)
-				{
-					throw new SignException(tl("tradeSignEmptyOwner"), e);
-				}
-			}
-			Trade.log("Sign", "Trade", "Deposit", username, store, username, null, sign.getBlock().getLocation(), ess);
-		}
-		else
-		{
-			final Trade charge = getTrade(sign, 1, AmountType.COST, false, ess);
-			final Trade trade = getTrade(sign, 2, AmountType.COST, true, ess);
-			charge.isAffordableFor(player);
-			addAmount(sign, 1, charge, ess);
-			subtractAmount(sign, 2, trade, ess);
-			if (!trade.pay(player))
-			{
-				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;
-	}
+                if (withdraw == null) {
+                    Trade.log("Sign", "Trade", "Withdraw", username, store, username, null, sign.getBlock().getLocation(), ess);
+                } else {
+                    setAmount(sign, 1, BigDecimal.valueOf(withdraw.get(0).getAmount()), ess);
+                    Trade.log("Sign", "Trade", "Withdraw", username, stored, username, new Trade(withdraw.get(0), ess), sign.getBlock().getLocation(), ess);
+                }
+            } catch (SignException e) {
+                if (store == null) {
+                    throw new SignException(tl("tradeSignEmptyOwner"), e);
+                }
+            }
+            Trade.log("Sign", "Trade", "Deposit", username, store, username, null, sign.getBlock().getLocation(), ess);
+        } else {
+            final Trade charge = getTrade(sign, 1, AmountType.COST, false, ess);
+            final Trade trade = getTrade(sign, 2, AmountType.COST, true, ess);
+            charge.isAffordableFor(player);
+            addAmount(sign, 1, charge, ess);
+            subtractAmount(sign, 2, trade, ess);
+            if (!trade.pay(player)) {
+                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 User player) throws SignException, ChargeException
-	{
-		final Trade trade = getTrade(sign, 2, AmountType.COST, false, ess);
-		if (trade.getItemStack() != null && player.getBase().getItemInHand() != null
-			&& trade.getItemStack().getType() == player.getBase().getItemInHand().getType()
-			&& trade.getItemStack().getDurability() == player.getBase().getItemInHand().getDurability()
-			&& trade.getItemStack().getEnchantments().equals(player.getBase().getItemInHand().getEnchantments()))
-		{
-			int amount = player.getBase().getItemInHand().getAmount();
-			amount -= amount % trade.getItemStack().getAmount();
-			if (amount > 0)
-			{
-				final ItemStack stack = player.getBase().getItemInHand().clone();
-				stack.setAmount(amount);
-				final Trade store = new Trade(stack, ess);
-				addAmount(sign, 2, store, ess);
-				store.charge(player);
-				return store;
-			}
-		}
-		return null;
-	}
+    private Trade rechargeSign(final ISign sign, final IEssentials ess, final User player) throws SignException, ChargeException {
+        final Trade trade = getTrade(sign, 2, AmountType.COST, false, ess);
+        if (trade.getItemStack() != null && player.getBase().getItemInHand() != null && trade.getItemStack().getType() == player.getBase().getItemInHand().getType() && trade.getItemStack().getDurability() == player.getBase().getItemInHand().getDurability() && trade.getItemStack().getEnchantments().equals(player.getBase().getItemInHand().getEnchantments())) {
+            int amount = player.getBase().getItemInHand().getAmount();
+            amount -= amount % trade.getItemStack().getAmount();
+            if (amount > 0) {
+                final ItemStack stack = player.getBase().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 User player, final String username, final IEssentials ess) throws SignException, MaxMoneyException
-	{
-		final String signOwner = sign.getLine(3);
-		
-		final boolean isOwner = (signOwner.length() > 3 && signOwner.substring(2).equalsIgnoreCase(username));
-		final boolean canBreak = isOwner ? true : player.isAuthorized("essentials.signs.trade.override");
-		final boolean canCollect = isOwner ? true : player.isAuthorized("essentials.signs.trade.override.collect");
-				
-		if (canBreak)
-		{
-			try
-			{
-				final Trade stored1 = getTrade(sign, 1, AmountType.TOTAL, false, ess);
-				final Trade stored2 = getTrade(sign, 2, AmountType.TOTAL, false, ess);
-				
-				if (!canCollect)
-				{
-					Trade.log("Sign", "Trade", "Destroy", signOwner, stored2, username, stored1, sign.getBlock().getLocation(), ess);
-					return true;
-				}				
-				
-				final Map withdraw1 = stored1.pay(player, OverflowType.RETURN);
-				final Map withdraw2 = stored2.pay(player, OverflowType.RETURN);
+    @Override
+    protected boolean onSignBreak(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException, MaxMoneyException {
+        final String signOwner = sign.getLine(3);
 
-				if (withdraw1 == null && withdraw2 == null)
-				{
-					Trade.log("Sign", "Trade", "Break", signOwner, stored2, username, stored1, sign.getBlock().getLocation(), ess);
-					return true;
-				}
+        final boolean isOwner = (signOwner.length() > 3 && signOwner.substring(2).equalsIgnoreCase(username));
+        final boolean canBreak = isOwner ? true : player.isAuthorized("essentials.signs.trade.override");
+        final boolean canCollect = isOwner ? true : player.isAuthorized("essentials.signs.trade.override.collect");
 
-				setAmount(sign, 1, BigDecimal.valueOf(withdraw1 == null ? 0L : withdraw1.get(0).getAmount()), ess);
-				Trade.log("Sign", "Trade", "Withdraw", signOwner, stored1, username, withdraw1 == null ? null : new Trade(withdraw1.get(0), ess), sign.getBlock().getLocation(), ess);
+        if (canBreak) {
+            try {
+                final Trade stored1 = getTrade(sign, 1, AmountType.TOTAL, false, ess);
+                final Trade stored2 = getTrade(sign, 2, AmountType.TOTAL, false, ess);
 
-				setAmount(sign, 2, BigDecimal.valueOf(withdraw2 == null ? 0L : withdraw2.get(0).getAmount()), ess);
-				Trade.log("Sign", "Trade", "Withdraw", signOwner, stored2, username, withdraw2 == null ? null : new Trade(withdraw2.get(0), ess), sign.getBlock().getLocation(), ess);
+                if (!canCollect) {
+                    Trade.log("Sign", "Trade", "Destroy", signOwner, stored2, username, stored1, sign.getBlock().getLocation(), ess);
+                    return true;
+                }
 
-				sign.updateSign();
-			}
-			catch (SignException e)
-			{
-				if (player.isAuthorized("essentials.signs.trade.override"))
-				{
-					return true;
-				}
-				throw e;
-			}
-			return false;
-		}
-		else
-		{
-			return false;
-		}
-	}
+                final Map withdraw1 = stored1.pay(player, OverflowType.RETURN);
+                final Map withdraw2 = stored2.pay(player, OverflowType.RETURN);
 
-	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 (withdraw1 == null && withdraw2 == null) {
+                    Trade.log("Sign", "Trade", "Break", signOwner, stored2, username, stored1, sign.getBlock().getLocation(), ess);
+                    return true;
+                }
 
-		if (split.length == 1 && !amountNeeded)
-		{
-			final BigDecimal money = getMoney(split[0]);
-			if (money != null)
-			{
-				if (NumberUtil.shortCurrency(money, ess).length() * 2 > 15)
-				{
-					throw new SignException("Line can be too long!");
-				}
-				sign.setLine(index, NumberUtil.shortCurrency(money, ess) + ":0");
-				return;
-			}
-		}
+                setAmount(sign, 1, BigDecimal.valueOf(withdraw1 == null ? 0L : withdraw1.get(0).getAmount()), ess);
+                Trade.log("Sign", "Trade", "Withdraw", signOwner, stored1, username, withdraw1 == null ? null : new Trade(withdraw1.get(0), ess), sign.getBlock().getLocation(), ess);
 
-		if (split.length == 2 && amountNeeded)
-		{
-			final BigDecimal money = getMoney(split[0]);
-			BigDecimal amount = getBigDecimalPositive(split[1]);
-			if (money != null && amount != null)
-			{
-				amount = amount.subtract(amount.remainder(money));
-				if (amount.compareTo(MINTRANSACTION) < 0 || money.compareTo(MINTRANSACTION) < 0)
-				{
-					throw new SignException(tl("moreThanZero"));
-				}
-				sign.setLine(index, NumberUtil.shortCurrency(money, ess) + ":" + NumberUtil.shortCurrency(amount, ess).substring(1));
-				return;
-			}
-		}
+                setAmount(sign, 2, BigDecimal.valueOf(withdraw2 == null ? 0L : withdraw2.get(0).getAmount()), ess);
+                Trade.log("Sign", "Trade", "Withdraw", signOwner, stored2, username, withdraw2 == null ? null : new Trade(withdraw2.get(0), ess), sign.getBlock().getLocation(), ess);
 
-		if (split.length == 2 && !amountNeeded)
-		{
-			final int amount = getIntegerPositive(split[0]);
+                sign.updateSign();
+            } catch (SignException e) {
+                if (player.isAuthorized("essentials.signs.trade.override")) {
+                    return true;
+                }
+                throw e;
+            }
+            return false;
+        } else {
+            return false;
+        }
+    }
 
-			if (amount < 1)
-			{
-				throw new SignException(tl("moreThanZero"));
-			}
-			if (!(split[1].equalsIgnoreCase("exp") || split[1].equalsIgnoreCase("xp"))
-				&& getItemStack(split[1], amount, ess).getType() == Material.AIR)
-			{
-				throw new SignException(tl("moreThanZero"));
-			}
-			String newline = amount + " " + split[1] + ":0";
-			if ((newline + amount).length() > 15)
-			{
-				throw new SignException("Line can be too long!");
-			}
-			sign.setLine(index, newline);
-			return;
-		}
+    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 == 3 && amountNeeded)
-		{
-			final int stackamount = getIntegerPositive(split[0]);
-			int amount = getIntegerPositive(split[2]);
-			amount -= amount % stackamount;
-			if (amount < 1 || stackamount < 1)
-			{
-				throw new SignException(tl("moreThanZero"));
-			}
-			if (!(split[1].equalsIgnoreCase("exp") || split[1].equalsIgnoreCase("xp"))
-				&& getItemStack(split[1], stackamount, ess).getType() == Material.AIR)
-			{
-				throw new SignException(tl("moreThanZero"));
-			}
-			sign.setLine(index, stackamount + " " + split[1] + ":" + amount);
-			return;
-		}
-		throw new SignException(tl("invalidSignLine", index + 1));
-	}
+        if (split.length == 1 && !amountNeeded) {
+            final BigDecimal money = getMoney(split[0]);
+            if (money != null) {
+                if (NumberUtil.shortCurrency(money, ess).length() * 2 > 15) {
+                    throw new SignException("Line can be too long!");
+                }
+                sign.setLine(index, NumberUtil.shortCurrency(money, ess) + ":0");
+                return;
+            }
+        }
 
-	protected final Trade getTrade(final ISign sign, final int index, final AmountType amountType, 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 && amountNeeded) {
+            final BigDecimal money = getMoney(split[0]);
+            BigDecimal amount = getBigDecimalPositive(split[1]);
+            if (money != null && amount != null) {
+                amount = amount.subtract(amount.remainder(money));
+                if (amount.compareTo(MINTRANSACTION) < 0 || money.compareTo(MINTRANSACTION) < 0) {
+                    throw new SignException(tl("moreThanZero"));
+                }
+                sign.setLine(index, NumberUtil.shortCurrency(money, ess) + ":" + NumberUtil.shortCurrency(amount, ess).substring(1));
+                return;
+            }
+        }
 
-		if (split.length == 2)
-		{
-			try
-			{
-				final BigDecimal money = getMoney(split[0]);
-				final BigDecimal amount = notEmpty ? getBigDecimalPositive(split[1]) : getBigDecimal(split[1]);
-				if (money != null && amount != null)
-				{
-					return new Trade(amountType == AmountType.COST ? money : amount, ess);
-				}
-			}
-			catch (SignException e)
-			{
-				throw new SignException(tl("tradeSignEmpty"), e);
-			}
-		}
+        if (split.length == 2 && !amountNeeded) {
+            final int amount = getIntegerPositive(split[0]);
 
-		if (split.length == 3)
-		{
-			if (split[1].equalsIgnoreCase("exp") || split[1].equalsIgnoreCase("xp"))
-			{
-				final int stackamount = getIntegerPositive(split[0]);
-				int amount = getInteger(split[2]);
-				if (amountType == AmountType.ROUNDED)
-				{
-					amount -= amount % stackamount;
-				}
-				if (notEmpty && (amount < 1 || stackamount < 1))
-				{
-					throw new SignException(tl("tradeSignEmpty"));
-				}
-				return new Trade((amountType == AmountType.COST ? stackamount : amount), ess);
-			}
-			else
-			{
-				final int stackamount = getIntegerPositive(split[0]);
-				final ItemStack item = getItemStack(split[1], stackamount, ess);
-				int amount = getInteger(split[2]);
-				if (amountType == AmountType.ROUNDED)
-				{
-					amount -= amount % stackamount;
-				}
-				if (notEmpty && (amount < 1 || stackamount < 1 || item.getType() == Material.AIR || amount < stackamount))
-				{
-					throw new SignException(tl("tradeSignEmpty"));
-				}
-				item.setAmount(amountType == AmountType.COST ? stackamount : amount);
-				return new Trade(item, ess);
-			}
-		}
-		throw new SignException(tl("invalidSignLine", index + 1));
-	}
+            if (amount < 1) {
+                throw new SignException(tl("moreThanZero"));
+            }
+            if (!(split[1].equalsIgnoreCase("exp") || split[1].equalsIgnoreCase("xp")) && getItemStack(split[1], amount, ess).getType() == Material.AIR) {
+                throw new SignException(tl("moreThanZero"));
+            }
+            String newline = amount + " " + split[1] + ":0";
+            if ((newline + amount).length() > 15) {
+                throw new SignException("Line can be too long!");
+            }
+            sign.setLine(index, newline);
+            return;
+        }
 
-	protected final void subtractAmount(final ISign sign, final int index, final Trade trade, final IEssentials ess) throws SignException
-	{
-		final BigDecimal money = trade.getMoney();
-		if (money != null)
-		{
-			changeAmount(sign, index, money.negate(), ess);
-		}
-		final ItemStack item = trade.getItemStack();
-		if (item != null)
-		{
-			changeAmount(sign, index, BigDecimal.valueOf(-item.getAmount()), ess);
-		}
-		final Integer exp = trade.getExperience();
-		if (exp != null)
-		{
-			changeAmount(sign, index, BigDecimal.valueOf(-exp.intValue()), ess);
-		}
-	}
+        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(tl("moreThanZero"));
+            }
+            if (!(split[1].equalsIgnoreCase("exp") || split[1].equalsIgnoreCase("xp")) && getItemStack(split[1], stackamount, ess).getType() == Material.AIR) {
+                throw new SignException(tl("moreThanZero"));
+            }
+            sign.setLine(index, stackamount + " " + split[1] + ":" + amount);
+            return;
+        }
+        throw new SignException(tl("invalidSignLine", index + 1));
+    }
 
-	protected final void addAmount(final ISign sign, final int index, final Trade trade, final IEssentials ess) throws SignException
-	{
-		final BigDecimal money = trade.getMoney();
-		if (money != null)
-		{
-			changeAmount(sign, index, money, ess);
-		}
-		final ItemStack item = trade.getItemStack();
-		if (item != null)
-		{
-			changeAmount(sign, index, BigDecimal.valueOf(item.getAmount()), ess);
-		}
-		final Integer exp = trade.getExperience();
-		if (exp != null)
-		{
-			changeAmount(sign, index, BigDecimal.valueOf(exp.intValue()), ess);
-		}
-	}
+    protected final Trade getTrade(final ISign sign, final int index, final AmountType amountType, 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("[ :]+");
 
-	//TODO: Translate these exceptions.
-	private void changeAmount(final ISign sign, final int index, final BigDecimal 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) {
+            try {
+                final BigDecimal money = getMoney(split[0]);
+                final BigDecimal amount = notEmpty ? getBigDecimalPositive(split[1]) : getBigDecimal(split[1]);
+                if (money != null && amount != null) {
+                    return new Trade(amountType == AmountType.COST ? money : amount, ess);
+                }
+            } catch (SignException e) {
+                throw new SignException(tl("tradeSignEmpty"), e);
+            }
+        }
 
-		if (split.length == 2)
-		{
-			final BigDecimal amount = getBigDecimal(split[1]).add(value);
-			setAmount(sign, index, amount, ess);
-			return;
-		}
-		if (split.length == 3)
-		{
-			final BigDecimal amount = getBigDecimal(split[2]).add(value);
-			setAmount(sign, index, amount, ess);
-			return;
-		}
-		throw new SignException(tl("invalidSignLine", index + 1));
-	}
+        if (split.length == 3) {
+            if (split[1].equalsIgnoreCase("exp") || split[1].equalsIgnoreCase("xp")) {
+                final int stackamount = getIntegerPositive(split[0]);
+                int amount = getInteger(split[2]);
+                if (amountType == AmountType.ROUNDED) {
+                    amount -= amount % stackamount;
+                }
+                if (notEmpty && (amount < 1 || stackamount < 1)) {
+                    throw new SignException(tl("tradeSignEmpty"));
+                }
+                return new Trade((amountType == AmountType.COST ? stackamount : amount), ess);
+            } else {
+                final int stackamount = getIntegerPositive(split[0]);
+                final ItemStack item = getItemStack(split[1], stackamount, ess);
+                int amount = getInteger(split[2]);
+                if (amountType == AmountType.ROUNDED) {
+                    amount -= amount % stackamount;
+                }
+                if (notEmpty && (amount < 1 || stackamount < 1 || item.getType() == Material.AIR || amount < stackamount)) {
+                    throw new SignException(tl("tradeSignEmpty"));
+                }
+                item.setAmount(amountType == AmountType.COST ? stackamount : amount);
+                return new Trade(item, ess);
+            }
+        }
+        throw new SignException(tl("invalidSignLine", index + 1));
+    }
 
-	//TODO: Translate these exceptions.
-	private void setAmount(final ISign sign, final int index, final BigDecimal value, final IEssentials ess) throws SignException
-	{
+    protected final void subtractAmount(final ISign sign, final int index, final Trade trade, final IEssentials ess) throws SignException {
+        final BigDecimal money = trade.getMoney();
+        if (money != null) {
+            changeAmount(sign, index, money.negate(), ess);
+        }
+        final ItemStack item = trade.getItemStack();
+        if (item != null) {
+            changeAmount(sign, index, BigDecimal.valueOf(-item.getAmount()), ess);
+        }
+        final Integer exp = trade.getExperience();
+        if (exp != null) {
+            changeAmount(sign, index, BigDecimal.valueOf(-exp.intValue()), ess);
+        }
+    }
 
-		final String line = sign.getLine(index).trim();
-		if (line.isEmpty())
-		{
-			throw new SignException("Empty line");
-		}
-		final String[] split = line.split("[ :]+");
+    protected final void addAmount(final ISign sign, final int index, final Trade trade, final IEssentials ess) throws SignException {
+        final BigDecimal money = trade.getMoney();
+        if (money != null) {
+            changeAmount(sign, index, money, ess);
+        }
+        final ItemStack item = trade.getItemStack();
+        if (item != null) {
+            changeAmount(sign, index, BigDecimal.valueOf(item.getAmount()), ess);
+        }
+        final Integer exp = trade.getExperience();
+        if (exp != null) {
+            changeAmount(sign, index, BigDecimal.valueOf(exp.intValue()), ess);
+        }
+    }
 
-		if (split.length == 2)
-		{
-			final BigDecimal money = getMoney(split[0]);
-			final BigDecimal amount = getBigDecimal(split[1]);
-			if (money != null && amount != null)
-			{
-				final String newline = NumberUtil.shortCurrency(money, ess) + ":" + NumberUtil.shortCurrency(value, ess).substring(1);
-				if (newline.length() > 15)
-				{
-					throw new SignException("This sign is full: Line too long!");
-				}
-				sign.setLine(index, newline);
-				return;
-			}
-		}
+    //TODO: Translate these exceptions.
+    private void changeAmount(final ISign sign, final int index, final BigDecimal 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 == 3)
-		{
-			if (split[1].equalsIgnoreCase("exp") || split[1].equalsIgnoreCase("xp"))
-			{
-				final int stackamount = getIntegerPositive(split[0]);
-				final String newline = stackamount + " " + split[1] + ":" + (value.intValueExact());
-				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]);
-				getItemStack(split[1], stackamount, ess);
-				final String newline = stackamount + " " + split[1] + ":" + (value.intValueExact());
-				if (newline.length() > 15)
-				{
-					throw new SignException("This sign is full: Line too long!");
-				}
-				sign.setLine(index, newline);
-				return;
-			}
-		}
-		throw new SignException(tl("invalidSignLine", index + 1));
-	}
+        if (split.length == 2) {
+            final BigDecimal amount = getBigDecimal(split[1]).add(value);
+            setAmount(sign, index, amount, ess);
+            return;
+        }
+        if (split.length == 3) {
+            final BigDecimal amount = getBigDecimal(split[2]).add(value);
+            setAmount(sign, index, amount, ess);
+            return;
+        }
+        throw new SignException(tl("invalidSignLine", index + 1));
+    }
+
+    //TODO: Translate these exceptions.
+    private void setAmount(final ISign sign, final int index, final BigDecimal 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 BigDecimal money = getMoney(split[0]);
+            final BigDecimal amount = getBigDecimal(split[1]);
+            if (money != null && amount != null) {
+                final String newline = NumberUtil.shortCurrency(money, ess) + ":" + NumberUtil.shortCurrency(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 String newline = stackamount + " " + split[1] + ":" + (value.intValueExact());
+                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]);
+                getItemStack(split[1], stackamount, ess);
+                final String newline = stackamount + " " + split[1] + ":" + (value.intValueExact());
+                if (newline.length() > 15) {
+                    throw new SignException("This sign is full: Line too long!");
+                }
+                sign.setLine(index, newline);
+                return;
+            }
+        }
+        throw new SignException(tl("invalidSignLine", index + 1));
+    }
 
 
-	public enum AmountType
-	{
-		TOTAL,
-		ROUNDED,
-		COST
-	}
+    public enum AmountType {
+        TOTAL,
+        ROUNDED,
+        COST
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/signs/SignWarp.java b/Essentials/src/com/earth2me/essentials/signs/SignWarp.java
index 2281ec650..47af8228b 100644
--- a/Essentials/src/com/earth2me/essentials/signs/SignWarp.java
+++ b/Essentials/src/com/earth2me/essentials/signs/SignWarp.java
@@ -1,72 +1,55 @@
 package com.earth2me.essentials.signs;
 
 import com.earth2me.essentials.ChargeException;
-import static com.earth2me.essentials.I18n.tl;
 import com.earth2me.essentials.Trade;
 import com.earth2me.essentials.User;
 import net.ess3.api.IEssentials;
 import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
 
+import static com.earth2me.essentials.I18n.tl;
 
-public class SignWarp extends EssentialsSign
-{
-	public SignWarp()
-	{
-		super("Warp");
-	}
 
-	@Override
-	protected boolean onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException
-	{
-		validateTrade(sign, 3, ess);
-		final String warpName = sign.getLine(1);
+public class SignWarp extends EssentialsSign {
+    public SignWarp() {
+        super("Warp");
+    }
 
-		if (warpName.isEmpty())
-		{
-			sign.setLine(1, "§c");
-			throw new SignException(tl("invalidSignLine", 1));
-		}
-		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 onSignCreate(final ISign sign, final User player, final String username, final IEssentials ess) throws SignException {
+        validateTrade(sign, 3, ess);
+        final String warpName = sign.getLine(1);
 
-	@Override
-	protected boolean onSignInteract(final ISign sign, final User 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)
-				 || player.inGroup(group)))
-			|| (group.isEmpty() && (!ess.getSettings().getPerWarpPermission() || player.isAuthorized("essentials.warps." + warpName))))
-		{
-			final Trade charge = getTrade(sign, 3, ess);
-			try
-			{
-				player.getTeleport().warp(player, warpName, charge, TeleportCause.PLUGIN);
-				Trade.log("Sign", "Warp", "Interact", username, null, username, charge, sign.getBlock().getLocation(), ess);
-			}
-			catch (Exception ex)
-			{
-				throw new SignException(ex.getMessage(), ex);
-			}
-			return true;
-		}
-		return false;
-	}
+        if (warpName.isEmpty()) {
+            sign.setLine(1, "§c");
+            throw new SignException(tl("invalidSignLine", 1));
+        } 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 User 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) || player.inGroup(group))) || (group.isEmpty() && (!ess.getSettings().getPerWarpPermission() || player.isAuthorized("essentials.warps." + warpName)))) {
+            final Trade charge = getTrade(sign, 3, ess);
+            try {
+                player.getTeleport().warp(player, warpName, charge, TeleportCause.PLUGIN);
+                Trade.log("Sign", "Warp", "Interact", username, null, username, charge, sign.getBlock().getLocation(), ess);
+            } catch (Exception ex) {
+                throw new SignException(ex.getMessage(), ex);
+            }
+            return true;
+        }
+        return false;
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/signs/SignWeather.java b/Essentials/src/com/earth2me/essentials/signs/SignWeather.java
index 910adeb32..534d14832 100644
--- a/Essentials/src/com/earth2me/essentials/signs/SignWeather.java
+++ b/Essentials/src/com/earth2me/essentials/signs/SignWeather.java
@@ -1,58 +1,51 @@
 package com.earth2me.essentials.signs;
 
 import com.earth2me.essentials.ChargeException;
-import static com.earth2me.essentials.I18n.tl;
 import com.earth2me.essentials.Trade;
 import com.earth2me.essentials.User;
 import net.ess3.api.IEssentials;
 
+import static com.earth2me.essentials.I18n.tl;
 
-public class SignWeather extends EssentialsSign
-{
-	public SignWeather()
-	{
-		super("Weather");
-	}
 
-	@Override
-	protected boolean onSignCreate(final ISign sign, final User 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;
-		}
-		sign.setLine(1, "§c");
-		throw new SignException(tl("onlySunStorm"));
-	}
+public class SignWeather extends EssentialsSign {
+    public SignWeather() {
+        super("Weather");
+    }
 
-	@Override
-	protected boolean onSignInteract(final ISign sign, final User 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);
-			Trade.log("Sign", "WeatherSun", "Interact", username, null, username, charge, sign.getBlock().getLocation(), ess);
-			return true;
-		}
-		if ("§2Storm".equalsIgnoreCase(weatherString))
-		{
-			player.getWorld().setStorm(true);
-			charge.charge(player);
-			Trade.log("Sign", "WeatherStorm", "Interact", username, null, username, charge, sign.getBlock().getLocation(), ess);
-			return true;
-		}
-		throw new SignException(tl("onlySunStorm"));
-	}
+    @Override
+    protected boolean onSignCreate(final ISign sign, final User 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;
+        }
+        sign.setLine(1, "§c");
+        throw new SignException(tl("onlySunStorm"));
+    }
+
+    @Override
+    protected boolean onSignInteract(final ISign sign, final User 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);
+            Trade.log("Sign", "WeatherSun", "Interact", username, null, username, charge, sign.getBlock().getLocation(), ess);
+            return true;
+        }
+        if ("§2Storm".equalsIgnoreCase(weatherString)) {
+            player.getWorld().setStorm(true);
+            charge.charge(player);
+            Trade.log("Sign", "WeatherStorm", "Interact", username, null, username, charge, sign.getBlock().getLocation(), ess);
+            return true;
+        }
+        throw new SignException(tl("onlySunStorm"));
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/signs/Signs.java b/Essentials/src/com/earth2me/essentials/signs/Signs.java
index 8076cb2a7..7113378be 100644
--- a/Essentials/src/com/earth2me/essentials/signs/Signs.java
+++ b/Essentials/src/com/earth2me/essentials/signs/Signs.java
@@ -1,35 +1,32 @@
 package com.earth2me.essentials.signs;
 
 //This enum is used when checking to see what signs are enabled
-public enum Signs
-{
-	BALANCE(new SignBalance()),
-	BUY(new SignBuy()),
-	DISPOSAL(new SignDisposal()),
-	ENCHANT(new SignEnchant()),
-	FREE(new SignFree()),
-	GAMEMODE(new SignGameMode()),
-	HEAL(new SignHeal()),
-	INFO(new SignInfo()),
-	KIT(new SignKit()),
-	MAIL(new SignMail()),
-	PROTECTION(new SignProtection()),
-	REPAIR(new SignRepair()),
-	SELL(new SignSell()),
-	SPAWNMOB(new SignSpawnmob()),
-	TIME(new SignTime()),
-	TRADE(new SignTrade()),
-	WARP(new SignWarp()),
-	WEATHER(new SignWeather());
-	private final EssentialsSign sign;
+public enum Signs {
+    BALANCE(new SignBalance()),
+    BUY(new SignBuy()),
+    DISPOSAL(new SignDisposal()),
+    ENCHANT(new SignEnchant()),
+    FREE(new SignFree()),
+    GAMEMODE(new SignGameMode()),
+    HEAL(new SignHeal()),
+    INFO(new SignInfo()),
+    KIT(new SignKit()),
+    MAIL(new SignMail()),
+    PROTECTION(new SignProtection()),
+    REPAIR(new SignRepair()),
+    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;
-	}
+    private Signs(final EssentialsSign sign) {
+        this.sign = sign;
+    }
 
-	public EssentialsSign getSign()
-	{
-		return sign;
-	}
+    public EssentialsSign getSign() {
+        return sign;
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileReader.java b/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileReader.java
index 752a48289..f7dd7a09e 100644
--- a/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileReader.java
+++ b/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileReader.java
@@ -1,71 +1,57 @@
 package com.earth2me.essentials.storage;
 
+import net.ess3.api.IEssentials;
+import org.bukkit.Bukkit;
+
 import java.io.File;
 import java.io.FileNotFoundException;
 import java.io.FileReader;
 import java.io.IOException;
 import java.util.logging.Level;
-import net.ess3.api.IEssentials;
-import org.bukkit.Bukkit;
 
 
-public abstract class AbstractDelayedYamlFileReader implements Runnable
-{
-	private final transient File file;
-	private final transient Class clazz;
-	protected final transient IEssentials plugin;
+public abstract class AbstractDelayedYamlFileReader implements Runnable {
+    private final transient File file;
+    private final transient Class clazz;
+    protected final transient IEssentials plugin;
 
-	public AbstractDelayedYamlFileReader(final IEssentials ess, final File file, final Class clazz)
-	{
-		this.file = file;
-		this.clazz = clazz;
-		this.plugin = ess;
-		ess.runTaskAsynchronously(this);
-	}
+    public AbstractDelayedYamlFileReader(final IEssentials ess, final File file, final Class clazz) {
+        this.file = file;
+        this.clazz = clazz;
+        this.plugin = ess;
+        ess.runTaskAsynchronously(this);
+    }
 
-	public abstract void onStart();
+    public abstract void onStart();
 
-	@Override
-	public void run()
-	{
-		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);
-				}
-			}
+    @Override
+    public void run() {
+        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();
-			if (plugin.getSettings() == null || plugin.getSettings().isDebug())
-			{
-				Bukkit.getLogger().log(Level.INFO, "File not found: " + file.toString());
-			}
-		}
-		catch (ObjectLoadException ex)
-		{
-			onException();
-			Bukkit.getLogger().log(Level.SEVERE, "File broken: " + file.toString(), ex.getCause());
-		}
-	}
+        } catch (FileNotFoundException ex) {
+            onException();
+            if (plugin.getSettings() == null || plugin.getSettings().isDebug()) {
+                Bukkit.getLogger().log(Level.INFO, "File not found: " + file.toString());
+            }
+        } catch (ObjectLoadException ex) {
+            onException();
+            Bukkit.getLogger().log(Level.SEVERE, "File broken: " + file.toString(), ex.getCause());
+        }
+    }
 
-	public abstract void onSuccess(T object);
+    public abstract void onSuccess(T object);
 
-	public abstract void onException();
+    public abstract void onException();
 }
diff --git a/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileWriter.java b/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileWriter.java
index cf1c1c90e..26cbb3e59 100644
--- a/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileWriter.java
+++ b/Essentials/src/com/earth2me/essentials/storage/AbstractDelayedYamlFileWriter.java
@@ -1,54 +1,45 @@
 package com.earth2me.essentials.storage;
 
+import net.ess3.api.IEssentials;
+import org.bukkit.Bukkit;
+
 import java.io.File;
 import java.io.FileNotFoundException;
 import java.io.PrintWriter;
 import java.util.logging.Level;
-import net.ess3.api.IEssentials;
-import org.bukkit.Bukkit;
 
 
-public abstract class AbstractDelayedYamlFileWriter implements Runnable
-{
-	private final transient File file;
+public abstract class AbstractDelayedYamlFileWriter implements Runnable {
+    private final transient File file;
 
-	public AbstractDelayedYamlFileWriter(IEssentials ess, File file)
-	{
-		this.file = file;
-		ess.runTaskAsynchronously(this);
-	}
+    public AbstractDelayedYamlFileWriter(IEssentials ess, File file) {
+        this.file = file;
+        ess.runTaskAsynchronously(this);
+    }
 
-	public abstract StorageObject getObject();
+    public abstract StorageObject getObject();
 
-	@Override
-	public void run()
-	{
-		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();
-			}
-		}
+    @Override
+    public void run() {
+        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();
+            }
+        }
 
-	}
+    }
 
-	public abstract void onFinish();
+    public abstract void onFinish();
 }
diff --git a/Essentials/src/com/earth2me/essentials/storage/AsyncStorageObjectHolder.java b/Essentials/src/com/earth2me/essentials/storage/AsyncStorageObjectHolder.java
index 5282587e7..5817ab5ff 100644
--- a/Essentials/src/com/earth2me/essentials/storage/AsyncStorageObjectHolder.java
+++ b/Essentials/src/com/earth2me/essentials/storage/AsyncStorageObjectHolder.java
@@ -1,167 +1,135 @@
 package com.earth2me.essentials.storage;
 
 import com.earth2me.essentials.IConf;
-import java.io.File;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-import java.util.logging.Level;
 import net.ess3.api.IEssentials;
 import net.ess3.api.IReload;
 import org.bukkit.Bukkit;
 
-
-public abstract class AsyncStorageObjectHolder implements IConf, IStorageObjectHolder, IReload
-{
-	private transient T data;
-	private final transient ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
-	private final transient Class clazz;
-	protected final transient IEssentials ess;
-
-	public AsyncStorageObjectHolder(final IEssentials ess, final Class clazz)
-	{
-		this.ess = ess;
-		this.clazz = clazz;
-		try
-		{
-			this.data = clazz.newInstance();
-		}
-		catch (IllegalAccessException ex)
-		{
-			Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
-		}
-		catch (InstantiationException ex)
-		{
-			Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
-		}
-	}
-
-	@Override
-	public T getData()
-	{
-		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();
-			new StorageObjectDataWriter();
-		}
-		while (rwl.getReadHoldCount() > 0)
-		{
-			rwl.readLock().unlock();
-		}
-	}
-
-	@Override
-	public void reloadConfig()
-	{
-		new StorageObjectDataReader();
-	}
-
-	@Override
-	public void onReload()
-	{
-		new StorageObjectDataReader();
-	}
-
-	public abstract void finishRead();
-
-	public abstract void finishWrite();
-
-	public abstract File getStorageFile();
+import java.io.File;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import java.util.logging.Level;
 
 
-	private class StorageObjectDataWriter extends AbstractDelayedYamlFileWriter
-	{
-		StorageObjectDataWriter()
-		{
-			super(ess, getStorageFile());
-		}
+public abstract class AsyncStorageObjectHolder implements IConf, IStorageObjectHolder, IReload {
+    private transient T data;
+    private final transient ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
+    private final transient Class clazz;
+    protected final transient IEssentials ess;
 
-		@Override
-		public StorageObject getObject()
-		{
-			acquireReadLock();
-			return getData();
-		}
+    public AsyncStorageObjectHolder(final IEssentials ess, final Class clazz) {
+        this.ess = ess;
+        this.clazz = clazz;
+        try {
+            this.data = clazz.newInstance();
+        } catch (IllegalAccessException ex) {
+            Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
+        } catch (InstantiationException ex) {
+            Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
+        }
+    }
 
-		@Override
-		public void onFinish()
-		{
-			unlock();
-			finishWrite();
-		}
-	}
+    @Override
+    public T getData() {
+        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();
+            new StorageObjectDataWriter();
+        }
+        while (rwl.getReadHoldCount() > 0) {
+            rwl.readLock().unlock();
+        }
+    }
+
+    @Override
+    public void reloadConfig() {
+        new StorageObjectDataReader();
+    }
+
+    @Override
+    public void onReload() {
+        new StorageObjectDataReader();
+    }
+
+    public abstract void finishRead();
+
+    public abstract void finishWrite();
+
+    public abstract File getStorageFile();
 
 
-	private class StorageObjectDataReader extends AbstractDelayedYamlFileReader
-	{
-		StorageObjectDataReader()
-		{
-			super(ess, getStorageFile(), clazz);
-		}
+    private class StorageObjectDataWriter extends AbstractDelayedYamlFileWriter {
+        StorageObjectDataWriter() {
+            super(ess, getStorageFile());
+        }
 
-		@Override
-		public void onStart()
-		{
-			rwl.writeLock().lock();
-		}
+        @Override
+        public StorageObject getObject() {
+            acquireReadLock();
+            return getData();
+        }
 
-		@Override
-		public void onSuccess(final T object)
-		{
-			if (object != null)
-			{
-				data = object;
-			}
-			rwl.writeLock().unlock();
-			finishRead();
-		}
+        @Override
+        public void onFinish() {
+            unlock();
+            finishWrite();
+        }
+    }
 
-		@Override
-		public void onException()
-		{
-			if (data == null)
-			{
-				try
-				{
-					data = clazz.newInstance();
-				}
-				catch (IllegalAccessException ex)
-				{
-					Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
-				}
-				catch (InstantiationException ex)
-				{
-					Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
-				}
-			}
-			rwl.writeLock().unlock();
-		}
-	}
+
+    private class StorageObjectDataReader extends AbstractDelayedYamlFileReader {
+        StorageObjectDataReader() {
+            super(ess, getStorageFile(), clazz);
+        }
+
+        @Override
+        public void onStart() {
+            rwl.writeLock().lock();
+        }
+
+        @Override
+        public void onSuccess(final T object) {
+            if (object != null) {
+                data = object;
+            }
+            rwl.writeLock().unlock();
+            finishRead();
+        }
+
+        @Override
+        public void onException() {
+            if (data == null) {
+                try {
+                    data = clazz.newInstance();
+                } catch (IllegalAccessException ex) {
+                    Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
+                } catch (InstantiationException ex) {
+                    Bukkit.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
+                }
+            }
+            rwl.writeLock().unlock();
+        }
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/storage/BukkitConstructor.java b/Essentials/src/com/earth2me/essentials/storage/BukkitConstructor.java
index cf0a656a6..a235ebf85 100644
--- a/Essentials/src/com/earth2me/essentials/storage/BukkitConstructor.java
+++ b/Essentials/src/com/earth2me/essentials/storage/BukkitConstructor.java
@@ -1,10 +1,6 @@
 package com.earth2me.essentials.storage;
 
 import com.earth2me.essentials.utils.NumberUtil;
-import java.lang.reflect.Field;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
 import org.bukkit.Bukkit;
 import org.bukkit.Location;
 import org.bukkit.Material;
@@ -20,387 +16,302 @@ import org.yaml.snakeyaml.error.YAMLException;
 import org.yaml.snakeyaml.introspector.Property;
 import org.yaml.snakeyaml.nodes.*;
 
-
-public class BukkitConstructor extends CustomClassLoaderConstructor
-{
-	private final transient Plugin plugin;
-
-	public BukkitConstructor(final Class clazz, final Plugin plugin)
-	{
-		super(clazz, plugin.getClass().getClassLoader());
-		this.plugin = plugin;
-		yamlClassConstructors.put(NodeId.scalar, new ConstructBukkitScalar());
-		yamlClassConstructors.put(NodeId.mapping, new ConstructBukkitMapping());
-	}
+import java.lang.reflect.Field;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
 
 
-	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 (NumberUtil.isInt(val))
-				{
-					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 (NumberUtil.isInt(split[0]))
-				{
-					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 && NumberUtil.isInt(split[1]))
-				{
-					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 (NumberUtil.isInt(split2[0]))
-				{
-					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 && NumberUtil.isInt(split2[1]))
-				{
-					data = Short.parseShort(split2[1]);
-				}
-				int size = mat.getMaxStackSize();
-				if (split1.length > 1 && NumberUtil.isInt(split1[1]))
-				{
-					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 (NumberUtil.isInt(split3[0]))
-						{
-							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 && NumberUtil.isInt(split3[1]))
-						{
-							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 (NumberUtil.isInt(split[0]))
-				{
-					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 && NumberUtil.isInt(split[1]))
-				{
-					level = Integer.parseInt(split[1]);
-				}
-				if (level < enchant.getStartLevel())
-				{
-					level = enchant.getStartLevel();
-				}
-				if (level > enchant.getMaxLevel())
-				{
-					level = enchant.getMaxLevel();
-				}
-				return new EnchantmentLevel(enchant, level);
-			}
-			return super.construct(node);
-		}
-	}
+public class BukkitConstructor extends CustomClassLoaderConstructor {
+    private final transient Plugin plugin;
+
+    public BukkitConstructor(final Class clazz, final Plugin plugin) {
+        super(clazz, plugin.getClass().getClassLoader());
+        this.plugin = plugin;
+        yamlClassConstructors.put(NodeId.scalar, new ConstructBukkitScalar());
+        yamlClassConstructors.put(NodeId.mapping, new ConstructBukkitMapping());
+    }
 
 
-	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;
-				}
-				final World world = Bukkit.getWorld(worldName);
-				if (world == null)
-				{
-					return null;
-				}
-				return new Location(world, x, y, z, yaw, pitch);
-			}
-			return super.construct(node);
-		}
+    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 (NumberUtil.isInt(val)) {
+                    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 (NumberUtil.isInt(split[0])) {
+                    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 && NumberUtil.isInt(split[1])) {
+                    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 (NumberUtil.isInt(split2[0])) {
+                    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 && NumberUtil.isInt(split2[1])) {
+                    data = Short.parseShort(split2[1]);
+                }
+                int size = mat.getMaxStackSize();
+                if (split1.length > 1 && NumberUtil.isInt(split1[1])) {
+                    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 (NumberUtil.isInt(split3[0])) {
+                            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 && NumberUtil.isInt(split3[1])) {
+                            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 (NumberUtil.isInt(split[0])) {
+                    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 && NumberUtil.isInt(split[1])) {
+                    level = Integer.parseInt(split[1]);
+                }
+                if (level < enchant.getStartLevel()) {
+                    level = enchant.getStartLevel();
+                }
+                if (level > enchant.getMaxLevel()) {
+                    level = enchant.getMaxLevel();
+                }
+                return new EnchantmentLevel(enchant, level);
+            }
+            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;
-		}
-	}
+
+    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;
+                }
+                final World world = Bukkit.getWorld(worldName);
+                if (world == null) {
+                    return null;
+                }
+                return new Location(world, 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;
+        }
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/storage/Comment.java b/Essentials/src/com/earth2me/essentials/storage/Comment.java
index 8cb9d4d31..848c02ee8 100644
--- a/Essentials/src/com/earth2me/essentials/storage/Comment.java
+++ b/Essentials/src/com/earth2me/essentials/storage/Comment.java
@@ -3,10 +3,6 @@ package com.earth2me.essentials.storage;
 import java.lang.annotation.*;
 
 
-@Target(ElementType.FIELD)
-@Documented
-@Retention(RetentionPolicy.RUNTIME)
-public @interface Comment
-{
-	String[] value() default "";
+@Target(ElementType.FIELD) @Documented @Retention(RetentionPolicy.RUNTIME) public @interface Comment {
+    String[] value() default "";
 }
\ No newline at end of file
diff --git a/Essentials/src/com/earth2me/essentials/storage/EnchantmentLevel.java b/Essentials/src/com/earth2me/essentials/storage/EnchantmentLevel.java
index f4cacea67..a9cec87b1 100644
--- a/Essentials/src/com/earth2me/essentials/storage/EnchantmentLevel.java
+++ b/Essentials/src/com/earth2me/essentials/storage/EnchantmentLevel.java
@@ -1,80 +1,67 @@
 package com.earth2me.essentials.storage;
 
-import java.util.Map.Entry;
 import org.bukkit.enchantments.Enchantment;
 
+import java.util.Map.Entry;
 
-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 class EnchantmentLevel implements Entry {
+    private Enchantment enchantment;
+    private int level;
 
-	public Enchantment getEnchantment()
-	{
-		return enchantment;
-	}
+    public EnchantmentLevel(final Enchantment enchantment, final int level) {
+        this.enchantment = enchantment;
+        this.level = level;
+    }
 
-	public void setEnchantment(final Enchantment enchantment)
-	{
-		this.enchantment = enchantment;
-	}
+    public Enchantment getEnchantment() {
+        return enchantment;
+    }
 
-	public int getLevel()
-	{
-		return level;
-	}
+    public void setEnchantment(final Enchantment enchantment) {
+        this.enchantment = enchantment;
+    }
 
-	public void setLevel(final int level)
-	{
-		this.level = level;
-	}
+    public int getLevel() {
+        return level;
+    }
 
-	@Override
-	public Enchantment getKey()
-	{
-		return enchantment;
-	}
+    public void setLevel(final int level) {
+        this.level = level;
+    }
 
-	@Override
-	public Integer getValue()
-	{
-		return level;
-	}
+    @Override
+    public Enchantment getKey() {
+        return enchantment;
+    }
 
-	@Override
-	public Integer setValue(final Integer v)
-	{
-		int t = level;
-		level = v;
-		return t;
-	}
+    @Override
+    public Integer getValue() {
+        return level;
+    }
 
-	@Override
-	public int hashCode()
-	{
-		return enchantment.hashCode() ^ level;
-	}
+    @Override
+    public Integer setValue(final Integer v) {
+        int t = level;
+        level = v;
+        return t;
+    }
 
-	@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 enchant = (Enchantment)entry.getKey();
-				final Integer lvl = (Integer)entry.getValue();
-				return this.enchantment.equals(enchant) && this.level == lvl.intValue();
-			}
-		}
-		return false;
-	}
+    @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 enchant = (Enchantment) entry.getKey();
+                final Integer lvl = (Integer) entry.getValue();
+                return this.enchantment.equals(enchant) && this.level == lvl.intValue();
+            }
+        }
+        return false;
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/storage/IStorageObjectHolder.java b/Essentials/src/com/earth2me/essentials/storage/IStorageObjectHolder.java
index 4e860bd8c..586b3ecd2 100644
--- a/Essentials/src/com/earth2me/essentials/storage/IStorageObjectHolder.java
+++ b/Essentials/src/com/earth2me/essentials/storage/IStorageObjectHolder.java
@@ -1,15 +1,14 @@
 package com.earth2me.essentials.storage;
 
 
-public interface IStorageObjectHolder
-{
-	T getData();
+public interface IStorageObjectHolder {
+    T getData();
 
-	void acquireReadLock();
+    void acquireReadLock();
 
-	void acquireWriteLock();
+    void acquireWriteLock();
 
-	void close();
+    void close();
 
-	void unlock();
+    void unlock();
 }
diff --git a/Essentials/src/com/earth2me/essentials/storage/IStorageReader.java b/Essentials/src/com/earth2me/essentials/storage/IStorageReader.java
index d59adafe0..03103ae5d 100644
--- a/Essentials/src/com/earth2me/essentials/storage/IStorageReader.java
+++ b/Essentials/src/com/earth2me/essentials/storage/IStorageReader.java
@@ -1,7 +1,6 @@
 package com.earth2me.essentials.storage;
 
 
-public interface IStorageReader
-{
-	  T load(final Class clazz) throws ObjectLoadException;
+public interface IStorageReader {
+     T load(final Class clazz) throws ObjectLoadException;
 }
diff --git a/Essentials/src/com/earth2me/essentials/storage/IStorageWriter.java b/Essentials/src/com/earth2me/essentials/storage/IStorageWriter.java
index 5b8498869..f6a03bdde 100644
--- a/Essentials/src/com/earth2me/essentials/storage/IStorageWriter.java
+++ b/Essentials/src/com/earth2me/essentials/storage/IStorageWriter.java
@@ -1,7 +1,6 @@
 package com.earth2me.essentials.storage;
 
 
-public interface IStorageWriter
-{
-	void save(final StorageObject object);
+public interface IStorageWriter {
+    void save(final StorageObject object);
 }
diff --git a/Essentials/src/com/earth2me/essentials/storage/ListType.java b/Essentials/src/com/earth2me/essentials/storage/ListType.java
index 9bf6e2e64..acedaec2e 100644
--- a/Essentials/src/com/earth2me/essentials/storage/ListType.java
+++ b/Essentials/src/com/earth2me/essentials/storage/ListType.java
@@ -6,9 +6,6 @@ import java.lang.annotation.RetentionPolicy;
 import java.lang.annotation.Target;
 
 
-@Target(ElementType.FIELD)
-@Retention(RetentionPolicy.RUNTIME)
-public @interface ListType
-{
-	Class value() default String.class;
+@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface ListType {
+    Class value() default String.class;
 }
diff --git a/Essentials/src/com/earth2me/essentials/storage/MapKeyType.java b/Essentials/src/com/earth2me/essentials/storage/MapKeyType.java
index aa162e51c..37b6e12ca 100644
--- a/Essentials/src/com/earth2me/essentials/storage/MapKeyType.java
+++ b/Essentials/src/com/earth2me/essentials/storage/MapKeyType.java
@@ -6,9 +6,6 @@ import java.lang.annotation.RetentionPolicy;
 import java.lang.annotation.Target;
 
 
-@Target(ElementType.FIELD)
-@Retention(RetentionPolicy.RUNTIME)
-public @interface MapKeyType
-{
-	Class value() default String.class;
+@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface MapKeyType {
+    Class value() default String.class;
 }
\ No newline at end of file
diff --git a/Essentials/src/com/earth2me/essentials/storage/MapValueType.java b/Essentials/src/com/earth2me/essentials/storage/MapValueType.java
index 1b5fff978..69ec9e366 100644
--- a/Essentials/src/com/earth2me/essentials/storage/MapValueType.java
+++ b/Essentials/src/com/earth2me/essentials/storage/MapValueType.java
@@ -6,9 +6,6 @@ import java.lang.annotation.RetentionPolicy;
 import java.lang.annotation.Target;
 
 
-@Target(ElementType.FIELD)
-@Retention(RetentionPolicy.RUNTIME)
-public @interface MapValueType
-{
-	Class value() default String.class;
+@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface MapValueType {
+    Class value() default String.class;
 }
\ No newline at end of file
diff --git a/Essentials/src/com/earth2me/essentials/storage/ObjectLoadException.java b/Essentials/src/com/earth2me/essentials/storage/ObjectLoadException.java
index 8b804abc3..b14a1c6b5 100644
--- a/Essentials/src/com/earth2me/essentials/storage/ObjectLoadException.java
+++ b/Essentials/src/com/earth2me/essentials/storage/ObjectLoadException.java
@@ -1,10 +1,8 @@
 package com.earth2me.essentials.storage;
 
 
-public class ObjectLoadException extends Exception
-{
-	public ObjectLoadException(Throwable thrwbl)
-	{
-		super(thrwbl);
-	}
+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
index 0c66fefcf..d980c337b 100644
--- a/Essentials/src/com/earth2me/essentials/storage/StorageObject.java
+++ b/Essentials/src/com/earth2me/essentials/storage/StorageObject.java
@@ -1,6 +1,5 @@
 package com.earth2me.essentials.storage;
 
 
-public interface StorageObject
-{
+public interface StorageObject {
 }
diff --git a/Essentials/src/com/earth2me/essentials/storage/YamlStorageReader.java b/Essentials/src/com/earth2me/essentials/storage/YamlStorageReader.java
index 6f921ec10..03a0fdb9f 100644
--- a/Essentials/src/com/earth2me/essentials/storage/YamlStorageReader.java
+++ b/Essentials/src/com/earth2me/essentials/storage/YamlStorageReader.java
@@ -1,123 +1,96 @@
 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;
 
+import java.io.Reader;
+import java.lang.reflect.Field;
+import java.util.*;
+import java.util.concurrent.locks.ReentrantLock;
 
-public class YamlStorageReader implements IStorageReader
-{
-	private transient static final Map PREPARED_YAMLS = Collections.synchronizedMap(new HashMap());
-	private transient static final Map LOCKS = new HashMap();
-	private transient final Reader reader;
-	private transient final Plugin plugin;
 
-	public YamlStorageReader(final Reader reader, final Plugin plugin)
-	{
-		this.reader = reader;
-		this.plugin = plugin;
-	}
+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;
 
-	@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 (IllegalAccessException ex)
-		{
-			throw new ObjectLoadException(ex);
-		}
-		catch (InstantiationException ex)
-		{
-			throw new ObjectLoadException(ex);
-		}
-		finally
-		{
-			lock.unlock();
-		}
-	}
+    public YamlStorageReader(final Reader reader, final Plugin plugin) {
+        this.reader = reader;
+        this.plugin = plugin;
+    }
 
-	private Constructor prepareConstructor(final Class clazz)
-	{
-		final Constructor constructor = new BukkitConstructor(clazz, plugin);
-		final Set classes = new HashSet();
+    @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 (IllegalAccessException ex) {
+            throw new ObjectLoadException(ex);
+        } catch (InstantiationException ex) {
+            throw new ObjectLoadException(ex);
+        } finally {
+            lock.unlock();
+        }
+    }
 
-		prepareConstructor(constructor, classes, clazz);
-		return constructor;
-	}
+    private Constructor prepareConstructor(final Class clazz) {
+        final Constructor constructor = new BukkitConstructor(clazz, plugin);
+        final Set classes = new HashSet();
 
-	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);
-	}
+        prepareConstructor(constructor, classes, clazz);
+        return constructor;
+    }
 
-	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 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 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());
-			}
-		}
-	}
+    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
index f08e734f8..8071e1445 100644
--- a/Essentials/src/com/earth2me/essentials/storage/YamlStorageWriter.java
+++ b/Essentials/src/com/earth2me/essentials/storage/YamlStorageWriter.java
@@ -1,5 +1,12 @@
 package com.earth2me.essentials.storage;
 
+import org.bukkit.Location;
+import org.bukkit.Material;
+import org.bukkit.enchantments.Enchantment;
+import org.bukkit.inventory.ItemStack;
+import org.bukkit.material.MaterialData;
+import org.yaml.snakeyaml.Yaml;
+
 import java.io.PrintWriter;
 import java.lang.reflect.Field;
 import java.lang.reflect.Modifier;
@@ -11,330 +18,240 @@ import java.util.Map.Entry;
 import java.util.logging.Level;
 import java.util.logging.Logger;
 import java.util.regex.Pattern;
-import org.bukkit.Location;
-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 static final Yaml YAML = new Yaml();
-	private transient final PrintWriter writer;
+public class YamlStorageWriter implements IStorageWriter {
+    private transient static final Pattern NON_WORD_PATTERN = Pattern.compile("\\W");
+    private transient static final Yaml YAML = new Yaml();
+    private transient final PrintWriter writer;
 
-	public YamlStorageWriter(final PrintWriter writer)
-	{
-		this.writer = writer;
-	}
+    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);
-		}
-	}
+    @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);
+    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();
-				}
-			}
-		}
-	}
+                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 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 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 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 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 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 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 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 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 Material)
-		{
-			writeMaterial(data);
-		}
-		else if (data instanceof MaterialData)
-		{
-			writeMaterialData(data);
-		}
-		else if (data instanceof EnchantmentLevel)
-		{
-			writeEnchantmentLevel(data);
-		}
-		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 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 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 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 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 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.getWorld().getName());
-		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());
-	}
+    private void writeLocation(final Location entry, final int depth) {
+        writer.println();
+        writeIndention(depth);
+        writer.print("world: ");
+        writeScalar(entry.getWorld().getName());
+        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/textreader/BookInput.java b/Essentials/src/com/earth2me/essentials/textreader/BookInput.java
index 4c0ee9236..7de17209d 100644
--- a/Essentials/src/com/earth2me/essentials/textreader/BookInput.java
+++ b/Essentials/src/com/earth2me/essentials/textreader/BookInput.java
@@ -1,130 +1,105 @@
 package com.earth2me.essentials.textreader;
 
+import net.ess3.api.IEssentials;
+
 import java.io.*;
 import java.lang.ref.SoftReference;
 import java.util.*;
-import net.ess3.api.IEssentials;
 
 
-public class BookInput implements IText
-{
-	private final static HashMap> cache = new HashMap>();
-	private final transient List lines;
-	private final transient List chapters;
-	private final transient Map bookmarks;
-	private final transient long lastChange;
+public class BookInput implements IText {
+    private final static HashMap> cache = new HashMap>();
+    private final transient List lines;
+    private final transient List chapters;
+    private final transient Map bookmarks;
+    private final transient long lastChange;
 
-	public BookInput(final String filename, final boolean createFile, final IEssentials ess) throws IOException
-	{
+    public BookInput(final String filename, final boolean createFile, final IEssentials ess) throws IOException {
 
-		File file = null;
-		if (file == null || !file.exists())
-		{
-			file = new File(ess.getDataFolder(), filename + ".txt");
-		}
-		if (!file.exists())
-		{
-			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
-				{
-					output.close();
-					input.close();
-				}
-				ess.getLogger().info("File " + filename + ".txt does not exist. Creating one for you.");
-			}
-		}
-		if (!file.exists())
-		{
-			lastChange = 0;
-			lines = Collections.emptyList();
-			chapters = Collections.emptyList();
-			bookmarks = Collections.emptyMap();
-			throw new FileNotFoundException("Could not create " + filename + ".txt");
-		}
-		else
-		{
-			lastChange = file.lastModified();
-			boolean readFromfile;
-			synchronized (cache)
-			{
-				final SoftReference inputRef = cache.get(file.getName());
-				BookInput 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 Reader reader = new InputStreamReader(new FileInputStream(file), "utf-8");
-				final BufferedReader bufferedReader = new BufferedReader(reader);
-				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
-				{
-					reader.close();
-					bufferedReader.close();
-				}
-			}
-		}
-	}
+        File file = null;
+        if (file == null || !file.exists()) {
+            file = new File(ess.getDataFolder(), filename + ".txt");
+        }
+        if (!file.exists()) {
+            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 {
+                    output.close();
+                    input.close();
+                }
+                ess.getLogger().info("File " + filename + ".txt does not exist. Creating one for you.");
+            }
+        }
+        if (!file.exists()) {
+            lastChange = 0;
+            lines = Collections.emptyList();
+            chapters = Collections.emptyList();
+            bookmarks = Collections.emptyMap();
+            throw new FileNotFoundException("Could not create " + filename + ".txt");
+        } else {
+            lastChange = file.lastModified();
+            boolean readFromfile;
+            synchronized (cache) {
+                final SoftReference inputRef = cache.get(file.getName());
+                BookInput 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 Reader reader = new InputStreamReader(new FileInputStream(file), "utf-8");
+                final BufferedReader bufferedReader = new BufferedReader(reader);
+                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 {
+                    reader.close();
+                    bufferedReader.close();
+                }
+            }
+        }
+    }
 
-	@Override
-	public List getLines()
-	{
-		return lines;
-	}
+    @Override
+    public List getLines() {
+        return lines;
+    }
 
-	@Override
-	public List getChapters()
-	{
-		return chapters;
-	}
+    @Override
+    public List getChapters() {
+        return chapters;
+    }
 
-	@Override
-	public Map getBookmarks()
-	{
-		return bookmarks;
-	}
+    @Override
+    public Map getBookmarks() {
+        return bookmarks;
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/textreader/BookPager.java b/Essentials/src/com/earth2me/essentials/textreader/BookPager.java
index b84bfea79..72214fb26 100644
--- a/Essentials/src/com/earth2me/essentials/textreader/BookPager.java
+++ b/Essentials/src/com/earth2me/essentials/textreader/BookPager.java
@@ -1,181 +1,146 @@
 package com.earth2me.essentials.textreader;
 
-import static com.earth2me.essentials.I18n.tl;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
 
+import static com.earth2me.essentials.I18n.tl;
 
-public class BookPager
-{
-	private final transient IText text;
-	final double pageMax = 254;
-	final double charMax = 18.5;
-	final int lineMax = 12;
 
-	public BookPager(final IText text)
-	{
-		this.text = text;
-	}
+public class BookPager {
+    private final transient IText text;
+    final double pageMax = 254;
+    final double charMax = 18.5;
+    final int lineMax = 12;
 
-	public List getPages(final String pageStr) throws Exception
-	{
-		List lines = text.getLines();
-		List chapters = text.getChapters();
-		List pageLines = new ArrayList();
-		Map bookmarks = text.getBookmarks();
+    public BookPager(final IText text) {
+        this.text = text;
+    }
 
-		//This checks to see if we have the chapter in the index
-		if (!bookmarks.containsKey(pageStr.toLowerCase(Locale.ENGLISH)))
-		{
-			throw new Exception(tl("infoUnknownChapter"));
-		}
+    public List getPages(final String pageStr) throws Exception {
+        List lines = text.getLines();
+        List chapters = text.getChapters();
+        List pageLines = new ArrayList();
+        Map bookmarks = text.getBookmarks();
 
-		//Since we have a valid chapter, count the number of lines in the chapter
-		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;
-			}
-		}
+        //This checks to see if we have the chapter in the index
+        if (!bookmarks.containsKey(pageStr.toLowerCase(Locale.ENGLISH))) {
+            throw new Exception(tl("infoUnknownChapter"));
+        }
 
-		List pages = new ArrayList();
-		double pageLength = 0;
+        //Since we have a valid chapter, count the number of lines in the chapter
+        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;
+            }
+        }
 
-		for (int lineNo = chapterstart; lineNo < chapterend; lineNo += 1)
-		{
-			String pageLine = lines.get(lineNo);
-			String tempLine;
+        List pages = new ArrayList();
+        double pageLength = 0;
 
-			final int lineLength = pageLine.length();
-			double length = 0;
-			int pointer = 0;
-			int start = 0;
-			double weight = 1;
-			boolean forcePageEnd = false;
+        for (int lineNo = chapterstart; lineNo < chapterend; lineNo += 1) {
+            String pageLine = lines.get(lineNo);
+            String tempLine;
 
-			while (pointer < lineLength)
-			{
-				Character letter = pageLine.charAt(pointer);
+            final int lineLength = pageLine.length();
+            double length = 0;
+            int pointer = 0;
+            int start = 0;
+            double weight = 1;
+            boolean forcePageEnd = false;
 
-				if (pageLine.charAt(start) == ' ')
-				{
-					start++;
-					pointer++;
-					continue;
-				}
+            while (pointer < lineLength) {
+                Character letter = pageLine.charAt(pointer);
 
-				if (pageLength >= pageMax)
-				{
-					length = charMax;
-					pageLength = 0;
-					forcePageEnd = true;
-				}
+                if (pageLine.charAt(start) == ' ') {
+                    start++;
+                    pointer++;
+                    continue;
+                }
 
-				if (length >= charMax || (letter == '\u00a7' && length + 1 >= charMax))
-				{
-					int pos = pointer;
-					int rollback = 0;
-					while (pos > start && pageLine.charAt(pos) != ' ' && pageLine.charAt(pos) != "\n".charAt(0))
-					{
-						rollback++;
-						pos--;
-					}
-					if (pos != start)
-					{
-						pointer = pos;
-						pageLength -= rollback;
-					}
+                if (pageLength >= pageMax) {
+                    length = charMax;
+                    pageLength = 0;
+                    forcePageEnd = true;
+                }
 
-					tempLine = pageLine.substring(start, pointer);
-					pageLines.add(tempLine);
-					if (buildPage(pages, pageLines, forcePageEnd))
-					{
-						pageLength = 0;
-					}
-					forcePageEnd = false;
+                if (length >= charMax || (letter == '\u00a7' && length + 1 >= charMax)) {
+                    int pos = pointer;
+                    int rollback = 0;
+                    while (pos > start && pageLine.charAt(pos) != ' ' && pageLine.charAt(pos) != "\n".charAt(0)) {
+                        rollback++;
+                        pos--;
+                    }
+                    if (pos != start) {
+                        pointer = pos;
+                        pageLength -= rollback;
+                    }
 
-					start = pointer;
-					length = 0;
-					pageLength += 1;
-				}
+                    tempLine = pageLine.substring(start, pointer);
+                    pageLines.add(tempLine);
+                    if (buildPage(pages, pageLines, forcePageEnd)) {
+                        pageLength = 0;
+                    }
+                    forcePageEnd = false;
 
-				pageLength++;
+                    start = pointer;
+                    length = 0;
+                    pageLength += 1;
+                }
 
-				if (letter == '\u00a7' && pointer + 1 < lineLength)
-				{
-					Character nextLetter = pageLine.charAt(pointer + 1);
-					if (nextLetter == 'l' || nextLetter == 'L')
-					{
-						weight = 1.25;
-					}
-					else
-					{
-						weight = 1;
-					}
-					pointer++;
-				}
-				else if (letter == 'i' || letter == '.' || letter == ',' || letter == '!' || letter == ':' || letter == ';' || letter == '|')
-				{
-					length += (0.34 * weight);
-				}
-				else if (letter == 'l' || letter == '\'' || letter == '`')
-				{
-					length += (0.53 * weight);
-				}
-				else if (letter == ' ' || letter == 't' || letter == 'I' || letter == '[' || letter == ']')
-				{
-					length += (0.69 * weight);
-				}
-				else if (letter == 'f' || letter == 'k' || letter == '"' || letter == '*'
-						 || letter == '(' || letter == ')' || letter == '{' || letter == '}' || letter == '<' || letter == '>')
-				{
-					length += (0.85 * weight);
-				}
-				else if (letter == '@' || letter == '~')
-				{
-					length += (1.2 * weight);
-				}
-				else
-				{
-					length += weight;
-				}
-				pointer++;
-			}
+                pageLength++;
 
-			if (length > 0)
-			{
-				tempLine = pageLine.substring(start, lineLength);
-				pageLines.add(tempLine);
-				if (buildPage(pages, pageLines, false))
-				{
-					pageLength = 0;
-				}
-			}
-		}
+                if (letter == '\u00a7' && pointer + 1 < lineLength) {
+                    Character nextLetter = pageLine.charAt(pointer + 1);
+                    if (nextLetter == 'l' || nextLetter == 'L') {
+                        weight = 1.25;
+                    } else {
+                        weight = 1;
+                    }
+                    pointer++;
+                } else if (letter == 'i' || letter == '.' || letter == ',' || letter == '!' || letter == ':' || letter == ';' || letter == '|') {
+                    length += (0.34 * weight);
+                } else if (letter == 'l' || letter == '\'' || letter == '`') {
+                    length += (0.53 * weight);
+                } else if (letter == ' ' || letter == 't' || letter == 'I' || letter == '[' || letter == ']') {
+                    length += (0.69 * weight);
+                } else if (letter == 'f' || letter == 'k' || letter == '"' || letter == '*' || letter == '(' || letter == ')' || letter == '{' || letter == '}' || letter == '<' || letter == '>') {
+                    length += (0.85 * weight);
+                } else if (letter == '@' || letter == '~') {
+                    length += (1.2 * weight);
+                } else {
+                    length += weight;
+                }
+                pointer++;
+            }
 
-		buildPage(pages, pageLines, true);
-		return pages;
-	}
+            if (length > 0) {
+                tempLine = pageLine.substring(start, lineLength);
+                pageLines.add(tempLine);
+                if (buildPage(pages, pageLines, false)) {
+                    pageLength = 0;
+                }
+            }
+        }
 
-	boolean buildPage(List pages, List lines, boolean override)
-	{
-		if (override || lines.size() > lineMax)
-		{
-			StringBuilder newPage = new StringBuilder();
-			for (String aline : lines)
-			{
-				newPage.append(aline).append("\n");
-			}
-			pages.add(newPage.toString());
-			lines.clear();
-			return true;
-		}
-		return false;
-	}
+        buildPage(pages, pageLines, true);
+        return pages;
+    }
+
+    boolean buildPage(List pages, List lines, boolean override) {
+        if (override || lines.size() > lineMax) {
+            StringBuilder newPage = new StringBuilder();
+            for (String aline : lines) {
+                newPage.append(aline).append("\n");
+            }
+            pages.add(newPage.toString());
+            lines.clear();
+            return true;
+        }
+        return false;
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/textreader/HelpInput.java b/Essentials/src/com/earth2me/essentials/textreader/HelpInput.java
index 1e74871d4..036761be1 100644
--- a/Essentials/src/com/earth2me/essentials/textreader/HelpInput.java
+++ b/Essentials/src/com/earth2me/essentials/textreader/HelpInput.java
@@ -1,171 +1,129 @@
 package com.earth2me.essentials.textreader;
 
-import static com.earth2me.essentials.I18n.tl;
 import com.earth2me.essentials.User;
-import java.io.IOException;
-import java.util.*;
-import java.util.logging.Level;
-import java.util.logging.Logger;
 import net.ess3.api.IEssentials;
 import org.bukkit.plugin.Plugin;
 import org.bukkit.plugin.PluginDescriptionFile;
 
+import java.io.IOException;
+import java.util.*;
+import java.util.logging.Level;
+import java.util.logging.Logger;
 
-public class HelpInput implements IText
-{
-	private static final String DESCRIPTION = "description";
-	private static final String PERMISSION = "permission";
-	private static final String PERMISSIONS = "permissions";
-	private static final Logger logger = Logger.getLogger("Essentials");
-	private final transient List lines = new ArrayList();
-	private final transient List chapters = new ArrayList();
-	private final transient Map bookmarks = new HashMap();
+import static com.earth2me.essentials.I18n.tl;
 
-	public HelpInput(final User user, final String match, final IEssentials ess) throws IOException
-	{
-		boolean reported = false;
-		final List newLines = new ArrayList();
-		String pluginName = "";
-		String pluginNameLow = "";
-		if (!match.equalsIgnoreCase(""))
-		{
-			lines.add(tl("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(tl("helpFrom", p.getDescription().getName()));
-				}
-				final boolean isOnWhitelist = user.isAuthorized("essentials.help." + pluginNameLow);
+public class HelpInput implements IText {
+    private static final String DESCRIPTION = "description";
+    private static final String PERMISSION = "permission";
+    private static final String PERMISSIONS = "permissions";
+    private static final Logger logger = Logger.getLogger("Essentials");
+    private final transient List lines = new ArrayList();
+    private final transient List chapters = new ArrayList();
+    private final transient Map bookmarks = new HashMap();
 
-				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;
-						}
+    public HelpInput(final User user, final String match, final IEssentials ess) throws IOException {
+        boolean reported = false;
+        final List newLines = new ArrayList();
+        String pluginName = "";
+        String pluginNameLow = "";
+        if (!match.equalsIgnoreCase("")) {
+            lines.add(tl("helpMatching", match));
+        }
 
-						if (pluginNameLow.contains("essentials"))
-						{
-							final String node = "essentials." + k.getKey();
-							if (!ess.getSettings().isCommandDisabled(k.getKey()) && user.isAuthorized(node))
-							{
-								pluginLines.add(tl("helpLine", k.getKey(), k.getValue().get(DESCRIPTION)));
-							}
-						}
-						else
-						{
-							if (ess.getSettings().showNonEssCommandsInHelp())
-							{
-								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 (isOnWhitelist || user.isAuthorized("essentials.help." + pluginNameLow + "." + k.getKey()))
-								{
-									pluginLines.add(tl("helpLine", k.getKey(), value.get(DESCRIPTION)));
-								}
-								else if (permissions instanceof List && !((List)permissions).isEmpty())
-								{
-									boolean enabled = false;
-									for (Object o : (List)permissions)
-									{
-										if (o instanceof String && user.isAuthorized(o.toString()))
-										{
-											enabled = true;
-											break;
-										}
-									}
-									if (enabled)
-									{
-										pluginLines.add(tl("helpLine", k.getKey(), value.get(DESCRIPTION)));
-									}
-								}
-								else if (permissions instanceof String && !"".equals(permissions))
-								{
-									if (user.isAuthorized(permissions.toString()))
-									{
-										pluginLines.add(tl("helpLine", k.getKey(), value.get(DESCRIPTION)));
-									}
-								}
-								else
-								{
-									if (!ess.getSettings().hidePermissionlessHelp())
-									{
-										pluginLines.add(tl("helpLine", k.getKey(), value.get(DESCRIPTION)));
-									}
-								}
-							}
-						}
-					}
-					catch (NullPointerException ex)
-					{
-					}
-				}
-				if (!pluginLines.isEmpty())
-				{
-					newLines.addAll(pluginLines);
-					if (pluginNameLow.equals(match))
-					{
-						break;
-					}
-					if (match.equalsIgnoreCase(""))
-					{
-						lines.add(tl("helpPlugin", pluginName, pluginNameLow));
-					}
-				}
-			}
-			catch (NullPointerException ex)
-			{
-			}
-			catch (Exception ex)
-			{
-				if (!reported)
-				{
-					logger.log(Level.WARNING, tl("commandHelpFailedForPlugin", pluginNameLow), ex);
-				}
-				reported = true;
-			}
-		}
-		lines.addAll(newLines);
-	}
+        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(tl("helpFrom", p.getDescription().getName()));
+                }
+                final boolean isOnWhitelist = user.isAuthorized("essentials.help." + pluginNameLow);
 
-	@Override
-	public List getLines()
-	{
-		return lines;
-	}
+                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;
+                        }
 
-	@Override
-	public List getChapters()
-	{
-		return chapters;
-	}
+                        if (pluginNameLow.contains("essentials")) {
+                            final String node = "essentials." + k.getKey();
+                            if (!ess.getSettings().isCommandDisabled(k.getKey()) && user.isAuthorized(node)) {
+                                pluginLines.add(tl("helpLine", k.getKey(), k.getValue().get(DESCRIPTION)));
+                            }
+                        } else {
+                            if (ess.getSettings().showNonEssCommandsInHelp()) {
+                                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 (isOnWhitelist || user.isAuthorized("essentials.help." + pluginNameLow + "." + k.getKey())) {
+                                    pluginLines.add(tl("helpLine", k.getKey(), value.get(DESCRIPTION)));
+                                } else if (permissions instanceof List && !((List) permissions).isEmpty()) {
+                                    boolean enabled = false;
+                                    for (Object o : (List) permissions) {
+                                        if (o instanceof String && user.isAuthorized(o.toString())) {
+                                            enabled = true;
+                                            break;
+                                        }
+                                    }
+                                    if (enabled) {
+                                        pluginLines.add(tl("helpLine", k.getKey(), value.get(DESCRIPTION)));
+                                    }
+                                } else if (permissions instanceof String && !"".equals(permissions)) {
+                                    if (user.isAuthorized(permissions.toString())) {
+                                        pluginLines.add(tl("helpLine", k.getKey(), value.get(DESCRIPTION)));
+                                    }
+                                } else {
+                                    if (!ess.getSettings().hidePermissionlessHelp()) {
+                                        pluginLines.add(tl("helpLine", k.getKey(), value.get(DESCRIPTION)));
+                                    }
+                                }
+                            }
+                        }
+                    } catch (NullPointerException ex) {
+                    }
+                }
+                if (!pluginLines.isEmpty()) {
+                    newLines.addAll(pluginLines);
+                    if (pluginNameLow.equals(match)) {
+                        break;
+                    }
+                    if (match.equalsIgnoreCase("")) {
+                        lines.add(tl("helpPlugin", pluginName, pluginNameLow));
+                    }
+                }
+            } catch (NullPointerException ex) {
+            } catch (Exception ex) {
+                if (!reported) {
+                    logger.log(Level.WARNING, tl("commandHelpFailedForPlugin", pluginNameLow), ex);
+                }
+                reported = true;
+            }
+        }
+        lines.addAll(newLines);
+    }
 
-	@Override
-	public Map getBookmarks()
-	{
-		return bookmarks;
-	}
+    @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/textreader/IText.java b/Essentials/src/com/earth2me/essentials/textreader/IText.java
index 60db6dadf..cc47a2499 100644
--- a/Essentials/src/com/earth2me/essentials/textreader/IText.java
+++ b/Essentials/src/com/earth2me/essentials/textreader/IText.java
@@ -4,14 +4,13 @@ import java.util.List;
 import java.util.Map;
 
 
-public interface IText
-{
-	// Contains the raw text lines
-	List getLines();
+public interface IText {
+    // Contains the raw text lines
+    List getLines();
 
-	// Chapters contain the names that are displayed automatically if the file doesn't contain a introduction chapter.
-	List getChapters();
+    // Chapters contain the names that are displayed automatically if the file doesn't contain a introduction chapter.
+    List getChapters();
 
-	// Bookmarks contains the string mappings from 'chapters' to line numbers.
-	Map getBookmarks();
+    // Bookmarks contains the string mappings from 'chapters' to line numbers.
+    Map getBookmarks();
 }
diff --git a/Essentials/src/com/earth2me/essentials/textreader/KeywordReplacer.java b/Essentials/src/com/earth2me/essentials/textreader/KeywordReplacer.java
index c2c40b1dc..3b96acbb8 100644
--- a/Essentials/src/com/earth2me/essentials/textreader/KeywordReplacer.java
+++ b/Essentials/src/com/earth2me/essentials/textreader/KeywordReplacer.java
@@ -2,418 +2,348 @@ package com.earth2me.essentials.textreader;
 
 import com.earth2me.essentials.CommandSource;
 import com.earth2me.essentials.ExecuteTimer;
-import static com.earth2me.essentials.I18n.tl;
 import com.earth2me.essentials.PlayerList;
 import com.earth2me.essentials.User;
-import static com.earth2me.essentials.textreader.KeywordType.DISPLAYNAME;
-import static com.earth2me.essentials.textreader.KeywordType.PLAYER;
 import com.earth2me.essentials.utils.DateUtil;
 import com.earth2me.essentials.utils.DescParseTickFormat;
 import com.earth2me.essentials.utils.NumberUtil;
-import java.lang.management.ManagementFactory;
-import java.text.DateFormat;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.logging.Level;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
 import net.ess3.api.IEssentials;
 import org.bukkit.Location;
 import org.bukkit.World;
 import org.bukkit.entity.Player;
 import org.bukkit.plugin.Plugin;
 
+import java.lang.management.ManagementFactory;
+import java.text.DateFormat;
+import java.util.*;
+import java.util.logging.Level;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 
-public class KeywordReplacer implements IText
-{
-	private static final Pattern KEYWORD = Pattern.compile("\\{([^\\{\\}]+)\\}");
-	private static final Pattern KEYWORDSPLIT = Pattern.compile("\\:");
-	private final transient IText input;
-	private final transient List replaced;
-	private final transient IEssentials ess;
-	private final transient boolean includePrivate;
-	private transient ExecuteTimer execTimer;
-	private final EnumMap keywordCache = new EnumMap(KeywordType.class);
+import static com.earth2me.essentials.I18n.tl;
 
-	public KeywordReplacer(final IText input, final CommandSource sender, final IEssentials ess)
-	{
-		this.input = input;
-		this.replaced = new ArrayList(this.input.getLines().size());
-		this.ess = ess;
-		this.includePrivate = true;
-		replaceKeywords(sender);
-	}
 
-	public KeywordReplacer(final IText input, final CommandSource sender, final IEssentials ess, final boolean showPrivate)
-	{
-		this.input = input;
-		this.replaced = new ArrayList(this.input.getLines().size());
-		this.ess = ess;
-		this.includePrivate = showPrivate;
-		replaceKeywords(sender);
-	}
+public class KeywordReplacer implements IText {
+    private static final Pattern KEYWORD = Pattern.compile("\\{([^\\{\\}]+)\\}");
+    private static final Pattern KEYWORDSPLIT = Pattern.compile("\\:");
+    private final transient IText input;
+    private final transient List replaced;
+    private final transient IEssentials ess;
+    private final transient boolean includePrivate;
+    private transient ExecuteTimer execTimer;
+    private final EnumMap keywordCache = new EnumMap(KeywordType.class);
 
-	private void replaceKeywords(final CommandSource sender)
-	{
-		execTimer = new ExecuteTimer();
-		execTimer.start();
-		User user = null;
-		if (sender.isPlayer())
-		{
-			user = ess.getUser(sender.getPlayer());
-		}
-		execTimer.mark("User Grab");
+    public KeywordReplacer(final IText input, final CommandSource sender, final IEssentials ess) {
+        this.input = input;
+        this.replaced = new ArrayList(this.input.getLines().size());
+        this.ess = ess;
+        this.includePrivate = true;
+        replaceKeywords(sender);
+    }
 
-		for (int i = 0; i < input.getLines().size(); i++)
-		{
-			String line = input.getLines().get(i);
-			final Matcher matcher = KEYWORD.matcher(line);
+    public KeywordReplacer(final IText input, final CommandSource sender, final IEssentials ess, final boolean showPrivate) {
+        this.input = input;
+        this.replaced = new ArrayList(this.input.getLines().size());
+        this.ess = ess;
+        this.includePrivate = showPrivate;
+        replaceKeywords(sender);
+    }
 
-			while (matcher.find())
-			{
-				final String fullMatch = matcher.group(0);
-				final String keywordMatch = matcher.group(1);
-				final String[] matchTokens = KEYWORDSPLIT.split(keywordMatch);
-				line = replaceLine(line, fullMatch, matchTokens, user);
-			}
-			replaced.add(line);
-		}
+    private void replaceKeywords(final CommandSource sender) {
+        execTimer = new ExecuteTimer();
+        execTimer.start();
+        User user = null;
+        if (sender.isPlayer()) {
+            user = ess.getUser(sender.getPlayer());
+        }
+        execTimer.mark("User Grab");
 
-		execTimer.mark("Text Replace");
-		final String timeroutput = execTimer.end();
-		if (ess.getSettings().isDebug())
-		{
-			ess.getLogger().log(Level.INFO, "Keyword Replacer " + timeroutput);
-		}
-	}
+        for (int i = 0; i < input.getLines().size(); i++) {
+            String line = input.getLines().get(i);
+            final Matcher matcher = KEYWORD.matcher(line);
 
-	private String replaceLine(String line, final String fullMatch, final String[] matchTokens, final User user)
-	{
-		final String keyword = matchTokens[0];
-		try
-		{
-			String replacer = null;
-			KeywordType validKeyword = KeywordType.valueOf(keyword);
-			if (validKeyword.getType().equals(KeywordCachable.CACHEABLE) && keywordCache.containsKey(validKeyword))
-			{
-				replacer = keywordCache.get(validKeyword).toString();
-			}
-			else if (validKeyword.getType().equals(KeywordCachable.SUBVALUE))
-			{
-				String subKeyword = "";
-				if (matchTokens.length > 1)
-				{
-					subKeyword = matchTokens[1].toLowerCase(Locale.ENGLISH);
-				}
+            while (matcher.find()) {
+                final String fullMatch = matcher.group(0);
+                final String keywordMatch = matcher.group(1);
+                final String[] matchTokens = KEYWORDSPLIT.split(keywordMatch);
+                line = replaceLine(line, fullMatch, matchTokens, user);
+            }
+            replaced.add(line);
+        }
 
-				if (keywordCache.containsKey(validKeyword))
-				{
-					Map values = (Map)keywordCache.get(validKeyword);
-					if (values.containsKey(subKeyword))
-					{
-						replacer = values.get(subKeyword);
-					}
-				}
-			}
+        execTimer.mark("Text Replace");
+        final String timeroutput = execTimer.end();
+        if (ess.getSettings().isDebug()) {
+            ess.getLogger().log(Level.INFO, "Keyword Replacer " + timeroutput);
+        }
+    }
 
-			if (validKeyword.isPrivate() && !includePrivate)
-			{
-				replacer = "";
-			}
+    private String replaceLine(String line, final String fullMatch, final String[] matchTokens, final User user) {
+        final String keyword = matchTokens[0];
+        try {
+            String replacer = null;
+            KeywordType validKeyword = KeywordType.valueOf(keyword);
+            if (validKeyword.getType().equals(KeywordCachable.CACHEABLE) && keywordCache.containsKey(validKeyword)) {
+                replacer = keywordCache.get(validKeyword).toString();
+            } else if (validKeyword.getType().equals(KeywordCachable.SUBVALUE)) {
+                String subKeyword = "";
+                if (matchTokens.length > 1) {
+                    subKeyword = matchTokens[1].toLowerCase(Locale.ENGLISH);
+                }
 
-			if (replacer == null)
-			{
-				replacer = "";
-				switch (validKeyword)
-				{
-				case PLAYER:
-				case DISPLAYNAME:
-					if (user != null)
-					{
-						replacer = user.getDisplayName();
-					}
-					break;
-				case USERNAME:
-					if (user != null)
-					{
-						replacer = user.getName();
-					}
-					break;
-				case BALANCE:
-					if (user != null)
-					{
-						replacer = NumberUtil.displayCurrency(user.getMoney(), ess);
-					}
-					break;
-				case MAILS:
-					if (user != null)
-					{
-						replacer = Integer.toString(user.getMails().size());
-					}
-					break;
-				case WORLD:
-				case WORLDNAME:
-					if (user != null)
-					{
-						final Location location = user.getLocation();
-						replacer = location == null || location.getWorld() == null ? "" : location.getWorld().getName();
-					}
-					break;
-				case ONLINE:
-					int playerHidden = 0;
-					for (User u : ess.getOnlineUsers())
-					{
-						if (u.isHidden())
-						{
-							playerHidden++;
-						}
-					}
-					replacer = Integer.toString(ess.getOnlinePlayers().size() - playerHidden);
-					break;
-				case UNIQUE:
-					replacer = Integer.toString(ess.getUserMap().getUniqueUsers());
-					break;
-				case WORLDS:
-					final StringBuilder worldsBuilder = new StringBuilder();
-					for (World w : ess.getServer().getWorlds())
-					{
-						if (worldsBuilder.length() > 0)
-						{
-							worldsBuilder.append(", ");
-						}
-						worldsBuilder.append(w.getName());
-					}
-					replacer = worldsBuilder.toString();
-					break;
-				case PLAYERLIST:
-					final Map outputList;
-					if (keywordCache.containsKey(validKeyword))
-					{
-						outputList = (Map)keywordCache.get(validKeyword);
-					}
-					else
-					{
-						final boolean showHidden;
-						if (user == null)
-						{
-							showHidden = true;
-						}
-						else
-						{
-							showHidden = user.isAuthorized("essentials.list.hidden") || user.canInteractVanished();
-						}
+                if (keywordCache.containsKey(validKeyword)) {
+                    Map values = (Map) keywordCache.get(validKeyword);
+                    if (values.containsKey(subKeyword)) {
+                        replacer = values.get(subKeyword);
+                    }
+                }
+            }
 
-						//First lets build the per group playerlist
-						final Map> playerList = PlayerList.getPlayerLists(ess, user, showHidden);
-						outputList = new HashMap();
-						for (String groupName : playerList.keySet())
-						{
-							final List groupUsers = playerList.get(groupName);
-							if (groupUsers != null && !groupUsers.isEmpty())
-							{
-								outputList.put(groupName, PlayerList.listUsers(ess, groupUsers, " "));
-							}
-						}
+            if (validKeyword.isPrivate() && !includePrivate) {
+                replacer = "";
+            }
 
-						//Now lets build the all user playerlist
-						final StringBuilder playerlistBuilder = new StringBuilder();
-						for (Player p : ess.getOnlinePlayers())
-						{
-							if (ess.getUser(p).isHidden())
-							{
-								continue;
-							}
-							if (playerlistBuilder.length() > 0)
-							{
-								playerlistBuilder.append(", ");
-							}
-							playerlistBuilder.append(p.getDisplayName());
-						}
-						outputList.put("", playerlistBuilder.toString());
-						keywordCache.put(validKeyword, outputList);
-					}
+            if (replacer == null) {
+                replacer = "";
+                switch (validKeyword) {
+                    case PLAYER:
+                    case DISPLAYNAME:
+                        if (user != null) {
+                            replacer = user.getDisplayName();
+                        }
+                        break;
+                    case USERNAME:
+                        if (user != null) {
+                            replacer = user.getName();
+                        }
+                        break;
+                    case BALANCE:
+                        if (user != null) {
+                            replacer = NumberUtil.displayCurrency(user.getMoney(), ess);
+                        }
+                        break;
+                    case MAILS:
+                        if (user != null) {
+                            replacer = Integer.toString(user.getMails().size());
+                        }
+                        break;
+                    case WORLD:
+                    case WORLDNAME:
+                        if (user != null) {
+                            final Location location = user.getLocation();
+                            replacer = location == null || location.getWorld() == null ? "" : location.getWorld().getName();
+                        }
+                        break;
+                    case ONLINE:
+                        int playerHidden = 0;
+                        for (User u : ess.getOnlineUsers()) {
+                            if (u.isHidden()) {
+                                playerHidden++;
+                            }
+                        }
+                        replacer = Integer.toString(ess.getOnlinePlayers().size() - playerHidden);
+                        break;
+                    case UNIQUE:
+                        replacer = Integer.toString(ess.getUserMap().getUniqueUsers());
+                        break;
+                    case WORLDS:
+                        final StringBuilder worldsBuilder = new StringBuilder();
+                        for (World w : ess.getServer().getWorlds()) {
+                            if (worldsBuilder.length() > 0) {
+                                worldsBuilder.append(", ");
+                            }
+                            worldsBuilder.append(w.getName());
+                        }
+                        replacer = worldsBuilder.toString();
+                        break;
+                    case PLAYERLIST:
+                        final Map outputList;
+                        if (keywordCache.containsKey(validKeyword)) {
+                            outputList = (Map) keywordCache.get(validKeyword);
+                        } else {
+                            final boolean showHidden;
+                            if (user == null) {
+                                showHidden = true;
+                            } else {
+                                showHidden = user.isAuthorized("essentials.list.hidden") || user.canInteractVanished();
+                            }
 
-					//Now thats all done, output the one we want and cache the rest.
-					if (matchTokens.length == 1)
-					{
-						replacer = outputList.get("");
-					}
-					else if (outputList.containsKey(matchTokens[1].toLowerCase(Locale.ENGLISH)))
-					{
-						replacer = outputList.get(matchTokens[1].toLowerCase(Locale.ENGLISH));
-					}
-					else if (matchTokens.length > 2)
-					{
-						replacer = matchTokens[2];
-					}
+                            //First lets build the per group playerlist
+                            final Map> playerList = PlayerList.getPlayerLists(ess, user, showHidden);
+                            outputList = new HashMap();
+                            for (String groupName : playerList.keySet()) {
+                                final List groupUsers = playerList.get(groupName);
+                                if (groupUsers != null && !groupUsers.isEmpty()) {
+                                    outputList.put(groupName, PlayerList.listUsers(ess, groupUsers, " "));
+                                }
+                            }
 
-					keywordCache.put(validKeyword, outputList);
-					break;
-				case TIME:
-					replacer = DateFormat.getTimeInstance(DateFormat.MEDIUM, ess.getI18n().getCurrentLocale()).format(new Date());
-					break;
-				case DATE:
-					replacer = DateFormat.getDateInstance(DateFormat.MEDIUM, ess.getI18n().getCurrentLocale()).format(new Date());
-					break;
-				case WORLDTIME12:
-					if (user != null)
-					{
-						replacer = DescParseTickFormat.format12(user.getWorld() == null ? 0 : user.getWorld().getTime());
-					}
-					break;
-				case WORLDTIME24:
-					if (user != null)
-					{
-						replacer = DescParseTickFormat.format24(user.getWorld() == null ? 0 : user.getWorld().getTime());
-					}
-					break;
-				case WORLDDATE:
-					if (user != null)
-					{
-						replacer = DateFormat.getDateInstance(DateFormat.MEDIUM, ess.getI18n().getCurrentLocale()).format(DescParseTickFormat.ticksToDate(user.getWorld() == null ? 0 : user.getWorld().getFullTime()));
-					}
-					break;
-				case COORDS:
-					if (user != null)
-					{
-						final Location location = user.getLocation();
-						replacer = tl("coordsKeyword", location.getBlockX(), location.getBlockY(), location.getBlockZ());
-					}
-					break;
-				case TPS:
-					replacer = NumberUtil.formatDouble(ess.getTimer().getAverageTPS());
-					break;
-				case UPTIME:
-					replacer = DateUtil.formatDateDiff(ManagementFactory.getRuntimeMXBean().getStartTime());
-					break;
-				case IP:
-					if (user != null)
-					{
-						replacer = user.getBase().getAddress() == null || user.getBase().getAddress().getAddress() == null ? "" : user.getBase().getAddress().getAddress().toString();
-					}
-					break;
-				case ADDRESS:
-					if (user != null)
-					{
-						replacer = user.getBase().getAddress() == null ? "" : user.getBase().getAddress().toString();
-					}
-					break;
-				case PLUGINS:
-					final StringBuilder pluginlistBuilder = new StringBuilder();
-					for (Plugin p : ess.getServer().getPluginManager().getPlugins())
-					{
-						if (pluginlistBuilder.length() > 0)
-						{
-							pluginlistBuilder.append(", ");
-						}
-						pluginlistBuilder.append(p.getDescription().getName());
-					}
-					replacer = pluginlistBuilder.toString();
-					break;
-				case VERSION:
-					replacer = ess.getServer().getVersion();
-					break;
-				default:
-					replacer = "N/A";
-					break;
-				}
+                            //Now lets build the all user playerlist
+                            final StringBuilder playerlistBuilder = new StringBuilder();
+                            for (Player p : ess.getOnlinePlayers()) {
+                                if (ess.getUser(p).isHidden()) {
+                                    continue;
+                                }
+                                if (playerlistBuilder.length() > 0) {
+                                    playerlistBuilder.append(", ");
+                                }
+                                playerlistBuilder.append(p.getDisplayName());
+                            }
+                            outputList.put("", playerlistBuilder.toString());
+                            keywordCache.put(validKeyword, outputList);
+                        }
 
-				//If this is just a regular keyword, lets throw it into the cache
-				if (validKeyword.getType().equals(KeywordCachable.CACHEABLE))
-				{
-					keywordCache.put(validKeyword, replacer);
-				}
-			}
+                        //Now thats all done, output the one we want and cache the rest.
+                        if (matchTokens.length == 1) {
+                            replacer = outputList.get("");
+                        } else if (outputList.containsKey(matchTokens[1].toLowerCase(Locale.ENGLISH))) {
+                            replacer = outputList.get(matchTokens[1].toLowerCase(Locale.ENGLISH));
+                        } else if (matchTokens.length > 2) {
+                            replacer = matchTokens[2];
+                        }
 
-			line = line.replace(fullMatch, replacer);
-		}
-		catch (IllegalArgumentException ex)
-		{
-		}
+                        keywordCache.put(validKeyword, outputList);
+                        break;
+                    case TIME:
+                        replacer = DateFormat.getTimeInstance(DateFormat.MEDIUM, ess.getI18n().getCurrentLocale()).format(new Date());
+                        break;
+                    case DATE:
+                        replacer = DateFormat.getDateInstance(DateFormat.MEDIUM, ess.getI18n().getCurrentLocale()).format(new Date());
+                        break;
+                    case WORLDTIME12:
+                        if (user != null) {
+                            replacer = DescParseTickFormat.format12(user.getWorld() == null ? 0 : user.getWorld().getTime());
+                        }
+                        break;
+                    case WORLDTIME24:
+                        if (user != null) {
+                            replacer = DescParseTickFormat.format24(user.getWorld() == null ? 0 : user.getWorld().getTime());
+                        }
+                        break;
+                    case WORLDDATE:
+                        if (user != null) {
+                            replacer = DateFormat.getDateInstance(DateFormat.MEDIUM, ess.getI18n().getCurrentLocale()).format(DescParseTickFormat.ticksToDate(user.getWorld() == null ? 0 : user.getWorld().getFullTime()));
+                        }
+                        break;
+                    case COORDS:
+                        if (user != null) {
+                            final Location location = user.getLocation();
+                            replacer = tl("coordsKeyword", location.getBlockX(), location.getBlockY(), location.getBlockZ());
+                        }
+                        break;
+                    case TPS:
+                        replacer = NumberUtil.formatDouble(ess.getTimer().getAverageTPS());
+                        break;
+                    case UPTIME:
+                        replacer = DateUtil.formatDateDiff(ManagementFactory.getRuntimeMXBean().getStartTime());
+                        break;
+                    case IP:
+                        if (user != null) {
+                            replacer = user.getBase().getAddress() == null || user.getBase().getAddress().getAddress() == null ? "" : user.getBase().getAddress().getAddress().toString();
+                        }
+                        break;
+                    case ADDRESS:
+                        if (user != null) {
+                            replacer = user.getBase().getAddress() == null ? "" : user.getBase().getAddress().toString();
+                        }
+                        break;
+                    case PLUGINS:
+                        final StringBuilder pluginlistBuilder = new StringBuilder();
+                        for (Plugin p : ess.getServer().getPluginManager().getPlugins()) {
+                            if (pluginlistBuilder.length() > 0) {
+                                pluginlistBuilder.append(", ");
+                            }
+                            pluginlistBuilder.append(p.getDescription().getName());
+                        }
+                        replacer = pluginlistBuilder.toString();
+                        break;
+                    case VERSION:
+                        replacer = ess.getServer().getVersion();
+                        break;
+                    default:
+                        replacer = "N/A";
+                        break;
+                }
 
-		return line;
-	}
+                //If this is just a regular keyword, lets throw it into the cache
+                if (validKeyword.getType().equals(KeywordCachable.CACHEABLE)) {
+                    keywordCache.put(validKeyword, replacer);
+                }
+            }
 
-	@Override
-	public List getLines()
-	{
-		return replaced;
-	}
+            line = line.replace(fullMatch, replacer);
+        } catch (IllegalArgumentException ex) {
+        }
 
-	@Override
-	public List getChapters()
-	{
-		return input.getChapters();
-	}
+        return line;
+    }
 
-	@Override
-	public Map getBookmarks()
-	{
-		return input.getBookmarks();
-	}
+    @Override
+    public List getLines() {
+        return replaced;
+    }
+
+    @Override
+    public List getChapters() {
+        return input.getChapters();
+    }
+
+    @Override
+    public Map getBookmarks() {
+        return input.getBookmarks();
+    }
 }
 
 //When adding a keyword here, you also need to add the implementation above
-enum KeywordType
-{
-	PLAYER(KeywordCachable.CACHEABLE),
-	DISPLAYNAME(KeywordCachable.CACHEABLE),
-	USERNAME(KeywordCachable.NOTCACHEABLE),
-	BALANCE(KeywordCachable.CACHEABLE),
-	MAILS(KeywordCachable.CACHEABLE),
-	WORLD(KeywordCachable.CACHEABLE),
-	WORLDNAME(KeywordCachable.CACHEABLE),
-	ONLINE(KeywordCachable.CACHEABLE),
-	UNIQUE(KeywordCachable.CACHEABLE),
-	WORLDS(KeywordCachable.CACHEABLE),
-	PLAYERLIST(KeywordCachable.SUBVALUE, true),
-	TIME(KeywordCachable.CACHEABLE),
-	DATE(KeywordCachable.CACHEABLE),
-	WORLDTIME12(KeywordCachable.CACHEABLE),
-	WORLDTIME24(KeywordCachable.CACHEABLE),
-	WORLDDATE(KeywordCachable.CACHEABLE),
-	COORDS(KeywordCachable.CACHEABLE),
-	TPS(KeywordCachable.CACHEABLE),
-	UPTIME(KeywordCachable.CACHEABLE),
-	IP(KeywordCachable.CACHEABLE, true),
-	ADDRESS(KeywordCachable.CACHEABLE, true),
-	PLUGINS(KeywordCachable.CACHEABLE, true),
-	VERSION(KeywordCachable.CACHEABLE, true);
-	private final KeywordCachable type;
-	private final boolean isPrivate;
+enum KeywordType {
+    PLAYER(KeywordCachable.CACHEABLE),
+    DISPLAYNAME(KeywordCachable.CACHEABLE),
+    USERNAME(KeywordCachable.NOTCACHEABLE),
+    BALANCE(KeywordCachable.CACHEABLE),
+    MAILS(KeywordCachable.CACHEABLE),
+    WORLD(KeywordCachable.CACHEABLE),
+    WORLDNAME(KeywordCachable.CACHEABLE),
+    ONLINE(KeywordCachable.CACHEABLE),
+    UNIQUE(KeywordCachable.CACHEABLE),
+    WORLDS(KeywordCachable.CACHEABLE),
+    PLAYERLIST(KeywordCachable.SUBVALUE, true),
+    TIME(KeywordCachable.CACHEABLE),
+    DATE(KeywordCachable.CACHEABLE),
+    WORLDTIME12(KeywordCachable.CACHEABLE),
+    WORLDTIME24(KeywordCachable.CACHEABLE),
+    WORLDDATE(KeywordCachable.CACHEABLE),
+    COORDS(KeywordCachable.CACHEABLE),
+    TPS(KeywordCachable.CACHEABLE),
+    UPTIME(KeywordCachable.CACHEABLE),
+    IP(KeywordCachable.CACHEABLE, true),
+    ADDRESS(KeywordCachable.CACHEABLE, true),
+    PLUGINS(KeywordCachable.CACHEABLE, true),
+    VERSION(KeywordCachable.CACHEABLE, true);
+    private final KeywordCachable type;
+    private final boolean isPrivate;
 
-	KeywordType(KeywordCachable type)
-	{
-		this.type = type;
-		this.isPrivate = false;
-	}
+    KeywordType(KeywordCachable type) {
+        this.type = type;
+        this.isPrivate = false;
+    }
 
-	KeywordType(KeywordCachable type, boolean isPrivate)
-	{
-		this.type = type;
-		this.isPrivate = isPrivate;
-	}
+    KeywordType(KeywordCachable type, boolean isPrivate) {
+        this.type = type;
+        this.isPrivate = isPrivate;
+    }
 
-	public KeywordCachable getType()
-	{
-		return type;
-	}
+    public KeywordCachable getType() {
+        return type;
+    }
 
-	public boolean isPrivate()
-	{
-		return isPrivate;
-	}
+    public boolean isPrivate() {
+        return isPrivate;
+    }
 }
 
 
-enum KeywordCachable
-{
-	CACHEABLE, // This keyword can be cached as a string
-	SUBVALUE, // This keyword can be cached as a map
-	NOTCACHEABLE; // This keyword should never be cached
+enum KeywordCachable {
+    CACHEABLE, // This keyword can be cached as a string
+    SUBVALUE, // This keyword can be cached as a map
+    NOTCACHEABLE; // This keyword should never be cached
 }
\ No newline at end of file
diff --git a/Essentials/src/com/earth2me/essentials/textreader/SimpleTextInput.java b/Essentials/src/com/earth2me/essentials/textreader/SimpleTextInput.java
index f15ce6df5..2c4109b26 100644
--- a/Essentials/src/com/earth2me/essentials/textreader/SimpleTextInput.java
+++ b/Essentials/src/com/earth2me/essentials/textreader/SimpleTextInput.java
@@ -3,39 +3,32 @@ package com.earth2me.essentials.textreader;
 import java.util.*;
 
 
-public class SimpleTextInput implements IText
-{
-	private final transient List lines = new ArrayList();
+public class SimpleTextInput implements IText {
+    private final transient List lines = new ArrayList();
 
-	public SimpleTextInput(final String input)
-	{
-		lines.addAll(Arrays.asList(input.split("\\n")));
-	}
+    public SimpleTextInput(final String input) {
+        lines.addAll(Arrays.asList(input.split("\\n")));
+    }
 
-	public SimpleTextInput(final List input)
-	{
-		lines.addAll(input);
-	}
+    public SimpleTextInput(final List input) {
+        lines.addAll(input);
+    }
 
-	public SimpleTextInput()
-	{
-	}
+    public SimpleTextInput() {
+    }
 
-	@Override
-	public List getLines()
-	{
-		return lines;
-	}
+    @Override
+    public List getLines() {
+        return lines;
+    }
 
-	@Override
-	public List getChapters()
-	{
-		return Collections.emptyList();
-	}
+    @Override
+    public List getChapters() {
+        return Collections.emptyList();
+    }
 
-	@Override
-	public Map getBookmarks()
-	{
-		return Collections.emptyMap();
-	}
+    @Override
+    public Map getBookmarks() {
+        return Collections.emptyMap();
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/textreader/SimpleTextPager.java b/Essentials/src/com/earth2me/essentials/textreader/SimpleTextPager.java
index 2556201f1..b7349439f 100644
--- a/Essentials/src/com/earth2me/essentials/textreader/SimpleTextPager.java
+++ b/Essentials/src/com/earth2me/essentials/textreader/SimpleTextPager.java
@@ -1,36 +1,30 @@
 package com.earth2me.essentials.textreader;
 
 import com.earth2me.essentials.CommandSource;
+
 import java.util.List;
 
-public class SimpleTextPager
-{
-	private final transient IText text;
+public class SimpleTextPager {
+    private final transient IText text;
 
-	public SimpleTextPager(final IText text)
-	{
-		this.text = text;
-	}
+    public SimpleTextPager(final IText text) {
+        this.text = text;
+    }
 
-	public void showPage(final CommandSource sender)
-	{
-		for (String line : text.getLines())
-		{
-			sender.sendMessage(line);
-		}
-	}
+    public void showPage(final CommandSource sender) {
+        for (String line : text.getLines()) {
+            sender.sendMessage(line);
+        }
+    }
 
-	public List getLines()
-	{
-		return text.getLines();
-	}
+    public List getLines() {
+        return text.getLines();
+    }
 
-	public String getLine(int line)
-	{
-		if (text.getLines().size() < line)
-		{
-			return null;
-		}
-		return text.getLines().get(line);
-	}
+    public String getLine(int line) {
+        if (text.getLines().size() < line) {
+            return null;
+        }
+        return text.getLines().get(line);
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/textreader/TextInput.java b/Essentials/src/com/earth2me/essentials/textreader/TextInput.java
index 7de60979d..e2fb26d25 100644
--- a/Essentials/src/com/earth2me/essentials/textreader/TextInput.java
+++ b/Essentials/src/com/earth2me/essentials/textreader/TextInput.java
@@ -4,140 +4,113 @@ import com.earth2me.essentials.CommandSource;
 import com.earth2me.essentials.User;
 import com.earth2me.essentials.utils.FormatUtil;
 import com.earth2me.essentials.utils.StringUtil;
+import net.ess3.api.IEssentials;
+
 import java.io.*;
 import java.lang.ref.SoftReference;
 import java.util.*;
-import net.ess3.api.IEssentials;
 
 
-public class TextInput implements IText
-{
-	private static final HashMap> cache = new HashMap>();
-	private final transient List lines;
-	private final transient List chapters;
-	private final transient Map bookmarks;
-	private final transient long lastChange;
+public class TextInput implements IText {
+    private static final HashMap> cache = new HashMap>();
+    private final transient List lines;
+    private final transient List chapters;
+    private final transient Map bookmarks;
+    private final transient long lastChange;
 
-	public TextInput(final CommandSource sender, final String filename, final boolean createFile, final IEssentials ess) throws IOException
-	{
+    public TextInput(final CommandSource sender, final String filename, final boolean createFile, final IEssentials ess) throws IOException {
 
-		File file = null;
-		if (sender.isPlayer())
-		{
-			final User user = ess.getUser(sender.getPlayer());
-			file = new File(ess.getDataFolder(), filename + "_" + StringUtil.sanitizeFileName(user.getName()) + ".txt");
-			if (!file.exists())
-			{
-				file = new File(ess.getDataFolder(), filename + "_" + StringUtil.sanitizeFileName(user.getGroup()) + ".txt");
-			}
-		}
-		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 Reader reader = new InputStreamReader(new FileInputStream(file), "utf-8");
-				final BufferedReader bufferedReader = new BufferedReader(reader);
-				try
-				{
-					int lineNumber = 0;
-					while (bufferedReader.ready())
-					{
-						final String line = bufferedReader.readLine();
-						if (line == null)
-						{
-							break;
-						}
-						if (line.length() > 1 && line.charAt(0) == '#')
-						{
-							String[] titles = line.substring(1).trim().replace(" ", "_").split(",");
-							chapters.add(FormatUtil.replaceFormat(titles[0]));
-							for (String title : titles)
-							{
-								bookmarks.put(FormatUtil.stripEssentialsFormat(title.toLowerCase(Locale.ENGLISH)), lineNumber);
-							}
-						}
-						lines.add(FormatUtil.replaceFormat(line));
-						lineNumber++;
-					}
-				}
-				finally
-				{
-					reader.close();
-					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
-				{
-					output.close();
-					input.close();
-				}
-				throw new FileNotFoundException("File " + filename + ".txt does not exist. Creating one for you.");
-			}
-		}
-	}
+        File file = null;
+        if (sender.isPlayer()) {
+            final User user = ess.getUser(sender.getPlayer());
+            file = new File(ess.getDataFolder(), filename + "_" + StringUtil.sanitizeFileName(user.getName()) + ".txt");
+            if (!file.exists()) {
+                file = new File(ess.getDataFolder(), filename + "_" + StringUtil.sanitizeFileName(user.getGroup()) + ".txt");
+            }
+        }
+        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 Reader reader = new InputStreamReader(new FileInputStream(file), "utf-8");
+                final BufferedReader bufferedReader = new BufferedReader(reader);
+                try {
+                    int lineNumber = 0;
+                    while (bufferedReader.ready()) {
+                        final String line = bufferedReader.readLine();
+                        if (line == null) {
+                            break;
+                        }
+                        if (line.length() > 1 && line.charAt(0) == '#') {
+                            String[] titles = line.substring(1).trim().replace(" ", "_").split(",");
+                            chapters.add(FormatUtil.replaceFormat(titles[0]));
+                            for (String title : titles) {
+                                bookmarks.put(FormatUtil.stripEssentialsFormat(title.toLowerCase(Locale.ENGLISH)), lineNumber);
+                            }
+                        }
+                        lines.add(FormatUtil.replaceFormat(line));
+                        lineNumber++;
+                    }
+                } finally {
+                    reader.close();
+                    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 {
+                    output.close();
+                    input.close();
+                }
+                throw new FileNotFoundException("File " + filename + ".txt does not exist. Creating one for you.");
+            }
+        }
+    }
 
-	@Override
-	public List getLines()
-	{
-		return lines;
-	}
+    @Override
+    public List getLines() {
+        return lines;
+    }
 
-	@Override
-	public List getChapters()
-	{
-		return chapters;
-	}
+    @Override
+    public List getChapters() {
+        return chapters;
+    }
 
-	@Override
-	public Map getBookmarks()
-	{
-		return bookmarks;
-	}
+    @Override
+    public Map getBookmarks() {
+        return bookmarks;
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/textreader/TextPager.java b/Essentials/src/com/earth2me/essentials/textreader/TextPager.java
index 13b8aca00..cb9e60251 100644
--- a/Essentials/src/com/earth2me/essentials/textreader/TextPager.java
+++ b/Essentials/src/com/earth2me/essentials/textreader/TextPager.java
@@ -2,172 +2,140 @@ package com.earth2me.essentials.textreader;
 
 import com.earth2me.essentials.CommandSource;
 import com.earth2me.essentials.I18n;
-import static com.earth2me.essentials.I18n.tl;
+
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
 
+import static com.earth2me.essentials.I18n.tl;
 
-public class TextPager
-{
-	private final transient IText text;
-	private final transient boolean onePage;
 
-	public TextPager(final IText text)
-	{
-		this(text, false);
-	}
+public class TextPager {
+    private final transient IText text;
+    private final transient boolean onePage;
 
-	public TextPager(final IText text, final boolean onePage)
-	{
-		this.text = text;
-		this.onePage = onePage;
-	}
+    public TextPager(final IText text) {
+        this(text, false);
+    }
 
-	public void showPage(final String pageStr, final String chapterPageStr, final String commandName, final CommandSource sender)
-	{
-		List lines = text.getLines();
-		List chapters = text.getChapters();
-		Map bookmarks = text.getBookmarks();
+    public TextPager(final IText text, final boolean onePage) {
+        this.text = text;
+        this.onePage = onePage;
+    }
 
-		//This code deals with the initial chapter.  We use this to display the initial output or contents.
-		//We also use this code to display some extra information if we don't intend to use chapters
-		if (pageStr == null || pageStr.isEmpty() || pageStr.matches("[0-9]+"))
-		{
-			//If an info file starts with a chapter title, list the chapters
-			//If not display the text up until the first chapter.
-			if (!lines.isEmpty() && lines.get(0).startsWith("#"))
-			{
-				if (onePage)
-				{
-					return;
-				}
-				sender.sendMessage(tl("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 (NumberFormatException ex)
-				{
-					page = 1;
-				}
-				if (page < 1)
-				{
-					page = 1;
-				}
+    public void showPage(final String pageStr, final String chapterPageStr, final String commandName, final CommandSource sender) {
+        List lines = text.getLines();
+        List chapters = text.getChapters();
+        Map bookmarks = text.getBookmarks();
 
-				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;
-					}
-				}
+        //This code deals with the initial chapter.  We use this to display the initial output or contents.
+        //We also use this code to display some extra information if we don't intend to use chapters
+        if (pageStr == null || pageStr.isEmpty() || pageStr.matches("[0-9]+")) {
+            //If an info file starts with a chapter title, list the chapters
+            //If not display the text up until the first chapter.
+            if (!lines.isEmpty() && lines.get(0).startsWith("#")) {
+                if (onePage) {
+                    return;
+                }
+                sender.sendMessage(tl("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 (NumberFormatException ex) {
+                    page = 1;
+                }
+                if (page < 1) {
+                    page = 1;
+                }
 
-				int pages = end / 9 + (end % 9 > 0 ? 1 : 0);
-				if (!onePage && commandName != null)
-				{
+                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;
+                    }
+                }
 
-					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
-					{
-						content.append(I18n.capitalCase(commandName));
-					}
-					sender.sendMessage(tl("infoPages", page, pages, content));
-				}
-				for (int i = start; i < end && i < start + (onePage ? 20 : 9); i++)
-				{
-					sender.sendMessage("§r" + lines.get(i));
-				}
-				if (!onePage && page < pages && commandName != null)
-				{
-					sender.sendMessage(tl("readNextPage", commandName, page + 1));
-				}
-				return;
-			}
-		}
+                int pages = end / 9 + (end % 9 > 0 ? 1 : 0);
+                if (!onePage && commandName != null) {
 
-		//If we have a chapter, check to see if we have a page number
-		int chapterpage = 0;
-		if (chapterPageStr != null)
-		{
-			try
-			{
-				chapterpage = Integer.parseInt(chapterPageStr) - 1;
-			}
-			catch (NumberFormatException ex)
-			{
-				chapterpage = 0;
-			}
-			if (chapterpage < 0)
-			{
-				chapterpage = 0;
-			}
-		}
+                    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 {
+                        content.append(I18n.capitalCase(commandName));
+                    }
+                    sender.sendMessage(tl("infoPages", page, pages, content));
+                }
+                for (int i = start; i < end && i < start + (onePage ? 20 : 9); i++) {
+                    sender.sendMessage("§r" + lines.get(i));
+                }
+                if (!onePage && page < pages && commandName != null) {
+                    sender.sendMessage(tl("readNextPage", commandName, page + 1));
+                }
+                return;
+            }
+        }
 
-		//This checks to see if we have the chapter in the index
-		if (!bookmarks.containsKey(pageStr.toLowerCase(Locale.ENGLISH)))
-		{
-			sender.sendMessage(tl("infoUnknownChapter"));
-			return;
-		}
+        //If we have a chapter, check to see if we have a page number
+        int chapterpage = 0;
+        if (chapterPageStr != null) {
+            try {
+                chapterpage = Integer.parseInt(chapterPageStr) - 1;
+            } catch (NumberFormatException ex) {
+                chapterpage = 0;
+            }
+            if (chapterpage < 0) {
+                chapterpage = 0;
+            }
+        }
 
-		//Since we have a valid chapter, count the number of lines in the chapter
-		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;
-			}
-		}
+        //This checks to see if we have the chapter in the index
+        if (!bookmarks.containsKey(pageStr.toLowerCase(Locale.ENGLISH))) {
+            sender.sendMessage(tl("infoUnknownChapter"));
+            return;
+        }
 
-		//Display the chapter from the starting position
-		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 && commandName != null)
-		{
-			StringBuilder content = new StringBuilder();
-			content.append(I18n.capitalCase(commandName)).append(": ");
-			content.append(pageStr);
-			sender.sendMessage(tl("infoChapterPages", content, page, pages));
-		}
-		for (int i = start; i < chapterend && i < start + (onePage ? 20 : 9); i++)
-		{
-			sender.sendMessage("§r" + lines.get(i));
-		}
-		if (!onePage && page < pages && commandName != null)
-		{
-			sender.sendMessage(tl("readNextPage", commandName, pageStr + " " + (page + 1)));
-		}
-	}
+        //Since we have a valid chapter, count the number of lines in the chapter
+        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;
+            }
+        }
+
+        //Display the chapter from the starting position
+        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 && commandName != null) {
+            StringBuilder content = new StringBuilder();
+            content.append(I18n.capitalCase(commandName)).append(": ");
+            content.append(pageStr);
+            sender.sendMessage(tl("infoChapterPages", content, page, pages));
+        }
+        for (int i = start; i < chapterend && i < start + (onePage ? 20 : 9); i++) {
+            sender.sendMessage("§r" + lines.get(i));
+        }
+        if (!onePage && page < pages && commandName != null) {
+            sender.sendMessage(tl("readNextPage", commandName, pageStr + " " + (page + 1)));
+        }
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/utils/DateUtil.java b/Essentials/src/com/earth2me/essentials/utils/DateUtil.java
index 77a374f88..c12bcd91c 100644
--- a/Essentials/src/com/earth2me/essentials/utils/DateUtil.java
+++ b/Essentials/src/com/earth2me/essentials/utils/DateUtil.java
@@ -1,182 +1,143 @@
 package com.earth2me.essentials.utils;
 
-import static com.earth2me.essentials.I18n.tl;
 import java.util.Calendar;
 import java.util.GregorianCalendar;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
+import static com.earth2me.essentials.I18n.tl;
 
-public class DateUtil
-{
-	private static 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);
 
-	public static String removeTimePattern(String input)
-	{
-		return timePattern.matcher(input).replaceFirst("").trim();
-	}
+public class DateUtil {
+    private static 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);
 
-	public static long parseDateDiff(String time, boolean future) throws Exception
-	{
-		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(tl("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));
-		}
-		Calendar max = new GregorianCalendar();
-		max.add(Calendar.YEAR, 10);
-		if (c.after(max))
-		{
-			return max.getTimeInMillis();
-		}
-		return c.getTimeInMillis();
-	}
+    public static String removeTimePattern(String input) {
+        return timePattern.matcher(input).replaceFirst("").trim();
+    }
 
-	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 {
+        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(tl("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));
+        }
+        Calendar max = new GregorianCalendar();
+        max.add(Calendar.YEAR, 10);
+        if (c.after(max)) {
+            return max.getTimeInMillis();
+        }
+        return c.getTimeInMillis();
+    }
 
-	public static String formatDateDiff(long date)
-	{
-		Calendar c = new GregorianCalendar();
-		c.setTimeInMillis(date);
-		Calendar now = new GregorianCalendar();
-		return DateUtil.formatDateDiff(now, c);
-	}
+    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 String formatDateDiff(Calendar fromDate, Calendar toDate)
-	{
-		boolean future = false;
-		if (toDate.equals(fromDate))
-		{
-			return tl("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[]
-		{
-			tl("year"), tl("years"), tl("month"), tl("months"), tl("day"), tl("days"), tl("hour"), tl("hours"), tl("minute"), tl("minutes"), tl("second"), tl("seconds")
-		};
-		int accuracy = 0;
-		for (int i = 0; i < types.length; i++)
-		{
-			if (accuracy > 2)
-			{
-				break;
-			}
-			int diff = dateDiff(types[i], fromDate, toDate, future);
-			if (diff > 0)
-			{
-				accuracy++;
-				sb.append(" ").append(diff).append(" ").append(names[i * 2 + (diff > 1 ? 1 : 0)]);
-			}
-		}
-		if (sb.length() == 0)
-		{
-			return "now";
-		}
-		return sb.toString().trim();
-	}
+    public static String formatDateDiff(long date) {
+        Calendar c = new GregorianCalendar();
+        c.setTimeInMillis(date);
+        Calendar now = new GregorianCalendar();
+        return DateUtil.formatDateDiff(now, c);
+    }
+
+    public static String formatDateDiff(Calendar fromDate, Calendar toDate) {
+        boolean future = false;
+        if (toDate.equals(fromDate)) {
+            return tl("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[]{tl("year"), tl("years"), tl("month"), tl("months"), tl("day"), tl("days"), tl("hour"), tl("hours"), tl("minute"), tl("minutes"), tl("second"), tl("seconds")};
+        int accuracy = 0;
+        for (int i = 0; i < types.length; i++) {
+            if (accuracy > 2) {
+                break;
+            }
+            int diff = dateDiff(types[i], fromDate, toDate, future);
+            if (diff > 0) {
+                accuracy++;
+                sb.append(" ").append(diff).append(" ").append(names[i * 2 + (diff > 1 ? 1 : 0)]);
+            }
+        }
+        if (sb.length() == 0) {
+            return "now";
+        }
+        return sb.toString().trim();
+    }
 }
diff --git a/Essentials/src/com/earth2me/essentials/utils/DescParseTickFormat.java b/Essentials/src/com/earth2me/essentials/utils/DescParseTickFormat.java
index f2087f914..07b7d8894 100644
--- a/Essentials/src/com/earth2me/essentials/utils/DescParseTickFormat.java
+++ b/Essentials/src/com/earth2me/essentials/utils/DescParseTickFormat.java
@@ -1,292 +1,248 @@
 package com.earth2me.essentials.utils;
 
-import static com.earth2me.essentials.I18n.tl;
 import java.text.SimpleDateFormat;
 import java.util.*;
 
+import static com.earth2me.essentials.I18n.tl;
+
 
 /**
  * This utility class is used for converting between the ingame time in ticks to ingame time as a friendly string. Note
  * that the time is INGAME.
- *
+ * 

* http://www.minecraftwiki.net/wiki/Day/night_cycle * * @author Olof Larsson */ -public final class DescParseTickFormat -{ - // ============================================ - // First some information vars. TODO: Should this be in a config file? - // -------------------------------------------- - 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:mm aa", Locale.ENGLISH); +public final class DescParseTickFormat { + // ============================================ + // First some information vars. TODO: Should this be in a config file? + // -------------------------------------------- + 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:mm aa", Locale.ENGLISH); - static - { - SDFTwentyFour.setTimeZone(TimeZone.getTimeZone("GMT")); - SDFTwelve.setTimeZone(TimeZone.getTimeZone("GMT")); + static { + SDFTwentyFour.setTimeZone(TimeZone.getTimeZone("GMT")); + SDFTwelve.setTimeZone(TimeZone.getTimeZone("GMT")); - nameToTicks.put("sunrise", 23000); - nameToTicks.put("dawn", 23000); + nameToTicks.put("sunrise", 23000); + nameToTicks.put("dawn", 23000); - nameToTicks.put("daystart", 0); - nameToTicks.put("day", 0); + nameToTicks.put("daystart", 0); + nameToTicks.put("day", 0); - nameToTicks.put("morning", 1000); + nameToTicks.put("morning", 1000); - nameToTicks.put("midday", 6000); - nameToTicks.put("noon", 6000); + nameToTicks.put("midday", 6000); + nameToTicks.put("noon", 6000); - nameToTicks.put("afternoon", 9000); + nameToTicks.put("afternoon", 9000); - nameToTicks.put("sunset", 12000); - nameToTicks.put("dusk", 12000); - nameToTicks.put("sundown", 12000); - nameToTicks.put("nightfall", 12000); + 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("nightstart", 14000); + nameToTicks.put("night", 14000); - nameToTicks.put("midnight", 18000); + nameToTicks.put("midnight", 18000); - resetAliases.add("reset"); - resetAliases.add("normal"); - resetAliases.add("default"); - } + resetAliases.add("reset"); + resetAliases.add("normal"); + resetAliases.add("default"); + } - // ============================================ - 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:]", ""); + // ============================================ + 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 (NumberFormatException e) - { - } + // Detect ticks format + try { + return parseTicks(desc); + } catch (NumberFormatException e) { + } - // Detect 24-hour format - try - { - return parse24(desc); - } - catch (NumberFormatException e) - { - } + // Detect 24-hour format + try { + return parse24(desc); + } catch (NumberFormatException e) { + } - // Detect 12-hour format - try - { - return parse12(desc); - } - catch (NumberFormatException e) - { - } + // Detect 12-hour format + try { + return parse12(desc); + } catch (NumberFormatException e) { + } - // Detect aliases - try - { - return parseAlias(desc); - } - catch (NumberFormatException e) - { - } + // Detect aliases + try { + return parseAlias(desc); + } catch (NumberFormatException 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(); - } + // Well we failed to understand... + throw new NumberFormatException(); + } - desc = desc.replaceAll("[^0-9]", ""); + public static long parseTicks(String desc) throws NumberFormatException { + if (!desc.matches("^[0-9]+ti?c?k?s?$")) { + throw new NumberFormatException(); + } - return Long.parseLong(desc) % 24000; - } + desc = desc.replaceAll("[^0-9]", ""); - public static long parse24(String desc) throws NumberFormatException - { - if (!desc.matches("^[0-9]{2}[^0-9]?[0-9]{2}$")) - { - throw new NumberFormatException(); - } + return Long.parseLong(desc) % 24000; + } - desc = desc.toLowerCase(Locale.ENGLISH).replaceAll("[^0-9]", ""); + public static long parse24(String desc) throws NumberFormatException { + if (!desc.matches("^[0-9]{2}[^0-9]?[0-9]{2}$")) { + throw new NumberFormatException(); + } - if (desc.length() != 4) - { - throw new NumberFormatException(); - } + desc = desc.toLowerCase(Locale.ENGLISH).replaceAll("[^0-9]", ""); - final int hours = Integer.parseInt(desc.substring(0, 2)); - final int minutes = Integer.parseInt(desc.substring(2, 4)); + if (desc.length() != 4) { + throw new NumberFormatException(); + } - return hoursMinutesToTicks(hours, minutes); - } + final int hours = Integer.parseInt(desc.substring(0, 2)); + final int minutes = Integer.parseInt(desc.substring(2, 4)); - 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(); - } + return hoursMinutesToTicks(hours, minutes); + } - int hours = 0; - int minutes = 0; + 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(); + } - desc = desc.toLowerCase(Locale.ENGLISH); - String parsetime = desc.replaceAll("[^0-9]", ""); + int hours = 0; + int minutes = 0; - if (parsetime.length() > 4) - { - throw new NumberFormatException(); - } + desc = desc.toLowerCase(Locale.ENGLISH); + String parsetime = desc.replaceAll("[^0-9]", ""); - 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 (parsetime.length() > 4) { + throw new NumberFormatException(); + } - if (desc.endsWith("pm") && hours != 12) - { - hours += 12; - } + 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("am") && hours == 12) - { - hours -= 12; - } + if (desc.endsWith("pm") && hours != 12) { + hours += 12; + } - return hoursMinutesToTicks(hours, minutes); - } + if (desc.endsWith("am") && hours == 12) { + hours -= 12; + } - public static long hoursMinutesToTicks(final int hours, final int minutes) - { - long ret = ticksAtMidnight; - ret += (hours) * ticksPerHour; + return hoursMinutesToTicks(hours, minutes); + } - ret += (minutes / 60.0) * ticksPerHour; + public static long hoursMinutesToTicks(final int hours, final int minutes) { + long ret = ticksAtMidnight; + ret += (hours) * ticksPerHour; - ret %= ticksPerDay; - return ret; - } + ret += (minutes / 60.0) * ticksPerHour; - public static long parseAlias(final String desc) throws NumberFormatException - { - final Integer ret = nameToTicks.get(desc); - if (ret == null) - { - throw new NumberFormatException(); - } + ret %= ticksPerDay; + return ret; + } - return ret; - } + public static long parseAlias(final String desc) throws NumberFormatException { + final Integer ret = nameToTicks.get(desc); + if (ret == null) { + throw new NumberFormatException(); + } - public static boolean meansReset(final String desc) - { - return resetAliases.contains(desc); - } + return ret; + } - // ============================================ - public static String format(final long ticks) - { - return tl("timeFormat", format24(ticks), format12(ticks), formatTicks(ticks)); - } - public static String formatTicks(final long ticks) - { - return (ticks % ticksPerDay) + "ticks"; - } + public static boolean meansReset(final String desc) { + return resetAliases.contains(desc); + } - public static String format24(final long ticks) - { - synchronized (SDFTwentyFour) - { - return formatDateFormat(ticks, SDFTwentyFour); - } - } + // ============================================ + public static String format(final long ticks) { + return tl("timeFormat", format24(ticks), format12(ticks), formatTicks(ticks)); + } - public static String format12(final long ticks) - { - synchronized (SDFTwelve) - { - return formatDateFormat(ticks, SDFTwelve); - } - } + public static String formatTicks(final long ticks) { + return (ticks % ticksPerDay) + "ticks"; + } - public static String formatDateFormat(final long ticks, final SimpleDateFormat format) - { - final Date date = ticksToDate(ticks); - return format.format(date); - } + public static String format24(final long ticks) { + synchronized (SDFTwentyFour) { + return formatDateFormat(ticks, SDFTwentyFour); + } + } - 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; + public static String format12(final long ticks) { + synchronized (SDFTwelve) { + return formatDateFormat(ticks, SDFTwelve); + } + } - // How many ingame days have passed since the server start? - final long days = ticks / ticksPerDay; - ticks -= days * ticksPerDay; + public static String formatDateFormat(final long ticks, final SimpleDateFormat format) { + final Date date = ticksToDate(ticks); + return format.format(date); + } - // How many hours on the last day? - final long hours = ticks / ticksPerHour; - ticks -= hours * ticksPerHour; + 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 minutes on the last day? - final long minutes = (long)Math.floor(ticks / ticksPerMinute); - final double dticks = ticks - minutes * ticksPerMinute; + // How many ingame days have passed since the server start? + final long days = ticks / ticksPerDay; + ticks -= days * ticksPerDay; - // How many seconds on the last day? - final long seconds = (long)Math.floor(dticks / ticksPerSecond); + // How many hours on the last day? + final long hours = ticks / ticksPerHour; + ticks -= hours * ticksPerHour; - // 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); + // How many minutes on the last day? + final long minutes = (long) Math.floor(ticks / ticksPerMinute); + final double dticks = ticks - minutes * ticksPerMinute; - // 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. + // How many seconds on the last day? + final long seconds = (long) Math.floor(dticks / ticksPerSecond); - return cal.getTime(); - } + // 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); - private DescParseTickFormat() - { - } + // 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(); + } + + private DescParseTickFormat() { + } } diff --git a/Essentials/src/com/earth2me/essentials/utils/FormatUtil.java b/Essentials/src/com/earth2me/essentials/utils/FormatUtil.java index 8c68d746b..46cc3509e 100644 --- a/Essentials/src/com/earth2me/essentials/utils/FormatUtil.java +++ b/Essentials/src/com/earth2me/essentials/utils/FormatUtil.java @@ -1,152 +1,122 @@ package com.earth2me.essentials.utils; -import java.util.regex.Pattern; import net.ess3.api.IUser; +import java.util.regex.Pattern; -public class FormatUtil -{ - //Vanilla patterns used to strip existing formats - static final transient Pattern VANILLA_PATTERN = Pattern.compile("\u00a7+[0-9A-FK-ORa-fk-or]?"); - static final transient Pattern VANILLA_COLOR_PATTERN = Pattern.compile("\u00a7+[0-9A-Fa-f]"); - static final transient Pattern VANILLA_MAGIC_PATTERN = Pattern.compile("\u00a7+[Kk]"); - static final transient Pattern VANILLA_FORMAT_PATTERN = Pattern.compile("\u00a7+[L-ORl-or]"); - //Essentials '&' convention colour codes - static final transient Pattern REPLACE_ALL_PATTERN = Pattern.compile("(? HOLLOW_MATERIALS = new HashSet(); - private static final HashSet TRANSPARENT_MATERIALS = new HashSet(); - - static - { - HOLLOW_MATERIALS.add(Material.AIR.getId()); - HOLLOW_MATERIALS.add(Material.SAPLING.getId()); - HOLLOW_MATERIALS.add(Material.POWERED_RAIL.getId()); - HOLLOW_MATERIALS.add(Material.DETECTOR_RAIL.getId()); - HOLLOW_MATERIALS.add(Material.LONG_GRASS.getId()); - HOLLOW_MATERIALS.add(Material.DEAD_BUSH.getId()); - HOLLOW_MATERIALS.add(Material.YELLOW_FLOWER.getId()); - HOLLOW_MATERIALS.add(Material.RED_ROSE.getId()); - HOLLOW_MATERIALS.add(Material.BROWN_MUSHROOM.getId()); - HOLLOW_MATERIALS.add(Material.RED_MUSHROOM.getId()); - HOLLOW_MATERIALS.add(Material.TORCH.getId()); - HOLLOW_MATERIALS.add(Material.REDSTONE_WIRE.getId()); - HOLLOW_MATERIALS.add(Material.SEEDS.getId()); - HOLLOW_MATERIALS.add(Material.SIGN_POST.getId()); - HOLLOW_MATERIALS.add(Material.WOODEN_DOOR.getId()); - HOLLOW_MATERIALS.add(Material.LADDER.getId()); - HOLLOW_MATERIALS.add(Material.RAILS.getId()); - HOLLOW_MATERIALS.add(Material.WALL_SIGN.getId()); - HOLLOW_MATERIALS.add(Material.LEVER.getId()); - HOLLOW_MATERIALS.add(Material.STONE_PLATE.getId()); - HOLLOW_MATERIALS.add(Material.IRON_DOOR_BLOCK.getId()); - HOLLOW_MATERIALS.add(Material.WOOD_PLATE.getId()); - HOLLOW_MATERIALS.add(Material.REDSTONE_TORCH_OFF.getId()); - HOLLOW_MATERIALS.add(Material.REDSTONE_TORCH_ON.getId()); - HOLLOW_MATERIALS.add(Material.STONE_BUTTON.getId()); - HOLLOW_MATERIALS.add(Material.SNOW.getId()); - HOLLOW_MATERIALS.add(Material.SUGAR_CANE_BLOCK.getId()); - HOLLOW_MATERIALS.add(Material.DIODE_BLOCK_OFF.getId()); - HOLLOW_MATERIALS.add(Material.DIODE_BLOCK_ON.getId()); - HOLLOW_MATERIALS.add(Material.PUMPKIN_STEM.getId()); - HOLLOW_MATERIALS.add(Material.MELON_STEM.getId()); - HOLLOW_MATERIALS.add(Material.VINE.getId()); - HOLLOW_MATERIALS.add(Material.FENCE_GATE.getId()); - HOLLOW_MATERIALS.add(Material.WATER_LILY.getId()); - HOLLOW_MATERIALS.add(Material.NETHER_WARTS.getId()); - HOLLOW_MATERIALS.add(Material.CARPET.getId()); - - for (Integer integer : HOLLOW_MATERIALS) - { - TRANSPARENT_MATERIALS.add(integer.byteValue()); - } - TRANSPARENT_MATERIALS.add((byte)Material.WATER.getId()); - TRANSPARENT_MATERIALS.add((byte)Material.STATIONARY_WATER.getId()); - } - public static final int RADIUS = 3; - public static final Vector3D[] VOLUME; - - 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; - } +import static com.earth2me.essentials.I18n.tl; - public static class Vector3D - { - public int x; - public int y; - public int z; +public class LocationUtil { + // The player can stand inside these materials + public static final Set HOLLOW_MATERIALS = new HashSet(); + private static final HashSet TRANSPARENT_MATERIALS = new HashSet(); - public Vector3D(int x, int y, int z) - { - this.x = x; - this.y = y; - this.z = z; - } - } + static { + HOLLOW_MATERIALS.add(Material.AIR.getId()); + HOLLOW_MATERIALS.add(Material.SAPLING.getId()); + HOLLOW_MATERIALS.add(Material.POWERED_RAIL.getId()); + HOLLOW_MATERIALS.add(Material.DETECTOR_RAIL.getId()); + HOLLOW_MATERIALS.add(Material.LONG_GRASS.getId()); + HOLLOW_MATERIALS.add(Material.DEAD_BUSH.getId()); + HOLLOW_MATERIALS.add(Material.YELLOW_FLOWER.getId()); + HOLLOW_MATERIALS.add(Material.RED_ROSE.getId()); + HOLLOW_MATERIALS.add(Material.BROWN_MUSHROOM.getId()); + HOLLOW_MATERIALS.add(Material.RED_MUSHROOM.getId()); + HOLLOW_MATERIALS.add(Material.TORCH.getId()); + HOLLOW_MATERIALS.add(Material.REDSTONE_WIRE.getId()); + HOLLOW_MATERIALS.add(Material.SEEDS.getId()); + HOLLOW_MATERIALS.add(Material.SIGN_POST.getId()); + HOLLOW_MATERIALS.add(Material.WOODEN_DOOR.getId()); + HOLLOW_MATERIALS.add(Material.LADDER.getId()); + HOLLOW_MATERIALS.add(Material.RAILS.getId()); + HOLLOW_MATERIALS.add(Material.WALL_SIGN.getId()); + HOLLOW_MATERIALS.add(Material.LEVER.getId()); + HOLLOW_MATERIALS.add(Material.STONE_PLATE.getId()); + HOLLOW_MATERIALS.add(Material.IRON_DOOR_BLOCK.getId()); + HOLLOW_MATERIALS.add(Material.WOOD_PLATE.getId()); + HOLLOW_MATERIALS.add(Material.REDSTONE_TORCH_OFF.getId()); + HOLLOW_MATERIALS.add(Material.REDSTONE_TORCH_ON.getId()); + HOLLOW_MATERIALS.add(Material.STONE_BUTTON.getId()); + HOLLOW_MATERIALS.add(Material.SNOW.getId()); + HOLLOW_MATERIALS.add(Material.SUGAR_CANE_BLOCK.getId()); + HOLLOW_MATERIALS.add(Material.DIODE_BLOCK_OFF.getId()); + HOLLOW_MATERIALS.add(Material.DIODE_BLOCK_ON.getId()); + HOLLOW_MATERIALS.add(Material.PUMPKIN_STEM.getId()); + HOLLOW_MATERIALS.add(Material.MELON_STEM.getId()); + HOLLOW_MATERIALS.add(Material.VINE.getId()); + HOLLOW_MATERIALS.add(Material.FENCE_GATE.getId()); + HOLLOW_MATERIALS.add(Material.WATER_LILY.getId()); + HOLLOW_MATERIALS.add(Material.NETHER_WARTS.getId()); + HOLLOW_MATERIALS.add(Material.CARPET.getId()); - static - { - List pos = new ArrayList(); - for (int x = -RADIUS; x <= RADIUS; x++) - { - for (int y = -RADIUS; y <= RADIUS; y++) - { - for (int z = -RADIUS; z <= RADIUS; z++) - { - pos.add(new Vector3D(x, y, z)); - } - } - } - Collections.sort( - pos, new Comparator() - { - @Override - public int compare(Vector3D a, Vector3D b) - { - return (a.x * a.x + a.y * a.y + a.z * a.z) - (b.x * b.x + b.y * b.y + b.z * b.z); - } - }); - VOLUME = pos.toArray(new Vector3D[0]); - } + for (Integer integer : HOLLOW_MATERIALS) { + TRANSPARENT_MATERIALS.add(integer.byteValue()); + } + TRANSPARENT_MATERIALS.add((byte) Material.WATER.getId()); + TRANSPARENT_MATERIALS.add((byte) Material.STATIONARY_WATER.getId()); + } - public static Location getTarget(final LivingEntity entity) throws Exception - { - final Block block = entity.getTargetBlock(TRANSPARENT_MATERIALS, 300); - if (block == null) - { - throw new Exception("Not targeting a block"); - } - return block.getLocation(); - } + public static final int RADIUS = 3; + public static final Vector3D[] VOLUME; - static boolean isBlockAboveAir(final World world, final int x, final int y, final int z) - { - if (y > world.getMaxHeight()) - { - return true; - } - return HOLLOW_MATERIALS.contains(world.getBlockAt(x, y - 1, z).getType().getId()); - } + 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; + } - public static boolean isBlockUnsafeForUser(final IUser user, final World world, final int x, final int y, final int z) - { - if (user.getBase().isOnline() && world.equals(user.getBase().getWorld()) - && (user.getBase().getGameMode() == GameMode.CREATIVE || user.isGodModeEnabled()) - && user.getBase().getAllowFlight()) - { - return false; - } - if (isBlockDamaging(world, x, y, z)) - { - return true; - } - return isBlockAboveAir(world, x, y, z); - } + public static class Vector3D { + public int x; + public int y; + public int z; - public static boolean isBlockUnsafe(final World world, final int x, final int y, final int z) - { - if (isBlockDamaging(world, x, y, z)) - { - return true; - } - return isBlockAboveAir(world, x, y, z); - } + public Vector3D(int x, int y, int z) { + this.x = x; + this.y = y; + this.z = z; + } + } - public static boolean isBlockDamaging(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 (below.getType() == Material.BED_BLOCK) - { - return true; - } - if ((!HOLLOW_MATERIALS.contains(world.getBlockAt(x, y, z).getType().getId())) || (!HOLLOW_MATERIALS.contains(world.getBlockAt(x, y + 1, z).getType().getId()))) - { - return true; - } - return false; - } + static { + List pos = new ArrayList(); + for (int x = -RADIUS; x <= RADIUS; x++) { + for (int y = -RADIUS; y <= RADIUS; y++) { + for (int z = -RADIUS; z <= RADIUS; z++) { + pos.add(new Vector3D(x, y, z)); + } + } + } + Collections.sort(pos, new Comparator() { + @Override + public int compare(Vector3D a, Vector3D b) { + return (a.x * a.x + a.y * a.y + a.z * a.z) - (b.x * b.x + b.y * b.y + b.z * b.z); + } + }); + VOLUME = pos.toArray(new Vector3D[0]); + } - // Not needed if using getSafeDestination(loc) - public static Location getRoundedDestination(final Location loc) - { - final World world = loc.getWorld(); - int x = loc.getBlockX(); - int y = (int)Math.round(loc.getY()); - int z = loc.getBlockZ(); - return new Location(world, x + 0.5, y, z + 0.5, loc.getYaw(), loc.getPitch()); - } + public static Location getTarget(final LivingEntity entity) throws Exception { + final Block block = entity.getTargetBlock(TRANSPARENT_MATERIALS, 300); + if (block == null) { + throw new Exception("Not targeting a block"); + } + return block.getLocation(); + } - public static Location getSafeDestination(final IUser user, final Location loc) throws Exception - { - if (user.getBase().isOnline() && loc.getWorld().equals(user.getBase().getWorld()) - && (user.getBase().getGameMode() == GameMode.CREATIVE || user.isGodModeEnabled()) - && user.getBase().getAllowFlight()) - { - if (shouldFly(loc)) - { - user.getBase().setFlying(true); - } - return getRoundedDestination(loc); - } - return getSafeDestination(loc); - } + static boolean isBlockAboveAir(final World world, final int x, final int y, final int z) { + if (y > world.getMaxHeight()) { + return true; + } + return HOLLOW_MATERIALS.contains(world.getBlockAt(x, y - 1, z).getType().getId()); + } - public static Location getSafeDestination(final Location loc) throws Exception - { - if (loc == null || loc.getWorld() == null) - { - throw new Exception(tl("destinationNotSet")); - } - final World world = loc.getWorld(); - int x = loc.getBlockX(); - int y = (int)Math.round(loc.getY()); - int z = loc.getBlockZ(); - final int origX = x; - final int origY = y; - final int origZ = z; - while (isBlockAboveAir(world, x, y, z)) - { - y -= 1; - if (y < 0) - { - y = origY; - break; - } - } - if (isBlockUnsafe(world, x, y, z)) - { - x = Math.round(loc.getX()) == origX ? x - 1 : x + 1; - z = Math.round(loc.getZ()) == origZ ? z - 1 : z + 1; - } - int i = 0; - while (isBlockUnsafe(world, x, y, z)) - { - i++; - if (i >= VOLUME.length) - { - x = origX; - y = origY + RADIUS; - z = origZ; - break; - } - x = origX + VOLUME[i].x; - y = origY + VOLUME[i].y; - z = origZ + VOLUME[i].z; - } - while (isBlockUnsafe(world, x, y, z)) - { - y += 1; - if (y >= world.getMaxHeight()) - { - x += 1; - break; - } - } - while (isBlockUnsafe(world, x, y, z)) - { - y -= 1; - if (y <= 1) - { - x += 1; - y = world.getHighestBlockYAt(x, z); - if (x - 48 > loc.getBlockX()) - { - throw new Exception(tl("holeInFloor")); - } - } - } - return new Location(world, x + 0.5, y, z + 0.5, loc.getYaw(), loc.getPitch()); - } + public static boolean isBlockUnsafeForUser(final IUser user, final World world, final int x, final int y, final int z) { + if (user.getBase().isOnline() && world.equals(user.getBase().getWorld()) && (user.getBase().getGameMode() == GameMode.CREATIVE || user.isGodModeEnabled()) && user.getBase().getAllowFlight()) { + return false; + } - public static boolean shouldFly(Location loc) - { - final World world = loc.getWorld(); - final int x = loc.getBlockX(); - int y = (int)Math.round(loc.getY()); - final int z = loc.getBlockZ(); - int count = 0; - while (LocationUtil.isBlockUnsafe(world, x, y, z) && y > -1) - { - y--; - count++; - if (count > 2) - { - return true; - } - } + if (isBlockDamaging(world, x, y, z)) { + return true; + } + return isBlockAboveAir(world, x, y, z); + } - return y < 0 ? true : false; - } + public static boolean isBlockUnsafe(final World world, final int x, final int y, final int z) { + if (isBlockDamaging(world, x, y, z)) { + return true; + } + return isBlockAboveAir(world, x, y, z); + } + + public static boolean isBlockDamaging(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 (below.getType() == Material.BED_BLOCK) { + return true; + } + if ((!HOLLOW_MATERIALS.contains(world.getBlockAt(x, y, z).getType().getId())) || (!HOLLOW_MATERIALS.contains(world.getBlockAt(x, y + 1, z).getType().getId()))) { + return true; + } + return false; + } + + // Not needed if using getSafeDestination(loc) + public static Location getRoundedDestination(final Location loc) { + final World world = loc.getWorld(); + int x = loc.getBlockX(); + int y = (int) Math.round(loc.getY()); + int z = loc.getBlockZ(); + return new Location(world, x + 0.5, y, z + 0.5, loc.getYaw(), loc.getPitch()); + } + + public static Location getSafeDestination(final IUser user, final Location loc) throws Exception { + if (user.getBase().isOnline() && loc.getWorld().equals(user.getBase().getWorld()) && (user.getBase().getGameMode() == GameMode.CREATIVE || user.isGodModeEnabled()) && user.getBase().getAllowFlight()) { + if (shouldFly(loc)) { + user.getBase().setFlying(true); + } + return getRoundedDestination(loc); + } + return getSafeDestination(loc); + } + + public static Location getSafeDestination(final Location loc) throws Exception { + if (loc == null || loc.getWorld() == null) { + throw new Exception(tl("destinationNotSet")); + } + final World world = loc.getWorld(); + int x = loc.getBlockX(); + int y = (int) Math.round(loc.getY()); + int z = loc.getBlockZ(); + final int origX = x; + final int origY = y; + final int origZ = z; + while (isBlockAboveAir(world, x, y, z)) { + y -= 1; + if (y < 0) { + y = origY; + break; + } + } + if (isBlockUnsafe(world, x, y, z)) { + x = Math.round(loc.getX()) == origX ? x - 1 : x + 1; + z = Math.round(loc.getZ()) == origZ ? z - 1 : z + 1; + } + int i = 0; + while (isBlockUnsafe(world, x, y, z)) { + i++; + if (i >= VOLUME.length) { + x = origX; + y = origY + RADIUS; + z = origZ; + break; + } + x = origX + VOLUME[i].x; + y = origY + VOLUME[i].y; + z = origZ + VOLUME[i].z; + } + while (isBlockUnsafe(world, x, y, z)) { + y += 1; + if (y >= world.getMaxHeight()) { + x += 1; + break; + } + } + while (isBlockUnsafe(world, x, y, z)) { + y -= 1; + if (y <= 1) { + x += 1; + y = world.getHighestBlockYAt(x, z); + if (x - 48 > loc.getBlockX()) { + throw new Exception(tl("holeInFloor")); + } + } + } + return new Location(world, x + 0.5, y, z + 0.5, loc.getYaw(), loc.getPitch()); + } + + public static boolean shouldFly(Location loc) { + final World world = loc.getWorld(); + final int x = loc.getBlockX(); + int y = (int) Math.round(loc.getY()); + final int z = loc.getBlockZ(); + int count = 0; + while (LocationUtil.isBlockUnsafe(world, x, y, z) && y > -1) { + y--; + count++; + if (count > 2) { + return true; + } + } + + return y < 0 ? true : false; + } } diff --git a/Essentials/src/com/earth2me/essentials/utils/NumberUtil.java b/Essentials/src/com/earth2me/essentials/utils/NumberUtil.java index 2c03d33da..dae7a3fcb 100644 --- a/Essentials/src/com/earth2me/essentials/utils/NumberUtil.java +++ b/Essentials/src/com/earth2me/essentials/utils/NumberUtil.java @@ -1,56 +1,48 @@ package com.earth2me.essentials.utils; -import static com.earth2me.essentials.I18n.tl; +import net.ess3.api.IEssentials; + import java.math.BigDecimal; import java.math.RoundingMode; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.Locale; -import net.ess3.api.IEssentials; + +import static com.earth2me.essentials.I18n.tl; -public class NumberUtil -{ - static DecimalFormat twoDPlaces = new DecimalFormat("#,###.##"); - static DecimalFormat currencyFormat = new DecimalFormat("#0.00", DecimalFormatSymbols.getInstance(Locale.US)); +public class NumberUtil { + static DecimalFormat twoDPlaces = new DecimalFormat("#,###.##"); + static DecimalFormat currencyFormat = new DecimalFormat("#0.00", DecimalFormatSymbols.getInstance(Locale.US)); - public static String shortCurrency(final BigDecimal value, final IEssentials ess) - { - return ess.getSettings().getCurrencySymbol() + formatAsCurrency(value); - } + public static String shortCurrency(final BigDecimal value, final IEssentials ess) { + return ess.getSettings().getCurrencySymbol() + formatAsCurrency(value); + } - public static String formatDouble(final double value) - { - twoDPlaces.setRoundingMode(RoundingMode.HALF_UP); - return twoDPlaces.format(value); - } + public static String formatDouble(final double value) { + twoDPlaces.setRoundingMode(RoundingMode.HALF_UP); + return twoDPlaces.format(value); + } - public static String formatAsCurrency(final BigDecimal value) - { - currencyFormat.setRoundingMode(RoundingMode.FLOOR); - String str = currencyFormat.format(value); - if (str.endsWith(".00")) - { - str = str.substring(0, str.length() - 3); - } - return str; - } + public static String formatAsCurrency(final BigDecimal value) { + currencyFormat.setRoundingMode(RoundingMode.FLOOR); + String str = currencyFormat.format(value); + if (str.endsWith(".00")) { + str = str.substring(0, str.length() - 3); + } + return str; + } - public static String displayCurrency(final BigDecimal value, final IEssentials ess) - { - return tl("currency", ess.getSettings().getCurrencySymbol(), formatAsCurrency(value)); - } + public static String displayCurrency(final BigDecimal value, final IEssentials ess) { + return tl("currency", ess.getSettings().getCurrencySymbol(), formatAsCurrency(value)); + } - public static boolean isInt(final String sInt) - { - try - { - Integer.parseInt(sInt); - } - catch (NumberFormatException e) - { - return false; - } - return true; - } + public static boolean isInt(final String sInt) { + try { + Integer.parseInt(sInt); + } catch (NumberFormatException e) { + return false; + } + return true; + } } diff --git a/Essentials/src/com/earth2me/essentials/utils/StringUtil.java b/Essentials/src/com/earth2me/essentials/utils/StringUtil.java index 6bb91313e..4f1ee1f6f 100644 --- a/Essentials/src/com/earth2me/essentials/utils/StringUtil.java +++ b/Essentials/src/com/earth2me/essentials/utils/StringUtil.java @@ -1,101 +1,78 @@ package com.earth2me.essentials.utils; -import java.util.*; +import java.util.Collection; +import java.util.Locale; import java.util.regex.Pattern; -public class StringUtil -{ - private static final Pattern INVALIDFILECHARS = Pattern.compile("[^a-z0-9-]"); - private static final Pattern STRICTINVALIDCHARS = Pattern.compile("[^a-z0-9]"); - private static final Pattern INVALIDCHARS = Pattern.compile("[^\t\n\r\u0020-\u007E\u0085\u00A0-\uD7FF\uE000-\uFFFC]"); +public class StringUtil { + private static final Pattern INVALIDFILECHARS = Pattern.compile("[^a-z0-9-]"); + private static final Pattern STRICTINVALIDCHARS = Pattern.compile("[^a-z0-9]"); + private static final Pattern INVALIDCHARS = Pattern.compile("[^\t\n\r\u0020-\u007E\u0085\u00A0-\uD7FF\uE000-\uFFFC]"); - //Used to clean file names before saving to disk - public static String sanitizeFileName(final String name) - { - return INVALIDFILECHARS.matcher(name.toLowerCase(Locale.ENGLISH)).replaceAll("_"); - } + //Used to clean file names before saving to disk + public static String sanitizeFileName(final String name) { + return INVALIDFILECHARS.matcher(name.toLowerCase(Locale.ENGLISH)).replaceAll("_"); + } - //Used to clean strings/names before saving as filenames/permissions - public static String safeString(final String string) - { - return STRICTINVALIDCHARS.matcher(string.toLowerCase(Locale.ENGLISH)).replaceAll("_"); - } + //Used to clean strings/names before saving as filenames/permissions + public static String safeString(final String string) { + return STRICTINVALIDCHARS.matcher(string.toLowerCase(Locale.ENGLISH)).replaceAll("_"); + } - //Less restrictive string sanitizing, when not used as perm or filename - public static String sanitizeString(final String string) - { - return INVALIDCHARS.matcher(string).replaceAll(""); - } + //Less restrictive string sanitizing, when not used as perm or filename + public static String sanitizeString(final String string) { + return INVALIDCHARS.matcher(string).replaceAll(""); + } - public static String joinList(Object... list) - { - return joinList(", ", list); - } + 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); - } + 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 String joinListSkip(String seperator, String skip, Object... list) - { - StringBuilder buf = new StringBuilder(); - for (Object each : list) - { - if (each.toString().equalsIgnoreCase(skip)) { - continue; - } - - 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(); + } - if (each instanceof Collection) - { - buf.append(joinListSkip(seperator, skip, ((Collection)each).toArray())); - } - else - { - try - { - buf.append(each.toString()); - } - catch (Exception e) - { - buf.append(each.toString()); - } - } - } - return buf.toString(); - } - - private StringUtil() - { - } + public static String joinListSkip(String seperator, String skip, Object... list) { + StringBuilder buf = new StringBuilder(); + for (Object each : list) { + if (each.toString().equalsIgnoreCase(skip)) { + continue; + } + + if (buf.length() > 0) { + buf.append(seperator); + } + + if (each instanceof Collection) { + buf.append(joinListSkip(seperator, skip, ((Collection) each).toArray())); + } else { + try { + buf.append(each.toString()); + } catch (Exception e) { + buf.append(each.toString()); + } + } + } + return buf.toString(); + } + + private StringUtil() { + } } diff --git a/Essentials/src/net/ess3/api/Economy.java b/Essentials/src/net/ess3/api/Economy.java index 283ef3722..f12572e10 100644 --- a/Essentials/src/net/ess3/api/Economy.java +++ b/Essentials/src/net/ess3/api/Economy.java @@ -1,7 +1,6 @@ package net.ess3.api; -public class Economy extends com.earth2me.essentials.api.Economy -{ - +public class Economy extends com.earth2me.essentials.api.Economy { + } diff --git a/Essentials/src/net/ess3/api/IEssentials.java b/Essentials/src/net/ess3/api/IEssentials.java index be5671176..17621415b 100644 --- a/Essentials/src/net/ess3/api/IEssentials.java +++ b/Essentials/src/net/ess3/api/IEssentials.java @@ -1,6 +1,5 @@ package net.ess3.api; -public interface IEssentials extends com.earth2me.essentials.IEssentials -{ - +public interface IEssentials extends com.earth2me.essentials.IEssentials { + } diff --git a/Essentials/src/net/ess3/api/II18n.java b/Essentials/src/net/ess3/api/II18n.java index 5bbe0e702..655746acf 100644 --- a/Essentials/src/net/ess3/api/II18n.java +++ b/Essentials/src/net/ess3/api/II18n.java @@ -1,7 +1,6 @@ package net.ess3.api; -public interface II18n extends com.earth2me.essentials.api.II18n -{ +public interface II18n extends com.earth2me.essentials.api.II18n { } diff --git a/Essentials/src/net/ess3/api/IItemDb.java b/Essentials/src/net/ess3/api/IItemDb.java index eb9afb3c5..b400d1740 100644 --- a/Essentials/src/net/ess3/api/IItemDb.java +++ b/Essentials/src/net/ess3/api/IItemDb.java @@ -1,7 +1,6 @@ package net.ess3.api; -public interface IItemDb extends com.earth2me.essentials.api.IItemDb -{ +public interface IItemDb extends com.earth2me.essentials.api.IItemDb { } diff --git a/Essentials/src/net/ess3/api/IJails.java b/Essentials/src/net/ess3/api/IJails.java index d36e4f76b..e6447ee89 100644 --- a/Essentials/src/net/ess3/api/IJails.java +++ b/Essentials/src/net/ess3/api/IJails.java @@ -1,7 +1,6 @@ package net.ess3.api; -public interface IJails extends com.earth2me.essentials.api.IJails -{ +public interface IJails extends com.earth2me.essentials.api.IJails { } diff --git a/Essentials/src/net/ess3/api/IReload.java b/Essentials/src/net/ess3/api/IReload.java index b706342e2..859528037 100644 --- a/Essentials/src/net/ess3/api/IReload.java +++ b/Essentials/src/net/ess3/api/IReload.java @@ -1,7 +1,6 @@ package net.ess3.api; -public interface IReload extends com.earth2me.essentials.api.IReload -{ +public interface IReload extends com.earth2me.essentials.api.IReload { } diff --git a/Essentials/src/net/ess3/api/ISettings.java b/Essentials/src/net/ess3/api/ISettings.java index 256cf1635..34e9f8763 100644 --- a/Essentials/src/net/ess3/api/ISettings.java +++ b/Essentials/src/net/ess3/api/ISettings.java @@ -1,7 +1,6 @@ package net.ess3.api; -public interface ISettings extends com.earth2me.essentials.ISettings -{ +public interface ISettings extends com.earth2me.essentials.ISettings { } diff --git a/Essentials/src/net/ess3/api/ITeleport.java b/Essentials/src/net/ess3/api/ITeleport.java index 967b38ba3..65c680761 100644 --- a/Essentials/src/net/ess3/api/ITeleport.java +++ b/Essentials/src/net/ess3/api/ITeleport.java @@ -1,7 +1,6 @@ package net.ess3.api; -public interface ITeleport extends com.earth2me.essentials.api.ITeleport -{ +public interface ITeleport extends com.earth2me.essentials.api.ITeleport { } diff --git a/Essentials/src/net/ess3/api/IUser.java b/Essentials/src/net/ess3/api/IUser.java index b68c6e5cf..aae8900a7 100644 --- a/Essentials/src/net/ess3/api/IUser.java +++ b/Essentials/src/net/ess3/api/IUser.java @@ -1,8 +1,6 @@ package net.ess3.api; - -public interface IUser extends com.earth2me.essentials.IUser -{ +public interface IUser extends com.earth2me.essentials.IUser { } diff --git a/Essentials/src/net/ess3/api/IWarps.java b/Essentials/src/net/ess3/api/IWarps.java index c71ef7d7f..4a9b979e7 100644 --- a/Essentials/src/net/ess3/api/IWarps.java +++ b/Essentials/src/net/ess3/api/IWarps.java @@ -1,7 +1,6 @@ package net.ess3.api; -public interface IWarps extends com.earth2me.essentials.api.IWarps -{ +public interface IWarps extends com.earth2me.essentials.api.IWarps { } diff --git a/Essentials/src/net/ess3/api/InvalidNameException.java b/Essentials/src/net/ess3/api/InvalidNameException.java index 013ac7ef0..8c78dcca9 100644 --- a/Essentials/src/net/ess3/api/InvalidNameException.java +++ b/Essentials/src/net/ess3/api/InvalidNameException.java @@ -1,16 +1,14 @@ package net.ess3.api; -public class InvalidNameException extends Exception -{ - /** - * NOTE: This is not implemented yet, just here for future 3.x api support - * Allow serialization of the InvalidNameException exception - */ - private static final long serialVersionUID = 1485321420293663139L; +public class InvalidNameException extends Exception { + /** + * NOTE: This is not implemented yet, just here for future 3.x api support Allow serialization of the + * InvalidNameException exception + */ + private static final long serialVersionUID = 1485321420293663139L; - public InvalidNameException(Throwable thrwbl) - { - super(thrwbl); - } + public InvalidNameException(Throwable thrwbl) { + super(thrwbl); + } } diff --git a/Essentials/src/net/ess3/api/InvalidWorldException.java b/Essentials/src/net/ess3/api/InvalidWorldException.java index 210b07762..f43b6e7c1 100644 --- a/Essentials/src/net/ess3/api/InvalidWorldException.java +++ b/Essentials/src/net/ess3/api/InvalidWorldException.java @@ -3,18 +3,15 @@ package net.ess3.api; import static com.earth2me.essentials.I18n.tl; -public class InvalidWorldException extends Exception -{ - private final String world; +public class InvalidWorldException extends Exception { + private final String world; - public InvalidWorldException(final String world) - { - super(tl("invalidWorld")); - this.world = world; - } + public InvalidWorldException(final String world) { + super(tl("invalidWorld")); + this.world = world; + } - public String getWorld() - { - return this.world; - } + public String getWorld() { + return this.world; + } } diff --git a/Essentials/src/net/ess3/api/MaxMoneyException.java b/Essentials/src/net/ess3/api/MaxMoneyException.java index bdc78aad2..3e934cedb 100644 --- a/Essentials/src/net/ess3/api/MaxMoneyException.java +++ b/Essentials/src/net/ess3/api/MaxMoneyException.java @@ -3,10 +3,8 @@ package net.ess3.api; import static com.earth2me.essentials.I18n.tl; -public class MaxMoneyException extends Exception -{ - public MaxMoneyException() - { - super(tl("maxMoney")); - } +public class MaxMoneyException extends Exception { + public MaxMoneyException() { + super(tl("maxMoney")); + } } diff --git a/Essentials/src/net/ess3/api/NoLoanPermittedException.java b/Essentials/src/net/ess3/api/NoLoanPermittedException.java index ed9cd8ca9..088265cf6 100644 --- a/Essentials/src/net/ess3/api/NoLoanPermittedException.java +++ b/Essentials/src/net/ess3/api/NoLoanPermittedException.java @@ -3,10 +3,8 @@ package net.ess3.api; import static com.earth2me.essentials.I18n.tl; -public class NoLoanPermittedException extends Exception -{ - public NoLoanPermittedException() - { - super(tl("negativeBalanceError")); - } +public class NoLoanPermittedException extends Exception { + public NoLoanPermittedException() { + super(tl("negativeBalanceError")); + } } diff --git a/Essentials/src/net/ess3/api/UserDoesNotExistException.java b/Essentials/src/net/ess3/api/UserDoesNotExistException.java index 9be186a5a..2c3f0daa9 100644 --- a/Essentials/src/net/ess3/api/UserDoesNotExistException.java +++ b/Essentials/src/net/ess3/api/UserDoesNotExistException.java @@ -3,10 +3,8 @@ package net.ess3.api; import static com.earth2me.essentials.I18n.tl; -public class UserDoesNotExistException extends Exception -{ - public UserDoesNotExistException(String name) - { - super(tl("userDoesNotExist", name)); - } +public class UserDoesNotExistException extends Exception { + public UserDoesNotExistException(String name) { + super(tl("userDoesNotExist", name)); + } } diff --git a/Essentials/src/net/ess3/api/events/AfkStatusChangeEvent.java b/Essentials/src/net/ess3/api/events/AfkStatusChangeEvent.java index 048bf1ce4..1fa99e3f6 100644 --- a/Essentials/src/net/ess3/api/events/AfkStatusChangeEvent.java +++ b/Essentials/src/net/ess3/api/events/AfkStatusChangeEvent.java @@ -3,10 +3,8 @@ package net.ess3.api.events; import net.ess3.api.IUser; -public class AfkStatusChangeEvent extends StatusChangeEvent -{ - public AfkStatusChangeEvent(IUser affected, boolean value) - { - super(affected, affected, value); - } +public class AfkStatusChangeEvent extends StatusChangeEvent { + public AfkStatusChangeEvent(IUser affected, boolean value) { + super(affected, affected, value); + } } diff --git a/Essentials/src/net/ess3/api/events/GodStatusChangeEvent.java b/Essentials/src/net/ess3/api/events/GodStatusChangeEvent.java index 2d141cf6d..b965a6e7b 100644 --- a/Essentials/src/net/ess3/api/events/GodStatusChangeEvent.java +++ b/Essentials/src/net/ess3/api/events/GodStatusChangeEvent.java @@ -3,10 +3,8 @@ package net.ess3.api.events; import net.ess3.api.IUser; -public class GodStatusChangeEvent extends StatusChangeEvent -{ - public GodStatusChangeEvent(IUser affected, IUser controller, boolean value) - { - super(affected, controller, value); - } +public class GodStatusChangeEvent extends StatusChangeEvent { + public GodStatusChangeEvent(IUser affected, IUser controller, boolean value) { + super(affected, controller, value); + } } diff --git a/Essentials/src/net/ess3/api/events/IgnoreStatusChangeEvent.java b/Essentials/src/net/ess3/api/events/IgnoreStatusChangeEvent.java index 2ea76228f..06a87651c 100644 --- a/Essentials/src/net/ess3/api/events/IgnoreStatusChangeEvent.java +++ b/Essentials/src/net/ess3/api/events/IgnoreStatusChangeEvent.java @@ -3,10 +3,8 @@ package net.ess3.api.events; import net.ess3.api.IUser; -public class IgnoreStatusChangeEvent extends StatusChangeEvent -{ - public IgnoreStatusChangeEvent(IUser affected, IUser controller, boolean value) - { - super(affected, controller, value); - } +public class IgnoreStatusChangeEvent extends StatusChangeEvent { + public IgnoreStatusChangeEvent(IUser affected, IUser controller, boolean value) { + super(affected, controller, value); + } } diff --git a/Essentials/src/net/ess3/api/events/JailStatusChangeEvent.java b/Essentials/src/net/ess3/api/events/JailStatusChangeEvent.java index ff884d1a2..03eda5932 100644 --- a/Essentials/src/net/ess3/api/events/JailStatusChangeEvent.java +++ b/Essentials/src/net/ess3/api/events/JailStatusChangeEvent.java @@ -3,10 +3,8 @@ package net.ess3.api.events; import net.ess3.api.IUser; -public class JailStatusChangeEvent extends StatusChangeEvent -{ - public JailStatusChangeEvent(IUser affected, IUser controller, boolean value) - { - super(affected, controller, value); - } +public class JailStatusChangeEvent extends StatusChangeEvent { + public JailStatusChangeEvent(IUser affected, IUser controller, boolean value) { + super(affected, controller, value); + } } \ No newline at end of file diff --git a/Essentials/src/net/ess3/api/events/LocalChatSpyEvent.java b/Essentials/src/net/ess3/api/events/LocalChatSpyEvent.java index 1071a9f6d..ab3cf431a 100644 --- a/Essentials/src/net/ess3/api/events/LocalChatSpyEvent.java +++ b/Essentials/src/net/ess3/api/events/LocalChatSpyEvent.java @@ -1,128 +1,116 @@ package net.ess3.api.events; -import static com.earth2me.essentials.I18n.tl; -import java.util.IllegalFormatException; -import java.util.Set; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; +import java.util.IllegalFormatException; +import java.util.Set; -public class LocalChatSpyEvent extends Event implements Cancellable -{ - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled = false; - private String message; - private String format; - private Player player; - private final Set recipients; +import static com.earth2me.essentials.I18n.tl; - public LocalChatSpyEvent(final boolean async, final Player who, final String format, final String message, final Set players) - { - super(async); - this.format = tl("chatTypeLocal").concat(tl("chatTypeSpy")).concat(format); - this.message = message; - recipients = players; - player = who; - } - /** - * Gets the message that the player is attempting to send. This message will be used with {@link #getFormat()}. - * - * @return Message the player is attempting to send - */ - public String getMessage() - { - return message; - } +public class LocalChatSpyEvent extends Event implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled = false; + private String message; + private String format; + private Player player; + private final Set recipients; - /** - * Sets the message that the player will send. This message will be used with {@link #getFormat()}. - * - * @param message New message that the player will send - */ - public void setMessage(String message) - { - this.message = message; - } + public LocalChatSpyEvent(final boolean async, final Player who, final String format, final String message, final Set players) { + super(async); + this.format = tl("chatTypeLocal").concat(tl("chatTypeSpy")).concat(format); + this.message = message; + recipients = players; + player = who; + } - /** - * Gets the format to use to display this chat message. When this event finishes execution, the first format - * parameter is the {@link Player#getDisplayName()} and the second parameter is {@link #getMessage()} - * - * @return {@link String#format(String, Object...)} compatible format string - */ - public String getFormat() - { - return format; - } + /** + * Gets the message that the player is attempting to send. This message will be used with {@link #getFormat()}. + * + * @return Message the player is attempting to send + */ + public String getMessage() { + return message; + } - /** - * Sets the format to use to display this chat message. When this event finishes execution, the first format - * parameter is the {@link Player#getDisplayName()} and the second parameter is {@link #getMessage()} - * - * @param format {@link String#format(String, Object...)} compatible format string - * @throws IllegalFormatException if the underlying API throws the exception - * @throws NullPointerException if format is null - * @see String#format(String, Object...) - */ - public void setFormat(final String format) throws IllegalFormatException, NullPointerException - { - // Oh for a better way to do this! - try - { - String.format(format, player, message); - } - catch (RuntimeException ex) - { - ex.fillInStackTrace(); - throw ex; - } + /** + * Sets the message that the player will send. This message will be used with {@link #getFormat()}. + * + * @param message New message that the player will send + */ + public void setMessage(String message) { + this.message = message; + } - this.format = format; - } + /** + * Gets the format to use to display this chat message. When this event finishes execution, the first format + * parameter is the {@link Player#getDisplayName()} and the second parameter is {@link #getMessage()} + * + * @return {@link String#format(String, Object...)} compatible format string + */ + public String getFormat() { + return format; + } - /** - * Gets a set of recipients that this chat message will be displayed to. - * - * @return All Players who will see this chat message - */ - public Set getRecipients() - { - return recipients; - } + /** + * Sets the format to use to display this chat message. When this event finishes execution, the first format + * parameter is the {@link Player#getDisplayName()} and the second parameter is {@link #getMessage()} + * + * @param format {@link String#format(String, Object...)} compatible format string + * + * @throws IllegalFormatException if the underlying API throws the exception + * @throws NullPointerException if format is null + * @see String#format(String, Object...) + */ + public void setFormat(final String format) throws IllegalFormatException, NullPointerException { + // Oh for a better way to do this! + try { + String.format(format, player, message); + } catch (RuntimeException ex) { + ex.fillInStackTrace(); + throw ex; + } - /** - * Returns the player involved in this event - * - * @return Player who is involved in this event - */ - public final Player getPlayer() - { - return player; - } + this.format = format; + } - @Override - public boolean isCancelled() - { - return cancelled; - } + /** + * Gets a set of recipients that this chat message will be displayed to. + * + * @return All Players who will see this chat message + */ + public Set getRecipients() { + return recipients; + } - @Override - public void setCancelled(boolean cancel) - { - this.cancelled = cancel; - } + /** + * Returns the player involved in this event + * + * @return Player who is involved in this event + */ + public final Player getPlayer() { + return player; + } - @Override - public HandlerList getHandlers() - { - return handlers; - } + @Override + public boolean isCancelled() { + return cancelled; + } - public static HandlerList getHandlerList() - { - return handlers; - } + @Override + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static HandlerList getHandlerList() { + return handlers; + } } diff --git a/Essentials/src/net/ess3/api/events/MuteStatusChangeEvent.java b/Essentials/src/net/ess3/api/events/MuteStatusChangeEvent.java index 428883d76..4f67a1e12 100644 --- a/Essentials/src/net/ess3/api/events/MuteStatusChangeEvent.java +++ b/Essentials/src/net/ess3/api/events/MuteStatusChangeEvent.java @@ -3,10 +3,8 @@ package net.ess3.api.events; import net.ess3.api.IUser; -public class MuteStatusChangeEvent extends StatusChangeEvent -{ - public MuteStatusChangeEvent(IUser affected, IUser controller, boolean value) - { - super(affected, controller, value); - } +public class MuteStatusChangeEvent extends StatusChangeEvent { + public MuteStatusChangeEvent(IUser affected, IUser controller, boolean value) { + super(affected, controller, value); + } } diff --git a/Essentials/src/net/ess3/api/events/NickChangeEvent.java b/Essentials/src/net/ess3/api/events/NickChangeEvent.java index ac4a83b75..9cbb374e7 100644 --- a/Essentials/src/net/ess3/api/events/NickChangeEvent.java +++ b/Essentials/src/net/ess3/api/events/NickChangeEvent.java @@ -4,18 +4,15 @@ import net.ess3.api.IUser; import org.bukkit.event.Cancellable; -public class NickChangeEvent extends StateChangeEvent implements Cancellable -{ - private String newValue; +public class NickChangeEvent extends StateChangeEvent implements Cancellable { + private String newValue; - public NickChangeEvent(IUser affected, IUser controller, String value) - { - super(affected, controller); - this.newValue = value; - } + public NickChangeEvent(IUser affected, IUser controller, String value) { + super(affected, controller); + this.newValue = value; + } - public String getValue() - { - return newValue; - } + public String getValue() { + return newValue; + } } diff --git a/Essentials/src/net/ess3/api/events/SignBreakEvent.java b/Essentials/src/net/ess3/api/events/SignBreakEvent.java index 9c3e69d7e..a367621e7 100644 --- a/Essentials/src/net/ess3/api/events/SignBreakEvent.java +++ b/Essentials/src/net/ess3/api/events/SignBreakEvent.java @@ -4,10 +4,8 @@ import com.earth2me.essentials.signs.EssentialsSign; import net.ess3.api.IUser; -public class SignBreakEvent extends SignEvent -{ - public SignBreakEvent(EssentialsSign.ISign sign, EssentialsSign essSign, IUser user) - { - super(sign, essSign, user); - } +public class SignBreakEvent extends SignEvent { + public SignBreakEvent(EssentialsSign.ISign sign, EssentialsSign essSign, IUser user) { + super(sign, essSign, user); + } } diff --git a/Essentials/src/net/ess3/api/events/SignCreateEvent.java b/Essentials/src/net/ess3/api/events/SignCreateEvent.java index ac0520119..d295d11f2 100644 --- a/Essentials/src/net/ess3/api/events/SignCreateEvent.java +++ b/Essentials/src/net/ess3/api/events/SignCreateEvent.java @@ -4,10 +4,8 @@ import com.earth2me.essentials.signs.EssentialsSign; import net.ess3.api.IUser; -public class SignCreateEvent extends SignEvent -{ - public SignCreateEvent(EssentialsSign.ISign sign, EssentialsSign essSign, IUser user) - { - super(sign, essSign, user); - } +public class SignCreateEvent extends SignEvent { + public SignCreateEvent(EssentialsSign.ISign sign, EssentialsSign essSign, IUser user) { + super(sign, essSign, user); + } } diff --git a/Essentials/src/net/ess3/api/events/SignEvent.java b/Essentials/src/net/ess3/api/events/SignEvent.java index 01689db19..94df29ece 100644 --- a/Essentials/src/net/ess3/api/events/SignEvent.java +++ b/Essentials/src/net/ess3/api/events/SignEvent.java @@ -10,59 +10,49 @@ import org.bukkit.event.HandlerList; /** * This handles common boilerplate for other SignEvent - * */ -public class SignEvent extends Event implements Cancellable -{ - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled = false; - ISign sign; - EssentialsSign essSign; - IUser user; +public class SignEvent extends Event implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled = false; + ISign sign; + EssentialsSign essSign; + IUser user; - public SignEvent(final ISign sign, final EssentialsSign essSign, final IUser user) - { - super(); - this.sign = sign; - this.essSign = essSign; - this.user = user; - } + public SignEvent(final ISign sign, final EssentialsSign essSign, final IUser user) { + super(); + this.sign = sign; + this.essSign = essSign; + this.user = user; + } - public ISign getSign() - { - return sign; - } + public ISign getSign() { + return sign; + } - public EssentialsSign getEssentialsSign() - { - return essSign; - } + public EssentialsSign getEssentialsSign() { + return essSign; + } - public IUser getUser() - { - return user; - } + public IUser getUser() { + return user; + } - @Override - public HandlerList getHandlers() - { - return handlers; - } + @Override + public HandlerList getHandlers() { + return handlers; + } - public static HandlerList getHandlerList() - { - return handlers; - } + public static HandlerList getHandlerList() { + return handlers; + } - @Override - public boolean isCancelled() - { - return cancelled; - } + @Override + public boolean isCancelled() { + return cancelled; + } - @Override - public void setCancelled(boolean cancelled) - { - this.cancelled = cancelled; - } + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } } diff --git a/Essentials/src/net/ess3/api/events/SignInteractEvent.java b/Essentials/src/net/ess3/api/events/SignInteractEvent.java index f67f68a0e..6855984b8 100644 --- a/Essentials/src/net/ess3/api/events/SignInteractEvent.java +++ b/Essentials/src/net/ess3/api/events/SignInteractEvent.java @@ -4,10 +4,8 @@ import com.earth2me.essentials.signs.EssentialsSign; import net.ess3.api.IUser; -public class SignInteractEvent extends SignEvent -{ - public SignInteractEvent(EssentialsSign.ISign sign, EssentialsSign essSign, IUser user) - { - super(sign, essSign, user); - } +public class SignInteractEvent extends SignEvent { + public SignInteractEvent(EssentialsSign.ISign sign, EssentialsSign essSign, IUser user) { + super(sign, essSign, user); + } } diff --git a/Essentials/src/net/ess3/api/events/StateChangeEvent.java b/Essentials/src/net/ess3/api/events/StateChangeEvent.java index bcdfc247c..681db5410 100644 --- a/Essentials/src/net/ess3/api/events/StateChangeEvent.java +++ b/Essentials/src/net/ess3/api/events/StateChangeEvent.java @@ -8,59 +8,49 @@ import org.bukkit.event.HandlerList; /** * This handles common boilerplate for other StateChangeEvents - * */ -public class StateChangeEvent extends Event implements Cancellable -{ - private static final HandlerList handlers = new HandlerList(); - private boolean cancelled = false; - IUser affected; - IUser controller; +public class StateChangeEvent extends Event implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private boolean cancelled = false; + IUser affected; + IUser controller; - public StateChangeEvent(IUser affected, IUser controller) - { - super(); - this.affected = affected; - this.controller = controller; - } + public StateChangeEvent(IUser affected, IUser controller) { + super(); + this.affected = affected; + this.controller = controller; + } - public StateChangeEvent(boolean isAsync, IUser affected, IUser controller) - { - super(isAsync); - this.affected = affected; - this.controller = controller; - } + public StateChangeEvent(boolean isAsync, IUser affected, IUser controller) { + super(isAsync); + this.affected = affected; + this.controller = controller; + } - public IUser getAffected() - { - return this.affected; - } + public IUser getAffected() { + return this.affected; + } - public IUser getController() - { - return controller; - } + public IUser getController() { + return controller; + } - @Override - public HandlerList getHandlers() - { - return handlers; - } + @Override + public HandlerList getHandlers() { + return handlers; + } - public static HandlerList getHandlerList() - { - return handlers; - } + public static HandlerList getHandlerList() { + return handlers; + } - @Override - public boolean isCancelled() - { - return cancelled; - } + @Override + public boolean isCancelled() { + return cancelled; + } - @Override - public void setCancelled(boolean cancelled) - { - this.cancelled = cancelled; - } + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } } diff --git a/Essentials/src/net/ess3/api/events/StatusChangeEvent.java b/Essentials/src/net/ess3/api/events/StatusChangeEvent.java index d8d43a042..a2645baf5 100644 --- a/Essentials/src/net/ess3/api/events/StatusChangeEvent.java +++ b/Essentials/src/net/ess3/api/events/StatusChangeEvent.java @@ -6,26 +6,21 @@ import org.bukkit.event.Cancellable; /** * This handles common boilerplate for other StatusChangeEvents - * */ -public class StatusChangeEvent extends StateChangeEvent implements Cancellable -{ - private boolean newValue; +public class StatusChangeEvent extends StateChangeEvent implements Cancellable { + private boolean newValue; - public StatusChangeEvent(IUser affected, IUser controller, boolean value) - { - super(affected, controller); - this.newValue = value; - } + public StatusChangeEvent(IUser affected, IUser controller, boolean value) { + super(affected, controller); + this.newValue = value; + } - public StatusChangeEvent(boolean isAsync, IUser affected, IUser controller, boolean value) - { - super(isAsync, affected, controller); - this.newValue = value; - } + public StatusChangeEvent(boolean isAsync, IUser affected, IUser controller, boolean value) { + super(isAsync, affected, controller); + this.newValue = value; + } - public boolean getValue() - { - return newValue; - } + public boolean getValue() { + return newValue; + } } diff --git a/Essentials/src/net/ess3/api/events/UserBalanceUpdateEvent.java b/Essentials/src/net/ess3/api/events/UserBalanceUpdateEvent.java index f656388ee..7dd0c30f8 100644 --- a/Essentials/src/net/ess3/api/events/UserBalanceUpdateEvent.java +++ b/Essentials/src/net/ess3/api/events/UserBalanceUpdateEvent.java @@ -1,49 +1,42 @@ package net.ess3.api.events; -import java.math.BigDecimal; - import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; +import java.math.BigDecimal; -public class UserBalanceUpdateEvent extends Event -{ - private static final HandlerList handlers = new HandlerList(); - private final Player player; - private final BigDecimal originalBalance; - private final BigDecimal balance; - public UserBalanceUpdateEvent(Player player, BigDecimal originalBalance, BigDecimal balance) - { - this.player = player; - this.originalBalance = originalBalance; - this.balance = balance; - } +public class UserBalanceUpdateEvent extends Event { + private static final HandlerList handlers = new HandlerList(); + private final Player player; + private final BigDecimal originalBalance; + private final BigDecimal balance; - @Override - public HandlerList getHandlers() - { - return handlers; - } + public UserBalanceUpdateEvent(Player player, BigDecimal originalBalance, BigDecimal balance) { + this.player = player; + this.originalBalance = originalBalance; + this.balance = balance; + } - public static HandlerList getHandlerList() - { - return handlers; - } + @Override + public HandlerList getHandlers() { + return handlers; + } - public Player getPlayer() - { - return player; - } + public static HandlerList getHandlerList() { + return handlers; + } - public BigDecimal getNewBalance() - { - return balance; - } - - public BigDecimal getOldBalance() - { - return originalBalance; - } + public Player getPlayer() { + return player; + } + + public BigDecimal getNewBalance() { + return balance; + } + + public BigDecimal getOldBalance() { + return originalBalance; + } } diff --git a/Essentials/test/com/earth2me/essentials/EconomyTest.java b/Essentials/test/com/earth2me/essentials/EconomyTest.java index 00d994b2b..80cd140e5 100644 --- a/Essentials/test/com/earth2me/essentials/EconomyTest.java +++ b/Essentials/test/com/earth2me/essentials/EconomyTest.java @@ -2,125 +2,98 @@ package com.earth2me.essentials; import com.earth2me.essentials.api.NoLoanPermittedException; import com.earth2me.essentials.api.UserDoesNotExistException; -import java.io.IOException; import junit.framework.TestCase; -import static junit.framework.TestCase.assertFalse; -import static junit.framework.TestCase.fail; import net.ess3.api.Economy; 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 static final String NPCNAME = "npc1"; - private static final String PLAYERNAME = "testPlayer1"; - - public EconomyTest(final String testName) - { - super(testName); - final FakeServer server = new FakeServer(); - server.createWorld("testWorld", Environment.NORMAL); - ess = new Essentials(server); - try - { - ess.setupForTesting(server); - } - catch (InvalidDescriptionException ex) - { - fail("InvalidDescriptionException"); - } - catch (IOException ex) - { - fail("IOException"); - } - server.addPlayer(new OfflinePlayer(PLAYERNAME, ess.getServer())); - } - - // only one big test, since we use static instances - @Test - public void testEconomy() - { - // test NPC - assertFalse("NPC does not exists", Economy.playerExists(NPCNAME)); - assertTrue("Create NPC", Economy.createNPC(NPCNAME)); - assertTrue("NPC exists", Economy.playerExists(NPCNAME)); - assertNotNull("NPC can be accessed", ess.getOfflineUser(NPCNAME)); - try - { - Economy.removeNPC(NPCNAME); - } - catch (UserDoesNotExistException ex) - { - fail(ex.getMessage()); - } - assertFalse("NPC can be removed", Economy.playerExists(NPCNAME)); - - //test Math - try - { - - assertTrue("Player exists", Economy.playerExists(PLAYERNAME)); - Economy.resetBalance(PLAYERNAME); - assertEquals("Player has no money", 0.0, Economy.getMoney(PLAYERNAME)); - Economy.add(PLAYERNAME, 10.0); - assertEquals("Add money", 10.0, Economy.getMoney(PLAYERNAME)); - Economy.subtract(PLAYERNAME, 5.0); - assertEquals("Subtract money", 5.0, Economy.getMoney(PLAYERNAME)); - Economy.multiply(PLAYERNAME, 2.0); - assertEquals("Multiply money", 10.0, Economy.getMoney(PLAYERNAME)); - Economy.divide(PLAYERNAME, 2.0); - assertEquals("Divide money", 5.0, Economy.getMoney(PLAYERNAME)); - Economy.setMoney(PLAYERNAME, 10.0); - assertEquals("Set money", 10.0, Economy.getMoney(PLAYERNAME)); - } - catch (NoLoanPermittedException ex) - { - fail(ex.getMessage()); - } - catch (UserDoesNotExistException ex) - { - fail(ex.getMessage()); - } - - //test Format - assertEquals("Format $1000", "$1000", Economy.format(1000.0)); - assertEquals("Format $10", "$10", Economy.format(10.0)); - assertEquals("Format $10.10", "$10.10", Economy.format(10.10)); - assertEquals("Format $10.10", "$10.10", Economy.format(10.1000001)); - assertEquals("Format $10.10", "$10.10", Economy.format(10.1099999)); +import java.io.IOException; - //test Exceptions - try - { - assertTrue("Player exists", Economy.playerExists(PLAYERNAME)); - Economy.resetBalance(PLAYERNAME); - assertEquals("Reset balance", 0.0, Economy.getMoney(PLAYERNAME)); - Economy.subtract(PLAYERNAME, 5.0); - fail("Did not throw exception"); - } - catch (NoLoanPermittedException ex) - { - } - catch (UserDoesNotExistException ex) - { - fail(ex.getMessage()); - } +public class EconomyTest extends TestCase { + private final transient Essentials ess; + private static final String NPCNAME = "npc1"; + private static final String PLAYERNAME = "testPlayer1"; - try - { - Economy.resetBalance("UnknownPlayer"); - fail("Did not throw exception"); - } - catch (NoLoanPermittedException ex) - { - fail(ex.getMessage()); - } - catch (UserDoesNotExistException ex) - { - } - } + public EconomyTest(final String testName) { + super(testName); + final FakeServer server = new FakeServer(); + server.createWorld("testWorld", Environment.NORMAL); + ess = new Essentials(server); + try { + ess.setupForTesting(server); + } catch (InvalidDescriptionException ex) { + fail("InvalidDescriptionException"); + } catch (IOException ex) { + fail("IOException"); + } + server.addPlayer(new OfflinePlayer(PLAYERNAME, ess.getServer())); + } + + // only one big test, since we use static instances + @Test + public void testEconomy() { + // test NPC + assertFalse("NPC does not exists", Economy.playerExists(NPCNAME)); + assertTrue("Create NPC", Economy.createNPC(NPCNAME)); + assertTrue("NPC exists", Economy.playerExists(NPCNAME)); + assertNotNull("NPC can be accessed", ess.getOfflineUser(NPCNAME)); + try { + Economy.removeNPC(NPCNAME); + } catch (UserDoesNotExistException ex) { + fail(ex.getMessage()); + } + assertFalse("NPC can be removed", Economy.playerExists(NPCNAME)); + + //test Math + try { + + assertTrue("Player exists", Economy.playerExists(PLAYERNAME)); + Economy.resetBalance(PLAYERNAME); + assertEquals("Player has no money", 0.0, Economy.getMoney(PLAYERNAME)); + Economy.add(PLAYERNAME, 10.0); + assertEquals("Add money", 10.0, Economy.getMoney(PLAYERNAME)); + Economy.subtract(PLAYERNAME, 5.0); + assertEquals("Subtract money", 5.0, Economy.getMoney(PLAYERNAME)); + Economy.multiply(PLAYERNAME, 2.0); + assertEquals("Multiply money", 10.0, Economy.getMoney(PLAYERNAME)); + Economy.divide(PLAYERNAME, 2.0); + assertEquals("Divide money", 5.0, Economy.getMoney(PLAYERNAME)); + Economy.setMoney(PLAYERNAME, 10.0); + assertEquals("Set money", 10.0, Economy.getMoney(PLAYERNAME)); + } catch (NoLoanPermittedException ex) { + fail(ex.getMessage()); + } catch (UserDoesNotExistException ex) { + fail(ex.getMessage()); + } + + //test Format + assertEquals("Format $1000", "$1000", Economy.format(1000.0)); + assertEquals("Format $10", "$10", Economy.format(10.0)); + assertEquals("Format $10.10", "$10.10", Economy.format(10.10)); + assertEquals("Format $10.10", "$10.10", Economy.format(10.1000001)); + assertEquals("Format $10.10", "$10.10", Economy.format(10.1099999)); + + + //test Exceptions + try { + assertTrue("Player exists", Economy.playerExists(PLAYERNAME)); + Economy.resetBalance(PLAYERNAME); + assertEquals("Reset balance", 0.0, Economy.getMoney(PLAYERNAME)); + Economy.subtract(PLAYERNAME, 5.0); + fail("Did not throw exception"); + } catch (NoLoanPermittedException ex) { + } catch (UserDoesNotExistException ex) { + fail(ex.getMessage()); + } + + try { + Economy.resetBalance("UnknownPlayer"); + fail("Did not throw exception"); + } catch (NoLoanPermittedException ex) { + fail(ex.getMessage()); + } catch (UserDoesNotExistException ex) { + } + } } diff --git a/Essentials/test/com/earth2me/essentials/FakeServer.java b/Essentials/test/com/earth2me/essentials/FakeServer.java index e11d4ab76..664afd08a 100644 --- a/Essentials/test/com/earth2me/essentials/FakeServer.java +++ b/Essentials/test/com/earth2me/essentials/FakeServer.java @@ -2,13 +2,6 @@ package com.earth2me.essentials; import com.avaje.ebean.config.ServerConfig; import com.earth2me.essentials.craftbukkit.FakeWorld; - -import java.awt.image.BufferedImage; -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.Warning.WarningState; import org.bukkit.World.Environment; @@ -30,15 +23,7 @@ import org.bukkit.permissions.Permissible; import org.bukkit.permissions.Permission; import org.bukkit.permissions.PermissionAttachment; import org.bukkit.permissions.PermissionAttachmentInfo; -import org.bukkit.plugin.EventExecutor; -import org.bukkit.plugin.InvalidDescriptionException; -import org.bukkit.plugin.InvalidPluginException; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.PluginLoader; -import org.bukkit.plugin.PluginManager; -import org.bukkit.plugin.RegisteredListener; -import org.bukkit.plugin.ServicesManager; -import org.bukkit.plugin.UnknownDependencyException; +import org.bukkit.plugin.*; import org.bukkit.plugin.messaging.Messenger; import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.scheduler.BukkitTask; @@ -46,1242 +31,1035 @@ import org.bukkit.scheduler.BukkitWorker; import org.bukkit.scoreboard.ScoreboardManager; import org.bukkit.util.CachedServerIcon; - -public class FakeServer implements Server -{ - private List players = new ArrayList(); - private final List worlds = new ArrayList(); - PluginManager pluginManager = new FakePluginManager(); - - public FakeServer() - { - if (Bukkit.getServer() == null) - { - Bukkit.setServer(this); - } - } - - @Override - public String getName() - { - return "Essentials Fake Server"; - } - - @Override - public String getVersion() - { - return "1.0"; - } - - @Override - public Player[] _INVALID_getOnlinePlayers() - { - return players.toArray(new Player[0]); - } - - @Override - public Collection getOnlinePlayers() - { - return players; - } - - 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 boolean isHardcore() - { - 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; - } - - @Override - public PluginManager getPluginManager() - { - return pluginManager; - } - - @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 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 BukkitTask runTask(Plugin plugin, Runnable r) throws IllegalArgumentException - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public BukkitTask runTaskAsynchronously(Plugin plugin, Runnable r) throws IllegalArgumentException - { - r.run(); - return null; - } - - @Override - public BukkitTask runTaskLater(Plugin plugin, Runnable r, long l) throws IllegalArgumentException - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public BukkitTask runTaskLaterAsynchronously(Plugin plugin, Runnable r, long l) throws IllegalArgumentException - { - r.run(); - return null; - } - - @Override - public BukkitTask runTaskTimer(Plugin plugin, Runnable r, long l, long l1) throws IllegalArgumentException - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public BukkitTask runTaskTimerAsynchronously(Plugin plugin, Runnable r, long l, long l1) throws IllegalArgumentException - { - 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) - { - 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); - pluginManager.callEvent(new PlayerJoinEvent(base1, null)); - } - - public OfflinePlayer createPlayer(String name) - { - OfflinePlayer player = new OfflinePlayer(name, this); - player.setLocation(new Location(worlds.get(0), 0, 0, 0, 0, 0)); - return player; - } - - @Override - public World createWorld(WorldCreator creator) - { - 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 createOPlayer(string); - } - - private org.bukkit.OfflinePlayer createOPlayer(final String string) - { - return new org.bukkit.OfflinePlayer() - { - @Override - public boolean isOnline() - { - return false; - } - - @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 UUID getUniqueId() - { - if (string == "testPlayer1") - { - return UUID.fromString("3c9ebe1a-9098-43fd-bc0c-a369b76817ba"); - } - else if (string == "npc1") - { - return null; - } - throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. - } - }; - } - - @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() - { - return new ConsoleCommandSender() - { - @Override - public void sendMessage(String message) - { - System.out.println("Console message: " + message); - } - - @Override - public void sendMessage(String[] messages) - { - for (String message : messages) - { - System.out.println("Console message: " + message); - } - } - - @Override - public Server getServer() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public String getName() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isPermissionSet(String name) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isPermissionSet(Permission perm) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean hasPermission(String name) - { - return true; - } - - @Override - public boolean hasPermission(Permission perm) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public PermissionAttachment addAttachment(Plugin plugin) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value, int ticks) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public PermissionAttachment addAttachment(Plugin plugin, int ticks) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void removeAttachment(PermissionAttachment attachment) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void recalculatePermissions() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Set getEffectivePermissions() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isOp() - { - return true; - } - - @Override - public void setOp(boolean value) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isConversing() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void acceptConversationInput(String input) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean beginConversation(Conversation conversation) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void abandonConversation(Conversation conversation) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void abandonConversation(Conversation conversation, ConversationAbandonedEvent details) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void sendRawMessage(String message) - { - 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."); - } - - @Override - public String getMotd() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public WarningState getWarningState() - { - return WarningState.DEFAULT; - } - - @Override - public int getAmbientSpawnLimit() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public String getShutdownMessage() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public ItemFactory getItemFactory() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public ScoreboardManager getScoreboardManager() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public CachedServerIcon getServerIcon() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public CachedServerIcon loadServerIcon(File file) throws IllegalArgumentException, Exception - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public CachedServerIcon loadServerIcon(BufferedImage bufferedImage) throws IllegalArgumentException, Exception - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void setIdleTimeout(int i) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public int getIdleTimeout() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public UnsafeValues getUnsafe() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public BanList getBanList(BanList.Type arg0) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Player getPlayer(UUID arg0) - { - for (Player player : players) - { - if (player.getUniqueId().equals(arg0)) - { - return player; - } - } - return null; - } - - @Override - public org.bukkit.OfflinePlayer getOfflinePlayer(UUID arg0) - { - if (arg0.toString().equalsIgnoreCase("3c9ebe1a-9098-43fd-bc0c-a369b76817ba")) - { - return createOPlayer("testPlayer1"); - } - if (arg0.toString().equalsIgnoreCase("f4a37409-5c40-3b2c-9cd6-57d3c5abdc76")) - { - return createOPlayer("npc1"); - } - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Inventory createInventory(InventoryHolder arg0, InventoryType arg1, String arg2) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - - class FakePluginManager implements PluginManager - { - ArrayList listeners = new ArrayList(); - - @Override - public void registerInterface(Class loader) throws IllegalArgumentException - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Plugin getPlugin(String name) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Plugin[] getPlugins() - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public boolean isPluginEnabled(String name) - { - 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 directory) - { - 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) throws IllegalStateException - { - Logger.getLogger("Minecraft").info("Called event " + event.getEventName()); - if (event instanceof PlayerJoinEvent) - { - for (RegisteredListener listener : listeners) - { - if (listener.getListener() instanceof EssentialsPlayerListener) - { - PlayerJoinEvent jEvent = (PlayerJoinEvent)event; - EssentialsPlayerListener epl = (EssentialsPlayerListener)listener.getListener(); - epl.onPlayerJoin(jEvent); - Essentials ess = (Essentials)listener.getPlugin(); - ess.getLogger().info("Sending join event to Essentials"); - ess.getUser(jEvent.getPlayer()); - } - } - } - } - - @Override - public void registerEvents(Listener listener, Plugin plugin) - { - listeners.add(new RegisteredListener(listener, null, null, plugin, false)); - } - - @Override - public void registerEvent(Class event, Listener listener, EventPriority priority, EventExecutor executor, Plugin plugin) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void registerEvent(Class event, Listener listener, EventPriority priority, EventExecutor executor, Plugin plugin, boolean ignoreCancelled) - { - 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 name) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void addPermission(Permission perm) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void removePermission(Permission perm) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void removePermission(String name) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Set getDefaultPermissions(boolean op) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void recalculatePermissionDefaults(Permission perm) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void subscribeToPermission(String permission, Permissible permissible) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void unsubscribeFromPermission(String permission, Permissible permissible) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Set getPermissionSubscriptions(String permission) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void subscribeToDefaultPerms(boolean op, Permissible permissible) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public void unsubscribeFromDefaultPerms(boolean op, Permissible permissible) - { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Set getDefaultPermSubscriptions(boolean op) - { - 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."); - } - }; +import java.awt.image.BufferedImage; +import java.io.File; +import java.util.*; +import java.util.concurrent.Callable; +import java.util.concurrent.Future; +import java.util.logging.Logger; + + +public class FakeServer implements Server { + private List players = new ArrayList(); + private final List worlds = new ArrayList(); + PluginManager pluginManager = new FakePluginManager(); + + public FakeServer() { + if (Bukkit.getServer() == null) { + Bukkit.setServer(this); + } + } + + @Override + public String getName() { + return "Essentials Fake Server"; + } + + @Override + public String getVersion() { + return "1.0"; + } + + @Override + public Player[] _INVALID_getOnlinePlayers() { + return players.toArray(new Player[0]); + } + + @Override + public Collection getOnlinePlayers() { + return players; + } + + 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 boolean isHardcore() { + 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; + } + + @Override + public PluginManager getPluginManager() { + return pluginManager; + } + + @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 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 BukkitTask runTask(Plugin plugin, Runnable r) throws IllegalArgumentException { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public BukkitTask runTaskAsynchronously(Plugin plugin, Runnable r) throws IllegalArgumentException { + r.run(); + return null; + } + + @Override + public BukkitTask runTaskLater(Plugin plugin, Runnable r, long l) throws IllegalArgumentException { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public BukkitTask runTaskLaterAsynchronously(Plugin plugin, Runnable r, long l) throws IllegalArgumentException { + r.run(); + return null; + } + + @Override + public BukkitTask runTaskTimer(Plugin plugin, Runnable r, long l, long l1) throws IllegalArgumentException { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public BukkitTask runTaskTimerAsynchronously(Plugin plugin, Runnable r, long l, long l1) throws IllegalArgumentException { + 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) { + 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); + pluginManager.callEvent(new PlayerJoinEvent(base1, null)); + } + + public OfflinePlayer createPlayer(String name) { + OfflinePlayer player = new OfflinePlayer(name, this); + player.setLocation(new Location(worlds.get(0), 0, 0, 0, 0, 0)); + return player; + } + + @Override + public World createWorld(WorldCreator creator) { + 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 createOPlayer(string); + } + + private org.bukkit.OfflinePlayer createOPlayer(final String string) { + return new org.bukkit.OfflinePlayer() { + @Override + public boolean isOnline() { + return false; + } + + @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 UUID getUniqueId() { + if (string == "testPlayer1") { + return UUID.fromString("3c9ebe1a-9098-43fd-bc0c-a369b76817ba"); + } else if (string == "npc1") { + return null; + } + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + }; + } + + @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() { + return new ConsoleCommandSender() { + @Override + public void sendMessage(String message) { + System.out.println("Console message: " + message); + } + + @Override + public void sendMessage(String[] messages) { + for (String message : messages) { + System.out.println("Console message: " + message); + } + } + + @Override + public Server getServer() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public String getName() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isPermissionSet(String name) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isPermissionSet(Permission perm) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean hasPermission(String name) { + return true; + } + + @Override + public boolean hasPermission(Permission perm) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public PermissionAttachment addAttachment(Plugin plugin) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value, int ticks) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public PermissionAttachment addAttachment(Plugin plugin, int ticks) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void removeAttachment(PermissionAttachment attachment) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void recalculatePermissions() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Set getEffectivePermissions() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isOp() { + return true; + } + + @Override + public void setOp(boolean value) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isConversing() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void acceptConversationInput(String input) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean beginConversation(Conversation conversation) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void abandonConversation(Conversation conversation) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void abandonConversation(Conversation conversation, ConversationAbandonedEvent details) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void sendRawMessage(String message) { + 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."); + } + + @Override + public String getMotd() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public WarningState getWarningState() { + return WarningState.DEFAULT; + } + + @Override + public int getAmbientSpawnLimit() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public String getShutdownMessage() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public ItemFactory getItemFactory() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public ScoreboardManager getScoreboardManager() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public CachedServerIcon getServerIcon() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public CachedServerIcon loadServerIcon(File file) throws IllegalArgumentException, Exception { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public CachedServerIcon loadServerIcon(BufferedImage bufferedImage) throws IllegalArgumentException, Exception { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void setIdleTimeout(int i) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public int getIdleTimeout() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public UnsafeValues getUnsafe() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public BanList getBanList(BanList.Type arg0) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Player getPlayer(UUID arg0) { + for (Player player : players) { + if (player.getUniqueId().equals(arg0)) { + return player; + } + } + return null; + } + + @Override + public org.bukkit.OfflinePlayer getOfflinePlayer(UUID arg0) { + if (arg0.toString().equalsIgnoreCase("3c9ebe1a-9098-43fd-bc0c-a369b76817ba")) { + return createOPlayer("testPlayer1"); + } + if (arg0.toString().equalsIgnoreCase("f4a37409-5c40-3b2c-9cd6-57d3c5abdc76")) { + return createOPlayer("npc1"); + } + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Inventory createInventory(InventoryHolder arg0, InventoryType arg1, String arg2) { + throw new UnsupportedOperationException("Not supported yet."); + } + + + class FakePluginManager implements PluginManager { + ArrayList listeners = new ArrayList(); + + @Override + public void registerInterface(Class loader) throws IllegalArgumentException { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Plugin getPlugin(String name) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Plugin[] getPlugins() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public boolean isPluginEnabled(String name) { + 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 directory) { + 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) throws IllegalStateException { + Logger.getLogger("Minecraft").info("Called event " + event.getEventName()); + if (event instanceof PlayerJoinEvent) { + for (RegisteredListener listener : listeners) { + if (listener.getListener() instanceof EssentialsPlayerListener) { + PlayerJoinEvent jEvent = (PlayerJoinEvent) event; + EssentialsPlayerListener epl = (EssentialsPlayerListener) listener.getListener(); + epl.onPlayerJoin(jEvent); + Essentials ess = (Essentials) listener.getPlugin(); + ess.getLogger().info("Sending join event to Essentials"); + ess.getUser(jEvent.getPlayer()); + } + } + } + } + + @Override + public void registerEvents(Listener listener, Plugin plugin) { + listeners.add(new RegisteredListener(listener, null, null, plugin, false)); + } + + @Override + public void registerEvent(Class event, Listener listener, EventPriority priority, EventExecutor executor, Plugin plugin) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void registerEvent(Class event, Listener listener, EventPriority priority, EventExecutor executor, Plugin plugin, boolean ignoreCancelled) { + 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 name) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void addPermission(Permission perm) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void removePermission(Permission perm) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void removePermission(String name) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Set getDefaultPermissions(boolean op) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void recalculatePermissionDefaults(Permission perm) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void subscribeToPermission(String permission, Permissible permissible) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void unsubscribeFromPermission(String permission, Permissible permissible) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Set getPermissionSubscriptions(String permission) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void subscribeToDefaultPerms(boolean op, Permissible permissible) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void unsubscribeFromDefaultPerms(boolean op, Permissible permissible) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Set getDefaultPermSubscriptions(boolean op) { + 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."); + } + } + + ; } diff --git a/Essentials/test/com/earth2me/essentials/StorageTest.java b/Essentials/test/com/earth2me/essentials/StorageTest.java index 617d3c6b3..7982e8397 100644 --- a/Essentials/test/com/earth2me/essentials/StorageTest.java +++ b/Essentials/test/com/earth2me/essentials/StorageTest.java @@ -1,6 +1,5 @@ package com.earth2me.essentials; -import java.io.IOException; import junit.framework.TestCase; import org.bukkit.Location; import org.bukkit.World; @@ -8,55 +7,48 @@ import org.bukkit.World.Environment; import org.bukkit.plugin.InvalidDescriptionException; import org.junit.Test; +import java.io.IOException; -public class StorageTest extends TestCase -{ - Essentials ess; - FakeServer server; - World world; - public StorageTest() - { - server = new FakeServer(); - world = server.createWorld("testWorld", Environment.NORMAL); - ess = new Essentials(server); - try - { - ess.setupForTesting(server); - } - catch (InvalidDescriptionException ex) - { - fail("InvalidDescriptionException"); - } - catch (IOException ex) - { - fail("IOException"); - } - } +public class StorageTest extends TestCase { + Essentials ess; + FakeServer server; + World world; - @Test - public void testOldUserdata() - { - ExecuteTimer ext = new ExecuteTimer(); - ext.start(); - OfflinePlayer base1 = server.createPlayer("testPlayer1"); - 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()); - } + public StorageTest() { + server = new FakeServer(); + world = server.createWorld("testWorld", Environment.NORMAL); + ess = new Essentials(server); + try { + ess.setupForTesting(server); + } catch (InvalidDescriptionException ex) { + fail("InvalidDescriptionException"); + } catch (IOException ex) { + fail("IOException"); + } + } + + @Test + public void testOldUserdata() { + ExecuteTimer ext = new ExecuteTimer(); + ext.start(); + OfflinePlayer base1 = server.createPlayer("testPlayer1"); + 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/ToggleTest.java b/Essentials/test/com/earth2me/essentials/ToggleTest.java index d3a496df9..330ac7ccb 100644 --- a/Essentials/test/com/earth2me/essentials/ToggleTest.java +++ b/Essentials/test/com/earth2me/essentials/ToggleTest.java @@ -2,268 +2,173 @@ package com.earth2me.essentials; import com.earth2me.essentials.commands.IEssentialsCommand; import com.earth2me.essentials.commands.NoChargeException; -import java.io.IOException; import junit.framework.TestCase; import org.bukkit.World.Environment; import org.bukkit.command.CommandSender; import org.bukkit.plugin.InvalidDescriptionException; +import java.io.IOException; -public class ToggleTest extends TestCase -{ - private final OfflinePlayer base1; - private final Essentials ess; - private final FakeServer server; - public ToggleTest(String testName) - { - super(testName); - server = new FakeServer(); - server.createWorld("testWorld", Environment.NORMAL); - ess = new Essentials(server); - try - { - ess.setupForTesting(server); - } - catch (InvalidDescriptionException ex) - { - fail("InvalidDescriptionException"); - } - catch (IOException ex) - { - fail("IOException"); - } - base1 = server.createPlayer("testPlayer1"); - server.addPlayer(base1); - ess.getUser(base1); - } +public class ToggleTest extends TestCase { + private final OfflinePlayer base1; + private final Essentials ess; + private final FakeServer server; - private void runCommand(String command, User user, String[] args) throws Exception - { - IEssentialsCommand cmd; + public ToggleTest(String testName) { + super(testName); + server = new FakeServer(); + server.createWorld("testWorld", Environment.NORMAL); + ess = new Essentials(server); + try { + ess.setupForTesting(server); + } catch (InvalidDescriptionException ex) { + fail("InvalidDescriptionException"); + } catch (IOException ex) { + fail("IOException"); + } + base1 = server.createPlayer("testPlayer1"); + server.addPlayer(base1); + ess.getUser(base1); + } - try - { - cmd = (IEssentialsCommand)Essentials.class.getClassLoader().loadClass("com.earth2me.essentials.commands.Command" + command).newInstance(); - cmd.setEssentials(ess); - cmd.run(server, user, command, null, args); - } - catch (NoChargeException ex) - { - } + private void runCommand(String command, User user, String[] args) throws Exception { + IEssentialsCommand cmd; - } + try { + cmd = (IEssentialsCommand) Essentials.class.getClassLoader().loadClass("com.earth2me.essentials.commands.Command" + command).newInstance(); + cmd.setEssentials(ess); + cmd.run(server, user, command, null, args); + } catch (NoChargeException ex) { + } - private void runConsoleCommand(String command, String[] args) throws Exception - { - IEssentialsCommand cmd; + } - CommandSender sender = server.getConsoleSender(); + private void runConsoleCommand(String command, String[] args) throws Exception { + IEssentialsCommand cmd; - try - { - cmd = (IEssentialsCommand)Essentials.class.getClassLoader().loadClass("com.earth2me.essentials.commands.Command" + command).newInstance(); - cmd.setEssentials(ess); - cmd.run(server, new CommandSource(sender), command, null, args); - } - catch (NoChargeException ex) - { - } + CommandSender sender = server.getConsoleSender(); - } + try { + cmd = (IEssentialsCommand) Essentials.class.getClassLoader().loadClass("com.earth2me.essentials.commands.Command" + command).newInstance(); + cmd.setEssentials(ess); + cmd.run(server, new CommandSource(sender), command, null, args); + } catch (NoChargeException ex) { + } - public void testFlyToggle() throws Exception - { - User user = ess.getUser(base1); + } - assertFalse(user.getBase().getAllowFlight()); + public void testFlyToggle() throws Exception { + User user = ess.getUser(base1); - runCommand("fly", user, new String[] - { - "on" - }); - assertTrue(user.getBase().getAllowFlight()); + assertFalse(user.getBase().getAllowFlight()); - runCommand("fly", user, new String[] - { - "on" - }); - assertTrue(user.getBase().getAllowFlight()); + runCommand("fly", user, new String[]{"on"}); + assertTrue(user.getBase().getAllowFlight()); - runCommand("fly", user, new String[] - { - "off" - }); - assertFalse(user.getBase().getAllowFlight()); + runCommand("fly", user, new String[]{"on"}); + assertTrue(user.getBase().getAllowFlight()); - runCommand("fly", user, new String[] - { - "off" - }); - assertFalse(user.getBase().getAllowFlight()); + runCommand("fly", user, new String[]{"off"}); + assertFalse(user.getBase().getAllowFlight()); - runCommand("fly", user, new String[] - { - }); - assertTrue(user.getBase().getAllowFlight()); + runCommand("fly", user, new String[]{"off"}); + assertFalse(user.getBase().getAllowFlight()); - runCommand("fly", user, new String[] - { - }); - assertFalse(user.getBase().getAllowFlight()); - } + runCommand("fly", user, new String[]{}); + assertTrue(user.getBase().getAllowFlight()); - public void testFlyDisOnToggle() throws Exception - { - User user = ess.getUser(base1); + runCommand("fly", user, new String[]{}); + assertFalse(user.getBase().getAllowFlight()); + } - user.getBase().setAllowFlight(true); - user.getBase().setFlying(true); - assertTrue(user.getBase().isFlying()); - runCommand("fly", user, new String[] - { - }); - assertFalse(user.getBase().getAllowFlight()); - assertFalse(user.getBase().isFlying()); - } + public void testFlyDisOnToggle() throws Exception { + User user = ess.getUser(base1); - public void testGodToggle() throws Exception - { - User user = ess.getUser(base1); + user.getBase().setAllowFlight(true); + user.getBase().setFlying(true); + assertTrue(user.getBase().isFlying()); + runCommand("fly", user, new String[]{}); + assertFalse(user.getBase().getAllowFlight()); + assertFalse(user.getBase().isFlying()); + } - assertFalse(user.isGodModeEnabled()); + public void testGodToggle() throws Exception { + User user = ess.getUser(base1); - runCommand("god", user, new String[] - { - "on" - }); - assertTrue(user.isGodModeEnabled()); + assertFalse(user.isGodModeEnabled()); - runCommand("god", user, new String[] - { - "on" - }); - assertTrue(user.isGodModeEnabled()); + runCommand("god", user, new String[]{"on"}); + assertTrue(user.isGodModeEnabled()); - runCommand("god", user, new String[] - { - "off" - }); - assertFalse(user.isGodModeEnabled()); + runCommand("god", user, new String[]{"on"}); + assertTrue(user.isGodModeEnabled()); - runCommand("god", user, new String[] - { - "off" - }); - assertFalse(user.isGodModeEnabled()); + runCommand("god", user, new String[]{"off"}); + assertFalse(user.isGodModeEnabled()); - runCommand("god", user, new String[] - { - }); - assertTrue(user.isGodModeEnabled()); + runCommand("god", user, new String[]{"off"}); + assertFalse(user.isGodModeEnabled()); - runCommand("god", user, new String[] - { - }); - assertFalse(user.isGodModeEnabled()); - } + runCommand("god", user, new String[]{}); + assertTrue(user.isGodModeEnabled()); - public void testConsoleToggle() throws Exception - { - User user = ess.getUser(base1); + runCommand("god", user, new String[]{}); + assertFalse(user.isGodModeEnabled()); + } - assertFalse(user.getBase().getAllowFlight()); + public void testConsoleToggle() throws Exception { + User user = ess.getUser(base1); - runConsoleCommand("fly", new String[] - { - base1.getName(), "on" - }); - assertTrue(user.getBase().getAllowFlight()); + assertFalse(user.getBase().getAllowFlight()); - runConsoleCommand("fly", new String[] - { - base1.getName(), "on" - }); - assertTrue(user.getBase().getAllowFlight()); + runConsoleCommand("fly", new String[]{base1.getName(), "on"}); + assertTrue(user.getBase().getAllowFlight()); - runConsoleCommand("fly", new String[] - { - base1.getName(), "off" - }); - assertFalse(user.getBase().getAllowFlight()); + runConsoleCommand("fly", new String[]{base1.getName(), "on"}); + assertTrue(user.getBase().getAllowFlight()); - runConsoleCommand("fly", new String[] - { - base1.getName(), "off" - }); - assertFalse(user.getBase().getAllowFlight()); + runConsoleCommand("fly", new String[]{base1.getName(), "off"}); + assertFalse(user.getBase().getAllowFlight()); - runConsoleCommand("fly", new String[] - { - base1.getName() - }); - assertTrue(user.getBase().getAllowFlight()); + runConsoleCommand("fly", new String[]{base1.getName(), "off"}); + assertFalse(user.getBase().getAllowFlight()); - runConsoleCommand("fly", new String[] - { - base1.getName() - }); - assertFalse(user.getBase().getAllowFlight()); - } + runConsoleCommand("fly", new String[]{base1.getName()}); + assertTrue(user.getBase().getAllowFlight()); - public void testAliasesToggle() throws Exception - { - User user = ess.getUser(base1); + runConsoleCommand("fly", new String[]{base1.getName()}); + assertFalse(user.getBase().getAllowFlight()); + } - assertFalse(user.getBase().getAllowFlight()); + public void testAliasesToggle() throws Exception { + User user = ess.getUser(base1); - runConsoleCommand("fly", new String[] - { - base1.getName(), "enable" - }); - assertTrue(user.getBase().getAllowFlight()); + assertFalse(user.getBase().getAllowFlight()); - runConsoleCommand("fly", new String[] - { - base1.getName(), "enable" - }); - assertTrue(user.getBase().getAllowFlight()); + runConsoleCommand("fly", new String[]{base1.getName(), "enable"}); + assertTrue(user.getBase().getAllowFlight()); - runConsoleCommand("fly", new String[] - { - base1.getName(), "disable" - }); - assertFalse(user.getBase().getAllowFlight()); + runConsoleCommand("fly", new String[]{base1.getName(), "enable"}); + assertTrue(user.getBase().getAllowFlight()); - runConsoleCommand("fly", new String[] - { - base1.getName(), "disable" - }); - assertFalse(user.getBase().getAllowFlight()); + runConsoleCommand("fly", new String[]{base1.getName(), "disable"}); + assertFalse(user.getBase().getAllowFlight()); - runConsoleCommand("fly", new String[] - { - base1.getName(), "1" - }); - assertTrue(user.getBase().getAllowFlight()); + runConsoleCommand("fly", new String[]{base1.getName(), "disable"}); + assertFalse(user.getBase().getAllowFlight()); - runConsoleCommand("fly", new String[] - { - base1.getName(), "1" - }); - assertTrue(user.getBase().getAllowFlight()); + runConsoleCommand("fly", new String[]{base1.getName(), "1"}); + assertTrue(user.getBase().getAllowFlight()); - runConsoleCommand("fly", new String[] - { - base1.getName(), "0" - }); - assertFalse(user.getBase().getAllowFlight()); + runConsoleCommand("fly", new String[]{base1.getName(), "1"}); + assertTrue(user.getBase().getAllowFlight()); - runConsoleCommand("fly", new String[] - { - base1.getName(), "0" - }); - assertFalse(user.getBase().getAllowFlight()); + runConsoleCommand("fly", new String[]{base1.getName(), "0"}); + assertFalse(user.getBase().getAllowFlight()); - } + runConsoleCommand("fly", new String[]{base1.getName(), "0"}); + assertFalse(user.getBase().getAllowFlight()); + + } } diff --git a/Essentials/test/com/earth2me/essentials/UserTest.java b/Essentials/test/com/earth2me/essentials/UserTest.java index 7bae28c31..23b0ba581 100644 --- a/Essentials/test/com/earth2me/essentials/UserTest.java +++ b/Essentials/test/com/earth2me/essentials/UserTest.java @@ -1,97 +1,83 @@ package com.earth2me.essentials; -import java.io.IOException; -import java.math.BigDecimal; import junit.framework.TestCase; import net.ess3.api.MaxMoneyException; import org.bukkit.Location; import org.bukkit.World.Environment; import org.bukkit.plugin.InvalidDescriptionException; +import java.io.IOException; +import java.math.BigDecimal; -public class UserTest extends TestCase -{ - private final OfflinePlayer base1; - private final Essentials ess; - private final FakeServer server; - public UserTest(String testName) - { - super(testName); - server = new FakeServer(); - server.createWorld("testWorld", Environment.NORMAL); - ess = new Essentials(server); - try - { - ess.setupForTesting(server); - } - catch (InvalidDescriptionException ex) - { - fail("InvalidDescriptionException"); - } - catch (IOException ex) - { - fail("IOException"); - } - base1 = server.createPlayer("testPlayer1"); - server.addPlayer(base1); - ess.getUser(base1); - } +public class UserTest extends TestCase { + private final OfflinePlayer base1; + private final Essentials ess; + private final FakeServer server; - private void should(String what) - { - System.out.println(getName() + " should " + what); - } + public UserTest(String testName) { + super(testName); + server = new FakeServer(); + server.createWorld("testWorld", Environment.NORMAL); + ess = new Essentials(server); + try { + ess.setupForTesting(server); + } catch (InvalidDescriptionException ex) { + fail("InvalidDescriptionException"); + } catch (IOException ex) { + fail("IOException"); + } + base1 = server.createPlayer("testPlayer1"); + server.addPlayer(base1); + ess.getUser(base1); + } - public void testUpdate() - { - OfflinePlayer base1alt = server.createPlayer(base1.getName()); - assertEquals(base1alt, ess.getUser(base1alt).getBase()); - } + private void should(String what) { + System.out.println(getName() + " should " + what); + } - public void testHome() - { - User user = ess.getUser(base1); - Location loc = base1.getLocation(); - user.setHome("home", loc); - OfflinePlayer base2 = server.createPlayer(base1.getName()); - User user2 = ess.getUser(base2); + public void testUpdate() { + OfflinePlayer base1alt = server.createPlayer(base1.getName()); + assertEquals(base1alt, ess.getUser(base1alt).getBase()); + } - 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 testHome() { + User user = ess.getUser(base1); + Location loc = base1.getLocation(); + user.setHome("home", loc); + OfflinePlayer base2 = server.createPlayer(base1.getName()); + User user2 = ess.getUser(base2); - public void testMoney() - { - should("properly set, take, give, and get money"); - User user = ess.getUser(base1); - BigDecimal i = new BigDecimal("100.5"); - try - { - user.setMoney(i); - user.takeMoney(new BigDecimal(50)); - i = i.subtract(BigDecimal.valueOf(50)); - user.giveMoney(new BigDecimal(25)); - i = i.add(BigDecimal.valueOf(25)); - } - catch (MaxMoneyException ex) - { - fail(); - } - - assertEquals(user.getMoney(), i); - } + 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 testGetGroup() - { - should("return the default group"); - User user = ess.getUser(base1); - assertEquals(user.getGroup(), "default"); - } + public void testMoney() { + should("properly set, take, give, and get money"); + User user = ess.getUser(base1); + BigDecimal i = new BigDecimal("100.5"); + try { + user.setMoney(i); + user.takeMoney(new BigDecimal(50)); + i = i.subtract(BigDecimal.valueOf(50)); + user.giveMoney(new BigDecimal(25)); + i = i.add(BigDecimal.valueOf(25)); + } catch (MaxMoneyException ex) { + fail(); + } + + assertEquals(user.getMoney(), i); + } + + public void testGetGroup() { + should("return the default group"); + User user = ess.getUser(base1); + assertEquals(user.getGroup(), "default"); + } } diff --git a/Essentials/test/com/earth2me/essentials/UtilTest.java b/Essentials/test/com/earth2me/essentials/UtilTest.java index 497d26d7a..9bf4717ef 100644 --- a/Essentials/test/com/earth2me/essentials/UtilTest.java +++ b/Essentials/test/com/earth2me/essentials/UtilTest.java @@ -2,204 +2,192 @@ package com.earth2me.essentials; import com.earth2me.essentials.utils.DateUtil; import com.earth2me.essentials.utils.LocationUtil; +import junit.framework.TestCase; +import org.bukkit.World.Environment; +import org.bukkit.plugin.InvalidDescriptionException; + import java.io.IOException; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.HashSet; import java.util.Set; -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 class UtilTest extends TestCase { + private final Essentials ess; + private final FakeServer server; - public UtilTest() - { - server = new FakeServer(); - server.createWorld("testWorld", Environment.NORMAL); - ess = new Essentials(server); - try - { - ess.setupForTesting(server); - } - catch (InvalidDescriptionException ex) - { - fail("InvalidDescriptionException"); - } - catch (IOException ex) - { - fail("IOException"); - } - } + public UtilTest() { + server = new FakeServer(); + server.createWorld("testWorld", Environment.NORMAL); + ess = new Essentials(server); + try { + ess.setupForTesting(server); + } catch (InvalidDescriptionException ex) { + fail("InvalidDescriptionException"); + } catch (IOException ex) { + fail("IOException"); + } + } - public void testSafeLocation() - { - Set testSet = new HashSet(); - int count = 0; - int x, y, z, origX, origY, origZ; - x = y = z = origX = origY = origZ = 0; - int i = 0; - while (true) - { - testSet.add(x + ":" + y + ":" + z); - count++; - i++; - if (i >= LocationUtil.VOLUME.length) - { - break; - } - x = origX + LocationUtil.VOLUME[i].x; - y = origY + LocationUtil.VOLUME[i].y; - z = origZ + LocationUtil.VOLUME[i].z; - } - assertTrue(testSet.contains("0:0:0")); - assertTrue(testSet.contains("3:3:3")); - assertEquals(testSet.size(), count); - int diameter = LocationUtil.RADIUS * 2 + 1; - assertEquals(diameter * diameter * diameter, count); - } + public void testSafeLocation() { + Set testSet = new HashSet(); + int count = 0; + int x, y, z, origX, origY, origZ; + x = y = z = origX = origY = origZ = 0; + int i = 0; + while (true) { + testSet.add(x + ":" + y + ":" + z); + count++; + i++; + if (i >= LocationUtil.VOLUME.length) { + break; + } + x = origX + LocationUtil.VOLUME[i].x; + y = origY + LocationUtil.VOLUME[i].y; + z = origZ + LocationUtil.VOLUME[i].z; + } + assertTrue(testSet.contains("0:0:0")); + assertTrue(testSet.contains("3:3:3")); + assertEquals(testSet.size(), count); + int diameter = LocationUtil.RADIUS * 2 + 1; + assertEquals(diameter * diameter * diameter, count); + } - public void testFDDnow() - { - Calendar c = new GregorianCalendar(); - String resp = DateUtil.formatDateDiff(c, c); - assertEquals(resp, "now"); - } + public void testFDDnow() { + Calendar c = new GregorianCalendar(); + String resp = DateUtil.formatDateDiff(c, c); + assertEquals(resp, "now"); + } - 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", 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", 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 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", 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", 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", 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", 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", 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", DateUtil.formatDateDiff(a, b)); + } } diff --git a/EssentialsAntiBuild/pom.xml b/EssentialsAntiBuild/pom.xml index 66eae3c20..45deb6a4e 100644 --- a/EssentialsAntiBuild/pom.xml +++ b/EssentialsAntiBuild/pom.xml @@ -1,51 +1,51 @@ - 4.0.0 + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - - net.ess3 - EssentialsParent - 2.x-SNAPSHOT - + + net.ess3 + EssentialsParent + 2.x-SNAPSHOT + - EssentialsAntiBuild + EssentialsAntiBuild - http://ess3.net/ + http://ess3.net/ - - Essentials Team - http://ess3.net/ - + + Essentials Team + http://ess3.net/ + - - - GPLv3 - http://www.gnu.org/copyleft/gpl.html - - + + + GPLv3 + http://www.gnu.org/copyleft/gpl.html + + - - scm:git:https://github.com/essentials/Essentials.git - scm:git:https://github.com/essentials/Essentials.git - https://github.com/essentials/Essentials - + + scm:git:https://github.com/essentials/Essentials.git + scm:git:https://github.com/essentials/Essentials.git + https://github.com/essentials/Essentials + - - JIRA - http://essentials3.atlassian.net - + + JIRA + http://essentials3.atlassian.net + - - TeamCity - http://ci.ess3.net/ - + + TeamCity + http://ci.ess3.net/ + - - - net.ess3 - Essentials - ${project.version} - - + + + net.ess3 + Essentials + ${project.version} + + \ No newline at end of file diff --git a/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/AntiBuildConfig.java b/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/AntiBuildConfig.java index f0cdfcef4..7b7efc172 100644 --- a/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/AntiBuildConfig.java +++ b/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/AntiBuildConfig.java @@ -1,74 +1,65 @@ package com.earth2me.essentials.antibuild; -public enum AntiBuildConfig -{ - disable_build("protect.disable.build", true), - disable_use("protect.disable.use", true), - 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"), - blacklist_dispenser("protect.blacklist.dispenser"); - private final String configName; - private final String defValueString; - private final boolean defValueBoolean; - private final boolean isList; - private final boolean isString; +public enum AntiBuildConfig { + disable_build("protect.disable.build", true), + disable_use("protect.disable.use", true), + 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"), + blacklist_dispenser("protect.blacklist.dispenser"); + private final String configName; + private final String defValueString; + private final boolean defValueBoolean; + private final boolean isList; + private final boolean isString; - private AntiBuildConfig(final String configName) - { - this(configName, null, false, true, false); - } + private AntiBuildConfig(final String configName) { + this(configName, null, false, true, false); + } - private AntiBuildConfig(final String configName, final boolean defValueBoolean) - { - this(configName, null, defValueBoolean, false, false); - } + private AntiBuildConfig(final String configName, final boolean defValueBoolean) { + this(configName, null, defValueBoolean, false, false); + } - private AntiBuildConfig(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; - } + private AntiBuildConfig(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 configName + */ + public String getConfigName() { + return configName; + } - /** - * @return the default value String - */ - public String getDefaultValueString() - { - return defValueString; - } + /** + * @return the default value String + */ + public String getDefaultValueString() { + return defValueString; + } - /** - * @return the default value boolean - */ - public boolean getDefaultValueBoolean() - { - return defValueBoolean; - } + /** + * @return the default value boolean + */ + public boolean getDefaultValueBoolean() { + return defValueBoolean; + } - public boolean isString() - { - return isString; - } + public boolean isString() { + return isString; + } - public boolean isList() - { - return isList; - } + public boolean isList() { + return isList; + } } diff --git a/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/EssentialsAntiBuild.java b/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/EssentialsAntiBuild.java index 8654b9949..41378ad3a 100644 --- a/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/EssentialsAntiBuild.java +++ b/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/EssentialsAntiBuild.java @@ -1,63 +1,56 @@ package com.earth2me.essentials.antibuild; -import java.util.EnumMap; -import java.util.List; -import java.util.Map; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; -public class EssentialsAntiBuild extends JavaPlugin implements IAntiBuild -{ - private final transient Map settingsBoolean = new EnumMap(AntiBuildConfig.class); - private final transient Map> settingsList = new EnumMap>(AntiBuildConfig.class); - private transient EssentialsConnect ess = null; - @Override - public void onEnable() - { - final PluginManager pm = this.getServer().getPluginManager(); - final Plugin essPlugin = pm.getPlugin("Essentials"); - if (essPlugin == null || !essPlugin.isEnabled()) - { - return; - } - ess = new EssentialsConnect(essPlugin, this); +public class EssentialsAntiBuild extends JavaPlugin implements IAntiBuild { + private final transient Map settingsBoolean = new EnumMap(AntiBuildConfig.class); + private final transient Map> settingsList = new EnumMap>(AntiBuildConfig.class); + private transient EssentialsConnect ess = null; - final EssentialsAntiBuildListener blockListener = new EssentialsAntiBuildListener(this); - pm.registerEvents(blockListener, this); - } + @Override + public void onEnable() { + final PluginManager pm = this.getServer().getPluginManager(); + final Plugin essPlugin = pm.getPlugin("Essentials"); + if (essPlugin == null || !essPlugin.isEnabled()) { + return; + } + ess = new EssentialsConnect(essPlugin, this); - @Override - public boolean checkProtectionItems(final AntiBuildConfig list, final int id) - { - final List itemList = settingsList.get(list); - return itemList != null && !itemList.isEmpty() && itemList.contains(id); - } + final EssentialsAntiBuildListener blockListener = new EssentialsAntiBuildListener(this); + pm.registerEvents(blockListener, this); + } - @Override - public EssentialsConnect getEssentialsConnect() - { - return ess; - } + @Override + public boolean checkProtectionItems(final AntiBuildConfig list, final int id) { + final List itemList = settingsList.get(list); + return itemList != null && !itemList.isEmpty() && itemList.contains(id); + } - @Override - public Map getSettingsBoolean() - { - return settingsBoolean; - } + @Override + public EssentialsConnect getEssentialsConnect() { + return ess; + } - @Override - public Map> getSettingsList() - { - return settingsList; - } + @Override + public Map getSettingsBoolean() { + return settingsBoolean; + } - @Override - public boolean getSettingBool(final AntiBuildConfig protectConfig) - { - final Boolean bool = settingsBoolean.get(protectConfig); - return bool == null ? protectConfig.getDefaultValueBoolean() : bool; - } + @Override + public Map> getSettingsList() { + return settingsList; + } + + @Override + public boolean getSettingBool(final AntiBuildConfig protectConfig) { + final Boolean bool = settingsBoolean.get(protectConfig); + return bool == null ? protectConfig.getDefaultValueBoolean() : bool; + } } diff --git a/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/EssentialsAntiBuildListener.java b/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/EssentialsAntiBuildListener.java index f9e924931..f879c80b4 100644 --- a/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/EssentialsAntiBuildListener.java +++ b/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/EssentialsAntiBuildListener.java @@ -1,9 +1,7 @@ package com.earth2me.essentials.antibuild; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; import net.ess3.api.IEssentials; -import java.util.logging.Level; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.Entity; @@ -21,305 +19,240 @@ import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.inventory.ItemStack; +import java.util.logging.Level; -public class EssentialsAntiBuildListener implements Listener -{ - final private transient IAntiBuild prot; - final private transient IEssentials ess; +import static com.earth2me.essentials.I18n.tl; - public EssentialsAntiBuildListener(final IAntiBuild parent) - { - this.prot = parent; - this.ess = prot.getEssentialsConnect().getEssentials(); - } - private boolean metaPermCheck(final User user, final String action, final Block block) - { - if (block == null) - { - if (ess.getSettings().isDebug()) - { - ess.getLogger().log(Level.INFO, "AntiBuild permission check failed, invalid block."); - } - return false; - } - return metaPermCheck(user, action, block.getTypeId(), block.getData()); - } +public class EssentialsAntiBuildListener implements Listener { + final private transient IAntiBuild prot; + final private transient IEssentials ess; - private boolean metaPermCheck(final User user, final String action, final int blockId) - { - final String blockPerm = "essentials.build." + action + "." + blockId; - return user.isAuthorized(blockPerm); - } + public EssentialsAntiBuildListener(final IAntiBuild parent) { + this.prot = parent; + this.ess = prot.getEssentialsConnect().getEssentials(); + } - private boolean metaPermCheck(final User user, final String action, final int blockId, final short data) - { - final String blockPerm = "essentials.build." + action + "." + blockId; - final String dataPerm = blockPerm + ":" + data; + private boolean metaPermCheck(final User user, final String action, final Block block) { + if (block == null) { + if (ess.getSettings().isDebug()) { + ess.getLogger().log(Level.INFO, "AntiBuild permission check failed, invalid block."); + } + return false; + } + return metaPermCheck(user, action, block.getTypeId(), block.getData()); + } - if (user.getBase().isPermissionSet(dataPerm)) - { - return user.isAuthorized(dataPerm); - } - else - { - if (ess.getSettings().isDebug()) - { - ess.getLogger().log(Level.INFO, "DataValue perm on " + user.getName() + " is not directly set: " + dataPerm); - } - } + private boolean metaPermCheck(final User user, final String action, final int blockId) { + final String blockPerm = "essentials.build." + action + "." + blockId; + return user.isAuthorized(blockPerm); + } - return user.isAuthorized(blockPerm); - } + private boolean metaPermCheck(final User user, final String action, final int blockId, final short data) { + final String blockPerm = "essentials.build." + action + "." + blockId; + final String dataPerm = blockPerm + ":" + data; - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockPlace(final BlockPlaceEvent event) - { - final User user = ess.getUser(event.getPlayer()); - final Block block = event.getBlockPlaced(); - final int typeId = block.getTypeId(); - final Material type = block.getType(); + if (user.getBase().isPermissionSet(dataPerm)) { + return user.isAuthorized(dataPerm); + } else { + if (ess.getSettings().isDebug()) { + ess.getLogger().log(Level.INFO, "DataValue perm on " + user.getName() + " is not directly set: " + dataPerm); + } + } - if (prot.getSettingBool(AntiBuildConfig.disable_build) && !user.canBuild() && !user.isAuthorized("essentials.build") - && !metaPermCheck(user, "place", block)) - { - if (ess.getSettings().warnOnBuildDisallow()) - { - user.sendMessage(tl("antiBuildPlace", type.toString())); - } - event.setCancelled(true); - return; - } + return user.isAuthorized(blockPerm); + } - if (prot.checkProtectionItems(AntiBuildConfig.blacklist_placement, typeId) && !user.isAuthorized("essentials.protect.exemptplacement")) - { - if (ess.getSettings().warnOnBuildDisallow()) - { - user.sendMessage(tl("antiBuildPlace", type.toString())); - } - event.setCancelled(true); - return; - } + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockPlace(final BlockPlaceEvent event) { + final User user = ess.getUser(event.getPlayer()); + final Block block = event.getBlockPlaced(); + final int typeId = block.getTypeId(); + final Material type = block.getType(); - if (prot.checkProtectionItems(AntiBuildConfig.alert_on_placement, typeId) - && !user.isAuthorized("essentials.protect.alerts.notrigger")) - { - prot.getEssentialsConnect().alert(user, type.toString(), tl("alertPlaced")); - } - } + if (prot.getSettingBool(AntiBuildConfig.disable_build) && !user.canBuild() && !user.isAuthorized("essentials.build") && !metaPermCheck(user, "place", block)) { + if (ess.getSettings().warnOnBuildDisallow()) { + user.sendMessage(tl("antiBuildPlace", type.toString())); + } + event.setCancelled(true); + return; + } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockBreak(final BlockBreakEvent event) - { - final User user = ess.getUser(event.getPlayer()); - final Block block = event.getBlock(); - final int typeId = block.getTypeId(); - final Material type = block.getType(); + if (prot.checkProtectionItems(AntiBuildConfig.blacklist_placement, typeId) && !user.isAuthorized("essentials.protect.exemptplacement")) { + if (ess.getSettings().warnOnBuildDisallow()) { + user.sendMessage(tl("antiBuildPlace", type.toString())); + } + event.setCancelled(true); + return; + } - if (prot.getSettingBool(AntiBuildConfig.disable_build) && !user.canBuild() && !user.isAuthorized("essentials.build") - && !metaPermCheck(user, "break", block)) - { - if (ess.getSettings().warnOnBuildDisallow()) - { - user.sendMessage(tl("antiBuildBreak", type.toString())); - } - event.setCancelled(true); - return; - } + if (prot.checkProtectionItems(AntiBuildConfig.alert_on_placement, typeId) && !user.isAuthorized("essentials.protect.alerts.notrigger")) { + prot.getEssentialsConnect().alert(user, type.toString(), tl("alertPlaced")); + } + } - if (prot.checkProtectionItems(AntiBuildConfig.blacklist_break, typeId) - && !user.isAuthorized("essentials.protect.exemptbreak")) - { - if (ess.getSettings().warnOnBuildDisallow()) - { - user.sendMessage(tl("antiBuildBreak", type.toString())); - } - event.setCancelled(true); - return; - } + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockBreak(final BlockBreakEvent event) { + final User user = ess.getUser(event.getPlayer()); + final Block block = event.getBlock(); + final int typeId = block.getTypeId(); + final Material type = block.getType(); - if (prot.checkProtectionItems(AntiBuildConfig.alert_on_break, typeId) - && !user.isAuthorized("essentials.protect.alerts.notrigger")) - { - prot.getEssentialsConnect().alert(user, type.toString(), tl("alertBroke")); - } - } + if (prot.getSettingBool(AntiBuildConfig.disable_build) && !user.canBuild() && !user.isAuthorized("essentials.build") && !metaPermCheck(user, "break", block)) { + if (ess.getSettings().warnOnBuildDisallow()) { + user.sendMessage(tl("antiBuildBreak", type.toString())); + } + event.setCancelled(true); + return; + } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onHangingBreak(final HangingBreakByEntityEvent event) - { - final Entity entity = event.getRemover(); - if (entity instanceof Player) - { - final User user = ess.getUser((Player)entity); - final EntityType type = event.getEntity().getType(); - final boolean warn = ess.getSettings().warnOnBuildDisallow(); - if (prot.getSettingBool(AntiBuildConfig.disable_build) && !user.canBuild() && !user.isAuthorized("essentials.build")) - { - if (type == EntityType.PAINTING && !metaPermCheck(user, "break", Material.PAINTING.getId())) - { - if (warn) - { - user.sendMessage(tl("antiBuildBreak", Material.PAINTING.toString())); - } - event.setCancelled(true); - } - else if(type == EntityType.ITEM_FRAME && !metaPermCheck(user, "break", Material.ITEM_FRAME.getId())) - { - if (warn) - { - user.sendMessage(tl("antiBuildBreak", Material.ITEM_FRAME.toString())); - } - event.setCancelled(true); - } - } - } - } + if (prot.checkProtectionItems(AntiBuildConfig.blacklist_break, typeId) && !user.isAuthorized("essentials.protect.exemptbreak")) { + if (ess.getSettings().warnOnBuildDisallow()) { + user.sendMessage(tl("antiBuildBreak", type.toString())); + } + event.setCancelled(true); + return; + } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockPistonExtend(final BlockPistonExtendEvent event) - { - for (Block block : event.getBlocks()) - { - if (prot.checkProtectionItems(AntiBuildConfig.blacklist_piston, block.getTypeId())) - { - event.setCancelled(true); - return; - } - } - } + if (prot.checkProtectionItems(AntiBuildConfig.alert_on_break, typeId) && !user.isAuthorized("essentials.protect.alerts.notrigger")) { + prot.getEssentialsConnect().alert(user, type.toString(), tl("alertBroke")); + } + } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockPistonRetract(final BlockPistonRetractEvent event) - { - if (!event.isSticky()) - { - return; - } - final Block block = event.getRetractLocation().getBlock(); - if (prot.checkProtectionItems(AntiBuildConfig.blacklist_piston, block.getTypeId())) - { - event.setCancelled(true); - } - } + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onHangingBreak(final HangingBreakByEntityEvent event) { + final Entity entity = event.getRemover(); + if (entity instanceof Player) { + final User user = ess.getUser((Player) entity); + final EntityType type = event.getEntity().getType(); + final boolean warn = ess.getSettings().warnOnBuildDisallow(); + if (prot.getSettingBool(AntiBuildConfig.disable_build) && !user.canBuild() && !user.isAuthorized("essentials.build")) { + if (type == EntityType.PAINTING && !metaPermCheck(user, "break", Material.PAINTING.getId())) { + if (warn) { + user.sendMessage(tl("antiBuildBreak", Material.PAINTING.toString())); + } + event.setCancelled(true); + } else if (type == EntityType.ITEM_FRAME && !metaPermCheck(user, "break", Material.ITEM_FRAME.getId())) { + if (warn) { + user.sendMessage(tl("antiBuildBreak", Material.ITEM_FRAME.toString())); + } + event.setCancelled(true); + } + } + } + } - @EventHandler(priority = EventPriority.LOW) - public void onPlayerInteract(final PlayerInteractEvent event) - { - // Do not return if cancelled, because the interact event has 2 cancelled states. - final User user = ess.getUser(event.getPlayer()); - final ItemStack item = event.getItem(); + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockPistonExtend(final BlockPistonExtendEvent event) { + for (Block block : event.getBlocks()) { + if (prot.checkProtectionItems(AntiBuildConfig.blacklist_piston, block.getTypeId())) { + event.setCancelled(true); + return; + } + } + } - if (item != null - && prot.checkProtectionItems(AntiBuildConfig.blacklist_usage, item.getTypeId()) - && !user.isAuthorized("essentials.protect.exemptusage")) - { - if (ess.getSettings().warnOnBuildDisallow()) - { - user.sendMessage(tl("antiBuildUse", item.getType().toString())); - } - event.setCancelled(true); - return; - } + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockPistonRetract(final BlockPistonRetractEvent event) { + if (!event.isSticky()) { + return; + } + final Block block = event.getRetractLocation().getBlock(); + if (prot.checkProtectionItems(AntiBuildConfig.blacklist_piston, block.getTypeId())) { + event.setCancelled(true); + } + } - if (item != null - && prot.checkProtectionItems(AntiBuildConfig.alert_on_use, item.getTypeId()) - && !user.isAuthorized("essentials.protect.alerts.notrigger")) - { - prot.getEssentialsConnect().alert(user, item.getType().toString(), tl("alertUsed")); - } + @EventHandler(priority = EventPriority.LOW) + public void onPlayerInteract(final PlayerInteractEvent event) { + // Do not return if cancelled, because the interact event has 2 cancelled states. + final User user = ess.getUser(event.getPlayer()); + final ItemStack item = event.getItem(); - if (prot.getSettingBool(AntiBuildConfig.disable_use) && !user.canBuild() && !user.isAuthorized("essentials.build")) - { - if (event.hasItem() && !metaPermCheck(user, "interact", item.getTypeId(), item.getDurability())) - { - event.setCancelled(true); - if (ess.getSettings().warnOnBuildDisallow()) - { - user.sendMessage(tl("antiBuildUse", item.getType().toString())); - } - return; - } - if (event.hasBlock() && !metaPermCheck(user, "interact", event.getClickedBlock())) - { - event.setCancelled(true); - if (ess.getSettings().warnOnBuildDisallow()) - { - user.sendMessage(tl("antiBuildInteract", event.getClickedBlock().getType().toString())); - } - } - } - } + if (item != null && prot.checkProtectionItems(AntiBuildConfig.blacklist_usage, item.getTypeId()) && !user.isAuthorized("essentials.protect.exemptusage")) { + if (ess.getSettings().warnOnBuildDisallow()) { + user.sendMessage(tl("antiBuildUse", item.getType().toString())); + } + event.setCancelled(true); + return; + } - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onCraftItemEvent(final CraftItemEvent event) - { - HumanEntity entity = event.getWhoClicked(); + if (item != null && prot.checkProtectionItems(AntiBuildConfig.alert_on_use, item.getTypeId()) && !user.isAuthorized("essentials.protect.alerts.notrigger")) { + prot.getEssentialsConnect().alert(user, item.getType().toString(), tl("alertUsed")); + } - if (entity instanceof Player) - { - final User user = ess.getUser((Player)entity); - final ItemStack item = event.getRecipe().getResult(); + if (prot.getSettingBool(AntiBuildConfig.disable_use) && !user.canBuild() && !user.isAuthorized("essentials.build")) { + if (event.hasItem() && !metaPermCheck(user, "interact", item.getTypeId(), item.getDurability())) { + event.setCancelled(true); + if (ess.getSettings().warnOnBuildDisallow()) { + user.sendMessage(tl("antiBuildUse", item.getType().toString())); + } + return; + } + if (event.hasBlock() && !metaPermCheck(user, "interact", event.getClickedBlock())) { + event.setCancelled(true); + if (ess.getSettings().warnOnBuildDisallow()) { + user.sendMessage(tl("antiBuildInteract", event.getClickedBlock().getType().toString())); + } + } + } + } - if (prot.getSettingBool(AntiBuildConfig.disable_use) && !user.canBuild() && !user.isAuthorized("essentials.build")) - { - if (!metaPermCheck(user, "craft", item.getTypeId(), item.getDurability())) - { - event.setCancelled(true); - if (ess.getSettings().warnOnBuildDisallow()) - { - user.sendMessage(tl("antiBuildCraft", item.getType().toString())); - } - } - } - } - } + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onCraftItemEvent(final CraftItemEvent event) { + HumanEntity entity = event.getWhoClicked(); - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onPlayerPickupItem(PlayerPickupItemEvent event) - { + if (entity instanceof Player) { + final User user = ess.getUser((Player) entity); + final ItemStack item = event.getRecipe().getResult(); - final User user = ess.getUser(event.getPlayer()); - final ItemStack item = event.getItem().getItemStack(); + if (prot.getSettingBool(AntiBuildConfig.disable_use) && !user.canBuild() && !user.isAuthorized("essentials.build")) { + if (!metaPermCheck(user, "craft", item.getTypeId(), item.getDurability())) { + event.setCancelled(true); + if (ess.getSettings().warnOnBuildDisallow()) { + user.sendMessage(tl("antiBuildCraft", item.getType().toString())); + } + } + } + } + } - if (prot.getSettingBool(AntiBuildConfig.disable_use) && !user.canBuild() && !user.isAuthorized("essentials.build")) - { - if (!metaPermCheck(user, "pickup", item.getTypeId(), item.getDurability())) - { - event.setCancelled(true); - event.getItem().setPickupDelay(50); - } - } - } + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onPlayerPickupItem(PlayerPickupItemEvent event) { - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onPlayerDropItem(final PlayerDropItemEvent event) - { + final User user = ess.getUser(event.getPlayer()); + final ItemStack item = event.getItem().getItemStack(); - final User user = ess.getUser(event.getPlayer()); - final ItemStack item = event.getItemDrop().getItemStack(); + if (prot.getSettingBool(AntiBuildConfig.disable_use) && !user.canBuild() && !user.isAuthorized("essentials.build")) { + if (!metaPermCheck(user, "pickup", item.getTypeId(), item.getDurability())) { + event.setCancelled(true); + event.getItem().setPickupDelay(50); + } + } + } - if (prot.getSettingBool(AntiBuildConfig.disable_use) && !user.canBuild() && !user.isAuthorized("essentials.build")) - { - if (!metaPermCheck(user, "drop", item.getTypeId(), item.getDurability())) - { - event.setCancelled(true); - user.getBase().updateInventory(); - if (ess.getSettings().warnOnBuildDisallow()) - { - user.sendMessage(tl("antiBuildDrop", item.getType().toString())); - } - } - } - } + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onPlayerDropItem(final PlayerDropItemEvent event) { - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onBlockDispense(final BlockDispenseEvent event) - { - final ItemStack item = event.getItem(); - if (prot.checkProtectionItems(AntiBuildConfig.blacklist_dispenser, item.getTypeId())) - { - event.setCancelled(true); - } - } + final User user = ess.getUser(event.getPlayer()); + final ItemStack item = event.getItemDrop().getItemStack(); + + if (prot.getSettingBool(AntiBuildConfig.disable_use) && !user.canBuild() && !user.isAuthorized("essentials.build")) { + if (!metaPermCheck(user, "drop", item.getTypeId(), item.getDurability())) { + event.setCancelled(true); + user.getBase().updateInventory(); + if (ess.getSettings().warnOnBuildDisallow()) { + user.sendMessage(tl("antiBuildDrop", item.getType().toString())); + } + } + } + } + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onBlockDispense(final BlockDispenseEvent event) { + final ItemStack item = event.getItem(); + if (prot.checkProtectionItems(AntiBuildConfig.blacklist_dispenser, item.getTypeId())) { + event.setCancelled(true); + } + } } diff --git a/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/EssentialsConnect.java b/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/EssentialsConnect.java index 2a7b4ecf7..c2a8f7a2d 100644 --- a/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/EssentialsConnect.java +++ b/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/EssentialsConnect.java @@ -2,79 +2,65 @@ package com.earth2me.essentials.antibuild; import com.earth2me.essentials.IConf; import com.earth2me.essentials.User; -import static com.earth2me.essentials.I18n.tl; import net.ess3.api.IEssentials; -import java.util.logging.Level; -import java.util.logging.Logger; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; +import java.util.logging.Level; +import java.util.logging.Logger; -public class EssentialsConnect -{ - private static final Logger LOGGER = Logger.getLogger("Minecraft"); - private final transient IEssentials ess; - private final transient IAntiBuild protect; - - public EssentialsConnect(Plugin essPlugin, Plugin essProtect) - { - if (!essProtect.getDescription().getVersion().equals(essPlugin.getDescription().getVersion())) - { - LOGGER.log(Level.WARNING, tl("versionMismatchAll")); - } - ess = (IEssentials)essPlugin; - protect = (IAntiBuild)essProtect; - AntiBuildReloader pr = new AntiBuildReloader(); - pr.reloadConfig(); - ess.addReloadListener(pr); - } - - public void onDisable() - { - } - - public IEssentials getEssentials() - { - return ess; - } - - public void alert(final User user, final String item, final String type) - { - final Location loc = user.getLocation(); - final String warnMessage = tl("alertFormat", user.getName(), type, item, - loc.getWorld().getName() + "," + loc.getBlockX() + "," - + loc.getBlockY() + "," + loc.getBlockZ()); - LOGGER.log(Level.WARNING, warnMessage); - for (Player p : ess.getServer().getOnlinePlayers()) - { - final User alertUser = ess.getUser(p); - if (alertUser.isAuthorized("essentials.protect.alerts")) - { - alertUser.sendMessage(warnMessage); - } - } - } +import static com.earth2me.essentials.I18n.tl; - private class AntiBuildReloader implements IConf - { - @Override - public void reloadConfig() - { - for (AntiBuildConfig protectConfig : AntiBuildConfig.values()) - { - if (protectConfig.isList()) - { - protect.getSettingsList().put(protectConfig, ess.getSettings().getProtectList(protectConfig.getConfigName())); - } - else - { - protect.getSettingsBoolean().put(protectConfig, ess.getSettings().getProtectBoolean(protectConfig.getConfigName(), protectConfig.getDefaultValueBoolean())); - } +public class EssentialsConnect { + private static final Logger LOGGER = Logger.getLogger("Minecraft"); + private final transient IEssentials ess; + private final transient IAntiBuild protect; - } + public EssentialsConnect(Plugin essPlugin, Plugin essProtect) { + if (!essProtect.getDescription().getVersion().equals(essPlugin.getDescription().getVersion())) { + LOGGER.log(Level.WARNING, tl("versionMismatchAll")); + } + ess = (IEssentials) essPlugin; + protect = (IAntiBuild) essProtect; + AntiBuildReloader pr = new AntiBuildReloader(); + pr.reloadConfig(); + ess.addReloadListener(pr); + } - } - } + public void onDisable() { + } + + public IEssentials getEssentials() { + return ess; + } + + public void alert(final User user, final String item, final String type) { + final Location loc = user.getLocation(); + final String warnMessage = tl("alertFormat", user.getName(), type, item, loc.getWorld().getName() + "," + loc.getBlockX() + "," + loc.getBlockY() + "," + loc.getBlockZ()); + LOGGER.log(Level.WARNING, warnMessage); + for (Player p : ess.getServer().getOnlinePlayers()) { + final User alertUser = ess.getUser(p); + if (alertUser.isAuthorized("essentials.protect.alerts")) { + alertUser.sendMessage(warnMessage); + } + } + } + + + private class AntiBuildReloader implements IConf { + @Override + public void reloadConfig() { + for (AntiBuildConfig protectConfig : AntiBuildConfig.values()) { + if (protectConfig.isList()) { + protect.getSettingsList().put(protectConfig, ess.getSettings().getProtectList(protectConfig.getConfigName())); + } else { + protect.getSettingsBoolean().put(protectConfig, ess.getSettings().getProtectBoolean(protectConfig.getConfigName(), protectConfig.getDefaultValueBoolean())); + } + + } + + } + } } diff --git a/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/IAntiBuild.java b/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/IAntiBuild.java index c7b370006..bfb8facd3 100644 --- a/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/IAntiBuild.java +++ b/EssentialsAntiBuild/src/com/earth2me/essentials/antibuild/IAntiBuild.java @@ -1,19 +1,19 @@ package com.earth2me.essentials.antibuild; +import org.bukkit.plugin.Plugin; + import java.util.List; import java.util.Map; -import org.bukkit.plugin.Plugin; -public interface IAntiBuild extends Plugin -{ - boolean checkProtectionItems(final AntiBuildConfig list, final int id); +public interface IAntiBuild extends Plugin { + boolean checkProtectionItems(final AntiBuildConfig list, final int id); - boolean getSettingBool(final AntiBuildConfig protectConfig); + boolean getSettingBool(final AntiBuildConfig protectConfig); - EssentialsConnect getEssentialsConnect(); + EssentialsConnect getEssentialsConnect(); - Map getSettingsBoolean(); + Map getSettingsBoolean(); - Map> getSettingsList(); + Map> getSettingsList(); } diff --git a/EssentialsChat/pom.xml b/EssentialsChat/pom.xml index 20916f31f..8289affc1 100644 --- a/EssentialsChat/pom.xml +++ b/EssentialsChat/pom.xml @@ -1,51 +1,51 @@ - 4.0.0 + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - - net.ess3 - EssentialsParent - 2.x-SNAPSHOT - + + net.ess3 + EssentialsParent + 2.x-SNAPSHOT + - EssentialsChat + EssentialsChat - http://ess3.net/ + http://ess3.net/ - - Essentials Team - http://ess3.net/ - + + Essentials Team + http://ess3.net/ + - - - GPLv3 - http://www.gnu.org/copyleft/gpl.html - - + + + GPLv3 + http://www.gnu.org/copyleft/gpl.html + + - - scm:git:https://github.com/essentials/Essentials.git - scm:git:https://github.com/essentials/Essentials.git - https://github.com/essentials/Essentials - + + scm:git:https://github.com/essentials/Essentials.git + scm:git:https://github.com/essentials/Essentials.git + https://github.com/essentials/Essentials + - - JIRA - http://essentials3.atlassian.net - + + JIRA + http://essentials3.atlassian.net + - - TeamCity - http://ci.ess3.net/ - + + TeamCity + http://ci.ess3.net/ + - - - net.ess3 - Essentials - ${project.version} - - + + + net.ess3 + Essentials + ${project.version} + + \ No newline at end of file diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/ChatStore.java b/EssentialsChat/src/com/earth2me/essentials/chat/ChatStore.java index 8e40a3dff..d82cbb63f 100644 --- a/EssentialsChat/src/com/earth2me/essentials/chat/ChatStore.java +++ b/EssentialsChat/src/com/earth2me/essentials/chat/ChatStore.java @@ -5,47 +5,39 @@ import com.earth2me.essentials.User; import net.ess3.api.IEssentials; -public class ChatStore -{ - private final User user; - private final String type; - private final Trade charge; - private long radius; +public class ChatStore { + private final User user; + private final String type; + private final Trade charge; + private long radius; - ChatStore(final IEssentials ess, final User user, final String type) - { - this.user = user; - this.type = type; - this.charge = new Trade(getLongType(), ess); - } + ChatStore(final IEssentials ess, final User user, final String type) { + this.user = user; + this.type = type; + this.charge = new Trade(getLongType(), ess); + } - public User getUser() - { - return user; - } + public User getUser() { + return user; + } - public Trade getCharge() - { - return charge; - } + public Trade getCharge() { + return charge; + } - public String getType() - { - return type; - } + public String getType() { + return type; + } - public final String getLongType() - { - return type.length() == 0 ? "chat" : "chat-" + type; - } + public final String getLongType() { + return type.length() == 0 ? "chat" : "chat-" + type; + } - public long getRadius() - { - return radius; - } + public long getRadius() { + return radius; + } - public void setRadius(long radius) - { - this.radius = radius; - } + public void setRadius(long radius) { + this.radius = radius; + } } diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChat.java b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChat.java index d8b40d36c..4374f56cd 100644 --- a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChat.java +++ b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChat.java @@ -1,44 +1,42 @@ package com.earth2me.essentials.chat; -import static com.earth2me.essentials.I18n.tl; import net.ess3.api.IEssentials; +import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; -import org.bukkit.event.player.AsyncPlayerChatEvent; -import org.bukkit.plugin.PluginManager; -import org.bukkit.plugin.java.JavaPlugin; + +import static com.earth2me.essentials.I18n.tl; -public class EssentialsChat extends JavaPlugin -{ - private static final Logger LOGGER = Logger.getLogger("Minecraft"); +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"); - if (!this.getDescription().getVersion().equals(ess.getDescription().getVersion())) - { - LOGGER.log(Level.WARNING, tl("versionMismatchAll")); - } - if (!ess.isEnabled()) - { - this.setEnabled(false); - return; - } + @Override + public void onEnable() { + final PluginManager pluginManager = getServer().getPluginManager(); + final IEssentials ess = (IEssentials) pluginManager.getPlugin("Essentials"); + if (!this.getDescription().getVersion().equals(ess.getDescription().getVersion())) { + LOGGER.log(Level.WARNING, tl("versionMismatchAll")); + } + if (!ess.isEnabled()) { + this.setEnabled(false); + return; + } - final Map chatStore = Collections.synchronizedMap(new HashMap()); + final Map chatStore = Collections.synchronizedMap(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 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); - } + } } diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayer.java b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayer.java index 8b8737e14..2edb03766 100644 --- a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayer.java +++ b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayer.java @@ -4,97 +4,76 @@ import com.earth2me.essentials.ChargeException; import com.earth2me.essentials.Trade; import com.earth2me.essentials.User; import net.ess3.api.IEssentials; -import java.util.Map; -import java.util.logging.Logger; import org.bukkit.Server; import org.bukkit.event.Listener; import org.bukkit.event.player.AsyncPlayerChatEvent; +import java.util.Map; +import java.util.logging.Logger; -public abstract class EssentialsChatPlayer implements Listener -{ - protected static final Logger logger = Logger.getLogger("Minecraft"); - protected transient IEssentials ess; - 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 abstract class EssentialsChatPlayer implements Listener { + protected static final Logger logger = Logger.getLogger("Minecraft"); + protected transient IEssentials ess; + protected final transient Server server; + protected final transient Map chatStorage; - public void onPlayerChat(final AsyncPlayerChatEvent event) - { - } + public EssentialsChatPlayer(final Server server, final IEssentials ess, final Map chatStorage) { + this.ess = ess; + this.server = server; + this.chatStorage = chatStorage; + } - public boolean isAborted(final AsyncPlayerChatEvent event) - { - if (event.isCancelled()) - { - return true; - } - return false; - } + public void onPlayerChat(final AsyncPlayerChatEvent event) { + } - public String getChatType(final String message) - { - if (message.length() == 0) - { - //Ignore empty chat events generated by plugins - return ""; - } - - final char prefix = message.charAt(0); - if (prefix == ess.getSettings().getChatShout()) - { - return "shout"; - } - else if (prefix == ess.getSettings().getChatQuestion()) - { - return "question"; - } - else - { - return ""; - } - } + public boolean isAborted(final AsyncPlayerChatEvent event) { + if (event.isCancelled()) { + return true; + } + return false; + } - public ChatStore getChatStore(final AsyncPlayerChatEvent event) - { - return chatStorage.get(event); - } + public String getChatType(final String message) { + if (message.length() == 0) { + //Ignore empty chat events generated by plugins + return ""; + } - public void setChatStore(final AsyncPlayerChatEvent event, final ChatStore chatStore) - { - chatStorage.put(event, chatStore); - } + final char prefix = message.charAt(0); + if (prefix == ess.getSettings().getChatShout()) { + return "shout"; + } else if (prefix == ess.getSettings().getChatQuestion()) { + return "question"; + } else { + return ""; + } + } - public ChatStore delChatStore(final AsyncPlayerChatEvent event) - { - return chatStorage.remove(event); - } + public ChatStore getChatStore(final AsyncPlayerChatEvent event) { + return chatStorage.get(event); + } - protected void charge(final User user, final Trade charge) throws ChargeException - { - charge.charge(user); - } + public void setChatStore(final AsyncPlayerChatEvent event, final ChatStore chatStore) { + chatStorage.put(event, chatStore); + } - protected boolean charge(final AsyncPlayerChatEvent event, final ChatStore chatStore) - { - try - { - charge(chatStore.getUser(), chatStore.getCharge()); - } - catch (ChargeException e) - { - ess.showError(chatStore.getUser().getSource(), e, "\\ chat " + chatStore.getLongType()); - event.setCancelled(true); - return false; - } - return true; - } + public ChatStore delChatStore(final AsyncPlayerChatEvent event) { + return chatStorage.remove(event); + } + + protected void charge(final User user, final Trade charge) throws ChargeException { + charge.charge(user); + } + + protected boolean charge(final AsyncPlayerChatEvent event, final ChatStore chatStore) { + try { + charge(chatStore.getUser(), chatStore.getCharge()); + } catch (ChargeException e) { + ess.showError(chatStore.getUser().getSource(), e, "\\ chat " + chatStore.getLongType()); + event.setCancelled(true); + return false; + } + return true; + } } diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListenerHighest.java b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListenerHighest.java index 2a0d621a4..ce62c2bc3 100644 --- a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListenerHighest.java +++ b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListenerHighest.java @@ -1,35 +1,30 @@ package com.earth2me.essentials.chat; import net.ess3.api.IEssentials; -import java.util.Map; import org.bukkit.Server; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.AsyncPlayerChatEvent; +import java.util.Map; -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 AsyncPlayerChatEvent event) - { - final ChatStore chatStore = delChatStore(event); - if (isAborted(event) || chatStore == null) - { - return; - } +public class EssentialsChatPlayerListenerHighest extends EssentialsChatPlayer { + public EssentialsChatPlayerListenerHighest(final Server server, final IEssentials ess, final Map chatStorage) { + super(server, ess, chatStorage); + } - /** - * This file should handle charging the user for the action before returning control back - */ - charge(event, chatStore); - } + @EventHandler(priority = EventPriority.HIGHEST) + @Override + public void onPlayerChat(final AsyncPlayerChatEvent event) { + final ChatStore chatStore = delChatStore(event); + if (isAborted(event) || chatStore == null) { + return; + } + + /** + * This file should handle charging the user for the action before returning control back + */ + charge(event, chatStore); + } } diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListenerLowest.java b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListenerLowest.java index aa40a8148..a3df5215c 100644 --- a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListenerLowest.java +++ b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListenerLowest.java @@ -3,62 +3,55 @@ package com.earth2me.essentials.chat; import com.earth2me.essentials.User; import com.earth2me.essentials.utils.FormatUtil; import net.ess3.api.IEssentials; -import java.util.Locale; -import java.util.Map; import org.bukkit.Server; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.scoreboard.Team; +import java.util.Locale; +import java.util.Map; -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 AsyncPlayerChatEvent event) - { - if (isAborted(event)) - { - return; - } +public class EssentialsChatPlayerListenerLowest extends EssentialsChatPlayer { + public EssentialsChatPlayerListenerLowest(final Server server, final IEssentials ess, final Map chatStorage) { + super(server, ess, chatStorage); + } - final User user = ess.getUser(event.getPlayer()); + @EventHandler(priority = EventPriority.LOWEST) + @Override + public void onPlayerChat(final AsyncPlayerChatEvent event) { + if (isAborted(event)) { + return; + } - if (user == null) - { - event.setCancelled(true); - return; - } + final User user = ess.getUser(event.getPlayer()); - final ChatStore chatStore = new ChatStore(ess, user, getChatType(event.getMessage())); - setChatStore(event, chatStore); + if (user == null) { + event.setCancelled(true); + return; + } - /** - * This listener should apply the general chat formatting only...then return control back the event handler - */ - event.setMessage(FormatUtil.formatMessage(user, "essentials.chat", event.getMessage())); - String group = user.getGroup(); - String world = user.getWorld().getName(); - Team team = user.getBase().getScoreboard().getPlayerTeam(user.getBase()); + final ChatStore chatStore = new ChatStore(ess, user, getChatType(event.getMessage())); + setChatStore(event, chatStore); - String format = ess.getSettings().getChatFormat(group); - format = format.replace("{0}", group); - format = format.replace("{1}", world); - format = format.replace("{2}", world.substring(0, 1).toUpperCase(Locale.ENGLISH)); - format = format.replace("{3}", team == null ? "" : team.getPrefix()); - format = format.replace("{4}", team == null ? "" : team.getSuffix()); - format = format.replace("{5}", team == null ? "" : team.getDisplayName()); - synchronized (format) - { - event.setFormat(format); - } - } + /** + * This listener should apply the general chat formatting only...then return control back the event handler + */ + event.setMessage(FormatUtil.formatMessage(user, "essentials.chat", event.getMessage())); + String group = user.getGroup(); + String world = user.getWorld().getName(); + Team team = user.getBase().getScoreboard().getPlayerTeam(user.getBase()); + + String format = ess.getSettings().getChatFormat(group); + format = format.replace("{0}", group); + format = format.replace("{1}", world); + format = format.replace("{2}", world.substring(0, 1).toUpperCase(Locale.ENGLISH)); + format = format.replace("{3}", team == null ? "" : team.getPrefix()); + format = format.replace("{4}", team == null ? "" : team.getSuffix()); + format = format.replace("{5}", team == null ? "" : team.getDisplayName()); + synchronized (format) { + event.setFormat(format); + } + } } diff --git a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListenerNormal.java b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListenerNormal.java index 07e81d9d4..91bfd4c2b 100644 --- a/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListenerNormal.java +++ b/EssentialsChat/src/com/earth2me/essentials/chat/EssentialsChatPlayerListenerNormal.java @@ -1,15 +1,7 @@ package com.earth2me.essentials.chat; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.User; -import static com.earth2me.essentials.chat.EssentialsChatPlayer.logger; import net.ess3.api.IEssentials; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.logging.Level; import net.ess3.api.events.LocalChatSpyEvent; import org.bukkit.Location; import org.bukkit.Server; @@ -19,136 +11,117 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.player.AsyncPlayerChatEvent; +import java.util.*; +import java.util.logging.Level; -public class EssentialsChatPlayerListenerNormal extends EssentialsChatPlayer -{ - public EssentialsChatPlayerListenerNormal(final Server server, - final IEssentials ess, - final Map chatStorage) - { - super(server, ess, chatStorage); - } +import static com.earth2me.essentials.I18n.tl; - @EventHandler(priority = EventPriority.NORMAL) - @Override - public void onPlayerChat(final AsyncPlayerChatEvent event) - { - if (isAborted(event)) - { - return; - } - /** - * This file should handle detection of the local chat features... if local chat is enabled, we need to handle - * it here - */ - long radius = ess.getSettings().getChatRadius(); - if (radius < 1) - { - return; - } - radius *= radius; +public class EssentialsChatPlayerListenerNormal extends EssentialsChatPlayer { + public EssentialsChatPlayerListenerNormal(final Server server, final IEssentials ess, final Map chatStorage) { + super(server, ess, chatStorage); + } - final ChatStore chatStore = getChatStore(event); - final User user = chatStore.getUser(); - chatStore.setRadius(radius); + @EventHandler(priority = EventPriority.NORMAL) + @Override + public void onPlayerChat(final AsyncPlayerChatEvent event) { + if (isAborted(event)) { + return; + } - if (event.getMessage().length() > 1 && chatStore.getType().length() > 0) - { - final StringBuilder permission = new StringBuilder(); - permission.append("essentials.chat.").append(chatStore.getType()); + /** + * This file should handle detection of the local chat features... if local chat is enabled, we need to handle + * it here + */ + long radius = ess.getSettings().getChatRadius(); + if (radius < 1) { + return; + } + radius *= radius; - if (user.isAuthorized(permission.toString())) - { - final StringBuilder format = new StringBuilder(); - format.append(chatStore.getType()).append("Format"); - event.setMessage(event.getMessage().substring(1)); - event.setFormat(tl(format.toString(), event.getFormat())); - return; - } + final ChatStore chatStore = getChatStore(event); + final User user = chatStore.getUser(); + chatStore.setRadius(radius); - final StringBuilder errorMsg = new StringBuilder(); - errorMsg.append("notAllowedTo").append(chatStore.getType().substring(0, 1).toUpperCase(Locale.ENGLISH)).append(chatStore.getType().substring(1)); + if (event.getMessage().length() > 1 && chatStore.getType().length() > 0) { + final StringBuilder permission = new StringBuilder(); + permission.append("essentials.chat.").append(chatStore.getType()); - user.sendMessage(tl(errorMsg.toString())); - event.setCancelled(true); - return; - } + if (user.isAuthorized(permission.toString())) { + final StringBuilder format = new StringBuilder(); + format.append(chatStore.getType()).append("Format"); + event.setMessage(event.getMessage().substring(1)); + event.setFormat(tl(format.toString(), event.getFormat())); + return; + } - final Location loc = user.getLocation(); - final World world = loc.getWorld(); + final StringBuilder errorMsg = new StringBuilder(); + errorMsg.append("notAllowedTo").append(chatStore.getType().substring(0, 1).toUpperCase(Locale.ENGLISH)).append(chatStore.getType().substring(1)); - if (charge(event, chatStore) == false) - { - return; - } + user.sendMessage(tl(errorMsg.toString())); + event.setCancelled(true); + return; + } - Set outList = event.getRecipients(); - Set spyList = new HashSet(); + final Location loc = user.getLocation(); + final World world = loc.getWorld(); - try - { - outList.add(event.getPlayer()); - } - catch (UnsupportedOperationException ex) - { - if (ess.getSettings().isDebug()) - { - ess.getLogger().log(Level.INFO, "Plugin triggered custom chat event, local chat handling aborted.", ex); - } - return; - } - - final String format = event.getFormat(); - event.setFormat(tl("chatTypeLocal").concat(event.getFormat())); + if (charge(event, chatStore) == false) { + return; + } - logger.info(tl("localFormat", user.getName(), event.getMessage())); + Set outList = event.getRecipients(); + Set spyList = new HashSet(); - final Iterator it = outList.iterator(); - while (it.hasNext()) - { - final Player onlinePlayer = it.next(); - final User onlineUser = ess.getUser(onlinePlayer); - if (!onlineUser.equals(user)) - { - boolean abort = false; - final Location playerLoc = onlineUser.getLocation(); - if (playerLoc.getWorld() != world) - { - abort = true; - } - else - { - final double delta = playerLoc.distanceSquared(loc); - if (delta > chatStore.getRadius()) - { - abort = true; - } - } - if (abort) - { - if (onlineUser.isAuthorized("essentials.chat.spy")) - { - spyList.add(onlinePlayer); - } - it.remove(); - } - } - } + try { + outList.add(event.getPlayer()); + } catch (UnsupportedOperationException ex) { + if (ess.getSettings().isDebug()) { + ess.getLogger().log(Level.INFO, "Plugin triggered custom chat event, local chat handling aborted.", ex); + } + return; + } - if (outList.size() < 2) { - user.sendMessage(tl("localNoOne")); - } + final String format = event.getFormat(); + event.setFormat(tl("chatTypeLocal").concat(event.getFormat())); - LocalChatSpyEvent spyEvent = new LocalChatSpyEvent(event.isAsynchronous(), event.getPlayer(), format, event.getMessage(), spyList); - server.getPluginManager().callEvent(spyEvent); + logger.info(tl("localFormat", user.getName(), event.getMessage())); - if (!spyEvent.isCancelled()) - { - for (Player onlinePlayer : spyEvent.getRecipients()) - { - onlinePlayer.sendMessage(String.format(spyEvent.getFormat(), user.getDisplayName(), spyEvent.getMessage())); - } - } - } + final Iterator it = outList.iterator(); + while (it.hasNext()) { + final Player onlinePlayer = it.next(); + final User onlineUser = ess.getUser(onlinePlayer); + if (!onlineUser.equals(user)) { + boolean abort = false; + final Location playerLoc = onlineUser.getLocation(); + if (playerLoc.getWorld() != world) { + abort = true; + } else { + final double delta = playerLoc.distanceSquared(loc); + if (delta > chatStore.getRadius()) { + abort = true; + } + } + if (abort) { + if (onlineUser.isAuthorized("essentials.chat.spy")) { + spyList.add(onlinePlayer); + } + it.remove(); + } + } + } + + if (outList.size() < 2) { + user.sendMessage(tl("localNoOne")); + } + + LocalChatSpyEvent spyEvent = new LocalChatSpyEvent(event.isAsynchronous(), event.getPlayer(), format, event.getMessage(), spyList); + server.getPluginManager().callEvent(spyEvent); + + if (!spyEvent.isCancelled()) { + for (Player onlinePlayer : spyEvent.getRecipients()) { + onlinePlayer.sendMessage(String.format(spyEvent.getFormat(), user.getDisplayName(), spyEvent.getMessage())); + } + } + } } diff --git a/EssentialsGeoIP/pom.xml b/EssentialsGeoIP/pom.xml index 4e886a4bb..97b442068 100644 --- a/EssentialsGeoIP/pom.xml +++ b/EssentialsGeoIP/pom.xml @@ -1,81 +1,81 @@ - 4.0.0 + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - - net.ess3 - EssentialsParent - 2.x-SNAPSHOT - + + net.ess3 + EssentialsParent + 2.x-SNAPSHOT + - EssentialsGeoIP + EssentialsGeoIP - http://ess3.net/ + http://ess3.net/ - - Essentials Team - http://ess3.net/ - + + Essentials Team + http://ess3.net/ + - - - GPLv3 - http://www.gnu.org/copyleft/gpl.html - - + + + GPLv3 + http://www.gnu.org/copyleft/gpl.html + + - - scm:git:https://github.com/essentials/Essentials.git - scm:git:https://github.com/essentials/Essentials.git - https://github.com/essentials/Essentials - + + scm:git:https://github.com/essentials/Essentials.git + scm:git:https://github.com/essentials/Essentials.git + https://github.com/essentials/Essentials + - - JIRA - http://essentials3.atlassian.net - + + JIRA + http://essentials3.atlassian.net + - - TeamCity - http://ci.ess3.net/ - + + TeamCity + http://ci.ess3.net/ + - - - net.ess3 - Essentials - ${project.version} - - - com.maxmind.geoip - geoip-api - 1.2.11 - - + + + net.ess3 + Essentials + ${project.version} + + + com.maxmind.geoip + geoip-api + 1.2.11 + + - - - - org.apache.maven.plugins - maven-shade-plugin - 2.1 - - - package - - shade - - - - - - - com.maxmind.geoip:geoip-api - - - - - - + + + + org.apache.maven.plugins + maven-shade-plugin + 2.1 + + + package + + shade + + + + + + + com.maxmind.geoip:geoip-api + + + + + + \ No newline at end of file diff --git a/EssentialsGeoIP/src/com/earth2me/essentials/geoip/EssentialsGeoIP.java b/EssentialsGeoIP/src/com/earth2me/essentials/geoip/EssentialsGeoIP.java index aced4ccb8..8b3bdfb29 100644 --- a/EssentialsGeoIP/src/com/earth2me/essentials/geoip/EssentialsGeoIP.java +++ b/EssentialsGeoIP/src/com/earth2me/essentials/geoip/EssentialsGeoIP.java @@ -1,40 +1,37 @@ package com.earth2me.essentials.geoip; -import static com.earth2me.essentials.I18n.tl; import net.ess3.api.IEssentials; -import java.util.logging.Level; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; +import java.util.logging.Level; -public class EssentialsGeoIP extends JavaPlugin -{ - public EssentialsGeoIP() - { - } - - @Override - public void onDisable() - { - } - - @Override - public void onEnable() - { - final PluginManager pm = getServer().getPluginManager(); - final IEssentials ess = (IEssentials)pm.getPlugin("Essentials"); - if (!this.getDescription().getVersion().equals(ess.getDescription().getVersion())) - { - getLogger().log(Level.WARNING, tl("versionMismatchAll")); - } - if (!ess.isEnabled()) { - this.setEnabled(false); - return; - } - final EssentialsGeoIPPlayerListener playerListener = new EssentialsGeoIPPlayerListener(getDataFolder(), ess); - pm.registerEvents(playerListener, this); +import static com.earth2me.essentials.I18n.tl; - getLogger().log(Level.INFO, "This product includes GeoLite data created by MaxMind, available from http://www.maxmind.com/."); - } +public class EssentialsGeoIP extends JavaPlugin { + public EssentialsGeoIP() { + } + + @Override + public void onDisable() { + } + + @Override + public void onEnable() { + final PluginManager pm = getServer().getPluginManager(); + final IEssentials ess = (IEssentials) pm.getPlugin("Essentials"); + if (!this.getDescription().getVersion().equals(ess.getDescription().getVersion())) { + getLogger().log(Level.WARNING, tl("versionMismatchAll")); + } + if (!ess.isEnabled()) { + this.setEnabled(false); + return; + } + final EssentialsGeoIPPlayerListener playerListener = new EssentialsGeoIPPlayerListener(getDataFolder(), ess); + pm.registerEvents(playerListener, this); + + + 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 index a6cb28ddc..f38ff8c55 100644 --- a/EssentialsGeoIP/src/com/earth2me/essentials/geoip/EssentialsGeoIPPlayerListener.java +++ b/EssentialsGeoIP/src/com/earth2me/essentials/geoip/EssentialsGeoIPPlayerListener.java @@ -1,13 +1,18 @@ package com.earth2me.essentials.geoip; import com.earth2me.essentials.EssentialsConf; -import static com.earth2me.essentials.I18n.tl; import com.earth2me.essentials.IConf; import com.earth2me.essentials.User; -import net.ess3.api.IEssentials; import com.maxmind.geoip.Location; import com.maxmind.geoip.LookupService; import com.maxmind.geoip.regionName; +import net.ess3.api.IEssentials; +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 java.io.*; import java.net.InetAddress; import java.net.MalformedURLException; @@ -16,174 +21,131 @@ 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 static com.earth2me.essentials.I18n.tl; -public class EssentialsGeoIPPlayerListener implements Listener, IConf -{ - LookupService ls = null; - private static final Logger logger = Logger.getLogger("Minecraft"); - File databaseFile; - File dataFolder; - final EssentialsConf config; - private final transient IEssentials ess; +public class EssentialsGeoIPPlayerListener implements Listener, IConf { + LookupService ls = null; + private static final Logger logger = Logger.getLogger("Minecraft"); + File databaseFile; + File dataFolder; + final EssentialsConf config; + private final transient IEssentials ess; - public EssentialsGeoIPPlayerListener(File dataFolder, IEssentials ess) - { - this.ess = ess; - this.dataFolder = dataFolder; - this.config = new EssentialsConf(new File(dataFolder, "config.yml")); - config.setTemplateName("/config.yml", EssentialsGeoIP.class); - reloadConfig(); - } + public EssentialsGeoIPPlayerListener(File dataFolder, IEssentials ess) { + this.ess = ess; + this.dataFolder = dataFolder; + this.config = new EssentialsConf(new File(dataFolder, "config.yml")); + config.setTemplateName("/config.yml", EssentialsGeoIP.class); + reloadConfig(); + } - @EventHandler(priority = EventPriority.MONITOR) - public void onPlayerJoin(final PlayerJoinEvent event) - { - ess.runTaskAsynchronously(new Runnable() - { - @Override - public void run() - { - delayedJoin(event.getPlayer()); - } - }); - } + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerJoin(final PlayerJoinEvent event) { + ess.runTaskAsynchronously(new Runnable() { + @Override + public void run() { + delayedJoin(event.getPlayer()); + } + }); + } - public void delayedJoin(Player player) - { - User u = ess.getUser(player); - if (u.isAuthorized("essentials.geoip.hide") || player.getAddress() == null) - { - return; - } - InetAddress address = player.getAddress().getAddress(); - StringBuilder sb = new StringBuilder(); - if (config.getBoolean("database.show-cities", false)) - { - Location loc = ls.getLocation(address); - if (loc == null) - { - return; - } - if (loc.city != null) - { - sb.append(loc.city).append(", "); - } - String region = regionName.regionNameByCode(loc.countryCode, loc.region); - if (region != null) - { - sb.append(region).append(", "); - } - sb.append(loc.countryName); - } - else - { - sb.append(ls.getCountry(address).getName()); - } - if (config.getBoolean("show-on-whois", true)) - { - u.setGeoLocation(sb.toString()); - } - if (config.getBoolean("show-on-login", true) && !u.isHidden()) - { - for (Player onlinePlayer : player.getServer().getOnlinePlayers()) - { - User user = ess.getUser(onlinePlayer); - if (user.isAuthorized("essentials.geoip.show")) - { - user.sendMessage(tl("geoipJoinFormat", u.getDisplayName(), sb.toString())); - } - } - } - } + public void delayedJoin(Player player) { + User u = ess.getUser(player); + if (u.isAuthorized("essentials.geoip.hide") || player.getAddress() == null) { + return; + } + InetAddress address = player.getAddress().getAddress(); + StringBuilder sb = new StringBuilder(); + if (config.getBoolean("database.show-cities", false)) { + Location loc = ls.getLocation(address); + if (loc == null) { + return; + } + if (loc.city != null) { + sb.append(loc.city).append(", "); + } + String region = regionName.regionNameByCode(loc.countryCode, loc.region); + if (region != null) { + sb.append(region).append(", "); + } + sb.append(loc.countryName); + } else { + sb.append(ls.getCountry(address).getName()); + } + if (config.getBoolean("show-on-whois", true)) { + u.setGeoLocation(sb.toString()); + } + if (config.getBoolean("show-on-login", true) && !u.isHidden()) { + for (Player onlinePlayer : player.getServer().getOnlinePlayers()) { + User user = ess.getUser(onlinePlayer); + if (user.isAuthorized("essentials.geoip.show")) { + user.sendMessage(tl("geoipJoinFormat", u.getDisplayName(), sb.toString())); + } + } + } + } - @Override - public final void reloadConfig() - { - config.load(); + @Override + public final void reloadConfig() { + config.load(); - if (config.getBoolean("database.show-cities", false)) - { - databaseFile = new File(dataFolder, "GeoIPCity.dat"); - } - else - { - databaseFile = new File(dataFolder, "GeoIP.dat"); - } - if (!databaseFile.exists()) - { - if (config.getBoolean("database.download-if-missing", true)) - { - downloadDatabase(); - } - else - { - logger.log(Level.SEVERE, tl("cantFindGeoIpDB")); - return; - } - } - try - { - ls = new LookupService(databaseFile); - } - catch (IOException ex) - { - logger.log(Level.SEVERE, tl("cantReadGeoIpDB"), ex); - } - } + if (config.getBoolean("database.show-cities", false)) { + databaseFile = new File(dataFolder, "GeoIPCity.dat"); + } else { + databaseFile = new File(dataFolder, "GeoIP.dat"); + } + if (!databaseFile.exists()) { + if (config.getBoolean("database.download-if-missing", true)) { + downloadDatabase(); + } else { + logger.log(Level.SEVERE, tl("cantFindGeoIpDB")); + return; + } + } + try { + ls = new LookupService(databaseFile); + } catch (IOException ex) { + logger.log(Level.SEVERE, tl("cantReadGeoIpDB"), ex); + } + } - private void downloadDatabase() - { - try - { - String url; - if (config.getBoolean("database.show-cities", false)) - { - url = config.getString("database.download-url-city"); - } - else - { - url = config.getString("database.download-url"); - } - if (url == null || url.isEmpty()) - { - logger.log(Level.SEVERE, tl("geoIpUrlEmpty")); - return; - } - logger.log(Level.INFO, tl("downloadingGeoIp")); - URL downloadUrl = new URL(url); - URLConnection conn = downloadUrl.openConnection(); - conn.setConnectTimeout(10000); - conn.connect(); - InputStream input = conn.getInputStream(); - if (url.endsWith(".gz")) - { - input = new GZIPInputStream(input); - } - OutputStream output = new FileOutputStream(databaseFile); - byte[] buffer = new byte[2048]; - int length = input.read(buffer); - while (length >= 0) - { - output.write(buffer, 0, length); - length = input.read(buffer); - } - output.close(); - input.close(); - } - catch (MalformedURLException ex) - { - logger.log(Level.SEVERE, tl("geoIpUrlInvalid"), ex); - return; - } - catch (IOException ex) - { - logger.log(Level.SEVERE, tl("connectionFailed"), ex); - } - } + private void downloadDatabase() { + try { + String url; + if (config.getBoolean("database.show-cities", false)) { + url = config.getString("database.download-url-city"); + } else { + url = config.getString("database.download-url"); + } + if (url == null || url.isEmpty()) { + logger.log(Level.SEVERE, tl("geoIpUrlEmpty")); + return; + } + logger.log(Level.INFO, tl("downloadingGeoIp")); + URL downloadUrl = new URL(url); + URLConnection conn = downloadUrl.openConnection(); + conn.setConnectTimeout(10000); + conn.connect(); + InputStream input = conn.getInputStream(); + if (url.endsWith(".gz")) { + input = new GZIPInputStream(input); + } + OutputStream output = new FileOutputStream(databaseFile); + byte[] buffer = new byte[2048]; + int length = input.read(buffer); + while (length >= 0) { + output.write(buffer, 0, length); + length = input.read(buffer); + } + output.close(); + input.close(); + } catch (MalformedURLException ex) { + logger.log(Level.SEVERE, tl("geoIpUrlInvalid"), ex); + return; + } catch (IOException ex) { + logger.log(Level.SEVERE, tl("connectionFailed"), ex); + } + } } diff --git a/EssentialsGroupManager/nbproject/build-impl.xml b/EssentialsGroupManager/nbproject/build-impl.xml index df136f2ba..f0ac81068 100644 --- a/EssentialsGroupManager/nbproject/build-impl.xml +++ b/EssentialsGroupManager/nbproject/build-impl.xml @@ -19,7 +19,10 @@ is divided into following sections: - cleanup --> - + @@ -27,7 +30,7 @@ is divided into following sections: - + - + @@ -714,9 +753,12 @@ is divided into following sections: - + Must set JVM to use for profiling in profiler.info.jvm - Must set profiler agent JVM arguments in profiler.info.jvmargs.agent + Must set profiler agent JVM arguments in + profiler.info.jvmargs.agent + - + @@ -946,13 +998,15 @@ is divided into following sections: Must select some files in the IDE or set javac.includes - + - + - + - + - + @@ -995,12 +1052,14 @@ is divided into following sections: - + - + @@ -1008,7 +1067,8 @@ is divided into following sections: - + To run this application from the command line without Ant, try: @@ -1019,12 +1079,14 @@ is divided into following sections: - + - + - + This target only works when run from inside the NetBeans IDE. @@ -1106,7 +1173,8 @@ is divided into following sections: - + Must select one file in the IDE or set profile.class This target only works when run from inside the NetBeans IDE. @@ -1129,14 +1197,16 @@ is divided into following sections: - + This target only works when run from inside the NetBeans IDE. - + @@ -1163,27 +1233,33 @@ is divided into following sections: - + - + Must select one file in the IDE or set run.class - - + + Must select some files in the IDE or set test.includes - + Must select one file in the IDE or set run.class - + Must select one file in the IDE or set applet.url @@ -1195,7 +1271,8 @@ is divided into following sections: --> - + @@ -1203,7 +1280,12 @@ is divided into following sections: - + @@ -1242,10 +1324,14 @@ is divided into following sections: - + - - + + @@ -1254,15 +1340,20 @@ is divided into following sections: - + - + Must select some files in the IDE or set javac.includes - + @@ -1271,7 +1362,8 @@ is divided into following sections: - + Must select one file in the IDE or set test.class - + - + Must select one file in the IDE or set test.class Must select some method in the IDE or set test.method - + - + @@ -1358,7 +1460,8 @@ is divided into following sections: - + - build/** - dist/** - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.9.1 - - - org.apache.maven.plugins - maven-deploy-plugin - 2.8.1 - - true - - - - - - src - - *.properties - *.yml - *.csv - *.txt - - true - - - + + build/** + dist/** + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.9.1 + + + org.apache.maven.plugins + maven-deploy-plugin + 2.8.1 + + true + + + + + + src + + *.properties + *.yml + *.csv + *.txt + + true + + + - - TeamCity - GMBuildVer - UTF-8 + + TeamCity + GMBuildVer + UTF-8 - - true - 2 - 2 - 2 - 120 - none - project - true - - true - - true - - true - - true - - true - - true - - true - - true - - true - - true - - true - - true - - 0 - - 2 - - NEW_LINE - - false - - * - - 4 - - false - - NEW_LINE - - NEW_LINE - - true - - true - - true - - true - - false - - false - - 4 - - 4 - + + true + + 2 + + 2 + + 2 + + 120 + + none + + project + + true + + true + + true + + true + + true + + true + + true + + true + + true + + true + + true + + true + + true + + 0 + + 2 + + NEW_LINE + + false + + * + + 4 + + false + + NEW_LINE + + NEW_LINE + + true + + true + + true + + true + + false + + false + + 4 + + 4 + +