1
0
mirror of https://github.com/essentials/Essentials.git synced 2025-09-11 23:20:45 +02:00

Compare commits

..

167 Commits

Author SHA1 Message Date
KHobbits
d11a295ffd Merge branch '2.x' of github.com:essentials/Essentials into 2.x 2014-09-03 00:21:42 +01:00
KHobbits
ffea359661 rework /seen to be a little stricter on argument matching. 2014-08-18 21:00:03 +01:00
md_5
037456c99d Fix missed cases from previous user iteration optimizations. 2014-08-16 19:04:13 +10:00
KHobbits
5125a137f4 Make sure we close any open inventories of players who leave. 2014-08-14 01:58:17 +01:00
KHobbits
3f1c996959 Use quicker ban lookup to reduce /seen lag. 2014-08-14 01:50:31 +01:00
KHobbits
53a7cd732f Add paging to mail.
Support aliases in rule and baltop output.
2014-08-11 19:03:24 +01:00
KHobbits
4fd026ff99 Add mailFormat TL key. 2014-08-11 18:46:04 +01:00
Necrodoom
d9fbd68529 Misc clarification (socialspy and kit delay)
clarify allow-silent-join-quit
2014-08-11 00:12:43 +01:00
Necrodoom
49d80462d1 Remove outdated try-catches 2014-08-11 00:11:06 +01:00
Necrodoom
1d859e49ad Add /tempban missing syntax 2014-08-11 00:10:09 +01:00
FearFree
a2c43d822c Add amount required to notEnoughMoney TL key.
See https://essentials3.atlassian.net/browse/ESS-5125 for request.
2014-07-19 20:31:50 +01:00
KHobbits
7907565377 Formatting fixes. 2014-07-19 20:11:45 +01:00
SidShakal
d1c014fe16 Fix sticky piston retract breaking essentials sign
Sticky pistons could break signs that were mounted on blocks the pistons were retracting.

This patch extends the protection from just the piston base to include the extended piston arm and the block at the end of the piston arm as well.

This method will very likely need to be changed again when 1.8 comes out, but this should bring us a bit closer, by wrapping the block tests in a loop.
2014-07-19 20:08:38 +01:00
md_5
465041b98b Optimize player / user iteration.
* Add a method for backwards compatability with unmapped code.
* Convert all getOnlinePlayers() calls to use this method, part of the IEssentials interface
* Add a new method getOnlineUsers() Ljava/lang/Iterable;
* Convert appropriate calls to use this method
* Update Bukkit to #1945
* Update CraftBukkit to #3103
2014-07-19 20:07:50 +01:00
Alexander Likhachev
ed56afda26 Add permission check before resetting speed on login The staff of my server asked me to do this fix, but I think it is very useful for all. This commit change is to reset player fly & run speed only if player has no permission to change speed. 2014-07-19 20:07:09 +01:00
KHobbits
23f14bc2d5 If a player already exists in the usermap, don't replace it with a eco npc. 2014-07-19 18:04:35 +01:00
KHobbits
c829a32555 Clean up tempban messages to be a little clearer. 2014-07-14 21:23:56 +01:00
KHobbits
ae984c2055 Update translations from Crowdin (http://translate2.ess3.net) 2014-07-12 22:12:51 +01:00
KHobbits
0c416c8366 Remove ban check from /ess cleanup, no longer required.
Fix ban upgrade script.
2014-07-12 19:13:23 +01:00
FearFree
51be2131f7 Update to new ban method. 2014-07-12 17:40:14 +01:00
KHobbits
575a8142ff Add ban reason to /banip 2014-07-12 17:23:11 +01:00
KHobbits
093a1f677b Still give 'nickNoMore' message when removing a nickname. 2014-07-12 16:48:01 +01:00
KHobbits
8311da2653 Allow for changing of username casing without adding 'nickname' prefix. 2014-07-12 16:43:57 +01:00
KHobbits
b5976a52e0 Prevent users from setting unsafe homes when teleport safety is disabled. 2014-07-12 16:34:18 +01:00
KHobbits
4e6c98ac57 Allow people with god & fly to teleport to unsafe locations even when teleport safety is disabled. 2014-07-12 16:33:50 +01:00
KHobbits
a2c692af39 Converge ban message translations, and add reason support to default tempban tl key. 2014-07-12 16:32:42 +01:00
KHobbits
a131527a15 Switch sudo to command dispatch, this will allow vanilla commands to be executed. 2014-07-12 15:29:25 +01:00
KHobbits
0b925e6fc0 Don't cascade null usernames passed from eco api 2014-07-10 11:48:54 +01:00
KHobbits
97c8f5192e New permission :essentials.tp.position Required to use /tp [player] <x> <y> <z> 2014-07-06 18:41:12 +01:00
Necrodoom
7c372cd978 Add support for vanilla /tp <x> <y> <z> teleport syntax. 2014-07-06 18:41:01 +01:00
KHobbits
02fe58161c Allow forcing adult status on randomly generated /spawnmob mobs. 2014-07-06 18:25:00 +01:00
KHobbits
2ba2ebaa43 Update Bukkit
CB: 3092 B: 1938
2014-07-06 16:40:06 +01:00
KHobbits
549500eaf2 Show warp teleport status to teleport owner. 2014-06-28 18:10:32 +01:00
KHobbits
8e7589e450 Slightly reorder teleport messages to be less confusing. 2014-06-28 18:06:13 +01:00
KHobbits
9b69403ee1 Fix NPE with /list in console 2014-06-27 04:28:33 +01:00
KHobbits
6269ce9a3f Update essentials to support 3rd party vanish toggling. 2014-06-27 01:46:37 +01:00
KHobbits
0f6625aea9 Add some debugging to make it easier to diagnose kit errors. 2014-06-25 19:19:04 +01:00
KHobbits
dbceccaa3e Kit cleanup and refactor. 2014-06-25 19:03:31 +01:00
KHobbits
6c7ba6a76f Allow multiple kits to be spawned per command. 2014-06-23 00:38:13 +01:00
KHobbits
f76a517339 New permission: essentials.signs.trade.override.collect
People with this permission will collect the resources of other peoples trade signs broken with admin permissions (essentials.signs.trade.override).
2014-06-21 21:47:33 +01:00
Necrodoom
2c747ecf36 empty array is not null array 2014-06-19 16:22:38 +01:00
KHobbits
1f8b60081e Reduce a few nickname refresh calls. 2014-06-19 04:02:15 +01:00
KHobbits
a800359e0b Force listener cleanup on plugin disable. 2014-06-19 02:59:08 +01:00
KHobbits
4854961901 Add a lag check for permission system checks.
This doesn't include normal permission checks, since the overhead could be detrimental.
2014-06-19 02:38:28 +01:00
KHobbits
50a815bdb9 Revert "Add spawn location cache to reduce blocking on player respawn."
This reverts commit 7804516793.
2014-06-17 23:27:46 +01:00
KHobbits
1690b9d83d If "sethome-multiple" config section is invalid, silently fallback to default config values. 2014-06-17 00:19:59 +01:00
KHobbits
7804516793 Add spawn location cache to reduce blocking on player respawn. 2014-06-16 19:55:34 +01:00
KHobbits
c54e9b5dba Add default ban reason for tempban reason. 2014-06-14 22:06:26 +01:00
KHobbits
71936cfe22 Check for arraynull on pex group request. 2014-06-14 18:20:49 +01:00
KHobbits
27890e2b22 Only remove first date match from ban reason. 2014-06-14 16:27:34 +01:00
KHobbits
da6df89126 Add optional {2} in 'tempBanned' TL key, for reason. 2014-06-14 16:21:05 +01:00
KHobbits
95ff197910 Show UUID in trackUUID debug message. 2014-06-07 18:21:10 +01:00
KHobbits
2215b0f53f Don't allow old UUID's to accidentally overwrite current UUID for user mapping.
Add some extra logging and uuid debug.
2014-06-07 18:08:25 +01:00
KHobbits
3887fdd47d New permission: essentials.itemspawn.meta-vanilla
Without this permission you cannot use vanilla itemmeta.  You can still use essentials style meta, if you have the appropriate permissions.
2014-06-07 16:08:51 +01:00
KHobbits
7e9328bd25 Try to use consistent UUIDs and not rely on Bukkit lookup while saving. 2014-06-07 15:45:57 +01:00
KHobbits
9d9af25c7f Add local echo of mail being sent on /mail send. 2014-06-05 00:07:27 +01:00
KHobbits
5a2fd19bcf Fix firework recipe in /recipe 2014-06-04 16:13:20 +01:00
KHobbits
3a50850734 Use strings for cachemap key, should prevent accidental key issues. 2014-06-01 21:50:24 +01:00
KHobbits
812de5c35c Add API logging to Eco API. 2014-05-31 20:37:44 +01:00
KHobbits
bffea1d7c8 Extend getUser(Object) to match uuid and offline players. 2014-05-30 22:16:06 +01:00
KHobbits
b00f458e67 Emulate player join for mocking. 2014-05-27 21:14:45 +01:00
KHobbits
80ef955eae Improve fakeServer model 2014-05-27 20:31:13 +01:00
KHobbits
44509ff6e4 Remove online player lookup in usermap.getUUIDMap(), throw log entry on failback. 2014-05-27 18:04:02 +01:00
KHobbits
e1d4129869 Log takeMoney exception, even if we ignore it. 2014-05-27 10:46:25 +01:00
KHobbits
00655f724d Revert writecount reset, this could cause odd behavior. 2014-05-27 06:18:34 +01:00
KHobbits
4590e7ea26 Enforce userdata save on player dispose. 2014-05-27 04:52:52 +01:00
KHobbits
2ac1ce4f56 If we are modifying money, force transaction clear, this is important. 2014-05-27 03:41:18 +01:00
KHobbits
f726035660 Don't check silentjoin.vanish if another plugin has hidden the join message. 2014-05-26 22:08:18 +01:00
KHobbits
57bb1ee475 New permission: essentials.silentjoin.vanish
The server needs silentjoin to be enabled first.
2014-05-25 19:31:55 +01:00
KHobbits
889dde7549 Abort transaction before updating funds on balance overflow. 2014-05-25 17:03:23 +01:00
KHobbits
ada2fe01a2 Utilize write transactions for delaylogin task. 2014-05-25 01:38:37 +01:00
KHobbits
cf29a0ba6a Rename listening methods to be a little more descriptive of their purpose. 2014-05-24 18:47:40 +01:00
KHobbits
c929ebb89a Convert 9 anonymous scheduled tasks to named classes for better logging. 2014-05-18 21:32:07 +01:00
KHobbits
8159530906 Fix invalid TL key. 2014-05-18 19:47:18 +01:00
KHobbits
7e8ba9a256 Exempt named mobs by default from /remove
Named mobs can be removed using /remove named
Killing all mobs now requires /remove all,tamed,named
2014-05-18 14:43:07 +01:00
KHobbits
b145ec59ea Tweak to player login event. 2014-05-18 13:26:27 +01:00
KHobbits
429a7275ee Update worth.yml to be more descriptive. 2014-05-17 04:31:44 +01:00
KHobbits
3bd0608b6e Update /condense syntax hint. 2014-05-17 04:21:51 +01:00
@ArkhamNetwork
9307e0cb71 Optimize PlayerLoginEvent 2014-05-17 04:05:51 +01:00
@ArkhamNetwork
4672e51806 Move the teleport timer to an async task. 2014-05-17 03:35:44 +01:00
KHobbits
18811122b3 Prevent near empty userdata file creation. 2014-05-17 03:06:48 +01:00
KHobbits
cbaf126a25 Stop using old string player lookup. 2014-05-17 02:47:10 +01:00
KHobbits
8e7abe325e Prevent reading and writing the usermap at the same time. 2014-05-17 01:50:41 +01:00
Faris Rehman
ed9e4ecd28 Add user messages. 2014-05-16 20:39:49 +01:00
KHobbits
bd866de950 First draft of /condense 2014-05-16 20:30:06 +01:00
KHobbits
4ecb6b5fdb If Bukkit doesn't know who a player is, but we do, substitute the last known nickname when ban checking. 2014-05-10 21:52:45 +01:00
KHobbits
0d6bca2080 Update English TL keys. 2014-05-10 17:49:37 +01:00
KHobbits
05ef05dcac Update translations from crowdin (http://translate2.ess3.net/) 2014-05-10 16:11:03 +01:00
Luke Anderson (stuntguy3000)
7ba097c640 Improve messages/formatting 2014-05-10 16:03:39 +01:00
Burke D
6adacbb357 Grammatical changes to config.yml 2014-05-10 15:46:08 +01:00
clou44
69f62574c4 Updated Items.csv: Added nemofish and fishnemo.
Added shorter aliases for salmon, pufferfish, and clownfish.
2014-05-10 15:38:29 +01:00
KHobbits
b00c31730f Only dispose users who are offline at point of disposal.
This should cater for quick reconnects on lagged servers.
2014-05-10 15:36:58 +01:00
KHobbits
f09180659d Initialize TL Bundle on plugin start. 2014-05-06 07:00:57 +01:00
KHobbits
c12373bf41 Remove '-' from valid account names again.
This could cause issues with NPC's converted to UUID before this version.
2014-05-05 22:46:46 +01:00
KHobbits
04666b66b4 Reload locale even if it is set to null. 2014-05-05 20:47:48 +01:00
KHobbits
363aee70d5 Better handle TL failover. 2014-05-05 14:48:25 +01:00
KHobbits
01d03d5d41 Update teleport timer to handle UUID rather than player names. 2014-05-05 13:01:20 +01:00
KHobbits
4575fc5aff Better handle corrupted chunks. 2014-05-04 19:39:35 +01:00
ElgarL
27e9e3aa88 Error in logic 2014-05-04 17:12:15 +01:00
ElgarL
b0187698b9 Prevent players who have never logged in before from taking over existing accounts. 2014-05-04 16:22:58 +01:00
KHobbits
0364d4e0de Allow disabling userfile cache on uuid convert.
Add "ignore-userfiles-cache: true" to "upgrades-done.yml" to disable cache, forcing uuid lookup requests.
2014-05-04 13:25:20 +01:00
ElgarL
86b57804c6 Fix clones forgetting sub groups. 2014-05-04 12:50:22 +01:00
ElgarL
211dc220d8 Set a default mirror map if none is found in the config. 2014-05-04 12:50:21 +01:00
ElgarL
aae586f79a Fix overloadedWorldHolder so it correctly calls the new WorldHolder code when the user is not overloaded. 2014-05-04 12:50:20 +01:00
ElgarL
32f49350cf Fixup javadocs 2014-05-04 12:50:18 +01:00
ElgarL
9739784e75 v2.1: - Update for CraftBukkit 1.7.8-R0.1(3050). - Add UUID support. Plugins can still query by player name but a UUID is faster and preferable. 2014-05-04 12:50:17 +01:00
ElgarL
a0e93af758 Do not override higher level permissions with negations. 2014-05-04 12:50:16 +01:00
Necrodoom
81c6291338 Fix a /mangcheckp message 2014-05-04 12:50:15 +01:00
ElgarL
24509d60be Update mangcheckp to understand Exception nodes. 2014-05-04 12:50:14 +01:00
ElgarL
f0947e9a7c Fix manucheckp to understand and report correctly on Exception nodes. 2014-05-04 12:50:13 +01:00
ElgarL
92bb4e0e66 Allow Exceptions in any inherited group to override negation of permissions. 2014-05-04 12:50:12 +01:00
Necrodoom
8f810ad447 Cleanup plugin description 2014-05-04 12:50:11 +01:00
ElgarL
3f35a6b59c Prevent adding sub groups for ranks the granting player doesn't have access to. 2014-05-04 12:50:09 +01:00
ElgarL
427dd714c9 Allow Exception permission to override negations when in the same group. 2014-05-04 12:50:08 +01:00
ElgarL
9d7a2043f7 Change to use LinkedHashSets to preserve ordering. Fixes an issue with populating bukkit perms in the wrong order. Fix wildcard negation in parent groups. 2014-05-04 12:50:07 +01:00
ElgarL
ff3ec84b0d Fix Cyclic mirroring test (silly me) 2014-05-04 12:50:06 +01:00
ElgarL
1f9e72c5e2 Tidy imports 2014-05-04 12:50:05 +01:00
Necrodoom
67be18566c Improve Javadocs, clean ' strip checks, update changelog. 2014-05-04 12:50:04 +01:00
Necrodoom
862e71bc85 add recursive permission adding/removing
also other minor fixes
2014-05-04 12:50:03 +01:00
ElgarL
395655ba19 Check subgroup permissions with an equal priority so no one subgroup is higher ranked than another. 2014-05-04 12:50:02 +01:00
KHobbits
1bb569fff2 Fix attempting to spawn invalid items. 2014-04-30 05:41:42 +01:00
KHobbits
e66ad88451 Skip npc's when doing cleanup. 2014-04-29 04:42:55 +01:00
KHobbits
3bf3093177 Better handle a write locked usermap.csv 2014-04-29 01:44:28 +01:00
KHobbits
5eb82add06 Run user dispose on another thread. 2014-04-28 23:12:35 +01:00
Corin Simpson-Bryars
8bd1a9f3bc Updating pom for vault
When deploying with Jenkins the build will fail due to there being no http://repo.ess3.net:8071/content/groups/public/net/milkbowl/vault/1.2.27 however there's a valid jar/dir for vault at http://repo.ess3.net:8071/content/groups/public/net/milkbowl/vault/Vault/1.2.32/
This will keep maven happy and the build not to error.
2014-04-28 00:52:06 +01:00
KHobbits
145d24c34c Fix /home for offline players. 2014-04-27 17:09:44 +01:00
KHobbits
229ff9f0e4 Update UUID mapping, if uuid for a username changes. 2014-04-27 01:35:52 +01:00
KHobbits
0557aa58b0 Switch AFK check to use UUID. 2014-04-27 01:10:44 +01:00
KHobbits
b40aa43872 Delay uuidconversion for 10s and show warning.
UUID conversion should now better handle offline conversion.
2014-04-26 23:50:12 +01:00
KHobbits
a1cdfa19b0 Fix time command exit statuses. 2014-04-24 10:24:35 +01:00
KHobbits
d62b401db8 Skip empty user names on uuid conversion. 2014-04-22 18:07:02 +01:00
KHobbits
887957756e [Breaking] Fix ECO NPC's. This is a work around of CB's recent changes blocking invalid uuid lookups.
NPC's converted with the previous version will need manual changes.
2014-04-19 02:03:39 +01:00
KHobbits
b6d6b24796 Only write to UUIDMap if the entry doesn't exist. 2014-04-18 06:48:14 +01:00
KHobbits
b6c0871daa Format /seen account history list, optimize map loading. 2014-04-18 05:57:47 +01:00
KHobbits
b080187808 Add previous account tracking to /seen 2014-04-18 04:48:34 +01:00
KHobbits
3c613fd59b Force CB 3050+ 2014-04-18 03:58:27 +01:00
KHobbits
547c6e4073 Fix offlineplayers with null names. 2014-04-17 06:09:08 +01:00
KHobbits
6098086a99 Optimize uuidmap writing, and use userConf write buffering. 2014-04-17 05:34:34 +01:00
KHobbits
87f90e9bdd Add progress status and /ess uuidconvert command for manual conversion. 2014-04-17 02:18:28 +01:00
KHobbits
65b1821196 Update Bukkit to 1.7.8-R0.1
Bukkit: 1922 CraftBukkit: 3050
2014-04-15 00:24:12 +01:00
KHobbits
756321d280 Add UUID mocking support, and fix tests. 2014-04-15 00:08:02 +01:00
KHobbits
3dbf69f163 Allow usermap to support legacy users, and restore ability to create user on first access, as well as server join. 2014-04-15 00:07:35 +01:00
KHobbits
e8ace54036 Make eco npc methods use proper user config creation and resets. 2014-04-15 00:06:29 +01:00
KHobbits
22e1c14e7e Stop delayed writes from reversing user reset. 2014-04-15 00:05:56 +01:00
KHobbits
cd38aeb544 Remove Ess object from FakeServer. 2014-04-14 00:03:07 +01:00
KHobbits
9e9409da1e Essentials UUID conversion. 2014-04-13 21:40:15 +01:00
KHobbits
36e580474f Converted emulated player class calls to use base class. 2014-04-13 01:01:49 +01:00
clou44
e007331581 Update items.csv
Added additional aliases for various flowers.
2014-04-10 23:31:05 +01:00
clou44
8d435ec86e Update items.csv
Added additional aliases for coal blocks.
2014-04-10 23:30:58 +01:00
KHobbits
214d64e4ad Update config.yml to reflect vanilla fallback no longer works. 2014-04-07 14:09:09 +01:00
KHobbits
737fadc390 Update Bukkit 1.7.5-R0.1
Bukkit 1919 CB: 3039
No UUID update yet.
2014-04-06 15:57:37 +01:00
KHobbits
10de6ac929 Cleanup 2014-04-06 15:44:37 +01:00
KHobbits
fe9fbf585f Correctly handle line overflow in book pager
Fixes a bug with the last book pager tweak.
2014-04-05 15:33:38 +01:00
KHobbits
af3f3fb4c7 Fix fly logic check (creative doesn't mean fly is enabled) 2014-03-31 03:26:48 +01:00
KHobbits
0e6a5240db Add chat configurables. 2014-03-30 15:50:32 +01:00
KHobbits
f272a7ecd6 See if we can better handle book paging to fit more context on a line, without causing text loss after reaching character limit. 2014-03-29 16:07:32 +00:00
evonuts
104caea3c9 Minor phrasing fixes. 2014-03-26 22:08:37 +00:00
Matt Anthony
44fbd05df7 Add colors to a few TL keys. 2014-03-26 21:58:36 +00:00
KHobbits
6cfb5084e1 Add local echo to tempban command. 2014-03-26 20:08:38 +00:00
KHobbits
ae1804758a Helpop should use broadcast method
Add local echo's to helpop and mute commands.
2014-03-26 20:06:01 +00:00
Necrodoom
4b470b32c5 Add socialspy wildcard support 2014-03-26 19:09:00 +00:00
Necrodoom
cfe89dde17 Match /clearinventory multiple permission to /msg 2014-03-26 19:07:48 +00:00
Necrodoom
30dae51ddf Some messages fixes, and information addition. 2014-03-26 19:07:41 +00:00
KHobbits
0b11abf8f4 Revert "Do not allow a block with an Essentials Sign attached to it to be pulled with a sticky piston"
This reverts commit b673882b2f.
2014-03-26 15:14:40 +00:00
Chris Ward
b673882b2f Do not allow a block with an Essentials Sign attached to it to be pulled with a sticky piston 2014-03-26 22:00:57 +11:00
KHobbits
200dbda6d3 Merge branch '2.x' of github.com:essentials/Essentials into 2.x 2014-03-23 18:14:21 +00:00
FearFree
5724c0c8df Future Java versions may not support _ as identifier. 2014-03-22 16:08:11 +11:00
267 changed files with 8624 additions and 5657 deletions

2
.gitignore vendored
View File

@@ -49,3 +49,5 @@ target/
dependency-reduced-pom.xml
/Essentials/config.yml
/Essentials/userdata/testplayer1.yml
/Essentials/usermap.csv
/Essentials/userdata

View File

@@ -40,8 +40,19 @@
<system>TeamCity</system>
<url>http://ci.ess3.net/</url>
</ciManagement>
<dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
@@ -118,9 +129,9 @@
<systemPath>${project.basedir}/../lib/SimplyPerms.jar</systemPath>
</dependency>
<dependency>
<groupId>net.milkbowl</groupId>
<artifactId>vault</artifactId>
<version>1.2.27</version>
<groupId>net.milkbowl.vault</groupId>
<artifactId>Vault</artifactId>
<version>1.2.32</version>
</dependency>
<dependency>
<groupId>zPermissions</groupId>

View File

@@ -1,6 +1,6 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
@@ -24,7 +24,7 @@ public class Backup implements Runnable
{
this.ess = ess;
server = ess.getServer();
if (server.getOnlinePlayers().length > 0)
if (!ess.getOnlinePlayers().isEmpty())
{
ess.runTaskAsynchronously(new Runnable()
{
@@ -86,7 +86,7 @@ public class Backup implements Runnable
active = false;
return;
}
LOGGER.log(Level.INFO, _("backupStarted"));
LOGGER.log(Level.INFO, tl("backupStarted"));
final CommandSender cs = server.getConsoleSender();
server.dispatchCommand(cs, "save-all");
server.dispatchCommand(cs, "save-off");
@@ -146,20 +146,21 @@ public class Backup implements Runnable
}
finally
{
ess.scheduleSyncDelayedTask(new Runnable()
class BackupEnableSaveTask implements Runnable
{
@Override
public void run()
{
server.dispatchCommand(cs, "save-on");
if (server.getOnlinePlayers().length == 0)
if (ess.getOnlinePlayers().isEmpty())
{
stopTask();
}
active = false;
LOGGER.log(Level.INFO, _("backupFinished"));
LOGGER.log(Level.INFO, tl("backupFinished"));
}
});
}
ess.scheduleSyncDelayedTask(new BackupEnableSaveTask());
}
}
});

View File

@@ -142,20 +142,13 @@ public class Enchantments
ALIASENCHANTMENTS.put("unlimitedarrows", Enchantment.ARROW_INFINITE);
ALIASENCHANTMENTS.put("ai", Enchantment.ARROW_INFINITE);
try // 1.7 update
{
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);
}
catch (java.lang.NoSuchFieldError e)
{
Essentials.wrongVersion();
}
ENCHANTMENTS.put("lure", Enchantment.LURE);
ALIASENCHANTMENTS.put("rodlure", Enchantment.LURE);
}
public static Enchantment getByName(String name)

View File

@@ -17,7 +17,7 @@
*/
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
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;
@@ -35,11 +35,19 @@ import com.earth2me.essentials.textreader.IText;
import com.earth2me.essentials.textreader.KeywordReplacer;
import com.earth2me.essentials.textreader.SimpleTextInput;
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;
@@ -58,9 +66,7 @@ import org.bukkit.command.BlockCommandSender;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.PluginCommand;
import org.bukkit.command.SimpleCommandMap;
import org.bukkit.command.TabCompleter;
import org.bukkit.command.defaults.VanillaCommand;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
@@ -82,7 +88,7 @@ import org.yaml.snakeyaml.error.YAMLException;
public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials
{
public static final int BUKKIT_VERSION = 2922;
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);
@@ -100,11 +106,11 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials
private transient I18n i18n;
private transient Metrics metrics;
private transient EssentialsTimer timer;
private transient List<String> vanishedPlayers = new ArrayList<String>();
private final transient List<String> vanishedPlayers = new ArrayList<String>();
private transient Method oldGetOnlinePlayers;
public Essentials()
{
}
public Essentials(final Server server)
@@ -131,14 +137,17 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials
}
i18n = new I18n(this);
i18n.onEnable();
LOGGER.log(Level.INFO, _("usingTempFolderForTesting"));
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);
i18n.updateLocale("en");
userMap = new UserMap(this);
permissionsHandler = new PermissionsHandler(this, false);
Economy.setEss(this);
confList = new ArrayList<IConf>();
jails = new Jails(this);
registerListeners(server.getPluginManager());
}
@Override
@@ -159,7 +168,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials
&& !plugin.getDescription().getVersion().equals(this.getDescription().getVersion())
&& !plugin.getDescription().getName().equals("EssentialsAntiCheat"))
{
LOGGER.log(Level.WARNING, _("versionMismatch", plugin.getDescription().getName()));
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());
@@ -175,11 +184,21 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials
}
else
{
LOGGER.log(Level.INFO, _("bukkitFormatChanged"));
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);
@@ -189,12 +208,12 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials
settings = new Settings(this);
confList.add(settings);
execTimer.mark("Settings");
upgrade.afterSettings();
execTimer.mark("Upgrade2");
i18n.updateLocale(settings.getLocale());
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)");
@@ -211,11 +230,11 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials
{
if (pm.getPlugin("EssentialsUpdate") != null)
{
LOGGER.log(Level.SEVERE, _("essentialsHelp2"));
LOGGER.log(Level.SEVERE, tl("essentialsHelp2"));
}
else
{
LOGGER.log(Level.SEVERE, _("essentialsHelp1"));
LOGGER.log(Level.SEVERE, tl("essentialsHelp1"));
}
handleCrash(exception);
return;
@@ -244,7 +263,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials
final String timeroutput = execTimer.end();
if (getSettings().isDebug())
{
LOGGER.log(Level.INFO, "Essentials load " + timeroutput);
LOGGER.log(Level.INFO, "Essentials load {0}", timeroutput);
}
}
catch (NumberFormatException ex)
@@ -306,14 +325,14 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials
@Override
public void onDisable()
{
for (Player p : getServer().getOnlinePlayers())
for (User user : getOnlineUsers())
{
User user = getUser(p);
if (user.isVanished())
{
user.setVanished(false);
user.sendMessage(_("unvanishedReload"));
user.sendMessage(tl("unvanishedReload"));
}
user.stopTransaction();
}
cleanupOpenInventories();
if (i18n != null)
@@ -326,6 +345,9 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials
}
Economy.setEss(null);
Trade.closeLog();
getUserMap().getUUIDMap().forceWriteUUIDMap();
HandlerList.unregisterAll(this);
}
@Override
@@ -441,7 +463,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials
final List<String> mail = user.getMails();
if (mail != null && !mail.isEmpty())
{
user.sendMessage(_("youHaveNewMail", mail.size()));
user.sendMessage(tl("youHaveNewMail", mail.size()));
}
}
@@ -467,16 +489,16 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials
}
catch (Exception ex)
{
sender.sendMessage(_("commandNotLoaded", commandLabel));
LOGGER.log(Level.SEVERE, _("commandNotLoaded", commandLabel), 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, _("deniedAccessCommand", user.getName()));
user.sendMessage(_("noAccessCommand"));
LOGGER.log(Level.INFO, tl("deniedAccessCommand", user.getName()));
user.sendMessage(tl("noAccessCommand"));
return true;
}
@@ -484,11 +506,11 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials
{
if (user.getJailTimeout() > 0)
{
user.sendMessage(_("playerJailedFor", user.getName(), DateUtil.formatDateDiff(user.getJailTimeout())));
user.sendMessage(tl("playerJailedFor", user.getName(), DateUtil.formatDateDiff(user.getJailTimeout())));
}
else
{
user.sendMessage(_("jailMessage"));
user.sendMessage(tl("jailMessage"));
}
return true;
}
@@ -532,16 +554,15 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials
}
catch (Throwable ex)
{
LOGGER.log(Level.SEVERE, _("commandFailed", commandLabel), ex);
LOGGER.log(Level.SEVERE, tl("commandFailed", commandLabel), ex);
return true;
}
}
public void cleanupOpenInventories()
{
for (Player player : getServer().getOnlinePlayers())
for (User user : getOnlineUsers())
{
User user = getUser(player);
if (user.isRecipeSee())
{
user.getBase().getOpenInventory().getTopInventory().clear();
@@ -560,18 +581,18 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials
@Override
public void showError(final CommandSource sender, final Throwable exception, final String commandLabel)
{
sender.sendMessage(_("errorWithMessage", exception.getMessage()));
sender.sendMessage(tl("errorWithMessage", exception.getMessage()));
if (getSettings().isDebug())
{
LOGGER.log(Level.WARNING, _("errorCallingCommand", commandLabel), exception);
LOGGER.log(Level.INFO, tl("errorCallingCommand", commandLabel), exception);
}
}
public static void wrongVersion()
{
LOGGER.log(Level.SEVERE, " * ! * ! * ! * ! * ! * ! * ! * ! * ! * ! * ! * ! *");
LOGGER.log(Level.SEVERE, _("notRecommendedBukkit"));
LOGGER.log(Level.SEVERE, _("requiredBukkit", Integer.toString(BUKKIT_VERSION)));
LOGGER.log(Level.SEVERE, tl("notRecommendedBukkit"));
LOGGER.log(Level.SEVERE, tl("requiredBukkit", Integer.toString(BUKKIT_VERSION)));
LOGGER.log(Level.SEVERE, " * ! * ! * ! * ! * ! * ! * ! * ! * ! * ! * ! * ! *");
}
@@ -625,6 +646,14 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials
{
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);
@@ -636,7 +665,14 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials
@Override
public User getUser(final String base)
{
return getOfflineUser((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.
@@ -646,7 +682,16 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials
final User user = userMap.getUser(name);
if (user != null && user.getBase() instanceof OfflinePlayer)
{
((OfflinePlayer)user.getBase()).setName(name);
//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;
}
@@ -666,13 +711,13 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials
return null;
}
User user = userMap.getUser(base.getName());
User user = userMap.getUser(base.getUniqueId());
if (user == null)
{
if (getSettings().isDebug())
{
LOGGER.log(Level.INFO, "Constructing new userfile from base player " + base.getName());
LOGGER.log(Level.INFO, "Constructing new userfile from base player {0}", base.getName());
}
user = new User(base, this);
}
@@ -695,7 +740,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials
event.getPlayer().sendMessage("Essentials failed to load, read the log file.");
}
}, this);
for (Player player : getServer().getOnlinePlayers())
for (Player player : getOnlinePlayers())
{
player.sendMessage("Essentials failed to load, read the log file.");
}
@@ -755,7 +800,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials
IText broadcast = new SimpleTextInput(message);
final Player[] players = getServer().getOnlinePlayers();
final Collection<Player> players = getOnlinePlayers();
for (Player player : players)
{
@@ -774,7 +819,7 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials
}
}
return players.length;
return players.size();
}
@Override
@@ -788,6 +833,12 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials
{
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)
@@ -855,6 +906,43 @@ public class Essentials extends JavaPlugin implements net.ess3.api.IEssentials
return vanishedPlayers;
}
@Override
public Collection<Player> getOnlinePlayers()
{
try
{
return (Collection<Player>)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<User> getOnlineUsers()
{
return Iterables.transform(getOnlinePlayers(), new Function<Player, User>()
{
@Override
public User apply(Player player)
{
return getUser(player);
}
});
}
private static class EssentialsWorldListener implements Listener, Runnable
{

View File

@@ -54,10 +54,9 @@ public class EssentialsBlockListener implements Listener
}
final User user = ess.getUser(event.getPlayer());
if (user.hasUnlimited(is) && user.getGameMode() == GameMode.SURVIVAL)
if (user.hasUnlimited(is) && user.getBase().getGameMode() == GameMode.SURVIVAL)
{
ess.scheduleSyncDelayedTask(
new Runnable()
class UnlimitedItemSpawnTask implements Runnable
{
@Override
public void run()
@@ -65,7 +64,8 @@ public class EssentialsBlockListener implements Listener
user.getBase().getInventory().addItem(is);
user.getBase().updateInventory();
}
});
}
ess.scheduleSyncDelayedTask(new UnlimitedItemSpawnTask());
}
}
}

View File

@@ -1,6 +1,6 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.google.common.io.Files;
import java.io.*;
import java.math.BigDecimal;
@@ -15,6 +15,7 @@ import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -31,13 +32,14 @@ import org.bukkit.util.Vector;
public class EssentialsConf extends YamlConfiguration
{
private static final Logger LOGGER = Logger.getLogger("Essentials");
private final File configFile;
private String templateName = null;
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 Charset UTF8 = Charset.forName("UTF-8");
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)
{
@@ -50,14 +52,14 @@ public class EssentialsConf extends YamlConfiguration
{
if (pendingDiskWrites.get() != 0)
{
LOGGER.log(Level.INFO, "File " + configFile + " not read, because it's not yet written to disk.");
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, _("failedToCreateConfig", configFile.toString()));
LOGGER.log(Level.SEVERE, tl("failedToCreateConfig", configFile.toString()));
}
}
// This will delete files where the first character is 0. In most cases they are broken.
@@ -98,9 +100,17 @@ public class EssentialsConf extends YamlConfiguration
if (!configFile.exists())
{
if (templateName != null)
if (legacyFileExists())
{
LOGGER.log(Level.INFO, _("creatingConfigFromTemplate", configFile.toString()));
convertLegacyFile();
}
else if (altFileExists())
{
convertAltFile();
}
else if (templateName != null)
{
LOGGER.log(Level.INFO, tl("creatingConfigFromTemplate", configFile.toString()));
createFromTemplate();
}
else
@@ -180,6 +190,26 @@ public class EssentialsConf extends YamlConfiguration
}
}
public boolean legacyFileExists()
{
return false;
}
public void convertLegacyFile()
{
LOGGER.log(Level.SEVERE, "Unable to import legacy config file.");
}
public boolean altFileExists()
{
return false;
}
public void convertAltFile()
{
LOGGER.log(Level.SEVERE, "Unable to import alt config file.");
}
private void createFromTemplate()
{
InputStream istr = null;
@@ -189,7 +219,7 @@ public class EssentialsConf extends YamlConfiguration
istr = resourceClass.getResourceAsStream(templateName);
if (istr == null)
{
LOGGER.log(Level.SEVERE, _("couldNotFindTemplate", templateName));
LOGGER.log(Level.SEVERE, tl("couldNotFindTemplate", templateName));
return;
}
ostr = new FileOutputStream(configFile);
@@ -204,7 +234,7 @@ public class EssentialsConf extends YamlConfiguration
}
catch (IOException ex)
{
LOGGER.log(Level.SEVERE, _("failedToWriteConfig", configFile.toString()), ex);
LOGGER.log(Level.SEVERE, tl("failedToWriteConfig", configFile.toString()), ex);
}
finally
{
@@ -228,7 +258,7 @@ public class EssentialsConf extends YamlConfiguration
}
catch (IOException ex)
{
LOGGER.log(Level.SEVERE, _("failedToCloseConfig", configFile.toString()), ex);
LOGGER.log(Level.SEVERE, tl("failedToCloseConfig", configFile.toString()), ex);
}
}
}
@@ -249,6 +279,17 @@ public class EssentialsConf extends YamlConfiguration
this.resourceClass = resClass;
}
public void startTransaction()
{
transaction.set(true);
}
public void stopTransaction()
{
transaction.set(false);
save();
}
public void save()
{
try
@@ -269,9 +310,14 @@ public class EssentialsConf extends YamlConfiguration
@Override
public synchronized void save(final File file) throws IOException
{
delayedSave(file);
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
@@ -292,9 +338,13 @@ public class EssentialsConf extends YamlConfiguration
}
}
public synchronized void cleanup()
{
forceSave();
}
private Future<?> delayedSave(final File file)
{
//long startTime = System.nanoTime();
if (file == null)
{
throw new IllegalArgumentException("File cannot be null");
@@ -307,12 +357,8 @@ public class EssentialsConf extends YamlConfiguration
return null;
}
pendingDiskWrites.incrementAndGet();
Future<?> future = EXECUTOR_SERVICE.submit(new WriteRunner(configFile, data, pendingDiskWrites));
//LOGGER.log(Level.INFO, configFile + " prepared for writing in " + (System.nanoTime() - startTime) + " nsec.");
return future;
}
@@ -352,16 +398,16 @@ public class EssentialsConf extends YamlConfiguration
{
try
{
LOGGER.log(Level.INFO, _("creatingEmptyConfig", configFile.toString()));
LOGGER.log(Level.INFO, tl("creatingEmptyConfig", configFile.toString()));
if (!configFile.createNewFile())
{
LOGGER.log(Level.SEVERE, _("failedToCreateConfig", configFile.toString()));
LOGGER.log(Level.SEVERE, tl("failedToCreateConfig", configFile.toString()));
return;
}
}
catch (IOException ex)
{
LOGGER.log(Level.SEVERE, _("failedToCreateConfig", configFile.toString()), ex);
LOGGER.log(Level.SEVERE, tl("failedToCreateConfig", configFile.toString()), ex);
return;
}
}

View File

@@ -1,6 +1,6 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -42,20 +42,20 @@ public class EssentialsEntityListener implements Listener
}
else if (eDefend instanceof Ageable)
{
final ItemStack hand = attacker.getItemInHand();
final ItemStack hand = attacker.getBase().getItemInHand();
if (hand != null && hand.getType() == Material.MILK_BUCKET)
{
((Ageable)eDefend).setBaby();
hand.setType(Material.BUCKET);
attacker.setItemInHand(hand);
attacker.updateInventory();
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();
@@ -97,7 +97,7 @@ public class EssentialsEntityListener implements Listener
private void onPlayerVsPlayerPowertool(final EntityDamageByEntityEvent event, final Player defender, final User attacker)
{
final List<String> commandList = attacker.getPowertool(attacker.getItemInHand());
final List<String> commandList = attacker.getPowertool(attacker.getBase().getItemInHand());
if (commandList != null && !commandList.isEmpty())
{
for (final String tempCommand : commandList)
@@ -105,8 +105,8 @@ public class EssentialsEntityListener implements Listener
final String command = powertoolPlayer.matcher(tempCommand).replaceAll(defender.getName());
if (command != null && !command.isEmpty() && !command.equals(tempCommand))
{
ess.scheduleSyncDelayedTask(
new Runnable()
class PowerToolInteractTask implements Runnable
{
@Override
public void run()
@@ -114,7 +114,8 @@ public class EssentialsEntityListener implements Listener
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());
event.setCancelled(true);
return;
@@ -151,7 +152,7 @@ public class EssentialsEntityListener implements Listener
if (user.isAuthorized("essentials.back.ondeath") && !ess.getSettings().isCommandDisabled("back"))
{
user.setLastLocation();
user.sendMessage(_("backAfterDeath"));
user.sendMessage(tl("backAfterDeath"));
}
if (!ess.getSettings().areDeathMessagesEnabled())
{
@@ -180,8 +181,8 @@ public class EssentialsEntityListener implements Listener
{
if (user.isGodModeEnabledRaw())
{
user.setFoodLevel(20);
user.setSaturation(10);
user.getBase().setFoodLevel(20);
user.getBase().setSaturation(10);
}
event.setCancelled(true);
}

View File

@@ -1,11 +1,10 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
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.DateUtil;
import com.earth2me.essentials.utils.LocationUtil;
import java.io.IOException;
import java.util.Iterator;
@@ -37,25 +36,25 @@ 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)
{
@@ -63,8 +62,8 @@ public class EssentialsPlayerListener implements Listener
if (user.isMuted())
{
event.setCancelled(true);
user.sendMessage(_("voiceSilenced"));
LOGGER.info(_("mutedUserSpeaks", user.getName()));
user.sendMessage(tl("voiceSilenced"));
LOGGER.info(tl("mutedUserSpeaks", user.getName()));
}
try
{
@@ -89,11 +88,11 @@ public class EssentialsPlayerListener implements Listener
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)
{
@@ -103,19 +102,19 @@ public class EssentialsPlayerListener implements Listener
{
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())
{
@@ -146,12 +145,12 @@ public class EssentialsPlayerListener implements Listener
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);
@@ -164,7 +163,7 @@ public class EssentialsPlayerListener implements Listener
.replace("{PLAYER}", player.getDisplayName())
.replace("{USERNAME}", player.getName()));
}
if (ess.getSettings().removeGodOnDisconnect() && user.isGodModeEnabled())
{
user.setGodModeEnabled(false);
@@ -178,10 +177,23 @@ public class EssentialsPlayerListener implements Listener
{
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)
{
@@ -199,42 +211,69 @@ public class EssentialsPlayerListener implements Listener
event.setJoinMessage(null);
}
}
public void delayedJoin(final Player player, final String message)
{
if (!player.isOnline())
{
return;
}
ess.getBackup().onPlayerJoin();
final User user = ess.getUser(player);
if (user.isNPC())
final User dUser = ess.getUser(player);
if (dUser.isNPC())
{
user.setNPC(false);
dUser.setNPC(false);
}
final long currentTime = System.currentTimeMillis();
user.checkMuteTimeout(currentTime);
user.updateActivity(false);
ess.scheduleSyncDelayedTask(new Runnable()
dUser.checkMuteTimeout(currentTime);
dUser.updateActivity(false);
IText tempInput = null;
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());
}
}
}
final IText input = tempInput;
class DelayJoinTask implements Runnable
{
@Override
public void run()
{
if (!user.isOnline())
final User user = ess.getUser(player);
if (!user.getBase().isOnline())
{
return;
}
user.trackUUID();
user.startTransaction();
user.setLastAccountName(user.getBase().getName());
user.setLastLogin(currentTime);
user.setDisplayNick();
updateCompass(user);
if (!ess.getVanishedPlayers().isEmpty() && !user.isAuthorized("essentials.vanish.see"))
{
for (String p : ess.getVanishedPlayers())
@@ -242,19 +281,26 @@ public class EssentialsPlayerListener implements Listener
Player toVanish = ess.getServer().getPlayerExact(p);
if (toVanish != null && toVanish.isOnline())
{
user.hidePlayer(toVanish);
user.getBase().hidePlayer(toVanish);
}
}
}
if (user.isAuthorized("essentials.sleepingignored"))
{
user.setSleepingIgnored(true);
user.getBase().setSleepingIgnored(true);
}
if ((ess.getSettings().allowSilentJoinQuit() && user.isAuthorized("essentials.silentjoin")) || message == null)
if (ess.getSettings().allowSilentJoinQuit() && (user.isAuthorized("essentials.silentjoin") || user.isAuthorized("essentials.silentjoin.vanish")))
{
// Do nothing - silently join
if (user.isAuthorized("essentials.silentjoin.vanish"))
{
user.setVanished(true);
}
}
else if (message == null)
{
//NOOP
}
else if (ess.getSettings().isCustomJoinMessage())
{
@@ -267,57 +313,49 @@ public class EssentialsPlayerListener implements Listener
{
ess.getServer().broadcastMessage(message);
}
if (!ess.getSettings().isCommandDisabled("motd") && user.isAuthorized("essentials.motd"))
if (input != null && user.isAuthorized("essentials.motd"))
{
try
{
final IText input = new TextInput(user.getSource(), "motd", true, ess);
final IText output = new KeywordReplacer(input, user.getSource(), ess);
final TextPager pager = new TextPager(output, true);
pager.showPage("1", null, "motd", user.getSource());
}
catch (IOException ex)
{
if (ess.getSettings().isDebug())
{
LOGGER.log(Level.WARNING, ex.getMessage(), ex);
}
else
{
LOGGER.log(Level.WARNING, ex.getMessage());
}
}
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().isCommandDisabled("mail") && user.isAuthorized("essentials.mail"))
{
final List<String> mail = user.getMails();
if (mail.isEmpty())
{
user.sendMessage(_("noNewMail"));
user.sendMessage(tl("noNewMail"));
}
else
{
user.sendMessage(_("youHaveNewMail", mail.size()));
user.sendMessage(tl("youHaveNewMail", mail.size()));
}
}
if (user.isAuthorized("essentials.fly.safelogin"))
{
user.setFallDistance(0);
user.getBase().setFallDistance(0);
if (LocationUtil.shouldFly(user.getLocation()))
{
user.setAllowFlight(true);
user.setFlying(true);
user.sendMessage(_("flyMode", _("enabled"), user.getDisplayName()));
}
user.getBase().setAllowFlight(true);
user.getBase().setFlying(true);
user.getBase().sendMessage(tl("flyMode", tl("enabled"), user.getDisplayName()));
}
}
user.setFlySpeed(0.1f);
user.setWalkSpeed(0.2f);
if (!user.isAuthorized("essentials.speed"))
{
user.getBase().setFlySpeed(0.1f);
user.getBase().setWalkSpeed(0.2f);
}
user.stopTransaction();
}
});
}
ess.scheduleSyncDelayedTask(new DelayJoinTask());
}
// Makes the compass item ingame always point to the first essentials home. #EasterEgg
@@ -326,72 +364,34 @@ public class EssentialsPlayerListener implements Listener
Location loc = user.getHome(user.getLocation());
if (loc == null)
{
loc = user.getBedSpawnLocation();
loc = user.getBase().getBedSpawnLocation();
}
if (loc != null)
{
final Location updateLoc = loc;
user.setCompassTarget(updateLoc);
user.getBase().setCompassTarget(updateLoc);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerLogin2(final PlayerLoginEvent event)
{
switch (event.getResult())
{
case KICK_BANNED:
break;
default:
return;
}
final String banReason = _("banFormat", _("defaultBanReason"), "Console");
event.disallow(Result.KICK_BANNED, banReason);
}
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerLogin(final PlayerLoginEvent event)
{
switch (event.getResult())
{
case KICK_FULL:
case KICK_BANNED:
break;
default:
return;
}
final User user = ess.getUser(event.getPlayer());
if (event.getResult() == Result.KICK_BANNED || user.isBanned())
{
final boolean banExpired = user.checkBanTimeout(System.currentTimeMillis());
if (!banExpired)
final User kfuser = ess.getUser(event.getPlayer());
if (kfuser.isAuthorized("essentials.joinfullserver"))
{
String banReason = user.getBanReason();
if (banReason == null || banReason.isEmpty() || banReason.equalsIgnoreCase("ban"))
{
banReason = event.getKickMessage();
}
if (user.getBanTimeout() > 0)
{
//TODO: TL This
banReason += "\n\n" + "Expires in " + DateUtil.formatDateDiff(user.getBanTimeout());
}
event.disallow(Result.KICK_BANNED, banReason);
event.allow();
return;
}
event.disallow(Result.KICK_FULL, tl("serverFull"));
break;
default:
break;
}
if (event.getResult() == Result.KICK_FULL && !user.isAuthorized("essentials.joinfullserver"))
{
event.disallow(Result.KICK_FULL, _("serverFull"));
return;
}
event.allow();
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerTeleport(final PlayerTeleportEvent event)
{
@@ -411,7 +411,7 @@ public class EssentialsPlayerListener implements Listener
}
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerEggThrow(final PlayerEggThrowEvent event)
{
@@ -419,11 +419,11 @@ public class EssentialsPlayerListener implements Listener
final ItemStack stack = new ItemStack(Material.EGG, 1);
if (user.hasUnlimited(stack))
{
user.getInventory().addItem(stack);
user.updateInventory();
user.getBase().getInventory().addItem(stack);
user.getBase().updateInventory();
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerBucketEmpty(final PlayerBucketEmptyEvent event)
{
@@ -436,23 +436,22 @@ public class EssentialsPlayerListener implements Listener
@Override
public void run()
{
user.updateInventory();
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))
if (ess.getSettings().getSocialSpyCommands().contains(cmd) || ess.getSettings().getSocialSpyCommands().contains("*"))
{
for (Player onlinePlayer : ess.getServer().getOnlinePlayers())
for (User spyer : ess.getOnlineUsers())
{
final User spyer = ess.getUser(onlinePlayer);
if (spyer.isSocialSpyEnabled() && !player.equals(onlinePlayer))
if (spyer.isSocialSpyEnabled() && !player.equals(spyer.getBase()))
{
spyer.sendMessage(player.getDisplayName() + " : " + event.getMessage());
}
@@ -464,43 +463,43 @@ public class EssentialsPlayerListener implements Listener
user.updateActivity(true);
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerChangedWorldFlyReset(final PlayerChangedWorldEvent event)
{
final User user = ess.getUser(event.getPlayer());
if (user.getGameMode() != GameMode.CREATIVE && !user.isAuthorized("essentials.fly"))
if (user.getBase().getGameMode() != GameMode.CREATIVE && !user.isAuthorized("essentials.fly"))
{
user.setFallDistance(0f);
user.setAllowFlight(false);
user.getBase().setFallDistance(0f);
user.getBase().setAllowFlight(false);
}
if (!user.isAuthorized("essentials.speed"))
{
user.setFlySpeed(0.1f);
user.setWalkSpeed(0.2f);
user.getBase().setFlySpeed(0.1f);
user.getBase().setWalkSpeed(0.2f);
}
else
{
if (user.getFlySpeed() > ess.getSettings().getMaxFlySpeed() && !user.isAuthorized("essentials.speed.bypass"))
if (user.getBase().getFlySpeed() > ess.getSettings().getMaxFlySpeed() && !user.isAuthorized("essentials.speed.bypass"))
{
user.setFlySpeed((float)ess.getSettings().getMaxFlySpeed());
user.getBase().setFlySpeed((float)ess.getSettings().getMaxFlySpeed());
}
else
{
user.setFlySpeed(user.getFlySpeed() * 0.99999f);
user.getBase().setFlySpeed(user.getBase().getFlySpeed() * 0.99999f);
}
if (user.getWalkSpeed() > ess.getSettings().getMaxWalkSpeed() && !user.isAuthorized("essentials.speed.bypass"))
if (user.getBase().getWalkSpeed() > ess.getSettings().getMaxWalkSpeed() && !user.isAuthorized("essentials.speed.bypass"))
{
user.setWalkSpeed((float)ess.getSettings().getMaxWalkSpeed());
user.getBase().setWalkSpeed((float)ess.getSettings().getMaxWalkSpeed());
}
else
{
user.setWalkSpeed(user.getWalkSpeed() * 0.99999f);
user.getBase().setWalkSpeed(user.getBase().getWalkSpeed() * 0.99999f);
}
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerChangedWorld(final PlayerChangedWorldEvent event)
{
@@ -510,19 +509,19 @@ public class EssentialsPlayerListener implements Listener
updateCompass(user);
if (ess.getSettings().getNoGodWorlds().contains(newWorld) && user.isGodModeEnabledRaw())
{
user.sendMessage(_("noGodWorldWarning"));
user.sendMessage(tl("noGodWorldWarning"));
}
if (!user.getWorld().getName().equals(newWorld))
{
user.sendMessage(_("currentWorld", 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)
{
@@ -534,8 +533,8 @@ public class EssentialsPlayerListener implements Listener
User player = ess.getUser(event.getPlayer());
if (player.isAuthorized("essentials.sethome.bed"))
{
player.setBedSpawnLocation(event.getClickedBlock().getLocation());
player.sendMessage(_("bedSet", player.getLocation().getWorld().getName(), player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ()));
player.getBase().setBedSpawnLocation(event.getClickedBlock().getLocation());
player.sendMessage(tl("bedSet", player.getLocation().getWorld().getName(), player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ()));
}
}
break;
@@ -571,9 +570,8 @@ public class EssentialsPlayerListener implements Listener
try
{
final Location otarget = LocationUtil.getTarget(user.getBase());
ess.scheduleSyncDelayedTask(
new Runnable()
class DelayedClickJumpTask implements Runnable
{
@Override
public void run()
@@ -587,7 +585,8 @@ public class EssentialsPlayerListener implements Listener
}
user.getBase().teleport(loc, TeleportCause.PLUGIN);
}
});
}
ess.scheduleSyncDelayedTask(new DelayedClickJumpTask());
}
catch (Exception ex)
{
@@ -597,7 +596,7 @@ public class EssentialsPlayerListener implements Listener
}
}
}
private boolean usePowertools(final User user, final int id)
{
final List<String> commandList = user.getPowertool(id);
@@ -616,13 +615,13 @@ public class EssentialsPlayerListener implements Listener
else if (command.startsWith("c:"))
{
used = true;
user.chat(command.substring(2));
user.getBase().chat(command.substring(2));
}
else
{
used = true;
ess.scheduleSyncDelayedTask(
new Runnable()
class PowerToolUseTask implements Runnable
{
@Override
public void run()
@@ -630,12 +629,14 @@ public class EssentialsPlayerListener implements Listener
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)
{
@@ -647,14 +648,14 @@ public class EssentialsPlayerListener implements Listener
}
}
}
@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());
@@ -664,7 +665,7 @@ public class EssentialsPlayerListener implements Listener
final User invOwner = ess.getUser((Player)invHolder);
if (user.isInvSee() && (!user.isAuthorized("essentials.invsee.modify")
|| invOwner.isAuthorized("essentials.invsee.preventmodify")
|| !invOwner.isOnline()))
|| !invOwner.getBase().isOnline()))
{
event.setCancelled(true);
refreshPlayer = user.getBase();
@@ -699,7 +700,7 @@ public class EssentialsPlayerListener implements Listener
refreshPlayer = user.getBase();
}
}
if (refreshPlayer != null)
{
final Player player = refreshPlayer;
@@ -713,7 +714,7 @@ public class EssentialsPlayerListener implements Listener
}, 1);
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onInventoryCloseEvent(final InventoryCloseEvent event)
{
@@ -752,7 +753,7 @@ public class EssentialsPlayerListener implements Listener
refreshPlayer = user.getBase();
}
}
if (refreshPlayer != null)
{
final Player player = refreshPlayer;
@@ -766,7 +767,7 @@ public class EssentialsPlayerListener implements Listener
}, 1);
}
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlayerFishEvent(final PlayerFishEvent event)
{

View File

@@ -4,6 +4,7 @@ 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;
@@ -12,7 +13,7 @@ import org.bukkit.entity.Player;
public class EssentialsTimer implements Runnable
{
private final transient IEssentials ess;
private final transient Set<String> onlineUsers = new HashSet<String>();
private final transient Set<UUID> onlineUsers = new HashSet<UUID>();
private transient long lastPoll = System.nanoTime();
private final LinkedList<Double> history = new LinkedList<Double>();
private int skip1 = 0;
@@ -47,7 +48,7 @@ public class EssentialsTimer implements Runnable
}
lastPoll = startTime;
int count = 0;
for (Player player : ess.getServer().getOnlinePlayers())
for (Player player : ess.getOnlinePlayers())
{
count++;
if (skip1 > 0)
@@ -66,7 +67,7 @@ public class EssentialsTimer implements Runnable
try
{
final User user = ess.getUser(player);
onlineUsers.add(user.getName());
onlineUsers.add(user.getBase().getUniqueId());
user.setLastOnlineActivity(currentTime);
user.checkActivity();
}
@@ -77,7 +78,7 @@ public class EssentialsTimer implements Runnable
}
count = 0;
final Iterator<String> iterator = onlineUsers.iterator();
final Iterator<UUID> iterator = onlineUsers.iterator();
while (iterator.hasNext())
{
count++;

View File

@@ -1,10 +1,12 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
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 java.io.*;
import java.math.BigInteger;
import java.security.DigestInputStream;
@@ -13,11 +15,10 @@ 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.Material;
import org.bukkit.World;
import org.bukkit.inventory.ItemStack;
public class EssentialsUpgrade
@@ -37,46 +38,6 @@ public class EssentialsUpgrade
doneFile.load();
}
private void moveWorthValuesToWorthYml()
{
if (doneFile.getBoolean("moveWorthValuesToWorthYml", false))
{
return;
}
try
{
final File configFile = new File(ess.getDataFolder(), "config.yml");
if (!configFile.exists())
{
return;
}
final EssentialsConf conf = new EssentialsConf(configFile);
conf.load();
final Worth worth = new Worth(ess.getDataFolder());
boolean found = false;
for (Material mat : Material.values())
{
final int id = mat.getId();
final double value = conf.getDouble("worth-" + id, Double.NaN);
if (!Double.isNaN(value))
{
found = true;
worth.setPrice(new ItemStack(mat, 1, (short)0, (byte)0), value);
}
}
if (found)
{
removeLinesFromConfig(configFile, "\\s*#?\\s*worth-[0-9]+.*", "# Worth values have been moved to worth.yml");
}
doneFile.setProperty("moveWorthValuesToWorthYml", true);
doneFile.save();
}
catch (Exception e)
{
LOGGER.log(Level.SEVERE, _("upgradingFilesError"), e);
}
}
private void moveMotdRulesToFile(String name)
{
if (doneFile.getBoolean("move" + name + "ToFile", false))
@@ -117,7 +78,7 @@ public class EssentialsUpgrade
}
catch (IOException e)
{
LOGGER.log(Level.SEVERE, _("upgradingFilesError"), e);
LOGGER.log(Level.SEVERE, tl("upgradingFilesError"), e);
}
}
@@ -167,11 +128,11 @@ public class EssentialsUpgrade
{
if (!file.renameTo(new File(file.getParentFile(), file.getName().concat("." + System.currentTimeMillis() + ".upgradebackup"))))
{
throw new Exception(_("configFileMoveError"));
throw new Exception(tl("configFileMoveError"));
}
if (!tempFile.renameTo(file))
{
throw new Exception(_("configFileRenameError"));
throw new Exception(tl("configFileRenameError"));
}
}
else
@@ -180,73 +141,6 @@ public class EssentialsUpgrade
}
}
private void updateUsersToNewDefaultHome()
{
if (doneFile.getBoolean("updateUsersToNewDefaultHome", 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 List<Object> vals = (List<Object>)config.getProperty("home");
if (vals == null)
{
continue;
}
World world = ess.getServer().getWorlds().get(0);
if (vals.size() > 5)
{
world = ess.getServer().getWorld((String)vals.get(5));
}
if (world != null)
{
final Location loc = new Location(
world,
((Number)vals.get(0)).doubleValue(),
((Number)vals.get(1)).doubleValue(),
((Number)vals.get(2)).doubleValue(),
((Number)vals.get(3)).floatValue(),
((Number)vals.get(4)).floatValue());
final String worldName = world.getName().toLowerCase(Locale.ENGLISH);
if (worldName != null && !worldName.isEmpty())
{
config.removeProperty("home");
config.setProperty("home.default", worldName);
config.setProperty("home.worlds." + worldName, loc);
config.forceSave();
}
}
}
}
catch (RuntimeException ex)
{
LOGGER.log(Level.INFO, "File: " + file.toString());
throw ex;
}
}
doneFile.setProperty("updateUsersToNewDefaultHome", true);
doneFile.save();
}
private void updateUsersPowerToolsFormat()
{
if (doneFile.getBoolean("updateUsersPowerToolsFormat", false))
@@ -374,195 +268,6 @@ public class EssentialsUpgrade
doneFile.save();
}
private void moveUsersDataToUserdataFolder()
{
final File usersFile = new File(ess.getDataFolder(), "users.yml");
if (!usersFile.exists())
{
return;
}
final EssentialsConf usersConfig = new EssentialsConf(usersFile);
usersConfig.load();
for (String username : usersConfig.getKeys(false))
{
final User user = new User(new OfflinePlayer(username, ess), ess);
final String nickname = usersConfig.getString(username + ".nickname");
if (nickname != null && !nickname.isEmpty() && !nickname.equals(username))
{
user.setNickname(nickname);
}
final List<String> mails = usersConfig.getStringList(username + ".mail");
if (mails != null && !mails.isEmpty())
{
user.setMails(mails);
}
if (!user.hasHome())
{
@SuppressWarnings("unchecked")
final List<Object> vals = (List<Object>)usersConfig.getProperty(username + ".home");
if (vals != null)
{
World world = ess.getServer().getWorlds().get(0);
if (vals.size() > 5)
{
world = getFakeWorld((String)vals.get(5));
}
if (world != null)
{
user.setHome("home", new Location(world,
((Number)vals.get(0)).doubleValue(),
((Number)vals.get(1)).doubleValue(),
((Number)vals.get(2)).doubleValue(),
((Number)vals.get(3)).floatValue(),
((Number)vals.get(4)).floatValue()));
}
}
}
}
usersFile.renameTo(new File(usersFile.getAbsolutePath() + ".old"));
}
private void convertWarps()
{
final File warpsFolder = new File(ess.getDataFolder(), "warps");
if (!warpsFolder.exists())
{
warpsFolder.mkdirs();
}
final File[] listOfFiles = warpsFolder.listFiles();
if (listOfFiles.length >= 1)
{
for (int i = 0; i < listOfFiles.length; i++)
{
final String filename = listOfFiles[i].getName();
if (listOfFiles[i].isFile() && filename.endsWith(".dat"))
{
try
{
final BufferedReader rx = new BufferedReader(new FileReader(listOfFiles[i]));
double x, y, z;
float yaw, pitch;
String worldName;
try
{
if (!rx.ready())
{
continue;
}
x = Double.parseDouble(rx.readLine().trim());
if (!rx.ready())
{
continue;
}
y = Double.parseDouble(rx.readLine().trim());
if (!rx.ready())
{
continue;
}
z = Double.parseDouble(rx.readLine().trim());
if (!rx.ready())
{
continue;
}
yaw = Float.parseFloat(rx.readLine().trim());
if (!rx.ready())
{
continue;
}
pitch = Float.parseFloat(rx.readLine().trim());
worldName = rx.readLine();
}
finally
{
rx.close();
}
World w = null;
for (World world : ess.getServer().getWorlds())
{
if (world.getEnvironment() != World.Environment.NETHER)
{
w = world;
break;
}
}
if (worldName != null)
{
worldName = worldName.trim();
World w1 = null;
w1 = getFakeWorld(worldName);
if (w1 != null)
{
w = w1;
}
}
final Location loc = new Location(w, x, y, z, yaw, pitch);
ess.getWarps().setWarp(filename.substring(0, filename.length() - 4), loc);
if (!listOfFiles[i].renameTo(new File(warpsFolder, filename + ".old")))
{
throw new Exception(_("fileRenameError", filename));
}
}
catch (Exception ex)
{
LOGGER.log(Level.SEVERE, null, ex);
}
}
}
}
final File warpFile = new File(ess.getDataFolder(), "warps.txt");
if (warpFile.exists())
{
try
{
final BufferedReader rx = new BufferedReader(new FileReader(warpFile));
try
{
for (String[] parts = new String[0]; rx.ready(); parts = rx.readLine().split(":"))
{
if (parts.length < 6)
{
continue;
}
final String name = parts[0];
final double x = Double.parseDouble(parts[1].trim());
final double y = Double.parseDouble(parts[2].trim());
final double z = Double.parseDouble(parts[3].trim());
final float yaw = Float.parseFloat(parts[4].trim());
final float pitch = Float.parseFloat(parts[5].trim());
if (name.isEmpty())
{
continue;
}
World w = null;
for (World world : ess.getServer().getWorlds())
{
if (world.getEnvironment() != World.Environment.NETHER)
{
w = world;
break;
}
}
final Location loc = new Location(w, x, y, z, yaw, pitch);
ess.getWarps().setWarp(name, loc);
if (!warpFile.renameTo(new File(ess.getDataFolder(), "warps.txt.old")))
{
throw new Exception(_("fileRenameError", "warps.txt"));
}
}
}
finally
{
rx.close();
}
}
catch (Exception ex)
{
LOGGER.log(Level.SEVERE, null, ex);
}
}
}
private void sanitizeAllUserFilenames()
{
if (doneFile.getBoolean("sanitizeAllUserFilenames", false))
@@ -591,17 +296,17 @@ public class EssentialsUpgrade
final File newFile = new File(listOfFile.getParentFile(), sanitizedFilename);
if (!listOfFile.renameTo(tmpFile))
{
LOGGER.log(Level.WARNING, _("userdataMoveError", filename, sanitizedFilename));
LOGGER.log(Level.WARNING, tl("userdataMoveError", filename, sanitizedFilename));
continue;
}
if (newFile.exists())
{
LOGGER.log(Level.WARNING, _("duplicatedUserdata", filename, sanitizedFilename));
LOGGER.log(Level.WARNING, tl("duplicatedUserdata", filename, sanitizedFilename));
continue;
}
if (!tmpFile.renameTo(newFile))
{
LOGGER.log(Level.WARNING, _("userdataMoveBackError", sanitizedFilename, sanitizedFilename));
LOGGER.log(Level.WARNING, tl("userdataMoveBackError", sanitizedFilename, sanitizedFilename));
}
}
doneFile.setProperty("sanitizeAllUserFilenames", true);
@@ -711,7 +416,7 @@ public class EssentialsUpgrade
}
if (!configFile.renameTo(new File(ess.getDataFolder(), "spawn.yml.old")))
{
throw new Exception(_("fileRenameError", "spawn.yml"));
throw new Exception(tl("fileRenameError", "spawn.yml"));
}
PrintWriter writer = new PrintWriter(configFile);
try
@@ -758,7 +463,7 @@ public class EssentialsUpgrade
}
if (!configFile.renameTo(new File(ess.getDataFolder(), "jail.yml.old")))
{
throw new Exception(_("fileRenameError", "jail.yml"));
throw new Exception(tl("fileRenameError", "jail.yml"));
}
PrintWriter writer = new PrintWriter(configFile);
try
@@ -791,13 +496,272 @@ public class EssentialsUpgrade
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();
}
moveWorthValuesToWorthYml();
moveMotdRulesToFile("motd");
moveMotdRulesToFile("rules");
}
@@ -805,14 +769,13 @@ public class EssentialsUpgrade
public void afterSettings()
{
sanitizeAllUserFilenames();
updateUsersToNewDefaultHome();
moveUsersDataToUserdataFolder();
convertWarps();
updateUsersPowerToolsFormat();
updateUsersHomesFormat();
deleteOldItemsCsv();
updateSpawnsToNewSpawnsConfig();
updateJailsToNewJailsConfig();
uuidFileChange();
banFormatChange();
warnMetrics();
}
}

View File

@@ -0,0 +1,76 @@
package com.earth2me.essentials;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
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 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 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);
}
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 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);
}
}
}

View File

@@ -12,6 +12,7 @@ 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
@@ -23,16 +24,28 @@ public class I18n implements net.ess3.api.II18n
private transient ResourceBundle customBundle;
private transient ResourceBundle localeBundle;
private final transient ResourceBundle defaultBundle;
private final transient Map<String, MessageFormat> messageFormatCache = new HashMap<String, MessageFormat>();
private transient Map<String, MessageFormat> messageFormatCache = new HashMap<String, MessageFormat>();
private final transient IEssentials ess;
private static final Pattern NODOUBLEMARK = Pattern.compile("''");
private static final ResourceBundle NULL_BUNDLE = new ResourceBundle()
{
public Enumeration<String> getKeys()
{
return null;
}
protected Object handleGetObject(String key)
{
return null;
}
};
public I18n(final IEssentials ess)
{
this.ess = ess;
customBundle = ResourceBundle.getBundle(MESSAGES, defaultLocale, new FileResClassLoader(I18n.class.getClassLoader(), ess));
localeBundle = ResourceBundle.getBundle(MESSAGES, defaultLocale);
defaultBundle = ResourceBundle.getBundle(MESSAGES, Locale.ENGLISH);
localeBundle = defaultBundle;
customBundle = NULL_BUNDLE;
}
public void onEnable()
@@ -71,7 +84,7 @@ public class I18n implements net.ess3.api.II18n
}
}
public static String _(final String string, final Object... objects)
public static String tl(final String string, final Object... objects)
{
if (instance == null)
{
@@ -110,27 +123,43 @@ public class I18n implements net.ess3.api.II18n
public void updateLocale(final String loc)
{
if (loc == null || loc.isEmpty())
if (loc != null && !loc.isEmpty())
{
return;
}
final String[] parts = loc.split("[_\\.]");
if (parts.length == 1)
{
currentLocale = new Locale(parts[0]);
}
if (parts.length == 2)
{
currentLocale = new Locale(parts[0], parts[1]);
}
if (parts.length == 3)
{
currentLocale = new Locale(parts[0], parts[1], parts[2]);
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<String, MessageFormat>();
Logger.getLogger("Essentials").log(Level.INFO, String.format("Using locale %s", currentLocale.toString()));
customBundle = ResourceBundle.getBundle(MESSAGES, currentLocale, new FileResClassLoader(I18n.class.getClassLoader(), ess));
localeBundle = ResourceBundle.getBundle(MESSAGES, currentLocale);
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;
}
}
public static String capitalCase(final String input)
@@ -166,7 +195,7 @@ public class I18n implements net.ess3.api.II18n
{
}
}
return super.getResource(string);
return null;
}
@Override
@@ -183,7 +212,7 @@ public class I18n implements net.ess3.api.II18n
{
}
}
return super.getResourceAsStream(string);
return null;
}
}
}

View File

@@ -6,7 +6,9 @@ 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;
@@ -27,6 +29,8 @@ public interface IEssentials extends Plugin
@Deprecated
User getUser(Object base);
User getUser(UUID base);
User getUser(String base);
User getUser(Player base);
@@ -60,12 +64,14 @@ public interface IEssentials extends Plugin
BukkitTask runTaskAsynchronously(Runnable run);
BukkitTask runTaskLaterAsynchronously(Runnable run, long delay);
BukkitTask runTaskTimerAsynchronously(Runnable run, long delay, long period);
int scheduleSyncDelayedTask(Runnable run);
int scheduleSyncDelayedTask(Runnable run, long delay);
int scheduleSyncRepeatingTask(final Runnable run, long delay, long period);
int scheduleSyncRepeatingTask(Runnable run, long delay, long period);
TNTExplodeListener getTNTListener();
@@ -73,7 +79,7 @@ public interface IEssentials extends Plugin
AlternativeCommandsHandler getAlternativeCommandsHandler();
void showError(final CommandSource sender, final Throwable exception, final String commandLabel);
void showError(CommandSource sender, Throwable exception, String commandLabel);
IItemDb getItemDb();
@@ -86,4 +92,8 @@ public interface IEssentials extends Plugin
EssentialsTimer getTimer();
List<String> getVanishedPlayers();
Collection<Player> getOnlinePlayers();
Iterable<User> getOnlineUsers();
}

View File

@@ -29,6 +29,10 @@ public interface ISettings extends IConf
String getChatFormat(String group);
int getChatRadius();
char getChatShout();
char getChatQuestion();
BigDecimal getCommandCost(IEssentialsCommand cmd);
@@ -189,6 +193,8 @@ public interface ISettings extends IConf
int getMailsPerMinute();
long getEconomyLagWarning();
long getPermissionsLagWarning();
void setEssentialsChatActive(boolean b);

View File

@@ -8,7 +8,6 @@ import java.util.Set;
import net.ess3.api.ITeleport;
import net.ess3.api.MaxMoneyException;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

View File

@@ -1,6 +1,6 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.utils.NumberUtil;
import com.earth2me.essentials.utils.StringUtil;
import java.util.*;
@@ -143,20 +143,20 @@ public class ItemDb implements IConf, net.ess3.api.IItemDb
}
catch (Throwable throwable)
{
throw new Exception(_("unknownItemName", itemname), throwable);
throw new Exception(tl("unknownItemName", itemname), throwable);
}
}
}
if (itemid < 1)
{
throw new Exception(_("unknownItemName", itemname));
throw new Exception(tl("unknownItemName", itemname));
}
final Material mat = Material.getMaterial(itemid);
if (mat == null)
{
throw new Exception(_("unknownItemId", itemid));
throw new Exception(tl("unknownItemId", itemid));
}
final ItemStack retval = new ItemStack(mat);
retval.setAmount(mat.getMaxStackSize());
@@ -171,15 +171,15 @@ public class ItemDb implements IConf, net.ess3.api.IItemDb
if (args.length < 1)
{
is.add(user.getItemInHand());
is.add(user.getBase().getItemInHand());
}
else if (args[0].equalsIgnoreCase("hand"))
{
is.add(user.getItemInHand());
is.add(user.getBase().getItemInHand());
}
else if (args[0].equalsIgnoreCase("inventory") || args[0].equalsIgnoreCase("invent") || args[0].equalsIgnoreCase("all"))
{
for (ItemStack stack : user.getInventory().getContents())
for (ItemStack stack : user.getBase().getInventory().getContents())
{
if (stack == null || stack.getType() == Material.AIR)
{
@@ -190,7 +190,7 @@ public class ItemDb implements IConf, net.ess3.api.IItemDb
}
else if (args[0].equalsIgnoreCase("blocks"))
{
for (ItemStack stack : user.getInventory().getContents())
for (ItemStack stack : user.getBase().getInventory().getContents())
{
if (stack == null || stack.getTypeId() > 255 || stack.getType() == Material.AIR)
{
@@ -206,7 +206,7 @@ public class ItemDb implements IConf, net.ess3.api.IItemDb
if (is.isEmpty() || is.get(0).getType() == Material.AIR)
{
throw new Exception(_("itemSellAir"));
throw new Exception(tl("itemSellAir"));
}
return is;

View File

@@ -1,6 +1,6 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.storage.AsyncStorageObjectHolder;
import java.io.File;
import java.util.*;
@@ -93,12 +93,12 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett
if (getData().getJails() == null || jailName == null
|| !getData().getJails().containsKey(jailName.toLowerCase(Locale.ENGLISH)))
{
throw new Exception(_("jailNotExist"));
throw new Exception(tl("jailNotExist"));
}
Location loc = getData().getJails().get(jailName.toLowerCase(Locale.ENGLISH));
if (loc == null || loc.getWorld() == null)
{
throw new Exception(_("jailNotExist"));
throw new Exception(tl("jailNotExist"));
}
return loc;
}
@@ -198,7 +198,7 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett
private class JailListener implements Listener
{
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onBlockBreak(final BlockBreakEvent event)
public void onJailBlockBreak(final BlockBreakEvent event)
{
final User user = ess.getUser(event.getPlayer());
if (user.isJailed())
@@ -208,7 +208,7 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onBlockPlace(final BlockPlaceEvent event)
public void onJailBlockPlace(final BlockPlaceEvent event)
{
final User user = ess.getUser(event.getPlayer());
if (user.isJailed())
@@ -218,7 +218,7 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onBlockDamage(final BlockDamageEvent event)
public void onJailBlockDamage(final BlockDamageEvent event)
{
final User user = ess.getUser(event.getPlayer());
if (user.isJailed())
@@ -228,7 +228,7 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onEntityDamageByEntity(final EntityDamageByEntityEvent event)
public void onJailEntityDamageByEntity(final EntityDamageByEntityEvent event)
{
if (event.getCause() != DamageCause.ENTITY_ATTACK || event.getEntity().getType() != EntityType.PLAYER)
{
@@ -246,7 +246,7 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlayerInteract(final PlayerInteractEvent event)
public void onJailPlayerInteract(final PlayerInteractEvent event)
{
final User user = ess.getUser(event.getPlayer());
if (user.isJailed())
@@ -256,7 +256,7 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerRespawn(final PlayerRespawnEvent event)
public void onJailPlayerRespawn(final PlayerRespawnEvent event)
{
final User user = ess.getUser(event.getPlayer());
if (!user.isJailed() || user.getJail() == null || user.getJail().isEmpty())
@@ -272,17 +272,17 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett
{
if (ess.getSettings().isDebug())
{
LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex);
LOGGER.log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex);
}
else
{
LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()));
LOGGER.log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()));
}
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerTeleport(final PlayerTeleportEvent event)
public void onJailPlayerTeleport(final PlayerTeleportEvent event)
{
final User user = ess.getUser(event.getPlayer());
if (!user.isJailed() || user.getJail() == null || user.getJail().isEmpty())
@@ -298,18 +298,18 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett
{
if (ess.getSettings().isDebug())
{
LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex);
LOGGER.log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex);
}
else
{
LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()));
LOGGER.log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()));
}
}
user.sendMessage(_("jailMessage"));
user.sendMessage(tl("jailMessage"));
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerJoin(final PlayerJoinEvent event)
public void onJailPlayerJoin(final PlayerJoinEvent event)
{
final User user = ess.getUser(event.getPlayer());
final long currentTime = System.currentTimeMillis();
@@ -327,14 +327,14 @@ public class Jails extends AsyncStorageObjectHolder<com.earth2me.essentials.sett
{
if (ess.getSettings().isDebug())
{
LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex);
LOGGER.log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()), ex);
}
else
{
LOGGER.log(Level.INFO, _("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()));
LOGGER.log(Level.INFO, tl("returnPlayerToJailError", user.getName(), ex.getLocalizedMessage()));
}
}
user.sendMessage(_("jailMessage"));
user.sendMessage(tl("jailMessage"));
}
}
}

View File

@@ -1,6 +1,6 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
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;
@@ -21,6 +21,24 @@ import org.bukkit.inventory.ItemStack;
public class Kit
{
final IEssentials ess;
final String kitName;
final Map<String, Object> kit;
final Trade charge;
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"));
}
}
//TODO: Convert this to use one of the new text classes?
public static String listKits(final IEssentials ess, final User user) throws Exception
{
@@ -41,13 +59,13 @@ public class Kit
BigDecimal costPrice = new Trade("kit-" + kitItem.toLowerCase(Locale.ENGLISH), ess).getCommandCost(user);
if (costPrice.signum() > 0)
{
cost = _("kitCost", NumberUtil.displayCurrency(costPrice, ess));
cost = tl("kitCost", NumberUtil.displayCurrency(costPrice, ess));
}
final Map<String, Object> kit = ess.getSettings().getKit(kitItem);
if (Kit.getNextUse(user, kitItem, kit) != 0)
Kit kit = new Kit(kitItem, ess);
if (kit.getNextUse(user) != 0)
{
name = _("kitDelay", name);
name = tl("kitDelay", name);
}
list.append(" ").append(name).append(cost);
@@ -57,33 +75,61 @@ public class Kit
}
catch (Exception ex)
{
throw new Exception(_("kitError"), ex);
throw new Exception(tl("kitError"), ex);
}
}
public static void checkTime(final User user, final String kitName, final Map<String, Object> els) throws Exception
public String getName()
{
final Calendar time = new GregorianCalendar();
long nextUse = getNextUse(user, kitName, els);
return kitName;
}
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);
if (nextUse == 0L)
{
user.setKitTimestamp(kitName, time.getTimeInMillis());
return;
}
else if (nextUse < 0L)
{
user.sendMessage(_("kitOnce"));
user.sendMessage(tl("kitOnce"));
throw new NoChargeException();
}
else
{
user.sendMessage(_("kitTimed", DateUtil.formatDateDiff(nextUse)));
user.sendMessage(tl("kitTimed", DateUtil.formatDateDiff(nextUse)));
throw new NoChargeException();
}
}
public static long getNextUse(final User user, final String kitName, final Map<String, Object> els) throws Exception
public void checkAffordable(final User user) throws Exception
{
charge.isAffordableFor(user);
}
public void setTime(final User user) throws Exception
{
final Calendar time = new GregorianCalendar();
user.setKitTimestamp(kitName, time.getTimeInMillis());
}
public void chargeUser(final User user) throws Exception
{
charge.charge(user);
}
public long getNextUse(final User user) throws Exception
{
if (user.isAuthorized("essentials.kit.exemptdelay"))
{
@@ -96,11 +142,11 @@ public class Kit
try
{
// Make sure delay is valid
delay = els.containsKey("delay") ? ((Number)els.get("delay")).doubleValue() : 0.0d;
delay = kit.containsKey("delay") ? ((Number)kit.get("delay")).doubleValue() : 0.0d;
}
catch (Exception e)
{
throw new Exception(_("kitError2"));
throw new Exception(tl("kitError2"));
}
// When was the last kit used?
@@ -134,11 +180,11 @@ public class Kit
}
}
public static List<String> getItems(final IEssentials ess, final User user, final String kitName, final Map<String, Object> kit) throws Exception
public List<String> getItems(final User user) throws Exception
{
if (kit == null)
{
throw new Exception(_("kitNotFound"));
throw new Exception(tl("kitNotFound"));
}
try
{
@@ -162,11 +208,16 @@ public class Kit
catch (Exception e)
{
ess.getLogger().log(Level.WARNING, "Error parsing kit " + kitName + ": " + e.getMessage());
throw new Exception(_("kitError2"), e);
throw new Exception(tl("kitError2"), e);
}
}
public static void expandItems(final IEssentials ess, final User user, final List<String> items) throws Exception
public void expandItems(final User user) throws Exception
{
expandItems(user, getItems(user));
}
public void expandItems(final User user, final List<String> items) throws Exception
{
try
{
@@ -187,11 +238,12 @@ public class Kit
final String[] parts = kitItem.split(" +");
final ItemStack parseStack = ess.getItemDb().get(parts[0], parts.length > 1 ? Integer.parseInt(parts[1]) : 1);
if (parseStack.getType() == Material.AIR) {
if (parseStack.getType() == Material.AIR)
{
continue;
}
final MetaItemStack metaStack = new MetaItemStack(parseStack);
if (parts.length > 2)
@@ -204,36 +256,38 @@ public class Kit
final boolean allowOversizedStacks = user.isAuthorized("essentials.oversizedstacks");
if (allowOversizedStacks)
{
overfilled = InventoryWorkaround.addOversizedItems(user.getInventory(), ess.getSettings().getOversizedStackSize(), metaStack.getItemStack());
overfilled = InventoryWorkaround.addOversizedItems(user.getBase().getInventory(), ess.getSettings().getOversizedStackSize(), metaStack.getItemStack());
}
else
{
overfilled = InventoryWorkaround.addItems(user.getInventory(), metaStack.getItemStack());
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());
if (!allowOversizedStacks)
{
itemStack.setAmount(spillAmount < itemStack.getMaxStackSize() ? spillAmount : itemStack.getMaxStackSize());
}
while (spillAmount > 0) {
while (spillAmount > 0)
{
user.getWorld().dropItemNaturally(user.getLocation(), itemStack);
spillAmount -= itemStack.getAmount();
}
spew = true;
}
}
user.updateInventory();
user.getBase().updateInventory();
if (spew)
{
user.sendMessage(_("kitInvFull"));
user.sendMessage(tl("kitInvFull"));
}
}
catch (Exception e)
{
user.updateInventory();
user.getBase().updateInventory();
ess.getLogger().log(Level.WARNING, e.getMessage());
throw new Exception(_("kitError2"), e);
throw new Exception(tl("kitError2"), e);
}
}
}

View File

@@ -1,6 +1,6 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import java.io.*;
import java.math.BigInteger;
import java.security.DigestInputStream;
@@ -47,7 +47,7 @@ public class ManagedFile
}
catch (IOException ex)
{
Bukkit.getLogger().log(Level.SEVERE, _("itemsCsvNotLoaded"), ex);
Bukkit.getLogger().log(Level.SEVERE, tl("itemsCsvNotLoaded"), ex);
}
}
}

View File

@@ -1,6 +1,6 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
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;
@@ -10,6 +10,7 @@ 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;
@@ -26,6 +27,7 @@ public class MetaItemStack
{
private static final Map<String, DyeColor> colorMap = new HashMap<String, DyeColor>();
private static final Map<String, FireworkEffect.Type> fireworkShape = new HashMap<String, FireworkEffect.Type>();
static
{
for (DyeColor color : DyeColor.values())
@@ -95,17 +97,53 @@ public class MetaItemStack
completePotion = true;
}
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 void parseStringMeta(final CommandSource sender, final boolean allowUnsafe, String[] string, int fromArg, final IEssentials ess) throws Exception
{
if (string[fromArg].startsWith("{"))
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(_("noMetaJson"), nsme);
throw new Exception(tl("noMetaJson"), nsme);
}
catch (Throwable throwable)
{
@@ -122,14 +160,14 @@ public class MetaItemStack
{
if (!hasMetaPermission(sender, "firework", true, true, ess))
{
throw new Exception(_("noMetaFirework"));
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(_("multipleCharges"));
throw new Exception(tl("multipleCharges"));
}
stack.setItemMeta(fmeta);
}
@@ -173,7 +211,7 @@ public class MetaItemStack
}
else
{
throw new Exception(_("onlyPlayerSkulls"));
throw new Exception(tl("onlyPlayerSkulls"));
}
}
else if (split.length > 1 && split[0].equalsIgnoreCase("book") && stack.getType() == Material.WRITTEN_BOOK
@@ -234,7 +272,7 @@ public class MetaItemStack
}
else
{
throw new Exception(_("leatherSyntax"));
throw new Exception(tl("leatherSyntax"));
}
}
else
@@ -260,14 +298,14 @@ public class MetaItemStack
{
if (!hasMetaPermission(sender, "firework", true, true, ess))
{
throw new Exception(_("noMetaFirework"));
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(_("multipleCharges"));
throw new Exception(tl("multipleCharges"));
}
stack.setItemMeta(fmeta);
builder = FireworkEffect.builder();
@@ -284,7 +322,7 @@ public class MetaItemStack
}
else
{
throw new Exception(_("invalidFireworkFormat", split[1], split[0]));
throw new Exception(tl("invalidFireworkFormat", split[1], split[0]));
}
}
builder.withColor(primaryColors);
@@ -299,7 +337,7 @@ public class MetaItemStack
}
else
{
throw new Exception(_("invalidFireworkFormat", split[1], split[0]));
throw new Exception(tl("invalidFireworkFormat", split[1], split[0]));
}
if (finalEffect != null)
{
@@ -318,7 +356,7 @@ public class MetaItemStack
}
else
{
throw new Exception(_("invalidFireworkFormat", split[1], split[0]));
throw new Exception(tl("invalidFireworkFormat", split[1], split[0]));
}
}
if (!fadeColors.isEmpty())
@@ -341,7 +379,7 @@ public class MetaItemStack
}
else
{
throw new Exception(_("invalidFireworkFormat", split[1], split[0]));
throw new Exception(tl("invalidFireworkFormat", split[1], split[0]));
}
}
}
@@ -370,12 +408,12 @@ public class MetaItemStack
}
else
{
throw new Exception(_("noPotionEffectPerm", pEffectType.getName().toLowerCase(Locale.ENGLISH)));
throw new Exception(tl("noPotionEffectPerm", pEffectType.getName().toLowerCase(Locale.ENGLISH)));
}
}
else
{
throw new Exception(_("invalidPotionMeta", split[1]));
throw new Exception(tl("invalidPotionMeta", split[1]));
}
}
else if (split[0].equalsIgnoreCase("power") || (allowShortName && split[0].equalsIgnoreCase("p")))
@@ -391,7 +429,7 @@ public class MetaItemStack
}
else
{
throw new Exception(_("invalidPotionMeta", split[1]));
throw new Exception(tl("invalidPotionMeta", split[1]));
}
}
else if (split[0].equalsIgnoreCase("duration") || (allowShortName && split[0].equalsIgnoreCase("d")))
@@ -403,7 +441,7 @@ public class MetaItemStack
}
else
{
throw new Exception(_("invalidPotionMeta", split[1]));
throw new Exception(tl("invalidPotionMeta", split[1]));
}
}
@@ -413,7 +451,7 @@ public class MetaItemStack
pEffect = pEffectType.createEffect(duration, power);
if (pmeta.getCustomEffects().size() > 1 && !hasMetaPermission(sender, "potions.multiple", true, false, ess))
{
throw new Exception(_("multiplePotionEffects"));
throw new Exception(tl("multiplePotionEffects"));
}
pmeta.addCustomEffect(pEffect, true);
stack.setItemMeta(pmeta);
@@ -454,7 +492,7 @@ public class MetaItemStack
{
if (enchantment == null)
{
throw new Exception(_("enchantmentNotFound"));
throw new Exception(tl("enchantmentNotFound"));
}
try
{
@@ -508,7 +546,7 @@ public class MetaItemStack
if (!hasMetaPermission(user, "enchantments." + enchantmentName, true, false))
{
throw new Exception(_("enchantmentPerm", enchantmentName));
throw new Exception(tl("enchantmentPerm", enchantmentName));
}
return enchantment;
}
@@ -533,7 +571,7 @@ public class MetaItemStack
}
else
{
throw new Exception(_("noMetaPerm", metaPerm));
throw new Exception(tl("noMetaPerm", metaPerm));
}
}
}

View File

@@ -1,6 +1,6 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -95,7 +95,7 @@ public enum Mob
final Entity entity = world.spawn(loc, (Class<? extends Entity>)this.bukkitType.getEntityClass());
if (entity == null)
{
logger.log(Level.WARNING, _("unableToSpawnMob"));
logger.log(Level.WARNING, tl("unableToSpawnMob"));
throw new MobException();
}
return entity;

View File

@@ -1,6 +1,6 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.utils.StringUtil;
import java.util.*;
import java.util.logging.Logger;
@@ -30,6 +30,7 @@ import org.bukkit.material.Colorable;
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),
@@ -83,6 +84,7 @@ public enum MobData
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),
@@ -113,8 +115,10 @@ public enum MobData
public enum Data
{
ADULT,
BABY,
CHEST,
ADULTZOMBIE,
BABYZOMBIE,
VILLAGER,
HORSESADDLE,
@@ -214,10 +218,18 @@ public enum MobData
{
((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);
@@ -274,7 +286,7 @@ public enum MobData
}
catch (Exception e)
{
throw new Exception(_("sheepMalformedColor"), e);
throw new Exception(tl("sheepMalformedColor"), e);
}
}
else if (this.value.equals(Data.EXP))
@@ -286,7 +298,7 @@ public enum MobData
}
catch (NumberFormatException e)
{
throw new Exception(_("invalidNumber"), e);
throw new Exception(tl("invalidNumber"), e);
}
}
else if (this.value.equals(Data.SIZE))
@@ -298,7 +310,7 @@ public enum MobData
}
catch (NumberFormatException e)
{
throw new Exception(_("slimeMalformedSize"), e);
throw new Exception(tl("slimeMalformedSize"), e);
}
}
else if (this.value instanceof Horse.Color)

View File

@@ -1,10 +1,8 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import java.net.InetSocketAddress;
import java.util.*;
import lombok.Delegate;
import net.ess3.api.IEssentials;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.conversations.Conversation;
@@ -25,22 +23,31 @@ import org.bukkit.potion.PotionEffectType;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.util.Vector;
public class OfflinePlayer implements Player
{
private final transient IEssentials ess;
private final transient Server server;
private transient Location location = new Location(null, 0, 0, 0, 0, 0);
private transient World world;
private final transient UUID uniqueId = UUID.randomUUID();
@Delegate(types = org.bukkit.OfflinePlayer.class)
private transient org.bukkit.OfflinePlayer base;
private boolean allowFlight = false;
private boolean isFlying = false;
private String name = null;
public OfflinePlayer(final String name, final IEssentials ess)
public OfflinePlayer(final UUID uuid, final Server server)
{
this.ess = ess;
this.world = ess.getServer().getWorlds().get(0);
this.base = ess.getServer().getOfflinePlayer(name);
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
@@ -180,25 +187,25 @@ public class OfflinePlayer implements Player
@Override
public int getRemainingAir()
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void setRemainingAir(int i)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public int getMaximumAir()
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void setMaximumAir(int i)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
@@ -210,245 +217,245 @@ public class OfflinePlayer implements Player
@Override
public void setSneaking(boolean bln)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void updateInventory()
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void chat(String string)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public double getEyeHeight()
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public double getEyeHeight(boolean bln)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public List<Block> getLineOfSight(HashSet<Byte> hs, int i)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public Block getTargetBlock(HashSet<Byte> hs, int i)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public List<Block> getLastTwoTargetBlocks(HashSet<Byte> hs, int i)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public int getFireTicks()
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public int getMaxFireTicks()
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void setFireTicks(int i)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void remove()
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public Server getServer()
{
return ess == null ? null : ess.getServer();
return server;
}
public Vector getMomentum()
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
public void setMomentum(Vector vector)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void setVelocity(Vector vector)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public Vector getVelocity()
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void damage(double d)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void damage(double d, Entity entity)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public Location getEyeLocation()
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void sendRawMessage(String string)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public Location getCompassTarget()
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public int getMaximumNoDamageTicks()
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void setMaximumNoDamageTicks(int i)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public double getLastDamage()
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void setLastDamage(double d)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public int getNoDamageTicks()
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void setNoDamageTicks(int i)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public boolean teleport(Location lctn)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public boolean teleport(Entity entity)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public Entity getPassenger()
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public boolean setPassenger(Entity entity)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public boolean isEmpty()
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public boolean eject()
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void saveData()
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void loadData()
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public boolean isSleeping()
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public int getSleepTicks()
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public List<Entity> getNearbyEntities(double d, double d1, double d2)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public boolean isDead()
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public float getFallDistance()
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
@@ -459,156 +466,175 @@ public class OfflinePlayer implements Player
@Override
public void setSleepingIgnored(boolean bln)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public boolean isSleepingIgnored()
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void awardAchievement(Achievement a)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void removeAchievement(Achievement achievement)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public boolean hasAchievement(Achievement achievement)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void incrementStatistic(Statistic ststc)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void decrementStatistic(Statistic statistic) throws IllegalArgumentException
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void incrementStatistic(Statistic ststc, int i)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void decrementStatistic(Statistic statistic, int i) throws IllegalArgumentException
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void setStatistic(Statistic statistic, int i) throws IllegalArgumentException
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public int getStatistic(Statistic statistic) throws IllegalArgumentException
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void incrementStatistic(Statistic ststc, Material mtrl)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void decrementStatistic(Statistic statistic, Material material) throws IllegalArgumentException
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public int getStatistic(Statistic statistic, Material material) throws IllegalArgumentException
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void incrementStatistic(Statistic ststc, Material mtrl, int i)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void decrementStatistic(Statistic statistic, Material material, int i) throws IllegalArgumentException
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void setStatistic(Statistic statistic, Material material, int i) throws IllegalArgumentException
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void incrementStatistic(Statistic statistic, EntityType entityType) throws IllegalArgumentException
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void decrementStatistic(Statistic statistic, EntityType entityType) throws IllegalArgumentException
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public int getStatistic(Statistic statistic, EntityType entityType) throws IllegalArgumentException
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void incrementStatistic(Statistic statistic, EntityType entityType, int i) throws IllegalArgumentException
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void decrementStatistic(Statistic statistic, EntityType entityType, int i)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void setStatistic(Statistic statistic, EntityType entityType, int i)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void playNote(Location lctn, byte b, byte b1)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void sendBlockChange(Location lctn, Material mtrl, byte b)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void sendBlockChange(Location lctn, int i, byte b)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void setLastDamageCause(EntityDamageEvent ede)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public EntityDamageEvent getLastDamageCause()
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
public void playEffect(Location lctn, Effect effect, int i)
{
throw new UnsupportedOperationException(_("notSupportedYet"));
throw new UnsupportedOperationException(tl("notSupportedYet"));
}
@Override
@@ -617,12 +643,6 @@ public class OfflinePlayer implements Player
return true;
}
@Override
public UUID getUniqueId()
{
return uniqueId;
}
@Override
public void playNote(Location lctn, Instrument i, Note note)
{
@@ -817,13 +837,12 @@ public class OfflinePlayer implements Player
@Override
public void setPlayerListName(String name)
{
}
@Override
public String getPlayerListName()
{
return getName();
return name;
}
@Override
@@ -882,9 +901,10 @@ public class OfflinePlayer implements Player
void setName(final String name)
{
if (!this.base.getName().equalsIgnoreCase(name))
this.name = base.getName();
if (this.name == null)
{
this.base = ess.getServer().getOfflinePlayer(name);
this.name = name;
}
}
@@ -923,7 +943,7 @@ public class OfflinePlayer implements Player
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void playEffect(EntityEffect ee)
{
@@ -1080,7 +1100,6 @@ public class OfflinePlayer implements Player
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isConversing()
{
@@ -1134,7 +1153,7 @@ public class OfflinePlayer implements Player
{
isFlying = arg0;
}
@Override
public int getExpToLevel()
{
@@ -1238,7 +1257,8 @@ public class OfflinePlayer implements Player
}
@Override
public void setResourcePack(String s) {
public void setResourcePack(String s)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@@ -1415,4 +1435,115 @@ public class OfflinePlayer implements Player
{
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<String, Object> serialize()
{
return base.serialize();
}
}

View File

@@ -1,6 +1,9 @@
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;
@@ -13,12 +16,6 @@ import org.bukkit.permissions.ServerOperator;
public class PlayerExtension
{
@Delegate(types =
{
Player.class, Entity.class, CommandSender.class, ServerOperator.class,
HumanEntity.class, ConfigurationSerializable.class, LivingEntity.class,
Permissible.class
})
protected Player base;
public PlayerExtension(final Player base)
@@ -35,4 +32,17 @@ public class PlayerExtension
{
return this.base = base;
}
public Server getServer()
{
return base.getServer();
}
public World getWorld() {
return base.getWorld();
}
public Location getLocation() {
return base.getLocation();
}
}

View File

@@ -1,6 +1,6 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.utils.FormatUtil;
import java.util.ArrayList;
import java.util.Collections;
@@ -30,11 +30,11 @@ public class PlayerList
needComma = true;
if (user.isAfk())
{
groupString.append(_("listAfkTag"));
groupString.append(tl("listAfkTag"));
}
if (user.isHidden())
{
groupString.append(_("listHiddenTag"));
groupString.append(tl("listHiddenTag"));
}
user.setDisplayNick();
groupString.append(user.getDisplayName());
@@ -44,38 +44,43 @@ public class PlayerList
}
// Produce a user summary: There are 5 out of maximum 10 players online.
public static String listSummary(final IEssentials ess, final boolean showHidden)
public static String listSummary(final IEssentials ess, final User user, final boolean showHidden)
{
Server server = ess.getServer();
int playerHidden = 0;
for (Player onlinePlayer : server.getOnlinePlayers())
int hiddenCount = 0;
for (User onlinePlayer : ess.getOnlineUsers())
{
if (ess.getUser(onlinePlayer).isHidden())
if (onlinePlayer.isHidden() || (user != null && !user.getBase().canSee(onlinePlayer.getBase())))
{
playerHidden++;
if (showHidden || user.getBase().canSee(onlinePlayer.getBase()))
{
hiddenCount++;
}
}
}
String online;
if (showHidden && playerHidden > 0)
if (hiddenCount > 0)
{
online = _("listAmountHidden", server.getOnlinePlayers().length - playerHidden, playerHidden, server.getMaxPlayers());
online = tl("listAmountHidden", ess.getOnlinePlayers().size() - playerHidden, hiddenCount, server.getMaxPlayers());
}
else
{
online = _("listAmount", server.getOnlinePlayers().length - playerHidden, server.getMaxPlayers());
online = tl("listAmount", ess.getOnlinePlayers().size() - playerHidden, server.getMaxPlayers());
}
return online;
}
// Build the basic player list, divided by groups.
public static Map<String, List<User>> getPlayerLists(final IEssentials ess, final boolean showHidden)
public static Map<String, List<User>> getPlayerLists(final IEssentials ess, final User sender, final boolean showHidden)
{
Server server = ess.getServer();
final Map<String, List<User>> playerList = new HashMap<String, List<User>>();
for (Player onlinePlayer : server.getOnlinePlayers())
for (User onlineUser : ess.getOnlineUsers())
{
final User onlineUser = ess.getUser(onlinePlayer);
if (onlineUser.isHidden() && !showHidden)
if ((sender == null && !showHidden && onlineUser.isHidden()) ||
(sender != null && !showHidden && !sender.getBase().canSee(onlineUser.getBase())))
{
continue;
}
@@ -132,7 +137,7 @@ public class PlayerList
}
if (users == null || users.isEmpty())
{
throw new Exception(_("groupDoesNotExist"));
throw new Exception(tl("groupDoesNotExist"));
}
final StringBuilder displayGroupName = new StringBuilder();
displayGroupName.append(Character.toTitleCase(groupName.charAt(0)));
@@ -144,7 +149,7 @@ public class PlayerList
public static String outputFormat(final String group, final String message)
{
final StringBuilder outputString = new StringBuilder();
outputString.append(_("listGroupTag", FormatUtil.replaceFormat(group)));
outputString.append(tl("listGroupTag", FormatUtil.replaceFormat(group)));
outputString.append(message);
return outputString.toString();
}

View File

@@ -100,35 +100,20 @@ public class Potions
POTIONS.put("wither", PotionEffectType.WITHER);
ALIASPOTIONS.put("decay", PotionEffectType.WITHER);
POTIONS.put("healthboost", PotionEffectType.HEALTH_BOOST);
ALIASPOTIONS.put("boost", PotionEffectType.HEALTH_BOOST);
try // 1.6 update
{
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);
}
catch (java.lang.NoSuchFieldError e)
{
Essentials.wrongVersion();
}
POTIONS.put("saturation", PotionEffectType.SATURATION);
ALIASPOTIONS.put("food", PotionEffectType.SATURATION);
try // 1.7 update
{
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);
}
catch (java.lang.NoSuchFieldError e)
{
Essentials.wrongVersion();
}
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 PotionEffectType getByName(String name)

View File

@@ -1,6 +1,6 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
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;
@@ -51,7 +51,8 @@ public class Settings implements net.ess3.api.ISettings
@Override
public Set<String> getMultipleHomes()
{
return config.getConfigurationSection("sethome-multiple").getKeys(false);
final ConfigurationSection section = config.getConfigurationSection("sethome-multiple");
return section == null ? null : section.getKeys(false);
}
@Override
@@ -94,7 +95,32 @@ public class Settings implements net.ess3.api.ISettings
{
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()
@@ -205,7 +231,6 @@ public class Settings implements net.ess3.api.ISettings
final ConfigurationSection newSection = new MemoryConfiguration();
for (String command : section.getKeys(false))
{
PluginCommand cmd = ess.getServer().getPluginCommand(command);
if (command.charAt(0) == '/')
{
ess.getLogger().warning("Invalid command cost. '" + command + "' should not start with '/'.");
@@ -524,17 +549,20 @@ public class Settings implements net.ess3.api.ISettings
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 = _isJoinQuitMessagesDisabled();
allowSilentJoin = _allowSilentJoinQuit();
customJoinMessage = _getCustomJoinMessage();
isCustomJoinMessage = !customJoinMessage.equals("none");
customQuitMessage = _getCustomQuitMessage();
@@ -570,7 +598,7 @@ public class Settings implements net.ess3.api.ISettings
}
catch (Exception ex)
{
logger.log(Level.SEVERE, _("unknownItemInList", itemName, "item-spawn-blacklist"));
logger.log(Level.SEVERE, tl("unknownItemInList", itemName, "item-spawn-blacklist"));
}
}
return epItemSpwn;
@@ -606,7 +634,7 @@ public class Settings implements net.ess3.api.ISettings
}
catch (Exception ex)
{
logger.log(Level.SEVERE, _("unknownItemInList", signName, "enabledSigns"));
logger.log(Level.SEVERE, tl("unknownItemInList", signName, "enabledSigns"));
continue;
}
signsEnabled = true;
@@ -710,7 +738,7 @@ public class Settings implements net.ess3.api.ISettings
}
catch (Exception ex)
{
logger.log(Level.SEVERE, _("unknownItemInList", itemName, configName));
logger.log(Level.SEVERE, tl("unknownItemInList", itemName, configName));
}
}
return list;
@@ -1110,8 +1138,8 @@ public class Settings implements net.ess3.api.ISettings
private long _getEconomyLagWarning()
{
// Default to 20ms
final long value = (long)(config.getDouble("economy-lag-warning", 20.0) * 1000000);
// Default to 25ms
final long value = (long)(config.getDouble("economy-lag-warning", 25.0) * 1000000);
return value;
}
@@ -1120,6 +1148,22 @@ public class Settings implements net.ess3.api.ISettings
{
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()
@@ -1134,9 +1178,9 @@ public class Settings implements net.ess3.api.ISettings
}
private boolean allowSilentJoin;
public boolean _isJoinQuitMessagesDisabled()
public boolean _allowSilentJoinQuit()
{
return config.getBoolean("allow-silent-join-quit");
return config.getBoolean("allow-silent-join-quit", false);
}
@Override

View File

@@ -1,6 +1,6 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
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;
@@ -34,7 +34,7 @@ public class SpawnMob
}
if (availableList.isEmpty())
{
availableList.add(_("none"));
availableList.add(tl("none"));
}
return StringUtil.joinList(availableList);
}
@@ -88,7 +88,7 @@ public class SpawnMob
final Block block = LocationUtil.getTarget(user.getBase()).getBlock();
if (block == null)
{
throw new Exception(_("unableToSpawnMob"));
throw new Exception(tl("unableToSpawnMob"));
}
spawnmob(ess, server, user.getSource(), user, block.getLocation(), parts, data, mobCount);
}
@@ -125,7 +125,7 @@ public class SpawnMob
if (mobCount > effectiveLimit)
{
mobCount = effectiveLimit;
sender.sendMessage(_("mobSpawnLimit"));
sender.sendMessage(tl("mobSpawnLimit"));
}
Mob mob = Mob.fromName(parts.get(0)); // Get the first mob
@@ -135,19 +135,19 @@ public class SpawnMob
{
spawnMob(ess, server, sender, target, sloc, parts, data);
}
sender.sendMessage(mobCount * parts.size() + " " + mob.name.toLowerCase(Locale.ENGLISH) + mob.suffix + " " + _("spawned"));
sender.sendMessage(mobCount * parts.size() + " " + mob.name.toLowerCase(Locale.ENGLISH) + mob.suffix + " " + tl("spawned"));
}
catch (MobException e1)
{
throw new Exception(_("unableToSpawnMob"), e1);
throw new Exception(tl("unableToSpawnMob"), e1);
}
catch (NumberFormatException e2)
{
throw new Exception(_("numberRequired"), e2);
throw new Exception(tl("numberRequired"), e2);
}
catch (NullPointerException np)
{
throw new Exception(_("soloMob"), np);
throw new Exception(tl("soloMob"), np);
}
}
@@ -194,17 +194,17 @@ public class SpawnMob
{
if (mob == null)
{
throw new Exception(_("invalidMob"));
throw new Exception(tl("invalidMob"));
}
if (ess.getSettings().getProtectPreventSpawn(mob.getType().toString().toLowerCase(Locale.ENGLISH)))
{
throw new Exception(_("disabledToSpawnMob"));
throw new Exception(tl("disabledToSpawnMob"));
}
if (sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.spawnmob." + mob.name.toLowerCase(Locale.ENGLISH)))
{
throw new Exception(_("noPermToSpawnMob"));
throw new Exception(tl("noPermToSpawnMob"));
}
}
@@ -214,7 +214,16 @@ public class SpawnMob
if (data.isEmpty())
{
sender.sendMessage(_("mobDataList", StringUtil.joinList(MobData.getValidHelp(spawned))));
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 (spawned instanceof Zombie || type == EntityType.SKELETON)
@@ -285,7 +294,10 @@ public class SpawnMob
if (type == EntityType.PIG_ZOMBIE)
{
final EntityEquipment invent = ((LivingEntity)spawned).getEquipment();
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);
@@ -295,7 +307,10 @@ public class SpawnMob
if (type == EntityType.ZOMBIE)
{
final EntityEquipment invent = ((LivingEntity)spawned).getEquipment();
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);
}

View File

@@ -1,6 +1,6 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.utils.DateUtil;
import com.earth2me.essentials.utils.LocationUtil;
import java.math.BigDecimal;
@@ -54,7 +54,7 @@ public class Teleport implements net.ess3.api.ITeleport
time.setTimeInMillis(lastTime);
time.add(Calendar.SECOND, (int)cooldown);
time.add(Calendar.MILLISECOND, (int)((cooldown * 1000.0) % 1000.0));
throw new Exception(_("timeBeforeTeleport", DateUtil.formatDateDiff(time.getTimeInMillis())));
throw new Exception(tl("timeBeforeTeleport", DateUtil.formatDateDiff(time.getTimeInMillis())));
}
}
// if justCheck is set, don't update lastTeleport; we're just checking
@@ -69,7 +69,7 @@ public class Teleport implements net.ess3.api.ITeleport
Calendar c = new GregorianCalendar();
c.add(Calendar.SECOND, (int)delay);
c.add(Calendar.MILLISECOND, (int)((delay * 1000.0) % 1000.0));
user.sendMessage(_("dontMoveMessage", DateUtil.formatDateDiff(c.getTimeInMillis())));
user.sendMessage(tl("dontMoveMessage", DateUtil.formatDateDiff(c.getTimeInMillis())));
}
//The now function is used when you want to skip tp delay when teleporting someone to a location or player.
@@ -93,7 +93,7 @@ public class Teleport implements net.ess3.api.ITeleport
}
final ITarget target = new PlayerTarget(entity);
now(teleportOwner, target, cause);
teleportOwner.sendMessage(_("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()));
}
protected void now(IUser teleportee, ITarget target, TeleportCause cause) throws Exception
@@ -102,7 +102,7 @@ public class Teleport implements net.ess3.api.ITeleport
teleportee.setLastLocation();
final Location loc = target.getLocation();
if (LocationUtil.isBlockUnsafe(loc.getWorld(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()))
if (LocationUtil.isBlockUnsafeForUser(teleportee, loc.getWorld(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()))
{
if (ess.getSettings().isTeleportSafetyEnabled())
{
@@ -114,7 +114,7 @@ public class Teleport implements net.ess3.api.ITeleport
}
else
{
throw new Exception(_("unsafeTeleportDestination", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()));
throw new Exception(tl("unsafeTeleportDestination", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()));
}
}
else
@@ -147,8 +147,8 @@ public class Teleport implements net.ess3.api.ITeleport
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);
teleportOwner.sendMessage(_("teleporting", target.getLocation().getWorld().getName(), target.getLocation().getBlockX(), target.getLocation().getBlockY(), target.getLocation().getBlockZ()));
}
//This is used when teleporting to stored location
@@ -164,8 +164,8 @@ public class Teleport implements net.ess3.api.ITeleport
{
ITarget target = new PlayerTarget(entity);
teleport(teleportee, target, chargeFor, cause);
teleportee.sendMessage(_("teleporting", target.getLocation().getWorld().getName(), target.getLocation().getBlockX(), target.getLocation().getBlockY(), target.getLocation().getBlockZ()));
teleportOwner.sendMessage(_("teleporting", target.getLocation().getWorld().getName(), target.getLocation().getBlockX(), target.getLocation().getBlockY(), target.getLocation().getBlockZ()));
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()));
}
private void teleport(IUser teleportee, ITarget target, Trade chargeFor, TeleportCause cause) throws Exception
@@ -177,7 +177,7 @@ public class Teleport implements net.ess3.api.ITeleport
if (chargeFor != null)
{
chargeFor.isAffordableFor(teleportOwner);
//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))
{
@@ -255,7 +255,11 @@ public class Teleport implements net.ess3.api.ITeleport
public void warp(IUser teleportee, String warp, Trade chargeFor, TeleportCause cause) throws Exception
{
Location loc = ess.getWarps().getWarp(warp);
teleportee.sendMessage(_("warpingTo", warp, loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()));
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);
}
@@ -264,7 +268,7 @@ public class Teleport implements net.ess3.api.ITeleport
public void back(Trade chargeFor) throws Exception
{
final Location loc = teleportOwner.getLastLocation();
teleportOwner.sendMessage(_("backUsageMsg", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()));
teleportOwner.sendMessage(tl("backUsageMsg", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()));
teleport(teleportOwner, new LocationTarget(loc), chargeFor, TeleportCause.COMMAND);
}

View File

@@ -1,8 +1,7 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
import java.util.logging.Level;
import java.util.logging.Logger;
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;
@@ -15,7 +14,7 @@ public class TimedTeleport implements Runnable
private final IUser teleportOwner;
private final IEssentials ess;
private final Teleport teleport;
private final String timer_teleportee;
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
@@ -44,14 +43,14 @@ public class TimedTeleport implements Runnable
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.getName();
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");
timer_task = ess.scheduleSyncRepeatingTask(this, 20, 20);
timer_task = ess.runTaskTimerAsynchronously(this, 20, 20).getTaskId();
}
@Override
@@ -64,7 +63,7 @@ public class TimedTeleport implements Runnable
return;
}
IUser teleportUser = ess.getUser(this.timer_teleportee);
final IUser teleportUser = ess.getUser(this.timer_teleportee);
if (teleportUser == null || !teleportUser.getBase().isOnline())
{
@@ -90,49 +89,65 @@ public class TimedTeleport implements Runnable
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)
class DelayedTeleportTask implements Runnable
{
try
@Override
public void run()
{
teleport.cooldown(false);
}
catch (Exception ex)
{
teleportOwner.sendMessage(_("cooldownWithMessage", ex.getMessage()));
if (teleportOwner != teleportUser)
{
teleportUser.sendMessage(_("cooldownWithMessage", ex.getMessage()));
}
}
try
{
cancelTimer(false);
teleportUser.sendMessage(_("teleportationCommencing"));
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)
{
ess.showError(teleportOwner.getSource(), ex, "\\ teleport");
}
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"));
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
@@ -147,10 +162,10 @@ public class TimedTeleport implements Runnable
ess.getServer().getScheduler().cancelTask(timer_task);
if (notifyUser)
{
teleportOwner.sendMessage(_("pendingTeleportCancelled"));
if (timer_teleportee != null && !timer_teleportee.equals(teleportOwner.getName()))
teleportOwner.sendMessage(tl("pendingTeleportCancelled"));
if (timer_teleportee != null && !timer_teleportee.equals(teleportOwner.getBase().getUniqueId()))
{
ess.getUser(timer_teleportee).sendMessage(_("pendingTeleportCancelled"));
ess.getUser(timer_teleportee).sendMessage(tl("pendingTeleportCancelled"));
}
}
}

View File

@@ -1,8 +1,9 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
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 java.io.File;
import java.io.FileWriter;
import java.io.IOException;
@@ -28,7 +29,7 @@ public class Trade
private final transient BigDecimal money;
private final transient ItemStack itemStack;
private final transient Integer exp;
private final transient com.earth2me.essentials.IEssentials ess;
private final transient IEssentials ess;
public enum TradeType
@@ -59,7 +60,7 @@ public class Trade
@Deprecated
public Trade(final double money, final com.earth2me.essentials.IEssentials ess)
{
this(null, null, BigDecimal.valueOf(money), null, null, ess);
this(null, null, BigDecimal.valueOf(money), null, null, (IEssentials)ess);
}
public Trade(final BigDecimal money, final IEssentials ess)
@@ -77,7 +78,7 @@ public class Trade
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 com.earth2me.essentials.IEssentials 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;
@@ -99,13 +100,13 @@ public class Trade
&& getMoney().signum() > 0
&& !user.canAfford(getMoney()))
{
throw new ChargeException(_("notEnoughMoney"));
throw new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(getMoney(), ess)));
}
if (getItemStack() != null
&& !user.getBase().getInventory().containsAtLeast(itemStack, itemStack.getAmount()))
{
throw new ChargeException(_("missingItems", getItemStack().getAmount(), ess.getItemDb().name(getItemStack())));
throw new ChargeException(tl("missingItems", getItemStack().getAmount(), ess.getItemDb().name(getItemStack())));
}
BigDecimal money;
@@ -113,13 +114,13 @@ public class Trade
&& (money = getCommandCost(user)).signum() > 0
&& !user.canAfford(money))
{
throw new ChargeException(_("notEnoughMoney"));
throw new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(money, ess)));
}
if (exp != null && exp > 0
&& SetExpFix.getTotalExperience(user.getBase()) < exp)
{
throw new ChargeException(_("notEnoughExperience"));
throw new ChargeException(tl("notEnoughExperience"));
}
}
@@ -223,7 +224,7 @@ public class Trade
}
if (!user.canAfford(getMoney()) && getMoney().signum() > 0)
{
throw new ChargeException(_("notEnoughMoney"));
throw new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(getMoney(), ess)));
}
user.takeMoney(getMoney());
}
@@ -235,7 +236,7 @@ public class Trade
}
if (!user.getBase().getInventory().containsAtLeast(getItemStack(), getItemStack().getAmount()))
{
throw new ChargeException(_("missingItems", getItemStack().getAmount(), getItemStack().getType().toString().toLowerCase(Locale.ENGLISH).replace("_", " ")));
throw new ChargeException(tl("missingItems", getItemStack().getAmount(), getItemStack().getType().toString().toLowerCase(Locale.ENGLISH).replace("_", " ")));
}
user.getBase().getInventory().removeItem(getItemStack());
user.getBase().updateInventory();
@@ -245,7 +246,7 @@ public class Trade
final BigDecimal cost = getCommandCost(user);
if (!user.canAfford(cost) && cost.signum() > 0)
{
throw new ChargeException(_("notEnoughMoney"));
throw new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(cost, ess)));
}
user.takeMoney(cost);
}
@@ -258,7 +259,7 @@ public class Trade
final int experience = SetExpFix.getTotalExperience(user.getBase());
if (experience < getExperience() && getExperience() > 0)
{
throw new ChargeException(_("notEnoughExperience"));
throw new ChargeException(tl("notEnoughExperience"));
}
SetExpFix.setTotalExperience(user.getBase(), experience - getExperience());
}

View File

@@ -0,0 +1,212 @@
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 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.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 UUIDMap(final net.ess3.api.IEssentials ess)
{
this.ess = ess;
userList = new File(ess.getDataFolder(), "usermap.csv");
}
public void loadAllUsers(final ConcurrentSkipListMap<String, UUID> names, final ConcurrentSkipListMap<UUID, ArrayList<String>> history)
{
try
{
if (!userList.exists())
{
userList.createNewFile();
}
synchronized (pendingDiskWrites)
{
if (ess.getSettings().isDebug())
{
ess.getLogger().log(Level.INFO, "Reading usermap from disk");
}
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<String> list = new ArrayList<String>();
list.add(name);
history.put(uuid, list);
}
else
{
final ArrayList<String> 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 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<String, UUID> 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<String, UUID> names;
private final AtomicInteger pendingDiskWrites;
private WriteRunner(final File location, final File endFile, final ConcurrentSkipListMap<String, UUID> 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;
}
File configFile = null;
try
{
configFile = File.createTempFile("usermap", ".tmp.csv", location);
final BufferedWriter bWriter = new BufferedWriter(new FileWriter(configFile));
for (Map.Entry<String, UUID> 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();
}
}
}
}
}

View File

@@ -1,6 +1,6 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
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;
@@ -10,6 +10,7 @@ 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;
@@ -18,7 +19,6 @@ import net.ess3.api.events.AfkStatusChangeEvent;
import net.ess3.api.events.UserBalanceUpdateEvent;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.potion.PotionEffect;
@@ -29,7 +29,7 @@ public class User extends UserData implements Comparable<User>, IReplyTo, net.es
{
private static final Logger logger = Logger.getLogger("Essentials");
private CommandSource replyTo = null;
private transient String teleportRequester;
private transient UUID teleportRequester;
private transient boolean teleportRequestHere;
private transient Location teleportLocation;
private transient boolean vanished;
@@ -46,13 +46,13 @@ public class User extends UserData implements Comparable<User>, IReplyTo, net.es
private boolean enderSee = false;
private transient long teleportInvulnerabilityTimestamp = 0;
User(final Player base, final IEssentials ess)
public User(final Player base, final IEssentials ess)
{
super(base, ess);
teleport = new Teleport(this, ess);
if (isAfk())
{
afkPosition = this.getBase().getLocation();
afkPosition = this.getLocation();
}
if (this.getBase().isOnline())
{
@@ -129,14 +129,14 @@ public class User extends UserData implements Comparable<User>, IReplyTo, net.es
cooldownTime.add(Calendar.MILLISECOND, (int)((cooldown * 1000.0) % 1000.0));
if (cooldownTime.after(now) && !isAuthorized("essentials.heal.cooldown.bypass"))
{
throw new Exception(_("timeBeforeHeal", DateUtil.formatDateDiff(cooldownTime.getTimeInMillis())));
throw new Exception(tl("timeBeforeHeal", DateUtil.formatDateDiff(cooldownTime.getTimeInMillis())));
}
}
setLastHealTimestamp(now.getTimeInMillis());
}
@Override
public void giveMoney(final BigDecimal value) throws MaxMoneyException
public void giveMoney(final BigDecimal value) throws MaxMoneyException
{
giveMoney(value, (CommandSource)null);
}
@@ -149,10 +149,10 @@ public class User extends UserData implements Comparable<User>, IReplyTo, net.es
return;
}
setMoney(getMoney().add(value));
sendMessage(_("addedToAccount", NumberUtil.displayCurrency(value, ess)));
sendMessage(tl("addedToAccount", NumberUtil.displayCurrency(value, ess)));
if (initiator != null)
{
initiator.sendMessage(_("addedToOthersAccount", NumberUtil.displayCurrency(value, ess), this.getDisplayName(), NumberUtil.displayCurrency(getMoney(), ess)));
initiator.sendMessage(tl("addedToOthersAccount", NumberUtil.displayCurrency(value, ess), this.getDisplayName(), NumberUtil.displayCurrency(getMoney(), ess)));
}
}
@@ -167,12 +167,12 @@ public class User extends UserData implements Comparable<User>, IReplyTo, net.es
{
setMoney(getMoney().subtract(value));
reciever.setMoney(reciever.getMoney().add(value));
sendMessage(_("moneySentTo", NumberUtil.displayCurrency(value, ess), reciever.getDisplayName()));
reciever.sendMessage(_("moneyRecievedFrom", NumberUtil.displayCurrency(value, ess), getDisplayName()));
sendMessage(tl("moneySentTo", NumberUtil.displayCurrency(value, ess), reciever.getDisplayName()));
reciever.sendMessage(tl("moneyRecievedFrom", NumberUtil.displayCurrency(value, ess), getDisplayName()));
}
else
{
throw new ChargeException(_("notEnoughMoney"));
throw new ChargeException(tl("notEnoughMoney", NumberUtil.displayCurrency(value, ess)));
}
}
@@ -195,12 +195,12 @@ public class User extends UserData implements Comparable<User>, IReplyTo, net.es
}
catch (MaxMoneyException ex)
{
//We shouldn't be able to throw an exception on subtract money
ess.getLogger().log(Level.WARNING, "Invalid call to takeMoney, total balance can't be more than the max-money limit.", ex);
}
sendMessage(_("takenFromAccount", NumberUtil.displayCurrency(value, ess)));
sendMessage(tl("takenFromAccount", NumberUtil.displayCurrency(value, ess)));
if (initiator != null)
{
initiator.sendMessage(_("takenFromOthersAccount", NumberUtil.displayCurrency(value, ess), this.getDisplayName(), NumberUtil.displayCurrency(getMoney(), ess)));
initiator.sendMessage(tl("takenFromOthersAccount", NumberUtil.displayCurrency(value, ess), this.getDisplayName(), NumberUtil.displayCurrency(getMoney(), ess)));
}
}
@@ -226,7 +226,23 @@ public class User extends UserData implements Comparable<User>, IReplyTo, net.es
public void dispose()
{
this.base = new OfflinePlayer(getName(), ess);
ess.runTaskAsynchronously(new Runnable()
{
@Override
public void run()
{
_dispose();
}
});
}
private void _dispose()
{
if (!base.isOnline())
{
this.base = new OfflinePlayer(getConfigUUID(), ess.getServer());
}
cleanup();
}
@Override
@@ -238,20 +254,20 @@ public class User extends UserData implements Comparable<User>, IReplyTo, net.es
@Override
public void setLastLocation()
{
setLastLocation(this.getBase().getLocation());
setLastLocation(this.getLocation());
}
@Override
public void setLogoutLocation()
{
setLogoutLocation(this.getBase().getLocation());
setLogoutLocation(this.getLocation());
}
@Override
public void requestTeleport(final User player, final boolean here)
{
teleportRequestTime = System.currentTimeMillis();
teleportRequester = player == null ? null : player.getName();
teleportRequester = player == null ? null : player.getBase().getUniqueId();
teleportRequestHere = here;
if (player == null)
{
@@ -259,11 +275,11 @@ public class User extends UserData implements Comparable<User>, IReplyTo, net.es
}
else
{
teleportLocation = here ? player.getBase().getLocation() : this.getBase().getLocation();
teleportLocation = here ? player.getLocation() : this.getLocation();
}
}
public String getTeleportRequest()
public UUID getTeleportRequest()
{
return teleportRequester;
}
@@ -284,10 +300,13 @@ public class User extends UserData implements Comparable<User>, IReplyTo, net.es
String nickname;
String suffix = "";
final String nick = getNickname();
if (ess.getSettings().isCommandDisabled("nick") || nick == null || nick.isEmpty() || nick.equalsIgnoreCase(getName()))
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;
@@ -494,11 +513,11 @@ public class User extends UserData implements Comparable<User>, IReplyTo, net.es
{
return;
}
this.getBase().setSleepingIgnored(this.isAuthorized("essentials.sleepingignored") ? true : set);
if (set && !isAfk())
{
afkPosition = this.getBase().getLocation();
afkPosition = this.getLocation();
}
else if (!set && isAfk())
{
@@ -506,7 +525,7 @@ public class User extends UserData implements Comparable<User>, IReplyTo, net.es
}
_setAfk(set);
}
public boolean toggleAfk()
{
setAfk(!isAfk());
@@ -518,6 +537,11 @@ public class User extends UserData implements Comparable<User>, IReplyTo, net.es
{
return hidden;
}
public boolean isHidden(final Player player)
{
return hidden || !player.canSee(getBase());
}
@Override
public void setHidden(final boolean hidden)
@@ -536,7 +560,7 @@ public class User extends UserData implements Comparable<User>, IReplyTo, net.es
{
setJailTimeout(0);
setJailed(false);
sendMessage(_("haveBeenReleased"));
sendMessage(tl("haveBeenReleased"));
setJail(null);
try
{
@@ -563,25 +587,13 @@ public class User extends UserData implements Comparable<User>, IReplyTo, net.es
if (getMuteTimeout() > 0 && getMuteTimeout() < currentTime && isMuted())
{
setMuteTimeout(0);
sendMessage(_("canTalkAgain"));
sendMessage(tl("canTalkAgain"));
setMuted(false);
return true;
}
return false;
}
//Returns true if status expired during this check
public boolean checkBanTimeout(final long currentTime)
{
if (getBanTimeout() > 0 && getBanTimeout() < currentTime && this.getBase().isBanned())
{
setBanTimeout(0);
this.getBase().setBanned(false);
return true;
}
return false;
}
public void updateActivity(final boolean broadcast)
{
if (isAfk() && ess.getSettings().cancelAfkOnInteract())
@@ -590,7 +602,7 @@ public class User extends UserData implements Comparable<User>, IReplyTo, net.es
if (broadcast && !isHidden())
{
setDisplayNick();
final String msg = _("userIsNotAway", getDisplayName());
final String msg = tl("userIsNotAway", getDisplayName());
if (!msg.isEmpty())
{
ess.broadcastMessage(this, msg);
@@ -606,17 +618,16 @@ public class User extends UserData implements Comparable<User>, IReplyTo, net.es
if (autoafkkick > 0 && lastActivity > 0 && (lastActivity + (autoafkkick * 1000)) < System.currentTimeMillis()
&& !isHidden() && !isAuthorized("essentials.kick.exempt") && !isAuthorized("essentials.afk.kickexempt"))
{
final String kickReason = _("autoAfkKickReason", autoafkkick / 60.0);
final String kickReason = tl("autoAfkKickReason", autoafkkick / 60.0);
lastActivity = 0;
this.getBase().kickPlayer(kickReason);
for (Player player : ess.getServer().getOnlinePlayers())
for (User user : ess.getOnlineUsers())
{
final User user = ess.getUser(player);
if (user.isAuthorized("essentials.kick.notify"))
{
user.sendMessage(_("playerKicked", Console.NAME, getName(), kickReason));
user.sendMessage(tl("playerKicked", Console.NAME, getName(), kickReason));
}
}
}
@@ -627,7 +638,7 @@ public class User extends UserData implements Comparable<User>, IReplyTo, net.es
if (!isHidden())
{
setDisplayNick();
final String msg = _("userIsAway", getDisplayName());
final String msg = tl("userIsAway", getDisplayName());
if (!msg.isEmpty())
{
ess.broadcastMessage(this, msg);
@@ -644,7 +655,7 @@ public class User extends UserData implements Comparable<User>, IReplyTo, net.es
@Override
public boolean isGodModeEnabled()
{
return (super.isGodModeEnabled() && !ess.getSettings().getNoGodWorlds().contains(this.getBase().getLocation().getWorld().getName()))
return (super.isGodModeEnabled() && !ess.getSettings().getNoGodWorlds().contains(this.getLocation().getWorld().getName()))
|| (isAfk() && ess.getSettings().getFreezeAfkPlayers());
}
@@ -735,6 +746,11 @@ public class User extends UserData implements Comparable<User>, IReplyTo, net.es
{
return teleportInvulnerabilityTimestamp != 0 && teleportInvulnerabilityTimestamp >= System.currentTimeMillis();
}
public boolean canInteractVanished()
{
return isAuthorized("essentials.vanish.interact");
}
@Override
public boolean isVanished()
@@ -748,11 +764,11 @@ public class User extends UserData implements Comparable<User>, IReplyTo, net.es
vanished = set;
if (set)
{
for (Player p : ess.getServer().getOnlinePlayers())
for (User user : ess.getOnlineUsers())
{
if (!ess.getUser(p).isAuthorized("essentials.vanish.see"))
if (!user.isAuthorized("essentials.vanish.see"))
{
p.hidePlayer(getBase());
user.getBase().hidePlayer(getBase());
}
}
setHidden(true);
@@ -764,7 +780,7 @@ public class User extends UserData implements Comparable<User>, IReplyTo, net.es
}
else
{
for (Player p : ess.getServer().getOnlinePlayers())
for (Player p : ess.getOnlinePlayers())
{
p.showPlayer(getBase());
}
@@ -795,7 +811,7 @@ public class User extends UserData implements Comparable<User>, IReplyTo, net.es
public void updateThrottle()
{
lastThrottledAction = System.currentTimeMillis();;
lastThrottledAction = System.currentTimeMillis();
}
public boolean isFlyClickJump()

View File

@@ -1,6 +1,6 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.utils.NumberUtil;
import com.earth2me.essentials.utils.StringUtil;
import java.io.File;
@@ -18,7 +18,7 @@ import org.bukkit.inventory.ItemStack;
public abstract class UserData extends PlayerExtension implements IConf
{
protected final transient IEssentials ess;
private final EssentialsConf config;
private final EssentialsUserConf config;
private final File folder;
protected UserData(Player base, IEssentials ess)
@@ -30,14 +30,35 @@ public abstract class UserData extends PlayerExtension implements IConf
{
folder.mkdirs();
}
config = new EssentialsConf(new File(folder, StringUtil.sanitizeFileName(base.getName()) + ".yml"));
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();
ess.getUserMap().removeUser(this.getBase().getName());
if (config.username != null)
{
ess.getUserMap().removeUser(config.username);
}
}
public final void cleanup()
{
config.cleanup();
}
@Override
@@ -71,6 +92,7 @@ public abstract class UserData extends PlayerExtension implements IConf
nickname = _getNickname();
ignoredPlayers = _getIgnoredPlayers();
logoutLocation = _getLogoutLocation();
lastAccountName = _getLastAccountName();
}
private BigDecimal money;
@@ -102,23 +124,26 @@ public abstract class UserData extends PlayerExtension implements IConf
public void setMoney(BigDecimal value, boolean throwError) throws MaxMoneyException
{
money = value;
BigDecimal maxMoney = ess.getSettings().getMaxMoney();
BigDecimal minMoney = ess.getSettings().getMinMoney();
if (money.compareTo(maxMoney) > 0)
if (value.compareTo(maxMoney) > 0)
{
money = maxMoney;
if (throwError)
{
throw new MaxMoneyException();
}
money = maxMoney;
}
else
{
money = value;
}
if (money.compareTo(minMoney) < 0)
{
money = minMoney;
}
config.setProperty("money", money);
config.save();
stopTransaction();
}
private Map<String, Object> homes;
@@ -211,7 +236,7 @@ public abstract class UserData extends PlayerExtension implements IConf
}
else
{
throw new Exception(_("invalidHome", search));
throw new Exception(tl("invalidHome", search));
}
}
@@ -642,27 +667,6 @@ public abstract class UserData extends PlayerExtension implements IConf
config.save();
}
public String getBanReason()
{
return config.getString("ban.reason", "");
}
public void setBanReason(String reason)
{
config.setProperty("ban.reason", StringUtil.sanitizeString(reason));
config.save();
}
public long getBanTimeout()
{
return config.getLong("ban.timeout", 0);
}
public void setBanTimeout(long time)
{
config.setProperty("ban.timeout", time);
config.save();
}
private long lastLogin;
private long _getLastLogin()
@@ -799,6 +803,25 @@ public abstract class UserData extends PlayerExtension implements IConf
{
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)
{
@@ -873,12 +896,6 @@ public abstract class UserData extends PlayerExtension implements IConf
config.save();
}
public void trackUUID()
{
config.setProperty("uuid", base.getUniqueId().toString());
config.save();
}
public void setConfigProperty(String node, Object object)
{
final String prefix = "info.";
@@ -933,8 +950,23 @@ public abstract class UserData extends PlayerExtension implements IConf
return new HashMap<String, Object>();
}
public UUID getConfigUUID()
{
return config.uuid;
}
public void save()
{
config.save();
}
public void startTransaction()
{
config.startTransaction();
}
public void stopTransaction()
{
config.stopTransaction();
}
}

View File

@@ -4,10 +4,17 @@ 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;
@@ -18,14 +25,19 @@ public class UserMap extends CacheLoader<String, User> implements IConf
{
private final transient IEssentials ess;
private final transient Cache<String, User> users;
private final transient ConcurrentSkipListSet<String> keys = new ConcurrentSkipListSet<String>();
private final transient ConcurrentSkipListSet<UUID> keys = new ConcurrentSkipListSet<UUID>();
private final transient ConcurrentSkipListMap<String, UUID> names = new ConcurrentSkipListMap<String, UUID>();
private final transient ConcurrentSkipListMap<UUID, ArrayList<String>> history = new ConcurrentSkipListMap<UUID, ArrayList<String>>();
private UUIDMap uuidMap;
public UserMap(final IEssentials ess)
{
super();
this.ess = ess;
users = CacheBuilder.newBuilder().maximumSize(ess.getSettings().getMaxUserCacheCount()).softValues().build(this);
loadAllUsersAsync(ess);
uuidMap = new UUIDMap(ess);
//RemovalListener<UUID, User> 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);
}
private void loadAllUsersAsync(final IEssentials ess)
@@ -35,37 +47,74 @@ public class UserMap extends CacheLoader<String, User> implements IConf
@Override
public void run()
{
final File userdir = new File(ess.getDataFolder(), "userdata");
if (!userdir.exists())
synchronized (users)
{
return;
}
keys.clear();
users.invalidateAll();
for (String string : userdir.list())
{
if (!string.endsWith(".yml"))
final File userdir = new File(ess.getDataFolder(), "userdata");
if (!userdir.exists())
{
continue;
return;
}
final String name = string.substring(0, string.length() - 4);
keys.add(StringUtil.sanitizeFileName(name));
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 boolean userExists(final String name)
public boolean userExists(final UUID uuid)
{
return keys.contains(StringUtil.sanitizeFileName(name));
return keys.contains(uuid);
}
public User getUser(final String name)
{
try
{
String sanitizedName = StringUtil.sanitizeFileName(name);
return users.get(sanitizedName);
final String sanitizedName = StringUtil.safeString(name);
if (names.containsKey(sanitizedName))
{
final UUID uuid = names.get(sanitizedName);
return getUser(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 UUID uuid)
{
try
{
return users.get(uuid.toString());
}
catch (ExecutionException ex)
{
@@ -77,43 +126,97 @@ public class UserMap extends CacheLoader<String, User> implements IConf
}
}
@Override
public User load(final String sanitizedName) throws Exception
public void trackUUID(final UUID uuid, final String name, boolean replace)
{
for (Player player : ess.getServer().getOnlinePlayers())
{
String sanitizedPlayer = StringUtil.sanitizeFileName(player.getName());
if (sanitizedPlayer.equalsIgnoreCase(sanitizedName))
if (uuid != null)
{
keys.add(uuid);
if (name != null && name.length() > 0)
{
keys.add(sanitizedName);
return new User(player, ess);
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 = getUserFile2(sanitizedName);
}
@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;
}
final File userFile = getUserFileFromID(uuid);
if (userFile.exists())
{
keys.add(sanitizedName);
return new User(new OfflinePlayer(sanitizedName, ess), ess);
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;
}
throw new Exception("User not found!");
}
@Override
public void reloadConfig()
{
getUUIDMap().forceWriteUUIDMap();
loadAllUsersAsync(ess);
}
public void invalidateAll()
{
users.invalidateAll();
}
public void removeUser(final String name)
{
keys.remove(StringUtil.sanitizeFileName(name));
users.invalidate(StringUtil.sanitizeFileName(name));
users.invalidate(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 Set<String> getAllUniqueUsers()
public Set<UUID> getAllUniqueUsers()
{
return Collections.unmodifiableSet(keys);
return Collections.unmodifiableSet(keys.clone());
}
public int getUniqueUsers()
@@ -121,14 +224,47 @@ public class UserMap extends CacheLoader<String, User> implements IConf
return keys.size();
}
public File getUserFile(final String name)
protected ConcurrentSkipListMap<String, UUID> getNames()
{
return getUserFile2(StringUtil.sanitizeFileName(name));
return names;
}
private File getUserFile2(final String name)
protected ConcurrentSkipListMap<UUID, ArrayList<String>> getHistory()
{
return history;
}
public List<String> getUserHistory(final UUID uuid)
{
return history.get(uuid);
}
public UUIDMap getUUIDMap()
{
return uuidMap;
}
private File getUserFileFromID(final UUID uuid)
{
final File userFolder = new File(ess.getDataFolder(), "userdata");
return new File(userFolder, name + ".yml");
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
// public void onRemoval(final RemovalNotification notification)
// {
// Object value = notification.getValue();
// if (value != null)
// {
// ((User)value).cleanup();
// }
// }
// }
}

View File

@@ -1,6 +1,6 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.commands.WarpNotFoundException;
import com.earth2me.essentials.utils.StringUtil;
import java.io.File;
@@ -71,7 +71,7 @@ public class Warps implements IConf, net.ess3.api.IWarps
File confFile = new File(warpsFolder, filename + ".yml");
if (confFile.exists())
{
throw new Exception(_("similarWarpExist"));
throw new Exception(tl("similarWarpExist"));
}
conf = new EssentialsConf(confFile);
warpPoints.put(new StringIgnoreCase(name), conf);
@@ -84,7 +84,7 @@ public class Warps implements IConf, net.ess3.api.IWarps
}
catch (IOException ex)
{
throw new IOException(_("invalidWarpName"));
throw new IOException(tl("invalidWarpName"));
}
}
@@ -94,11 +94,11 @@ public class Warps implements IConf, net.ess3.api.IWarps
EssentialsConf conf = warpPoints.get(new StringIgnoreCase(name));
if (conf == null)
{
throw new Exception(_("warpNotExist"));
throw new Exception(tl("warpNotExist"));
}
if (!conf.getFile().delete())
{
throw new Exception(_("warpDeleteError"));
throw new Exception(tl("warpDeleteError"));
}
warpPoints.remove(new StringIgnoreCase(name));
}
@@ -127,7 +127,7 @@ public class Warps implements IConf, net.ess3.api.IWarps
}
catch (Exception ex)
{
logger.log(Level.WARNING, _("loadWarpError", filename), ex);
logger.log(Level.WARNING, tl("loadWarpError", filename), ex);
}
}
}

View File

@@ -1,6 +1,6 @@
package com.earth2me.essentials;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.commands.NotEnoughArgumentsException;
import java.io.File;
import java.math.BigDecimal;
@@ -13,7 +13,6 @@ import org.bukkit.inventory.ItemStack;
public class Worth implements IConf
{
private static final Logger logger = Logger.getLogger("Essentials");
private final EssentialsConf config;
public Worth(File dataFolder)
@@ -85,7 +84,7 @@ public class Worth implements IConf
{
if (is == null || is.getType() == Material.AIR)
{
throw new Exception(_("itemSellAir"));
throw new Exception(tl("itemSellAir"));
}
int id = is.getTypeId();
int amount = 0;
@@ -111,11 +110,11 @@ public class Worth implements IConf
if (requireStack && !stack)
{
throw new Exception(_("itemMustBeStacked"));
throw new Exception(tl("itemMustBeStacked"));
}
int max = 0;
for (ItemStack s : user.getInventory().getContents())
for (ItemStack s : user.getBase().getInventory().getContents())
{
if (s == null || !s.isSimilar(is))
{
@@ -141,9 +140,9 @@ public class Worth implements IConf
{
if (!isBulkSell)
{
user.sendMessage(_("itemNotEnough2"));
user.sendMessage(_("itemNotEnough3"));
throw new Exception(_("itemNotEnough1"));
user.sendMessage(tl("itemNotEnough2"));
user.sendMessage(tl("itemNotEnough3"));
throw new Exception(tl("itemNotEnough1"));
}
else
{

View File

@@ -1,7 +1,9 @@
package com.earth2me.essentials.api;
import com.earth2me.essentials.EssentialsConf;
import static com.earth2me.essentials.I18n._;
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;
@@ -15,9 +17,11 @@ 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 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;
@@ -48,35 +52,25 @@ public class Economy
private static void createNPCFile(String name)
{
File folder = new File(ess.getDataFolder(), "userdata");
name = StringUtil.safeString(name);
if (!folder.exists())
{
folder.mkdirs();
}
EssentialsConf npcConfig = new EssentialsConf(new File(folder, StringUtil.sanitizeFileName(name) + ".yml"));
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 void deleteNPC(String name)
{
File folder = new File(ess.getDataFolder(), "userdata");
if (!folder.exists())
{
folder.mkdirs();
}
File config = new File(folder, StringUtil.sanitizeFileName(name) + ".yml");
EssentialsConf npcConfig = new EssentialsConf(config);
npcConfig.load();
if (npcConfig.hasProperty("npc") && npcConfig.getBoolean("npc", false))
{
if (!config.delete())
{
logger.log(Level.WARNING, _("deleteFileError", config));
}
ess.getUserMap().removeUser(name);
}
User user = ess.getUser(name);
user.reset();
}
private static User getUserByName(String name)
@@ -85,6 +79,10 @@ public class Economy
{
throw new RuntimeException(noCallBeforeLoad);
}
if (name == null)
{
throw new RuntimeException("Economy username cannot be null");
}
return ess.getUser(name);
}
@@ -155,6 +153,7 @@ public class Economy
{
//TODO: Update API to show max balance errors
}
Trade.log("API", "Set", "API", name, new Trade(balance, ess), null, null, null, ess);
}
/**
@@ -182,6 +181,7 @@ public class Economy
{
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);
}
/**
@@ -209,6 +209,7 @@ public class Economy
{
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);
}
/**
@@ -236,6 +237,7 @@ public class Economy
{
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);
}
/**
@@ -263,6 +265,7 @@ public class Economy
{
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);
}
/**
@@ -279,6 +282,7 @@ public class Economy
throw new RuntimeException(noCallBeforeLoad);
}
setMoney(name, ess.getSettings().getStartingBalance());
Trade.log("API", "Reset", "API", name, new Trade(BigDecimal.ZERO, ess), null, null, null, ess);
}
/**
@@ -458,4 +462,3 @@ public class Economy
deleteNPC(name);
}
}

View File

@@ -1,6 +1,6 @@
package com.earth2me.essentials.api;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
public class InvalidWorldException extends Exception
@@ -9,7 +9,7 @@ public class InvalidWorldException extends Exception
public InvalidWorldException(final String world)
{
super(_("invalidWorld"));
super(tl("invalidWorld"));
this.world = world;
}

View File

@@ -1,12 +1,12 @@
package com.earth2me.essentials.api;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
public class UserDoesNotExistException extends Exception
{
public UserDoesNotExistException(String name)
{
super(_("userDoesNotExist", name));
super(tl("userDoesNotExist", name));
}
}

View File

@@ -1,7 +1,7 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.User;
import org.bukkit.Server;
@@ -50,7 +50,7 @@ public class Commandafk extends EssentialsCommand
//user.sendMessage(_("markedAsNotAway"));
if (!user.isHidden())
{
msg = _("userIsNotAway", user.getDisplayName());
msg = tl("userIsNotAway", user.getDisplayName());
}
user.updateActivity(false);
}
@@ -59,7 +59,7 @@ public class Commandafk extends EssentialsCommand
//user.sendMessage(_("markedAsAway"));
if (!user.isHidden())
{
msg = _("userIsAway", user.getDisplayName());
msg = tl("userIsAway", user.getDisplayName());
}
}
if (!msg.isEmpty())

View File

@@ -1,6 +1,6 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.Trade;
import com.earth2me.essentials.User;
import org.bukkit.Server;
@@ -18,12 +18,12 @@ public class Commandback extends EssentialsCommand
{
if (user.getLastLocation() == null)
{
throw new Exception(_("noLocationFound"));
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(_("noPerm", "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);

View File

@@ -2,7 +2,7 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.Backup;
import com.earth2me.essentials.CommandSource;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import org.bukkit.Server;
@@ -19,14 +19,14 @@ public class Commandbackup extends EssentialsCommand
final Backup backup = ess.getBackup();
if (backup == null)
{
throw new Exception(_("backupDisabled"));
throw new Exception(tl("backupDisabled"));
}
final String command = ess.getSettings().getBackupCommand();
if (command == null || "".equals(command) || "save-all".equalsIgnoreCase(command))
{
throw new Exception(_("backupDisabled"));
throw new Exception(tl("backupDisabled"));
}
backup.run();
sender.sendMessage(_("backupStarted"));
sender.sendMessage(tl("backupStarted"));
}
}

View File

@@ -1,7 +1,7 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.NumberUtil;
import java.math.BigDecimal;
@@ -24,7 +24,7 @@ public class Commandbalance extends EssentialsCommand
}
User target = getPlayer(server, args, 0, true, true);
sender.sendMessage(_("balanceOther", target.isHidden() ? target.getName() : target.getDisplayName(), NumberUtil.displayCurrency(target.getMoney(), ess)));
sender.sendMessage(tl("balanceOther", target.isHidden() ? target.getName() : target.getDisplayName(), NumberUtil.displayCurrency(target.getMoney(), ess)));
}
@Override
@@ -34,12 +34,12 @@ public class Commandbalance extends EssentialsCommand
{
final User target = getPlayer(server, args, 0, true, true);
final BigDecimal bal = target.getMoney();
user.sendMessage(_("balanceOther", target.isHidden() ? target.getName() : target.getDisplayName(), NumberUtil.displayCurrency(bal, ess)));
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(_("balance", NumberUtil.displayCurrency(bal, ess)));
user.sendMessage(tl("balance", NumberUtil.displayCurrency(bal, ess)));
}
else
{

View File

@@ -1,7 +1,7 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.User;
import com.earth2me.essentials.textreader.SimpleTextInput;
import com.earth2me.essentials.textreader.TextPager;
@@ -12,7 +12,6 @@ import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.bukkit.Server;
import org.bukkit.entity.Player;
public class Commandbalancetop extends EssentialsCommand
@@ -54,37 +53,37 @@ public class Commandbalancetop extends EssentialsCommand
{
if (cacheage > System.currentTimeMillis() - CACHETIME)
{
outputCache(sender, page);
outputCache(sender, commandLabel, page);
return;
}
if (ess.getUserMap().getUniqueUsers() > MINUSERS)
{
sender.sendMessage(_("orderBalances", ess.getUserMap().getUniqueUsers()));
sender.sendMessage(tl("orderBalances", ess.getUserMap().getUniqueUsers()));
}
}
finally
{
lock.readLock().unlock();
}
ess.runTaskAsynchronously(new Viewer(sender, page, force));
ess.runTaskAsynchronously(new Viewer(sender, commandLabel, page, force));
}
else
{
if (ess.getUserMap().getUniqueUsers() > MINUSERS)
{
sender.sendMessage(_("orderBalances", ess.getUserMap().getUniqueUsers()));
sender.sendMessage(tl("orderBalances", ess.getUserMap().getUniqueUsers()));
}
ess.runTaskAsynchronously(new Viewer(sender, page, force));
ess.runTaskAsynchronously(new Viewer(sender, commandLabel, page, force));
}
}
private static void outputCache(final CommandSource sender, int page)
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(_("balanceTop", format.format(cal.getTime())));
sender.sendMessage(tl("balanceTop", format.format(cal.getTime())));
new TextPager(cache).showPage(Integer.toString(page), null, "balancetop", sender);
}
@@ -120,7 +119,7 @@ public class Commandbalancetop extends EssentialsCommand
}
else
{
for (String u : ess.getUserMap().getAllUniqueUsers())
for (UUID u : ess.getUserMap().getAllUniqueUsers())
{
final User user = ess.getUserMap().getUser(u);
if (user != null)
@@ -144,7 +143,7 @@ public class Commandbalancetop extends EssentialsCommand
}
});
cache.getLines().add(_("serverTotal", NumberUtil.displayCurrency(totalMoney, ess)));
cache.getLines().add(tl("serverTotal", NumberUtil.displayCurrency(totalMoney, ess)));
int pos = 1;
for (Map.Entry<String, BigDecimal> entry : sortedEntries)
{
@@ -168,12 +167,14 @@ public class Commandbalancetop extends EssentialsCommand
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 int page, final boolean force)
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
@@ -184,7 +185,7 @@ public class Commandbalancetop extends EssentialsCommand
{
if (!force && cacheage > System.currentTimeMillis() - CACHETIME)
{
outputCache(sender, page);
outputCache(sender, commandLabel, page);
return;
}
}
@@ -192,7 +193,7 @@ public class Commandbalancetop extends EssentialsCommand
{
lock.readLock().unlock();
}
ess.runTaskAsynchronously(new Calculator(new Viewer(sender, page, false), force));
ess.runTaskAsynchronously(new Calculator(new Viewer(sender, commandLabel, page, false), force));
}
}
}

View File

@@ -2,11 +2,13 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.Console;
import static com.earth2me.essentials.I18n._;
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;
@@ -33,20 +35,20 @@ public class Commandban extends EssentialsCommand
catch (PlayerNotFoundException e)
{
nomatch = true;
user = ess.getUser(new OfflinePlayer(args[0], ess));
user = ess.getUser(new OfflinePlayer(args[0], ess.getServer()));
}
if (!user.isOnline())
if (!user.getBase().isOnline())
{
if (sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.ban.offline"))
{
throw new Exception(_("banExemptOffline"));
throw new Exception(tl("banExemptOffline"));
}
}
else
{
if (user.isAuthorized("essentials.ban.exempt") && sender.isPlayer())
{
throw new Exception(_("banExempt"));
throw new Exception(tl("banExempt"));
}
}
@@ -58,21 +60,21 @@ public class Commandban extends EssentialsCommand
}
else
{
banReason = _("defaultBanReason");
banReason = tl("defaultBanReason");
}
ess.getServer().getBanList(BanList.Type.NAME).addBan(user.getName(), banReason, null, senderName);
user.setBanReason(_("banFormat", banReason, senderName));
user.setBanned(true);
user.setBanTimeout(0);
user.kickPlayer(_("banFormat", banReason, senderName));
server.getLogger().log(Level.INFO, _("playerBanned", senderName, user.getName(), banReason));
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(_("userUnknown", user.getName()));
sender.sendMessage(tl("userUnknown", user.getName()));
}
ess.broadcastMessage("essentials.ban.notify", _("playerBanned", senderName, user.getName(), banReason));
ess.broadcastMessage("essentials.ban.notify", tl("playerBanned", senderName, user.getName(), banReason));
}
}

View File

@@ -2,13 +2,16 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.Console;
import static com.earth2me.essentials.I18n._;
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;
//TODO: Add kick to online players matching ip ban.
public class Commandbanip extends EssentialsCommand
{
public Commandbanip()
@@ -49,9 +52,19 @@ public class Commandbanip extends EssentialsCommand
throw new PlayerNotFoundException();
}
ess.getServer().banIP(ipAddress);
server.getLogger().log(Level.INFO, _("playerBanIpAddress", senderName, ipAddress));
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", _("playerBanIpAddress", senderName, ipAddress));
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));
}
}

View File

@@ -1,6 +1,6 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.LocationUtil;
import org.bukkit.Location;
@@ -41,11 +41,11 @@ public class Commandbigtree extends EssentialsCommand
final boolean success = user.getWorld().generateTree(safeLocation, tree);
if (success)
{
user.sendMessage(_("bigTreeSuccess"));
user.sendMessage(tl("bigTreeSuccess"));
}
else
{
throw new Exception(_("bigTreeFailure"));
throw new Exception(tl("bigTreeFailure"));
}
}
}

View File

@@ -1,6 +1,6 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.User;
import org.bukkit.Material;
import org.bukkit.Server;
@@ -19,7 +19,7 @@ public class Commandbook extends EssentialsCommand
@Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception
{
final ItemStack item = user.getItemInHand();
final ItemStack item = user.getBase().getItemInHand();
final String player = user.getName();
if (item.getType() == Material.WRITTEN_BOOK)
{
@@ -31,11 +31,11 @@ public class Commandbook extends EssentialsCommand
{
bmeta.setAuthor(args[1]);
item.setItemMeta(bmeta);
user.sendMessage(_("bookAuthorSet", getFinalArg(args, 1)));
user.sendMessage(tl("bookAuthorSet", getFinalArg(args, 1)));
}
else
{
throw new Exception(_("denyChangeAuthor"));
throw new Exception(tl("denyChangeAuthor"));
}
}
else if (args.length > 1 && args[0].equalsIgnoreCase("title"))
@@ -44,11 +44,11 @@ public class Commandbook extends EssentialsCommand
{
bmeta.setTitle(args[1]);
item.setItemMeta(bmeta);
user.sendMessage(_("bookTitleSet", getFinalArg(args, 1)));
user.sendMessage(tl("bookTitleSet", getFinalArg(args, 1)));
}
else
{
throw new Exception(_("denyChangeTitle"));
throw new Exception(tl("denyChangeTitle"));
}
}
else
@@ -57,12 +57,12 @@ public class Commandbook extends EssentialsCommand
{
ItemStack newItem = new ItemStack(Material.BOOK_AND_QUILL, item.getAmount());
newItem.setItemMeta(bmeta);
user.setItemInHand(newItem);
user.sendMessage(_("editBookContents"));
user.getBase().setItemInHand(newItem);
user.sendMessage(tl("editBookContents"));
}
else
{
throw new Exception(_("denyBookEdit"));
throw new Exception(tl("denyBookEdit"));
}
}
}
@@ -75,12 +75,12 @@ public class Commandbook extends EssentialsCommand
}
ItemStack newItem = new ItemStack(Material.WRITTEN_BOOK, item.getAmount());
newItem.setItemMeta(bmeta);
user.setItemInHand(newItem);
user.sendMessage(_("bookLocked"));
user.getBase().setItemInHand(newItem);
user.sendMessage(tl("bookLocked"));
}
else
{
throw new Exception(_("holdBook"));
throw new Exception(tl("holdBook"));
}
}

View File

@@ -1,6 +1,6 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.User;
import org.bukkit.Material;
import org.bukkit.Server;
@@ -19,7 +19,7 @@ public class Commandbreak extends EssentialsCommand
@Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception
{
final Block block = user.getTargetBlock(null, 20);
final Block block = user.getBase().getTargetBlock(null, 20);
if (block == null)
{
throw new NoChargeException();
@@ -30,7 +30,7 @@ public class Commandbreak extends EssentialsCommand
}
if (block.getType() == Material.BEDROCK && !user.isAuthorized("essentials.break.bedrock"))
{
throw new Exception(_("noBreakBedrock"));
throw new Exception(tl("noBreakBedrock"));
}
//final List<ItemStack> list = (List<ItemStack>)block.getDrops();
//final BlockBreakEvent event = new BlockBreakEvent(block, user.getBase(), list);

View File

@@ -1,7 +1,7 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.FormatUtil;
import org.bukkit.Server;
@@ -33,6 +33,6 @@ public class Commandbroadcast extends EssentialsCommand
throw new NotEnoughArgumentsException();
}
ess.broadcastMessage(_("broadcast", FormatUtil.replaceFormat(getFinalArg(args, 0)).replace("\\n", "\n"), name));
ess.broadcastMessage(tl("broadcast", FormatUtil.replaceFormat(getFinalArg(args, 0)).replace("\\n", "\n"), name));
}
}

View File

@@ -1,7 +1,7 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.User;
import org.bukkit.Server;
@@ -27,7 +27,7 @@ public class Commandburn extends EssentialsCommand
}
User user = getPlayer(server, sender, args, 0);
user.setFireTicks(Integer.parseInt(args[1]) * 20);
sender.sendMessage(_("burnMsg", user.getDisplayName(), Integer.parseInt(args[1])));
user.getBase().setFireTicks(Integer.parseInt(args[1]) * 20);
sender.sendMessage(tl("burnMsg", user.getDisplayName(), Integer.parseInt(args[1])));
}
}

View File

@@ -1,12 +1,11 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import static com.earth2me.essentials.I18n._;
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.Arrays;
import java.util.List;
import java.util.Collection;
import java.util.Locale;
import org.bukkit.Server;
import org.bukkit.entity.Player;
@@ -25,7 +24,7 @@ public class Commandclearinventory extends EssentialsCommand
@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"));
parseCommand(server, user.getSource(), args, user.isAuthorized("essentials.clearinventory.others"), user.isAuthorized("essentials.clearinventory.all") || user.isAuthorized("essentials.clearinventory.multiple"));
}
@Override
@@ -36,7 +35,7 @@ public class Commandclearinventory extends EssentialsCommand
private void parseCommand(Server server, CommandSource sender, String[] args, boolean allowOthers, boolean allowAll) throws Exception
{
List<Player> players = new ArrayList<Player>();
Collection<Player> players = new ArrayList<Player>();
int offset = 0;
if (sender.isPlayer())
@@ -46,9 +45,9 @@ public class Commandclearinventory extends EssentialsCommand
if (allowAll && args.length > 0 && args[0].contentEquals("*"))
{
sender.sendMessage(_("inventoryClearingFromAll"));
sender.sendMessage(tl("inventoryClearingFromAll"));
offset = 1;
players = Arrays.asList(server.getOnlinePlayers());
players = ess.getOnlinePlayers();
}
else if (allowOthers && args.length > 0 && args[0].trim().length() > 2)
{
@@ -103,7 +102,7 @@ public class Commandclearinventory extends EssentialsCommand
{
if (showExtended)
{
sender.sendMessage(_("inventoryClearingAllItems", player.getDisplayName()));
sender.sendMessage(tl("inventoryClearingAllItems", player.getDisplayName()));
}
player.getInventory().clear();
}
@@ -111,7 +110,7 @@ public class Commandclearinventory extends EssentialsCommand
{
if (showExtended)
{
sender.sendMessage(_("inventoryClearingAllArmor", player.getDisplayName()));
sender.sendMessage(tl("inventoryClearingAllArmor", player.getDisplayName()));
}
player.getInventory().clear();
player.getInventory().setArmorContents(null);
@@ -123,7 +122,7 @@ public class Commandclearinventory extends EssentialsCommand
ItemStack stack = new ItemStack(type);
if (showExtended)
{
sender.sendMessage(_("inventoryClearingAllStack", stack.getType().toString().toLowerCase(Locale.ENGLISH), player.getDisplayName()));
sender.sendMessage(tl("inventoryClearingAllStack", stack.getType().toString().toLowerCase(Locale.ENGLISH), player.getDisplayName()));
}
player.getInventory().clear(type, data);
}
@@ -134,7 +133,7 @@ public class Commandclearinventory extends EssentialsCommand
final int removedAmount = (BASE_AMOUNT - removedStack.getAmount());
if (removedAmount > 0 || showExtended)
{
sender.sendMessage(_("inventoryClearingStack", removedAmount, stack.getType().toString().toLowerCase(Locale.ENGLISH), player.getDisplayName()));
sender.sendMessage(tl("inventoryClearingStack", removedAmount, stack.getType().toString().toLowerCase(Locale.ENGLISH), player.getDisplayName()));
}
}
else
@@ -146,14 +145,14 @@ public class Commandclearinventory extends EssentialsCommand
ItemStack stack = new ItemStack(type, amount, data);
if (player.getInventory().containsAtLeast(stack, amount))
{
sender.sendMessage(_("inventoryClearingStack", amount, stack.getType().toString().toLowerCase(Locale.ENGLISH), player.getDisplayName()));
sender.sendMessage(tl("inventoryClearingStack", amount, stack.getType().toString().toLowerCase(Locale.ENGLISH), player.getDisplayName()));
player.getInventory().removeItem(stack);
}
else
{
if (showExtended)
{
sender.sendMessage(_("inventoryClearFail", player.getDisplayName(), amount, stack.getType().toString().toLowerCase(Locale.ENGLISH)));
sender.sendMessage(tl("inventoryClearFail", player.getDisplayName(), amount, stack.getType().toString().toLowerCase(Locale.ENGLISH)));
}
}
}

View File

@@ -1,6 +1,6 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.User;
import org.bukkit.Server;
@@ -53,6 +53,6 @@ public class Commandcompass extends EssentialsCommand
{
dir = "N";
}
user.sendMessage(_("compassBearing", dir, bearing));
user.sendMessage(tl("compassBearing", dir, bearing));
}
}

View File

@@ -0,0 +1,221 @@
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;
public class Commandcondense extends EssentialsCommand
{
public Commandcondense()
{
super("condense");
}
private Map<ItemStack, SimpleRecipe> condenseList = new HashMap<ItemStack, SimpleRecipe>();
@Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception
{
List<ItemStack> is = new ArrayList<ItemStack>();
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;
}
boolean didConvert = false;
for (final ItemStack itemStack : is)
{
if (condenseStack(user, itemStack, validateReverse))
{
didConvert = true;
}
}
user.getBase().updateInventory();
if (didConvert)
{
user.sendMessage(tl("itemsConverted"));
}
else
{
user.sendMessage(tl("itemsNotConverted"));
throw new NoChargeException();
}
}
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 (validateReverse)
{
boolean pass = false;
for (Recipe revRecipe : ess.getServer().getRecipesFor(input))
{
if (getStackOnRecipeMatch(revRecipe, result) != null)
{
pass = true;
break;
}
}
if (!pass)
{
return false;
}
}
int amount = 0;
for (final ItemStack contents : user.getBase().getInventory().getContents())
{
if (contents != null && contents.isSimilar(stack))
{
amount += contents.getAmount();
}
}
int output = ((amount / input.getAmount()) * result.getAmount());
amount -= amount % input.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;
}
private SimpleRecipe getCondenseType(final ItemStack stack)
{
if (condenseList.containsKey(stack))
{
return condenseList.get(stack);
}
final Iterator<Recipe> intr = ess.getServer().recipeIterator();
while (intr.hasNext())
{
final Recipe recipe = intr.next();
final Collection<ItemStack> recipeItems = getStackOnRecipeMatch(recipe, 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;
}
}
condenseList.put(stack, null);
return null;
}
private Collection<ItemStack> getStackOnRecipeMatch(final Recipe recipe, final ItemStack stack)
{
final Collection<ItemStack> inputList;
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;
}
boolean match = true;
Iterator<ItemStack> iter = inputList.iterator();
while (iter.hasNext())
{
ItemStack inputSlot = iter.next();
if (inputSlot == null)
{
iter.remove();
continue;
}
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 SimpleRecipe(ItemStack result, ItemStack input)
{
this.result = result;
this.input = input;
}
@Override
public ItemStack getResult()
{
return result.clone();
}
public ItemStack getInput()
{
return input.clone();
}
}
}

View File

@@ -18,8 +18,13 @@ public class Commandcustomtext extends EssentialsCommand
@Override
protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception
{
final IText input = new TextInput(sender, "custom", true, ess);
{
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;

View File

@@ -1,7 +1,7 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.User;
import java.util.Locale;
import org.bukkit.Server;
@@ -53,10 +53,10 @@ public class Commanddelhome extends EssentialsCommand
if (name.equalsIgnoreCase("bed"))
{
throw new Exception(_("invalidHomeName"));
throw new Exception(tl("invalidHomeName"));
}
user.delHome(name.toLowerCase(Locale.ENGLISH));
sender.sendMessage(_("deleteHome", name));
sender.sendMessage(tl("deleteHome", name));
}
}

View File

@@ -1,7 +1,7 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import org.bukkit.Server;
@@ -21,6 +21,6 @@ public class Commanddeljail extends EssentialsCommand
}
ess.getJails().removeJail(args[0]);
sender.sendMessage(_("deleteJail", args[0]));
sender.sendMessage(tl("deleteJail", args[0]));
}
}

View File

@@ -1,7 +1,7 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import org.bukkit.Server;
@@ -21,6 +21,6 @@ public class Commanddelwarp extends EssentialsCommand
}
ess.getWarps().removeWarp(args[0]);
sender.sendMessage(_("deleteWarp", args[0]));
sender.sendMessage(tl("deleteWarp", args[0]));
}
}

View File

@@ -1,6 +1,6 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.User;
import org.bukkit.Server;
@@ -18,15 +18,15 @@ public class Commanddepth extends EssentialsCommand
final int depth = user.getLocation().getBlockY() - 63;
if (depth > 0)
{
user.sendMessage(_("depthAboveSea", depth));
user.sendMessage(tl("depthAboveSea", depth));
}
else if (depth < 0)
{
user.sendMessage(_("depthBelowSea", (-depth)));
user.sendMessage(tl("depthBelowSea", (-depth)));
}
else
{
user.sendMessage(_("depth"));
user.sendMessage(tl("depth"));
}
}
}

View File

@@ -2,13 +2,11 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.ChargeException;
import com.earth2me.essentials.CommandSource;
import static com.earth2me.essentials.I18n._;
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 java.util.logging.Level;
import java.util.logging.Logger;
import net.ess3.api.MaxMoneyException;
import org.bukkit.Server;
@@ -49,11 +47,11 @@ public class Commandeco extends EssentialsLoopCommand
{
if (args[1].contentEquals("**"))
{
server.broadcastMessage(_("resetBalAll", NumberUtil.displayCurrency(amount, ess)));
server.broadcastMessage(tl("resetBalAll", NumberUtil.displayCurrency(amount, ess)));
}
else if (args[1].contentEquals("*"))
{
server.broadcastMessage(_("resetBal", NumberUtil.displayCurrency(amount, ess)));
server.broadcastMessage(tl("resetBal", NumberUtil.displayCurrency(amount, ess)));
}
}
}
@@ -96,23 +94,25 @@ public class Commandeco extends EssentialsLoopCommand
{
// Take shouldn't be able to throw a max money exception
}
player.sendMessage(_("takenFromAccount", NumberUtil.displayCurrency(player.getMoney(), ess)));
player.sendMessage(tl("takenFromAccount", NumberUtil.displayCurrency(player.getMoney(), ess)));
}
else
{
throw new ChargeException(_("insufficientFunds"));
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);
player.setMoney(underMinimum ? minBalance : amount);
player.sendMessage(_("setBal", NumberUtil.displayCurrency(player.getMoney(), ess)));
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(_("setBalOthers", player.getDisplayName(), NumberUtil.displayCurrency(player.getMoney(), ess)));
sender.sendMessage(tl("setBalOthers", player.getDisplayName(), NumberUtil.displayCurrency(player.getMoney(), ess)));
}
}

View File

@@ -1,7 +1,7 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.Enchantments;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.MetaItemStack;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.StringUtil;
@@ -26,10 +26,10 @@ public class Commandenchant extends EssentialsCommand
@Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception
{
final ItemStack stack = user.getItemInHand();
final ItemStack stack = user.getBase().getItemInHand();
if (stack == null || stack.getType() == Material.AIR)
{
throw new Exception(_("nothingInHand"));
throw new Exception(tl("nothingInHand"));
}
if (args.length == 0)
{
@@ -43,7 +43,7 @@ public class Commandenchant extends EssentialsCommand
//enchantmentslist.add(enchantmentName);
}
}
throw new NotEnoughArgumentsException(_("enchantments", StringUtil.joinList(enchantmentslist.toArray())));
throw new NotEnoughArgumentsException(tl("enchantments", StringUtil.joinList(enchantmentslist.toArray())));
}
int level = -1;
@@ -64,17 +64,17 @@ public class Commandenchant extends EssentialsCommand
final MetaItemStack metaStack = new MetaItemStack(stack);
final Enchantment enchantment = metaStack.getEnchantment(user, args[0]);
metaStack.addEnchantment(user.getSource(), allowUnsafe, enchantment, level);
user.getInventory().setItemInHand(metaStack.getItemStack());
user.getBase().getInventory().setItemInHand(metaStack.getItemStack());
user.updateInventory();
user.getBase().updateInventory();
final String enchantmentName = enchantment.getName().toLowerCase(Locale.ENGLISH);
if (level == 0)
{
user.sendMessage(_("enchantmentRemoved", enchantmentName.replace('_', ' ')));
user.sendMessage(tl("enchantmentRemoved", enchantmentName.replace('_', ' ')));
}
else
{
user.sendMessage(_("enchantmentApplied", enchantmentName.replace('_', ' ')));
user.sendMessage(tl("enchantmentApplied", enchantmentName.replace('_', ' ')));
}
}
}

View File

@@ -17,14 +17,14 @@ public class Commandenderchest extends EssentialsCommand
if (args.length > 0 && user.isAuthorized("essentials.enderchest.others"))
{
final User invUser = getPlayer(server, user, args, 0);
user.closeInventory();
user.openInventory(invUser.getEnderChest());
user.getBase().closeInventory();
user.getBase().openInventory(invUser.getBase().getEnderChest());
user.setEnderSee(true);
}
else
{
user.closeInventory();
user.openInventory(user.getEnderChest());
user.getBase().closeInventory();
user.getBase().openInventory(user.getBase().getEnderChest());
user.setEnderSee(false);
}

View File

@@ -1,15 +1,19 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import static com.earth2me.essentials.I18n._;
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;
@@ -57,6 +61,14 @@ public class Commandessentials extends EssentialsCommand
{
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);
@@ -79,7 +91,7 @@ public class Commandessentials extends EssentialsCommand
}
if (disabledCommands.length() > 0)
{
sender.sendMessage(_("blockList"));
sender.sendMessage(tl("blockList"));
sender.sendMessage(disabledCommands.toString());
}
}
@@ -104,7 +116,7 @@ public class Commandessentials extends EssentialsCommand
private void run_reload(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception
{
ess.reload();
sender.sendMessage(_("essentialsReload", ess.getDescription().getVersion()));
sender.sendMessage(tl("essentialsReload", ess.getDescription().getVersion()));
}
private void run_nya(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception
@@ -153,7 +165,7 @@ public class Commandessentials extends EssentialsCommand
{
return;
}
for (Player onlinePlayer : server.getOnlinePlayers())
for (Player onlinePlayer : ess.getOnlinePlayers())
{
onlinePlayer.playSound(onlinePlayer.getLocation(), Sound.NOTE_PIANO, 1, noteMap.get(note));
}
@@ -202,7 +214,7 @@ public class Commandessentials extends EssentialsCommand
{
logger.info(s);
}
for (Player player : ess.getServer().getOnlinePlayers())
for (Player player : ess.getOnlinePlayers())
{
player.sendMessage(playerMoo);
player.playSound(player.getLocation(), Sound.COW_IDLE, 1, 1.0f);
@@ -252,15 +264,14 @@ public class Commandessentials extends EssentialsCommand
{
sender.sendMessage("This sub-command will delete users who havent logged in in the last <days> 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/bans.");
throw new Exception("/<command> cleanup <days> [money] [homes] [ban count]");
sender.sendMessage("Unless you define larger default values, this command wil ignore people who have more than 0 money/homes.");
throw new Exception("/<command> cleanup <days> [money] [homes]");
}
sender.sendMessage(_("cleaning"));
sender.sendMessage(tl("cleaning"));
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 int bansArg = args.length >= 5 && NumberUtil.isInt(args[4]) ? Integer.parseInt(args[4]) : 0;
final UserMap userMap = ess.getUserMap();
ess.runTaskAsynchronously(new Runnable()
@@ -269,7 +280,7 @@ public class Commandessentials extends EssentialsCommand
public void run()
{
Long currTime = System.currentTimeMillis();
for (String u : userMap.getAllUniqueUsers())
for (UUID u : userMap.getAllUniqueUsers())
{
final User user = ess.getUserMap().getUser(u);
if (user == null)
@@ -277,8 +288,6 @@ public class Commandessentials extends EssentialsCommand
continue;
}
int ban = user.getBanReason().isEmpty() ? 0 : 1;
long lastLog = user.getLastLogout();
if (lastLog == 0)
{
@@ -289,12 +298,17 @@ public class Commandessentials extends EssentialsCommand
user.setLastLogin(currTime);
}
if (user.isNPC())
{
continue;
}
long timeDiff = currTime - lastLog;
long milliDays = daysArg * 24L * 60L * 60L * 1000L;
int homeCount = user.getHomes().size();
double moneyCount = user.getMoney().doubleValue();
if ((lastLog == 0) || (ban > bansArg) || (timeDiff < milliDays)
if ((lastLog == 0) || (timeDiff < milliDays)
|| (homeCount > homesArg) || (moneyCount > moneyArg))
{
continue;
@@ -307,9 +321,62 @@ public class Commandessentials extends EssentialsCommand
user.reset();
}
sender.sendMessage(_("cleaned"));
sender.sendMessage(tl("cleaned"));
}
});
}
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.");
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_uuidtest(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception
{
if (args.length < 2)
{
throw new Exception("/<command> uuidtest <name>");
}
String name = args[1];
sender.sendMessage("Looking up UUID for " + name);
UUID onlineUUID = null;
for (Player player : ess.getOnlinePlayers())
{
if (player.getName().equalsIgnoreCase(name))
{
onlineUUID = player.getUniqueId();
break;
}
}
UUID essUUID = ess.getUserMap().getUser(name).getConfigUUID();
org.bukkit.OfflinePlayer player = ess.getServer().getOfflinePlayer(name);
UUID bukkituuid = player.getUniqueId();
sender.sendMessage("Bukkit Lookup: " + bukkituuid.toString());
if (onlineUUID != null && onlineUUID != bukkituuid)
{
sender.sendMessage("Online player: " + onlineUUID.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());
}
}

View File

@@ -1,7 +1,7 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.User;
import com.earth2me.essentials.craftbukkit.SetExpFix;
import com.earth2me.essentials.utils.NumberUtil;
@@ -117,13 +117,13 @@ public class Commandexp extends EssentialsCommand
private void showMatch(final Server server, final CommandSource sender, final String match) throws PlayerNotFoundException
{
boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.vanish.interact");
boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished();
boolean foundUser = false;
final List<Player> matchedPlayers = server.matchPlayer(match);
for (Player matchPlayer : matchedPlayers)
{
final User player = ess.getUser(matchPlayer);
if (skipHidden && player.isHidden())
if (skipHidden && player.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(matchPlayer))
{
continue;
}
@@ -138,13 +138,13 @@ public class Commandexp extends EssentialsCommand
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()).isAuthorized("essentials.vanish.interact");
boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished();
boolean foundUser = false;
final List<Player> matchedPlayers = server.matchPlayer(match);
for (Player matchPlayer : matchedPlayers)
{
final User player = ess.getUser(matchPlayer);
if (skipHidden && player.isHidden())
if (skipHidden && player.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(matchPlayer))
{
continue;
}
@@ -159,7 +159,7 @@ public class Commandexp extends EssentialsCommand
private void showExp(final CommandSource sender, final User target)
{
sender.sendMessage(_("exp", target.getDisplayName(), SetExpFix.getTotalExperience(target.getBase()), target.getLevel(), SetExpFix.getExpUntilNextLevel(target.getBase())));
sender.sendMessage(tl("exp", target.getDisplayName(), SetExpFix.getTotalExperience(target.getBase()), target.getBase().getLevel(), SetExpFix.getExpUntilNextLevel(target.getBase())));
}
//TODO: Limit who can give negative exp?
@@ -173,7 +173,7 @@ public class Commandexp extends EssentialsCommand
int neededLevel = Integer.parseInt(strAmount);
if (give)
{
neededLevel += target.getLevel();
neededLevel += target.getBase().getLevel();
}
amount = (long)SetExpFix.getExpToLevel(neededLevel);
SetExpFix.setTotalExperience(target.getBase(), 0);
@@ -200,6 +200,6 @@ public class Commandexp extends EssentialsCommand
amount = 0l;
}
SetExpFix.setTotalExperience(target.getBase(), (int)amount);
sender.sendMessage(_("expSet", target.getDisplayName(), amount));
sender.sendMessage(tl("expSet", target.getDisplayName(), amount));
}
}

View File

@@ -1,7 +1,7 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.User;
import org.bukkit.Server;
import org.bukkit.entity.Player;
@@ -31,7 +31,7 @@ public class Commandext extends EssentialsLoopCommand
if (args.length < 1)
{
extPlayer(user.getBase());
user.sendMessage(_("extinguish"));
user.sendMessage(tl("extinguish"));
return;
}
@@ -42,7 +42,7 @@ public class Commandext extends EssentialsLoopCommand
protected void updatePlayer(final Server server, final CommandSource sender, final User player, final String[] args)
{
extPlayer(player.getBase());
sender.sendMessage(_("extinguishOthers", player.getDisplayName()));
sender.sendMessage(tl("extinguishOthers", player.getDisplayName()));
}
private void extPlayer(final Player player)

View File

@@ -1,7 +1,7 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.User;
import org.bukkit.Server;
import org.bukkit.entity.Player;
@@ -30,7 +30,7 @@ public class Commandfeed extends EssentialsLoopCommand
}
feedPlayer(user.getBase());
user.sendMessage(_("feed"));
user.sendMessage(tl("feed"));
}
@Override
@@ -50,7 +50,7 @@ public class Commandfeed extends EssentialsLoopCommand
try
{
feedPlayer(player.getBase());
sender.sendMessage(_("feedOther", player.getDisplayName()));
sender.sendMessage(tl("feedOther", player.getDisplayName()));
}
catch (QuietAbortException e)
{

View File

@@ -50,8 +50,8 @@ public class Commandfireball extends EssentialsCommand
type = LargeFireball.class;
}
}
final Vector direction = user.getEyeLocation().getDirection().multiply(speed);
projectile = (Projectile)user.getWorld().spawn(user.getEyeLocation().add(direction.getX(), direction.getY(), direction.getZ()), type);
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);
}

View File

@@ -1,6 +1,6 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.MetaItemStack;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.NumberUtil;
@@ -32,7 +32,6 @@ import org.bukkit.util.Vector;
public class Commandfirework extends EssentialsCommand
{
private final transient Pattern splitPattern = Pattern.compile("[:+',;.]");
public Commandfirework()
{
@@ -42,7 +41,7 @@ public class Commandfirework extends EssentialsCommand
@Override
protected void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception
{
final ItemStack stack = user.getItemInHand();
final ItemStack stack = user.getBase().getItemInHand();
if (stack.getType() == Material.FIREWORK)
{
if (args.length > 0)
@@ -52,7 +51,7 @@ public class Commandfirework extends EssentialsCommand
FireworkMeta fmeta = (FireworkMeta)stack.getItemMeta();
fmeta.clearEffects();
stack.setItemMeta(fmeta);
user.sendMessage(_("fireworkEffectsCleared"));
user.sendMessage(tl("fireworkEffectsCleared"));
}
else if (args.length > 1 && (args[0].equalsIgnoreCase("power") || (args[0].equalsIgnoreCase("p"))))
{
@@ -64,7 +63,7 @@ public class Commandfirework extends EssentialsCommand
}
catch (NumberFormatException e)
{
throw new Exception(_("invalidFireworkFormat", args[1], args[0]));
throw new Exception(tl("invalidFireworkFormat", args[1], args[0]));
}
stack.setItemMeta(fmeta);
}
@@ -82,7 +81,7 @@ public class Commandfirework extends EssentialsCommand
if (amount > serverLimit)
{
amount = serverLimit;
user.sendMessage(_("mobSpawnLimit"));
user.sendMessage(tl("mobSpawnLimit"));
}
}
else
@@ -96,7 +95,7 @@ public class Commandfirework extends EssentialsCommand
FireworkMeta fmeta = (FireworkMeta)stack.getItemMeta();
if (direction)
{
final Vector vector = user.getEyeLocation().getDirection().multiply(0.070);
final Vector vector = user.getBase().getEyeLocation().getDirection().multiply(0.070);
if (fmeta.getPower() > 1)
{
fmeta.setPower(1);
@@ -117,7 +116,7 @@ public class Commandfirework extends EssentialsCommand
}
catch (Exception e)
{
user.sendMessage(_("fireworkSyntax"));
user.sendMessage(tl("fireworkSyntax"));
throw e;
}
}
@@ -128,15 +127,15 @@ public class Commandfirework extends EssentialsCommand
FireworkEffect effect = mStack.getFireworkBuilder().build();
if (fmeta.getEffects().size() > 0 && !user.isAuthorized("essentials.firework.multiple"))
{
throw new Exception(_("multipleCharges"));
throw new Exception(tl("multipleCharges"));
}
fmeta.addEffect(effect);
stack.setItemMeta(fmeta);
}
else
{
user.sendMessage(_("fireworkSyntax"));
throw new Exception(_("fireworkColor"));
user.sendMessage(tl("fireworkSyntax"));
throw new Exception(tl("fireworkColor"));
}
}
}
@@ -147,7 +146,7 @@ public class Commandfirework extends EssentialsCommand
}
else
{
throw new Exception(_("holdFirework"));
throw new Exception(tl("holdFirework"));
}
}
}

View File

@@ -1,7 +1,7 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.User;
import org.bukkit.Server;
@@ -49,21 +49,21 @@ public class Commandfly extends EssentialsToggleCommand
{
if (enabled == null)
{
enabled = !user.getAllowFlight();
enabled = !user.getBase().getAllowFlight();
}
user.setFallDistance(0f);
user.setAllowFlight(enabled);
user.getBase().setFallDistance(0f);
user.getBase().setAllowFlight(enabled);
if (!user.getAllowFlight())
if (!user.getBase().getAllowFlight())
{
user.setFlying(false);
user.getBase().setFlying(false);
}
user.sendMessage(_("flyMode", _(enabled ? "enabled" : "disabled"), user.getDisplayName()));
user.sendMessage(tl("flyMode", tl(enabled ? "enabled" : "disabled"), user.getDisplayName()));
if (!sender.isPlayer() || !sender.getPlayer().equals(user.getBase()))
{
sender.sendMessage(_("flyMode", _(enabled ? "enabled" : "disabled"), user.getDisplayName()));
sender.sendMessage(tl("flyMode", tl(enabled ? "enabled" : "disabled"), user.getDisplayName()));
}
}
}

View File

@@ -1,7 +1,7 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.User;
import java.util.List;
import java.util.Locale;
@@ -71,32 +71,32 @@ public class Commandgamemode extends EssentialsCommand
}
if (gameMode == null)
{
gameMode = user.getGameMode() == GameMode.SURVIVAL ? GameMode.CREATIVE : user.getGameMode() == GameMode.CREATIVE ? GameMode.ADVENTURE : GameMode.SURVIVAL;
gameMode = user.getBase().getGameMode() == GameMode.SURVIVAL ? GameMode.CREATIVE : user.getBase().getGameMode() == GameMode.CREATIVE ? GameMode.ADVENTURE : GameMode.SURVIVAL;
}
user.setGameMode(gameMode);
user.sendMessage(_("gameMode", _(user.getGameMode().toString().toLowerCase(Locale.ENGLISH)), user.getDisplayName()));
user.getBase().setGameMode(gameMode);
user.sendMessage(tl("gameMode", tl(user.getBase().getGameMode().toString().toLowerCase(Locale.ENGLISH)), user.getDisplayName()));
}
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(_("gameModeInvalid"));
throw new NotEnoughArgumentsException(tl("gameModeInvalid"));
}
boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.vanish.interact");
boolean skipHidden = sender.isPlayer() && !ess.getUser(sender.getPlayer()).canInteractVanished();
boolean foundUser = false;
final List<Player> matchedPlayers = server.matchPlayer(name);
for (Player matchPlayer : matchedPlayers)
{
final User player = ess.getUser(matchPlayer);
if (skipHidden && player.isHidden())
if (skipHidden && player.isHidden(sender.getPlayer()) && !sender.getPlayer().canSee(matchPlayer))
{
continue;
}
foundUser = true;
player.setGameMode(gameMode);
sender.sendMessage(_("gameMode", _(player.getGameMode().toString().toLowerCase(Locale.ENGLISH)), player.getDisplayName()));
player.getBase().setGameMode(gameMode);
sender.sendMessage(tl("gameMode", tl(player.getBase().getGameMode().toString().toLowerCase(Locale.ENGLISH)), player.getDisplayName()));
}
if (!foundUser)
{

View File

@@ -1,11 +1,13 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.utils.DateUtil;
import com.earth2me.essentials.utils.NumberUtil;
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;
@@ -37,11 +39,11 @@ public class Commandgc extends EssentialsCommand
color = ChatColor.RED;
}
sender.sendMessage(_("uptime", DateUtil.formatDateDiff(ManagementFactory.getRuntimeMXBean().getStartTime())));
sender.sendMessage(_("tps", "" + color + NumberUtil.formatDouble(tps)));
sender.sendMessage(_("gcmax", (Runtime.getRuntime().maxMemory() / 1024 / 1024)));
sender.sendMessage(_("gctotal", (Runtime.getRuntime().totalMemory() / 1024 / 1024)));
sender.sendMessage(_("gcfree", (Runtime.getRuntime().freeMemory() / 1024 / 1024)));
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<World> worlds = server.getWorlds();
for (World w : worlds)
@@ -56,14 +58,22 @@ public class Commandgc extends EssentialsCommand
worldType = "The End";
break;
}
int tileEntities = 0;
for (Chunk chunk : w.getLoadedChunks()) {
tileEntities += chunk.getTileEntities().length;
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(_("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));
}
}
}

View File

@@ -1,7 +1,7 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.User;
import org.bukkit.Location;
import org.bukkit.Server;
@@ -39,15 +39,15 @@ public class Commandgetpos extends EssentialsCommand
private void outputPosition(final CommandSource sender, final Location coords, final Location distance)
{
sender.sendMessage(_("currentWorld", coords.getWorld().getName()));
sender.sendMessage(_("posX", coords.getBlockX()));
sender.sendMessage(_("posY", coords.getBlockY()));
sender.sendMessage(_("posZ", coords.getBlockZ()));
sender.sendMessage(_("posYaw", (coords.getYaw() + 180 + 360) % 360));
sender.sendMessage(_("posPitch", coords.getPitch()));
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(_("distance", coords.distance(distance)));
sender.sendMessage(tl("distance", coords.distance(distance)));
}
}
}

View File

@@ -1,7 +1,7 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.MetaItemStack;
import com.earth2me.essentials.User;
import com.earth2me.essentials.craftbukkit.InventoryWorkaround;
@@ -39,7 +39,7 @@ public class Commandgive extends EssentialsCommand
: (!ess.getUser(sender.getPlayer()).isAuthorized("essentials.itemspawn.exempt")
&& !ess.getUser(sender.getPlayer()).canSpawnItem(stack.getTypeId()))))
{
throw new Exception(_("cantSpawnItem", itemname));
throw new Exception(tl("cantSpawnItem", itemname));
}
final User giveTo = getPlayer(server, sender, args, 0);
@@ -69,9 +69,14 @@ public class Commandgive extends EssentialsCommand
throw new NotEnoughArgumentsException();
}
MetaItemStack metaStack = new MetaItemStack(stack);
if (!metaStack.canSpawn(ess))
{
throw new Exception(tl("unableToSpawnItem", itemname));
}
if (args.length > 3)
{
MetaItemStack metaStack = new MetaItemStack(stack);
boolean allowUnsafe = ess.getSettings().allowUnsafeEnchantments();
if (allowUnsafe && sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.enchantments.allowunsafe"))
{
@@ -90,28 +95,28 @@ public class Commandgive extends EssentialsCommand
if (stack.getType() == Material.AIR)
{
throw new Exception(_("cantSpawnItem", "Air"));
throw new Exception(tl("cantSpawnItem", "Air"));
}
final String itemName = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace('_', ' ');
sender.sendMessage(_("giveSpawn", stack.getAmount(), itemName, giveTo.getDisplayName()));
sender.sendMessage(tl("giveSpawn", stack.getAmount(), itemName, giveTo.getDisplayName()));
Map<Integer, ItemStack> leftovers;
if (giveTo.isAuthorized("essentials.oversizedstacks"))
{
leftovers = InventoryWorkaround.addOversizedItems(giveTo.getInventory(), ess.getSettings().getOversizedStackSize(), stack);
leftovers = InventoryWorkaround.addOversizedItems(giveTo.getBase().getInventory(), ess.getSettings().getOversizedStackSize(), stack);
}
else
{
leftovers = InventoryWorkaround.addItems(giveTo.getInventory(), stack);
leftovers = InventoryWorkaround.addItems(giveTo.getBase().getInventory(), stack);
}
for (ItemStack item : leftovers.values())
{
sender.sendMessage(_("giveSpawnFailure", item.getAmount(), itemName, giveTo.getDisplayName()));
sender.sendMessage(tl("giveSpawnFailure", item.getAmount(), itemName, giveTo.getDisplayName()));
}
giveTo.updateInventory();
giveTo.getBase().updateInventory();
}
}

View File

@@ -1,7 +1,7 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.User;
import net.ess3.api.events.GodStatusChangeEvent;
import org.bukkit.Server;
@@ -60,16 +60,16 @@ public class Commandgod extends EssentialsToggleCommand
{
user.setGodModeEnabled(enabled);
if (enabled && user.getHealth() != 0)
if (enabled && user.getBase().getHealth() != 0)
{
user.setHealth(user.getMaxHealth());
user.setFoodLevel(20);
user.getBase().setHealth(user.getBase().getMaxHealth());
user.getBase().setFoodLevel(20);
}
user.sendMessage(_("godMode", enabled ? _("enabled") : _("disabled")));
user.sendMessage(tl("godMode", enabled ? tl("enabled") : tl("disabled")));
if (!sender.isPlayer() || !sender.getPlayer().equals(user.getBase()))
{
sender.sendMessage(_("godMode", _(enabled ? "godEnabledFor" : "godDisabledFor", user.getDisplayName())));
sender.sendMessage(tl("godMode", tl(enabled ? "godEnabledFor" : "godDisabledFor", user.getDisplayName())));
}
}
}

View File

@@ -1,6 +1,6 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.User;
import com.earth2me.essentials.craftbukkit.InventoryWorkaround;
import org.bukkit.Material;
@@ -21,41 +21,41 @@ public class Commandhat extends EssentialsCommand
{
if (args.length > 0 && (args[0].contains("rem") || args[0].contains("off") || args[0].equalsIgnoreCase("0")))
{
final PlayerInventory inv = user.getInventory();
final PlayerInventory inv = user.getBase().getInventory();
final ItemStack head = inv.getHelmet();
if (head == null || head.getType() == Material.AIR)
{
user.sendMessage(_("hatEmpty"));
user.sendMessage(tl("hatEmpty"));
}
else
{
final ItemStack air = new ItemStack(Material.AIR);
inv.setHelmet(air);
InventoryWorkaround.addItems(user.getInventory(), head);
user.sendMessage(_("hatRemoved"));
InventoryWorkaround.addItems(user.getBase().getInventory(), head);
user.sendMessage(tl("hatRemoved"));
}
}
else
{
if (user.getItemInHand().getType() != Material.AIR)
if (user.getBase().getItemInHand().getType() != Material.AIR)
{
final ItemStack hand = user.getItemInHand();
final ItemStack hand = user.getBase().getItemInHand();
if (hand.getType().getMaxDurability() == 0)
{
final PlayerInventory inv = user.getInventory();
final PlayerInventory inv = user.getBase().getInventory();
final ItemStack head = inv.getHelmet();
inv.setHelmet(hand);
inv.setItemInHand(head);
user.sendMessage(_("hatPlaced"));
user.sendMessage(tl("hatPlaced"));
}
else
{
user.sendMessage(_("hatArmor"));
user.sendMessage(tl("hatArmor"));
}
}
else
{
user.sendMessage(_("hatFail"));
user.sendMessage(tl("hatFail"));
}
}
}

View File

@@ -1,7 +1,7 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.User;
import org.bukkit.Server;
import org.bukkit.entity.Player;
@@ -51,7 +51,7 @@ public class Commandheal extends EssentialsLoopCommand
try
{
healPlayer(player);
sender.sendMessage(_("healOther", player.getDisplayName()));
sender.sendMessage(tl("healOther", player.getDisplayName()));
}
catch (QuietAbortException e)
{
@@ -65,7 +65,7 @@ public class Commandheal extends EssentialsLoopCommand
if (player.getHealth() == 0)
{
throw new PlayerExemptException(_("healDead"));
throw new PlayerExemptException(tl("healDead"));
}
final double amount = player.getMaxHealth() - player.getHealth();
@@ -85,7 +85,7 @@ public class Commandheal extends EssentialsLoopCommand
player.setHealth(newAmount);
player.setFoodLevel(20);
player.setFireTicks(0);
user.sendMessage(_("heal"));
user.sendMessage(tl("heal"));
for (PotionEffect effect : player.getActivePotionEffects())
{
player.removePotionEffect(effect.getType());

View File

@@ -1,7 +1,7 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.User;
import com.earth2me.essentials.textreader.*;
import com.earth2me.essentials.utils.NumberUtil;
@@ -45,6 +45,7 @@ public class Commandhelp extends EssentialsCommand
}
else
{
user.setDisplayNick();
output = new KeywordReplacer(input, user.getSource(), ess);
}
final TextPager pager = new TextPager(output);
@@ -54,6 +55,6 @@ public class Commandhelp extends EssentialsCommand
@Override
protected void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception
{
sender.sendMessage(_("helpConsole"));
sender.sendMessage(tl("helpConsole"));
}
}

View File

@@ -2,12 +2,11 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.Console;
import static com.earth2me.essentials.I18n._;
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 org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class Commandhelpop extends EssentialsCommand
@@ -21,7 +20,11 @@ public class Commandhelpop extends EssentialsCommand
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception
{
user.setDisplayNick();
sendMessage(server, user.getSource(), user.getDisplayName(), args);
final String message = sendMessage(server, user.getSource(), user.getDisplayName(), args);
if (!user.isAuthorized("essentials.helpop.receive"))
{
user.sendMessage(message);
}
}
@Override
@@ -30,23 +33,15 @@ public class Commandhelpop extends EssentialsCommand
sendMessage(server, sender, Console.NAME, args);
}
private void sendMessage(final Server server, final CommandSource sender, final String from, final String[] args) throws Exception
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 = _("helpOp", from, FormatUtil.stripFormat(getFinalArg(args, 0)));
CommandSender cs = Console.getCommandSender(server);
cs.sendMessage(message);
for (Player onlinePlayer : server.getOnlinePlayers())
{
final User player = ess.getUser(onlinePlayer);
if (!player.isAuthorized("essentials.helpop.receive"))
{
continue;
}
player.sendMessage(message);
}
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;
}
}

View File

@@ -1,6 +1,6 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.Trade;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.StringUtil;
@@ -46,7 +46,7 @@ public class Commandhome extends EssentialsCommand
{
if ("bed".equalsIgnoreCase(homeName) && user.isAuthorized("essentials.home.bed"))
{
final Location bed = player.getBedSpawnLocation();
final Location bed = player.getBase().getBedSpawnLocation();
if (bed != null)
{
user.getTeleport().teleport(bed, charge, TeleportCause.COMMAND);
@@ -54,14 +54,14 @@ public class Commandhome extends EssentialsCommand
}
else
{
throw new Exception(_("bedMissing"));
throw new Exception(tl("bedMissing"));
}
}
goHome(user, player, homeName.toLowerCase(Locale.ENGLISH), charge);
}
catch (NotEnoughArgumentsException e)
{
Location bed = player.getBedSpawnLocation();
Location bed = player.getBase().getBedSpawnLocation();
final List<String> homes = player.getHomes();
if (homes.isEmpty() && player.equals(user))
{
@@ -69,7 +69,7 @@ public class Commandhome extends EssentialsCommand
}
else if (homes.isEmpty())
{
throw new Exception(_("noHomeSetPlayer"));
throw new Exception(tl("noHomeSetPlayer"));
}
else if (homes.size() == 1 && player.equals(user))
{
@@ -82,14 +82,14 @@ public class Commandhome extends EssentialsCommand
{
if (bed != null)
{
homes.add(_("bed"));
homes.add(tl("bed"));
}
else
{
homes.add(_("bedNull"));
homes.add(tl("bedNull"));
}
}
user.sendMessage(_("homes", StringUtil.joinList(homes), count, getHomeLimit(player)));
user.sendMessage(tl("homes", StringUtil.joinList(homes), count, getHomeLimit(player)));
}
}
throw new NoChargeException();
@@ -97,7 +97,7 @@ public class Commandhome extends EssentialsCommand
private String getHomeLimit(final User player)
{
if (!player.isOnline())
if (!player.getBase().isOnline())
{
return "?";
}
@@ -122,7 +122,7 @@ public class Commandhome extends EssentialsCommand
if (user.getWorld() != loc.getWorld() && ess.getSettings().isWorldHomePermissions()
&& !user.isAuthorized("essentials.worlds." + loc.getWorld().getName()))
{
throw new Exception(_("noPerm", "essentials.worlds." + loc.getWorld().getName()));
throw new Exception(tl("noPerm", "essentials.worlds." + loc.getWorld().getName()));
}
user.getTeleport().teleport(loc, charge, TeleportCause.COMMAND);
}

View File

@@ -1,6 +1,6 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.User;
import org.bukkit.Server;
@@ -23,7 +23,7 @@ public class Commandignore extends EssentialsCommand
sb.append(s).append(" ");
}
String ignoredList = sb.toString().trim();
user.sendMessage(ignoredList.length() > 0 ? _("ignoredList", ignoredList) : _("noIgnored"));
user.sendMessage(ignoredList.length() > 0 ? tl("ignoredList", ignoredList) : tl("noIgnored"));
}
else
{
@@ -41,17 +41,17 @@ public class Commandignore extends EssentialsCommand
throw new PlayerNotFoundException();
}
if (player.isIgnoreExempt()) {
user.sendMessage(_("ignoreExempt"));
user.sendMessage(tl("ignoreExempt"));
}
else if (user.isIgnoredPlayer(player))
{
user.setIgnoredPlayer(player, false);
user.sendMessage(_("unignorePlayer", player.getName()));
user.sendMessage(tl("unignorePlayer", player.getName()));
}
else
{
user.setIgnoredPlayer(player, true);
user.sendMessage(_("ignorePlayer", player.getName()));
user.sendMessage(tl("ignorePlayer", player.getName()));
}
}
}

View File

@@ -18,6 +18,11 @@ public class Commandinfo extends EssentialsCommand
@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);

View File

@@ -27,14 +27,14 @@ public class Commandinvsee extends EssentialsCommand
if (args.length > 1 && user.isAuthorized("essentials.invsee.equip"))
{
inv = server.createInventory(invUser.getBase(), 9, "Equipped");
inv.setContents(invUser.getInventory().getArmorContents());
inv.setContents(invUser.getBase().getInventory().getArmorContents());
}
else
{
inv = invUser.getInventory();
inv = invUser.getBase().getInventory();
}
user.closeInventory();
user.openInventory(inv);
user.getBase().closeInventory();
user.getBase().openInventory(inv);
user.setInvSee(true);
}
}

View File

@@ -1,6 +1,6 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.MetaItemStack;
import com.earth2me.essentials.User;
import com.earth2me.essentials.craftbukkit.InventoryWorkaround;
@@ -34,7 +34,7 @@ public class Commanditem extends EssentialsCommand
: (!user.isAuthorized("essentials.itemspawn.exempt")
&& !user.canSpawnItem(stack.getTypeId())))
{
throw new Exception(_("cantSpawnItem", itemname));
throw new Exception(tl("cantSpawnItem", itemname));
}
try
{
@@ -68,19 +68,19 @@ public class Commanditem extends EssentialsCommand
if (stack.getType() == Material.AIR)
{
throw new Exception(_("cantSpawnItem", "Air"));
throw new Exception(tl("cantSpawnItem", "Air"));
}
final String displayName = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace('_', ' ');
user.sendMessage(_("itemSpawn", stack.getAmount(), displayName));
user.sendMessage(tl("itemSpawn", stack.getAmount(), displayName));
if (user.isAuthorized("essentials.oversizedstacks"))
{
InventoryWorkaround.addOversizedItems(user.getInventory(), ess.getSettings().getOversizedStackSize(), stack);
InventoryWorkaround.addOversizedItems(user.getBase().getInventory(), ess.getSettings().getOversizedStackSize(), stack);
}
else
{
InventoryWorkaround.addItems(user.getInventory(), stack);
InventoryWorkaround.addItems(user.getBase().getInventory(), stack);
}
user.updateInventory();
user.getBase().updateInventory();
}
}

View File

@@ -1,7 +1,7 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.inventory.ItemStack;
@@ -35,7 +35,7 @@ public class Commanditemdb extends EssentialsCommand
{
itemStack = ess.getItemDb().get(args[0]);
}
sender.sendMessage(_("itemType", itemStack.getType().toString(), itemStack.getTypeId() + ":" + Integer.toString(itemStack.getDurability())));
sender.sendMessage(tl("itemType", itemStack.getType().toString(), itemStack.getTypeId() + ":" + Integer.toString(itemStack.getDurability())));
if (itemHeld && itemStack.getType() != Material.AIR)
{
@@ -43,13 +43,13 @@ public class Commanditemdb extends EssentialsCommand
int durability = ((maxuses + 1) - itemStack.getDurability());
if (maxuses != 0)
{
sender.sendMessage(_("durability", Integer.toString(durability)));
sender.sendMessage(tl("durability", Integer.toString(durability)));
}
}
final String itemNameList = ess.getItemDb().names(itemStack);
if (itemNameList != null)
{
sender.sendMessage(_("itemNames", ess.getItemDb().names(itemStack)));
sender.sendMessage(tl("itemNames", ess.getItemDb().names(itemStack)));
}
}
}

View File

@@ -1,6 +1,6 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.Trade;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.LocationUtil;
@@ -46,7 +46,7 @@ public class Commandjump extends EssentialsCommand
}
catch (NullPointerException ex)
{
throw new Exception(_("jumpError"), ex);
throw new Exception(tl("jumpError"), ex);
}
final Trade charge = new Trade(this.getName(), ess);

View File

@@ -2,7 +2,7 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.Console;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.FormatUtil;
import java.util.logging.Level;
@@ -28,24 +28,24 @@ public class Commandkick extends EssentialsCommand
if (sender.isPlayer())
{
User user = ess.getUser(sender.getPlayer());
if (target.isHidden() && !user.isAuthorized("essentials.vanish.interact"))
if (target.isHidden(sender.getPlayer()) && !user.canInteractVanished() && !sender.getPlayer().canSee(target.getBase()))
{
throw new PlayerNotFoundException();
}
if (target.isAuthorized("essentials.kick.exempt"))
{
throw new Exception(_("kickExempt"));
throw new Exception(tl("kickExempt"));
}
}
String kickReason = args.length > 1 ? getFinalArg(args, 1) : _("kickDefault");
String kickReason = args.length > 1 ? getFinalArg(args, 1) : tl("kickDefault");
kickReason = FormatUtil.replaceFormat(kickReason.replace("\\n", "\n").replace("|", "\n"));
target.kickPlayer(kickReason);
target.getBase().kickPlayer(kickReason);
final String senderName = sender.isPlayer() ? sender.getPlayer().getDisplayName() : Console.NAME;
server.getLogger().log(Level.INFO, _("playerKicked", senderName, target.getName(), kickReason));
ess.broadcastMessage("essentials.kick.notify", _("playerKicked", senderName, target.getName(), kickReason));
server.getLogger().log(Level.INFO, tl("playerKicked", senderName, target.getName(), kickReason));
ess.broadcastMessage("essentials.kick.notify", tl("playerKicked", senderName, target.getName(), kickReason));
}
}

View File

@@ -1,7 +1,7 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.utils.FormatUtil;
import org.bukkit.Server;
import org.bukkit.entity.Player;
@@ -17,16 +17,16 @@ public class Commandkickall extends EssentialsCommand
@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) : _("kickDefault");
String kickReason = args.length > 0 ? getFinalArg(args, 0) : tl("kickDefault");
kickReason = FormatUtil.replaceFormat(kickReason.replace("\\n", "\n").replace("|", "\n"));
for (Player onlinePlayer : server.getOnlinePlayers())
for (Player onlinePlayer : ess.getOnlinePlayers())
{
if (!sender.isPlayer() || !onlinePlayer.getName().equalsIgnoreCase(sender.getPlayer().getName()))
{
onlinePlayer.kickPlayer(kickReason);
}
}
sender.sendMessage(_("kickedAll"));
sender.sendMessage(tl("kickedAll"));
}
}

View File

@@ -1,7 +1,7 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.User;
import org.bukkit.Server;
import org.bukkit.entity.Player;
@@ -32,7 +32,7 @@ public class Commandkill extends EssentialsLoopCommand
final Player matchPlayer = user.getBase();
if (sender.isPlayer() && user.isAuthorized("essentials.kill.exempt") && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.kill.force"))
{
throw new PlayerExemptException(_("killExempt", matchPlayer.getDisplayName()));
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);
@@ -47,6 +47,6 @@ public class Commandkill extends EssentialsLoopCommand
matchPlayer.setHealth(0);
}
sender.sendMessage(_("kill", matchPlayer.getDisplayName()));
sender.sendMessage(tl("kill", matchPlayer.getDisplayName()));
}
}

View File

@@ -1,14 +1,14 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.Kit;
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 java.util.Map;
import java.util.logging.Level;
import org.bukkit.Server;
@@ -18,76 +18,108 @@ public class Commandkit extends EssentialsCommand
{
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 ? _("kits", kitList) : _("noKits"));
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 kitName = StringUtil.sanitizeString(args[0].toLowerCase(Locale.ENGLISH)).trim();
giveKit(userTo, user, kitName);
final String kitNames = StringUtil.sanitizeString(args[0].toLowerCase(Locale.ENGLISH)).trim();
giveKits(userTo, user, kitNames);
}
else
{
final String kitName = StringUtil.sanitizeString(args[0].toLowerCase(Locale.ENGLISH)).trim();
giveKit(user, user, kitName);
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 ? _("kits", kitList) : _("noKits"));
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 kitName = args[0].toLowerCase(Locale.ENGLISH);
final Map<String, Object> kit = ess.getSettings().getKit(kitName);
final List<String> items = Kit.getItems(ess, userTo, kitName, kit);
Kit.expandItems(ess, userTo, items);
sender.sendMessage(_("kitGiveTo", kitName, userTo.getDisplayName()));
userTo.sendMessage(_("kitReceive", kitName));
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 giveKit(User userTo, User userFrom, String kitName) throws Exception
{
if (kitName.isEmpty())
private void giveKits(final User userTo, final User userFrom, final String kitNames) throws Exception
{
if (kitNames.isEmpty())
{
throw new Exception(_("kitError2"));
throw new Exception(tl("kitNotFound"));
}
String[] kitList = kitNames.split(",");
List<Kit> kits = new ArrayList<Kit>();
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);
}
final Map<String, Object> kit = ess.getSettings().getKit(kitName);
if (!userFrom.isAuthorized("essentials.kits." + kitName))
for (final Kit kit : kits)
{
throw new Exception(_("noKitPermission", "essentials.kits." + kitName));
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());
}
}
final List<String> items = Kit.getItems(ess, userTo, kitName, kit);
final Trade charge = new Trade("kit-" + kitName, ess);
charge.isAffordableFor(userFrom);
Kit.checkTime(userFrom, kitName, kit);
Kit.expandItems(ess, userTo, items);
charge.charge(userFrom);
userFrom.sendMessage(_("kitGiveTo", kitName, userTo.getDisplayName()));
userTo.sendMessage(_("kitReceive", kitName));
}
}

View File

@@ -21,7 +21,7 @@ public class Commandkittycannon extends EssentialsCommand
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.getEyeLocation());
final Ocelot ocelot = (Ocelot)cat.spawn(user.getWorld(), server, user.getBase().getEyeLocation());
if (ocelot == null)
{
return;
@@ -30,8 +30,9 @@ public class Commandkittycannon extends EssentialsCommand
ocelot.setCatType(Ocelot.Type.values()[i]);
ocelot.setTamed(true);
ocelot.setBaby();
ocelot.setVelocity(user.getEyeLocation().getDirection().multiply(2));
ess.scheduleSyncDelayedTask(new Runnable()
ocelot.setVelocity(user.getBase().getEyeLocation().getDirection().multiply(2));
class KittyCannonExplodeTask implements Runnable
{
@Override
public void run()
@@ -40,6 +41,8 @@ public class Commandkittycannon extends EssentialsCommand
ocelot.remove();
loc.getWorld().createExplosion(loc, 0F);
}
}, 20);
}
ess.scheduleSyncDelayedTask(new KittyCannonExplodeTask(), 20);
}
}

View File

@@ -1,7 +1,7 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.User;
import org.bukkit.Server;
import org.bukkit.entity.LightningStrike;
@@ -25,7 +25,7 @@ public class Commandlightning extends EssentialsLoopCommand
user = ess.getUser(sender.getPlayer());
if ((args.length < 1 || user != null && !user.isAuthorized("essentials.lightning.others")))
{
user.getWorld().strikeLightning(user.getTargetBlock(null, 600).getLocation());
user.getWorld().strikeLightning(user.getBase().getTargetBlock(null, 600).getLocation());
return;
}
}
@@ -46,7 +46,7 @@ public class Commandlightning extends EssentialsLoopCommand
@Override
protected void updatePlayer(final Server server, final CommandSource sender, final User matchUser, final String[] args)
{
sender.sendMessage(_("lightningUse", matchUser.getDisplayName()));
sender.sendMessage(tl("lightningUse", matchUser.getDisplayName()));
final LightningStrike strike = matchUser.getBase().getWorld().strikeLightningEffect(matchUser.getBase().getLocation());
if (!matchUser.isGodModeEnabled())
@@ -55,7 +55,7 @@ public class Commandlightning extends EssentialsLoopCommand
}
if (ess.getSettings().warnOnSmite())
{
matchUser.sendMessage(_("lightningSmited"));
matchUser.sendMessage(tl("lightningSmited"));
}
}
}

View File

@@ -1,7 +1,7 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.PlayerList;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.FormatUtil;
@@ -21,12 +21,14 @@ public class Commandlist extends EssentialsCommand
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())
{
showHidden = ess.getUser(sender.getPlayer()).isAuthorized("essentials.list.hidden") || ess.getUser(sender.getPlayer()).isAuthorized("essentials.vanish.interact");
user = ess.getUser(sender.getPlayer());
showHidden = user.isAuthorized("essentials.list.hidden") || user.canInteractVanished();
}
sender.sendMessage(PlayerList.listSummary(ess, showHidden));
final Map<String, List<User>> playerList = PlayerList.getPlayerLists(ess, showHidden);
sender.sendMessage(PlayerList.listSummary(ess, user, showHidden));
final Map<String, List<User>> playerList = PlayerList.getPlayerLists(ess, user, showHidden);
if (args.length > 0)
{
@@ -77,7 +79,7 @@ public class Commandlist extends EssentialsCommand
int limit = Integer.parseInt(groupValue);
if (matchedList.size() > limit)
{
sender.sendMessage(PlayerList.outputFormat(oConfigGroup, _("groupNumber", matchedList.size(), commandLabel, FormatUtil.stripFormat(configGroup))));
sender.sendMessage(PlayerList.outputFormat(oConfigGroup, tl("groupNumber", matchedList.size(), commandLabel, FormatUtil.stripFormat(configGroup))));
}
else
{
@@ -124,7 +126,7 @@ public class Commandlist extends EssentialsCommand
if (ess.getPermissionsHandler().getName().equals("ConfigPermissions"))
{
groupName = _("connectedPlayers");
groupName = tl("connectedPlayers");
}
if (users == null || users.isEmpty())
{

View File

@@ -1,14 +1,19 @@
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 static com.earth2me.essentials.I18n._;
import java.util.UUID;
public class Commandmail extends EssentialsCommand
@@ -30,40 +35,43 @@ public class Commandmail extends EssentialsCommand
final List<String> mail = user.getMails();
if (mail.isEmpty())
{
user.sendMessage(_("noMail"));
user.sendMessage(tl("noMail"));
throw new NoChargeException();
}
for (String messages : mail)
{
user.sendMessage(messages);
}
user.sendMessage(_("mailClear"));
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(_("noPerm", "essentials.mail.send"));
}
if (user.isMuted())
{
throw new Exception(_("voiceSilenced"));
throw new Exception(tl("noPerm", "essentials.mail.send"));
}
User u = ess.getUser(args[1]);
if (user.isMuted())
{
throw new Exception(tl("voiceSilenced"));
}
User u = getPlayer(server, args[1], true, true);
if (u == null)
{
throw new Exception(_("playerNeverOnServer", args[1]));
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))
{
final String mail = user.getName() + ": " + StringUtil.sanitizeString(FormatUtil.stripFormat(getFinalArg(args, 2)));
if (mail.length() > 1000)
{
throw new Exception(_("mailTooLong"));
}
if (Math.abs(System.currentTimeMillis() - timestamp) > 60000)
{
timestamp = System.currentTimeMillis();
@@ -72,27 +80,29 @@ public class Commandmail extends EssentialsCommand
mailsPerMinute++;
if (mailsPerMinute > ess.getSettings().getMailsPerMinute())
{
throw new Exception(_("mailDelay", ess.getSettings().getMailsPerMinute()));
throw new Exception(tl("mailDelay", ess.getSettings().getMailsPerMinute()));
}
u.addMail(mail);
u.addMail(tl("mailMessage", mail));
}
user.sendMessage(_("mailSent"));
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(_("noPerm", "essentials.mail.sendall"));
throw new Exception(tl("noPerm", "essentials.mail.sendall"));
}
ess.runTaskAsynchronously(new SendAll(user.getName() + ": " + FormatUtil.stripFormat(getFinalArg(args, 1))));
user.sendMessage(_("mailSent"));
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(_("mailCleared"));
user.sendMessage(tl("mailCleared"));
return;
}
throw new NotEnoughArgumentsException();
@@ -103,39 +113,39 @@ public class Commandmail extends EssentialsCommand
{
if (args.length >= 1 && "read".equalsIgnoreCase(args[0]))
{
throw new Exception(_("onlyPlayers", commandLabel + " read"));
throw new Exception(tl("onlyPlayers", commandLabel + " read"));
}
else if (args.length >= 1 && "clear".equalsIgnoreCase(args[0]))
{
throw new Exception(_("onlyPlayers", commandLabel + " clear"));
throw new Exception(tl("onlyPlayers", commandLabel + " clear"));
}
else if (args.length >= 3 && "send".equalsIgnoreCase(args[0]))
{
User u = ess.getUser(args[1]);
User u = getPlayer(server, args[1], true, true);
if (u == null)
{
throw new Exception(_("playerNeverOnServer", args[1]));
throw new Exception(tl("playerNeverOnServer", args[1]));
}
u.addMail("Server: " + getFinalArg(args, 2));
sender.sendMessage(_("mailSent"));
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("Server: " + getFinalArg(args, 1)));
sender.sendMessage(_("mailSent"));
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 = ess.getUser(args[0]);
User u = getPlayer(server, args[0], true, true);
if (u == null)
{
throw new Exception(_("playerNeverOnServer", args[0]));
throw new Exception(tl("playerNeverOnServer", args[0]));
}
u.addMail("Server: " + getFinalArg(args, 1));
sender.sendMessage(_("mailSent"));
u.addMail(tl("mailFormat", "Server", getFinalArg(args, 1)));
sender.sendMessage(tl("mailSent"));
return;
}
throw new NotEnoughArgumentsException();
@@ -154,9 +164,9 @@ public class Commandmail extends EssentialsCommand
@Override
public void run()
{
for (String username : ess.getUserMap().getAllUniqueUsers())
for (UUID userid : ess.getUserMap().getAllUniqueUsers())
{
User user = ess.getUserMap().getUser(username);
User user = ess.getUserMap().getUser(userid);
if (user != null)
{
user.addMail(message);

View File

@@ -1,7 +1,7 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.FormatUtil;
import org.bukkit.Server;
@@ -19,7 +19,7 @@ public class Commandme extends EssentialsCommand
{
if (user.isMuted())
{
throw new Exception(_("voiceSilenced"));
throw new Exception(tl("voiceSilenced"));
}
if (args.length < 1)
@@ -31,7 +31,7 @@ public class Commandme extends EssentialsCommand
message = FormatUtil.formatMessage(user, "essentials.chat", message);
user.setDisplayNick();
ess.broadcastMessage(user, _("action", user.getDisplayName(), message));
ess.broadcastMessage(user, tl("action", user.getDisplayName(), message));
}
@Override
@@ -45,6 +45,6 @@ public class Commandme extends EssentialsCommand
String message = getFinalArg(args, 0);
message = FormatUtil.replaceFormat(message);
ess.getServer().broadcastMessage(_("action", "@", message));
ess.getServer().broadcastMessage(tl("action", "@", message));
}
}

View File

@@ -1,6 +1,6 @@
package com.earth2me.essentials.commands;
import static com.earth2me.essentials.I18n._;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.User;
import java.util.Locale;
import org.bukkit.Server;
@@ -17,15 +17,15 @@ public class Commandmore extends EssentialsCommand
@Override
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception
{
final ItemStack stack = user.getItemInHand();
final ItemStack stack = user.getBase().getItemInHand();
if (stack == null)
{
throw new Exception(_("cantSpawnItem", "Air"));
throw new Exception(tl("cantSpawnItem", "Air"));
}
if (stack.getAmount() >= ((user.isAuthorized("essentials.oversizedstacks"))
? ess.getSettings().getOversizedStackSize() : stack.getMaxStackSize()))
{
throw new Exception(_("fullStack"));
throw new Exception(tl("fullStack"));
}
final String itemname = stack.getType().toString().toLowerCase(Locale.ENGLISH).replace("_", "");
if (ess.getSettings().permissionBasedItemSpawn()
@@ -35,7 +35,7 @@ public class Commandmore extends EssentialsCommand
: (!user.isAuthorized("essentials.itemspawn.exempt")
&& !user.canSpawnItem(stack.getTypeId())))
{
throw new Exception(_("cantSpawnItem", itemname));
throw new Exception(tl("cantSpawnItem", itemname));
}
if (user.isAuthorized("essentials.oversizedstacks"))
{
@@ -45,6 +45,6 @@ public class Commandmore extends EssentialsCommand
{
stack.setAmount(stack.getMaxStackSize());
}
user.updateInventory();
user.getBase().updateInventory();
}
}

View File

@@ -18,6 +18,11 @@ public class Commandmotd extends EssentialsCommand
@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);

View File

@@ -2,7 +2,7 @@ package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.Console;
import static com.earth2me.essentials.I18n._;
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;
@@ -13,7 +13,7 @@ import org.bukkit.command.CommandSender;
public class Commandmsg extends EssentialsLoopCommand
{
final String translatedMe = _("me");
final String translatedMe = tl("me");
public Commandmsg()
{
@@ -35,7 +35,7 @@ public class Commandmsg extends EssentialsLoopCommand
User user = ess.getUser(sender.getPlayer());
if (user.isMuted())
{
throw new Exception(_("voiceSilenced"));
throw new Exception(tl("voiceSilenced"));
}
message = FormatUtil.formatMessage(user, "essentials.msg", message);
canWildcard = user.isAuthorized("essentials.msg.multiple");
@@ -51,9 +51,9 @@ public class Commandmsg extends EssentialsLoopCommand
final IReplyTo replyTo = sender.isPlayer() ? ess.getUser(sender.getPlayer()) : Console.getConsoleReplyTo();
final String senderName = sender.isPlayer() ? sender.getPlayer().getDisplayName() : Console.NAME;
sender.sendMessage(_("msgFormat", translatedMe, Console.NAME, message));
sender.sendMessage(tl("msgFormat", translatedMe, Console.NAME, message));
CommandSender cs = Console.getCommandSender(server);
cs.sendMessage(_("msgFormat", senderName, translatedMe, message));
cs.sendMessage(tl("msgFormat", senderName, translatedMe, message));
replyTo.setReplyTo(new CommandSource(cs));
Console.getConsoleReplyTo().setReplyTo(sender);
return;
@@ -70,16 +70,16 @@ public class Commandmsg extends EssentialsLoopCommand
if (matchedUser.isAfk())
{
sender.sendMessage(_("userAFK", matchedUser.getDisplayName()));
sender.sendMessage(tl("userAFK", matchedUser.getDisplayName()));
}
sender.sendMessage(_("msgFormat", translatedMe, matchedUser.getDisplayName(), args[0]));
sender.sendMessage(tl("msgFormat", translatedMe, matchedUser.getDisplayName(), args[0]));
if (sender.isPlayer() && matchedUser.isIgnoredPlayer(ess.getUser(sender.getPlayer())))
{
return;
}
matchedUser.sendMessage(_("msgFormat", senderName, translatedMe, args[0]));
matchedUser.sendMessage(tl("msgFormat", senderName, translatedMe, args[0]));
replyTo.setReplyTo(matchedUser.getSource());
matchedUser.setReplyTo(sender);
}

View File

@@ -1,10 +1,11 @@
package com.earth2me.essentials.commands;
import com.earth2me.essentials.CommandSource;
import static com.earth2me.essentials.I18n._;
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;
@@ -31,20 +32,20 @@ public class Commandmute extends EssentialsCommand
catch (PlayerNotFoundException e)
{
nomatch = true;
user = ess.getUser(new OfflinePlayer(args[0], ess));
user = ess.getUser(new OfflinePlayer(args[0], ess.getServer()));
}
if (!user.isOnline())
if (!user.getBase().isOnline())
{
if (sender.isPlayer() && !ess.getUser(sender.getPlayer()).isAuthorized("essentials.mute.offline"))
{
throw new Exception(_("muteExemptOffline"));
throw new Exception(tl("muteExemptOffline"));
}
}
else
{
if (user.isAuthorized("essentials.mute.exempt") && sender.isPlayer())
{
throw new Exception(_("muteExempt"));
throw new Exception(tl("muteExempt"));
}
}
@@ -66,27 +67,29 @@ public class Commandmute extends EssentialsCommand
if (nomatch)
{
sender.sendMessage(_("userUnknown", user.getName()));
sender.sendMessage(tl("userUnknown", user.getName()));
}
if (muted)
{
if (muteTimestamp > 0)
{
sender.sendMessage(_("mutedPlayerFor", user.getDisplayName(), muteTime));
user.sendMessage(_("playerMutedFor", muteTime));
sender.sendMessage(tl("mutedPlayerFor", user.getDisplayName(), muteTime));
user.sendMessage(tl("playerMutedFor", muteTime));
}
else
{
sender.sendMessage(_("mutedPlayer", user.getDisplayName()));
user.sendMessage(_("playerMuted"));
sender.sendMessage(tl("mutedPlayer", user.getDisplayName()));
user.sendMessage(tl("playerMuted"));
}
ess.broadcastMessage("essentials.mute.notify", _("muteNotify", sender.getSender().getName(), user.getName(), muteTime));
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(_("unmutedPlayer", user.getDisplayName()));
user.sendMessage(_("playerUnmuted"));
sender.sendMessage(tl("unmutedPlayer", user.getDisplayName()));
user.sendMessage(tl("playerUnmuted"));
}
}
}

Some files were not shown because too many files have changed in this diff Show More