Compare commits

..

484 Commits

Author SHA1 Message Date
ff401b65c4 3.5.0 Release 2016-11-26 18:02:39 -05:00
11913bfbe5 Fix compile issue 2016-11-26 17:53:44 -05:00
62b353f82d Various Sponge changes
- many improvements
- inventory utilities broke when updating to Sponge API 6.0.0
2016-11-26 16:49:13 -05:00
8d442f58d4 Fixes #1445 2016-11-26 12:05:08 -05:00
5cbd2f44bd Update Sponge Gradle 2016-11-26 11:55:59 -05:00
dc673f9715 Fixed #1440 , Fixed #1446 2016-11-26 11:55:38 -05:00
deb5441bcf *Fix compile error 2016-11-24 11:05:28 +11:00
8ebf71c87f DB fix 2016-11-24 10:19:00 +11:00
9fd53af483 Add world argument 2016-11-23 15:47:18 +11:00
fb729df59e Setting to sort plots by area 2016-11-23 15:36:25 +11:00
ce6e1be13e Fix maven dependencies (#1439)
* Fixes

* Fix wrong version
2016-11-21 09:59:11 -05:00
e126054053 Fixes #1429 Removes duplicate aliases. 2016-11-20 22:29:14 -05:00
77281017d4 Fixes #1428 , Fixes #1431 2016-11-20 22:24:27 -05:00
e0208aa369 Fix plot help category pagination 2016-11-18 10:49:03 +11:00
fdc42a3d5c Seems the new spigot 1.11 sqlite driver has issues parsing timestamps, no idea why. 2016-11-18 09:08:41 +11:00
3070557a3a Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared 2016-11-13 22:18:11 +11:00
2ec0b55482 Fix database lock error 2016-11-13 22:17:17 +11:00
10dd9b6371 Merge pull request #1424 from c7w/master
translation
2016-11-13 06:41:25 +11:00
c7w
1ac0a7dad0 translation
translation of chinese
2016-11-12 12:52:43 +08:00
f8b1fcffa1 Fix worldedit mask area 2016-11-12 00:14:12 +11:00
17762f5ae7 Tweak delete message 2016-11-09 00:13:46 +11:00
1d7cdde84a Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared 2016-11-02 04:28:11 +11:00
c950b0021f Notify inbox permission 2016-11-02 04:27:52 +11:00
e4bc2b30b1 Update ISSUE_TEMPLATE.md (#1409) 2016-10-28 10:15:38 -04:00
e0c4c944bb Merge remote-tracking branch 'origin/master' 2016-10-26 23:01:01 -04:00
dd09ef18e6 Add missing gradle batch
Signed-off-by: MattBDev <mattbdev@outlook.com>
2016-10-26 23:00:43 -04:00
68011f43cd Fixes #1390 2016-10-21 03:51:27 +11:00
93c4854454 Add misc-interact flag 2016-10-18 05:03:14 +11:00
e594227d95 Fix some height issues 2016-10-14 16:56:28 +11:00
d6be5703ae Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared 2016-10-14 15:14:35 +11:00
c97544d083 Minor fixes 2016-10-14 15:14:08 +11:00
a05fd2dd11 Fix #1386
Signed-off-by: MattBDev <mattbdev@outlook.com>
2016-10-10 00:18:35 -04:00
5978c9c3c0 Fix center 2016-10-03 00:56:27 +11:00
5d3e096501 *Fix the toggle 2016-10-03 00:56:26 +11:00
39e99c0593 Merge pull request #1381 from filoghost/patch-1
Fix permission checks being ignored
2016-10-02 14:08:22 +11:00
cd33aaa1b6 Fix permission checks being ignored 2016-10-01 21:35:57 +02:00
0244c0241c Trim deletes expired plots 2016-10-01 20:17:50 +10:00
5ed2190cb3 Fixes #1369 2016-09-30 23:32:49 +10:00
c533f0bae9 Fix area removal 2016-09-30 17:05:18 +10:00
cd2b6c8ccc Fixes #1379 2016-09-30 17:04:06 +10:00
6f2c7de0ff Minor fix to conversion 2016-09-30 16:46:10 +10:00
62373c0737 * 2016-09-30 16:15:15 +10:00
499120963a Streamline PlotMe conversion
Use reflection to disable PlotMe and forward DefaultGenerator to
PlotSquared
Fix border material copying from plotme config
You no longer need to delete the PlotMe jar for conversion
Fix some outdated messages
2016-09-30 16:14:35 +10:00
f1d581a8d8 Fixes #1377 2016-09-30 15:29:50 +10:00
6074fc8033 Nukkit generator fixes 2016-09-30 14:26:20 +10:00
e4d7270c28 Fix some merged plot events 2016-09-30 03:30:34 +10:00
b6df07f723 Add snow-form flag 2016-09-27 01:38:59 +10:00
177b33154f Multiple
Fixes #1362
Fixes border id for PlotMe converter
2016-09-27 00:56:39 +10:00
6bf2fbcfcf Command tweaks 2016-09-26 18:33:27 +10:00
12f8861d07 Various
externalize strings
plotme conversion fixes
2016-09-26 18:31:08 +10:00
c99e23bd3c Fixes #1367 2016-09-25 18:48:38 +10:00
1b6d08b3fe Fixes #1365 2016-09-25 18:43:53 +10:00
3b4490c1c6 Fixes #1366 2016-09-25 18:42:05 +10:00
04c011164a Add near cmd 2016-09-25 18:06:20 +10:00
86b776f742 Nukkit perms 2016-09-25 16:49:51 +10:00
61022b717a Fixes #1360 2016-09-21 13:42:59 +10:00
9e5af7a642 Possible fix for redstone in merged plots 2016-09-20 23:49:22 +10:00
364b4347d1 Fix area id parsing 2016-09-19 14:18:47 +10:00
d89274ce09 Merge remote-tracking branch 'origin/master'
# Conflicts:
#	Bukkit/src/main/java/com/plotsquared/bukkit/BukkitMain.java
2016-09-17 16:03:57 +10:00
264114332b Let generator be up to the implementation 2016-09-17 16:02:05 +10:00
a4363bdb27 Fix #1355
There is the possibility this will cause issues with sponge

Signed-off-by: MattBDev <mattbdev@outlook.com>
2016-09-14 19:27:30 -04:00
8e7e5dcb25 Cleanup
Signed-off-by: MattBDev <mattbdev@outlook.com>
2016-09-14 12:16:22 -04:00
56227a6d7d Fixes #1351 2016-09-14 10:21:14 +10:00
63259ec269 Merge pull request #1352 from MisterErwin/master
A (possible) fix to #1351
2016-09-14 10:17:11 +10:00
0286a7b046 Fixes #1131 2016-09-14 10:12:53 +10:00
b6dac54677 Code cleaning and Gradle Update
Updated gradle wrapper to 3.0
Updated Gradle files for Nukkit
Added/cleaned minor Nukkit code
Removed duplicate TitleManagement code

Signed-off-by: MattBDev <mattbdev@outlook.com>
2016-09-13 18:10:01 -04:00
bf1d487508 A (possible) fix to #1351 2016-09-12 17:05:13 +02:00
a95b68b73c Add villager-interact flag 2016-09-09 15:17:37 +10:00
85ff8bf639 Minor tweaks 2016-09-07 00:28:01 +10:00
0557671b80 Recover from third party generator error 2016-09-04 14:22:01 +10:00
d75ab130da Sponge fixes 2016-09-02 15:58:24 +10:00
6a12a6ba64 print chat to console
Fixes #1339
2016-09-02 15:47:19 +10:00
22901bf9f2 Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared 2016-09-01 16:57:52 +10:00
07ee19b4bb Fixes #1337 2016-08-31 19:09:17 +10:00
27c21b9ab6 Fix #1321 2016-08-30 21:50:52 -04:00
da7a12bc00 Fixes #1234 2016-08-29 16:21:14 +10:00
3b73b2e9d8 Fix grant check 2016-08-29 15:33:26 +10:00
970c80cb15 Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared 2016-08-29 15:01:27 +10:00
dd665ed9ce Fence rotation 2016-08-29 15:01:19 +10:00
572da7d436 Merge pull request #1332 from manuelgu/patch-2
Might resolve #1331
2016-08-29 14:41:48 +10:00
ab05b026e9 Merge pull request #1335 from Herocraft/fix/vault-repo
Switch Vault repository to the real one
2016-08-29 12:19:48 +10:00
2fcb59f8cf Switch Vault repository to the real one 2016-08-28 18:26:11 -07:00
20250bc989 Might resolve #1331
Wasn't able to reproduce the issue
2016-08-28 20:14:58 +02:00
5e4798165b Merge pull request #1330 from MinelinkNetwork/fix-pom
Fix Spigot artifact in POM
2016-08-28 18:26:57 +10:00
7fc3fb097e Fix Spigot artifact in POM
Use the correct groupId, artifactId and version of Spigot dependency
installed by BuildTools
2016-08-28 01:13:21 -07:00
3a08e5c091 Merge pull request #1326 from SupremeMortal/SupremeMortal-patch-1
Update Non-existent Repo
2016-08-28 00:52:04 +10:00
50770a78d7 Fixed mistake 2016-08-27 14:09:03 +01:00
1266eed86a Add Replacement Repo For Vault 2016-08-27 14:08:35 +01:00
c0996299b4 Remove non-existent Repo
"nexus.theyeticave.net" does not exist anymore.
2016-08-27 14:03:41 +01:00
90d48b2cd0 Fixes #1289 2016-08-26 13:54:22 +10:00
a95d18499e Fixes #1285 2016-08-26 13:19:42 +10:00
61d00e51ef Fixes #1303 2016-08-26 03:02:50 +10:00
b5349e16f0 Fixes #1305
Just teleports the player further back
Combine move/tp since tp extends move
2016-08-26 02:31:50 +10:00
a801127036 Merge pull request #1301 from MisterErwin/master
Calling events when players are removed from plots & correct calling of Member & Trusted events
2016-08-26 02:02:40 +10:00
2806f8b20c Fixes #1307 2016-08-26 01:36:35 +10:00
7d11147836 Add Lazzy "Offline -> Offline Lowercase" conversion 2016-08-20 21:40:54 +10:00
74a6df1fa7 Update README.md 2016-08-20 00:26:53 -04:00
bc0c0abe7e Fix NPE 2016-08-19 12:16:13 +10:00
56907e4580 Version Bump
3.4.6-SNAPSHOT
2016-08-18 10:38:06 -04:00
005e13a216 Maybe #1239 2016-08-17 18:30:58 +10:00
3558105789 Fix default flags NPE 2016-08-17 15:08:01 +10:00
f651607d2f Might work? 2016-08-17 12:22:45 +10:00
6b95e57d9e Merge pull request #1313 from MinelinkNetwork/blocked-cmds
Only show blocked-cmds message when event is cancelled
2016-08-17 12:13:27 +10:00
98d0819383 Only show blocked-cmds message when event is cancelled 2016-08-16 19:09:02 -07:00
30da060f83 Potential fix for schematic placement on clear 2016-08-16 15:53:26 +10:00
e4408d56ec *And this 2016-08-16 14:32:31 +10:00
f07ac646f3 Possible fix for greeting spam 2016-08-15 09:31:03 +10:00
ef3380dc0a Merge remote-tracking branch 'origin/master' 2016-08-12 15:04:18 -04:00
749ab83e5d Move permission check out of loop
See #1307
2016-08-12 15:04:11 -04:00
daea9cf60d Allow teleportation for console 2016-08-10 12:33:18 +10:00
2f74368879 Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared 2016-08-09 12:45:45 -04:00
63d4476d97 Fix #1181 2016-08-09 12:40:38 -04:00
db69da5b07 *Wrong runnable 2016-08-09 08:52:31 +10:00
634802ef98 Got rid of that auto-optimize-imports option 2016-08-08 23:20:31 +02:00
37e4a652dd Now calling the respective events when a user is removed from a plot.
And switched the event calling of adding Helpers and Trusted players. (Correct me if that was wrong)
2016-08-08 22:45:08 +02:00
d22f7b8781 Merge remote-tracking branch 'origin/master' 2016-08-08 14:03:17 -04:00
112da17614 Squashed commit of the following:
commit 91c78407cd
Author: Jesse Boyd <jessepaleg@gmail.com>
Date:   Sun Aug 7 11:29:59 2016 +1000

    Use a queue for expiry

commit 395d6364be
Author: Jesse Boyd <jessepaleg@gmail.com>
Date:   Sun Aug 7 04:43:41 2016 +1000

    Cache on fail as well

commit facd43700d
Author: Jesse Boyd <jessepaleg@gmail.com>
Date:   Sun Aug 7 04:00:50 2016 +1000

    Cache entity count every second

commit 1ae694ff5b
Author: Jesse Boyd <jessepaleg@gmail.com>
Date:   Sun Aug 7 03:52:37 2016 +1000

    Tweak entity counting

commit c99dd1e74a
Author: Jesse Boyd <jessepaleg@gmail.com>
Date:   Sat Aug 6 00:10:11 2016 +1000

    Needs sponge builds

commit f408ac82be
Author: Alexander Söderberg <Sauilitired@users.noreply.github.com>
Date:   Fri Aug 5 12:13:39 2016 +0200

    Update README.md

commit 9b95990ba6
Author: Alexander Söderberg <Sauilitired@users.noreply.github.com>
Date:   Thu Aug 4 16:50:37 2016 +0200

    Update this here as well
2016-08-08 14:02:25 -04:00
91c78407cd Use a queue for expiry 2016-08-07 11:29:59 +10:00
395d6364be Cache on fail as well 2016-08-07 04:43:41 +10:00
facd43700d Cache entity count every second 2016-08-07 04:00:50 +10:00
1ae694ff5b Tweak entity counting 2016-08-07 03:52:37 +10:00
c99dd1e74a Needs sponge builds 2016-08-06 00:10:11 +10:00
f408ac82be Update README.md 2016-08-05 12:13:39 +02:00
9b95990ba6 Update this here as well 2016-08-04 16:50:37 +02:00
77fb329c9e Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared 2016-07-31 21:26:18 -04:00
a13b9fb31b flag tix 2016-08-01 11:20:06 +10:00
ea3306d070 Fix #1034 2016-07-31 20:17:35 -04:00
bcbcd6d916 Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared 2016-07-31 18:14:12 +10:00
415c6fb0d4 Fixes #1283 2016-07-31 18:14:06 +10:00
e801c6d7e8 Merge branch '3.4.5' 2016-07-31 00:16:37 -04:00
409456e895 Minor sponge fix 2016-07-31 09:16:58 +10:00
e8f4eae6f7 Merge remote-tracking branch 'origin/3.4.5' into 3.4.5
# Conflicts:
#	Sponge/build.gradle
#	Sponge/src/main/java/com/plotsquared/sponge/util/SpongeSetupUtils.java
2016-07-29 21:45:34 -04:00
c8419f4a4a Added more Java 8 warnings 2016-07-29 21:40:23 -04:00
09994724db Fix #1277 2016-07-29 21:40:02 -04:00
610e204d12 Fix #1281 , Fix #1282 , and Sponge gradle 2016-07-29 12:47:42 -04:00
1f341e6ba9 Merge remote-tracking branch 'origin/master' into 3.4.5
# Conflicts:
#	Sponge/src/main/java/com/plotsquared/sponge/SpongeMain.java
#	Sponge/src/main/java/com/plotsquared/sponge/generator/SpongeAugmentedGenerator.java
#	Sponge/src/main/java/com/plotsquared/sponge/util/SpongeSetupUtils.java
#	Sponge/src/main/java/com/plotsquared/sponge/util/SpongeUtil.java
#	Sponge/src/main/java/com/plotsquared/sponge/util/block/GenChunk.java
#	build.gradle
2016-07-29 12:25:11 -04:00
ffddf5c187 Fix sponge generator cast 2016-07-29 12:12:28 +10:00
b5ec6232f9 Sponge Fixes and minor changes. 2016-07-25 22:25:15 -04:00
34c2da55ca Change Sponge method behavior 2016-07-25 22:25:15 -04:00
33ec80c2cb Fix Sponge generation casting 2016-07-25 22:25:15 -04:00
48064da1ee Fixed deny-teleport flag 2016-07-25 22:25:15 -04:00
adc021109f Added Polar Bear where missing 2016-07-25 22:25:15 -04:00
d23d8c2fd8 *should use this cause instead 2016-07-25 22:25:15 -04:00
3498f309e8 Minor sponge fixes 2016-07-25 22:24:31 -04:00
0b5177f192 Minor uuid cache changes 2016-07-25 22:23:49 -04:00
07dc6a46fb Remove metrics depend 2016-07-25 22:23:19 -04:00
0b19cc7d9d Possible fix + add guest-gamemode flag 2016-07-25 22:23:19 -04:00
4e019ab796 UUID cache changes 2016-07-25 22:23:19 -04:00
b2fdcad317 Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared into 3.4.5
# Conflicts:
#	Sponge/src/main/java/com/plotsquared/sponge/util/SpongeUtil.java
#	Sponge/src/main/java/com/plotsquared/sponge/util/block/GenChunk.java
2016-07-25 22:08:54 -04:00
80ea3e9ce7 Sponge Fixes and minor changes. 2016-07-25 20:00:59 -04:00
5f8c77a6cd Change Sponge method behavior 2016-07-25 18:43:11 -04:00
290e5c68dc Fix Sponge generation casting 2016-07-25 18:42:31 -04:00
5d92701100 Fixed deny-teleport flag 2016-07-25 18:04:17 -04:00
1a86d5fb9e Added Polar Bear where missing 2016-07-25 01:19:29 -04:00
30d18c917d *should use this cause instead 2016-07-25 09:54:35 +10:00
b91eab2f0c Minor sponge fixes 2016-07-25 09:47:49 +10:00
770b9be160 Minor uuid cache changes 2016-07-25 09:23:20 +10:00
14b2b11bf3 Remove metrics depend 2016-07-25 08:09:57 +10:00
975a5765c1 Possible fix + add guest-gamemode flag 2016-07-25 08:02:17 +10:00
2b9c2959cf Merge branch '3.4.5' of https://github.com/IntellectualSites/PlotSquared into 3.5.0 2016-07-24 17:45:34 -04:00
07977ac2ce UUID cache changes 2016-07-25 07:44:47 +10:00
9e5ac80435 Merge remote-tracking branch 'origin/3.4.5' into 3.4.5 2016-07-24 17:42:21 -04:00
dda6849412 Fix sponge compile 2016-07-24 17:42:03 -04:00
85d6e42462 Merge branch '3.4.5' of https://github.com/IntellectualSites/PlotSquared into 3.5.0 2016-07-24 17:27:41 -04:00
b1ee223b0a Merge pull request #1271 from manuelgu/patch-1
Make debug output useful
2016-07-24 07:51:45 +02:00
98e865cdf0 Make debug output useful 2016-07-23 12:50:39 +02:00
8b084839fd Fix #1261 2016-07-19 10:22:50 -04:00
c1d4c481fb Fix #1244 2016-07-17 23:20:31 -04:00
269e409e3e Version Bump 2016-07-17 23:19:37 -04:00
8538170cba Metrics 2016-07-16 22:51:49 -04:00
76bce7c0ef Catch CommandException 2016-07-14 20:29:11 +10:00
ba568a3f60 Recover from invalid flag value 2016-07-14 00:28:46 +10:00
a43430b722 Fix NPE for null arg 2016-07-13 00:14:26 +10:00
e2c57cea52 . 2016-07-12 23:56:59 +10:00
ca776b2912 Fixes #1226 2016-07-12 22:12:14 +10:00
e859a7f56c Change to interact perm, not build 2016-07-11 20:27:25 +10:00
ad2db9b836 Merge pull request #1245 from manuelgu/fix/CentreCenterName
Add additional alias for /p middle
2016-07-10 22:58:54 +10:00
279084b043 Add additional alias for /p middle
http://grammarist.com/spelling/center-centre/
2016-07-09 09:18:55 +02:00
8b0e59209c Remove getServerName() 2016-07-05 23:43:08 -04:00
ca8b82dcbe Version Bump 2016-07-05 23:39:38 -04:00
cf5d2a5e86 Entity Fix and Gradle changes 2016-07-01 17:13:49 -04:00
b9ad75ad84 Add teleport flag 2016-06-29 21:22:55 +10:00
185352d3cf Fixes #1229 2016-06-29 15:23:10 +10:00
f4fe762135 * 2016-06-28 20:21:50 +10:00
06682b18a5 Fix compile
Recover on unknown command error
Fixes #1224
Close #1213 (fixed elsewhere)
Fixes #1212
2016-06-28 19:55:51 +10:00
f8e97f14d6 Fix end crystal spawn cap 2016-06-28 02:03:23 +10:00
a579df00db Merge remote-tracking branch 'origin/master' 2016-06-27 10:14:28 -04:00
29a0b68dcb Fix currently online for seen info. 2016-06-27 23:59:38 +10:00
d2581bf38b Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared 2016-06-27 09:58:17 -04:00
817a5bc16e Various
Fix compatibility with bukkit 1.5
Recover on failed fancy message initialization
Fix /2 remove *
2016-06-27 18:38:14 +10:00
047f9a75b9 Fix #1222 2016-06-27 17:45:19 +10:00
96d0bb0e5e bump pom version 2016-06-26 17:08:54 +10:00
7da0b9877f Fixes #1221 (the NPE at least) 2016-06-26 17:07:46 +10:00
f20ef15774 Revert creature spawn message + change expire to seen 2016-06-26 04:30:12 +10:00
3a973342ae Merge remote-tracking branch 'origin/master' 2016-06-24 10:59:18 -04:00
6e25aab51f Cleanup some docs. 2016-06-24 10:56:38 -04:00
a49492aae3 Fix roadregen 2016-06-24 16:16:22 +10:00
dbe965e901 init script engine on get 2016-06-24 15:41:34 +10:00
2c82d1106a Fixed kick message 2016-06-23 23:19:02 -04:00
5b9dc59abf Updates to docs, code style tweaks, and some code optimizations 2016-06-23 20:12:17 -04:00
b587b430b8 #1211 2016-06-24 05:30:26 +10:00
8fd2599686 Fixes #1211 2016-06-24 02:20:21 +10:00
56000d60e7 Just in case 2016-06-23 13:14:29 +10:00
1643399fc6 Alternatives for setowner none if the username is taken 2016-06-23 13:11:26 +10:00
532fd09800 Merge remote-tracking branch 'origin/master' 2016-06-22 23:10:15 -04:00
e6387419f7 Potential fix for plot biome (untested) 2016-06-23 13:09:56 +10:00
30d49880b6 Fix #1208 NPE 2016-06-22 16:31:04 -04:00
16d191db2c Fixes /plot kick * 2016-06-23 04:08:06 +10:00
7dc7714261 Update Gradle to 2.14 2016-06-22 12:31:25 -04:00
9e1f6d8748 Closes #1209 2016-06-22 13:33:32 +10:00
7fb2631421 Cast to string if necessary 2016-06-21 14:23:04 +10:00
718831e8e0 * 2016-06-21 14:10:20 +10:00
df4585a847 Check args for grant 2016-06-21 13:38:08 +10:00
88d8339cfd fix other NPE 2016-06-21 13:32:28 +10:00
e08db3d12b Check teleportation on command location prefix 2016-06-21 03:02:41 +10:00
2ff4e07919 Setup border on world creation 2016-06-21 01:13:09 +10:00
f6fec56677 Potential fix for terrain 3 worlds. 2016-06-21 00:29:39 +10:00
3fabfa10d7 Add liquid-flow flag 2016-06-20 22:48:04 +10:00
a2ca9a52ea Merge pull request #1205 from manuelgu/fix/deadlink
Remove dead link
2016-06-20 18:52:35 +10:00
e5e3600206 Why were these restricted to players? 2016-06-20 18:52:00 +10:00
7ad50b6314 Remove dead link 2016-06-20 10:49:40 +02:00
01d508edf4 Fix remove * 2016-06-20 15:08:56 +10:00
9fa28e1179 * 2016-06-20 01:50:43 +10:00
c3dd28caeb Fix clear done flag requirements 2016-06-20 01:49:35 +10:00
0888940307 bump version 2016-06-20 01:37:27 +10:00
ce7468e63a Fix economy NPE 2016-06-20 00:52:05 +10:00
f5e7d08ace Allow duplicates after 5s 2016-06-19 16:14:13 +10:00
3ce225c044 Bump version 2016-06-19 15:51:46 +10:00
c2f10a7065 Update desc for debugpaste 2016-06-19 13:44:14 +10:00
8512adf9d6 Fix for augmented 2016-06-19 13:01:30 +10:00
b2c885e8d1 Merge pull request #1197 from manuelgu/patch-1
Fix #1196
2016-06-19 00:15:20 +02:00
5eabf863d6 Fix #1196 2016-06-19 00:11:21 +02:00
cff30a1db4 Fix scripting initialization 2016-06-18 16:29:51 +10:00
ab51d27e49 Remove pointless thread dump 2016-06-18 15:01:42 +10:00
6375922808 I can't count + fix variable scope 2016-06-18 13:54:35 +10:00
29ce4af350 Fixes #987 and #299 (untested)
Example usage:
claim: 50*{arg}
2016-06-18 13:43:34 +10:00
3ced832b80 Fix biome stripes (whoops) 2016-06-18 13:15:50 +10:00
91c742c141 Fixes #590 2016-06-18 13:13:36 +10:00
232091454a Fix augmented 2016-06-18 12:44:56 +10:00
600d060b6e Fix sponge compile issue 2016-06-17 22:05:06 +10:00
081081b36e Fixes #1063 2016-06-17 15:42:23 +10:00
4319300b34 Fixes #1126 2016-06-17 13:46:13 +10:00
b2b90a8d17 Fixes #1064 2016-06-17 13:33:47 +10:00
480453b716 Various
Fixes #1177
Additional check for left click with milk on adult entity
Add setting for enabling persistent meta
Only set fly persistent meta if it differs from the current gamemode fly
mode.
2016-06-16 20:16:48 +10:00
28ad14500a Fixes #1172 2016-06-16 17:59:39 +10:00
2bbfec1a32 Fix load / flush queue before sending message 2016-06-16 17:31:02 +10:00
b2997b7c7b Don't send duplicate messages 2016-06-16 10:31:33 +10:00
472aadcd01 Add suggestion for flags when invalid flag name was given :] 2016-06-16 02:30:16 +02:00
5b103d49c0 Fixes #1171 2016-06-16 02:08:01 +02:00
ae5e15e434 Fix invalid record type error 2016-06-13 15:05:38 -04:00
341967cbfc Reclassify armor stand as vehicle 2016-06-13 15:35:33 +10:00
b238bdbd21 Fix armor stand / hangings being considered vehicles 2016-06-13 15:32:13 +10:00
4f0ede646e Chat / Merge blocks placer / generator 2016-06-13 14:47:50 +10:00
506455ae40 Remove debug 2016-06-12 15:33:56 +10:00
15c7957d0e Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared 2016-06-12 15:27:23 +10:00
6165469e76 Fix scripting 2016-06-12 15:26:58 +10:00
a7087f314f Merge remote-tracking branch 'origin/master' 2016-06-11 19:25:27 -04:00
0cfef63376 Fix backwards compatibility 2016-06-11 19:25:13 -04:00
bfd9b53555 Update pom 2016-06-11 11:58:11 +10:00
5bdb2263dc CheckStyle code tweaks 2016-06-10 14:04:55 -04:00
76bcb76905 Merge remote-tracking branch 'origin/master' 2016-06-10 13:31:41 -04:00
93deebf4ca 1.10 fixes 2016-06-10 13:31:28 -04:00
482f4d6815 Modify Setting and Storage class names. 2016-06-10 13:00:34 -04:00
0d47e4599f Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared 2016-06-09 18:06:08 +10:00
f41c7dc1f6 Fix NPE 2016-06-09 18:06:00 +10:00
8fe381d098 Fix SpongeCommand 2016-06-08 19:06:07 -04:00
12c01760a6 Tweaks and small memory improvement. 2016-06-06 01:43:06 -04:00
880e084006 Register expiry tasks 2016-06-06 12:47:54 +10:00
f1f6b2781e Fix INSTABREAK flag 2016-06-06 06:34:05 +10:00
237a0d8b6b Always cache * uuid 2016-06-05 20:11:02 +10:00
a1c722aa9e Fix player location/current plot 2016-06-05 20:03:05 +10:00
960ad50070 Use DBFunc instead of dbManager 2016-06-05 19:54:33 +10:00
7d44850bb0 Mask getBlock 2016-06-05 19:46:52 +10:00
7427d83ae2 final primitives are final 2016-06-05 19:39:51 +10:00
48cf381ed6 * 2016-06-05 18:57:11 +10:00
0114dd7558 Fix convert 2016-06-05 18:42:34 +10:00
48382e0c4e Remove null version from storage 2016-06-05 18:23:24 +10:00
ce23ad5615 Fix NPE 2016-06-05 18:07:41 +10:00
0b1153da21 Include other config files in DebugPaste 2016-06-05 17:43:40 +10:00
386157edc1 fix reserved flags 2016-06-05 17:35:44 +10:00
b7a8c8ecd6 Don't need this 2016-06-05 17:33:06 +10:00
951a6b82a2 simplify config / multiple expiry tasks / block cache fix 2016-06-05 17:28:43 +10:00
70aaa984e2 Documentation and Flag Changes. 2016-06-04 17:19:37 -04:00
17ff6a7e1d Merge pull request #1157 from MisterErwin/master
Fixed invalid condition
2016-06-05 04:34:47 +10:00
281f60a4ef Fixed invalid condition 2016-06-04 20:26:32 +02:00
ca5d3a818b PlotBlock cache / events / flags 2016-06-04 06:20:13 +10:00
f84766074e Fixes #1145 2016-06-04 03:36:39 +10:00
7dba332455 Debug a player is added to the known list. 2016-06-03 11:17:08 -04:00
b4707c94c4 Fix #579
Also tweaks to deprecation for development purposes.
2016-06-03 10:57:25 -04:00
0147690eba Make Sponge compile
It doesn't work but it allows the project to compile.
2016-06-02 19:38:35 -04:00
cee970e3d9 Tweaked some things 2016-06-02 13:42:32 -04:00
da58c7b411 Beautify code 2016-06-02 11:38:47 -04:00
8e306a92e3 Condense HttpUtil 2016-06-02 09:59:54 -04:00
89c4ce24ef Merge branch 'fix/forcefieldflag' of https://github.com/manuelgu/PlotSquared into manuelgu-fix/forcefieldflag 2016-06-02 09:52:30 -04:00
e6433a24ab Fix grow flags 2016-06-02 00:33:50 -04:00
f21d159911 Various fixes and tweaks. 2016-06-01 16:50:35 -04:00
042d8950ee Fix #1139 2016-05-29 20:48:14 -04:00
8d6565c32c Fix NPE 2016-05-29 19:38:31 +02:00
def33bc9ad Fix IntellectualSites/PlotSquared#1140 2016-05-29 11:59:16 +02:00
53e4b728a6 Merge remote-tracking branch 'origin/master' 2016-05-28 22:38:10 -04:00
4af846967c Fix #958 2016-05-28 22:37:56 -04:00
9ae4f02205 Fix forcefield flag 2016-05-28 01:16:01 +02:00
85055320c2 Merge pull request #1134 from manuelgu/feature/componentevent
[WIP] Implement PlotComponentSetEvent
2016-05-28 09:13:04 +10:00
d7b2881778 Don't * import 2016-05-28 01:12:05 +02:00
a7c965c6b0 Merge branch 'feature/componentevent' of https://github.com/manuelgu/PlotSquared into feature/componentevent 2016-05-28 01:09:25 +02:00
ec4839ec3f Move event calling to Plot class 2016-05-28 01:09:13 +02:00
b5cc6eeb0c Merge remote-tracking branch 'origin/master'
# Conflicts:
#	Sponge/src/main/java/com/plotsquared/sponge/SpongeMain.java
2016-05-28 08:45:35 +10:00
4078f0708b Proper javadoc for event 2016-05-28 00:29:27 +02:00
28a5c9f597 Remove pre-init logging 2016-05-28 02:01:50 +10:00
604f62dbd3 Remove dumb log statement 2016-05-27 11:10:36 -04:00
6c40ed7718 Fix Titles 2016-05-27 10:54:06 -04:00
e615fb4c44 Merge remote-tracking branch 'origin/master' 2016-05-26 09:19:50 -04:00
cc2d99849b Optimizations and javadoc tweaks 2016-05-26 09:19:38 -04:00
ceb8fb9fa3 Implement PlotComponentSetEvent 2016-05-25 21:49:55 +02:00
d44ca23abd Minor change to issue template (#1132) 2016-05-25 15:14:16 -04:00
ef60aeb017 Minor change to issue template 2016-05-25 20:54:26 +02:00
88ad051637 Direction/chance for bo3 2016-05-26 04:14:47 +10:00
465f7f4504 Tweaks and doc updates. 2016-05-24 22:08:45 -04:00
83f664129f Fixes #1130 2016-05-23 17:27:40 +10:00
a2a43816ad *And this 2016-05-23 04:41:25 +10:00
7bdcde6d24 Why was this made private? 2016-05-23 04:12:11 +10:00
89442a0e77 Fix visit 2016-05-22 07:13:59 +10:00
b8afbe8a00 Optimize auto trim + command cost/confirmation 2016-05-22 05:29:27 +10:00
e2182260d9 Fix Sponge Errors 2016-05-21 12:55:06 -04:00
6f26e42251 Fix Sponge Errors 2016-05-21 12:54:50 -04:00
13b7a798e6 ignored exception 2016-05-21 11:54:00 -04:00
8af30667e4 ignored exception 2016-05-21 11:18:35 -04:00
4bd83ab298 Logger changes 2016-05-21 11:16:21 -04:00
7ae5042c32 Recover from bad data file
Closes #1122
2016-05-22 01:16:04 +10:00
3ea2d06e70 Closes #1124 2016-05-22 01:11:27 +10:00
4ceb54b566 Add logger 2016-05-22 00:47:14 +10:00
dc4776d16b Sponge changes. 2016-05-21 10:39:06 -04:00
b51d659ff9 Merge remote-tracking branch 'origin/master' 2016-05-20 20:29:32 -04:00
1768943360 Register flags 2016-05-20 20:29:16 -04:00
6b1298a5e6 *Fix version check 2016-05-20 05:10:46 +10:00
b125ef6668 Add git revision hash to version 2016-05-20 03:32:35 +10:00
82e162ae00 * 2016-05-20 03:29:51 +10:00
5665e9b709 Fix merging sometimes not removing intersection 2016-05-20 03:25:45 +10:00
6bad640cec Fixes #1037 2016-05-19 18:53:07 +10:00
7873bcf592 Fixes #1102 2016-05-19 18:28:06 +10:00
75c7fe969c Fixes #1008 2016-05-19 18:20:23 +10:00
1df9ae77ab Fixes #1111 2016-05-19 18:13:37 +10:00
78796ca7b4 Fixes #1117 2016-05-19 18:09:12 +10:00
1ece792e2b Create parent directory for bo3 2016-05-18 16:35:37 +10:00
1b9c92fd4a Fix #1067 2016-05-17 21:52:36 -04:00
18e3a7553e Fix #1085
Fix #1085
2016-05-15 22:05:52 -04:00
64f3e8f79b Fixes #1116 2016-05-15 01:54:12 +10:00
c70c2283a2 Recover from failed event registration 2016-05-14 23:50:43 +10:00
4b962c35ab Merge pull request #1118 from manuelgu/apilocationremoval
Remove unused API Location that got printed on startup
2016-05-14 21:46:20 +10:00
72096db8d6 Remove unused API Location that got printed on startup 2016-05-14 12:33:52 +02:00
2039cb2891 Merge pull request #1112 from manuelgu/stuffnthings
Method renaming, util class and logic change
2016-05-14 15:04:11 +10:00
a5a001130c Fetch latest vesion on command
PS.get().update would return the URL of the latest update at the time
the server was started. Not everybody is restarting their servers daily
so it might end up in people not noticing an update in a long while
2016-05-13 19:09:40 +02:00
c1bc3dfc29 Add HttpUtil utility class 2016-05-13 19:07:56 +02:00
7701e7f05f Beautify listing of plot areas 2016-05-13 19:05:50 +02:00
2c0743b7e9 Proper method name 2016-05-13 19:04:55 +02:00
00340d5154 Important fix 2016-05-14 01:13:08 +10:00
d47eeff23b Cleaning and Fix #1108 2016-05-12 18:00:38 -04:00
0958b57e46 Tidy code. 2016-05-12 17:09:35 -04:00
7947c3fdd7 Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared 2016-05-12 15:43:44 -04:00
0095af0ce5 Flag info 2016-05-13 03:38:32 +10:00
dee8072d83 Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared
# Conflicts:

#	Bukkit/src/main/java/com/plotsquared/bukkit/listeners/PlayerEvents.java

#	Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_9.java
2016-05-13 03:04:43 +10:00
63c7041a34 Flag tweaks 2016-05-13 02:55:57 +10:00
63472ebeaf Merge branch '3.3.4'
# Conflicts:
#	Bukkit/src/main/java/com/plotsquared/bukkit/util/SendChunk.java
2016-05-11 16:45:17 -04:00
d5cf81be5c 1.9.4 compatibility. 2016-05-11 12:11:46 -04:00
1db3d1aa72 Start 3.3.4 work to support 1.9.4 2016-05-11 11:16:38 -04:00
a4647b05e2 Fix #1011 2016-05-10 14:24:02 -04:00
3be0f74498 Fix #1098 2016-05-10 13:41:59 -04:00
e63b436edd Possible build everywhere fix. 2016-05-06 22:05:31 -04:00
1535c5e2f5 Fix test file 2016-05-05 13:41:11 -04:00
894524f998 Fix test file 2016-05-05 13:39:54 -04:00
8925c66b6e Fix file name 2016-05-05 13:19:15 -04:00
e4350feb2a Fixed missing type change 2016-05-05 13:17:17 -04:00
5d8492b675 Fixes cast exception 2016-05-05 13:13:55 -04:00
421203a27d Bug Fix and Cleanup 2016-04-29 18:14:12 -04:00
8f3d35bca3 Bug Fix and Cleanup 2016-04-28 16:38:51 -04:00
669359cd37 General changes 2016-04-26 10:14:22 -04:00
2c16c767e7 Fix flag values being loaded as strings 2016-04-26 08:40:52 -04:00
d8849f718c Fix plotworld get 2016-04-26 09:32:16 +10:00
8c56affb2f Fix for paint 2016-04-25 03:58:47 +10:00
1bce69d288 Merge flags to master 2016-04-22 23:54:53 -04:00
c266b1a428 Merge flags to master 2016-04-22 23:54:19 -04:00
e57af63af4 Possible remove fix. 2016-04-22 23:46:16 -04:00
3e4dbe0fbf fix compile error 2016-04-22 23:46:16 -04:00
74ed10c376 Completed and ready to test 2016-04-22 23:46:16 -04:00
aaf9511673 Start implementing new Flag system. 2016-04-22 23:46:16 -04:00
d3dd88eb8d Fixes #1062 2016-04-22 23:45:19 -04:00
9b22f38ff0 Fix plot download/done 2016-04-22 23:45:19 -04:00
10bf03f81b Disable colored chat 2016-04-22 23:45:19 -04:00
7c12a20a2b perm requirement for add/trust * 2016-04-22 23:45:19 -04:00
40e063e702 Fixes #1050 2016-04-22 23:45:19 -04:00
1c04b1a0e0 Fixes #1062 2016-04-19 15:32:31 +10:00
02d17b363d Fix plot download/done 2016-04-17 03:55:55 +10:00
d34abf4f02 Disable colored chat 2016-04-17 03:11:05 +10:00
30a2c5d881 perm requirement for add/trust * 2016-04-13 03:35:14 +10:00
76c3879c1f Fixes #1050 2016-04-13 02:41:40 +10:00
c2c20ff189 Merge remote-tracking branch 'remotes/origin/master' 2016-04-11 17:04:52 -04:00
588f5d7ebc Fixes #1047 2016-04-09 22:48:27 +10:00
9ba3b06854 change priority to low 2016-04-07 20:05:02 +10:00
45b6950111 Fixes chat error / plot deny * 2016-04-07 03:33:49 +10:00
8b10b7109c Merge remote-tracking branch 'origin/master'
# Conflicts:

#	Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_8_3.java

#	Bukkit/src/main/java/com/plotsquared/bukkit/util/block/FastQueue_1_9.java
2016-04-07 02:33:23 +10:00
f7810860da Re-add WorldEdit check 2016-04-07 02:14:50 +10:00
4dcac29028 Weaken Declaration 2016-04-06 00:17:30 -04:00
d49de5297b Tweaks 2016-04-05 23:50:04 -04:00
c5282b29b2 Merge remote-tracking branch 'origin/master' 2016-04-05 19:10:57 -04:00
3df772aa4e Fixed #852 and small changes
Hid updater error when debugging is not enabled.
Javadoc changes
2016-04-05 19:10:26 -04:00
de97028a20 Merge pull request #1045 from IntellectualSites/3.4.0 2016-04-05 12:55:06 -04:00
9c81dfa5c3 Cleanup and Optimizations
Abstracted TitleManagers
Removed a lot of Statics.
ETC.
2016-04-05 12:53:40 -04:00
fab60a0d53 Fix schematic on claim/auto 2016-04-05 11:07:37 +10:00
1f32707ec2 Fix populate offset for older versions 2016-04-05 10:08:10 +10:00
95c9fd01dd Merged 2016-04-04 12:49:11 -04:00
3c5e7a1509 version 2016-04-04 19:35:47 +10:00
6ea1383027 Merge pull request #1042 from manuelgu/feature/tpondeath
Add teleport on death feature
2016-04-04 19:35:44 +10:00
6ab3a029b2 Add teleport on death feature 2016-04-04 11:31:15 +02:00
b1cb6c0f57 Merge pull request #1038 from manuelgu/feature/bypassbreakbedrock
Add bypass permission for breaking blocks at y0
2016-04-04 18:46:57 +10:00
c69c4dd2e1 It actually is tested 2016-04-04 00:11:32 +02:00
4da38a6f9c Add bypass permission to breaking blocks at y0 2016-04-04 00:09:46 +02:00
dffa00858d More than 2 lines 2016-04-02 17:15:36 +11:00
4ebd778c62 Optimizations and a purge fix 2016-04-02 01:30:26 -04:00
8243e0118a Optionals introduced, code cleaned, potential purge fix 2016-04-01 19:14:46 -04:00
3edfd39af9 Bump Version 2016-04-01 09:30:13 -04:00
b7ebde874f Clean gradle target directory 2016-03-31 21:27:29 -04:00
8978d3b9a7 Update Gradle to 2.12 2016-03-31 16:45:07 -04:00
b909792d6a typo in disable titles 2016-04-01 06:54:28 +11:00
4a7112a0a5 Various
Add some 1.9 blocks to chest content with schematic paste
Restructure tileentity placement from schematic (will soon add signs
etc)
Prepare for release 3.3.3
2016-04-01 04:23:26 +11:00
edd18a7178 Various
- Fix some block change issues (for some reason sending a chunk would
sometimes reset any recent changes)
- Send chunk changes for relight command
- Have kick cmd kick the player from the server if they are kicked from
the spawn plot
- Plot size checks for downloading
- Fix some potential integer overflow issues for large plots (>64K x
64K)
- Fix some edge cases for plot move/copy
2016-03-31 20:49:00 +11:00
dbdd9f9e5a Merge pull request #1026 from manuelgu/feature/fixes
Fixes and cleanup
2016-03-31 20:42:31 +11:00
25dfc34695 Comma-separate plot area list again 2016-03-30 15:25:25 +02:00
ea17ba8e46 Fix sponge conflicts 2016-03-30 15:09:00 +02:00
6fc8bf587b Comma-separate list of plot worlds 2016-03-30 14:43:16 +02:00
429fed2ab3 Fix target command
Threw an exception when you didnt pass an argument
2016-03-30 14:43:04 +02:00
510b9a47dc Formatting 2016-03-30 14:42:41 +02:00
44e11e9c6b Add command to list all available scripts
Additional debugexec subcommand
2016-03-30 14:42:34 +02:00
95d03e878c Cancel potion throw 2016-03-30 13:41:13 +11:00
dca2696782 Forgot wall height 2016-03-30 13:26:23 +11:00
1e93398fd8 Cancel lingering potion splash
Cancelling the event still doesn't stop the animation.
2016-03-30 13:23:31 +11:00
1f6ad47a79 Merge remote-tracking branch 'origin/master'
# Conflicts:
#	Bukkit/src/main/java/com/intellectualcrafters/plot/api/PlotAPI.java
2016-03-30 12:12:19 +11:00
312ad4c48c fix index 2016-03-30 12:09:55 +11:00
31d346a587 Minor code cleanup
Plus an optimization
2016-03-29 17:00:07 -04:00
6007f040cd OCD 2016-03-29 15:47:59 -04:00
d0622eb87d PlotAPI doc and code cleaning 2016-03-29 14:35:40 -04:00
6ebfd426c3 Just "height" would have made more sense 2016-03-30 05:14:51 +11:00
bbe43f782c Fix nested command configuration 2016-03-30 04:47:47 +11:00
560ebf412b Relight command 2016-03-30 04:34:48 +11:00
df630f9be1 Remove outdated copyright notice at the top of each file
- No license is the same as all rights reserved
- There's already a license at the root of the project
- The message was not in most files. easier to remove it
- Support link isn't valid
- No longer just the bukkit API
2016-03-30 02:50:13 +11:00
578e884be7 Merge pull request #1025 from manuelgu/master
Cleanup
2016-03-29 20:08:33 +11:00
22f56d4da6 Remove ChatColor
Sponge support
2016-03-29 10:57:27 +02:00
745f9c4858 Buy 2016-03-29 19:52:57 +11:00
5f2856e0ea Cleanup
Consistent use of String[] instead of String...
Removed unused variables
2016-03-29 10:47:56 +02:00
d9c6d04b46 Debug PlotMe conversion (temporary) 2016-03-29 19:13:48 +11:00
8244086840 Merge pull request #1024 from dmodoomsirius/master
Revert "have clean help delete the output directory"
2016-03-29 19:13:00 +11:00
e282998765 Revert "have clean help delete the output directory"
This reverts commit afa9935a7a.
2016-03-29 04:11:25 -04:00
bd633c0150 Merge pull request #1023 from dmodoomsirius/master
Give the ability to clean the output directory
2016-03-29 19:00:57 +11:00
5ec6bc62ca Merge branch 'master' of https://github.com/dmodoomsirius/PlotSquared 2016-03-29 03:59:42 -04:00
afa9935a7a have clean help delete the output directory
to make things nice and clean
2016-03-29 03:59:12 -04:00
512ae38392 Fix plot kick args 2016-03-29 18:57:35 +11:00
19ef76de33 Oh, and this 2016-03-29 18:51:10 +11:00
638f267498 Remove required args for visit 2016-03-29 18:48:07 +11:00
bc8becae8e Check for null 2016-03-29 18:47:04 +11:00
6f9af04274 Cleanup BukkitChunkManager 2016-03-29 18:44:04 +11:00
75a70bcff4 Merge pull request #1022 from EvilOlaf/patch-1
Missing brackets
2016-03-29 18:11:12 +11:00
30043fd1c1 Missing brackets
very (VERY!) minor change ^^
2016-03-29 09:10:24 +02:00
ef4438889b Fix plot move 2016-03-29 18:09:40 +11:00
9bd3f2cbfd Fix plot list add 2016-03-29 17:56:48 +11:00
eed8cbec5a Fixes #1015 2016-03-29 17:39:29 +11:00
5f8a55568c Fix plot rate categories 2016-03-29 17:21:58 +11:00
5275d4ec62 Fix "cleanup" breaking plugin again 2016-03-29 17:13:19 +11:00
30dc20b3b3 Fix "Fixes #1015" not resetting the home location.
Resetting involves clearing the current value i.e. so it respects
whatever is set in the config, if that value is changed.
2016-03-29 17:06:58 +11:00
32ba55baf5 Code cleanup and Optimizations 2016-03-29 00:56:44 -04:00
49d18b9229 Code cleanup 2016-03-28 23:26:44 -04:00
a8fd6d00d0 Sorry for the versioning confusion 2016-03-28 23:23:56 -04:00
b1fa258688 Code cleanup 2016-03-28 19:30:55 -04:00
874da8c5bc Merge pull request #1019 from manuelgu/master
Fixes #1018
2016-03-28 18:17:45 -04:00
76e2b1f416 Code cleanup
maybe a bug fix or two
2016-03-28 17:31:40 -04:00
83fa310fbb Fix ArrayIndexOutOfBoundsExceptions
Occured for /plot trust and /plot add
2016-03-28 23:18:29 +02:00
8d4f042abc Cleanup of code 2016-03-28 13:28:21 -04:00
feee63b3af Fix DebugLoadTest 2016-03-28 13:02:20 -04:00
c4f5905252 Merge pull request #1016 from manuelgu/master
Fixes #1015
2016-03-28 11:25:33 -04:00
c2e48bb95b Fixes #1015 2016-03-28 16:27:32 +02:00
d9c0ec27b0 Fixes #774 2016-03-28 23:04:08 +11:00
dcd1a50a0c default tab completion + plot chat for merged plots 2016-03-28 22:52:29 +11:00
b6bdb02fa2 Merge pull request #1012 from manuelgu/master
Update Plugin command to show correct versions
2016-03-28 07:23:07 -04:00
8f0de80755 Update Plugin command to show correct version
Not using PS.get().update but rather reading from the GitHub releases. Can be changed if needed/wanted
2016-03-28 11:29:58 +02:00
978be89e52 Fix bug causing the Updater to not work. 2016-03-27 23:48:24 -04:00
93ef066d7b 3.3.3-SNAPSHOT Beginning
Sponge Gradle Changes
2016-03-27 18:55:57 -04:00
450 changed files with 26636 additions and 22423 deletions

View File

@ -7,6 +7,6 @@
Make sure you've completed the following steps (put an X between of brackets):
- [] Include `/plot debugpaste`
- [] Made sure there aren't duplicates of this report [(Use Search)](https://github.com/IntellectualSites/PlotSquared/issues)
- [] Made sure you're using an updated version of PlotSquared
- [] Made sure there aren't duplicates of this report [(Use Search)](https://github.com/IntellectualSites/PlotSquared/issues?utf8=%E2%9C%93&q=is%3Aissue)
- [] Made sure you're using an up-to-date version of PlotSquared
- [] Made sure the bug/error isn't caused by any other plugin

8
.gitignore vendored
View File

@ -1,5 +1,4 @@
### Others ###
*.bat
*.cmd
*.sh
*.prefs
@ -131,4 +130,9 @@ local.properties
# STS (Spring Tool Suite)
.springBeans
/target/
/target/
Nukkit/build/classes/
Nukkit/build/dependency-cache/
checkstyle.xml
classes/
p2error.txt

View File

@ -1,8 +1,16 @@
repositories {
maven {url "https://hub.spigotmc.org/nexus/content/groups/public/"}
maven { url = "https://oss.sonatype.org/content/repositories/snapshots/"}
maven {url "http://nexus.hc.to/content/repositories/pub_releases"}
mavenLocal()
}
dependencies {
compile project(':Core')
compile 'org.bukkit:bukkit:1.9-R0.1-SNAPSHOT'
compile 'org.mcstats.bukkit:metrics:R7'
compile 'net.milkbowl.vault:VaultAPI:1.5'
compile 'org.spigotmc:spigot-api:1.11-R0.1-SNAPSHOT'
compile("net.milkbowl.vault:VaultAPI:1.6") {
exclude module: 'bukkit'
}
}
sourceCompatibility = 1.7
@ -17,22 +25,21 @@ processResources {
)
}
}
apply plugin: 'com.github.johnrengelman.shadow'
// We only want the shadow jar produced
jar.enabled = false
shadowJar {
dependencies {
include(dependency(':Core'))
include(dependency('org.mcstats.bukkit:metrics:R7'))
}
relocate 'org.mcstats', 'com.plotsquared.stats'
relocate('org.mcstats', 'com.plotsquared.stats')
archiveName = "${parent.name}-${project.name}-${parent.version}.jar"
destinationDir = file '../target'
}
shadowJar.doLast {
task ->
ant.checksum file: task.archivePath
}
build.dependsOn(shadowJar);
build.dependsOn(shadowJar);

View File

@ -1,32 +1,12 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.api;
import com.intellectualcrafters.configuration.file.YamlConfiguration;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.commands.SubCommand;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.flag.AbstractFlag;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.flag.Flags;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotId;
@ -34,68 +14,53 @@ import com.intellectualcrafters.plot.object.PlotManager;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.SchematicHandler;
import com.intellectualcrafters.plot.util.SetQueue;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.util.block.GlobalBlockQueue;
import com.intellectualcrafters.plot.uuid.UUIDWrapper;
import com.plotsquared.bukkit.util.BukkitUtil;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
/**
* PlotSquared API<br>
* <br>
* @version API 3.3.1
* <br>
* Useful classes:<br>
* @see BukkitUtil
* @see PlotPlayer
* @see Plot
* @see com.intellectualcrafters.plot.object.Location
* @see PlotArea
* @see PS
* PlotSquared API.
*
* <p>Useful classes:
* <ul>
* <li>{@link BukkitUtil}</li>
* <li>{@link PlotPlayer}</li>
* <li>{@link Plot}</li>
* <li>{@link com.intellectualcrafters.plot.object.Location}</li>
* <li>{@link PlotArea}</li>
* <li>{@link PS}</li>
* </ul>
* @version 3.3.3
*/
public class PlotAPI {
/**
* Permission that allows for admin access, this permission node will allow the player to use any part of the
* plugin, without limitations.
* @deprecated Use C.PERMISSION_ADMIN instead
* Deprecated, does nothing.
* @param plugin not needed
* @deprecated Not needed
*/
@Deprecated
public static final String ADMIN_PERMISSION = C.PERMISSION_ADMIN.s();
public PlotAPI(JavaPlugin plugin) {}
public PlotAPI(){}
/**
* @deprecated Use new PlotAPI() instead
*/
@Deprecated
public PlotAPI(JavaPlugin plugin) {
}
/**
* @see PS
*
* @deprecated Use this class if you just want to do a few simple things.<br>
* - It will remain stable for future versions of the plugin
* - The PlotPlayer and Plot class should be considered relatively safe
* - For more advanced/intensive tasks you should consider using other classes
*
*
*/
@Deprecated
public PlotAPI() {
}
/**
* Get all plots
* Get all plots.
*
* @return all plots
*
@ -106,7 +71,7 @@ public class PlotAPI {
}
/**
* Return all plots for a player
* Return all plots for a player.
*
* @param player Player, whose plots to search for
*
@ -117,7 +82,7 @@ public class PlotAPI {
}
/**
* Add a plot world
* Add a plot world.
*
* @param plotArea Plot World Object
* @see PS#addPlotArea(PlotArea)
@ -127,6 +92,7 @@ public class PlotAPI {
}
/**
* Returns the PlotSquared configurations file.
* @return main configuration
*
* @see PS#config
@ -136,6 +102,7 @@ public class PlotAPI {
}
/**
* Get the PlotSquared storage file.
* @return storage configuration
*
* @see PS#storage
@ -145,8 +112,7 @@ public class PlotAPI {
}
/**
* Get the main class for this plugin <br> - Contains a lot of fields and methods - not very well organized <br>
* Only use this if you really need it
* Get the main class for this plugin. Only use this if you really need it.
*
* @return PlotSquared PlotSquared Main Class
*
@ -157,16 +123,18 @@ public class PlotAPI {
}
/**
* ChunkManager class contains several useful methods<br>
* - Chunk deletion<br>
* - Moving or copying regions<br>
* - plot swapping<br>
* - Entity tracking<br>
* - region regeneration<br>
* ChunkManager class contains several useful methods.
* <ul>
* <li>Chunk deletion</li>
* <li>Moving or copying regions</li>
* <li>Plot swapping</li>
* <li>Entity Tracking</li>
* <li>Region Regeneration</li>
* </ul>
*
* @return ChunkManager
*
* @see com.intellectualcrafters.plot.util.ChunkManager
* @see ChunkManager
*/
public ChunkManager getChunkManager() {
return ChunkManager.manager;
@ -174,18 +142,19 @@ public class PlotAPI {
/**
* Get the block/biome set queue
* @return SetQueue.IMP
* @return GlobalBlockQueue.IMP
*/
public SetQueue getSetQueue() {
return SetQueue.IMP;
public GlobalBlockQueue getBlockQueue() {
return GlobalBlockQueue.IMP;
}
/**
* UUIDWrapper class has basic methods for getting UUIDS (it's recommended to use the UUIDHandler class instead)
* UUIDWrapper class has basic methods for getting UUIDS. It's recommended
* to use the UUIDHandler class instead.
*
* @return UUIDWrapper
*
* @see com.intellectualcrafters.plot.uuid.UUIDWrapper
* @see UUIDWrapper
*/
public UUIDWrapper getUUIDWrapper() {
return UUIDHandler.getUUIDWrapper();
@ -197,7 +166,7 @@ public class PlotAPI {
*
* @return FlagManager
*
* @see com.intellectualcrafters.plot.flag.FlagManager
* @deprecated Use {@link FlagManager} directly
*/
@Deprecated
public FlagManager getFlagManager() {
@ -206,11 +175,9 @@ public class PlotAPI {
/**
* Do not use this. Instead use MainUtil.[method] in your code.
* - Basic plot management stuff
*
* @return MainUtil
*
* @see MainUtil
* @deprecated Use {@link MainUtil} directly
*/
@Deprecated
public MainUtil getMainUtil() {
@ -219,29 +186,30 @@ public class PlotAPI {
/**
* Do not use this. Instead use C.PERMISSION_[method] in your code.
* - Basic permission management stuff
*
* @return Array of strings
*
* @see com.intellectualcrafters.plot.util.Permissions
* @see Permissions
* @deprecated Use {@link C} to list all the permissions
*/
@Deprecated
public String[] getPermissions() {
ArrayList<String> perms = new ArrayList<>();
for (C c : C.values()) {
if ("static.permissions".equals(c.getCategory())) {
perms.add(c.s());
for (C caption : C.values()) {
if ("static.permissions".equals(caption.getCategory())) {
perms.add(caption.s());
}
}
return perms.toArray(new String[perms.size()]);
}
/**
* SchematicHandler class contains methods related to pasting, reading and writing schematics
* SchematicHandler class contains methods related to pasting, reading
* and writing schematics.
*
* @return SchematicHandler
*
* @see com.intellectualcrafters.plot.util.SchematicHandler
* @see SchematicHandler
*/
public SchematicHandler getSchematicHandler() {
return SchematicHandler.manager;
@ -251,8 +219,7 @@ public class PlotAPI {
* Use C.[caption] instead
*
* @return C
*
* @see com.intellectualcrafters.plot.config.C
* @deprecated Use {@link C}
*/
@Deprecated
public C[] getCaptions() {
@ -260,15 +227,17 @@ public class PlotAPI {
}
/**
* Get the plot manager for a world. - Most of these methods can be accessed through the MainUtil
* Get the plot manager for a world. Most of these methods can be accessed
* through the MainUtil.
*
* @param world Which manager to get
* @param world the world to retrieve the manager from
*
* @return PlotManager
*
* @see com.intellectualcrafters.plot.object.PlotManager
* @see PlotManager
* @see PS#getPlotManager(Plot)
*/
@SuppressWarnings("deprecation")
@Deprecated
public PlotManager getPlotManager(World world) {
if (world == null) {
@ -277,23 +246,28 @@ public class PlotAPI {
return getPlotManager(world.getName());
}
/**
* Get a list of PlotAreas in the world.
* @param world The world to check for plot areas
* @return A set of PlotAreas
*/
public Set<PlotArea> getPlotAreas(World world) {
if (world == null) {
return new HashSet<>();
return Collections.emptySet();
}
return PS.get().getPlotAreas(world.getName());
}
/**
* Get the plot manager for a world. - Contains useful low level methods for plot merging, clearing, and
* tessellation
* Get the plot manager for a world. Contains useful low level methods for
* plot merging, clearing, and tessellation.
*
* @param world
* @param world The world
*
* @return PlotManager
*
* @see PS#getPlotManager(Plot)
* @see com.intellectualcrafters.plot.object.PlotManager
* @see PlotManager
*/
@Deprecated
public PlotManager getPlotManager(String world) {
@ -310,16 +284,18 @@ public class PlotAPI {
}
/**
* Get the settings for a world (settings bundled in PlotArea class) - You will need to downcast for the specific
* settings a Generator has. e.g. DefaultPlotWorld class implements PlotArea
* Get the settings for a world (settings bundled in PlotArea class). You
* will need to downcast for the specific settings a Generator has. e.g.
* DefaultPlotWorld class implements PlotArea
*
* @param world (to get settings of)
* @param world The World
*
* @return PlotArea class for that world ! will return null if not a plot world world
* @return The {@link PlotArea} for the world or null if not in plotworld
*
* @see #getPlotAreas(World)
* @see com.intellectualcrafters.plot.object.PlotArea
* @see PlotArea
*/
@SuppressWarnings("deprecation")
@Deprecated
public PlotArea getWorldSettings(World world) {
if (world == null) {
@ -329,14 +305,14 @@ public class PlotAPI {
}
/**
* Get the settings for a world (settings bundled in PlotArea class)
* Get the settings for a world.
*
* @param world (to get settings of)
* @param world the world to retrieve settings from
*
* @return PlotArea class for that world ! will return null if not a plot world world
* @return The {@link PlotArea} for the world or null if not in plotworld
*
* @see PS#getPlotArea(String, String)
* @see com.intellectualcrafters.plot.object.PlotArea
* @see PlotArea
*/
@Deprecated
public PlotArea getWorldSettings(String world) {
@ -358,21 +334,20 @@ public class PlotAPI {
/**
* Send a message to a player.
*
* @param player Player that will receive the message
* @param c (Caption)
* @param player the recipient of the message
* @param caption the message
*
* @see MainUtil#sendMessage(PlotPlayer, C, String...)
* com.intellectualcrafters.plot.config.C, String...)
*/
public void sendMessage(Player player, C c) {
MainUtil.sendMessage(BukkitUtil.getPlayer(player), c);
public void sendMessage(Player player, C caption) {
MainUtil.sendMessage(BukkitUtil.getPlayer(player), caption);
}
/**
* Send a message to a player. - Supports color codes
* Send a message to a player. The message supports color codes.
*
* @param player Player that will receive the message
* @param string The message
* @param player the recipient of the message
* @param string the message
*
* @see MainUtil#sendMessage(PlotPlayer, String)
*/
@ -381,63 +356,50 @@ public class PlotAPI {
}
/**
* Send a message to the console. - Supports color codes
* Send a message to the console. The message supports color codes.
*
* @param msg Message that should be sent to the console
* @param message the message
*
* @see MainUtil#sendConsoleMessage(C, String...)
*/
public void sendConsoleMessage(String msg) {
PS.log(msg);
public void sendConsoleMessage(String message) {
PS.log(message);
}
/**
* Send a message to the console
* Send a message to the console.
*
* @param c (Caption)
* @param caption the message
*
* @see #sendConsoleMessage(String)
* @see com.intellectualcrafters.plot.config.C
* @see C
*/
public void sendConsoleMessage(C c) {
sendConsoleMessage(c.s());
public void sendConsoleMessage(C caption) {
sendConsoleMessage(caption.s());
}
/**
* Register a flag for use in plots
* Registers a flag for use in plots.
*
* @param flag Flag that should be registered
* @param flag the flag to register
*
* @see com.intellectualcrafters.plot.flag.FlagManager#addFlag(com.intellectualcrafters.plot.flag.AbstractFlag)
* @see com.intellectualcrafters.plot.flag.AbstractFlag
*/
public void addFlag(AbstractFlag flag) {
FlagManager.addFlag(flag);
public void addFlag(Flag<?> flag) {
Flags.registerFlag(flag);
}
/**
* get all the currently registered flags
* Gets a plot based on the ID.
*
* @return array of Flag[]
*
* @see com.intellectualcrafters.plot.flag.FlagManager#getFlags()
* @see com.intellectualcrafters.plot.flag.AbstractFlag
*/
public AbstractFlag[] getFlags() {
return FlagManager.getFlags().toArray(new AbstractFlag[FlagManager.getFlags().size()]);
}
/**
* Get a plot based on the ID.
*
* @param world World in which the plot is located
* @param x Plot Location X Co-ord
* @param z Plot Location Z Co-ord
* @param world the world the plot is located in
* @param x The PlotID x coordinate
* @param z The PlotID y coordinate
*
* @return plot, null if ID is wrong
*
* @see PlotArea#getPlot(PlotId)
*/
@SuppressWarnings("deprecation")
@Deprecated
public Plot getPlot(World world, int x, int z) {
if (world == null) {
@ -453,27 +415,27 @@ public class PlotAPI {
/**
* Get a plot based on the location.
*
* @param l The location that you want to to retrieve the plot from
* @param location the location to check
*
* @return plot if found, otherwise it creates a temporary plot-
* @return plot if found, otherwise it creates a temporary plot
*
* @see Plot
*/
public Plot getPlot(Location l) {
if (l == null) {
public Plot getPlot(Location location) {
if (location == null) {
return null;
}
return BukkitUtil.getLocation(l).getPlot();
return BukkitUtil.getLocation(location).getPlot();
}
/**
* Get a plot based on the player location.
*
* @param player Get the current plot for the player location
* @param player the player to check
*
* @return plot if found, otherwise it creates a temporary plot
*
* @see #getPlot(org.bukkit.Location)
* @see #getPlot(Location)
* @see Plot
*/
public Plot getPlot(Player player) {
@ -484,22 +446,24 @@ public class PlotAPI {
* Check whether or not a player has a plot.
*
* @param player Player that you want to check for
*
* @param world The world to check
* @return true if player has a plot, false if not.
*
* @see #getPlots(World, Player, boolean)
*/
@SuppressWarnings("deprecation")
@Deprecated
public boolean hasPlot(World world, Player player) {
return getPlots(world, player, true) != null && getPlots(world, player, true).length > 0;
return getPlots(world, player, true).length > 0;
}
/**
* Get all plots for the player.
*
* @param world
* @param world The world to retrieve plots from
* @param player The player to search for
* @param justOwner should we just search for owner? Or with rights?
* @return An array of plots for the player
*/
@Deprecated
public Plot[] getPlots(World world, Player player, boolean justOwner) {
@ -510,10 +474,8 @@ public class PlotAPI {
if (plot.hasOwner() && plot.isOwner(uuid)) {
pPlots.add(plot);
}
} else {
if (plot.isAdded(uuid)) {
pPlots.add(plot);
}
} else if (plot.isAdded(uuid)) {
pPlots.add(plot);
}
}
return pPlots.toArray(new Plot[pPlots.size()]);
@ -544,6 +506,7 @@ public class PlotAPI {
* @return World[] - array of plot worlds
*
*/
@SuppressWarnings("deprecation")
@Deprecated
public String[] getPlotWorlds() {
Set<String> plotWorldStrings = PS.get().getPlotWorldStrings();
@ -551,9 +514,9 @@ public class PlotAPI {
}
/**
* Get if plot world
* Get if plotworld.
*
* @param world (to check if plot world)
* @param world The world to check
*
* @return boolean (if plot world or not)
*
@ -565,9 +528,9 @@ public class PlotAPI {
}
/**
* Get plot locations
* Get plot locations.
*
* @param p Plot that you want to get the locations for
* @param plot Plot to get the locations for
*
* @return [0] = bottomLc, [1] = topLoc, [2] = home
*
@ -575,28 +538,32 @@ public class PlotAPI {
*
* @see Plot
*/
@SuppressWarnings("deprecation")
@Deprecated
public Location[] getLocations(Plot p) {
return new Location[]{BukkitUtil.getLocation(p.getBottom()), BukkitUtil.getLocation(p.getTop()), BukkitUtil.getLocation(p.getHome())};
public Location[] getLocations(Plot plot) {
Location bukkitBottom = BukkitUtil.getLocation(plot.getCorners()[0]);
Location bukkitTop = BukkitUtil.getLocation(plot.getCorners()[1]);
Location bukkitHome = BukkitUtil.getLocation(plot.getHome());
return new Location[]{bukkitBottom, bukkitTop, bukkitHome};
}
/**
* Get home location
* Get home location.
*
* @param p Plot that you want to get the location for
* @param plot Plot that you want to get the location for
*
* @return plot bottom location
*
* @see Plot
*/
public Location getHomeLocation(Plot p) {
return BukkitUtil.getLocation(p.getHome());
public Location getHomeLocation(Plot plot) {
return BukkitUtil.getLocation(plot.getHome());
}
/**
* Get Bottom Location (min, min, min)
* Get Bottom Location (min, min, min).
*
* @param p Plot that you want to get the location for
* @param plot Plot that you want to get the location for
*
* @return plot bottom location
*
@ -604,15 +571,16 @@ public class PlotAPI {
*
* @see Plot
*/
@SuppressWarnings("deprecation")
@Deprecated
public Location getBottomLocation(Plot p) {
return BukkitUtil.getLocation(p.getBottom());
public Location getBottomLocation(Plot plot) {
return BukkitUtil.getLocation(plot.getCorners()[0]);
}
/**
* Get Top Location (max, max, max)
* Get Top Location (max, max, max).
*
* @param p Plot that you want to get the location for
* @param plot Plot that you want to get the location for
*
* @return plot top location
*
@ -620,13 +588,14 @@ public class PlotAPI {
*
* @see Plot
*/
@SuppressWarnings("deprecation")
@Deprecated
public Location getTopLocation(Plot p) {
return BukkitUtil.getLocation(p.getTop());
public Location getTopLocation(Plot plot) {
return BukkitUtil.getLocation(plot.getCorners()[1]);
}
/**
* Check whether or not a player is in a plot
* Check whether or not a player is in a plot.
*
* @param player who we're checking for
*
@ -638,10 +607,10 @@ public class PlotAPI {
}
/**
* Register a subcommand
* Register a subcommand.
* @deprecated Command registration is done on object creation
* @param c SubCommand, that we want to register
* @see com.intellectualcrafters.plot.commands.SubCommand
* @see SubCommand
*/
@Deprecated
public void registerCommand(SubCommand c) {
@ -649,7 +618,7 @@ public class PlotAPI {
}
/**
* Get the PlotSquared class
* Gets the PlotSquared class.
*
* @return PlotSquared Class
*
@ -660,7 +629,7 @@ public class PlotAPI {
}
/**
* Get the player plot count
* Gets the player plot count.
*
* @param world Specify the world we want to select the plots from
* @param player Player, for whom we're getting the plot count
@ -676,7 +645,7 @@ public class PlotAPI {
}
/**
* Get a collection containing the players plots
* Gets a collection containing the players plots.
*
* @param world Specify the world we want to select the plots from
* @param player Player, for whom we're getting the plots
@ -691,67 +660,72 @@ public class PlotAPI {
if (world == null) {
return new HashSet<>();
}
return BukkitUtil.getPlayer(player).getPlots(world.getName());
return PlotPlayer.wrap(player).getPlots(world.getName());
}
/**
* Get the numbers of plots, which the player is able to build in
* Gets the number of plots, which the player is able to build in.
*
* @param player Player, for whom we're getting the plots (trusted, member and owner)
* @param player player, for whom we're getting the plots
*
* @return the number of allowed plots
*
*/
public int getAllowedPlots(Player player) {
PlotPlayer pp = BukkitUtil.getPlayer(player);
return pp.getAllowedPlots();
PlotPlayer plotPlayer = PlotPlayer.wrap(player);
return plotPlayer.getAllowedPlots();
}
/**
* Get the PlotPlayer for a player<br>
* - The PlotPlayer is usually cached and will provide useful functions relating to players
* Gets the PlotPlayer for a player. The PlotPlayer is usually cached and
* will provide useful functions relating to players.
*
* @see PlotPlayer#wrap(Object)
*
* @param player
* @return
* @param player the player to wrap
* @return a {@code PlotPlayer}
*/
public PlotPlayer wrapPlayer(Player player) {
return PlotPlayer.wrap(player);
}
/**
* Get the PlotPlayer for a UUID (Please note that PlotSquared can be configured to provide different UUIDs than bukkit)
* Get the PlotPlayer for a UUID.
*
* <p><i>Please note that PlotSquared can be configured to provide
* different UUIDs than bukkit</i>
*
* @see PlotPlayer#wrap(Object)
*
* @param uuid
* @return
* @param uuid the uuid of the player to wrap
* @return a {@code PlotPlayer}
*/
public PlotPlayer wrapPlayer(UUID uuid) {
return PlotPlayer.wrap(uuid);
}
/**
* Get the PlotPlayer for a username
* Get the PlotPlayer for a username.
*
* @see PlotPlayer#wrap(Object)
*
* @param player
* @return
* @param player the player to wrap
* @return a {@code PlotPlayer}
*/
public PlotPlayer wrapPlayer(String player) {
return PlotPlayer.wrap(player);
}
/**
* Get the PlotPlayer for an offline player<br>
* Note that this will work if the player is offline, however not all functionality will work
* Get the PlotPlayer for an offline player.
*
* <p>Note that this will work if the player is offline, however not all
* functionality will work.
*
* @see PlotPlayer#wrap(Object)
*
* @param player
* @return
* @param player the player to wrap
* @return a {@code PlotPlayer}
*/
public PlotPlayer wrapPlayer(OfflinePlayer player) {
return PlotPlayer.wrap(player);

View File

@ -6,7 +6,6 @@ import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.ConfigurationNode;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.generator.GeneratorWrapper;
import com.intellectualcrafters.plot.generator.HybridGen;
import com.intellectualcrafters.plot.generator.HybridUtils;
@ -16,6 +15,7 @@ import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.object.SetupObject;
import com.intellectualcrafters.plot.object.chat.PlainChatManager;
import com.intellectualcrafters.plot.util.AbstractTitle;
import com.intellectualcrafters.plot.util.ChatManager;
import com.intellectualcrafters.plot.util.ChunkManager;
@ -24,7 +24,6 @@ import com.intellectualcrafters.plot.util.EconHandler;
import com.intellectualcrafters.plot.util.EventUtil;
import com.intellectualcrafters.plot.util.InventoryUtil;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.PlotQueue;
import com.intellectualcrafters.plot.util.SchematicHandler;
import com.intellectualcrafters.plot.util.SetupUtils;
import com.intellectualcrafters.plot.util.StringMan;
@ -32,20 +31,20 @@ import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.util.UUIDHandlerImplementation;
import com.intellectualcrafters.plot.util.WorldUtil;
import com.intellectualcrafters.plot.util.block.QueueProvider;
import com.intellectualcrafters.plot.uuid.UUIDWrapper;
import com.plotsquared.bukkit.commands.DebugUUID;
import com.plotsquared.bukkit.database.plotme.ClassicPlotMeConnector;
import com.plotsquared.bukkit.database.plotme.LikePlotMeConverter;
import com.plotsquared.bukkit.database.plotme.PlotMeConnector_017;
import com.plotsquared.bukkit.generator.BukkitPlotGenerator;
import com.plotsquared.bukkit.listeners.ChunkListener;
import com.plotsquared.bukkit.listeners.ForceFieldListener;
import com.plotsquared.bukkit.listeners.EntitySpawnListener;
import com.plotsquared.bukkit.listeners.PlayerEvents;
import com.plotsquared.bukkit.listeners.PlayerEvents183;
import com.plotsquared.bukkit.listeners.PlayerEvents_1_8;
import com.plotsquared.bukkit.listeners.PlayerEvents_1_9;
import com.plotsquared.bukkit.listeners.PlotPlusListener;
import com.plotsquared.bukkit.listeners.WorldEvents;
import com.plotsquared.bukkit.listeners.worldedit.WEListener;
import com.plotsquared.bukkit.titles.DefaultTitle_19;
import com.plotsquared.bukkit.util.BukkitChatManager;
import com.plotsquared.bukkit.util.BukkitChunkManager;
@ -54,31 +53,25 @@ import com.plotsquared.bukkit.util.BukkitEconHandler;
import com.plotsquared.bukkit.util.BukkitEventUtil;
import com.plotsquared.bukkit.util.BukkitHybridUtils;
import com.plotsquared.bukkit.util.BukkitInventoryUtil;
import com.plotsquared.bukkit.util.BukkitPlainChatManager;
import com.plotsquared.bukkit.util.BukkitSchematicHandler;
import com.plotsquared.bukkit.util.BukkitSetupUtils;
import com.plotsquared.bukkit.util.BukkitTaskManager;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.bukkit.util.BukkitVersion;
import com.plotsquared.bukkit.util.Metrics;
import com.plotsquared.bukkit.util.SendChunk;
import com.plotsquared.bukkit.util.SetGenCB;
import com.plotsquared.bukkit.util.block.FastQueue_1_7;
import com.plotsquared.bukkit.util.block.FastQueue_1_8;
import com.plotsquared.bukkit.util.block.FastQueue_1_8_3;
import com.plotsquared.bukkit.util.block.FastQueue_1_9;
import com.plotsquared.bukkit.util.block.SlowQueue;
import com.plotsquared.bukkit.util.block.BukkitLocalQueue;
import com.plotsquared.bukkit.util.block.BukkitLocalQueue_1_7;
import com.plotsquared.bukkit.util.block.BukkitLocalQueue_1_8;
import com.plotsquared.bukkit.util.block.BukkitLocalQueue_1_8_3;
import com.plotsquared.bukkit.util.block.BukkitLocalQueue_1_9;
import com.plotsquared.bukkit.uuid.DefaultUUIDWrapper;
import com.plotsquared.bukkit.uuid.FileUUIDHandler;
import com.plotsquared.bukkit.uuid.LowerOfflineUUIDWrapper;
import com.plotsquared.bukkit.uuid.OfflineUUIDWrapper;
import com.plotsquared.bukkit.uuid.SQLUUIDHandler;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import com.sk89q.worldedit.WorldEdit;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
@ -86,19 +79,78 @@ import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.command.PluginCommand;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.metadata.MetadataValue;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public static BukkitMain THIS;
public static WorldEditPlugin worldEdit;
public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
private static ConcurrentHashMap<String, Plugin> pluginMap;
static {
// Disable AWE as otherwise both fail to load
PluginManager manager = Bukkit.getPluginManager();
try {
Settings.load(new File("plugins/PlotSquared/config/settings.yml"));
if (Settings.Enabled_Components.PLOTME_CONVERTER) { // Only disable PlotMe if conversion is enabled
Field pluginsField = manager.getClass().getDeclaredField("plugins");
Field lookupNamesField = manager.getClass().getDeclaredField("lookupNames");
pluginsField.setAccessible(true);
lookupNamesField.setAccessible(true);
List<Plugin> plugins = (List<Plugin>) pluginsField.get(manager);
Iterator<Plugin> iter = plugins.iterator();
while (iter.hasNext()) {
if (iter.next().getName().startsWith("PlotMe")) {
iter.remove();
}
}
Map<String, Plugin> lookupNames = (Map<String, Plugin>) lookupNamesField.get(manager);
lookupNames.remove("PlotMe");
lookupNames.remove("PlotMe-DefaultGenerator");
pluginsField.set(manager, new ArrayList<Plugin>(plugins) {
@Override
public boolean add(Plugin plugin) {
if (plugin.getName().startsWith("PlotMe")) {
System.out.print("Disabling `" + plugin.getName() + "` for PlotMe conversion (configure in PlotSquared settings.yml)");
} else {
return super.add(plugin);
}
return false;
}
});
pluginMap = new ConcurrentHashMap<String, Plugin>(lookupNames) {
@Override
public Plugin put(String key, Plugin plugin) {
if (!plugin.getName().startsWith("PlotMe")) {
return super.put(key, plugin);
}
return null;
}
};
lookupNamesField.set(manager, pluginMap);
}
} catch (Throwable ignore) {}
}
public static WorldEdit worldEdit;
private int[] version;
private String name;
@Override
public int[] getServerVersion() {
@ -115,7 +167,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
e.printStackTrace();
PS.debug(StringMan.getString(Bukkit.getBukkitVersion()));
PS.debug(StringMan.getString(Bukkit.getBukkitVersion().split("-")[0].split("\\.")));
return new int[]{Integer.MAX_VALUE, 0, 0};
return new int[]{1, 10, 0};
}
}
return this.version;
@ -123,55 +175,70 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
@Override
public void onEnable() {
THIS = this;
if (pluginMap != null) {
pluginMap.put("PlotMe-DefaultGenerator", this);
}
this.name = getDescription().getName();
getServer().getName();
new PS(this, "Bukkit");
if (Settings.Enabled_Components.METRICS) {
new Metrics(this).start();
PS.log(C.PREFIX + "&6Metrics enabled.");
} else {
PS.log(C.CONSOLE_PLEASE_ENABLE_METRICS.f(getPluginName()));
}
}
@Override
public void onDisable() {
PS.get().disable();
Bukkit.getScheduler().cancelTasks(this);
THIS = null;
}
@Override
public void log(String message) {
if (THIS != null) {
try {
message = C.color(message);
if (!Settings.CONSOLE_COLOR) {
message = ChatColor.stripColor(message);
}
this.getServer().getConsoleSender().sendMessage(message);
return;
} catch (Throwable ignored) {
//ignored
try {
message = C.color(message);
if (!Settings.Chat.CONSOLE_COLOR) {
message = ChatColor.stripColor(message);
}
this.getServer().getConsoleSender().sendMessage(message);
} catch (Throwable ignored) {
System.out.println(ConsoleColors.fromString(message));
}
System.out.println(ConsoleColors.fromString(message));
}
@Override
public void disable() {
if (THIS != null) {
onDisable();
}
onDisable();
}
@Override
public int[] getPluginVersion() {
String[] split = getDescription().getVersion().split("\\.");
String ver = getDescription().getVersion();
if (ver.contains("-")) {
ver = ver.split("-")[0];
}
String[] split = ver.split("\\.");
return new int[]{Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2])};
}
@Override public String getPluginVersionString() {
return getDescription().getVersion();
}
@Override
public String getPluginName() {
return name;
}
@Override
public void registerCommands() {
BukkitCommand bcmd = new BukkitCommand();
BukkitCommand bukkitCommand = new BukkitCommand();
PluginCommand plotCommand = getCommand("plots");
plotCommand.setExecutor(bcmd);
plotCommand.setExecutor(bukkitCommand);
plotCommand.setAliases(Arrays.asList("p", "ps", "plotme", "plot"));
plotCommand.setTabCompleter(bcmd);
new DebugUUID();
plotCommand.setTabCompleter(bukkitCommand);
}
@Override
@ -186,19 +253,19 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
@Override
public TaskManager getTaskManager() {
return new BukkitTaskManager();
return new BukkitTaskManager(this);
}
@Override
public void runEntityTask() {
log(C.PREFIX + "KillAllEntities started.");
PS.log(C.PREFIX + "KillAllEntities started.");
TaskManager.runTaskRepeat(new Runnable() {
@Override
public void run() {
PS.get().foreachPlotArea(new RunnableVal<PlotArea>() {
@Override
public void run(PlotArea pw) {
World world = Bukkit.getWorld(pw.worldname);
public void run(PlotArea plotArea) {
World world = Bukkit.getWorld(plotArea.worldname);
try {
if (world == null) {
return;
@ -209,10 +276,10 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
Entity entity = iterator.next();
switch (entity.getType()) {
case EGG:
case ENDER_CRYSTAL:
case COMPLEX_PART:
case FISHING_HOOK:
case ENDER_SIGNAL:
case LINGERING_POTION:
case AREA_EFFECT_CLOUD:
case EXPERIENCE_ORB:
case LEASH_HITCH:
@ -221,10 +288,9 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
case LIGHTNING:
case WITHER_SKULL:
case UNKNOWN:
case PLAYER: {
// non moving / unremovable
case PLAYER:
// non moving / unmovable
continue;
}
case THROWN_EXP_BOTTLE:
case SPLASH_POTION:
case SNOWBALL:
@ -232,58 +298,73 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
case SPECTRAL_ARROW:
case TIPPED_ARROW:
case ENDER_PEARL:
case ARROW: {
case ARROW:
case LLAMA_SPIT:
// managed elsewhere | projectile
continue;
}
case ARMOR_STAND:
case ITEM_FRAME:
case PAINTING: {
// TEMPORARILY CLASSIFY AS VEHICLE
}
case PAINTING:
// Not vehicles
continue;
case ARMOR_STAND:
// Temporarily classify as vehicle
case MINECART:
case MINECART_CHEST:
case MINECART_COMMAND:
case MINECART_FURNACE:
case MINECART_HOPPER:
case MINECART_MOB_SPAWNER:
case ENDER_CRYSTAL:
case MINECART_TNT:
case BOAT: {
if (!Settings.KILL_ROAD_VEHICLES) {
continue;
}
com.intellectualcrafters.plot.object.Location location = BukkitUtil.getLocation(entity.getLocation());
Plot plot = location.getPlot();
if (plot == null) {
if (location.isPlotArea()) {
case BOAT:
if (Settings.Enabled_Components.KILL_ROAD_VEHICLES) {
com.intellectualcrafters.plot.object.Location location = BukkitUtil.getLocation(entity.getLocation());
Plot plot = location.getPlot();
if (plot == null) {
if (location.isPlotArea()) {
iterator.remove();
entity.remove();
}
continue;
}
List<MetadataValue> meta = entity.getMetadata("plot");
if (meta.isEmpty()) {
continue;
}
Plot origin = (Plot) meta.get(0).value();
if (!plot.equals(origin.getBasePlot(false))) {
iterator.remove();
entity.remove();
}
continue;
}
List<MetadataValue> meta = entity.getMetadata("plot");
if (meta.isEmpty()) {
} else {
continue;
}
Plot origin = (Plot) meta.get(0).value();
if (!plot.equals(origin.getBasePlot(false))) {
iterator.remove();
entity.remove();
}
continue;
}
case SMALL_FIREBALL:
case FIREBALL:
case DRAGON_FIREBALL:
case DROPPED_ITEM: {
case DROPPED_ITEM:
// dropped item
continue;
}
case PRIMED_TNT:
case FALLING_BLOCK: {
case FALLING_BLOCK:
// managed elsewhere
continue;
}
case LLAMA:
case DONKEY:
case MULE:
case ZOMBIE_HORSE:
case SKELETON_HORSE:
case HUSK:
case ELDER_GUARDIAN:
case WITHER_SKELETON:
case STRAY:
case ZOMBIE_VILLAGER:
case EVOKER:
case EVOKER_FANGS:
case VEX:
case VINDICATOR:
case POLAR_BEAR:
case BAT:
case BLAZE:
case CAVE_SPIDER:
@ -317,19 +398,28 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
case WOLF:
case ZOMBIE:
case SHULKER:
default: {
if (!Settings.KILL_ROAD_MOBS) {
continue;
}
Location location = entity.getLocation();
if (BukkitUtil.getLocation(location).isPlotRoad()) {
Entity passenger = entity.getPassenger();
if (!(passenger instanceof Player) && entity.getMetadata("keep").isEmpty()) {
iterator.remove();
entity.remove();
default:
if (Settings.Enabled_Components.KILL_ROAD_MOBS) {
Location location = entity.getLocation();
if (BukkitUtil.getLocation(location).isPlotRoad()) {
if (entity instanceof LivingEntity) {
LivingEntity livingEntity = (LivingEntity) entity;
if (!livingEntity.isLeashed() || !entity.hasMetadata("keep")) {
Entity passenger = entity.getPassenger();
if (!(passenger instanceof Player) && entity.getMetadata("keep").isEmpty()) {
iterator.remove();
entity.remove();
}
}
} else {
Entity passenger = entity.getPassenger();
if (!(passenger instanceof Player) && entity.getMetadata("keep").isEmpty()) {
iterator.remove();
entity.remove();
}
}
}
}
}
}
}
} catch (Throwable e) {
@ -343,21 +433,47 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
@Override
public final ChunkGenerator getDefaultWorldGenerator(String world, String id) {
HybridGen result = new HybridGen();
if (Settings.Enabled_Components.PLOTME_CONVERTER) {
initPlotMeConverter();
Settings.Enabled_Components.PLOTME_CONVERTER = false;
}
IndependentPlotGenerator result = PS.get().IMP.getDefaultGenerator();
if (!PS.get().setupPlotWorld(world, id, result)) {
return null;
}
return (ChunkGenerator) result.specify();
return (ChunkGenerator) result.specify(world);
}
@Override
public void registerPlayerEvents() {
getServer().getPluginManager().registerEvents(new PlayerEvents(), this);
if (PS.get().checkVersion(getServerVersion(), 1, 8, 0)) {
getServer().getPluginManager().registerEvents(new PlayerEvents_1_8(), this);
PlayerEvents main = new PlayerEvents();
getServer().getPluginManager().registerEvents(main, this);
try {
getServer().getClass().getMethod("spigot");
getServer().getPluginManager().registerEvents(new EntitySpawnListener(), this);
} catch (NoSuchMethodException ignored) {
PS.debug("Not running Spigot. Skipping EntitySpawnListener event.");
}
if (PS.get().checkVersion(getServerVersion(), 1, 8, 3)) {
getServer().getPluginManager().registerEvents(new PlayerEvents183(), this);
if (PS.get().checkVersion(getServerVersion(), BukkitVersion.v1_8_0)) {
try {
getServer().getPluginManager().registerEvents(new PlayerEvents_1_8(), this);
} catch (Throwable e) {
e.printStackTrace();
}
}
if (PS.get().checkVersion(getServerVersion(), BukkitVersion.v1_8_3)) {
try {
getServer().getPluginManager().registerEvents(new PlayerEvents183(), this);
} catch (Throwable e) {
e.printStackTrace();
}
}
if (PS.get().checkVersion(getServerVersion(), BukkitVersion.v1_9_0)) {
try {
getServer().getPluginManager().registerEvents(new PlayerEvents_1_9(main), this);
} catch (Throwable e) {
e.printStackTrace();
}
}
}
@ -374,14 +490,12 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
@Override
public void registerForceFieldEvents() {
getServer().getPluginManager().registerEvents(new ForceFieldListener(), this);
}
@Override
public boolean initWorldEdit() {
if (getServer().getPluginManager().getPlugin("WorldEdit") != null) {
BukkitMain.worldEdit = (WorldEditPlugin) getServer().getPluginManager().getPlugin("WorldEdit");
getServer().getPluginManager().registerEvents(new WEListener(), this);
worldEdit = WorldEdit.getInstance();
return true;
}
return false;
@ -394,49 +508,31 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
if (econ.init()) {
return econ;
}
System.out.println("ECONOMY ENABLED!");
} catch (Throwable ignored) {
ignored.printStackTrace();
PS.debug("No economy detected!");
}
return null;
}
@Override
public PlotQueue initPlotQueue() {
public QueueProvider initBlockQueue() {
try {
new SendChunk();
MainUtil.canSendChunk = true;
} catch (Throwable e) {
e.printStackTrace();
} catch (ClassNotFoundException | NoSuchFieldException | NoSuchMethodException e) {
PS.debug(SendChunk.class + " does not support " + StringMan.getString(getServerVersion()));
MainUtil.canSendChunk = false;
}
if (PS.get().checkVersion(getServerVersion(), 1, 9, 0)) {
try {
return new FastQueue_1_9();
} catch (Throwable e) {
e.printStackTrace();
return new SlowQueue();
}
if (PS.get().checkVersion(getServerVersion(), BukkitVersion.v1_9_0)) {
return QueueProvider.of(BukkitLocalQueue_1_9.class, BukkitLocalQueue.class);
}
if (PS.get().checkVersion(getServerVersion(), 1, 8, 0)) {
try {
return new FastQueue_1_8_3();
} catch (Throwable e) {
e.printStackTrace();
try {
return new FastQueue_1_8();
} catch (Throwable e2) {
e2.printStackTrace();
return new SlowQueue();
}
}
if (PS.get().checkVersion(getServerVersion(), BukkitVersion.v1_8_3)) {
return QueueProvider.of(BukkitLocalQueue_1_8_3.class, BukkitLocalQueue.class);
}
try {
return new FastQueue_1_7();
} catch (Throwable e) {
e.printStackTrace();
return new SlowQueue();
if (PS.get().checkVersion(getServerVersion(), BukkitVersion.v1_8_0)) {
return QueueProvider.of(BukkitLocalQueue_1_8.class, BukkitLocalQueue.class);
}
return QueueProvider.of(BukkitLocalQueue_1_7.class, BukkitLocalQueue.class);
}
@Override
@ -446,21 +542,12 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
@Override
public boolean initPlotMeConverter() {
TaskManager.runTaskLaterAsync(new Runnable() {
@Override
public void run() {
if (new LikePlotMeConverter("PlotMe").run(new ClassicPlotMeConnector())) {
return;
}
if (new LikePlotMeConverter("PlotMe").run(new PlotMeConnector_017())) {
return;
}
if (new LikePlotMeConverter("AthionPlots").run(new ClassicPlotMeConnector())) {
return;
}
}
}, 20);
return Bukkit.getPluginManager().getPlugin("PlotMe") != null || Bukkit.getPluginManager().getPlugin("AthionPlots") != null;
if (new LikePlotMeConverter("PlotMe").run(new ClassicPlotMeConnector())) {
return true;
} else if (new LikePlotMeConverter("PlotMe").run(new PlotMeConnector_017())) {
return true;
}
return false;
}
@Override
@ -476,7 +563,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
}
return new BukkitPlotGenerator(world, gen);
} else {
return new BukkitPlotGenerator(new HybridGen());
return new BukkitPlotGenerator(PS.get().IMP.getDefaultGenerator());
}
}
@ -492,44 +579,43 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
@Override
public UUIDHandlerImplementation initUUIDHandler() {
boolean checkVersion = PS.get().checkVersion(getServerVersion(), 1, 7, 6);
boolean checkVersion = PS.get().checkVersion(getServerVersion(), BukkitVersion.v1_7_6);
UUIDWrapper wrapper;
if (Settings.OFFLINE_MODE) {
if (Settings.UUID_LOWERCASE) {
if (Settings.UUID.OFFLINE) {
if (Settings.UUID.FORCE_LOWERCASE) {
wrapper = new LowerOfflineUUIDWrapper();
} else {
wrapper = new OfflineUUIDWrapper();
}
Settings.OFFLINE_MODE = true;
Settings.UUID.OFFLINE = true;
} else if (checkVersion) {
wrapper = new DefaultUUIDWrapper();
Settings.OFFLINE_MODE = false;
Settings.UUID.OFFLINE = false;
} else {
if (Settings.UUID_LOWERCASE) {
if (Settings.UUID.FORCE_LOWERCASE) {
wrapper = new LowerOfflineUUIDWrapper();
} else {
wrapper = new OfflineUUIDWrapper();
}
Settings.OFFLINE_MODE = true;
Settings.UUID.OFFLINE = true;
}
if (!checkVersion) {
log(C.PREFIX + " &c[WARN] Titles are disabled - please update your version of Bukkit to support this feature.");
PS.log(C.PREFIX + " &c[WARN] Titles are disabled - please update your version of Bukkit to support this feature.");
Settings.TITLES = false;
FlagManager.removeFlag(FlagManager.getFlag("titles"));
} else {
AbstractTitle.TITLE_CLASS = new DefaultTitle_19();
if (wrapper instanceof DefaultUUIDWrapper || wrapper.getClass() == OfflineUUIDWrapper.class && !Bukkit.getOnlineMode()) {
Settings.TWIN_MODE_UUID = true;
Settings.UUID.NATIVE_UUID_PROVIDER = true;
}
}
if (Settings.OFFLINE_MODE) {
log(C.PREFIX
+ " &6PlotSquared is using Offline Mode UUIDs either because of user preference, or because you are using an old version of "
if (Settings.UUID.OFFLINE) {
PS.log(C.PREFIX
+ " &6" + getPluginName() + " is using Offline Mode UUIDs either because of user preference, or because you are using an old version of "
+ "Bukkit");
} else {
log(C.PREFIX + " &6PlotSquared is using online UUIDs");
PS.log(C.PREFIX + " &6" + getPluginName() + " is using online UUIDs");
}
if (Settings.USE_SQLUUIDHANDLER) {
if (Settings.UUID.USE_SQLUUIDHANDLER) {
return new SQLUUIDHandler(wrapper);
} else {
return new FileUUIDHandler(wrapper);
@ -561,21 +647,20 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
getServer().getPluginManager().registerEvents(new WorldEvents(), this);
}
@Override
public IndependentPlotGenerator getDefaultGenerator() {
return new HybridGen();
}
@Override
public InventoryUtil initInventoryUtil() {
return new BukkitInventoryUtil();
}
@Override
public String getServerName() {
return Bukkit.getServerName();
}
@Override
public void startMetrics() {
Metrics metrics = new Metrics(this);
metrics.start();
log(C.PREFIX + "&6Metrics enabled.");
new Metrics(this).start();
PS.log(C.PREFIX + "&6Metrics enabled.");
}
@Override
@ -583,8 +668,8 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
World world = BukkitUtil.getWorld(worldName);
if (world == null) {
// create world
ConfigurationSection worldConfig = PS.get().config.getConfigurationSection("worlds." + worldName);
String manager = worldConfig.getString("generator.plugin", "PlotSquared");
ConfigurationSection worldConfig = PS.get().worlds.getConfigurationSection("worlds." + worldName);
String manager = worldConfig.getString("generator.plugin", getPluginName());
SetupObject setup = new SetupObject();
setup.plotManager = manager;
setup.setupGenerator = worldConfig.getString("generator.init", manager);
@ -593,23 +678,24 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
setup.step = new ConfigurationNode[0];
setup.world = worldName;
SetupUtils.manager.setupWorld(setup);
world = Bukkit.getWorld(worldName);
} else {
try {
if (!PS.get().hasPlotArea(worldName)) {
SetGenCB.setGenerator(BukkitUtil.getWorld(worldName));
}
} catch (Exception e) {
log("Failed to reload world: " + world);
} catch (Exception ignored) {
PS.log("Failed to reload world: " + world + " | " + ignored.getMessage());
Bukkit.getServer().unloadWorld(world, false);
return;
}
}
world = Bukkit.getWorld(worldName);
ChunkGenerator gen = world.getGenerator();
if (gen instanceof BukkitPlotGenerator) {
PS.get().loadWorld(worldName, (BukkitPlotGenerator) gen);
} else if (gen != null) {
PS.get().loadWorld(worldName, new BukkitPlotGenerator(worldName, gen));
} else if (PS.get().config.contains("worlds." + worldName)) {
} else if (PS.get().worlds.contains("worlds." + worldName)) {
PS.get().loadWorld(worldName, null);
}
}
@ -629,11 +715,14 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
public PlotPlayer wrapPlayer(Object player) {
if (player instanceof Player) {
return BukkitUtil.getPlayer((Player) player);
} else if (player instanceof OfflinePlayer) {
}
if (player instanceof OfflinePlayer) {
return BukkitUtil.getPlayer((OfflinePlayer) player);
} else if (player instanceof String) {
}
if (player instanceof String) {
return UUIDHandler.getPlayer((String) player);
} else if (player instanceof UUID) {
}
if (player instanceof UUID) {
return UUIDHandler.getPlayer((UUID) player);
}
return null;
@ -647,15 +736,15 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
@Override
public ChatManager<?> initChatManager() {
if (Settings.FANCY_CHAT) {
if (Settings.Chat.INTERACTIVE) {
return new BukkitChatManager();
} else {
return new BukkitPlainChatManager();
return new PlainChatManager();
}
}
@Override
public GeneratorWrapper<?> wrapPlotGenerator(IndependentPlotGenerator generator) {
public GeneratorWrapper<?> wrapPlotGenerator(String world, IndependentPlotGenerator generator) {
return new BukkitPlotGenerator(generator);
}
@ -663,7 +752,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
public List<String> getPluginIds() {
ArrayList<String> names = new ArrayList<>();
for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
names.add(plugin.getName() + ";" + plugin.getDescription().getVersion() + ":" + plugin.isEnabled());
names.add(plugin.getName() + ';' + plugin.getDescription().getVersion() + ':' + plugin.isEnabled());
}
return names;
}

View File

@ -12,37 +12,86 @@ import java.util.Collection;
* <p>
* This class is intended for use as a key to a map.
* </p>
* @author Glen Husman
*
* @param <E> The type of elements in the array.
* @author Glen Husman
* @see Arrays
*/
public final class ArrayWrapper<E> {
private E[] array;
/**
* Creates an array wrapper with some elements.
*
* @param elements The elements of the array.
*/
public ArrayWrapper(E... elements) {
setArray(elements);
}
private E[] _array;
/**
* Retrieves a reference to the wrapped array instance.
*
* @return The array wrapped by this instance.
*/
public E[] getArray() {
return _array;
}
/**
* Set this wrapper to wrap a new array instance.
*
* @param array The new wrapped array.
*/
public void setArray(E[] array) {
Validate.notNull(array, "The array must not be null.");
_array = array;
}
/**
* Determines if this object has a value equivalent to another object.
*
* @see Arrays#equals(Object[], Object[])
*/
@SuppressWarnings("rawtypes")
@Override
public boolean equals(Object other) {
if (!(other instanceof ArrayWrapper)) {
return false;
}
return Arrays.equals(_array, ((ArrayWrapper) other)._array);
}
/**
* Gets the hash code represented by this objects value.
*
* @return This object's hash code.
* @see Arrays#hashCode(Object[])
*/
@Override
public int hashCode() {
return Arrays.hashCode(_array);
}
/**
* Converts an iterable element collection to an array of elements.
* The iteration order of the specified object will be used as the array element order.
*
* @param list The iterable of objects which will be converted to an array.
* @param c The type of the elements of the array.
* @param c The type of the elements of the array.
* @return An array of elements in the specified iterable.
*/
@SuppressWarnings("unchecked")
public static <T> T[] toArray(Iterable<? extends T> list, Class<T> c) {
int size = -1;
if (list instanceof Collection<?>) {
@SuppressWarnings("rawtypes") Collection coll = (Collection) list;
@SuppressWarnings("rawtypes")
Collection coll = (Collection) list;
size = coll.size();
}
if (size < 0) {
size = 0;
// Ugly hack: Count it ourselves
@ -59,43 +108,4 @@ public final class ArrayWrapper<E> {
return result;
}
/**
* Retrieves a reference to the wrapped array instance.
* @return The array wrapped by this instance.
*/
public E[] getArray() {
return this.array;
}
/**
* Set this wrapper to wrap a new array instance.
* @param array The new wrapped array.
*/
public void setArray(E[] array) {
Validate.notNull(array, "The array must not be null.");
this.array = array;
}
/**
* Determines if this object has a value equivalent to another object.
* @see Arrays#equals(Object[], Object[])
*/
@SuppressWarnings("rawtypes")
@Override
public boolean equals(Object other) {
if (!(other instanceof ArrayWrapper)) {
return false;
}
return Arrays.equals(this.array, ((ArrayWrapper) other).array);
}
/**
* Gets the hash code represented by this objects value.
* @see Arrays#hashCode(Object[])
* @return This object's hash code.
*/
@Override
public int hashCode() {
return Arrays.hashCode(this.array);
}
}

View File

@ -14,6 +14,6 @@ interface JsonRepresentedObject {
* @param writer The JSON writer which will receive the object.
* @throws IOException If an error occurs writing to the stream.
*/
void writeJson(JsonWriter writer) throws IOException;
public void writeJson(JsonWriter writer) throws IOException;
}

View File

@ -1,7 +1,7 @@
package com.plotsquared.bukkit.chat;
import com.google.gson.stream.JsonWriter;
import com.intellectualcrafters.configuration.serialization.ConfigurationSerializable;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import java.io.IOException;
import java.util.HashMap;
@ -14,14 +14,10 @@ import java.util.Map;
*/
final class JsonString implements JsonRepresentedObject, ConfigurationSerializable {
private final String _value;
private String _value;
public JsonString(CharSequence value) {
this._value = value == null ? null : value.toString();
}
public static JsonString deserialize(Map<String, Object> map) {
return new JsonString(map.get("stringValue").toString());
_value = value == null ? null : value.toString();
}
@Override
@ -30,18 +26,22 @@ final class JsonString implements JsonRepresentedObject, ConfigurationSerializab
}
public String getValue() {
return this._value;
return _value;
}
@Override
public Map<String, Object> serialize() {
HashMap<String, Object> theSingleValue = new HashMap<>();
theSingleValue.put("stringValue", this._value);
HashMap<String, Object> theSingleValue = new HashMap<String, Object>();
theSingleValue.put("stringValue", _value);
return theSingleValue;
}
public static JsonString deserialize(Map<String, Object> map) {
return new JsonString(map.get("stringValue").toString());
}
@Override
public String toString() {
return this._value;
return _value;
}
}

View File

@ -3,10 +3,10 @@ package com.plotsquared.bukkit.chat;
import com.google.common.collect.BiMap;
import com.google.common.collect.ImmutableBiMap;
import com.google.gson.stream.JsonWriter;
import com.intellectualcrafters.configuration.serialization.ConfigurationSerializable;
import com.intellectualcrafters.configuration.serialization.ConfigurationSerialization;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.configuration.serialization.ConfigurationSerialization;
import java.io.IOException;
import java.util.ArrayList;
@ -19,11 +19,48 @@ import java.util.logging.Level;
*/
final class MessagePart implements JsonRepresentedObject, ConfigurationSerializable, Cloneable {
ChatColor color = ChatColor.WHITE;
ArrayList<ChatColor> styles = new ArrayList<>();
String clickActionName = null;
String clickActionData = null;
String hoverActionName = null;
JsonRepresentedObject hoverActionData = null;
TextualComponent text = null;
String insertionData = null;
ArrayList<JsonRepresentedObject> translationReplacements = new ArrayList<>();
MessagePart(final TextualComponent text) {
this.text = text;
}
MessagePart() {
this.text = null;
}
boolean hasText() {
return text != null;
}
@Override
@SuppressWarnings("unchecked")
public MessagePart clone() throws CloneNotSupportedException {
MessagePart obj = (MessagePart) super.clone();
obj.styles = (ArrayList<ChatColor>) styles.clone();
if (hoverActionData instanceof JsonString) {
obj.hoverActionData = new JsonString(((JsonString) hoverActionData).getValue());
} else if (hoverActionData instanceof FancyMessage) {
obj.hoverActionData = ((FancyMessage) hoverActionData).clone();
}
obj.translationReplacements = (ArrayList<JsonRepresentedObject>) translationReplacements.clone();
return obj;
}
static final BiMap<ChatColor, String> stylesToNames;
static {
ImmutableBiMap.Builder<ChatColor, String> builder = ImmutableBiMap.builder();
for (ChatColor style : ChatColor.values()) {
for (final ChatColor style : ChatColor.values()) {
if (!style.isFormat()) {
continue;
}
@ -46,24 +83,57 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa
stylesToNames = builder.build();
}
static {
ConfigurationSerialization.registerClass(MessagePart.class);
public void writeJson(JsonWriter json) {
try {
json.beginObject();
text.writeJson(json);
json.name("color").value(color.name().toLowerCase());
for (final ChatColor style : styles) {
json.name(stylesToNames.get(style)).value(true);
}
if (clickActionName != null && clickActionData != null) {
json.name("clickEvent")
.beginObject()
.name("action").value(clickActionName)
.name("value").value(clickActionData)
.endObject();
}
if (hoverActionName != null && hoverActionData != null) {
json.name("hoverEvent")
.beginObject()
.name("action").value(hoverActionName)
.name("value");
hoverActionData.writeJson(json);
json.endObject();
}
if (insertionData != null) {
json.name("insertion").value(insertionData);
}
if (translationReplacements.size() > 0 && text != null && TextualComponent.isTranslatableText(text)) {
json.name("with").beginArray();
for (JsonRepresentedObject obj : translationReplacements) {
obj.writeJson(json);
}
json.endArray();
}
json.endObject();
} catch (IOException e) {
Bukkit.getLogger().log(Level.WARNING, "A problem occured during writing of JSON string", e);
}
}
ChatColor color = ChatColor.WHITE;
ArrayList<ChatColor> styles = new ArrayList<>();
String clickActionName = null, clickActionData = null, hoverActionName = null;
JsonRepresentedObject hoverActionData = null;
TextualComponent text = null;
String insertionData = null;
ArrayList<JsonRepresentedObject> translationReplacements = new ArrayList<>();
MessagePart(TextualComponent text) {
this.text = text;
}
MessagePart() {
this.text = null;
public Map<String, Object> serialize() {
HashMap<String, Object> map = new HashMap<>();
map.put("text", text);
map.put("styles", styles);
map.put("color", color.getChar());
map.put("hoverActionName", hoverActionName);
map.put("hoverActionData", hoverActionData);
map.put("clickActionName", clickActionName);
map.put("clickActionData", clickActionData);
map.put("insertion", insertionData);
map.put("translationReplacements", translationReplacements);
return map;
}
@SuppressWarnings("unchecked")
@ -80,72 +150,8 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa
return part;
}
boolean hasText() {
return this.text != null;
}
@Override
@SuppressWarnings("unchecked")
public MessagePart clone() throws CloneNotSupportedException {
MessagePart obj = (MessagePart) super.clone();
obj.styles = (ArrayList<ChatColor>) this.styles.clone();
if (this.hoverActionData instanceof JsonString) {
obj.hoverActionData = new JsonString(((JsonString) this.hoverActionData).getValue());
} else if (this.hoverActionData instanceof FancyMessage) {
obj.hoverActionData = ((FancyMessage) this.hoverActionData).clone();
}
obj.translationReplacements = (ArrayList<JsonRepresentedObject>) this.translationReplacements.clone();
return obj;
}
@Override
public void writeJson(JsonWriter json) {
try {
json.beginObject();
this.text.writeJson(json);
json.name("color").value(this.color.name().toLowerCase());
for (ChatColor style : this.styles) {
json.name(stylesToNames.get(style)).value(true);
}
if ((this.clickActionName != null) && (this.clickActionData != null)) {
json.name("clickEvent").beginObject().name("action").value(this.clickActionName).name("value").value(this.clickActionData)
.endObject();
}
if ((this.hoverActionName != null) && (this.hoverActionData != null)) {
json.name("hoverEvent").beginObject().name("action").value(this.hoverActionName).name("value");
this.hoverActionData.writeJson(json);
json.endObject();
}
if (this.insertionData != null) {
json.name("insertion").value(this.insertionData);
}
if (!this.translationReplacements.isEmpty() && (this.text != null) && TextualComponent.isTranslatableText(this.text)) {
json.name("with").beginArray();
for (JsonRepresentedObject obj : this.translationReplacements) {
obj.writeJson(json);
}
json.endArray();
}
json.endObject();
} catch (IOException e) {
Bukkit.getLogger().log(Level.WARNING, "A problem occurred during writing of JSON string", e);
}
}
@Override
public Map<String, Object> serialize() {
HashMap<String, Object> map = new HashMap<>();
map.put("text", this.text);
map.put("styles", this.styles);
map.put("color", this.color.getChar());
map.put("hoverActionName", this.hoverActionName);
map.put("hoverActionData", this.hoverActionData);
map.put("clickActionName", this.clickActionName);
map.put("clickActionData", this.clickActionData);
map.put("insertion", this.insertionData);
map.put("translationReplacements", this.translationReplacements);
return map;
static {
ConfigurationSerialization.registerClass(MessagePart.class);
}
}

View File

@ -1,6 +1,6 @@
package com.plotsquared.bukkit.chat;
import com.intellectualcrafters.plot.PS;
import org.bukkit.Bukkit;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
@ -29,36 +29,48 @@ public final class Reflection {
* The map maps [types to maps of [method names to maps of [parameter types to method instances]]].
*/
private static final Map<Class<?>, Map<String, Map<ArrayWrapper<Class<?>>, Method>>> _loadedMethods = new HashMap<>();
private static String _versionString;
private Reflection() { }
/**
* Gets the version string from the package name of the CraftBukkit server implementation.
* This is needed to bypass the JAR package name changing on each update.
*
* @return The version string of the OBC and NMS packages, <em>including the trailing dot</em>.
*/
public static synchronized String getVersion() {
return PS.get().IMP.getNMSPackage();
public synchronized static String getVersion() {
if (_versionString == null) {
if (Bukkit.getServer() == null) {
// The server hasn't started, static initializer call?
return null;
}
String name = Bukkit.getServer().getClass().getPackage().getName();
_versionString = name.substring(name.lastIndexOf('.') + 1) + ".";
}
return _versionString;
}
/**
* Gets a {@link Class} object representing a type contained within the {@code net.minecraft.server} versioned package.
* The class instances returned by this method are cached, such that no lookup will be done twice (unless multiple threads are accessing this
* method simultaneously).
* The class instances returned by this method are cached, such that no lookup will be done twice (unless multiple threads are accessing this method simultaneously).
*
* @param className The name of the class, excluding the package, within NMS.
* @return The class instance representing the specified NMS class, or {@code null} if it could not be loaded.
*/
public static synchronized Class<?> getNMSClass(String className) {
public synchronized static Class<?> getNMSClass(String className) {
if (_loadedNMSClasses.containsKey(className)) {
return _loadedNMSClasses.get(className);
}
String fullName = "net.minecraft.server." + getVersion() + "." + className;
String fullName = "net.minecraft.server." + getVersion() + className;
Class<?> clazz;
try {
clazz = Class.forName(fullName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
_loadedNMSClasses.put(className, null);
return null;
throw new RuntimeException(e);
}
_loadedNMSClasses.put(className, clazz);
return clazz;
@ -66,25 +78,23 @@ public final class Reflection {
/**
* Gets a {@link Class} object representing a type contained within the {@code org.bukkit.craftbukkit} versioned package.
* The class instances returned by this method are cached, such that no lookup will be done twice (unless multiple threads are accessing this
* method simultaneously).
* @param className The name of the class, excluding the package, within OBC. This name may contain a subpackage name, such as {@code inventory
* .CraftItemStack}.
* The class instances returned by this method are cached, such that no lookup will be done twice (unless multiple threads are accessing this method simultaneously).
*
* @param className The name of the class, excluding the package, within OBC. This name may contain a subpackage name, such as {@code inventory.CraftItemStack}.
* @return The class instance representing the specified OBC class, or {@code null} if it could not be loaded.
*/
public static synchronized Class<?> getOBCClass(String className) {
public synchronized static Class<?> getOBCClass(String className) {
if (_loadedOBCClasses.containsKey(className)) {
return _loadedOBCClasses.get(className);
}
String fullName = "org.bukkit.craftbukkit." + getVersion() + "." + className;
String fullName = "org.bukkit.craftbukkit." + getVersion() + className;
Class<?> clazz;
try {
clazz = Class.forName(fullName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
_loadedOBCClasses.put(className, null);
return null;
throw new RuntimeException(e);
}
_loadedOBCClasses.put(className, clazz);
return clazz;
@ -93,41 +103,35 @@ public final class Reflection {
/**
* Attempts to get the NMS handle of a CraftBukkit object.
* <p>
* The only match currently attempted by this method is a retrieval by using a parameterless {@code getHandle()} method implemented by the
* runtime type of the specified object.
* The only match currently attempted by this method is a retrieval by using a parameterless {@code getHandle()} method implemented by the runtime type of the specified object.
* </p>
*
* @param obj The object for which to retrieve an NMS handle.
* @return The NMS handle of the specified object, or {@code null} if it could not be retrieved using {@code getHandle()}.
*/
public static synchronized Object getHandle(Object obj) {
try {
public synchronized static Object getHandle(Object obj) throws InvocationTargetException, IllegalAccessException, IllegalArgumentException {
return getMethod(obj.getClass(), "getHandle").invoke(obj);
} catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException e) {
e.printStackTrace();
return null;
}
}
/**
* Retrieves a {@link Field} instance declared by the specified class with the specified name.
* Java access modifiers are ignored during this retrieval.
* No guarantee is made as to whether the field returned will be an
* instance or static field.
* Java access modifiers are ignored during this retrieval. No guarantee is made as to whether the field
* returned will be an instance or static field.
* <p>
* A global caching mechanism within this class is used to store fields. Combined with synchronization, this guarantees that
* no field will be reflectively looked up twice.
* </p>
* <p>
* If a field is deemed suitable for return,
* {@link Field#setAccessible(boolean) setAccessible} will be invoked with an argument of {@code true} before it is returned.
* If a field is deemed suitable for return, {@link Field#setAccessible(boolean) setAccessible} will be invoked with an argument of {@code true} before it is returned.
* This ensures that callers do not have to check or worry about Java access modifiers when dealing with the returned instance.
* </p>
*
* @param clazz The class which contains the field to retrieve.
* @param name The declared name of the field in the class.
* @param name The declared name of the field in the class.
* @return A field object with the specified name declared by the specified class.
* @see Class#getDeclaredField(String)
*/
public static synchronized Field getField(Class<?> clazz, String name) {
public synchronized static Field getField(Class<?> clazz, String name) {
Map<String, Field> loaded;
if (!_loadedFields.containsKey(clazz)) {
loaded = new HashMap<>();
@ -160,22 +164,19 @@ public final class Reflection {
* <p>
* A global caching mechanism within this class is used to store method. Combined with synchronization, this guarantees that
* no method will be reflectively looked up twice.
* </p>
* <p>
* If a method is deemed suitable for return, {@link Method#setAccessible(boolean) setAccessible} will be invoked with an argument of {@code
* true} before it is returned.
* If a method is deemed suitable for return, {@link Method#setAccessible(boolean) setAccessible} will be invoked with an argument of {@code true} before it is returned.
* This ensures that callers do not have to check or worry about Java access modifiers when dealing with the returned instance.
* </p>
*
* <p>
* This method does <em>not</em> search superclasses of the specified type for methods with the specified signature.
* Callers wishing this behavior should use {@link Class#getDeclaredMethod(String, Class...)}.
*
* @param clazz The class which contains the method to retrieve.
* @param name The declared name of the method in the class.
* @param args The formal argument types of the method.
* @param name The declared name of the method in the class.
* @param args The formal argument types of the method.
* @return A method object with the specified name declared by the specified class.
*/
public static synchronized Method getMethod(Class<?> clazz, String name, Class<?>... args) {
public synchronized static Method getMethod(Class<?> clazz, String name, Class<?>... args) {
if (!_loadedMethods.containsKey(clazz)) {
_loadedMethods.put(clazz, new HashMap<String, Map<ArrayWrapper<Class<?>>, Method>>());
}

View File

@ -3,8 +3,8 @@ package com.plotsquared.bukkit.chat;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.gson.stream.JsonWriter;
import com.intellectualcrafters.configuration.serialization.ConfigurationSerializable;
import com.intellectualcrafters.configuration.serialization.ConfigurationSerialization;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.configuration.serialization.ConfigurationSerialization;
import java.io.IOException;
import java.util.HashMap;
@ -24,10 +24,10 @@ public abstract class TextualComponent implements Cloneable {
}
static TextualComponent deserialize(Map<String, Object> map) {
if (map.containsKey("key") && (map.size() == 2) && map.containsKey("value")) {
if (map.containsKey("key") && map.size() == 2 && map.containsKey("value")) {
// Arbitrary text component
return ArbitraryTextTypeComponent.deserialize(map);
} else if ((map.size() >= 2) && map.containsKey("key") && !map.containsKey("value") /* It contains keys that START WITH value */) {
} else if (map.size() >= 2 && map.containsKey("key") && !map.containsKey("value") /* It contains keys that START WITH value */) {
// Complex JSON object
return ComplexTextTypeComponent.deserialize(map);
}
@ -40,12 +40,15 @@ public abstract class TextualComponent implements Cloneable {
}
static boolean isTranslatableText(TextualComponent component) {
return (component instanceof ComplexTextTypeComponent) && component.getKey().equals("translate");
return component instanceof ComplexTextTypeComponent && component.getKey().equals("translate");
}
/**
* Create a textual component representing a string literal.
* This is the default type of textual component when a single string literal is given to a method.
*
* <p>This is the default type of textual component when a single string
* literal is given to a method.
*
* @param textValue The text which will be represented.
* @return The text component representing the specified literal text.
*/
@ -61,6 +64,7 @@ public abstract class TextualComponent implements Cloneable {
* If the specified translation key is not present on the client resource pack, the translation key will be displayed as a string literal to
* the client.
* </p>
*
* @param translateKey The string key which maps to localized text.
* @return The text component representing the specified localized text.
*/
@ -78,6 +82,7 @@ public abstract class TextualComponent implements Cloneable {
* <p>
* <b>This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients.</b>
* </p>
*
* @param scoreboardObjective The name of the objective for which to display the score.
* @return The text component representing the specified scoreboard score (for the viewing player), or {@code null} if an error occurs during
* JSON serialization.
@ -89,22 +94,28 @@ public abstract class TextualComponent implements Cloneable {
/**
* Create a textual component representing a scoreboard value.
* The client will see the score of the specified player for the specified objective as the text represented by this component.
* <p>
* <b>This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients.</b>
* </p>
* @param playerName The name of the player whos score will be shown. If this string represents the single-character sequence "*", the viewing
* player's score will be displayed.
* Standard minecraft selectors (@a, @p, etc) are <em>not</em> supported.
* @param scoreboardObjective The name of the objective for which to display the score.
* @return The text component representing the specified scoreboard score for the specified player, or {@code null} if an error occurs during
* JSON serialization.
*
* <p><b>This method is currently guaranteed to throw an {@code UnsupportedOperationException}
* as it is only supported on snapshot clients.</b>
*
* @param playerName The name of the player whos score will be shown. If
* this string represents the single-character sequence
* "*", the viewing player's score will be displayed.
* Standard minecraft selectors (@a, @p, etc)
* are <em>not</em> supported.
* @param scoreboardObjective The name of the objective for
* which to display the score.
* @return The text component representing the specified scoreboard score
* for the specified player, or {@code null} if an error occurs during JSON serialization.
*/
public static TextualComponent objectiveScore(String playerName, String scoreboardObjective) {
throwUnsupportedSnapshot(); // Remove this line when the feature is released to non-snapshot versions, in addition to updating ALL THE
// OVERLOADS documentation accordingly
return new ComplexTextTypeComponent("score",
ImmutableMap.<String, String>builder().put("name", playerName).put("objective", scoreboardObjective).build());
return new ComplexTextTypeComponent("score", ImmutableMap.<String, String>builder()
.put("name", playerName)
.put("objective", scoreboardObjective)
.build());
}
/**
@ -113,6 +124,7 @@ public abstract class TextualComponent implements Cloneable {
* <p>
* <b>This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients.</b>
* </p>
*
* @param selector The minecraft player or entity selector which will capture the entities whose string representations will be displayed in
* the place of this text component.
* @return The text component representing the name of the entities captured by the selector.
@ -149,6 +161,7 @@ public abstract class TextualComponent implements Cloneable {
/**
* Writes the text data represented by this textual component to the specified JSON writer object.
* A new object within the writer is not started.
*
* @param writer The object to which to write the JSON data.
* @throws IOException If an error occurs while writing to the stream.
*/
@ -160,8 +173,8 @@ public abstract class TextualComponent implements Cloneable {
*/
private static final class ArbitraryTextTypeComponent extends TextualComponent implements ConfigurationSerializable {
private String _key;
private String _value;
private String key;
private String value;
public ArbitraryTextTypeComponent(String key, String value) {
setKey(key);
@ -174,21 +187,21 @@ public abstract class TextualComponent implements Cloneable {
@Override
public String getKey() {
return this._key;
return key;
}
public void setKey(String key) {
Preconditions.checkArgument((key != null) && !key.isEmpty(), "The key must be specified.");
this._key = key;
Preconditions.checkArgument(key != null && !key.isEmpty(), "The key must be specified.");
this.key = key;
}
public String getValue() {
return this._value;
return value;
}
public void setValue(String value) {
Preconditions.checkArgument(value != null, "The value must be specified.");
this._value = value;
this.value = value;
}
@Override
@ -220,13 +233,15 @@ public abstract class TextualComponent implements Cloneable {
}
/**
* Internal class used to represent a text component with a nested JSON value.
* Exception validating done is on keys and values.
* Internal class used to represent a text component with a nested JSON
* value.
*
* <p>Exception validating done is on keys and values.
*/
private static final class ComplexTextTypeComponent extends TextualComponent implements ConfigurationSerializable {
private String _key;
private Map<String, String> _value;
private String key;
private Map<String, String> value;
public ComplexTextTypeComponent(String key, Map<String, String> values) {
setKey(key);
@ -235,7 +250,7 @@ public abstract class TextualComponent implements Cloneable {
public static ComplexTextTypeComponent deserialize(Map<String, Object> map) {
String key = null;
Map<String, String> value = new HashMap<String, String>();
Map<String, String> value = new HashMap<>();
for (Map.Entry<String, Object> valEntry : map.entrySet()) {
if (valEntry.getKey().equals("key")) {
key = (String) valEntry.getValue();
@ -248,25 +263,25 @@ public abstract class TextualComponent implements Cloneable {
@Override
public String getKey() {
return this._key;
return key;
}
public void setKey(String key) {
Preconditions.checkArgument((key != null) && !key.isEmpty(), "The key must be specified.");
this._key = key;
Preconditions.checkArgument(key != null && !key.isEmpty(), "The key must be specified.");
this.key = key;
}
public Map<String, String> getValue() {
return this._value;
return value;
}
public void setValue(Map<String, String> value) {
Preconditions.checkArgument(value != null, "The value must be specified.");
this._value = value;
this.value = value;
}
@Override
public TextualComponent clone() throws CloneNotSupportedException {
public TextualComponent clone() {
// Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone
return new ComplexTextTypeComponent(getKey(), getValue());
}
@ -275,7 +290,7 @@ public abstract class TextualComponent implements Cloneable {
public void writeJson(JsonWriter writer) throws IOException {
writer.name(getKey());
writer.beginObject();
for (Map.Entry<String, String> jsonPair : this._value.entrySet()) {
for (Map.Entry<String, String> jsonPair : value.entrySet()) {
writer.name(jsonPair.getKey()).value(jsonPair.getValue());
}
writer.endObject();

View File

@ -1,31 +1,11 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.commands;
import com.google.common.collect.Sets;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.commands.CommandCategory;
import com.intellectualcrafters.plot.commands.RequiredType;
import com.intellectualcrafters.plot.commands.SubCommand;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.database.AbstractDB;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.object.OfflinePlotPlayer;
import com.intellectualcrafters.plot.object.Plot;
@ -37,14 +17,13 @@ import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.util.WorldUtil;
import com.intellectualcrafters.plot.uuid.UUIDWrapper;
import com.plotsquared.bukkit.uuid.DatFileFilter;
import com.plotsquared.bukkit.uuid.DefaultUUIDWrapper;
import com.plotsquared.bukkit.uuid.LowerOfflineUUIDWrapper;
import com.plotsquared.bukkit.uuid.OfflineUUIDWrapper;
import com.plotsquared.general.commands.Argument;
import com.plotsquared.general.commands.CommandDeclaration;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
@ -87,7 +66,7 @@ public class DebugUUID extends SubCommand {
try {
Class<?> clazz = Class.forName(args[0]);
newWrapper = (UUIDWrapper) clazz.newInstance();
} catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
} catch (ClassNotFoundException | IllegalAccessException | InstantiationException ignored) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot uuidconvert <lower|offline|online>");
return false;
}
@ -112,7 +91,7 @@ public class DebugUUID extends SubCommand {
MainUtil.sendMessage(player, "&6Beginning UUID mode conversion");
MainUtil.sendMessage(player, "&7 - Disconnecting players");
for (Entry<String, PlotPlayer> entry : UUIDHandler.getPlayers().entrySet()) {
entry.getValue().kick("PlotSquared UUID conversion has been initiated. You may reconnect when finished.");
entry.getValue().kick("UUID conversion has been initiated. You may reconnect when finished.");
}
MainUtil.sendMessage(player, "&7 - Initializing map");
@ -122,37 +101,25 @@ public class DebugUUID extends SubCommand {
MainUtil.sendMessage(player, "&7 - Collecting playerdata");
HashSet<String> worlds = new HashSet<>();
worlds.add(WorldUtil.IMP.getMainWorld());
worlds.add("world");
HashSet<String> worlds = Sets.newHashSet(WorldUtil.IMP.getMainWorld(), "world");
HashSet<UUID> uuids = new HashSet<>();
HashSet<String> names = new HashSet<>();
for (String worldname : worlds) {
File playerdataFolder = new File(worldname + File.separator + "playerdata");
String[] dat = playerdataFolder.list(new FilenameFilter() {
@Override
public boolean accept(File f, String s) {
return s.endsWith(".dat");
}
});
for (String worldName : worlds) {
File playerDataFolder = new File(worldName + File.separator + "playerdata");
String[] dat = playerDataFolder.list(new DatFileFilter());
if (dat != null) {
for (String current : dat) {
String s = current.replaceAll(".dat$", "");
try {
UUID uuid = UUID.fromString(s);
uuids.add(uuid);
} catch (Exception e) {
} catch (Exception ignored) {
MainUtil.sendMessage(player, C.PREFIX + "Invalid playerdata: " + current);
}
}
}
File playersFolder = new File(worldname + File.separator + "players");
dat = playersFolder.list(new FilenameFilter() {
@Override
public boolean accept(File f, String s) {
return s.endsWith(".dat");
}
});
File playersFolder = new File(worldName + File.separator + "players");
dat = playersFolder.list(new DatFileFilter());
if (dat != null) {
for (String current : dat) {
names.add(current.replaceAll(".dat$", ""));
@ -172,7 +139,7 @@ public class DebugUUID extends SubCommand {
uCMap.put(uuid, uuid2);
uCReverse.put(uuid2, uuid);
}
} catch (Throwable e) {
} catch (Throwable ignored) {
MainUtil.sendMessage(player, C.PREFIX + "&6Invalid playerdata: " + uuid.toString() + ".dat");
}
}
@ -188,7 +155,7 @@ public class DebugUUID extends SubCommand {
MainUtil.sendMessage(player, "&c - Error! Attempting to repopulate");
for (OfflinePlotPlayer op : currentUUIDWrapper.getOfflinePlayers()) {
if (op.getLastPlayed() != 0) {
// String name = op.getName();
// String name = op.getPluginName();
// StringWrapper wrap = new StringWrapper(name);
UUID uuid = currentUUIDWrapper.getUUID(op);
uuid2 = newWrapper.getUUID(op);
@ -268,13 +235,12 @@ public class DebugUUID extends SubCommand {
}
MainUtil.sendMessage(player, "&7 - Deleting database");
final AbstractDB database = DBFunc.dbManager;
boolean result = database.deleteTables();
boolean result = DBFunc.deleteTables();
MainUtil.sendMessage(player, "&7 - Creating tables");
try {
database.createTables();
DBFunc.createTables();
if (!result) {
MainUtil.sendMessage(player, "&cConversion failed! Attempting recovery");
for (Plot plot : PS.get().getPlots()) {
@ -283,7 +249,7 @@ public class DebugUUID extends SubCommand {
plot.owner = value;
}
}
database.createPlotsAndData(new ArrayList<>(PS.get().getPlots()), new Runnable() {
DBFunc.createPlotsAndData(new ArrayList<>(PS.get().getPlots()), new Runnable() {
@Override
public void run() {
MainUtil.sendMessage(player, "&6Recovery was successful!");
@ -297,16 +263,16 @@ public class DebugUUID extends SubCommand {
}
if (newWrapper instanceof OfflineUUIDWrapper) {
PS.get().config.set("UUID.force-lowercase", false);
PS.get().config.set("UUID.offline", true);
PS.get().worlds.set("UUID.force-lowercase", false);
PS.get().worlds.set("UUID.offline", true);
} else if (newWrapper instanceof DefaultUUIDWrapper) {
PS.get().config.set("UUID.force-lowercase", false);
PS.get().config.set("UUID.offline", false);
PS.get().worlds.set("UUID.force-lowercase", false);
PS.get().worlds.set("UUID.offline", false);
}
try {
PS.get().config.save(PS.get().configFile);
} catch (IOException e) {
MainUtil.sendMessage(player, "Could not save configuration. It will need to be manuall set!");
PS.get().worlds.save(PS.get().worldsFile);
} catch (IOException ignored) {
MainUtil.sendMessage(player, "Could not save configuration. It will need to be manual set!");
}
MainUtil.sendMessage(player, "&7 - Populating tables");
@ -315,7 +281,7 @@ public class DebugUUID extends SubCommand {
@Override
public void run() {
ArrayList<Plot> plots = new ArrayList<>(PS.get().getPlots());
database.createPlotsAndData(plots, new Runnable() {
DBFunc.createPlotsAndData(plots, new Runnable() {
@Override
public void run() {
MainUtil.sendMessage(player, "&aConversion complete!");

View File

@ -5,8 +5,6 @@ import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotId;
import org.bukkit.Bukkit;
import org.bukkit.World;
import java.sql.Connection;
import java.sql.SQLException;
@ -21,49 +19,42 @@ public abstract class APlotMeConnector {
public abstract boolean accepts(String version);
public String getWorld(String world) {
for (World newWorld : Bukkit.getWorlds()) {
if (newWorld.getName().equalsIgnoreCase(world)) {
return newWorld.getName();
}
}
return world;
}
public boolean isValidConnection(Connection connection) {
return connection != null;
}
public void copyConfig(FileConfiguration plotConfig, String world, String actualWorldName) {
int pathWidth = plotConfig.getInt("worlds." + world + ".PathWidth"); //
PS.get().config.set("worlds." + actualWorldName + ".road.width", pathWidth);
PS.get().worlds.set("worlds." + actualWorldName + ".road.width", pathWidth);
int plotSize = plotConfig.getInt("worlds." + world + ".PlotSize"); //
PS.get().config.set("worlds." + actualWorldName + ".plot.size", plotSize);
PS.get().worlds.set("worlds." + actualWorldName + ".plot.size", plotSize);
String wallBlock = plotConfig.getString("worlds." + world + ".WallBlockId"); //
PS.get().config.set("worlds." + actualWorldName + ".wall.block", wallBlock);
PS.get().worlds.set("worlds." + actualWorldName + ".wall.block", wallBlock);
String floor = plotConfig.getString("worlds." + world + ".PlotFloorBlockId"); //
PS.get().config.set("worlds." + actualWorldName + ".plot.floor", Collections.singletonList(floor));
PS.get().worlds.set("worlds." + actualWorldName + ".plot.floor", Collections.singletonList(floor));
String filling = plotConfig.getString("worlds." + world + ".PlotFillingBlockId"); //
PS.get().config.set("worlds." + actualWorldName + ".plot.filling", Collections.singletonList(filling));
PS.get().worlds.set("worlds." + actualWorldName + ".plot.filling", Collections.singletonList(filling));
String road = plotConfig.getString("worlds." + world + ".RoadMainBlockId");
PS.get().config.set("worlds." + actualWorldName + ".road.block", road);
PS.get().worlds.set("worlds." + actualWorldName + ".road.block", road);
int height = plotConfig.getInt("worlds." + world + ".RoadHeight"); //
PS.get().config.set("worlds." + actualWorldName + ".road.height", height);
PS.get().worlds.set("worlds." + actualWorldName + ".road.height", height);
PS.get().worlds.set("worlds." + actualWorldName + ".plot.height", height);
PS.get().worlds.set("worlds." + actualWorldName + ".wall.height", height);
}
public Location getPlotTopLocAbs(int path, int plot, PlotId plotid) {
int px = plotid.x;
int pz = plotid.y;
int x = (px * (path + plot)) - (int) Math.floor(path / 2) - 1;
int z = (pz * (path + plot)) - (int) Math.floor(path / 2) - 1;
public Location getPlotTopLocAbs(int path, int plot, PlotId plotId) {
int px = plotId.x;
int pz = plotId.y;
int x = px * (path + plot) - (int) Math.floor(path / 2) - 1;
int z = pz * (path + plot) - (int) Math.floor(path / 2) - 1;
return new Location(null, x, 256, z);
}
public Location getPlotBottomLocAbs(int path, int plot, PlotId plotid) {
int px = plotid.x;
int pz = plotid.y;
int x = (px * (path + plot)) - plot - (int) Math.floor(path / 2) - 1;
int z = (pz * (path + plot)) - plot - (int) Math.floor(path / 2) - 1;
public Location getPlotBottomLocAbs(int path, int plot, PlotId plotId) {
int px = plotId.x;
int pz = plotId.y;
int x = px * (path + plot) - plot - (int) Math.floor(path / 2) - 1;
int z = pz * (path + plot) - plot - (int) Math.floor(path / 2) - 1;
return new Location(null, x, 1, z);
}

View File

@ -26,25 +26,24 @@ import java.util.UUID;
public class ClassicPlotMeConnector extends APlotMeConnector {
private String plugin;
private String plugin = "PlotMe";
private String prefix;
@Override
public Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, String dataFolder) {
this.plugin = plugin.toLowerCase();
this.prefix = plotConfig.getString("mySQLprefix", plugin.toLowerCase());
this.prefix = plotConfig.getString("mySQLprefix", this.plugin.toLowerCase());
try {
if (plotConfig.getBoolean("usemySQL")) {
String user = plotConfig.getString("mySQLuname");
String password = plotConfig.getString("mySQLpass");
String con = plotConfig.getString("mySQLconn");
return DriverManager.getConnection(con, user, password);
// return new MySQL(plotsquared, hostname, port, database, username, password)
} else {
return new SQLite(dataFolder + File.separator + "plots.db").openConnection();
return new SQLite(new File(dataFolder + File.separator + "plots.db")).openConnection();
}
} catch (SQLException | ClassNotFoundException ignored) {
//ignored
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
@ -65,7 +64,7 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
} else if (checkUUID2) {
column = "ownerId";
}
boolean merge = !"plotme".equalsIgnoreCase(this.plugin) && Settings.CONVERT_PLOTME;
boolean merge = !"plotme".equalsIgnoreCase(this.plugin) && Settings.Enabled_Components.PLOTME_CONVERTER;
int missing = 0;
while (resultSet.next()) {
PlotId id = new PlotId(resultSet.getInt("idX"), resultSet.getInt("idZ"));
@ -74,8 +73,8 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
if (!plots.containsKey(world)) {
plots.put(world, new HashMap<PlotId, Plot>());
if (merge) {
int plot = PS.get().config.getInt("worlds." + world + ".plot.size");
int path = PS.get().config.getInt("worlds." + world + ".road.width");
int plot = PS.get().worlds.getInt("worlds." + world + ".plot.size");
int path = PS.get().worlds.getInt("worlds." + world + ".road.width");
plotWidth.put(world, plot);
roadWidth.put(world, path);
merges.put(world, new HashMap<PlotId, boolean[]>());
@ -109,32 +108,21 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
owner = DBFunc.everyone;
} else {
if (checkUUID || checkUUID2) {
try {
byte[] bytes = resultSet.getBytes(column);
if (bytes != null) {
try {
ByteBuffer bb = ByteBuffer.wrap(bytes);
long high = bb.getLong();
long low = bb.getLong();
owner = new UUID(high, low);
} catch (Exception e) {
e.printStackTrace();
owner = UUID.nameUUIDFromBytes(bytes);
}
UUIDHandler.add(new StringWrapper(name), owner);
}
} catch (SQLException e) {
e.printStackTrace();
byte[] bytes = resultSet.getBytes(column);
if (bytes != null) {
ByteBuffer bb = ByteBuffer.wrap(bytes);
long high = bb.getLong();
long low = bb.getLong();
owner = new UUID(high, low);
UUIDHandler.add(new StringWrapper(name), owner);
}
}
if (owner == null) {
if (!name.isEmpty()) {
owner = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name.toLowerCase()).getBytes(Charsets.UTF_8));
}
if (name.isEmpty()) {
PS.log("&cCould not identify owner for plot: " + id + " -> '" + name + "'");
missing++;
continue;
}
owner = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name.toLowerCase()).getBytes(Charsets.UTF_8));
}
} else {
UUIDHandler.add(new StringWrapper(name), owner);
@ -153,8 +141,8 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
for (Entry<String, HashMap<PlotId, boolean[]>> entry : merges.entrySet()) {
String world = entry.getKey();
for (Entry<PlotId, boolean[]> entry2 : entry.getValue().entrySet()) {
HashMap<PlotId, Plot> newplots = plots.get(world);
Plot plot = newplots.get(entry2.getKey());
HashMap<PlotId, Plot> newPlots = plots.get(world);
Plot plot = newPlots.get(entry2.getKey());
if (plot != null) {
plot.setMerged(entry2.getValue());
}
@ -179,22 +167,13 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
if ("*".equals(name)) {
denied = DBFunc.everyone;
} else if (DBFunc.hasColumn(resultSet, "playerid")) {
try {
byte[] bytes = resultSet.getBytes("playerid");
if (bytes != null) {
try {
ByteBuffer bb = ByteBuffer.wrap(bytes);
long high = bb.getLong();
long low = bb.getLong();
denied = new UUID(high, low);
} catch (Exception e) {
e.printStackTrace();
denied = UUID.nameUUIDFromBytes(bytes);
}
UUIDHandler.add(new StringWrapper(name), denied);
}
} catch (SQLException e) {
e.printStackTrace();
byte[] bytes = resultSet.getBytes("playerid");
if (bytes != null) {
ByteBuffer bb = ByteBuffer.wrap(bytes);
long mostSigBits = bb.getLong();
long leastSigBits = bb.getLong();
denied = new UUID(mostSigBits, leastSigBits);
UUIDHandler.add(new StringWrapper(name), denied);
}
}
if (denied == null) {
@ -223,22 +202,13 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
if ("*".equals(name)) {
helper = DBFunc.everyone;
} else if (DBFunc.hasColumn(resultSet, "playerid")) {
try {
byte[] bytes = resultSet.getBytes("playerid");
if (bytes != null) {
try {
ByteBuffer bb = ByteBuffer.wrap(bytes);
long high = bb.getLong();
long low = bb.getLong();
helper = new UUID(high, low);
} catch (Exception e) {
e.printStackTrace();
helper = UUID.nameUUIDFromBytes(bytes);
}
UUIDHandler.add(new StringWrapper(name), helper);
}
} catch (SQLException e) {
e.printStackTrace();
byte[] bytes = resultSet.getBytes("playerid");
if (bytes != null) {
ByteBuffer bb = ByteBuffer.wrap(bytes);
long mostSigBits = bb.getLong();
long leastSigBits = bb.getLong();
helper = new UUID(mostSigBits, leastSigBits);
UUIDHandler.add(new StringWrapper(name), helper);
}
}
if (helper == null) {
@ -258,9 +228,7 @@ public class ClassicPlotMeConnector extends APlotMeConnector {
resultSet.close();
statement.close();
} catch (SQLException ignored) {
//ignored
}
} catch (SQLException ignored) {}
return plots;
}

View File

@ -1,42 +1,17 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.database.plotme;
import com.intellectualcrafters.configuration.ConfigurationSection;
import com.intellectualcrafters.configuration.MemorySection;
import com.intellectualcrafters.configuration.file.FileConfiguration;
import com.intellectualcrafters.configuration.file.YamlConfiguration;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.generator.HybridGen;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.bukkit.generator.BukkitPlotGenerator;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.WorldCreator;
import org.bukkit.command.CommandException;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@ -44,45 +19,42 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.WorldCreator;
import org.bukkit.command.CommandException;
public class LikePlotMeConverter {
private final String plugin;
/**
* Constructor.
*
* @param plugin Plugin Used to run the converter
*/
public LikePlotMeConverter(String plugin) {
this.plugin = plugin;
}
public static String getWorld(String world) {
for (World newworld : Bukkit.getWorlds()) {
if (newworld.getName().equalsIgnoreCase(world)) {
return newworld.getName();
for (World newWorld : Bukkit.getWorlds()) {
if (newWorld.getName().equalsIgnoreCase(world)) {
return newWorld.getName();
}
}
return world;
}
private void sendMessage(String message) {
PS.debug("&3PlotMe&8->&3PlotSquared&8: &7" + message);
PS.debug("&3PlotMe&8->&3" + PS.imp().getPluginName() + "&8: &7" + message);
}
public String getPlotMePath() {
return new File(".").getAbsolutePath() + File.separator + "plugins" + File.separator + this.plugin + File.separator;
}
public String getAthionPlotsPath() {
return new File(".").getAbsolutePath() + File.separator + "plugins" + File.separator + this.plugin + File.separator;
return new File(".").getAbsolutePath() + File.separator + "plugins" + File.separator + plugin + File.separator;
}
public FileConfiguration getPlotMeConfig(String dataFolder) {
@ -97,7 +69,7 @@ public class LikePlotMeConverter {
return plotConfig.getConfigurationSection("worlds").getKeys(false);
}
public void mergeWorldYml(String plugin, FileConfiguration plotConfig) {
public void mergeWorldYml(FileConfiguration plotConfig) {
try {
File genConfig =
new File("plugins" + File.separator + plugin + File.separator + "PlotMe-DefaultGenerator" + File.separator + "config.yml");
@ -117,7 +89,7 @@ public class LikePlotMeConverter {
}
}
public void updateWorldYml(String plugin, String location) {
public void updateWorldYml(String location) {
try {
Path path = Paths.get(location);
File file = new File(location);
@ -125,12 +97,40 @@ public class LikePlotMeConverter {
return;
}
String content = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
content = content.replaceAll("PlotMe-DefaultGenerator", "PlotSquared");
content = content.replaceAll(plugin, "PlotSquared");
String pluginName = PS.imp().getPluginName();
content = content.replace("PlotMe-DefaultGenerator", pluginName);
content = content.replace("PlotMe", pluginName);
content = content.replace("AthionPlots", pluginName);
content = content.replace("PlotZWorld", pluginName);
Files.write(path, content.getBytes(StandardCharsets.UTF_8));
} catch (IOException ignored) {
//ignored
}
} catch (IOException ignored) {}
}
private void copyConfig(ConfigurationSection plotmeDgYml, String world) throws IOException {
String actualWorldName = getWorld(world);
String plotMeWorldName = world.toLowerCase();
Integer pathWidth = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".PathWidth"); //
PS.get().worlds.set("worlds." + world + ".road.width", pathWidth);
int height = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".RoadHeight", plotmeDgYml.getInt("worlds." + plotMeWorldName + ".GroundHeight", 64)); //
PS.get().worlds.set("worlds." + world + ".road.height", height);
PS.get().worlds.set("worlds." + world + ".wall.height", height);
PS.get().worlds.set("worlds." + world + ".plot.height", height);
int plotSize = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".PlotSize", 32); //
PS.get().worlds.set("worlds." + world + ".plot.size", plotSize);
String wallblock = plotmeDgYml.getString("worlds." + plotMeWorldName + ".UnclaimedBorder", plotmeDgYml.getString("worlds." + plotMeWorldName + ".WallBlock", "44")); //
PS.get().worlds.set("worlds." + world + ".wall.block", wallblock);
String claimed = plotmeDgYml.getString("worlds." + plotMeWorldName + ".ProtectedWallBlock", "44:1"); //
PS.get().worlds.set("worlds." + world + ".wall.block_claimed", claimed);
String floor = plotmeDgYml.getString("worlds." + plotMeWorldName + ".PlotFloorBlock", "2"); //
PS.get().worlds.set("worlds." + world + ".plot.floor", Collections.singletonList(floor));
String filling = plotmeDgYml.getString("worlds." + plotMeWorldName + ".FillBlock", "3"); //
PS.get().worlds.set("worlds." + world + ".plot.filling", Collections.singletonList(filling));
String road = plotmeDgYml.getString("worlds." + plotMeWorldName + ".RoadMainBlock", "5");
PS.get().worlds.set("worlds." + world + ".road.block", road);
PS.get().worlds.set("worlds." + actualWorldName + ".road.height", height);
PS.get().worlds.set("worlds." + actualWorldName + ".plot.height", height);
PS.get().worlds.set("worlds." + actualWorldName + ".wall.height", height);
PS.get().worlds.save(PS.get().worldsFile);
}
public boolean run(APlotMeConnector connector) {
@ -151,37 +151,37 @@ public class LikePlotMeConverter {
PS.debug("&3Using connector: " + connector.getClass().getCanonicalName());
Connection connection = connector.getPlotMeConnection(this.plugin, plotConfig, dataFolder);
Connection connection = connector.getPlotMeConnection(plugin,plotConfig, dataFolder);
if (!connector.isValidConnection(connection)) {
sendMessage("Cannot connect to PlotMe DB. Conversion process will not continue");
return false;
}
sendMessage(this.plugin + " conversion has started. To disable this, please set 'plotme-convert.enabled' to false in the 'settings.yml'");
sendMessage("PlotMe conversion has started. To disable this, please set 'enabled-components -> plotme-converter' to false in the 'settings.yml'");
mergeWorldYml(this.plugin, plotConfig);
mergeWorldYml(plotConfig);
sendMessage("Connecting to " + this.plugin + " DB");
sendMessage("Connecting to PlotMe DB");
ArrayList<Plot> createdPlots = new ArrayList<>();
sendMessage("Collecting plot data");
String dbPrefix = this.plugin.toLowerCase();
String dbPrefix = "PlotMe".toLowerCase();
sendMessage(" - " + dbPrefix + "Plots");
final Set<String> worlds = getPlotMeWorlds(plotConfig);
if (Settings.CONVERT_PLOTME) {
if (Settings.Enabled_Components.PLOTME_CONVERTER) {
sendMessage("Updating bukkit.yml");
updateWorldYml(this.plugin, "bukkit.yml");
updateWorldYml(this.plugin, "plugins/Multiverse-Core/worlds.yml");
updateWorldYml("bukkit.yml");
updateWorldYml("plugins/Multiverse-Core/worlds.yml");
for (String world : plotConfig.getConfigurationSection("worlds").getKeys(false)) {
sendMessage("Copying config for: " + world);
try {
String actualWorldName = getWorld(world);
connector.copyConfig(plotConfig, world, actualWorldName);
PS.get().config.save(PS.get().configFile);
PS.get().worlds.save(PS.get().worldsFile);
} catch (IOException e) {
e.printStackTrace();
sendMessage("&c-- &lFailed to save configuration for world '" + world
@ -194,7 +194,7 @@ public class LikePlotMeConverter {
for (Entry<String, HashMap<PlotId, Plot>> entry : plots.entrySet()) {
plotCount += entry.getValue().size();
}
if (!Settings.CONVERT_PLOTME) {
if (!Settings.Enabled_Components.PLOTME_CONVERTER) {
return false;
}
@ -205,53 +205,13 @@ public class LikePlotMeConverter {
if (plotmeDgFile.exists()) {
YamlConfiguration plotmeDgYml = YamlConfiguration.loadConfiguration(plotmeDgFile);
try {
for (String world : plots.keySet()) {
String actualWorldName = getWorld(world);
String plotMeWorldName = world.toLowerCase();
Integer pathwidth = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".PathWidth"); //
/*
* TODO: dead code
*
if (pathwidth == null) {
pathwidth = 7;
}
*/
PS.get().config.set("worlds." + world + ".road.width", pathwidth);
Integer pathheight = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".RoadHeight"); //
if (pathheight == 0) {
pathheight = 64;
}
PS.get().config.set("worlds." + world + ".road.height", pathheight);
PS.get().config.set("worlds." + world + ".wall.height", pathheight);
PS.get().config.set("worlds." + world + ".plot.height", pathheight);
Integer plotsize = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".PlotSize"); //
if (plotsize == 0) {
plotsize = 32;
}
PS.get().config.set("worlds." + world + ".plot.size", plotsize);
String wallblock = plotmeDgYml.getString("worlds." + plotMeWorldName + ".WallBlock", "44"); //
PS.get().config.set("worlds." + world + ".wall.block", wallblock);
String floor = plotmeDgYml.getString("worlds." + plotMeWorldName + ".PlotFloorBlock", "2"); //
PS.get().config.set("worlds." + world + ".plot.floor", Collections.singletonList(floor));
String filling = plotmeDgYml.getString("worlds." + plotMeWorldName + ".FillBlock", "3"); //
PS.get().config.set("worlds." + world + ".plot.filling", Collections.singletonList(filling));
String road = plotmeDgYml.getString("worlds." + plotMeWorldName + ".RoadMainBlock", "5");
PS.get().config.set("worlds." + world + ".road.block", road);
Integer height = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".RoadHeight"); //
if (height == 0) {
height = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".GroundHeight"); //
if (height == 0) {
height = 64;
}
}
PS.get().config.set("worlds." + actualWorldName + ".road.height", height);
PS.get().config.set("worlds." + actualWorldName + ".plot.height", height);
PS.get().config.set("worlds." + actualWorldName + ".wall.height", height);
PS.get().config.save(PS.get().configFile);
HashSet<String> allWorlds = new HashSet<>(plots.keySet());
allWorlds.addAll(worlds);
for (String world : allWorlds) {
copyConfig(plotmeDgYml, world);
}
} catch (IOException ignored) {
//ignored
ignored.printStackTrace();
}
}
for (Entry<String, HashMap<PlotId, Plot>> entry : plots.entrySet()) {
@ -301,7 +261,7 @@ public class LikePlotMeConverter {
done();
sendMessage("&aDatabase conversion is now complete!");
PS.debug("&c - Stop the server");
PS.debug("&c - Disable 'plotme-convert.enabled' and 'plotme-convert.cache-uuids' in the settings.yml");
PS.debug("&c - Disable 'plotme-converter' and 'plotme-convert.cache-uuids' in the settings.yml");
PS.debug("&c - Correct any generator settings that haven't copied to 'settings.yml' properly");
PS.debug("&c - Start the server");
PS.get().setPlots(DBFunc.getPlots());
@ -313,8 +273,8 @@ public class LikePlotMeConverter {
});
sendMessage("Saving configuration...");
try {
PS.get().config.save(PS.get().configFile);
} catch (IOException e) {
PS.get().worlds.save(PS.get().worldsFile);
} catch (IOException ignored) {
sendMessage(" - &cFailed to save configuration.");
}
TaskManager.runTask(new Runnable() {
@ -330,42 +290,47 @@ public class LikePlotMeConverter {
.isEnabled()) {
mw = true;
}
for (String worldname : worlds) {
World world = Bukkit.getWorld(getWorld(worldname));
for (String worldName : worlds) {
World world = Bukkit.getWorld(getWorld(worldName));
if (world == null) {
sendMessage("&cInvalid world in PlotMe configuration: " + worldname);
sendMessage("&cInvalid world in PlotMe configuration: " + worldName);
continue;
}
String actualWorldName = world.getName();
sendMessage("Reloading generator for world: '" + actualWorldName + "'...");
PS.get().removePlotAreas(actualWorldName);
if (mv) {
// unload world with MV
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv unload " + actualWorldName);
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
// load world with MV
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mv import " + actualWorldName + " normal -g PlotSquared");
} else if (mw) {
// unload world with MW
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw unload " + actualWorldName);
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
// load world with MW
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mw create " + actualWorldName + " plugin:PlotSquared");
if (!Bukkit.getWorlds().isEmpty() && Bukkit.getWorlds().get(0).getName().equals(worldName)) {
sendMessage("&cYou need to stop the server to reload this world properly");
} else {
// Load using Bukkit API
// - User must set generator manually
Bukkit.getServer().unloadWorld(world, true);
World myworld = WorldCreator.name(actualWorldName).generator(new BukkitPlotGenerator(new HybridGen())).createWorld();
myworld.save();
PS.get().removePlotAreas(actualWorldName);
if (mv) {
// unload world with MV
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv unload " + actualWorldName);
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
}
// load world with MV
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mv import " + actualWorldName + " normal -g " + PS.imp().getPluginName());
} else if (mw) {
// unload world with MW
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw unload " + actualWorldName);
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
}
// load world with MW
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
"mw create " + actualWorldName + " plugin:" + PS.imp().getPluginName());
} else {
// Load using Bukkit API
// - User must set generator manually
Bukkit.getServer().unloadWorld(world, true);
World myWorld = WorldCreator.name(actualWorldName).generator(new BukkitPlotGenerator(PS.get().IMP.getDefaultGenerator())).createWorld();
myWorld.save();
}
}
}
} catch (CommandException e) {
@ -375,7 +340,7 @@ public class LikePlotMeConverter {
done();
sendMessage("&aDatabase conversion is now complete!");
PS.debug("&c - Stop the server");
PS.debug("&c - Disable 'plotme-convert.enabled' and 'plotme-convert.cache-uuids' in the settings.yml");
PS.debug("&c - Disable 'plotme-converter' and 'plotme-convert.cache-uuids' in the settings.yml");
PS.debug("&c - Correct any generator settings that haven't copied to 'settings.yml' properly");
PS.debug("&c - Start the server");
} else {
@ -384,7 +349,7 @@ public class LikePlotMeConverter {
}
}
});
} catch (Exception e) {
} catch (InterruptedException | SQLException e) {
e.printStackTrace();
PS.debug("&/end/");
}

View File

@ -19,7 +19,6 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.UUID;
public class PlotMeConnector_017 extends APlotMeConnector {
@ -38,12 +37,12 @@ public class PlotMeConnector_017 extends APlotMeConnector {
} else {
File file = new File(dataFolder + File.separator + "plotmecore.db");
if (file.exists()) {
return new SQLite(dataFolder + File.separator + "plotmecore.db").openConnection();
return new SQLite(file).openConnection();
}
return new SQLite(dataFolder + File.separator + "plots.db").openConnection();
return new SQLite(new File(dataFolder + File.separator + "plots.db")).openConnection();
}
} catch (SQLException | ClassNotFoundException ignored) {
//ignored
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
@ -68,15 +67,15 @@ public class PlotMeConnector_017 extends APlotMeConnector {
return null;
}
boolean checkUUID = DBFunc.hasColumn(resultSet, "ownerID");
boolean merge = !this.plugin.equals("plotme") && Settings.CONVERT_PLOTME;
boolean merge = !"plotme".equals(this.plugin) && Settings.Enabled_Components.PLOTME_CONVERTER;
while (resultSet.next()) {
int key = resultSet.getInt("plot_id");
PlotId id = new PlotId(resultSet.getInt("plotX"), resultSet.getInt("plotZ"));
String name = resultSet.getString("owner");
String world = LikePlotMeConverter.getWorld(resultSet.getString("world"));
if (!plots.containsKey(world) && merge) {
int plot = PS.get().config.getInt("worlds." + world + ".plot.size");
int path = PS.get().config.getInt("worlds." + world + ".road.width");
int plot = PS.get().worlds.getInt("worlds." + world + ".plot.size");
int path = PS.get().worlds.getInt("worlds." + world + ".road.width");
plotWidth.put(world, plot);
roadWidth.put(world, path);
merges.put(world, new HashMap<PlotId, boolean[]>());
@ -109,18 +108,14 @@ public class PlotMeConnector_017 extends APlotMeConnector {
owner = DBFunc.everyone;
} else {
if (checkUUID) {
try {
byte[] bytes = resultSet.getBytes("ownerid");
if (bytes != null) {
owner = UUID.nameUUIDFromBytes(bytes);
UUIDHandler.add(new StringWrapper(name), owner);
}
} catch (Exception e) {
e.printStackTrace();
byte[] bytes = resultSet.getBytes("ownerid");
if (bytes != null) {
owner = UUID.nameUUIDFromBytes(bytes);
UUIDHandler.add(new StringWrapper(name), owner);
}
}
if (owner == null) {
PS.log("&cCould not identify owner for plot: " + id + " -> '" + name + "'");
PS.log("&cCould not identify owner for plot: " + id + " -> '" + name + '\'');
continue;
}
}
@ -130,8 +125,7 @@ public class PlotMeConnector_017 extends APlotMeConnector {
Plot plot = new Plot(PlotArea.createGeneric(world), id, owner);
plots.put(key, plot);
}
for (Entry<Integer, Plot> entry : plots.entrySet()) {
Plot plot = entry.getValue();
for (Plot plot : plots.values()) {
HashMap<PlotId, boolean[]> mergeMap = merges.get(plot.getArea().worldname);
if (mergeMap != null) {
if (mergeMap.containsKey(plot.getId())) {
@ -179,8 +173,7 @@ public class PlotMeConnector_017 extends APlotMeConnector {
}
HashMap<String, HashMap<PlotId, Plot>> processed = new HashMap<>();
for (Entry<Integer, Plot> entry : plots.entrySet()) {
Plot plot = entry.getValue();
for (Plot plot : plots.values()) {
HashMap<PlotId, Plot> map = processed.get(plot.getArea().worldname);
if (map == null) {
map = new HashMap<>();

View File

@ -1,23 +1,3 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import com.intellectualcrafters.plot.flag.Flag;

View File

@ -1,23 +1,3 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import com.intellectualcrafters.plot.object.Plot;

View File

@ -1,23 +1,3 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import com.intellectualcrafters.plot.object.Plot;

View File

@ -1,23 +1,3 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import com.intellectualcrafters.plot.object.Plot;

View File

@ -1,23 +1,3 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import com.intellectualcrafters.plot.object.Plot;

View File

@ -1,23 +1,3 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import com.intellectualcrafters.plot.object.Plot;

View File

@ -1,23 +1,3 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import com.intellectualcrafters.plot.object.Plot;

View File

@ -1,23 +1,3 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import com.intellectualcrafters.plot.object.Location;

View File

@ -1,23 +1,3 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import com.intellectualcrafters.plot.object.Plot;

View File

@ -0,0 +1,56 @@
package com.plotsquared.bukkit.events;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotId;
import org.bukkit.event.HandlerList;
/**
* Called when a plot component is set
*
*/
public class PlotComponentSetEvent extends PlotEvent {
private static final HandlerList handlers = new HandlerList();
private final String component;
public PlotComponentSetEvent(Plot plot, String component) {
super(plot);
this.component = component;
}
public static HandlerList getHandlerList() {
return handlers;
}
/**
* Get the PlotId
*
* @return PlotId
*/
public PlotId getPlotId() {
return getPlot().getId();
}
/**
* Get the world name
*
* @return String
*/
public String getWorld() {
return getPlot().getArea().worldname;
}
/**
* Get the component which was set
*
* @return Component name
*/
public String getComponent() {
return this.component;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
}

View File

@ -1,23 +1,3 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import com.intellectualcrafters.plot.object.Plot;

View File

@ -1,23 +1,3 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import com.intellectualcrafters.plot.flag.Flag;

View File

@ -1,23 +1,3 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import com.intellectualcrafters.plot.flag.Flag;

View File

@ -1,23 +1,3 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import com.intellectualcrafters.plot.object.Plot;

View File

@ -1,23 +1,3 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.events;
import com.intellectualcrafters.plot.object.PlotArea;

View File

@ -1,29 +1,11 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.generator;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.generator.GeneratorWrapper;
import com.intellectualcrafters.plot.generator.HybridGen;
import com.intellectualcrafters.plot.generator.IndependentPlotGenerator;
import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.object.ChunkWrapper;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotManager;
@ -31,8 +13,10 @@ import com.intellectualcrafters.plot.object.PseudoRandom;
import com.intellectualcrafters.plot.object.SetupObject;
import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.PlotChunk;
import com.intellectualcrafters.plot.util.SetQueue;
import com.intellectualcrafters.plot.util.MathMan;
import com.intellectualcrafters.plot.util.block.GlobalBlockQueue;
import com.intellectualcrafters.plot.util.block.LocalBlockQueue;
import com.intellectualcrafters.plot.util.block.ScopedLocalBlockQueue;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.bukkit.util.block.GenChunk;
import org.bukkit.Chunk;
@ -42,30 +26,58 @@ import org.bukkit.generator.BlockPopulator;
import org.bukkit.generator.ChunkGenerator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.Set;
public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrapper<ChunkGenerator> {
private final PlotChunk<Chunk> chunkSetter;
private final GenChunk chunkSetter;
private final PseudoRandom random = new PseudoRandom();
private final IndependentPlotGenerator plotGenerator;
private final List<BlockPopulator> populators = new ArrayList<>();
private List<BlockPopulator> populators;
private final ChunkGenerator platformGenerator;
private final boolean full;
private final HashMap<ChunkLoc, byte[][]> dataMap = new HashMap<>();
private boolean loaded = false;
public BukkitPlotGenerator(IndependentPlotGenerator generator) {
if (generator == null) {
throw new IllegalArgumentException("Generator may not be null!");
}
this.plotGenerator = generator;
this.platformGenerator = this;
populators = new ArrayList<>();
this.populators.add(new BlockPopulator() {
private LocalBlockQueue queue;
@Override
public void populate(World world, Random r, Chunk c) {
GenChunk result = (GenChunk) BukkitPlotGenerator.this.chunkSetter;
if (result.result_data != null) {
for (int i = 0; i < result.result_data.length; i++) {
byte[] section = result.result_data[i];
if (queue == null) {
queue = GlobalBlockQueue.IMP.getNewQueue(world.getName(), false);
}
ChunkLoc loc = new ChunkLoc(c.getX(), c.getZ());
byte[][] resultData;
if (!BukkitPlotGenerator.this.dataMap.containsKey(loc)) {
GenChunk result = BukkitPlotGenerator.this.chunkSetter;
// Set the chunk location
result.setChunk(c);
// Set the result data
result.result = new short[16][];
result.result_data = new byte[16][];
result.grid = null;
result.cd = null;
// Catch any exceptions (as exceptions usually thrown)
generate(world, loc.x, loc.z, result);
resultData = result.result_data;
} else {
resultData = BukkitPlotGenerator.this.dataMap.remove(loc);
}
if (resultData != null) {
for (int i = 0; i < resultData.length; i++) {
byte[] section = resultData[i];
if (section == null) {
continue;
}
@ -77,6 +89,13 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
}
}
}
BukkitPlotGenerator.this.random.state = c.getX() << 16 | c.getZ() & 0xFFFF;
PlotArea area = PS.get().getPlotArea(world.getName(), null);
ChunkWrapper wrap = new ChunkWrapper(area.worldname, c.getX(), c.getZ());
ScopedLocalBlockQueue chunk = queue.getForChunk(wrap.x, wrap.z);
if (BukkitPlotGenerator.this.plotGenerator.populateChunk(chunk, area, BukkitPlotGenerator.this.random)) {
queue.flush();
}
}
});
this.chunkSetter = new GenChunk(null, null);
@ -100,7 +119,7 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
@Override
public PlotManager getNewPlotManager() {
return new HybridGen().getNewPlotManager();
return PS.get().IMP.getDefaultGenerator().getNewPlotManager();
}
@Override
@ -110,17 +129,20 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
@Override
public PlotArea getNewPlotArea(String world, String id, PlotId min, PlotId max) {
return new HybridGen().getNewPlotArea(world, id, min, max);
return PS.get().IMP.getDefaultGenerator().getNewPlotArea(world, id, min, max);
}
@Override
public void generateChunk(final PlotChunk<?> result, PlotArea settings, PseudoRandom random) {
public void generateChunk(final ScopedLocalBlockQueue result, PlotArea settings, PseudoRandom random) {
World w = BukkitUtil.getWorld(world);
Random r = new Random(result.getChunkWrapper().hashCode());
Location min = result.getMin();
int cx = min.getX() >> 4;
int cz = min.getZ() >> 4;
Random r = new Random(MathMan.pair((short) cx, (short) cz));
BiomeGrid grid = new BiomeGrid() {
@Override
public void setBiome(int x, int z, Biome biome) {
result.setBiome(x, z, biome.ordinal());
result.setBiome(x, z, biome.name());
}
@Override
@ -130,15 +152,13 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
};
try {
// ChunkData will spill a bit
ChunkData data = cg.generateChunkData(w, r, result.getX(), result.getZ(), grid);
ChunkData data = cg.generateChunkData(w, r, cx, cz, grid);
if (data != null) {
return;
}
} catch (Throwable e) {
//ignored
}
} catch (Throwable ignored) {}
// Populator spillage
short[][] tmp = cg.generateExtBlockSections(w, r, result.getX(), result.getZ(), grid);
short[][] tmp = cg.generateExtBlockSections(w, r, cx, cz, grid);
if (tmp != null) {
for (int i = 0; i < tmp.length; i++) {
short[] section = tmp[i];
@ -163,14 +183,11 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
}
}
for (BlockPopulator populator : cg.getDefaultPopulators(w)) {
populator.populate(w, r, (Chunk) result.getChunk());
populator.populate(w, r, w.getChunkAt(cx, cz));
}
}
};
this.chunkSetter = new GenChunk(null, SetQueue.IMP.new ChunkWrapper(world, 0, 0));
if (cg != null) {
this.populators.addAll(cg.getDefaultPopulators(BukkitUtil.getWorld(world)));
}
this.chunkSetter = new GenChunk(null, new ChunkWrapper(world, 0, 0));
MainUtil.initCache();
}
@ -224,20 +241,30 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
} catch (Exception e) {
e.printStackTrace();
}
return this.populators;
ArrayList<BlockPopulator> toAdd = new ArrayList<>();
List<BlockPopulator> existing = world.getPopulators();
if (populators == null && platformGenerator != null) {
populators = new ArrayList<>(platformGenerator.getDefaultPopulators(world));
}
for (BlockPopulator populator : this.populators) {
if (!existing.contains(populator)) {
toAdd.add(populator);
}
}
return toAdd;
}
@Override
public ChunkData generateChunkData(World world, Random random, int cx, int cz, BiomeGrid grid) {
GenChunk result = (GenChunk) this.chunkSetter;
GenChunk result = this.chunkSetter;
// Set the chunk location
result.setChunkWrapper(SetQueue.IMP.new ChunkWrapper(world.getName(), cx, cz));
result.setChunk(new ChunkWrapper(world.getName(), cx, cz));
// Set the result data
result.cd = createChunkData(world);
result.grid = grid;
result.result = null;
result.result_data = null;
// Catch any exceptions (as exceptions usually thrown
// Catch any exceptions (as exceptions usually thrown)
try {
// Fill the result data if necessary
if (this.platformGenerator != this) {
@ -251,8 +278,8 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
// Return the result data
return result.cd;
}
public void generate(World world, int cx, int cz, GenChunk result) {
public void generate(World world, int cx, int cz, ScopedLocalBlockQueue result) {
// Load if improperly loaded
if (!this.loaded) {
String name = world.getName();
@ -266,27 +293,34 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
return;
}
PlotArea area = PS.get().getPlotArea(world.getName(), null);
this.plotGenerator.generateChunk(this.chunkSetter, area, this.random);
try {
this.plotGenerator.generateChunk(this.chunkSetter, area, this.random);
} catch (Throwable e) {
// Recover from generator error
e.printStackTrace();
}
ChunkManager.postProcessChunk(result);
}
@Override
public short[][] generateExtBlockSections(World world, Random r, int cx, int cz, BiomeGrid grid) {
GenChunk result = (GenChunk) this.chunkSetter;
GenChunk result = this.chunkSetter;
// Set the chunk location
result.setChunkWrapper(SetQueue.IMP.new ChunkWrapper(world.getName(), cx, cz));
result.setChunk(new ChunkWrapper(world.getName(), cx, cz));
// Set the result data
result.result = new short[16][];
result.result_data = new byte[16][];
result.grid = grid;
result.cd = null;
// Catch any exceptions (as exceptions usually thrown
// Catch any exceptions (as exceptions usually thrown)
try {
// Fill the result data
if (this.platformGenerator != this) {
return this.platformGenerator.generateExtBlockSections(world, r, cx, cz, grid);
} else {
generate(world, cx, cz, result);
this.dataMap.put(new ChunkLoc(cx, cz), result.result_data);
}
} catch (Throwable e) {
e.printStackTrace();
@ -310,7 +344,7 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
@Override
public String toString() {
if (this.platformGenerator == this) {
return "" + this.plotGenerator;
return this.plotGenerator.getName();
}
if (this.platformGenerator == null) {
return "null";

View File

@ -1,18 +1,16 @@
package com.plotsquared.bukkit.listeners;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefClass;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefField;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
import java.lang.reflect.Method;
import java.util.HashSet;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Material;
@ -31,9 +29,8 @@ import org.bukkit.event.entity.ItemSpawnEvent;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.event.world.ChunkUnloadEvent;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.Map.Entry;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
public class ChunkListener implements Listener {
@ -43,156 +40,121 @@ public class ChunkListener implements Listener {
public ChunkListener() {
if (Settings.CHUNK_PROCESSOR_GC || Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE) {
if (Settings.Chunk_Processor.AUTO_TRIM) {
try {
RefClass classChunk = getRefClass("{nms}.Chunk");
RefClass classCraftChunk = getRefClass("{cb}.CraftChunk");
this.mustSave = classChunk.getField("mustSave");
this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle");
} catch (Throwable e) {
PS.debug("PlotSquared/Server not compatible for chunk processor trim/gc");
Settings.CHUNK_PROCESSOR_GC = false;
Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE = false;
} catch (Throwable ignored) {
PS.debug(PS.imp().getPluginName() + "/Server not compatible for chunk processor trim/gc");
Settings.Chunk_Processor.AUTO_TRIM = false;
}
}
if (!Settings.CHUNK_PROCESSOR_GC) {
if (!Settings.Chunk_Processor.AUTO_TRIM) {
return;
}
TaskManager.runTask(new Runnable() {
for (World world : Bukkit.getWorlds()) {
world.setAutoSave(false);
}
TaskManager.runTaskRepeat(new Runnable() {
@Override
public void run() {
int distance = Bukkit.getViewDistance() + 2;
HashMap<String, HashMap<ChunkLoc, Integer>> players = new HashMap<>();
for (Entry<String, PlotPlayer> entry : UUIDHandler.getPlayers().entrySet()) {
PlotPlayer pp = entry.getValue();
Location location = pp.getLocation();
String world = location.getWorld();
if (!PS.get().hasPlotArea(world)) {
continue;
}
HashMap<ChunkLoc, Integer> map = players.get(world);
if (map == null) {
map = new HashMap<>();
players.put(world, map);
}
ChunkLoc origin = new ChunkLoc(location.getX() >> 4, location.getZ() >> 4);
Integer val = map.get(origin);
int check;
if (val != null) {
if (val == distance) {
try {
HashSet<Chunk> toUnload = new HashSet<>();
for (World world : Bukkit.getWorlds()) {
String worldName = world.getName();
if (!PS.get().hasPlotArea(worldName)) {
continue;
}
check = distance - val;
} else {
check = distance;
map.put(origin, distance);
}
for (int x = -distance; x <= distance; x++) {
if (x >= check || -x >= check) {
continue;
}
for (int z = -distance; z <= distance; z++) {
if (z >= check || -z >= check) {
Object w = world.getClass().getDeclaredMethod("getHandle").invoke(world);
Object chunkMap = w.getClass().getDeclaredMethod("getPlayerChunkMap").invoke(w);
Method methodIsChunkInUse = chunkMap.getClass().getDeclaredMethod("isChunkInUse", int.class, int.class);
Chunk[] chunks = world.getLoadedChunks();
for (Chunk chunk : chunks) {
if ((boolean) methodIsChunkInUse.invoke(chunkMap, chunk.getX(), chunk.getZ())) {
continue;
}
int weight = distance - Math.max(Math.abs(x), Math.abs(z));
ChunkLoc chunk = new ChunkLoc(x + origin.x, z + origin.z);
val = map.get(chunk);
if (val == null || val < weight) {
map.put(chunk, weight);
int x = chunk.getX();
int z = chunk.getZ();
if (!shouldSave(worldName, x, z)) {
unloadChunk(worldName, chunk, false);
continue;
}
}
}
}
int time = 300;
for (World world : Bukkit.getWorlds()) {
String name = world.getName();
if (!PS.get().hasPlotArea(name)) {
continue;
}
boolean autosave = world.isAutoSave();
if (autosave) {
world.setAutoSave(false);
}
HashMap<ChunkLoc, Integer> map = players.get(name);
if (map == null || map.isEmpty()) {
continue;
}
Chunk[] chunks = world.getLoadedChunks();
ArrayDeque<Chunk> toUnload = new ArrayDeque<>();
for (Chunk chunk : chunks) {
int x = chunk.getX();
int z = chunk.getZ();
if (!map.containsKey(new ChunkLoc(x, z))) {
toUnload.add(chunk);
}
}
if (!toUnload.isEmpty()) {
long start = System.currentTimeMillis();
Chunk chunk;
while ((chunk = toUnload.poll()) != null && System.currentTimeMillis() - start < 5) {
if (!Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE || !unloadChunk(name, chunk)) {
if (chunk.isLoaded()) {
chunk.unload(true, false);
}
}
}
if (!toUnload.isEmpty()) {
time = 1;
}
if (toUnload.isEmpty()) {
return;
}
if (!Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE && autosave) {
world.setAutoSave(true);
long start = System.currentTimeMillis();
for (Chunk chunk : toUnload) {
if (System.currentTimeMillis() - start > 5) {
return;
}
chunk.unload(true, false);
}
} catch (Throwable e) {
e.printStackTrace();
}
TaskManager.runTaskLater(this, time);
}
});
}, 1);
}
public boolean unloadChunk(String world, Chunk chunk) {
int X = chunk.getX();
int Z = chunk.getZ();
private boolean ignoreUnload = false;
public boolean unloadChunk(String world, Chunk chunk, boolean safe) {
if (safe && shouldSave(world, chunk.getX(), chunk.getZ())) {
return false;
}
Object c = this.methodGetHandleChunk.of(chunk).call();
RefField.RefExecutor field = this.mustSave.of(c);
if ((Boolean) field.get() == true) {
field.set(false);
if (chunk.isLoaded()) {
ignoreUnload = true;
chunk.unload(false, false);
ignoreUnload = false;
}
}
return true;
}
public boolean shouldSave(String world, int X, int Z) {
int x = X << 4;
int z = Z << 4;
int x2 = x + 15;
int z2 = z + 15;
Plot plot = new Location(world, x, 1, z).getOwnedPlotAbs();
if (plot != null && plot.hasOwner()) {
return false;
return true;
}
plot = new Location(world, x2, 1, z2).getOwnedPlotAbs();
if (plot != null && plot.hasOwner()) {
return false;
return true;
}
plot = new Location(world, x2, 1, z).getOwnedPlotAbs();
if (plot != null && plot.hasOwner()) {
return false;
return true;
}
plot = new Location(world, x, 1, z2).getOwnedPlotAbs();
if (plot != null && plot.hasOwner()) {
return false;
return true;
}
plot = new Location(world, x + 7, 1, z + 7).getOwnedPlotAbs();
if (plot != null && plot.hasOwner()) {
return false;
}
Object c = this.methodGetHandleChunk.of(chunk).call();
this.mustSave.of(c).set(false);
if (chunk.isLoaded()) {
chunk.unload(false, false);
}
return true;
return plot != null && plot.hasOwner();
}
@EventHandler
public void onChunkUnload(ChunkUnloadEvent event) {
if (Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE) {
if (ignoreUnload) {
return;
}
if (Settings.Chunk_Processor.AUTO_TRIM) {
Chunk chunk = event.getChunk();
String world = chunk.getWorld().getName();
if (PS.get().hasPlotArea(world)) {
if (unloadChunk(world, chunk)) {
if (unloadChunk(world, chunk, true)) {
return;
}
}
@ -220,7 +182,7 @@ public class ChunkListener implements Listener {
return;
}
Entity[] entities = chunk.getEntities();
if (entities.length > Settings.CHUNK_PROCESSOR_MAX_ENTITIES) {
if (entities.length > Settings.Chunk_Processor.MAX_ENTITIES) {
event.getEntity().remove();
event.setCancelled(true);
this.lastChunk = chunk;
@ -231,7 +193,7 @@ public class ChunkListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockPhysics(BlockPhysicsEvent event) {
if (Settings.CHUNK_PROCESSOR_DISABLE_PHYSICS) {
if (Settings.Chunk_Processor.DISABLE_PHYSICS) {
event.setCancelled(true);
}
}
@ -249,7 +211,7 @@ public class ChunkListener implements Listener {
return;
}
Entity[] entities = chunk.getEntities();
if (entities.length > Settings.CHUNK_PROCESSOR_MAX_ENTITIES) {
if (entities.length > Settings.Chunk_Processor.MAX_ENTITIES) {
event.getEntity().remove();
event.setCancelled(true);
this.lastChunk = chunk;
@ -267,7 +229,7 @@ public class ChunkListener implements Listener {
if (!chunk.isLoaded()) {
Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex));
TaskManager.tasks.remove(currentIndex);
PS.debug("[PlotSquared] &aSuccessfully processed and unloaded chunk!");
PS.debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!");
chunk.unload(true, true);
return;
}
@ -275,7 +237,7 @@ public class ChunkListener implements Listener {
if (tiles.length == 0) {
Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex));
TaskManager.tasks.remove(currentIndex);
PS.debug("[PlotSquared] &aSuccessfully processed and unloaded chunk!");
PS.debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!");
chunk.unload(true, true);
return;
}
@ -285,7 +247,7 @@ public class ChunkListener implements Listener {
if (i >= tiles.length) {
Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex));
TaskManager.tasks.remove(currentIndex);
PS.debug("[PlotSquared] &aSuccessfully processed and unloaded chunk!");
PS.debug(C.PREFIX.s() + "&aSuccessfully processed and unloaded chunk!");
chunk.unload(true, true);
return;
}
@ -303,17 +265,17 @@ public class ChunkListener implements Listener {
}
Entity[] entities = chunk.getEntities();
BlockState[] tiles = chunk.getTileEntities();
if (entities.length > Settings.CHUNK_PROCESSOR_MAX_ENTITIES) {
if (entities.length > Settings.Chunk_Processor.MAX_ENTITIES) {
for (Entity ent : entities) {
if (!(ent instanceof Player)) {
ent.remove();
}
}
PS.debug("[PlotSquared] &a detected unsafe chunk and processed: " + (chunk.getX() << 4) + "," + (chunk.getX() << 4));
PS.debug(C.PREFIX.s() + "&a detected unsafe chunk and processed: " + (chunk.getX() << 4) + "," + (chunk.getX() << 4));
}
if (tiles.length > Settings.CHUNK_PROCESSOR_MAX_BLOCKSTATES) {
if (tiles.length > Settings.Chunk_Processor.MAX_TILES) {
if (unload) {
PS.debug("[PlotSquared] &c detected unsafe chunk: " + (chunk.getX() << 4) + "," + (chunk.getX() << 4));
PS.debug(C.PREFIX.s() + "&c detected unsafe chunk: " + (chunk.getX() << 4) + "," + (chunk.getX() << 4));
cleanChunk(chunk);
return true;
}

View File

@ -0,0 +1,44 @@
package com.plotsquared.bukkit.listeners;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.flag.Flags;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea;
import com.plotsquared.bukkit.util.BukkitUtil;
import org.bukkit.entity.Entity;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntitySpawnEvent;
public class EntitySpawnListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void creatureSpawnEvent(EntitySpawnEvent event) {
Entity entity = event.getEntity();
Location location = BukkitUtil.getLocation(entity.getLocation());
PlotArea area = location.getPlotArea();
if (area == null) {
return;
}
Plot plot = area.getOwnedPlotAbs(location);
if (plot == null) {
return;
}
if (Settings.Done.RESTRICT_BUILDING && plot.hasFlag(Flags.DONE)) {
event.setCancelled(true);
}
switch (entity.getType()) {
case ENDER_CRYSTAL:
if (plot == null) {
if (!area.MOB_SPAWNING) {
event.setCancelled(true);
}
return;
}
if (PlayerEvents.checkEntity(entity, plot)) {
event.setCancelled(true);
}
}
}
}

View File

@ -1,73 +1,50 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.listeners;
import com.intellectualcrafters.plot.flag.FlagManager;
import com.google.common.collect.Iterables;
import com.intellectualcrafters.plot.flag.Flags;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.plotsquared.bukkit.events.PlayerEnterPlotEvent;
import com.plotsquared.bukkit.object.BukkitPlayer;
import com.plotsquared.bukkit.util.BukkitUtil;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.util.Vector;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
public class ForceFieldListener implements Listener {
public class ForceFieldListener {
private Set<PlotPlayer> getNearbyPlayers(Player player, Plot plot) {
private static Set<PlotPlayer> getNearbyPlayers(Player player, Plot plot) {
Set<PlotPlayer> players = new HashSet<>();
for (Entity entity : player.getNearbyEntities(5d, 5d, 5d)) {
PlotPlayer pp;
if (!(entity instanceof Player) || ((pp = BukkitUtil.getPlayer((Player) entity)) == null) || !plot.equals(pp.getCurrentPlot())) {
for (Player nearPlayer : Iterables.filter(player.getNearbyEntities(5d, 5d, 5d),Player.class)) {
PlotPlayer plotPlayer;
if ((plotPlayer = BukkitUtil.getPlayer(nearPlayer)) == null || !plot.equals(plotPlayer.getCurrentPlot())) {
continue;
}
if (!plot.isAdded(pp.getUUID())) {
players.add(pp);
if (!plot.isAdded(plotPlayer.getUUID())) {
players.add(plotPlayer);
}
}
return players;
}
private PlotPlayer hasNearbyPermitted(Player player, Plot plot) {
for (Entity entity : player.getNearbyEntities(5d, 5d, 5d)) {
PlotPlayer pp;
if (!(entity instanceof Player) || ((pp = BukkitUtil.getPlayer((Player) entity)) == null) || !plot.equals(pp.getCurrentPlot())) {
private static PlotPlayer hasNearbyPermitted(Player player, Plot plot) {
for (Player nearPlayer : Iterables.filter(player.getNearbyEntities(5d, 5d, 5d),Player.class)) {
PlotPlayer plotPlayer;
if ((plotPlayer = BukkitUtil.getPlayer(nearPlayer)) == null || !plot.equals(plotPlayer.getCurrentPlot())) {
continue;
}
if (plot.isAdded(pp.getUUID())) {
return pp;
if (plot.isAdded(plotPlayer.getUUID())) {
return plotPlayer;
}
}
return null;
}
public Vector calculateVelocity(PlotPlayer pp, PlotPlayer e) {
Location playerLocation = pp.getLocationFull();
private static Vector calculateVelocity(PlotPlayer player, PlotPlayer e) {
Location playerLocation = player.getLocationFull();
Location oPlayerLocation = e.getLocation();
double playerX = playerLocation.getX();
double playerY = playerLocation.getY();
@ -96,29 +73,20 @@ public class ForceFieldListener implements Listener {
return new Vector(x, y, z);
}
@EventHandler
public void onPlotEntry(PlayerEnterPlotEvent event) {
Player player = event.getPlayer();
PlotPlayer pp = BukkitUtil.getPlayer(player);
Plot plot = event.getPlot();
if (plot == null) {
return;
}
if ((FlagManager.getPlotFlagRaw(plot, "forcefield") != null) && FlagManager.getPlotFlagRaw(plot, "forcefield").getValue().equals("true")) {
if (!FlagManager.isBooleanFlag(plot, "forcefield", false)) {
UUID uuid = pp.getUUID();
if (plot.isAdded(uuid)) {
Set<PlotPlayer> players = getNearbyPlayers(player, plot);
for (PlotPlayer oPlayer : players) {
((BukkitPlayer) oPlayer).player.setVelocity(calculateVelocity(pp, oPlayer));
}
} else {
PlotPlayer oPlayer = hasNearbyPermitted(player, plot);
if (oPlayer == null) {
return;
}
player.setVelocity(calculateVelocity(oPlayer, pp));
public static void handleForcefield(Player player, PlotPlayer plotPlayer, Plot plot) {
if (Flags.FORCEFIELD.isTrue(plot)) {
UUID uuid = plotPlayer.getUUID();
if (plot.isAdded(uuid)) {
Set<PlotPlayer> players = getNearbyPlayers(player, plot);
for (PlotPlayer oPlayer : players) {
((BukkitPlayer) oPlayer).player.setVelocity(calculateVelocity(plotPlayer, oPlayer));
}
} else {
PlotPlayer oPlayer = hasNearbyPermitted(player, plot);
if (oPlayer == null) {
return;
}
player.setVelocity(calculateVelocity(oPlayer, plotPlayer));
}
}
}

View File

@ -1,7 +1,7 @@
package com.plotsquared.bukkit.listeners;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.flag.Flags;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea;
@ -18,31 +18,31 @@ public class PlayerEvents183 implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBigBoom(BlockExplodeEvent event) {
Block block = event.getBlock();
Location loc = BukkitUtil.getLocation(block.getLocation());
String world = loc.getWorld();
Location location = BukkitUtil.getLocation(block.getLocation());
String world = location.getWorld();
if (!PS.get().hasPlotArea(world)) {
return;
}
PlotArea area = loc.getPlotArea();
PlotArea area = location.getPlotArea();
if (area == null) {
Iterator<Block> iter = event.blockList().iterator();
while (iter.hasNext()) {
loc = BukkitUtil.getLocation(iter.next().getLocation());
if (loc.getPlotArea() != null) {
iter.remove();
Iterator<Block> iterator = event.blockList().iterator();
while (iterator.hasNext()) {
location = BukkitUtil.getLocation(iterator.next().getLocation());
if (location.getPlotArea() != null) {
iterator.remove();
}
}
return;
}
Plot plot = area.getOwnedPlot(loc);
if (plot == null || !FlagManager.isPlotFlagTrue(plot, "explosion")) {
Plot plot = area.getOwnedPlot(location);
if (plot == null || !plot.getFlag(Flags.EXPLOSION).or(false)) {
event.setCancelled(true);
}
Iterator<Block> iter = event.blockList().iterator();
while (iter.hasNext()) {
Block b = iter.next();
Iterator<Block> iterator = event.blockList().iterator();
while (iterator.hasNext()) {
Block b = iterator.next();
if (!plot.equals(area.getOwnedPlot(BukkitUtil.getLocation(b.getLocation())))) {
iter.remove();
iterator.remove();
}
}
}

View File

@ -2,6 +2,7 @@ package com.plotsquared.bukkit.listeners;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.flag.Flags;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea;
@ -32,6 +33,7 @@ import java.util.UUID;
public class PlayerEvents_1_8 extends PlotListener implements Listener {
@SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onInventoryClick(InventoryClickEvent event) {
if (!event.isLeftClick() || (event.getAction() != InventoryAction.PLACE_ALL) || event.isShiftClick()) {
@ -65,7 +67,7 @@ public class PlayerEvents_1_8 extends PlotListener implements Listener {
oldLore = lore.toString();
}
}
if (!newLore.equals("[(+NBT)]") || (current.equals(newItem) && newLore.equals(oldLore))) {
if (!"[(+NBT)]".equals(newLore) || (current.equals(newItem) && newLore.equals(oldLore))) {
return;
}
HashSet<Byte> blocks = null;
@ -140,6 +142,9 @@ public class PlayerEvents_1_8 extends PlotListener implements Listener {
} else {
UUID uuid = pp.getUUID();
if (!plot.isAdded(uuid)) {
if (Flags.MISC_INTERACT.isTrue(plot)) {
return;
}
if (!Permissions.hasPermission(pp, "plots.admin.interact.other")) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.other");
e.setCancelled(true);

View File

@ -0,0 +1,31 @@
package com.plotsquared.bukkit.listeners;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.object.Location;
import com.plotsquared.bukkit.util.BukkitUtil;
import org.bukkit.entity.LingeringPotion;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.LingeringPotionSplashEvent;
public class PlayerEvents_1_9 implements Listener {
private final PlayerEvents parent;
public PlayerEvents_1_9(PlayerEvents parent) {
this.parent = parent;
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPotionSplash(LingeringPotionSplashEvent event) {
LingeringPotion entity = event.getEntity();
Location l = BukkitUtil.getLocation(entity);
if (!PS.get().hasPlotArea(l.getWorld())) {
return;
}
if (!parent.onProjectileHit(event)) {
event.setCancelled(true);
}
}
}

View File

@ -1,27 +1,7 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.listeners;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.flag.FlagManager;
import com.google.common.base.Optional;
import com.intellectualcrafters.plot.flag.Flags;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.plotsquared.bukkit.events.PlayerEnterPlotEvent;
@ -34,11 +14,13 @@ import java.util.Map.Entry;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.block.Block;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
@ -56,15 +38,15 @@ public class PlotPlusListener extends PlotListener implements Listener {
@Override
public void run() {
if (!healRunnable.isEmpty()) {
for (Iterator<Entry<String, Interval>> iter = healRunnable.entrySet().iterator(); iter.hasNext(); ) {
Entry<String, Interval> entry = iter.next();
for (Iterator<Entry<String, Interval>> iterator = healRunnable.entrySet().iterator(); iterator.hasNext(); ) {
Entry<String, Interval> entry = iterator.next();
Interval value = entry.getValue();
++value.count;
if (value.count == value.interval) {
value.count = 0;
Player player = Bukkit.getPlayer(entry.getKey());
if (player == null) {
iter.remove();
iterator.remove();
continue;
}
double level = player.getHealth();
@ -75,15 +57,15 @@ public class PlotPlusListener extends PlotListener implements Listener {
}
}
if (!feedRunnable.isEmpty()) {
for (Iterator<Entry<String, Interval>> iter = feedRunnable.entrySet().iterator(); iter.hasNext(); ) {
Entry<String, Interval> entry = iter.next();
for (Iterator<Entry<String, Interval>> iterator = feedRunnable.entrySet().iterator(); iterator.hasNext(); ) {
Entry<String, Interval> entry = iterator.next();
Interval value = entry.getValue();
++value.count;
if (value.count == value.interval) {
value.count = 0;
Player player = Bukkit.getPlayer(entry.getKey());
if (player == null) {
iter.remove();
iterator.remove();
continue;
}
int level = player.getFoodLevel();
@ -107,8 +89,13 @@ public class PlotPlusListener extends PlotListener implements Listener {
if (plot == null) {
return;
}
if (FlagManager.isBooleanFlag(plot, "instabreak", false)) {
event.getBlock().breakNaturally();
if (Flags.INSTABREAK.isTrue(plot)) {
Block block = event.getBlock();
BlockBreakEvent call = new BlockBreakEvent(block, player);
Bukkit.getServer().getPluginManager().callEvent(call);
if (!call.isCancelled()) {
event.getBlock().breakNaturally();
}
}
}
@ -122,7 +109,7 @@ public class PlotPlusListener extends PlotListener implements Listener {
if (plot == null) {
return;
}
if (FlagManager.isBooleanFlag(plot, "invincible", false)) {
if (Flags.INVINCIBLE.isTrue(plot)) {
event.setCancelled(true);
}
}
@ -136,7 +123,7 @@ public class PlotPlusListener extends PlotListener implements Listener {
return;
}
UUID uuid = pp.getUUID();
if (plot.isAdded(uuid) && FlagManager.isBooleanFlag(plot, "drop-protection", false)) {
if (plot.isAdded(uuid) && Flags.DROP_PROTECTION.isTrue(plot)) {
event.setCancelled(true);
}
}
@ -150,8 +137,10 @@ public class PlotPlusListener extends PlotListener implements Listener {
return;
}
UUID uuid = pp.getUUID();
if (plot.isAdded(uuid) && FlagManager.isBooleanFlag(plot, "item-drop", false)) {
event.setCancelled(true);
if (!plot.isAdded(uuid)) {
if (Flags.ITEM_DROP.isFalse(plot)) {
event.setCancelled(true);
}
}
}
@ -159,14 +148,14 @@ public class PlotPlusListener extends PlotListener implements Listener {
public void onPlotEnter(PlayerEnterPlotEvent event) {
Player player = event.getPlayer();
Plot plot = event.getPlot();
Flag feed = FlagManager.getPlotFlagRaw(plot, "feed");
if (feed != null) {
Integer[] value = (Integer[]) feed.getValue();
Optional<Integer[]> feed = plot.getFlag(Flags.FEED);
if (feed.isPresent()) {
Integer[] value = feed.get();
feedRunnable.put(player.getName(), new Interval(value[0], value[1], 20));
}
Flag heal = FlagManager.getPlotFlagRaw(plot, "heal");
if (heal != null) {
Integer[] value = (Integer[]) heal.getValue();
Optional<Integer[]> heal = plot.getFlag(Flags.HEAL);
if (heal.isPresent()) {
Integer[] value = heal.get();
healRunnable.put(player.getName(), new Interval(value[0], value[1], 20));
}
}

View File

@ -1,329 +0,0 @@
package com.plotsquared.bukkit.listeners.worldedit;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.RegionWrapper;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.SetQueue;
import com.plotsquared.bukkit.BukkitMain;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.listener.WEManager;
import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.bukkit.selections.Selection;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
public class WEListener implements Listener {
public final HashSet<String> rad1 = new HashSet<>(
Arrays.asList("forestgen", "pumpkins", "drain", "fixwater", "fixlava", "replacenear", "snow", "thaw", "ex", "butcher", "size"));
public final HashSet<String> rad2 = new HashSet<>(Arrays.asList("fill", "fillr", "removenear", "remove"));
public final HashSet<String> rad2_1 = new HashSet<>(Arrays.asList("hcyl", "cyl"));
public final HashSet<String> rad2_2 = new HashSet<>(Arrays.asList("sphere", "pyramid"));
public final HashSet<String> rad2_3 = new HashSet<>(Collections.singletonList("brush smooth"));
public final HashSet<String> rad3_1 = new HashSet<>(Collections.singletonList("brush gravity"));
public final HashSet<String> rad3_2 = new HashSet<>(Arrays.asList("brush sphere", "brush cylinder"));
public final HashSet<String> region = new HashSet<>(
Arrays.asList("move", "set", "replace", "overlay", "walls", "outline", "deform", "hollow", "smooth", "naturalize", "paste", "count",
"distr",
"regen", "copy", "cut", "green", "setbiome"));
public final HashSet<String> regionExtend = new HashSet<>(Collections.singletonList("stack"));
public final HashSet<String> restricted = new HashSet<>(Collections.singletonList("up"));
public final HashSet<String> other = new HashSet<>(Arrays.asList("undo", "redo"));
public String reduceCmd(String cmd, boolean single) {
if (cmd.startsWith("/worldedit:/")) {
return cmd.substring(12);
}
if (cmd.startsWith("/worldedit:")) {
return cmd.substring(11);
}
if (cmd.startsWith("//")) {
return cmd.substring(2);
}
if (single && cmd.startsWith("/")) {
return cmd.substring(1);
}
return cmd;
}
public int getInt(String s) {
try {
int max = 0;
String[] split = s.split(",");
for (String rad : split) {
int val = Integer.parseInt(rad);
if (val > max) {
max = val;
}
}
return max;
} catch (NumberFormatException e) {
return 0;
}
}
public boolean checkVolume(PlotPlayer player, long volume, long max, Cancellable e) {
if (volume > max) {
MainUtil.sendMessage(player, C.WORLDEDIT_VOLUME.s().replaceAll("%current%", volume + "").replaceAll("%max%", max + ""));
e.setCancelled(true);
}
if (Permissions.hasPermission(player, "plots.worldedit.bypass")) {
MainUtil.sendMessage(player, C.WORLDEDIT_BYPASS);
}
return true;
}
public boolean checkSelection(Player p, PlotPlayer pp, int modifier, long max, Cancellable e) {
Selection selection = BukkitMain.worldEdit.getSelection(p);
if (selection == null) {
return true;
}
BlockVector pos1 = selection.getNativeMinimumPoint().toBlockVector();
BlockVector pos2 = selection.getNativeMaximumPoint().toBlockVector();
HashSet<RegionWrapper> mask = WEManager.getMask(pp);
RegionWrapper region = new RegionWrapper(pos1.getBlockX(), pos2.getBlockX(), pos1.getBlockZ(), pos2.getBlockZ());
if (Settings.REQUIRE_SELECTION) {
String arg = null;
if (!WEManager.regionContains(region, mask)) {
arg = "pos1 + pos2";
} else if (!WEManager.maskContains(mask, pos1.getBlockX(), pos1.getBlockY(), pos1.getBlockZ())) {
arg = "pos1";
} else if (!WEManager.maskContains(mask, pos2.getBlockX(), pos2.getBlockY(), pos2.getBlockZ())) {
arg = "pos2";
}
if (arg != null) {
e.setCancelled(true);
MainUtil.sendMessage(pp, C.REQUIRE_SELECTION_IN_MASK, arg);
if (Permissions.hasPermission(pp, "plots.worldedit.bypass")) {
MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASS);
}
return true;
}
if (!WEManager.regionContains(region, mask)) {
MainUtil.sendMessage(pp, C.REQUIRE_SELECTION_IN_MASK, "pos1 + pos2");
e.setCancelled(true);
if (Permissions.hasPermission(pp, "plots.worldedit.bypass")) {
MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASS);
}
return true;
}
}
long volume = Math.abs((pos1.getBlockX() - pos2.getBlockX()) * (pos1.getBlockY() - pos2.getBlockY()) * (pos1.getBlockZ() - pos2.getBlockZ()))
* modifier;
return checkVolume(pp, volume, max, e);
}
public boolean delay(final Player player, final String command, boolean delayed) {
if (!Settings.QUEUE_COMMANDS || !Settings.EXPERIMENTAL_FAST_ASYNC_WORLDEDIT) {
return false;
}
boolean free = SetQueue.IMP.addTask(null);
if (free) {
if (delayed) {
MainUtil.sendMessage(BukkitUtil.getPlayer(player), C.WORLDEDIT_RUN, command);
Bukkit.getServer().dispatchCommand(player, command.substring(1));
} else {
return false;
}
} else {
if (!delayed) {
MainUtil.sendMessage(BukkitUtil.getPlayer(player), C.WORLDEDIT_DELAYED);
}
SetQueue.IMP.addTask(new Runnable() {
@Override
public void run() {
delay(player, command, true);
}
});
}
return true;
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public boolean onPlayerCommand(PlayerCommandPreprocessEvent e) {
WorldEditPlugin worldedit = BukkitMain.worldEdit;
if (worldedit == null) {
HandlerList.unregisterAll(this);
return true;
}
Player p = e.getPlayer();
PlotPlayer pp = BukkitUtil.getPlayer(p);
if (!PS.get().hasPlotArea(p.getWorld().getName())) {
return true;
}
String message = e.getMessage();
String cmd = message.toLowerCase();
String[] split = cmd.split(" ");
long maxVolume = Settings.WE_MAX_VOLUME;
long maxIterations = Settings.WE_MAX_ITERATIONS;
if (pp.getAttribute("worldedit")) {
return true;
}
boolean single = true;
if (split.length >= 2) {
String reduced = reduceCmd(split[0], single);
String reduced2 = reduceCmd(split[0] + " " + split[1], single);
if (this.rad1.contains(reduced)) {
if (delay(p, message, false)) {
e.setCancelled(true);
return true;
}
long volume = getInt(split[1]) * 256;
return checkVolume(pp, volume, maxVolume, e);
}
if (this.rad2.contains(reduced)) {
if (delay(p, message, false)) {
e.setCancelled(true);
return true;
}
if (split.length >= 3) {
long volume = getInt(split[2]) * 256;
return checkVolume(pp, volume, maxVolume, e);
}
return true;
}
if (this.rad2_1.contains(reduced)) {
if (delay(p, message, false)) {
e.setCancelled(true);
return true;
}
if (split.length >= 4) {
long volume = getInt(split[2]) * getInt(split[3]);
return checkVolume(pp, volume, maxVolume, e);
}
return true;
}
if (this.rad2_2.contains(reduced)) {
if (delay(p, message, false)) {
e.setCancelled(true);
return true;
}
if (split.length >= 3) {
long radius = getInt(split[2]);
long volume = radius * radius;
return checkVolume(pp, volume, maxVolume, e);
}
return true;
}
if (this.rad2_3.contains(reduced2)) {
if (delay(p, message, false)) {
e.setCancelled(true);
return true;
}
if (split.length >= 3) {
if (split.length == 4) {
int iterations = getInt(split[3]);
if (iterations > maxIterations) {
MainUtil.sendMessage(pp,
C.WORLDEDIT_ITERATIONS.s().replaceAll("%current%", iterations + "").replaceAll("%max%", maxIterations + ""));
e.setCancelled(true);
if (Permissions.hasPermission(pp, "plots.worldedit.bypass")) {
MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASS);
}
return true;
}
}
long radius = getInt(split[2]);
long volume = radius * radius;
return checkVolume(pp, volume, maxVolume, e);
}
return true;
}
if (this.rad3_1.contains(reduced2)) {
if (delay(p, message, false)) {
e.setCancelled(true);
return true;
}
if (split.length >= 3) {
int i = 2;
if (split[i].equalsIgnoreCase("-h")) {
i = 3;
}
long radius = getInt(split[i]);
long volume = radius * radius;
return checkVolume(pp, volume, maxVolume, e);
}
return true;
}
if (this.rad3_2.contains(reduced2)) {
if (delay(p, message, false)) {
e.setCancelled(true);
return true;
}
if (split.length >= 4) {
int i = 3;
if (split[i].equalsIgnoreCase("-h")) {
i = 4;
}
long radius = getInt(split[i]);
long volume = radius * radius;
return checkVolume(pp, volume, maxVolume, e);
}
return true;
}
if (this.regionExtend.contains(reduced)) {
if (delay(p, message, false)) {
e.setCancelled(true);
return true;
}
return checkSelection(p, pp, getInt(split[1]), maxVolume, e);
}
}
String reduced = reduceCmd(split[0], single);
if (Settings.WE_BLACKLIST.contains(reduced)) {
MainUtil.sendMessage(pp, C.WORLDEDIT_UNSAFE);
e.setCancelled(true);
if (Permissions.hasPermission(pp, "plots.worldedit.bypass")) {
MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASS);
}
}
if (this.restricted.contains(reduced)) {
Plot plot = pp.getCurrentPlot();
if ((plot != null) && plot.isAdded(pp.getUUID())) {
if (delay(p, message, false)) {
e.setCancelled(true);
return true;
}
return true;
}
e.setCancelled(true);
MainUtil.sendMessage(pp, C.NO_PLOT_PERMS);
if (Permissions.hasPermission(pp, "plots.worldedit.bypass")) {
MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASS);
}
return true;
}
if (this.region.contains(reduced)) {
if (delay(p, message, false)) {
e.setCancelled(true);
return true;
}
return checkSelection(p, pp, 1, maxVolume, e);
}
if (this.other.contains(reduced)) {
if (delay(p, message, false)) {
e.setCancelled(true);
return true;
}
}
return true;
}
}

View File

@ -122,7 +122,7 @@ public class BukkitLazyBlock extends LazyBlock {
data = this.block.getData();
break;
}
this.pb = new PlotBlock((short) this.id, data);
this.pb = PlotBlock.get((short) this.id, data);
return this.pb;
}

View File

@ -10,8 +10,8 @@ public class BukkitOfflinePlayer implements OfflinePlotPlayer {
public final OfflinePlayer player;
/**
* <p>Please do not use this method. Instead use BukkitUtil.getPlayer(Player),
* as it caches player objects.</p>
* Please do not use this method. Instead use BukkitUtil.getPlayer(Player),
* as it caches player objects.
*
* @param player
*/

View File

@ -1,23 +1,24 @@
package com.plotsquared.bukkit.object;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.EconHandler;
import com.intellectualcrafters.plot.util.PlotGameMode;
import com.intellectualcrafters.plot.util.PlotWeather;
import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.bukkit.util.BukkitUtil;
import org.bukkit.Bukkit;
import org.bukkit.Effect;
import org.bukkit.GameMode;
import org.bukkit.WeatherType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventException;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.permissions.Permission;
import org.bukkit.plugin.PluginManager;
import java.util.UUID;
import org.bukkit.plugin.RegisteredListener;
public class BukkitPlayer extends PlotPlayer {
@ -25,11 +26,10 @@ public class BukkitPlayer extends PlotPlayer {
public boolean offline;
private UUID uuid;
private String name;
private long last = 0;
/**
* <p>Please do not use this method. Instead use BukkitUtil.getPlayer(Player),
* as it caches player objects.</p>
* <p>Please do not use this method. Instead use
* BukkitUtil.getPlayer(Player), as it caches player objects.</p>
* @param player
*/
public BukkitPlayer(Player player) {
@ -42,15 +42,7 @@ public class BukkitPlayer extends PlotPlayer {
this.offline = offline;
super.populatePersistentMetaMap();
}
@Override
public long getPreviousLogin() {
if (this.last == 0) {
this.last = this.player.getLastPlayed();
}
return this.last;
}
@Override
public Location getLocation() {
Location location = super.getLocation();
@ -64,7 +56,44 @@ public class BukkitPlayer extends PlotPlayer {
}
return this.uuid;
}
@Override public long getLastPlayed() {
return this.player.getLastPlayed();
}
@Override
public boolean canTeleport(Location loc) {
org.bukkit.Location to = BukkitUtil.getLocation(loc);
org.bukkit.Location from = player.getLocation();
PlayerTeleportEvent event = new PlayerTeleportEvent(player, from, to);
RegisteredListener[] listeners = event.getHandlers().getRegisteredListeners();
for (RegisteredListener listener : listeners) {
if (listener.getPlugin().getName().equals(PS.imp().getPluginName())) {
continue;
}
try {
listener.callEvent(event);
} catch (EventException e) {
e.printStackTrace();
}
}
if (event.isCancelled() || !event.getTo().equals(to)) {
return false;
}
event = new PlayerTeleportEvent(player, to, from);
for (RegisteredListener listener : listeners) {
if (listener.getPlugin().getName().equals(PS.imp().getPluginName())) {
continue;
}
try {
listener.callEvent(event);
} catch (EventException e) {
e.printStackTrace();
}
}
return true;
}
@Override
public boolean hasPermission(String permission) {
if (this.offline && EconHandler.manager != null) {
@ -73,32 +102,13 @@ public class BukkitPlayer extends PlotPlayer {
return this.player.hasPermission(permission);
}
public Permission getPermission(String node) {
PluginManager manager = Bukkit.getPluginManager();
Permission perm = manager.getPermission(node);
if (perm == null) {
String[] nodes = node.split("\\.");
perm = new Permission(node);
StringBuilder n = new StringBuilder();
for (int i = 0; i < nodes.length - 1; i++) {
n.append(nodes[i]).append(".");
if (!node.equals(n + C.PERMISSION_STAR.s())) {
Permission parent = getPermission(n + C.PERMISSION_STAR.s());
if (parent != null) {
perm.addParent(parent, true);
}
}
}
manager.addPermission(perm);
}
manager.recalculatePermissionDefaults(perm);
perm.recalculatePermissibles();
return perm;
}
@Override
public void sendMessage(String message) {
this.player.sendMessage(message);
if (!StringMan.isEqual(this.<String>getMeta("lastMessage"), message) || (System.currentTimeMillis() - this.<Long>getMeta("lastMessageTime") > 5000)) {
setMeta("lastMessage", message);
setMeta("lastMessageTime", System.currentTimeMillis());
this.player.sendMessage(message);
}
}
@Override
@ -166,7 +176,7 @@ public class BukkitPlayer extends PlotPlayer {
case SURVIVAL:
return PlotGameMode.SURVIVAL;
default:
return PlotGameMode.SURVIVAL;
return PlotGameMode.NOT_SET;
}
}
@ -204,9 +214,15 @@ public class BukkitPlayer extends PlotPlayer {
public void setFlight(boolean fly) {
this.player.setAllowFlight(fly);
}
@Override
public boolean getFlight() {
return player.getAllowFlight();
}
@Override
public void playMusic(Location location, int id) {
//noinspection deprecation
this.player.playEffect(BukkitUtil.getLocation(location), Effect.RECORD_PLAY, id);
}

View File

@ -1,7 +1,8 @@
package com.plotsquared.bukkit.object.entity;
public class AgeableStats {
public int age;
public boolean locked;
public boolean adult;
class AgeableStats {
int age;
boolean locked;
boolean adult;
}

View File

@ -1,16 +1,15 @@
package com.plotsquared.bukkit.object.entity;
public class ArmorStandStats {
class ArmorStandStats {
public final float[] head = new float[3];
public final float[] body = new float[3];
public final float[] leftLeg = new float[3];
public final float[] rightLeg = new float[3];
public final float[] leftArm = new float[3];
public final float[] rightArm = new float[3];
public boolean arms;
public boolean noplate;
public boolean nogravity;
public boolean invisible;
public boolean small;
final float[] head = new float[3];
final float[] body = new float[3];
final float[] leftLeg = new float[3];
final float[] rightLeg = new float[3];
final float[] leftArm = new float[3];
final float[] rightArm = new float[3];
boolean arms;
boolean noPlate;
boolean invisible;
boolean small;
}

View File

@ -1,12 +1,13 @@
package com.plotsquared.bukkit.object.entity;
public class EntityBaseStats {
public EntityWrapper passenger;
public float fall;
public short fire;
public int age;
public double v_z;
public double v_y;
public double v_x;
class EntityBaseStats {
EntityWrapper passenger;
float fall;
short fire;
int age;
double vZ;
double vY;
double vX;
}

View File

@ -1,21 +1,24 @@
package com.plotsquared.bukkit.object.entity;
import com.intellectualcrafters.plot.PS;
import com.plotsquared.bukkit.util.BukkitVersion;
import org.bukkit.Art;
import org.bukkit.DyeColor;
import org.bukkit.Location;
import org.bukkit.Rotation;
import org.bukkit.TreeSpecies;
import org.bukkit.World;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Ageable;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Bat;
import org.bukkit.entity.Boat;
import org.bukkit.entity.EnderDragon;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Guardian;
import org.bukkit.entity.Horse;
import org.bukkit.entity.Horse.Color;
import org.bukkit.entity.Horse.Style;
import org.bukkit.entity.Horse.Variant;
import org.bukkit.entity.IronGolem;
import org.bukkit.entity.Item;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.LivingEntity;
@ -25,6 +28,7 @@ import org.bukkit.entity.Rabbit.Type;
import org.bukkit.entity.Sheep;
import org.bukkit.entity.Skeleton;
import org.bukkit.entity.Skeleton.SkeletonType;
import org.bukkit.entity.Slime;
import org.bukkit.entity.Tameable;
import org.bukkit.inventory.EntityEquipment;
import org.bukkit.inventory.InventoryHolder;
@ -34,59 +38,67 @@ import org.bukkit.util.Vector;
public class EntityWrapper {
private final EntityType type;
private final float yaw;
private final float pitch;
private final short depth;
private final int hash;
public EntityType type;
public float yaw;
public float pitch;
private final EntityBaseStats base = new EntityBaseStats();
public double x;
public double y;
public double z;
public short depth;
public EntityBaseStats base = null;
// Extended
public ItemStack stack;
public ItemStack[] inventory;
public byte dataByte;
public byte dataByte2;
public String dataString;
public LivingEntityStats lived;
public AgeableStats aged;
public TameableStats tamed;
private HorseStats horse;
// Extended
private ItemStack stack;
private byte dataByte;
private byte dataByte2;
private String dataString;
private LivingEntityStats lived;
private AgeableStats aged;
private TameableStats tamed;
private ArmorStandStats stand;
@SuppressWarnings("deprecation")
public EntityWrapper(org.bukkit.entity.Entity entity, short depth) {
private HorseStats horse;
private boolean noGravity;
public EntityWrapper(Entity entity, short depth) {
this.hash = entity.getEntityId();
this.depth = depth;
Location loc = entity.getLocation();
this.yaw = loc.getYaw();
this.pitch = loc.getPitch();
this.x = loc.getX();
this.y = loc.getY();
this.z = loc.getZ();
Location location = entity.getLocation();
this.yaw = location.getYaw();
this.pitch = location.getPitch();
this.x = location.getX();
this.y = location.getY();
this.z = location.getZ();
this.type = entity.getType();
if (depth == 0) {
return;
}
this.base = new EntityBaseStats();
Entity p = entity.getPassenger();
if (p != null) {
this.base.passenger = new EntityWrapper(p, depth);
Entity passenger = entity.getPassenger();
if (passenger != null) {
this.base.passenger = new EntityWrapper(passenger, depth);
}
this.base.fall = entity.getFallDistance();
this.base.fire = (short) entity.getFireTicks();
this.base.age = entity.getTicksLived();
Vector velocity = entity.getVelocity();
this.base.v_x = velocity.getX();
this.base.v_y = velocity.getY();
this.base.v_z = velocity.getZ();
this.base.vX = velocity.getX();
this.base.vY = velocity.getY();
this.base.vZ = velocity.getZ();
if (depth == 1) {
return;
}
if (PS.get().checkVersion(PS.get().IMP.getServerVersion(), BukkitVersion.v1_10_0) || entity instanceof ArmorStand) {
if (!entity.hasGravity()) {
this.noGravity = true;
}
}
switch (entity.getType()) {
case ARROW:
case BOAT:
if (PS.get().checkVersion(PS.get().IMP.getServerVersion(), BukkitVersion.v1_9_0)) {
Boat boat = (Boat) entity;
this.dataByte = getOrdinal(TreeSpecies.values(), boat.getWoodType());
}
case COMPLEX_PART:
case EGG:
case ENDER_CRYSTAL:
@ -113,116 +125,109 @@ public class EntityWrapper {
case THROWN_EXP_BOTTLE:
case WEATHER:
case WITHER_SKULL:
case UNKNOWN: {
case UNKNOWN:
case TIPPED_ARROW:
case SPECTRAL_ARROW:
case SHULKER_BULLET:
case DRAGON_FIREBALL:
case LINGERING_POTION:
case AREA_EFFECT_CLOUD:
// Do this stuff later
return;
}
default: {
default:
PS.debug("&cCOULD NOT IDENTIFY ENTITY: " + entity.getType());
return;
}
// MISC //
case DROPPED_ITEM: {
case DROPPED_ITEM:
Item item = (Item) entity;
this.stack = item.getItemStack();
return;
}
case ITEM_FRAME: {
ItemFrame itemframe = (ItemFrame) entity;
case ITEM_FRAME:
this.x = Math.floor(this.x);
this.y = Math.floor(this.y);
this.z = Math.floor(this.z);
this.dataByte = getOrdinal(Rotation.values(), itemframe.getRotation());
this.stack = itemframe.getItem().clone();
ItemFrame itemFrame = (ItemFrame) entity;
this.dataByte = getOrdinal(Rotation.values(), itemFrame.getRotation());
this.stack = itemFrame.getItem().clone();
return;
}
case PAINTING: {
Painting painting = (Painting) entity;
case PAINTING:
this.x = Math.floor(this.x);
this.y = Math.floor(this.y);
this.z = Math.floor(this.z);
Art a = painting.getArt();
Painting painting = (Painting) entity;
Art art = painting.getArt();
this.dataByte = getOrdinal(BlockFace.values(), painting.getFacing());
int h = a.getBlockHeight();
if ((h % 2) == 0) {
int h = art.getBlockHeight();
if (h % 2 == 0) {
this.y -= 1;
}
this.dataString = a.name();
this.dataString = art.name();
return;
}
// END MISC //
// INVENTORY HOLDER //
case MINECART_CHEST:
case MINECART_HOPPER: {
case MINECART_HOPPER:
storeInventory((InventoryHolder) entity);
return;
}
// START LIVING ENTITY //
// START AGEABLE //
// START TAMEABLE //
case HORSE: {
case HORSE:
Horse horse = (Horse) entity;
this.horse = new HorseStats();
this.horse.jump = horse.getJumpStrength();
this.horse.chest = horse.isCarryingChest();
this.horse.variant = getOrdinal(Variant.values(), horse.getVariant());
this.horse.style = getOrdinal(Style.values(), horse.getStyle());
this.horse.color = getOrdinal(Color.values(), horse.getColor());
storeTameable((Tameable) entity);
storeAgeable((Ageable) entity);
storeLiving((LivingEntity) entity);
storeInventory((InventoryHolder) entity);
this.horse.variant = horse.getVariant();
this.horse.style = horse.getStyle();
this.horse.color = horse.getColor();
storeTameable(horse);
storeAgeable(horse);
storeLiving(horse);
storeInventory(horse);
return;
}
// END INVENTORY HOLDER //
case WOLF:
case OCELOT: {
case OCELOT:
storeTameable((Tameable) entity);
storeAgeable((Ageable) entity);
storeLiving((LivingEntity) entity);
return;
}
// END AMEABLE //
case SHEEP: {
// END TAMEABLE //
case SHEEP:
Sheep sheep = (Sheep) entity;
this.dataByte = (byte) (sheep.isSheared() ? 1 : 0);
this.dataByte2 = sheep.getColor().getDyeData();
storeAgeable((Ageable) entity);
storeLiving((LivingEntity) entity);
storeAgeable(sheep);
storeLiving(sheep);
return;
}
case VILLAGER:
case CHICKEN:
case COW:
case MUSHROOM_COW:
case PIG: {
case PIG:
case POLAR_BEAR:
storeAgeable((Ageable) entity);
storeLiving((LivingEntity) entity);
return;
}
// END AGEABLE //
case RABBIT: { // NEW
case RABBIT:
this.dataByte = getOrdinal(Type.values(), ((Rabbit) entity).getRabbitType());
storeAgeable((Ageable) entity);
storeLiving((LivingEntity) entity);
return;
}
case GUARDIAN: { // NEW
// END AGEABLE //
case GUARDIAN:
this.dataByte = (byte) (((Guardian) entity).isElder() ? 1 : 0);
storeLiving((LivingEntity) entity);
return;
}
case SKELETON: { // NEW
this.dataByte = (byte) ((Skeleton) entity).getSkeletonType().getId();
case SKELETON:
this.dataByte = getOrdinal(SkeletonType.values(),((Skeleton)entity).getSkeletonType());
storeLiving((LivingEntity) entity);
return;
}
case ARMOR_STAND: { // NEW
// CHECK positions
case ARMOR_STAND:
ArmorStand stand = (ArmorStand) entity;
this.inventory = new ItemStack[]{stand.getItemInHand().clone(), stand.getHelmet().clone(), stand.getChestplate().clone(),
stand.getLeggings().clone(), stand.getBoots().clone()};
storeLiving((LivingEntity) entity);
storeLiving(stand);
this.stand = new ArmorStandStats();
EulerAngle head = stand.getHeadPose();
@ -259,10 +264,7 @@ public class EntityWrapper {
this.stand.arms = true;
}
if (!stand.hasBasePlate()) {
this.stand.noplate = true;
}
if (!stand.hasGravity()) {
this.stand.nogravity = true;
this.stand.noPlate = true;
}
if (!stand.isVisible()) {
this.stand.invisible = true;
@ -271,10 +273,19 @@ public class EntityWrapper {
this.stand.small = true;
}
return;
}
case ENDERMITE: // NEW
case ENDERMITE:
return;
case BAT:
if (((Bat) entity).isAwake()) {
this.dataByte = (byte) 1;
} else {
this.dataByte = (byte) 0;
}
return;
case ENDER_DRAGON:
EnderDragon entity1 = (EnderDragon) entity;
this.dataByte = (byte) entity1.getPhase().ordinal();
return;
case GHAST:
case MAGMA_CUBE:
case SQUID:
@ -289,12 +300,18 @@ public class EntityWrapper {
case ENDERMAN:
case CREEPER:
case BLAZE:
case SHULKER:
case SNOWMAN:
case IRON_GOLEM: {
storeLiving((LivingEntity) entity);
return;
}
// END LIVING //
case IRON_GOLEM:
if (((IronGolem) entity).isPlayerCreated()) {
this.dataByte = (byte) 1;
} else {
this.dataByte = (byte) 0;
}
storeLiving((LivingEntity) entity);
// END LIVING //
}
}
@ -312,36 +329,49 @@ public class EntityWrapper {
this.inventory = held.getInventory().getContents().clone();
}
private void restoreLiving(LivingEntity entity) {
void restoreLiving(LivingEntity entity) {
entity.setCanPickupItems(this.lived.loot);
if (this.lived.name != null) {
entity.setCustomName(this.lived.name);
entity.setCustomNameVisible(this.lived.visible);
}
if ((this.lived.potions != null) && !this.lived.potions.isEmpty()) {
if (this.lived.potions != null && !this.lived.potions.isEmpty()) {
entity.addPotionEffects(this.lived.potions);
}
entity.setRemainingAir(this.lived.air);
entity.setRemoveWhenFarAway(this.lived.persistent);
if (this.lived.equipped) {
EntityEquipment equipment = entity.getEquipment();
equipment.setItemInHand(this.lived.hands);
equipment.setHelmet(this.lived.helmet);
equipment.setChestplate(this.lived.chestplate);
equipment.setLeggings(this.lived.leggings);
equipment.setBoots(this.lived.boots);
this.restoreEquipment(entity);
}
if (this.lived.leashed) {
// TODO leashes
// World world = entity.getWorld();
// Entity leash = world.spawnEntity(new Location(world, Math.floor(x) + lived.leash_x, Math.floor(y) + lived.leash_y, Math
// .floor(z) + lived.leash_z), EntityType.LEASH_HITCH);
// Entity leash = world.spawnEntity(new Location(world, Math.floor(x) + lived.leashX, Math.floor(y) + lived.leashY, Math
// .floor(z) + lived.leashZ), EntityType.LEASH_HITCH);
// entity.setLeashHolder(leash);
}
}
void restoreEquipment(LivingEntity entity) {
EntityEquipment equipment = entity.getEquipment();
if (PS.get().checkVersion(PS.get().IMP.getServerVersion(), BukkitVersion.v1_9_0)) {
equipment.setItemInMainHand(this.lived.mainHand);
equipment.setItemInOffHand(this.lived.offHand);
} else {
equipment.setItemInHand(this.lived.mainHand);
}
equipment.setHelmet(this.lived.helmet);
equipment.setChestplate(this.lived.chestplate);
equipment.setLeggings(this.lived.leggings);
equipment.setBoots(this.lived.boots);
}
private void restoreInventory(InventoryHolder entity) {
entity.getInventory().setContents(this.inventory);
try {
entity.getInventory().setContents(this.inventory);
} catch (IllegalArgumentException e) {
PS.debug("&c[WARN] Failed to restore inventory.\n Reason: " + e.getMessage());
}
}
public void storeLiving(LivingEntity lived) {
@ -355,22 +385,32 @@ public class EntityWrapper {
this.lived.persistent = lived.getRemoveWhenFarAway();
this.lived.leashed = lived.isLeashed();
if (this.lived.leashed) {
Location loc = lived.getLeashHolder().getLocation();
this.lived.leash_x = (short) (this.x - loc.getBlockX());
this.lived.leash_y = (short) (this.y - loc.getBlockY());
this.lived.leash_z = (short) (this.z - loc.getBlockZ());
Location location = lived.getLeashHolder().getLocation();
this.lived.leashX = (short) (this.x - location.getBlockX());
this.lived.leashY = (short) (this.y - location.getBlockY());
this.lived.leashZ = (short) (this.z - location.getBlockZ());
}
EntityEquipment equipment = lived.getEquipment();
this.lived.equipped = equipment != null;
if (this.lived.equipped) {
this.lived.hands = equipment.getItemInHand().clone();
this.lived.boots = equipment.getBoots().clone();
this.lived.leggings = equipment.getLeggings().clone();
this.lived.chestplate = equipment.getChestplate().clone();
this.lived.helmet = equipment.getHelmet().clone();
storeEquipment(equipment);
}
}
void storeEquipment(EntityEquipment equipment) {
if (PS.get().checkVersion(PS.get().IMP.getServerVersion(), BukkitVersion.v1_9_0)) {
this.lived.mainHand = equipment.getItemInMainHand().clone();
this.lived.offHand = equipment.getItemInOffHand().clone();
} else {
this.lived.mainHand = equipment.getItemInHand().clone();
this.lived.offHand = null;
}
this.lived.boots = equipment.getBoots().clone();
this.lived.leggings = equipment.getLeggings().clone();
this.lived.chestplate = equipment.getChestplate().clone();
this.lived.helmet = equipment.getHelmet().clone();
}
private void restoreTameable(Tameable entity) {
if (this.tamed.tamed) {
if (this.tamed.owner != null) {
@ -403,33 +443,28 @@ public class EntityWrapper {
this.tamed.tamed = tamed.isTamed();
}
@SuppressWarnings("deprecation")
public Entity spawn(World world, int x_offset, int z_offset) {
Location loc = new Location(world, this.x + x_offset, this.y, this.z + z_offset);
loc.setYaw(this.yaw);
loc.setPitch(this.pitch);
if (this.type.isSpawnable()) {
public Entity spawn(World world, int xOffset, int zOffset) {
Location location = new Location(world, this.x + xOffset, this.y, this.z + zOffset);
location.setYaw(this.yaw);
location.setPitch(this.pitch);
if (!this.type.isSpawnable()) {
return null;
}
Entity entity;
switch (this.type) {
case DROPPED_ITEM: {
return world.dropItem(loc, this.stack);
}
case DROPPED_ITEM:
return world.dropItem(location, this.stack);
case PLAYER:
case LEASH_HITCH: {
case LEASH_HITCH:
return null;
}
case ITEM_FRAME: {
entity = world.spawn(loc, ItemFrame.class);
case ITEM_FRAME:
entity = world.spawn(location, ItemFrame.class);
break;
}
case PAINTING: {
entity = world.spawn(loc, Painting.class);
case PAINTING:
entity = world.spawn(location, Painting.class);
break;
}
default:
entity = world.spawnEntity(loc, this.type);
entity = world.spawnEntity(location, this.type);
break;
}
if (this.depth == 0) {
@ -437,9 +472,8 @@ public class EntityWrapper {
}
if (this.base.passenger != null) {
try {
entity.setPassenger(this.base.passenger.spawn(world, x_offset, z_offset));
} catch (Exception e) {
}
entity.setPassenger(this.base.passenger.spawn(world, xOffset, zOffset));
} catch (Exception ignored) { }
}
if (this.base.fall != 0) {
entity.setFallDistance(this.base.fall);
@ -450,18 +484,29 @@ public class EntityWrapper {
if (this.base.age != 0) {
entity.setTicksLived(this.base.age);
}
entity.setVelocity(new Vector(this.base.v_x, this.base.v_y, this.base.v_z));
entity.setVelocity(new Vector(this.base.vX, this.base.vY, this.base.vZ));
if (this.depth == 1) {
return entity;
}
if (PS.get().checkVersion(PS.get().IMP.getServerVersion(), BukkitVersion.v1_10_0) || entity instanceof ArmorStand) {
if (this.noGravity) {
entity.setGravity(false);
}
}
switch (entity.getType()) {
case ARROW:
case BOAT:
if (PS.get().checkVersion(PS.get().IMP.getServerVersion(), BukkitVersion.v1_9_0)) {
Boat boat = (Boat) entity;
boat.setWoodType(TreeSpecies.values()[dataByte]);
}
case COMPLEX_PART:
case EGG:
case ENDER_CRYSTAL:
case ENDER_PEARL:
case ENDER_SIGNAL:
case DROPPED_ITEM:
case EXPERIENCE_ORB:
case FALLING_BLOCK:
case FIREBALL:
@ -475,68 +520,70 @@ public class EntityWrapper {
case MINECART_TNT:
case PLAYER:
case PRIMED_TNT:
return entity;
case SLIME:
((Slime) entity).setSize(this.dataByte);
return entity;
case SMALL_FIREBALL:
case SNOWBALL:
case SPLASH_POTION:
case THROWN_EXP_BOTTLE:
case WEATHER:
case TIPPED_ARROW:
case SPECTRAL_ARROW:
case SHULKER_BULLET:
case LINGERING_POTION:
case AREA_EFFECT_CLOUD:
case DRAGON_FIREBALL:
case WITHER_SKULL:
case MINECART_FURNACE:
case UNKNOWN: {
case UNKNOWN:
// Do this stuff later
return entity;
}
default: {
default:
PS.debug("&cCOULD NOT IDENTIFY ENTITY: " + entity.getType());
return entity;
}
// MISC //
case ITEM_FRAME: {
case ITEM_FRAME:
ItemFrame itemframe = (ItemFrame) entity;
itemframe.setRotation(Rotation.values()[this.dataByte]);
itemframe.setItem(this.stack);
return entity;
}
case PAINTING: {
case PAINTING:
Painting painting = (Painting) entity;
painting.setFacingDirection(BlockFace.values()[this.dataByte], true);
painting.setArt(Art.getByName(this.dataString), true);
return entity;
}
// END MISC //
// INVENTORY HOLDER //
case MINECART_CHEST:
case MINECART_HOPPER: {
case MINECART_HOPPER:
restoreInventory((InventoryHolder) entity);
return entity;
}
// START LIVING ENTITY //
// START AGEABLE //
// START TAMEABLE //
case HORSE: {
case HORSE:
Horse horse = (Horse) entity;
horse.setJumpStrength(this.horse.jump);
horse.setCarryingChest(this.horse.chest);
horse.setVariant(Variant.values()[this.horse.variant]);
horse.setStyle(Style.values()[this.horse.style]);
horse.setColor(Color.values()[this.horse.color]);
restoreTameable((Tameable) entity);
restoreAgeable((Ageable) entity);
restoreLiving((LivingEntity) entity);
restoreInventory((InventoryHolder) entity);
horse.setVariant(this.horse.variant);
horse.setStyle(this.horse.style);
horse.setColor(this.horse.color);
restoreTameable(horse);
restoreAgeable(horse);
restoreLiving(horse);
restoreInventory(horse);
return entity;
}
// END INVENTORY HOLDER //
case WOLF:
case OCELOT: {
case OCELOT:
restoreTameable((Tameable) entity);
restoreAgeable((Ageable) entity);
restoreLiving((LivingEntity) entity);
return entity;
}
// END AGEABLE //
case SHEEP: {
case SHEEP:
Sheep sheep = (Sheep) entity;
if (this.dataByte == 1) {
sheep.setSheared(true);
@ -544,44 +591,40 @@ public class EntityWrapper {
if (this.dataByte2 != 0) {
sheep.setColor(DyeColor.getByDyeData(this.dataByte2));
}
restoreAgeable((Ageable) entity);
restoreLiving((LivingEntity) entity);
return entity;
}
restoreAgeable(sheep);
restoreLiving(sheep);
return sheep;
case VILLAGER:
case CHICKEN:
case COW:
case POLAR_BEAR:
case MUSHROOM_COW:
case PIG: {
case PIG:
restoreAgeable((Ageable) entity);
restoreLiving((LivingEntity) entity);
return entity;
}
// END AGEABLE //
case RABBIT: { // NEW
case RABBIT:
if (this.dataByte != 0) {
((Rabbit) entity).setRabbitType(Type.values()[this.dataByte]);
}
restoreAgeable((Ageable) entity);
restoreLiving((LivingEntity) entity);
return entity;
}
case GUARDIAN: { // NEW
case GUARDIAN:
if (this.dataByte != 0) {
((Guardian) entity).setElder(true);
}
restoreLiving((LivingEntity) entity);
return entity;
}
case SKELETON: { // NEW
case SKELETON:
if (this.dataByte != 0) {
((Skeleton) entity).setSkeletonType(SkeletonType.values()[this.dataByte]);
}
storeLiving((LivingEntity) entity);
return entity;
}
case ARMOR_STAND: { // NEW
// CHECK positions
case ARMOR_STAND:
// CHECK positions
ArmorStand stand = (ArmorStand) entity;
if (this.inventory[0] != null) {
stand.setItemInHand(this.inventory[0]);
@ -598,27 +641,27 @@ public class EntityWrapper {
if (this.inventory[4] != null) {
stand.setBoots(this.inventory[4]);
}
if ((this.stand.head[0] != 0) || (this.stand.head[1] != 0) || (this.stand.head[2] != 0)) {
if (this.stand.head[0] != 0 || this.stand.head[1] != 0 || this.stand.head[2] != 0) {
EulerAngle pose = new EulerAngle(this.stand.head[0], this.stand.head[1], this.stand.head[2]);
stand.setHeadPose(pose);
}
if ((this.stand.body[0] != 0) || (this.stand.body[1] != 0) || (this.stand.body[2] != 0)) {
if (this.stand.body[0] != 0 || this.stand.body[1] != 0 || this.stand.body[2] != 0) {
EulerAngle pose = new EulerAngle(this.stand.body[0], this.stand.body[1], this.stand.body[2]);
stand.setBodyPose(pose);
}
if ((this.stand.leftLeg[0] != 0) || (this.stand.leftLeg[1] != 0) || (this.stand.leftLeg[2] != 0)) {
if (this.stand.leftLeg[0] != 0 || this.stand.leftLeg[1] != 0 || this.stand.leftLeg[2] != 0) {
EulerAngle pose = new EulerAngle(this.stand.leftLeg[0], this.stand.leftLeg[1], this.stand.leftLeg[2]);
stand.setLeftLegPose(pose);
}
if ((this.stand.rightLeg[0] != 0) || (this.stand.rightLeg[1] != 0) || (this.stand.rightLeg[2] != 0)) {
if (this.stand.rightLeg[0] != 0 || this.stand.rightLeg[1] != 0 || this.stand.rightLeg[2] != 0) {
EulerAngle pose = new EulerAngle(this.stand.rightLeg[0], this.stand.rightLeg[1], this.stand.rightLeg[2]);
stand.setRightLegPose(pose);
}
if ((this.stand.leftArm[0] != 0) || (this.stand.leftArm[1] != 0) || (this.stand.leftArm[2] != 0)) {
if (this.stand.leftArm[0] != 0 || this.stand.leftArm[1] != 0 || this.stand.leftArm[2] != 0) {
EulerAngle pose = new EulerAngle(this.stand.leftArm[0], this.stand.leftArm[1], this.stand.leftArm[2]);
stand.setLeftArmPose(pose);
}
if ((this.stand.rightArm[0] != 0) || (this.stand.rightArm[1] != 0) || (this.stand.rightArm[2] != 0)) {
if (this.stand.rightArm[0] != 0 || this.stand.rightArm[1] != 0 || this.stand.rightArm[2] != 0) {
EulerAngle pose = new EulerAngle(this.stand.rightArm[0], this.stand.rightArm[1], this.stand.rightArm[2]);
stand.setRightArmPose(pose);
}
@ -628,21 +671,27 @@ public class EntityWrapper {
if (this.stand.arms) {
stand.setArms(true);
}
if (this.stand.nogravity) {
stand.setGravity(false);
}
if (this.stand.noplate) {
if (this.stand.noPlate) {
stand.setBasePlate(false);
}
if (this.stand.small) {
stand.setSmall(true);
}
restoreLiving(stand);
return stand;
case BAT:
if (this.dataByte != 0) {
((Bat) entity).setAwake(true);
}
restoreLiving((LivingEntity) entity);
return entity;
}
case ENDERMITE: // NEW
case BAT:
case ENDER_DRAGON:
if (this.dataByte != 0) {
((EnderDragon) entity).setPhase(EnderDragon.Phase.values()[this.dataByte]);
}
restoreLiving((LivingEntity) entity);
return entity;
case ENDERMITE:
case GHAST:
case MAGMA_CUBE:
case SQUID:
@ -658,11 +707,16 @@ public class EntityWrapper {
case CREEPER:
case BLAZE:
case SNOWMAN:
case IRON_GOLEM: {
case SHULKER:
restoreLiving((LivingEntity) entity);
return entity;
}
// END LIVING //
case IRON_GOLEM:
if (this.dataByte != 0) {
((IronGolem) entity).setPlayerCreated(true);
}
restoreLiving((LivingEntity) entity);
return entity;
// END LIVING
}
}
@ -674,4 +728,10 @@ public class EntityWrapper {
}
return 0;
}
@SuppressWarnings("deprecation")
@Override
public String toString() {
return String.format("[%s, x=%s, y=%s, z=%s]", type.getName(), x, y, z);
}
}

View File

@ -1,9 +1,12 @@
package com.plotsquared.bukkit.object.entity;
public class HorseStats {
public double jump;
public boolean chest;
public int variant;
public int color;
public int style;
import org.bukkit.entity.Horse;
class HorseStats {
double jump;
boolean chest;
Horse.Variant variant;
Horse.Color color;
Horse.Style style;
}

View File

@ -1,26 +1,28 @@
package com.plotsquared.bukkit.object.entity;
import java.util.Collection;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
public class LivingEntityStats {
public boolean loot;
public String name;
public boolean visible;
public float health;
public short air;
public boolean persistent;
public boolean leashed;
public short leash_x;
public short leash_y;
public short leash_z;
public boolean equipped;
public ItemStack hands;
public ItemStack helmet;
public ItemStack boots;
public ItemStack leggings;
public ItemStack chestplate;
public Collection<PotionEffect> potions;
import java.util.Collection;
class LivingEntityStats {
boolean loot;
String name;
boolean visible;
float health;
short air;
boolean persistent;
boolean leashed;
short leashX;
short leashY;
short leashZ;
boolean equipped;
ItemStack mainHand;
ItemStack helmet;
ItemStack boots;
ItemStack leggings;
ItemStack chestplate;
Collection<PotionEffect> potions;
ItemStack offHand;
}

View File

@ -2,7 +2,8 @@ package com.plotsquared.bukkit.object.entity;
import org.bukkit.entity.AnimalTamer;
public class TameableStats {
public AnimalTamer owner;
public boolean tamed;
class TameableStats {
AnimalTamer owner;
boolean tamed;
}

View File

@ -6,11 +6,13 @@ import com.intellectualcrafters.jnbt.ListTag;
import com.intellectualcrafters.jnbt.ShortTag;
import com.intellectualcrafters.jnbt.Tag;
import com.intellectualcrafters.plot.object.schematic.ItemType;
import com.intellectualcrafters.plot.object.schematic.PlotItem;
import com.intellectualcrafters.plot.util.MathMan;
import com.intellectualcrafters.plot.util.SchematicHandler.Schematic;
import com.plotsquared.bukkit.util.BukkitUtil;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
@ -33,32 +35,50 @@ public class StateWrapper {
this.tag = tag;
}
public boolean restoreTag(short x, short y, short z, Schematic schematic) {
public boolean restoreTag(String worldName, int x, int y, int z) {
if (this.tag == null) {
return false;
}
List<Tag> itemsTag = this.tag.getListTag("Items").getValue();
int length = itemsTag.size();
short[] ids = new short[length];
byte[] datas = new byte[length];
byte[] amounts = new byte[length];
for (int i = 0; i < length; i++) {
Tag itemTag = itemsTag.get(i);
CompoundTag itemComp = (CompoundTag) itemTag;
short id = itemComp.getShort("id");
String idStr = itemComp.getString("id");
if (idStr != null && !MathMan.isInteger(idStr)) {
idStr = idStr.split(":")[0].toLowerCase();
id = (short) ItemType.getId(idStr);
}
ids[i] = id;
datas[i] = (byte) itemComp.getShort("Damage");
amounts[i] = itemComp.getByte("Count");
switch (this.tag.getString("id").toLowerCase()) {
case "chest":
List<Tag> itemsTag = this.tag.getListTag("Items").getValue();
int length = itemsTag.size();
short[] ids = new short[length];
byte[] datas = new byte[length];
byte[] amounts = new byte[length];
byte[] slots = new byte[length];
for (int i = 0; i < length; i++) {
Tag itemTag = itemsTag.get(i);
CompoundTag itemComp = (CompoundTag) itemTag;
short id = itemComp.getShort("id");
String idStr = itemComp.getString("id");
if (idStr != null && !MathMan.isInteger(idStr)) {
idStr = idStr.split(":")[1].toLowerCase();
id = (short) ItemType.getId(idStr);
}
ids[i] = id;
datas[i] = (byte) itemComp.getShort("Damage");
amounts[i] = itemComp.getByte("Count");
slots[i] = itemComp.getByte("Slot");
}
World world = BukkitUtil.getWorld(worldName);
Block block = world.getBlockAt(x, y, z);
if (block == null) {
return false;
}
BlockState state = block.getState();
if (state instanceof InventoryHolder) {
InventoryHolder holder = (InventoryHolder) state;
Inventory inv = holder.getInventory();
for (int i = 0; i < ids.length; i++) {
ItemStack item = new ItemStack(ids[i], amounts[i], datas[i]);
inv.addItem(item);
}
state.update(true);
return true;
}
}
if (length != 0) {
schematic.addItem(new PlotItem(x, y, z, ids, datas, amounts));
}
return true;
return false;
}
public CompoundTag getTag() {

View File

@ -11,7 +11,7 @@ public class DefaultTitle extends AbstractTitle {
try {
DefaultTitleManager title = new DefaultTitleManager(head, sub, in, delay, out);
title.send(((BukkitPlayer) player).player);
} catch (Throwable e) {
} catch (Exception ignored) {
AbstractTitle.TITLE_CLASS = new DefaultTitle_183();
AbstractTitle.TITLE_CLASS.sendTitle(player, head, sub, in, delay, out);
}

View File

@ -1,89 +1,13 @@
package com.plotsquared.bukkit.titles;
import com.plotsquared.bukkit.chat.Reflection;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
* [ PlotSquared DefaultTitleManager by Maxim Van de Wynckel ]
*
* @author Maxim Van de Wynckel
*
*/
public class DefaultTitleManager {
private static final Map<Class<?>, Class<?>> CORRESPONDING_TYPES = new HashMap<>();
/* Title packet */
private Class<?> packetTitle;
/* Title packet actions ENUM */
private Class<?> packetActions;
/* Chat serializer */
private Class<?> nmsChatSerializer;
private Class<?> chatBaseComponent;
/* Title text and color */
private String title = "";
private ChatColor titleColor = ChatColor.WHITE;
/* Subtitle text and color */
private String subtitle = "";
private ChatColor subtitleColor = ChatColor.WHITE;
/* Title timings */
private int fadeInTime = -1;
private int stayTime = -1;
private int fadeOutTime = -1;
private boolean ticks = false;
/**
* Create a new 1.8 title
*
* @param title
* Title
* @throws ClassNotFoundException
*/
public DefaultTitleManager(String title) throws ClassNotFoundException {
this.title = title;
loadClasses();
}
/**
* Create a new 1.8 title
*
* @param title
* Title text
* @param subtitle
* Subtitle text
* @throws ClassNotFoundException
*/
public DefaultTitleManager(String title, String subtitle) throws ClassNotFoundException {
this.title = title;
this.subtitle = subtitle;
loadClasses();
}
/**
* Copy 1.8 title.
*
* @param title Title
* @throws ClassNotFoundException
*/
public DefaultTitleManager(DefaultTitleManager title) throws ClassNotFoundException {
// Copy title
this.title = title.title;
this.subtitle = title.subtitle;
this.titleColor = title.titleColor;
this.subtitleColor = title.subtitleColor;
this.fadeInTime = title.fadeInTime;
this.fadeOutTime = title.fadeOutTime;
this.stayTime = title.stayTime;
this.ticks = title.ticks;
loadClasses();
}
public class DefaultTitleManager extends TitleManager {
/**
* Create a new 1.8 title.
@ -93,144 +17,22 @@ public class DefaultTitleManager {
* @param fadeInTime Fade in time
* @param stayTime Stay on screen time
* @param fadeOutTime Fade out time
* @throws ClassNotFoundException
*/
public DefaultTitleManager(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime)
throws ClassNotFoundException {
this.title = title;
this.subtitle = subtitle;
this.fadeInTime = fadeInTime;
this.stayTime = stayTime;
this.fadeOutTime = fadeOutTime;
loadClasses();
}
private static boolean equalsTypeArray(Class<?>[] a, Class<?>[] o) {
if (a.length != o.length) {
return false;
}
for (int i = 0; i < a.length; i++) {
if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i])) {
return false;
}
}
return true;
DefaultTitleManager(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) {
super(title, subtitle, fadeInTime, stayTime, fadeOutTime);
}
/**
* Load spigot and NMS classes
* @throws ClassNotFoundException
* Load spigot and NMS classes.
*/
private void loadClasses() throws ClassNotFoundException {
@Override void loadClasses() {
this.packetTitle = Reflection.getNMSClass("PacketPlayOutTitle");
this.packetActions = Reflection.getNMSClass("EnumTitleAction");
this.chatBaseComponent = Reflection.getNMSClass("IChatBaseComponent");
this.nmsChatSerializer = Reflection.getNMSClass("ChatSerializer");
}
/**
* Get title text
*
* @return Title text
*/
public String getTitle() {
return this.title;
}
/**
* Set title text
*
* @param title
* Title
*/
public void setTitle(String title) {
this.title = title;
}
/**
* Get subtitle text
*
* @return Subtitle text
*/
public String getSubtitle() {
return this.subtitle;
}
/**
* Set subtitle text.
*
* @param subtitle Subtitle text
*/
public void setSubtitle(String subtitle) {
this.subtitle = subtitle;
}
/**
* Set the title color.
*
* @param color Chat color
*/
public void setTitleColor(ChatColor color) {
this.titleColor = color;
}
/**
* Set the subtitle color.
*
* @param color Chat color
*/
public void setSubtitleColor(ChatColor color) {
this.subtitleColor = color;
}
/**
* Set title fade in time.
*
* @param time Time
*/
public void setFadeInTime(int time) {
this.fadeInTime = time;
}
/**
* Set title fade out time.
*
* @param time Time
*/
public void setFadeOutTime(int time) {
this.fadeOutTime = time;
}
/**
* Set title stay time.
*
* @param time Time
*/
public void setStayTime(int time) {
this.stayTime = time;
}
/**
* Set timings to ticks.
*/
public void setTimingsToTicks() {
this.ticks = true;
}
/**
* Set timings to seconds.
*/
public void setTimingsToSeconds() {
this.ticks = false;
}
/**
* Send the title to a player.
*
* @param player Player
* @throws Exception
*/
public void send(Player player) throws Exception {
@Override public void send(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
if (this.packetTitle != null) {
// First reset previous settings
resetTitle(player);
@ -248,38 +50,23 @@ public class DefaultTitleManager {
}
// Send title
Object serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.title) + "\",color:" + this.titleColor.name().toLowerCase() + "}");
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getTitle()) + "\",color:" + this.titleColor.name().toLowerCase()
+ '}');
packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[0], serialized);
sendPacket.invoke(connection, packet);
if (!this.subtitle.isEmpty()) {
if (!this.getSubtitle().isEmpty()) {
// Send subtitle if present
serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.subtitle) + "\",color:" + this.subtitleColor.name()
.toLowerCase() + "}");
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getSubtitle()) + "\",color:" + this.subtitleColor.name()
.toLowerCase() + '}');
packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[1], serialized);
sendPacket.invoke(connection, packet);
}
}
}
/**
* Broadcast the title to all players.
*
* @throws Exception
*/
public void broadcast() throws Exception {
for (Player p : Bukkit.getOnlinePlayers()) {
send(p);
}
}
/**
* Clear the title.
*
* @param player Player
* @throws Exception
*/
public void clearTitle(Player player) throws Exception {
@Override
public void clearTitle(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
// Send timings first
Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
@ -293,9 +80,12 @@ public class DefaultTitleManager {
* Reset the title settings.
*
* @param player Player
* @throws Exception
* @throws SecurityException
* @throws ReflectiveOperationException
* @throws SecurityException
*/
public void resetTitle(Player player) throws Exception {
@Override
public void resetTitle(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
// Send timings first
Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
@ -305,62 +95,20 @@ public class DefaultTitleManager {
sendPacket.invoke(connection, packet);
}
private Class<?> getPrimitiveType(Class<?> clazz) {
return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES.get(clazz) : clazz;
}
private Class<?>[] toPrimitiveTypeArray(Class<?>[] classes) {
int a = classes != null ? classes.length : 0;
Class<?>[] types = new Class<?>[a];
for (int i = 0; i < a; i++) {
types[i] = getPrimitiveType(classes[i]);
}
return types;
}
private Object getHandle(Object obj) {
try {
return getMethod("getHandle", obj.getClass()).invoke(obj);
} catch (IllegalAccessException e) {
e.printStackTrace();
return null;
} catch (IllegalArgumentException e) {
e.printStackTrace();
return null;
} catch (InvocationTargetException e) {
e.printStackTrace();
return null;
}
}
private Method getMethod(String name, Class<?> clazz, Class<?>... paramTypes) {
Class<?>[] t = toPrimitiveTypeArray(paramTypes);
for (Method m : clazz.getMethods()) {
Class<?>[] types = toPrimitiveTypeArray(m.getParameterTypes());
if (m.getName().equals(name) && equalsTypeArray(types, t)) {
return m;
}
}
return null;
}
private Field getField(Class<?> clazz, String name) {
Field getField(Class<?> clazz, String name) {
try {
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field;
} catch (NoSuchFieldException e) {
e.printStackTrace();
return null;
} catch (SecurityException e) {
} catch (NoSuchFieldException | SecurityException e) {
e.printStackTrace();
return null;
}
}
private Method getMethod(Class<?> clazz, String name, Class<?>... args) {
Method getMethod(Class<?> clazz, String name, Class<?>... args) {
for (Method m : clazz.getMethods()) {
if (m.getName().equals(name) && (args.length == 0 || ClassListEqual(args, m.getParameterTypes()))) {
if (m.getName().equals(name) && (args.length == 0 || classListEqual(args, m.getParameterTypes()))) {
m.setAccessible(true);
return m;
}
@ -368,17 +116,4 @@ public class DefaultTitleManager {
return null;
}
private boolean ClassListEqual(Class<?>[] l1, Class<?>[] l2) {
if (l1.length != l2.length) {
return false;
}
boolean equal = true;
for (int i = 0; i < l1.length; i++) {
if (l1[i] != l2[i]) {
equal = false;
break;
}
}
return equal;
}
}

View File

@ -1,252 +1,39 @@
package com.plotsquared.bukkit.titles;
import com.plotsquared.bukkit.chat.Reflection;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
* [ PlotSquared DefaultTitleManager by Maxim Van de Wynckel ]
*
* @version 1.1.0
* @author Maxim Van de Wynckel
*
*/
public class DefaultTitleManager_183 {
private static final Map<Class<?>, Class<?>> CORRESPONDING_TYPES = new HashMap<>();
/* Title packet */
private Class<?> packetTitle;
/* Title packet actions ENUM */
private Class<?> packetActions;
/* Chat serializer */
private Class<?> nmsChatSerializer;
private Class<?> chatBaseComponent;
/* Title text and color */
private String title = "";
private ChatColor titleColor = ChatColor.WHITE;
/* Subtitle text and color */
private String subtitle = "";
private ChatColor subtitleColor = ChatColor.WHITE;
/* Title timings */
private int fadeInTime = -1;
private int stayTime = -1;
private int fadeOutTime = -1;
private boolean ticks = false;
public class DefaultTitleManager_183 extends DefaultTitleManager {
/**
* Create a new 1.8 title
* Create a new 1.8 title.
*
* @param title
* Title
* @throws ClassNotFoundException
* @param title Title text
* @param subtitle Subtitle text
* @param fadeInTime Fade in time
* @param stayTime Stay on screen time
* @param fadeOutTime Fade out time
*/
public DefaultTitleManager_183(String title) throws ClassNotFoundException {
this.title = title;
loadClasses();
DefaultTitleManager_183(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) {
super(title, subtitle, fadeInTime, stayTime, fadeOutTime);
}
/**
* Create a new 1.8 title
*
* @param title
* Title text
* @param subtitle
* Subtitle text
* @throws ClassNotFoundException
* Load spigot and NMS classes.
*/
public DefaultTitleManager_183(String title, String subtitle) throws ClassNotFoundException {
this.title = title;
this.subtitle = subtitle;
loadClasses();
}
/**
* Copy 1.8 title
*
* @param title
* Title
* @throws ClassNotFoundException
*/
public DefaultTitleManager_183(DefaultTitleManager_183 title) throws ClassNotFoundException {
// Copy title
this.title = title.title;
this.subtitle = title.subtitle;
this.titleColor = title.titleColor;
this.subtitleColor = title.subtitleColor;
this.fadeInTime = title.fadeInTime;
this.fadeOutTime = title.fadeOutTime;
this.stayTime = title.stayTime;
this.ticks = title.ticks;
loadClasses();
}
/**
* Create a new 1.8 title
*
* @param title
* Title text
* @param subtitle
* Subtitle text
* @param fadeInTime
* Fade in time
* @param stayTime
* Stay on screen time
* @param fadeOutTime
* Fade out time
* @throws ClassNotFoundException
*/
public DefaultTitleManager_183(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) throws ClassNotFoundException {
this.title = title;
this.subtitle = subtitle;
this.fadeInTime = fadeInTime;
this.stayTime = stayTime;
this.fadeOutTime = fadeOutTime;
loadClasses();
}
private static boolean equalsTypeArray(Class<?>[] a, Class<?>[] o) {
if (a.length != o.length) {
return false;
}
for (int i = 0; i < a.length; i++) {
if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i])) {
return false;
}
}
return true;
}
/**
* Load spigot and NMS classes
* @throws ClassNotFoundException
*/
private void loadClasses() throws ClassNotFoundException {
@Override
void loadClasses() {
this.packetTitle = Reflection.getNMSClass("PacketPlayOutTitle");
this.chatBaseComponent = Reflection.getNMSClass("IChatBaseComponent");
this.packetActions = Reflection.getNMSClass("PacketPlayOutTitle$EnumTitleAction");
this.nmsChatSerializer = Reflection.getNMSClass("IChatBaseComponent$ChatSerializer");
}
/**
* Get title text
*
* @return Title text
*/
public String getTitle() {
return this.title;
}
/**
* Set title text
*
* @param title
* Title
*/
public void setTitle(String title) {
this.title = title;
}
/**
* Get subtitle text
*
* @return Subtitle text
*/
public String getSubtitle() {
return this.subtitle;
}
/**
* Set subtitle text
*
* @param subtitle
* Subtitle text
*/
public void setSubtitle(String subtitle) {
this.subtitle = subtitle;
}
/**
* Set the title color
*
* @param color
* Chat color
*/
public void setTitleColor(ChatColor color) {
this.titleColor = color;
}
/**
* Set the subtitle color
*
* @param color
* Chat color
*/
public void setSubtitleColor(ChatColor color) {
this.subtitleColor = color;
}
/**
* Set title fade in time
*
* @param time
* Time
*/
public void setFadeInTime(int time) {
this.fadeInTime = time;
}
/**
* Set title fade out time
*
* @param time
* Time
*/
public void setFadeOutTime(int time) {
this.fadeOutTime = time;
}
/**
* Set title stay time
*
* @param time
* Time
*/
public void setStayTime(int time) {
this.stayTime = time;
}
/**
* Set timings to ticks
*/
public void setTimingsToTicks() {
this.ticks = true;
}
/**
* Set timings to seconds
*/
public void setTimingsToSeconds() {
this.ticks = false;
}
/**
* Send the title to a player
*
* @param player
* Player
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public void send(Player player) throws Exception {
@Override
public void send(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
if (this.packetTitle != null) {
// First reset previous settings
resetTitle(player);
@ -258,11 +45,7 @@ public class DefaultTitleManager_183 {
Object packet = this.packetTitle
.getConstructor(this.packetActions, this.chatBaseComponent, Integer.TYPE, Integer.TYPE, Integer.TYPE)
.newInstance(actions[2], null,
this.fadeInTime * (
this.ticks ? 1 : 20),
this.fadeInTime * (this.ticks ? 1 : 20),
this.stayTime * (this.ticks ? 1 : 20), this.fadeOutTime * (this.ticks ? 1 : 20));
// Send if set
if ((this.fadeInTime != -1) && (this.fadeOutTime != -1) && (this.stayTime != -1)) {
@ -270,135 +53,18 @@ public class DefaultTitleManager_183 {
}
// Send title
Object serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.title) + "\",color:" + this.titleColor.name().toLowerCase() + "}");
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getTitle()) + "\",color:" + this.titleColor.name().toLowerCase()
+ "}");
packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[0], serialized);
sendPacket.invoke(connection, packet);
if (!this.subtitle.isEmpty()) {
if (!this.getSubtitle().isEmpty()) {
// Send subtitle if present
serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.subtitle) + "\",color:" + this.subtitleColor.name()
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getSubtitle()) + "\",color:" + this.subtitleColor.name()
.toLowerCase() + "}");
packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[1], serialized);
sendPacket.invoke(connection, packet);
}
}
}
/**
* Broadcast the title to all players
* @throws Exception
*/
public void broadcast() throws Exception {
for (Player p : Bukkit.getOnlinePlayers()) {
send(p);
}
}
/**
* Clear the title
*
* @param player
* Player
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public void clearTitle(Player player) throws Exception {
// Send timings first
Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object[] actions = this.packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[3], null);
sendPacket.invoke(connection, packet);
}
/**
* Reset the title settings
*
* @param player
* Player
* @throws SecurityException
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public void resetTitle(Player player) throws Exception {
// Send timings first
Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object[] actions = this.packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[4], null);
sendPacket.invoke(connection, packet);
}
private Class<?> getPrimitiveType(Class<?> clazz) {
return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES.get(clazz) : clazz;
}
private Class<?>[] toPrimitiveTypeArray(Class<?>[] classes) {
int a = classes != null ? classes.length : 0;
Class<?>[] types = new Class<?>[a];
for (int i = 0; i < a; i++) {
types[i] = getPrimitiveType(classes[i]);
}
return types;
}
private Object getHandle(Object obj) {
try {
return getMethod("getHandle", obj.getClass()).invoke(obj);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private Method getMethod(String name, Class<?> clazz, Class<?>... paramTypes) {
Class<?>[] t = toPrimitiveTypeArray(paramTypes);
for (Method m : clazz.getMethods()) {
Class<?>[] types = toPrimitiveTypeArray(m.getParameterTypes());
if (m.getName().equals(name) && equalsTypeArray(types, t)) {
return m;
}
}
return null;
}
private Field getField(Class<?> clazz, String name) {
try {
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field;
} catch (NoSuchFieldException | SecurityException e) {
e.printStackTrace();
return null;
}
}
private Method getMethod(Class<?> clazz, String name, Class<?>... args) {
for (Method m : clazz.getMethods()) {
if (m.getName().equals(name) && ((args.length == 0) || ClassListEqual(args, m.getParameterTypes()))) {
m.setAccessible(true);
return m;
}
}
return null;
}
private boolean ClassListEqual(Class<?>[] l1, Class<?>[] l2) {
if (l1.length != l2.length) {
return false;
}
boolean equal = true;
for (int i = 0; i < l1.length; i++) {
if (l1[i] != l2[i]) {
equal = false;
break;
}
}
return equal;
}
}

View File

@ -11,7 +11,7 @@ public class DefaultTitle_183 extends AbstractTitle {
try {
DefaultTitleManager_183 title = new DefaultTitleManager_183(head, sub, in, delay, out);
title.send(((BukkitPlayer) player).player);
} catch (Throwable e) {
} catch (Exception ignored) {
AbstractTitle.TITLE_CLASS = new HackTitle();
AbstractTitle.TITLE_CLASS.sendTitle(player, head, sub, in, delay, out);
}

View File

@ -6,6 +6,7 @@ import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.bukkit.object.BukkitPlayer;
import org.bukkit.entity.Player;
@SuppressWarnings("deprecation")
public class DefaultTitle_19 extends AbstractTitle {
@Override
@ -19,7 +20,7 @@ public class DefaultTitle_19 extends AbstractTitle {
playerObj.sendTitle("", "");
}
}, delay * 20);
} catch (Throwable e) {
} catch (Throwable ignored) {
AbstractTitle.TITLE_CLASS = new DefaultTitle();
AbstractTitle.TITLE_CLASS.sendTitle(player, head, sub, in, delay, out);
}

View File

@ -13,7 +13,7 @@ public class HackTitle extends AbstractTitle {
try {
HackTitleManager title = new HackTitleManager(head, sub, in, delay, out);
title.send(((BukkitPlayer) player).player);
} catch (Throwable e) {
} catch (Exception ignored) {
PS.debug("&cYour server version does not support titles!");
Settings.TITLES = false;
AbstractTitle.TITLE_CLASS = null;

View File

@ -6,80 +6,9 @@ import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
* Minecraft 1.8 Title.
*
* @version 1.0.4
* @author Maxim Van de Wynckel
*/
public class HackTitleManager {
private static final Map<Class<?>, Class<?>> CORRESPONDING_TYPES = new HashMap<>();
/* Title packet */
private Class<?> packetTitle;
/* Title packet actions ENUM */
private Class<?> packetActions;
/* Chat serializer */
private Class<?> nmsChatSerializer;
/* Title text and color */
private String title = "";
private ChatColor titleColor = ChatColor.WHITE;
/* Subtitle text and color */
private String subtitle = "";
private ChatColor subtitleColor = ChatColor.WHITE;
/* Title timings. */
private int fadeInTime = -1;
private int stayTime = -1;
private int fadeOutTime = -1;
private boolean ticks = false;
/**
* Create a new 1.8 title.
*
* @param title Title
* @throws ClassNotFoundException NMS Error.
*/
public HackTitleManager(String title) throws ClassNotFoundException {
this.title = title;
loadClasses();
}
/**
* Create a new 1.8 title.
*
* @param title Title text
* @param subtitle Subtitle text
* @throws ClassNotFoundException NMS Error
*/
public HackTitleManager(String title, String subtitle) throws ClassNotFoundException {
this.title = title;
this.subtitle = subtitle;
loadClasses();
}
/**
* Copy 1.8 title.
*
* @param title Title
* @throws ClassNotFoundException NMS Error
*/
public HackTitleManager(HackTitleManager title) throws ClassNotFoundException {
// Copy title
this.title = title.title;
this.subtitle = title.subtitle;
this.titleColor = title.titleColor;
this.subtitleColor = title.subtitleColor;
this.fadeInTime = title.fadeInTime;
this.fadeOutTime = title.fadeOutTime;
this.stayTime = title.stayTime;
this.ticks = title.ticks;
loadClasses();
}
public class HackTitleManager extends TitleManager {
/**
* Create a new 1.8 title.
@ -89,141 +18,22 @@ public class HackTitleManager {
* @param fadeInTime Fade in time
* @param stayTime Stay on screen time
* @param fadeOutTime Fade out time
* @throws ClassNotFoundException NMS error
*/
public HackTitleManager(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) throws ClassNotFoundException {
this.title = title;
this.subtitle = subtitle;
this.fadeInTime = fadeInTime;
this.stayTime = stayTime;
this.fadeOutTime = fadeOutTime;
loadClasses();
}
private static boolean equalsTypeArray(Class<?>[] a, Class<?>[] o) {
if (a.length != o.length) {
return false;
}
for (int i = 0; i < a.length; i++) {
if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i])) {
return false;
}
}
return true;
HackTitleManager(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) {
super(title, subtitle, fadeInTime, stayTime, fadeOutTime);
}
/**
* Load spigot and NMS classes.
* @throws ClassNotFoundException Spigot Error.
*/
private void loadClasses() throws ClassNotFoundException {
@Override
void loadClasses() {
this.packetTitle = getClass("org.spigotmc.ProtocolInjector$PacketTitle");
this.packetActions = getClass("org.spigotmc.ProtocolInjector$PacketTitle$Action");
this.nmsChatSerializer = Reflection.getNMSClass("ChatSerializer");
}
/**
* Get title text.
*
* @return Title text
*/
public String getTitle() {
return this.title;
}
/**
* Set title text.
*
* @param title Title
*/
public void setTitle(String title) {
this.title = title;
}
/**
* Get subtitle text.
*
* @return Subtitle text
*/
public String getSubtitle() {
return this.subtitle;
}
/**
* Set subtitle text.
*
* @param subtitle Subtitle text
*/
public void setSubtitle(String subtitle) {
this.subtitle = subtitle;
}
/**
* Set the title color.
*
* @param color Chat color
*/
public void setTitleColor(ChatColor color) {
this.titleColor = color;
}
/**
* Set the subtitle color.
*
* @param color Chat color
*/
public void setSubtitleColor(ChatColor color) {
this.subtitleColor = color;
}
/**
* Set title fade in time.
*
* @param time Time
*/
public void setFadeInTime(int time) {
this.fadeInTime = time;
}
/**
* Set title fade out time.
*
* @param time Time
*/
public void setFadeOutTime(int time) {
this.fadeOutTime = time;
}
/**
* Set title stay time.
*
* @param time Time
*/
public void setStayTime(int time) {
this.stayTime = time;
}
/**
* Set timings to ticks.
*/
public void setTimingsToTicks() {
this.ticks = true;
}
/**
* Set timings to seconds.
*/
public void setTimingsToSeconds() {
this.ticks = false;
}
/**
* Send the title to a player.
*
* @param player Player
* @throws Exception on NMS error
*/
public void send(Player player) throws Exception {
@Override public void send(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
if ((getProtocolVersion(player) >= 47) && isSpigot() && (this.packetTitle != null)) {
// First reset previous settings
resetTitle(player);
@ -242,14 +52,15 @@ public class HackTitleManager {
}
// Send title
Object serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.title) + "\",color:" + this.titleColor.name().toLowerCase() + "}");
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getTitle()) + "\",color:" + this.titleColor.name().toLowerCase()
+ "}");
packet = this.packetTitle.getConstructor(this.packetActions, Reflection.getNMSClass("IChatBaseComponent"))
.newInstance(actions[0], serialized);
sendPacket.invoke(connection, packet);
if (!this.subtitle.isEmpty()) {
if (!this.getSubtitle().isEmpty()) {
// Send subtitle if present
serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.subtitle) + "\",color:" + this.subtitleColor.name()
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getSubtitle()) + "\",color:" + this.subtitleColor.name()
.toLowerCase() + "}");
packet = this.packetTitle.getConstructor(this.packetActions, Reflection.getNMSClass("IChatBaseComponent"))
.newInstance(actions[1], serialized);
@ -258,23 +69,7 @@ public class HackTitleManager {
}
}
/**
* Broadcast the title to all players.
* @throws Exception on NMS Error
*/
public void broadcast() throws Exception {
for (Player p : Bukkit.getOnlinePlayers()) {
send(p);
}
}
/**
* Clear the title.
*
* @param player Player
* @throws Exception on NMS Error
*/
public void clearTitle(Player player) throws Exception {
@Override public void clearTitle(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
if ((getProtocolVersion(player) >= 47) && isSpigot()) {
// Send timings first
Object handle = getHandle(player);
@ -286,13 +81,7 @@ public class HackTitleManager {
}
}
/**
* Reset the title settings.
*
* @param player Player
* @throws Exception on NMS error.
*/
public void resetTitle(Player player) throws Exception {
@Override public void resetTitle(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
if ((getProtocolVersion(player) >= 47) && isSpigot()) {
// Send timings first
Object handle = getHandle(player);
@ -309,9 +98,11 @@ public class HackTitleManager {
*
* @param player Player
* @return Protocol version
* @throws Exception on NMS Error
* @throws IllegalArgumentException
* @throws ReflectiveOperationException
* @throws SecurityException
*/
private int getProtocolVersion(Player player) throws Exception {
private int getProtocolVersion(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object networkManager = getValue("networkManager", connection);
@ -336,54 +127,20 @@ public class HackTitleManager {
private Class<?> getClass(String namespace) {
try {
return Class.forName(namespace);
} catch (ClassNotFoundException ignored) {
}
} catch (ClassNotFoundException ignored) {}
return null;
}
private Field getField(String name, Class<?> clazz) throws Exception {
private Field getField(String name, Class<?> clazz) throws NoSuchFieldException, SecurityException {
return clazz.getDeclaredField(name);
}
private Object getValue(String name, Object obj) throws Exception {
private Object getValue(String name, Object obj) throws ReflectiveOperationException, SecurityException, IllegalArgumentException {
Field f = getField(name, obj.getClass());
f.setAccessible(true);
return f.get(obj);
}
private Class<?> getPrimitiveType(Class<?> clazz) {
return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES.get(clazz) : clazz;
}
private Class<?>[] toPrimitiveTypeArray(Class<?>[] classes) {
int a = classes != null ? classes.length : 0;
Class<?>[] types = new Class<?>[a];
for (int i = 0; i < a; i++) {
types[i] = getPrimitiveType(classes[i]);
}
return types;
}
private Object getHandle(Object obj) {
try {
return getMethod("getHandle", obj.getClass()).invoke(obj);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
return null;
}
}
private Method getMethod(String name, Class<?> clazz, Class<?>... paramTypes) {
Class<?>[] t = toPrimitiveTypeArray(paramTypes);
for (Method m : clazz.getMethods()) {
Class<?>[] types = toPrimitiveTypeArray(m.getParameterTypes());
if (m.getName().equals(name) && equalsTypeArray(types, t)) {
return m;
}
}
return null;
}
private Field getField(Class<?> clazz, String name) {
try {
Field field = clazz.getDeclaredField(name);
@ -405,17 +162,4 @@ public class HackTitleManager {
return null;
}
private boolean classListEqual(Class<?>[] l1, Class<?>[] l2) {
if (l1.length != l2.length) {
return false;
}
boolean equal = true;
for (int i = 0; i < l1.length; i++) {
if (l1[i] != l2[i]) {
equal = false;
break;
}
}
return equal;
}
}

View File

@ -0,0 +1,257 @@
package com.plotsquared.bukkit.titles;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public abstract class TitleManager {
private static final Map<Class<?>, Class<?>> CORRESPONDING_TYPES = new HashMap<>();
/* Title packet */
Class<?> packetTitle;
/* Title packet actions ENUM */
Class<?> packetActions;
/* Chat serializer */
Class<?> nmsChatSerializer;
Class<?> chatBaseComponent;
ChatColor titleColor = ChatColor.WHITE;
ChatColor subtitleColor = ChatColor.WHITE;
/* Title timings */
int fadeInTime = -1;
int stayTime = -1;
int fadeOutTime = -1;
boolean ticks = false;
/* Title text and color */
private String title = "";
/* Subtitle text and color */
private String subtitle = "";
/**
* Create a new 1.8 title.
*
* @param title Title text
* @param subtitle Subtitle text
* @param fadeInTime Fade in time
* @param stayTime Stay on screen time
* @param fadeOutTime Fade out time
*/
TitleManager(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) {
this.title = title;
this.subtitle = subtitle;
this.fadeInTime = fadeInTime;
this.stayTime = stayTime;
this.fadeOutTime = fadeOutTime;
loadClasses();
}
abstract void loadClasses();
/**
* Gets title text.
*
* @return Title text
*/
public final String getTitle() {
return this.title;
}
/**
* Sets the text for the title.
*
* @param title Title
*/
public final void setTitle(String title) {
this.title = title;
}
/**
* Gets the subtitle text.
*
* @return Subtitle text
*/
public final String getSubtitle() {
return this.subtitle;
}
/**
* Sets subtitle text.
*
* @param subtitle Subtitle text
*/
public final void setSubtitle(String subtitle) {
this.subtitle = subtitle;
}
/**
* Sets the title color.
*
* @param color Chat color
*/
public final void setTitleColor(ChatColor color) {
this.titleColor = color;
}
/**
* Sets the subtitle color.
*
* @param color Chat color
*/
public final void setSubtitleColor(ChatColor color) {
this.subtitleColor = color;
}
/**
* Sets title fade in time.
*
* @param time Time
*/
public final void setFadeInTime(int time) {
this.fadeInTime = time;
}
/**
* Sets title fade out time.
*
* @param time Time
*/
public final void setFadeOutTime(int time) {
this.fadeOutTime = time;
}
/**
* Sets title stay time.
*
* @param time Time
*/
public final void setStayTime(int time) {
this.stayTime = time;
}
/**
* Sets timings to ticks.
*/
public final void setTimingsToTicks() {
this.ticks = true;
}
/**
* Sets timings to seconds.
*/
public final void setTimingsToSeconds() {
this.ticks = false;
}
/**
* Sends the title to a player.
*
* @param player Player
* @throws IllegalArgumentException
* @throws ReflectiveOperationException
* @throws SecurityException
*/
public abstract void send(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException;
/**
* Broadcasts the title to all players.
*
* @throws Exception
*/
public final void broadcast() throws Exception {
for (Player player : Bukkit.getOnlinePlayers()) {
send(player);
}
}
/**
* Clears the title.
*
* @param player Player
* @throws IllegalArgumentException
* @throws ReflectiveOperationException
* @throws SecurityException
*/
public abstract void clearTitle(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException;
/**
* Resets the title settings.
*
* @param player Player
* @throws IllegalArgumentException
* @throws ReflectiveOperationException
* @throws SecurityException
*/
public abstract void resetTitle(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException;
private Class<?> getPrimitiveType(Class<?> clazz) {
if (CORRESPONDING_TYPES.containsKey(clazz)) {
return CORRESPONDING_TYPES.get(clazz);
} else {
return clazz;
}
}
private Class<?>[] toPrimitiveTypeArray(Class<?>[] classes) {
int a;
if (classes != null) {
a = classes.length;
} else {
a = 0;
}
Class<?>[] types = new Class<?>[a];
for (int i = 0; i < a; i++) {
types[i] = getPrimitiveType(classes[i]);
}
return types;
}
final Object getHandle(Object obj) {
try {
return getMethod("getHandle", obj.getClass()).invoke(obj);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
return null;
}
}
final Method getMethod(String name, Class<?> clazz, Class<?>... paramTypes) {
Class<?>[] t = toPrimitiveTypeArray(paramTypes);
for (Method m : clazz.getMethods()) {
Class<?>[] types = toPrimitiveTypeArray(m.getParameterTypes());
if (m.getName().equals(name) && equalsTypeArray(types, t)) {
return m;
}
}
return null;
}
private boolean equalsTypeArray(Class<?>[] a, Class<?>[] o) {
if (a.length != o.length) {
return false;
}
for (int i = 0; i < a.length; i++) {
if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i])) {
return false;
}
}
return true;
}
boolean classListEqual(Class<?>[] l1, Class<?>[] l2) {
if (l1.length != l2.length) {
return false;
}
boolean equal = true;
for (int i = 0; i < l1.length; i++) {
if (l1[i] != l2[i]) {
equal = false;
break;
}
}
return equal;
}
}

View File

@ -1,6 +1,7 @@
package com.plotsquared.bukkit.util;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.object.ConsolePlayer;
import com.intellectualcrafters.plot.object.PlotMessage;
import com.intellectualcrafters.plot.object.PlotPlayer;
@ -20,41 +21,41 @@ public class BukkitChatManager extends ChatManager<FancyMessage> {
}
@Override
public void color(PlotMessage m, String color) {
m.$(this).color(ChatColor.getByChar(C.color(color).substring(1)));
public void color(PlotMessage message, String color) {
message.$(this).color(ChatColor.getByChar(C.color(color).substring(1)));
}
@Override
public void tooltip(PlotMessage m, PlotMessage... tooltips) {
public void tooltip(PlotMessage message, PlotMessage... tooltips) {
List<FancyMessage> lines = new ArrayList<>();
for (PlotMessage tooltip : tooltips) {
lines.add(tooltip.$(this));
}
m.$(this).formattedTooltip(lines);
message.$(this).formattedTooltip(lines);
}
@Override
public void command(PlotMessage m, String command) {
m.$(this).command(command);
public void command(PlotMessage message, String command) {
message.$(this).command(command);
}
@Override
public void text(PlotMessage m, String text) {
m.$(this).then(ChatColor.stripColor(text));
public void text(PlotMessage message, String text) {
message.$(this).then(ChatColor.stripColor(text));
}
@Override
public void send(PlotMessage m, PlotPlayer player) {
if (ConsolePlayer.isConsole(player)) {
player.sendMessage(m.$(this).toOldMessageFormat());
public void send(PlotMessage plotMessage, PlotPlayer player) {
if (player instanceof ConsolePlayer || !Settings.Chat.INTERACTIVE) {
player.sendMessage(plotMessage.$(this).toOldMessageFormat());
} else {
m.$(this).send(((BukkitPlayer) player).player);
plotMessage.$(this).send(((BukkitPlayer) player).player);
}
}
@Override
public void suggest(PlotMessage m, String command) {
m.$(this).suggest(command);
public void suggest(PlotMessage plotMessage, String command) {
plotMessage.$(this).suggest(command);
}
}

View File

@ -4,15 +4,19 @@ import com.intellectualcrafters.plot.commands.MainCommand;
import com.intellectualcrafters.plot.object.ConsolePlayer;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.plotsquared.bukkit.commands.DebugUUID;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.command.ProxiedCommandSender;
import org.bukkit.command.RemoteConsoleCommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
public class BukkitCommand implements CommandExecutor, TabCompleter {
@ -21,41 +25,19 @@ public class BukkitCommand implements CommandExecutor, TabCompleter {
}
@Override
public boolean onCommand(final CommandSender commandSender, org.bukkit.command.Command command, final String commandLabel, String[] args) {
public boolean onCommand(CommandSender commandSender, Command command, String commandLabel, String[] args) {
if (commandSender instanceof Player) {
return MainCommand.onCommand(BukkitUtil.getPlayer((Player) commandSender), args);
}
if (commandSender == null || commandSender.getClass() == Bukkit.getConsoleSender().getClass()) {
if (commandSender instanceof ConsoleCommandSender || commandSender instanceof ProxiedCommandSender
|| commandSender instanceof RemoteConsoleCommandSender) {
return MainCommand.onCommand(ConsolePlayer.getConsole(), args);
}
@SuppressWarnings("deprecation")
ConsolePlayer sender = new ConsolePlayer() {
@Override
public void sendMessage(String message) {
commandSender.sendMessage(commandLabel);
}
@Override
public boolean hasPermission(String permission) {
return commandSender.hasPermission(commandLabel);
}
@Override
public String getName() {
if (commandSender.getName().equals("CONSOLE")) {
return "*";
}
return commandSender.getName();
}
};
sender.teleport(ConsolePlayer.getConsole().getLocationFull());
boolean result = MainCommand.onCommand(sender, args);
ConsolePlayer.getConsole().teleport(sender.getLocationFull());
return result;
return false;
}
@Override
public List<String> onTabComplete(CommandSender commandSender, org.bukkit.command.Command command, String s, String[] args) {
public List<String> onTabComplete(CommandSender commandSender, Command command, String s, String[] args) {
if (!(commandSender instanceof Player)) {
return null;
}
@ -71,6 +53,6 @@ public class BukkitCommand implements CommandExecutor, TabCompleter {
for (Object o : objects) {
result.add(o.toString());
}
return result;
return result.isEmpty() ? null : result;
}
}

View File

@ -15,16 +15,6 @@ public class BukkitEconHandler extends EconHandler {
private Economy econ;
private Permission perms;
public Economy getEconomy() {
init();
return this.econ;
}
public Permission getPermissions() {
init();
return this.perms;
}
public boolean init() {
if (this.econ == null || this.perms == null) {
setupPermissions();
@ -34,8 +24,7 @@ public class BukkitEconHandler extends EconHandler {
}
private boolean setupPermissions() {
RegisteredServiceProvider<Permission> permissionProvider =
Bukkit.getServer().getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class);
RegisteredServiceProvider<Permission> permissionProvider = Bukkit.getServer().getServicesManager().getRegistration(Permission.class);
if (permissionProvider != null) {
this.perms = permissionProvider.getProvider();
}
@ -43,8 +32,10 @@ public class BukkitEconHandler extends EconHandler {
}
private boolean setupEconomy() {
RegisteredServiceProvider<Economy> economyProvider =
Bukkit.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
if (Bukkit.getServer().getPluginManager().getPlugin("Vault") == null) {
return false;
}
RegisteredServiceProvider<Economy> economyProvider = Bukkit.getServer().getServicesManager().getRegistration(Economy.class);
if (economyProvider != null) {
this.econ = economyProvider.getProvider();
}
@ -79,9 +70,18 @@ public class BukkitEconHandler extends EconHandler {
public boolean hasPermission(String world, String player, String perm) {
return this.perms.playerHas(world, Bukkit.getOfflinePlayer(player), perm);
}
@Override
public double getBalance(PlotPlayer player) {
return this.econ.getBalance(player.getName());
}
public void setPermission(String world, String player, String perm, boolean value) {
if (value) {
this.perms.playerAdd(world, player, perm);
} else {
this.perms.playerRemove(world, player, perm);
}
}
}

View File

@ -18,6 +18,7 @@ import com.plotsquared.bukkit.events.PlayerPlotHelperEvent;
import com.plotsquared.bukkit.events.PlayerPlotTrustedEvent;
import com.plotsquared.bukkit.events.PlayerTeleportToPlotEvent;
import com.plotsquared.bukkit.events.PlotClearEvent;
import com.plotsquared.bukkit.events.PlotComponentSetEvent;
import com.plotsquared.bukkit.events.PlotDeleteEvent;
import com.plotsquared.bukkit.events.PlotFlagAddEvent;
import com.plotsquared.bukkit.events.PlotFlagRemoveEvent;
@ -57,6 +58,11 @@ public class BukkitEventUtil extends EventUtil {
return callEvent(new PlayerTeleportToPlotEvent(getPlayer(player), from, plot));
}
@Override
public boolean callComponentSet(Plot plot, String component) {
return callEvent(new PlotComponentSetEvent(plot, component));
}
@Override
public boolean callClear(Plot plot) {
return callEvent(new PlotClearEvent(plot));
@ -73,7 +79,7 @@ public class BukkitEventUtil extends EventUtil {
}
@Override
public boolean callFlagRemove(Flag flag, Plot plot) {
public boolean callFlagRemove(Flag<?> flag, Plot plot, Object value) {
return callEvent(new PlotFlagRemoveEvent(flag, plot));
}
@ -104,16 +110,16 @@ public class BukkitEventUtil extends EventUtil {
@Override
public void callTrusted(PlotPlayer initiator, Plot plot, UUID player, boolean added) {
callEvent(new PlayerPlotHelperEvent(getPlayer(initiator), plot, player, added));
}
@Override
public void callMember(PlotPlayer initiator, Plot plot, UUID player, boolean added) {
callEvent(new PlayerPlotTrustedEvent(getPlayer(initiator), plot, player, added));
}
@Override
public boolean callFlagRemove(Flag flag, PlotCluster cluster) {
public void callMember(PlotPlayer initiator, Plot plot, UUID player, boolean added) {
callEvent(new PlayerPlotHelperEvent(getPlayer(initiator), plot, player, added));
}
@Override
public boolean callFlagRemove(Flag flag, Object object, PlotCluster cluster) {
return callEvent(new ClusterFlagRemoveEvent(flag, cluster));
}

View File

@ -2,7 +2,6 @@ package com.plotsquared.bukkit.util;
import com.intellectualcrafters.plot.generator.HybridUtils;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.PlotAnalysis;
import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.object.RegionWrapper;
import com.intellectualcrafters.plot.object.RunnableVal;
@ -10,11 +9,13 @@ import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.MathMan;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.block.GlobalBlockQueue;
import com.intellectualcrafters.plot.util.block.LocalBlockQueue;
import com.intellectualcrafters.plot.util.expiry.PlotAnalysis;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.block.Block;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.generator.ChunkGenerator.BiomeGrid;
import org.bukkit.material.Directional;
@ -42,6 +43,7 @@ public class BukkitHybridUtils extends HybridUtils {
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
final LocalBlockQueue queue = GlobalBlockQueue.IMP.getNewQueue(world, false);
final World worldObj = Bukkit.getWorld(world);
final ChunkGenerator gen = worldObj.getGenerator();
if (gen == null) {
@ -255,10 +257,10 @@ public class BukkitHybridUtils extends HybridUtils {
for (int z = minZ; z <= maxZ; z++) {
int zz = cbz + z;
for (int y = 0; y < 256; y++) {
Block block = worldObj.getBlockAt(xx, y, zz);
PlotBlock block = queue.getBlock(xx, y, zz);
int xr = xb + x;
int zr = zb + z;
newBlocks[y][xr][zr] = (short) block.getTypeId();
newBlocks[y][xr][zr] = block.id;
}
}
}
@ -273,50 +275,4 @@ public class BukkitHybridUtils extends HybridUtils {
}
});
}
@Override
public int checkModified(String worldname, int x1, int x2, int y1, int y2, int z1, int z2,
PlotBlock[] blocks) {
World world = BukkitUtil.getWorld(worldname);
int count = 0;
for (int y = y1; y <= y2; y++) {
for (int x = x1; x <= x2; x++) {
for (int z = z1; z <= z2; z++) {
Block block = world.getBlockAt(x, y, z);
int id = block.getTypeId();
boolean same = false;
for (PlotBlock p : blocks) {
if (id == p.id) {
same = true;
break;
}
}
if (!same) {
count++;
}
}
}
}
return count;
}
@Override
public int get_ey(String worldname, int sx, int ex, int sz, int ez, int sy) {
World world = BukkitUtil.getWorld(worldname);
int maxY = world.getMaxHeight();
int ey = sy;
for (int x = sx; x <= ex; x++) {
for (int z = sz; z <= ez; z++) {
for (int y = sy; y < maxY; y++) {
if (y > ey) {
Block block = world.getBlockAt(x, y, z);
if (!block.getType().equals(Material.AIR)) {
ey = y;
}
}
}
}
}
return ey;
}
}

View File

@ -1,50 +0,0 @@
package com.plotsquared.bukkit.util;
import com.intellectualcrafters.plot.object.PlotMessage;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.ChatManager;
import org.bukkit.ChatColor;
import java.util.ArrayList;
import java.util.List;
public class BukkitPlainChatManager extends ChatManager<List<StringBuilder>> {
@Override
public List<StringBuilder> builder() {
return new ArrayList<>();
}
@Override
public void color(PlotMessage m, String color) {
List<StringBuilder> parts = m.$(this);
parts.get(parts.size() - 1).insert(0, color);
}
@Override
public void tooltip(PlotMessage m, PlotMessage... tooltips) {
}
@Override
public void command(PlotMessage m, String command) {
}
@Override
public void text(PlotMessage m, String text) {
m.$(this).add(new StringBuilder(ChatColor.stripColor(text)));
}
@Override
public void send(PlotMessage m, PlotPlayer player) {
StringBuilder built = new StringBuilder();
for (StringBuilder sb : m.$(this)) {
built.append(sb);
}
player.sendMessage(built.toString());
}
@Override
public void suggest(PlotMessage m, String command) {
}
}

View File

@ -1,23 +1,3 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.util;
import com.intellectualcrafters.jnbt.ByteArrayTag;
@ -34,6 +14,7 @@ import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.SchematicHandler;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.block.LocalBlockQueue;
import com.plotsquared.bukkit.object.schematic.StateWrapper;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
@ -46,7 +27,6 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
@ -65,9 +45,9 @@ public class BukkitSchematicHandler extends SchematicHandler {
final Location bot = corners[0];
Location top = corners[1];
final int width = (top.getX() - bot.getX()) + 1;
int height = (top.getY() - bot.getY()) + 1;
final int length = (top.getZ() - bot.getZ()) + 1;
final int width = top.getX() - bot.getX() + 1;
int height = top.getY() - bot.getY() + 1;
final int length = top.getZ() - bot.getZ() + 1;
// Main Schematic tag
final HashMap<String, Tag> schematic = new HashMap<>();
schematic.put("Width", new ShortTag("Width", (short) width));
@ -134,7 +114,7 @@ public class BukkitSchematicHandler extends SchematicHandler {
@Override
public void run() {
long start = System.currentTimeMillis();
while (!chunks.isEmpty() && ((System.currentTimeMillis() - start) < 20)) {
while (!chunks.isEmpty() && System.currentTimeMillis() - start < 20) {
// save schematics
ChunkLoc chunk = chunks.remove(0);
Chunk bc = worldObj.getChunkAt(chunk.x, chunk.z);
@ -165,7 +145,7 @@ public class BukkitSchematicHandler extends SchematicHandler {
int i1 = ry * width * length;
for (int z = zzb; z <= zzt; z++) {
int rz = z - bz;
int i2 = i1 + (rz * width);
int i2 = i1 + rz * width;
for (int x = xxb; x <= xxt; x++) {
int rx = x - bx;
int index = i2 + rx;
@ -239,9 +219,8 @@ public class BukkitSchematicHandler extends SchematicHandler {
case 189:
case 190:
case 191:
case 192: {
case 192:
break;
}
case 54:
case 130:
case 142:
@ -276,17 +255,14 @@ public class BukkitSchematicHandler extends SchematicHandler {
case 29:
case 33:
case 151:
case 178: {
case 178:
// TODO implement fully
BlockState state = block.getState();
if (state != null) {
StateWrapper wrapper = new StateWrapper(state);
CompoundTag rawTag = wrapper.getTag();
if (rawTag != null) {
Map<String, Tag> values = new HashMap<>();
for (Entry<String, Tag> entry : rawTag.getValue().entrySet()) {
values.put(entry.getKey(), entry.getValue());
}
Map<String, Tag> values = new HashMap<>(rawTag.getValue());
values.put("id", new StringTag("id", wrapper.getId()));
values.put("x", new IntTag("x", x));
values.put("y", new IntTag("y", y));
@ -295,10 +271,8 @@ public class BukkitSchematicHandler extends SchematicHandler {
tileEntities.add(tileEntityTag);
}
}
}
default: {
default:
blockData[index] = block.getData();
}
}
// For optimization reasons, we are not supporting custom data types
// Especially since the most likely reason beyond this range is modded servers in which the blocks
@ -330,7 +304,7 @@ public class BukkitSchematicHandler extends SchematicHandler {
}
@Override
public void restoreTag(CompoundTag ct, short x, short y, short z, Schematic schem) {
new StateWrapper(ct).restoreTag(x, y, z, schem);
public boolean restoreTile(LocalBlockQueue queue, CompoundTag ct, int x, int y, int z) {
return new StateWrapper(ct).restoreTag(queue.getWorld(), x, y, z);
}
}

View File

@ -31,19 +31,23 @@ public class BukkitSetupUtils extends SetupUtils {
}
String testWorld = "CheckingPlotSquaredGenerator";
for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
if (plugin.isEnabled()) {
ChunkGenerator generator = plugin.getDefaultWorldGenerator(testWorld, "");
if (generator != null) {
PS.get().removePlotAreas(testWorld);
String name = plugin.getDescription().getName();
GeneratorWrapper<?> wrapped;
if (generator instanceof GeneratorWrapper<?>) {
wrapped = (GeneratorWrapper<?>) generator;
} else {
wrapped = new BukkitPlotGenerator(testWorld, generator);
try {
if (plugin.isEnabled()) {
ChunkGenerator generator = plugin.getDefaultWorldGenerator(testWorld, "");
if (generator != null) {
PS.get().removePlotAreas(testWorld);
String name = plugin.getDescription().getName();
GeneratorWrapper<?> wrapped;
if (generator instanceof GeneratorWrapper<?>) {
wrapped = (GeneratorWrapper<?>) generator;
} else {
wrapped = new BukkitPlotGenerator(testWorld, generator);
}
SetupUtils.generators.put(name, wrapped);
}
SetupUtils.generators.put(name, wrapped);
}
} catch (Throwable e) { // Recover from third party generator error
e.printStackTrace();
}
}
}
@ -55,15 +59,15 @@ public class BukkitSetupUtils extends SetupUtils {
String world = object.world;
int type = object.type;
String worldPath = "worlds." + object.world;
if (!PS.get().config.contains(worldPath)) {
PS.get().config.createSection(worldPath);
if (!PS.get().worlds.contains(worldPath)) {
PS.get().worlds.createSection(worldPath);
}
ConfigurationSection worldSection = PS.get().config.getConfigurationSection(worldPath);
ConfigurationSection worldSection = PS.get().worlds.getConfigurationSection(worldPath);
switch (type) {
case 2: {
if (object.id != null) {
String areaname = object.id + "-" + object.min + "-" + object.max;
String areaPath = "areas." + areaname;
String areaName = object.id + "-" + object.min + "-" + object.max;
String areaPath = "areas." + areaName;
if (!worldSection.contains(areaPath)) {
worldSection.createSection(areaPath);
}
@ -75,7 +79,7 @@ public class BukkitSetupUtils extends SetupUtils {
options.put("generator.type", object.type);
options.put("generator.terrain", object.terrain);
options.put("generator.plugin", object.plotManager);
if ((object.setupGenerator != null) && !object.setupGenerator.equals(object.plotManager)) {
if (object.setupGenerator != null && !object.setupGenerator.equals(object.plotManager)) {
options.put("generator.init", object.setupGenerator);
}
for (Entry<String, Object> entry : options.entrySet()) {
@ -91,42 +95,40 @@ public class BukkitSetupUtils extends SetupUtils {
}
}
}
GeneratorWrapper<?> gen = generators.get(object.setupGenerator);
if ((gen != null) && gen.isFull()) {
GeneratorWrapper<?> gen = SetupUtils.generators.get(object.setupGenerator);
if (gen != null && gen.isFull()) {
object.setupGenerator = null;
}
break;
}
case 1: {
case 1:
for (ConfigurationNode step : steps) {
worldSection.set(step.getConstant(), step.getValue());
}
PS.get().config.set("worlds." + world + "." + "generator.type", object.type);
PS.get().config.set("worlds." + world + "." + "generator.terrain", object.terrain);
PS.get().config.set("worlds." + world + "." + "generator.plugin", object.plotManager);
if ((object.setupGenerator != null) && !object.setupGenerator.equals(object.plotManager)) {
PS.get().config.set("worlds." + world + "." + "generator.init", object.setupGenerator);
PS.get().worlds.set("worlds." + world + ".generator.type", object.type);
PS.get().worlds.set("worlds." + world + ".generator.terrain", object.terrain);
PS.get().worlds.set("worlds." + world + ".generator.plugin", object.plotManager);
if (object.setupGenerator != null && !object.setupGenerator.equals(object.plotManager)) {
PS.get().worlds.set("worlds." + world + ".generator.init", object.setupGenerator);
}
GeneratorWrapper<?> gen = generators.get(object.setupGenerator);
if ((gen != null) && gen.isFull()) {
GeneratorWrapper<?> gen = SetupUtils.generators.get(object.setupGenerator);
if (gen != null && gen.isFull()) {
object.setupGenerator = null;
}
break;
}
case 0: {
case 0:
for (ConfigurationNode step : steps) {
worldSection.set(step.getConstant(), step.getValue());
}
break;
}
}
try {
PS.get().config.save(PS.get().configFile);
PS.get().worlds.save(PS.get().worldsFile);
} catch (IOException e) {
e.printStackTrace();
}
if (object.setupGenerator != null) {
if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) && Bukkit.getPluginManager().getPlugin("Multiverse-Core")
if (Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null && Bukkit.getPluginManager().getPlugin("Multiverse-Core")
.isEnabled()) {
Bukkit.getServer()
.dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv create " + world + " normal -g " + object.setupGenerator);
@ -135,7 +137,7 @@ public class BukkitSetupUtils extends SetupUtils {
return world;
}
}
if ((Bukkit.getPluginManager().getPlugin("MultiWorld") != null) && Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled()) {
if (Bukkit.getPluginManager().getPlugin("MultiWorld") != null && Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled()) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw create " + world + " plugin:" + object.setupGenerator);
setGenerator(world, object.setupGenerator);
if (Bukkit.getWorld(world) != null) {
@ -148,14 +150,14 @@ public class BukkitSetupUtils extends SetupUtils {
Bukkit.createWorld(wc);
setGenerator(world, object.setupGenerator);
} else {
if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) && Bukkit.getPluginManager().getPlugin("Multiverse-Core")
if (Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null && Bukkit.getPluginManager().getPlugin("Multiverse-Core")
.isEnabled()) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv create " + world + " normal");
if (Bukkit.getWorld(world) != null) {
return world;
}
}
if ((Bukkit.getPluginManager().getPlugin("MultiWorld") != null) && Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled()) {
if (Bukkit.getPluginManager().getPlugin("MultiWorld") != null && Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled()) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw create " + world);
if (Bukkit.getWorld(world) != null) {
return world;
@ -181,11 +183,11 @@ public class BukkitSetupUtils extends SetupUtils {
}
@Override
public String getGenerator(PlotArea plotworld) {
public String getGenerator(PlotArea plotArea) {
if (SetupUtils.generators.isEmpty()) {
updateGenerators();
}
World world = Bukkit.getWorld(plotworld.worldname);
World world = Bukkit.getWorld(plotArea.worldname);
if (world == null) {
return null;
}
@ -193,7 +195,7 @@ public class BukkitSetupUtils extends SetupUtils {
if (!(generator instanceof BukkitPlotGenerator)) {
return null;
}
for (Entry<String, GeneratorWrapper<?>> entry : generators.entrySet()) {
for (Entry<String, GeneratorWrapper<?>> entry : SetupUtils.generators.entrySet()) {
GeneratorWrapper<?> current = entry.getValue();
if (current.equals(generator)) {
return entry.getKey();

View File

@ -6,35 +6,41 @@ import org.bukkit.Bukkit;
public class BukkitTaskManager extends TaskManager {
private final BukkitMain bukkitMain;
public BukkitTaskManager(BukkitMain bukkitMain) {
this.bukkitMain = bukkitMain;
}
@Override
public int taskRepeat(Runnable r, int interval) {
return BukkitMain.THIS.getServer().getScheduler().scheduleSyncRepeatingTask(BukkitMain.THIS, r, interval, interval);
public int taskRepeat(Runnable runnable, int interval) {
return this.bukkitMain.getServer().getScheduler().scheduleSyncRepeatingTask(this.bukkitMain, runnable, interval, interval);
}
@SuppressWarnings("deprecation")
@Override
public int taskRepeatAsync(Runnable r, int interval) {
return BukkitMain.THIS.getServer().getScheduler().scheduleAsyncRepeatingTask(BukkitMain.THIS, r, interval, interval);
public int taskRepeatAsync(Runnable runnable, int interval) {
return this.bukkitMain.getServer().getScheduler().scheduleAsyncRepeatingTask(this.bukkitMain, runnable, interval, interval);
}
@Override
public void taskAsync(Runnable r) {
BukkitMain.THIS.getServer().getScheduler().runTaskAsynchronously(BukkitMain.THIS, r).getTaskId();
public void taskAsync(Runnable runnable) {
this.bukkitMain.getServer().getScheduler().runTaskAsynchronously(this.bukkitMain, runnable).getTaskId();
}
@Override
public void task(Runnable r) {
BukkitMain.THIS.getServer().getScheduler().runTask(BukkitMain.THIS, r).getTaskId();
public void task(Runnable runnable) {
this.bukkitMain.getServer().getScheduler().runTask(this.bukkitMain, runnable).getTaskId();
}
@Override
public void taskLater(Runnable r, int delay) {
BukkitMain.THIS.getServer().getScheduler().runTaskLater(BukkitMain.THIS, r, delay).getTaskId();
public void taskLater(Runnable runnable, int delay) {
this.bukkitMain.getServer().getScheduler().runTaskLater(this.bukkitMain, runnable, delay).getTaskId();
}
@Override
public void taskLaterAsync(Runnable r, int delay) {
BukkitMain.THIS.getServer().getScheduler().runTaskLaterAsynchronously(BukkitMain.THIS, r, delay);
public void taskLaterAsync(Runnable runnable, int delay) {
this.bukkitMain.getServer().getScheduler().runTaskLaterAsynchronously(this.bukkitMain, runnable, delay);
}
@Override

View File

@ -8,10 +8,11 @@ import com.intellectualcrafters.plot.object.schematic.PlotItem;
import com.intellectualcrafters.plot.util.MathMan;
import com.intellectualcrafters.plot.util.StringComparison;
import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.util.WorldUtil;
import com.plotsquared.bukkit.object.BukkitPlayer;
import java.util.Arrays;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
@ -32,9 +33,6 @@ import org.bukkit.material.Tree;
import org.bukkit.material.WoodenStep;
import org.bukkit.material.Wool;
import java.util.Arrays;
import java.util.List;
public class BukkitUtil extends WorldUtil {
private static String lastString = null;
@ -43,7 +41,7 @@ public class BukkitUtil extends WorldUtil {
private static Player lastPlayer = null;
private static PlotPlayer lastPlotPlayer = null;
public static void removePlayer(String plr) {
public static void removePlayer(String player) {
lastPlayer = null;
lastPlotPlayer = null;
}
@ -62,9 +60,9 @@ public class BukkitUtil extends WorldUtil {
return lastPlotPlayer;
}
String name = player.getName();
PlotPlayer pp = UUIDHandler.getPlayer(name);
if (pp != null) {
return pp;
PlotPlayer plotPlayer = UUIDHandler.getPlayer(name);
if (plotPlayer != null) {
return plotPlayer;
}
lastPlotPlayer = new BukkitPlayer(player);
UUIDHandler.getPlayers().put(name, lastPlotPlayer);
@ -97,25 +95,25 @@ public class BukkitUtil extends WorldUtil {
return entity.getWorld().getName();
}
public static List<Entity> getEntities(String worldname) {
return getWorld(worldname).getEntities();
public static List<Entity> getEntities(String worldName) {
return getWorld(worldName).getEntities();
}
public static Location getLocation(Entity entity) {
org.bukkit.Location loc = entity.getLocation();
String world = loc.getWorld().getName();
return new Location(world, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
org.bukkit.Location location = entity.getLocation();
String world = location.getWorld().getName();
return new Location(world, location.getBlockX(), location.getBlockY(), location.getBlockZ());
}
public static Location getLocationFull(Entity entity) {
org.bukkit.Location loc = entity.getLocation();
return new Location(loc.getWorld().getName(), MathMan.roundInt(loc.getX()), MathMan.roundInt(loc.getY()), MathMan.roundInt(loc.getZ()),
loc.getYaw(), loc.getPitch());
org.bukkit.Location location = entity.getLocation();
return new Location(location.getWorld().getName(), MathMan.roundInt(location.getX()), MathMan.roundInt(location.getY()), MathMan.roundInt(location.getZ()),
location.getYaw(), location.getPitch());
}
@Override
public boolean isWorld(String world) {
return getWorld(world) != null;
public boolean isWorld(String worldName) {
return getWorld(worldName) != null;
}
@Override
@ -124,8 +122,8 @@ public class BukkitUtil extends WorldUtil {
}
@Override
public void setSign(String worldname, int x, int y, int z, String[] lines) {
World world = getWorld(worldname);
public void setSign(String worldName, int x, int y, int z, String[] lines) {
World world = getWorld(worldName);
Block block = world.getBlockAt(x, y, z);
// block.setType(Material.AIR);
block.setTypeIdAndData(Material.WALL_SIGN.getId(), (byte) 2, false);
@ -136,12 +134,6 @@ public class BukkitUtil extends WorldUtil {
sign.setLine(i, lines[i]);
}
sign.update(true);
TaskManager.runTaskLater(new Runnable() {
@Override
public void run() {
sign.update(true);
}
}, 20);
}
}
@ -157,6 +149,11 @@ public class BukkitUtil extends WorldUtil {
return null;
}
@Override
public Location getSpawn(PlotPlayer player) {
return getLocation(((BukkitPlayer) player).player.getBedSpawnLocation());
}
@Override
public Location getSpawn(String world) {
org.bukkit.Location temp = getWorld(world).getSpawnLocation();
@ -172,8 +169,8 @@ public class BukkitUtil extends WorldUtil {
}
@Override
public void saveWorld(String worldname) {
World world = getWorld(worldname);
public void saveWorld(String worldName) {
World world = getWorld(worldName);
if (world != null) {
world.save();
}
@ -181,15 +178,22 @@ public class BukkitUtil extends WorldUtil {
@Override
public int getHighestBlock(String world, int x, int z) {
return getWorld(world).getHighestBlockAt(x, z).getY();
World bukkitWorld = getWorld(world);
for (int y = bukkitWorld.getMaxHeight() - 1; y > 0; y--) {
Block block = bukkitWorld.getBlockAt(x, y, z);
if (block != null && block.getType().isSolid()) {
return y+1;
}
}
return 0;
}
@Override
public int getBiomeFromString(String biomeStr) {
public int getBiomeFromString(String biomeString) {
try {
Biome biome = Biome.valueOf(biomeStr.toUpperCase());
Biome biome = Biome.valueOf(biomeString.toUpperCase());
return Arrays.asList(Biome.values()).indexOf(biome);
} catch (IllegalArgumentException e) {
} catch (IllegalArgumentException ignored) {
return -1;
}
}
@ -247,7 +251,7 @@ public class BukkitUtil extends WorldUtil {
}
}
return false;
} catch (Exception e) {
} catch (Exception ignored) {
return false;
}
}
@ -256,7 +260,7 @@ public class BukkitUtil extends WorldUtil {
public String getClosestMatchingName(PlotBlock block) {
try {
return Material.getMaterial(block.id).name();
} catch (Exception e) {
} catch (Exception ignored) {
return null;
}
}
@ -265,10 +269,8 @@ public class BukkitUtil extends WorldUtil {
public StringComparison<PlotBlock>.ComparisonResult getClosestBlock(String name) {
try {
Material material = Material.valueOf(name.toUpperCase());
return new StringComparison<PlotBlock>().new ComparisonResult(0, new PlotBlock((short) material.getId(), (byte) 0));
} catch (IllegalArgumentException e) {
//ignored
}
return new StringComparison<PlotBlock>().new ComparisonResult(0, PlotBlock.get((short) material.getId(), (byte) 0));
} catch (IllegalArgumentException ignored) {}
try {
byte data;
String[] split = name.split(":");
@ -288,20 +290,18 @@ public class BukkitUtil extends WorldUtil {
match = comparison.match;
id = (short) comparison.best.getId();
}
PlotBlock block = new PlotBlock(id, data);
PlotBlock block = PlotBlock.get(id, data);
StringComparison<PlotBlock> outer = new StringComparison<>();
return outer.new ComparisonResult(match, block);
} catch (NumberFormatException e) {
//ignored
}
} catch (NumberFormatException ignored) {}
return null;
}
@Override
public void setBiomes(String worldName, RegionWrapper region, String biomeStr) {
public void setBiomes(String worldName, RegionWrapper region, String biomeString) {
World world = getWorld(worldName);
Biome biome = Biome.valueOf(biomeStr.toUpperCase());
Biome biome = Biome.valueOf(biomeString.toUpperCase());
for (int x = region.minX; x <= region.maxX; x++) {
for (int z = region.minZ; z <= region.maxZ; z++) {
world.setBiome(x, z, biome);
@ -316,7 +316,7 @@ public class BukkitUtil extends WorldUtil {
if (block == null) {
return PlotBlock.EVERYTHING;
}
return new PlotBlock((short) block.getTypeId(), block.getData());
return PlotBlock.get((short) block.getTypeId(), block.getData());
}
@Override

View File

@ -0,0 +1,14 @@
package com.plotsquared.bukkit.util;
public class BukkitVersion {
public static int[] v1_11_0 = {1, 11, 0};
public static int[] v1_10_2 = {1, 10, 2};
public static int[] v1_10_0 = {1, 10, 0};
public static int[] v1_9_4 = {1, 9, 4};
public static int[] v1_9_0 = {1, 9, 0};
public static int[] v1_8_3 = {1, 8, 3};
public static int[] v1_8_0 = {1, 8, 0};
public static int[] v1_7_6 = {1, 7, 6};
public static int[] v1_7_0 = {1, 7, 0};
public static int[] v1_6_0 = {1, 6, 0};
}

View File

@ -1,26 +1,5 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.util;
import com.intellectualcrafters.plot.PS;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
@ -29,75 +8,42 @@ import org.bukkit.scheduler.BukkitTask;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Level;
import java.util.zip.GZIPOutputStream;
public class Metrics {
/**
* The current revision number
*/
private final static int REVISION = 7;
/**
* The base url of the metrics domain
*/
/** The current revision number. */
private static final int REVISION = 7;
/** The base url of the metrics domain.*/
private static final String BASE_URL = "http://report.mcstats.org";
/**
* The url used to report a server's status
*/
/** The url used to report a server's status. */
private static final String REPORT_URL = "/plugin/%s";
/**
* Interval of time to ping (in minutes)
*/
/** Interval of time to ping (in minutes). */
private static final int PING_INTERVAL = 15;
/**
* The plugin this metrics submits for
*/
/** The plugin this metrics submits for. */
private final Plugin plugin;
/**
* All of the custom graphs to submit to metrics
*/
private final Set<Graph> graphs = Collections.synchronizedSet(new HashSet<Graph>());
/**
* Unique server id
*/
/** Unique server id. */
private final String guid;
/**
* Debug mode
*/
private final boolean debug;
/**
* The scheduled task
*/
/** The scheduled task. */
private volatile BukkitTask task = null;
public Metrics(Plugin plugin) {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null");
}
this.plugin = plugin;
this.guid = UUID.randomUUID().toString();
this.debug = false;
}
/**
* GZip compress a string of bytes
* GZip compress a string of bytes.
*
* @param input
*
@ -115,8 +61,7 @@ public class Metrics {
if (gzos != null) {
try {
gzos.close();
} catch (IOException ignore) {
}
} catch (IOException ignore) {}
}
}
return baos.toByteArray();
@ -129,7 +74,6 @@ public class Metrics {
* @param key
* @param value
*
* @throws UnsupportedEncodingException
*/
private static void appendJSONPair(StringBuilder json, String key, String value) {
boolean isValueNumeric = false;
@ -138,7 +82,7 @@ public class Metrics {
Double.parseDouble(value);
isValueNumeric = true;
}
} catch (NumberFormatException e) {
} catch (NumberFormatException ignored) {
isValueNumeric = false;
}
if (json.charAt(json.length() - 1) != '{') {
@ -208,38 +152,6 @@ public class Metrics {
return URLEncoder.encode(text, "UTF-8");
}
/**
* Construct and create a Graph that can be used to separate specific plotters to their own graphs on the metrics
* website. Plotters can be added to the graph object returned.
*
* @param name The name of the graph
*
* @return Graph object created. Will never return NULL under normal circumstances unless bad parameters are given
*/
public Graph createGraph(String name) {
if (name == null) {
throw new IllegalArgumentException("Graph name cannot be null");
}
// Construct the graph object
Graph graph = new Graph(name);
// Now we can add our graph
this.graphs.add(graph);
// and return back
return graph;
}
/**
* Add a Graph object to BukkitMetrics that represents data for the plugin that should be sent to the backend
*
* @param graph The name of the graph
*/
public void addGraph(Graph graph) {
if (graph == null) {
throw new IllegalArgumentException("Graph cannot be null");
}
this.graphs.add(graph);
}
/**
* Start measuring statistics. This will immediately create an async repeating task as the plugin and send the
* initial data to the metrics backend, and then after that it will post in increments of PING_INTERVAL * 1200
@ -266,57 +178,12 @@ public class Metrics {
this.firstPost = false;
} catch (IOException e) {
e.printStackTrace();
if (Metrics.this.debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage());
}
}
}
}, 0, PING_INTERVAL * 1200);
return true;
}
/**
* Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task.
*
* @throws java.io.IOException
*/
public void enable() {
// Enable Task, if it is not running
if (this.task == null) {
start();
}
}
/**
* Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task.
*
*/
public void disable() {
// Disable Task, if it is running
if (this.task != null) {
this.task.cancel();
this.task = null;
}
}
/**
* Gets the File object of the config file that should be used to store
* data such as the GUID and opt-out status.
*
* @return the File object for the config file
*/
public File getConfigFile() {
// I believe the easiest way to get the base folder (e.g craftbukkit set
// via -P) for plugins to use
// is to abuse the plugin object we already have
// plugin.getDataFolder() => base/plugins/PluginA/
// pluginsFolder => base/plugins/
// The base is not necessarily relative to the startup directory.
File pluginsFolder = this.plugin.getDataFolder().getParentFile();
// return => base/plugins/PluginMetrics/config.yml
return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml");
}
/**
* Generic method that posts a plugin to the metrics website.
*/
@ -342,7 +209,7 @@ public class Metrics {
// Construct the post data
StringBuilder json = new StringBuilder(1024);
json.append('{');
// The plugin's description file containg all of the plugin data such as name, version, author, etc
// The plugin's description file containing all of the plugin data such as name, version, author, etc
appendJSONPair(json, "guid", this.guid);
appendJSONPair(json, "plugin_version", pluginVersion);
appendJSONPair(json, "server_version", serverVersion);
@ -367,46 +234,12 @@ public class Metrics {
if (isPing) {
appendJSONPair(json, "ping", "1");
}
if (!this.graphs.isEmpty()) {
synchronized (this.graphs) {
json.append(',');
json.append('"');
json.append("graphs");
json.append('"');
json.append(':');
json.append('{');
boolean firstGraph = true;
for (Graph graph : this.graphs) {
StringBuilder graphJson = new StringBuilder();
graphJson.append('{');
for (Plotter plotter : graph.getPlotters()) {
appendJSONPair(graphJson, plotter.getColumnName(), Integer.toString(plotter.getValue()));
}
graphJson.append('}');
if (!firstGraph) {
json.append(',');
}
json.append(escapeJSON(graph.getName()));
json.append(':');
json.append(graphJson);
firstGraph = false;
}
json.append('}');
}
}
// close json
json.append('}');
// Create the url
URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName)));
// Connect to the website
URLConnection connection;
// Mineshafter creates a socks proxy, so we can safely bypass it
// It does not reroute POST requests so we need to go around it
if (isMineshafterPresent()) {
connection = url.openConnection(Proxy.NO_PROXY);
} else {
connection = url.openConnection();
}
URLConnection connection = url.openConnection();
byte[] uncompressed = json.toString().getBytes();
byte[] compressed = gzip(json.toString());
// Headers
@ -417,9 +250,6 @@ public class Metrics {
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.setDoOutput(true);
if (this.debug) {
PS.debug("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" + compressed.length);
}
try {
try (OutputStream os = connection.getOutputStream()) {
os.write(compressed);
@ -428,9 +258,6 @@ public class Metrics {
String response;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
response = reader.readLine();
if (this.debug) {
PS.debug("[Metrics] Response for " + pluginName + ": " + response);
}
}
if (response == null || response.startsWith("ERR") || response.startsWith("7")) {
if (response == null) {
@ -439,177 +266,7 @@ public class Metrics {
response = response.substring(response.startsWith("7,") ? 2 : 1);
}
throw new IOException(response);
} else {
// Is this the first update this hour?
if ("1".equals(response) || response.contains("This is your first update this hour")) {
synchronized (this.graphs) {
for (Graph graph : this.graphs) {
for (Plotter plotter : graph.getPlotters()) {
plotter.reset();
}
}
}
}
}
} catch (Exception e) {
if (this.debug) {
e.printStackTrace();
}
}
}
/**
* Check if mineshafter is present. If it is, we need to bypass it to send POST requests
*
* @return true if mineshafter is installed on the server
*/
private boolean isMineshafterPresent() {
try {
Class.forName("mineshafter.MineServer");
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
/**
* Represents a custom graph on the website
*/
public static class Graph {
/**
* The graph's name, alphanumeric and spaces only :) If it does not comply to the above when submitted, it is
* rejected
*/
private final String name;
/**
* The set of plotters that are contained within this graph
*/
private final Set<Plotter> plotters = new LinkedHashSet<>();
private Graph(String name) {
this.name = name;
}
/**
* Gets the graph's name
*
* @return the Graph's name
*/
public String getName() {
return this.name;
}
/**
* Add a plotter to the graph, which will be used to plot entries
*
* @param plotter the plotter to add to the graph
*/
public void addPlotter(Plotter plotter) {
this.plotters.add(plotter);
}
/**
* Remove a plotter from the graph
*
* @param plotter the plotter to remove from the graph
*/
public void removePlotter(Plotter plotter) {
this.plotters.remove(plotter);
}
/**
* Gets an <b>unmodifiable</b> set of the plotter objects in the graph
*
* @return an unmodifiable {@link java.util.Set} of the plotter objects
*/
public Set<Plotter> getPlotters() {
return Collections.unmodifiableSet(this.plotters);
}
@Override
public int hashCode() {
return this.name.hashCode();
}
@Override
public boolean equals(Object object) {
if (!(object instanceof Graph)) {
return false;
}
Graph graph = (Graph) object;
return graph.name.equals(this.name);
}
/**
* Called when the server owner decides to opt-out of BukkitMetrics while the server is running.
*/
protected void onOptOut() {
}
}
/**
* Interface used to collect custom data for a plugin
*/
public abstract static class Plotter {
/**
* The plot's name
*/
private final String name;
/**
* Construct a plotter with the default plot name
*/
public Plotter() {
this("Default");
}
/**
* Construct a plotter with a specific plot name
*
* @param name the name of the plotter to use, which will show up on the website
*/
public Plotter(String name) {
this.name = name;
}
/**
* Get the current value for the plotted point. Since this function defers to an external function it may or may
* not return immediately thus cannot be guaranteed to be thread friendly or safe. This function can be called
* from any thread so care should be taken when accessing resources that need to be synchronized.
*
* @return the current value for the point to be plotted.
*/
public abstract int getValue();
/**
* Get the column name for the plotted point
*
* @return the plotted point's column name
*/
public String getColumnName() {
return this.name;
}
/**
* Called after the website graphs have been updated
*/
public void reset() {
}
@Override
public int hashCode() {
return getColumnName().hashCode();
}
@Override
public boolean equals(Object object) {
if (!(object instanceof Plotter)) {
return false;
}
Plotter plotter = (Plotter) object;
return plotter.name.equals(this.name) && plotter.getValue() == getValue();
}
} catch (IOException ignored) {}
}
}

View File

@ -6,9 +6,8 @@ import com.google.common.collect.HashBiMap;
import com.google.common.collect.Lists;
import com.google.common.collect.MapMaker;
import com.google.common.io.ByteSink;
import com.google.common.io.ByteSource;
import com.google.common.io.Closeables;
import com.google.common.io.Files;
import com.google.common.io.InputSupplier;
import com.google.common.primitives.Primitives;
import org.bukkit.Bukkit;
import org.bukkit.Material;
@ -25,6 +24,7 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.AbstractList;
@ -159,19 +159,18 @@ public class NbtFactory {
/**
* Load the content of a file from a stream.
*
* Use {@link Files#newInputStreamSupplier(java.io.File)} to provide a stream from a file.
* @param stream - the stream supplier.
* @param option - whether or not to decompress the input stream.
* @return The decoded NBT compound.
* @throws IOException If anything went wrong.
*/
public static NbtCompound fromStream(InputSupplier<? extends InputStream> stream, StreamOptions option) throws IOException {
public static NbtCompound fromStream(ByteSource stream, StreamOptions option) throws IOException {
InputStream input = null;
DataInputStream data = null;
boolean suppress = true;
try {
input = stream.getInput();
input = stream.openStream();
if (option == StreamOptions.GZIP_COMPRESSION) {
data = new DataInputStream(new BufferedInputStream(new GZIPInputStream(input)));
} else {
@ -194,7 +193,6 @@ public class NbtFactory {
/**
* Save the content of a NBT compound to a stream.
*
* Use {@link Files#newOutputStreamSupplier(java.io.File)} to provide a stream supplier to a file.
* @param source - the NBT compound to save.
* @param stream - the stream.
* @param option - whether or not to compress the output.
@ -223,7 +221,7 @@ public class NbtFactory {
/**
* Construct a new NBT wrapper from a compound.
* @param nmsCompound - the NBT compund.
* @param nmsCompound - the NBT compound.
* @return The wrapper.
*/
public static NbtCompound fromCompound(Object nmsCompound) {
@ -247,7 +245,7 @@ public class NbtFactory {
/**
* Construct a wrapper for an NBT tag stored (in memory) in an item stack. This is where
* auxillary data such as enchanting, name and lore is stored. It does not include items
* auxiliary data such as enchanting, name and lore is stored. It does not include items
* material, damage value or count.
* <p>
* The item stack must be a wrapper for a CraftItemStack.
@ -283,7 +281,7 @@ public class NbtFactory {
Constructor<?> caller = INSTANCE.CRAFT_STACK.getDeclaredConstructor(ItemStack.class);
caller.setAccessible(true);
return (ItemStack) caller.newInstance(stack);
} catch (Exception e) {
} catch (Exception ignored) {
throw new IllegalStateException("Unable to convert " + stack + " + to a CraftItemStack.");
}
}
@ -314,7 +312,7 @@ public class NbtFactory {
private static Object invokeMethod(Method method, Object target, Object... params) {
try {
return method.invoke(target, params);
} catch (Exception e) {
} catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException e) {
throw new RuntimeException("Unable to invoke method " + method + " for " + target, e);
}
}
@ -322,7 +320,7 @@ public class NbtFactory {
private static void setFieldValue(Field field, Object target, Object value) {
try {
field.set(target, value);
} catch (Exception e) {
} catch (IllegalAccessException | IllegalArgumentException e) {
throw new RuntimeException("Unable to set " + field + " for " + target, e);
}
}
@ -330,13 +328,13 @@ public class NbtFactory {
private static Object getFieldValue(Field field, Object target) {
try {
return field.get(target);
} catch (Exception e) {
} catch (IllegalAccessException | IllegalArgumentException e) {
throw new RuntimeException("Unable to retrieve " + field + " for " + target, e);
}
}
/**
* Search for the first publically and privately defined method of the given name and parameter count.
* Search for the first publicly and privately defined method of the given name and parameter count.
* @param requireMod - modifiers that are required.
* @param bannedMod - modifiers that are banned.
* @param clazz - a class to start with.
@ -366,7 +364,7 @@ public class NbtFactory {
}
/**
* Search for the first publically and privately defined field of the given name.
* Search for the first publicly and privately defined field of the given name.
* @param instance - an instance of the class with the field.
* @param clazz - an optional class to start with, or NULL to deduce it from instance.
* @param fieldName - the field name.
@ -395,9 +393,7 @@ public class NbtFactory {
try {
this.STREAM_TOOLS = loader.loadClass(nmsPackage + ".NBTCompressedStreamTools");
this.READ_LIMITER_CLASS = loader.loadClass(nmsPackage + ".NBTReadLimiter");
} catch (ClassNotFoundException e) {
// Ignore - we will detect this later
}
} catch (ClassNotFoundException ignored) {}
}
private String getPackageName() {
@ -434,12 +430,10 @@ public class NbtFactory {
if (value instanceof Wrapper) {
return ((Wrapper) value).getHandle();
} else if (value instanceof List) {
throw new IllegalArgumentException("Can only insert a WrappedList.");
} else if (value instanceof Map) {
throw new IllegalArgumentException("Can only insert a WrappedCompound.");
} else {
return createNbtTag(getPrimitiveType(value), value);
}
@ -447,8 +441,7 @@ public class NbtFactory {
/**
* Convert a given NBT element to a primitive wrapper or List/Map equivalent.
* <p>
* All changes to any mutable objects will be reflected in the underlying NBT element(s).
* <p> All changes to any mutable objects will be reflected in the underlying NBT element(s).
* @param nms - the NBT element.
* @return The wrapper equivalent.
*/
@ -607,7 +600,7 @@ public class NbtFactory {
*/
private static class LoadMethodWorldUpdate extends LoadCompoundMethod {
public LoadMethodWorldUpdate(Class<?> streamClass) {
LoadMethodWorldUpdate(Class<?> streamClass) {
setMethod(getMethod(Modifier.STATIC, 0, streamClass, null, DataInput.class));
}
@ -624,7 +617,7 @@ public class NbtFactory {
private Object readLimiter;
public LoadMethodSkinUpdate(Class<?> streamClass, Class<?> readLimiterClass) {
LoadMethodSkinUpdate(Class<?> streamClass, Class<?> readLimiterClass) {
setMethod(getMethod(Modifier.STATIC, 0, streamClass, null, DataInput.class, readLimiterClass));
// Find the unlimited read limiter
@ -647,11 +640,10 @@ public class NbtFactory {
/**
* Represents a root NBT compound.
* <p>
* All changes to this map will be reflected in the underlying NBT compound. Values may only be one of the following:
* <p> All changes to this map will be reflected in the underlying NBT compound. Values may only be one of the following:
* <ul>
* <li>Primitive types</li>
* <li>{@link java.lang.String String}</li>
* <li>{@link String String}</li>
* <li>{@link NbtList}</li>
* <li>{@link NbtCompound}</li>
* </ul>
@ -669,7 +661,7 @@ public class NbtFactory {
super(handle, getDataMap(handle));
}
// Simplifiying access to each value
// Simplifying access to each value
public Byte getByte(String key, Byte defaultValue) {
return containsKey(key) ? (Byte) get(key) : defaultValue;
}
@ -771,8 +763,6 @@ public class NbtFactory {
/**
* Save the content of a NBT compound to a stream.
* <p>
* Use {@link Files#newOutputStreamSupplier(java.io.File)} to provide a stream supplier to a file.
* @param stream - the output stream.
* @param option - whether or not to compress the output.
* @throws IOException If anything went wrong.

View File

@ -56,7 +56,7 @@ public class OfflinePlayerUtil {
return name;
}
Constructor gameProfileConstructor = makeConstructor(gameProfileClass, UUID.class, String.class);
if (gameProfileConstructor == null) { //Verson has string constructor
if (gameProfileConstructor == null) { //Version has string constructor
gameProfileConstructor = makeConstructor(gameProfileClass, String.class, String.class);
return callConstructor(gameProfileConstructor, id.toString(), name);
} else { //Version has uuid constructor

View File

@ -26,9 +26,8 @@ import java.util.HashSet;
import java.util.Map.Entry;
/**
* An utility that can be used to send chunks, rather than using bukkit code to do so (uses heavy NMS)
*
* An utility that can be used to send chunks, rather than using bukkit code
* to do so (uses heavy NMS).
*/
public class SendChunk {
@ -40,9 +39,10 @@ public class SendChunk {
private final RefMethod methodInitLighting;
/**
* Constructor
* Constructor.
*/
public SendChunk() {
public SendChunk() throws ClassNotFoundException, NoSuchMethodException, NoSuchFieldException {
RefConstructor tempMapChunk;
RefClass classCraftPlayer = getRefClass("{cb}.entity.CraftPlayer");
this.methodGetHandlePlayer = classCraftPlayer.getMethod("getHandle");
RefClass classCraftChunk = getRefClass("{cb}.CraftChunk");
@ -50,7 +50,17 @@ public class SendChunk {
RefClass classChunk = getRefClass("{nms}.Chunk");
this.methodInitLighting = classChunk.getMethod("initLighting");
RefClass classMapChunk = getRefClass("{nms}.PacketPlayOutMapChunk");
this.mapChunk = classMapChunk.getConstructor(classChunk.getRealClass(), boolean.class, int.class);
if (PS.get().checkVersion(PS.get().IMP.getServerVersion(), BukkitVersion.v1_9_4)) {
//this works for 1.9.4 and 1.10
tempMapChunk = classMapChunk.getConstructor(classChunk.getRealClass(),int.class);
} else {
try {
tempMapChunk = classMapChunk.getConstructor(classChunk.getRealClass(), boolean.class, int.class);
} catch (NoSuchMethodException ignored) {
tempMapChunk = classMapChunk.getConstructor(classChunk.getRealClass(),boolean.class, int.class, int.class);
}
}
this.mapChunk = tempMapChunk;
RefClass classEntityPlayer = getRefClass("{nms}.EntityPlayer");
this.connection = classEntityPlayer.getField("playerConnection");
RefClass classPacket = getRefClass("{nms}.Packet");
@ -59,7 +69,7 @@ public class SendChunk {
}
public void sendChunk(Collection<Chunk> input) {
HashSet<Chunk> chunks = new HashSet<Chunk>(input);
HashSet<Chunk> chunks = new HashSet<>(input);
HashMap<String, ArrayList<Chunk>> map = new HashMap<>();
int view = Bukkit.getServer().getViewDistance();
for (Chunk chunk : chunks) {
@ -76,23 +86,23 @@ public class SendChunk {
for (Entry<String, PlotPlayer> entry : UUIDHandler.getPlayers().entrySet()) {
PlotPlayer pp = entry.getValue();
Plot plot = pp.getCurrentPlot();
Location loc = null;
Location location = null;
String world;
if (plot != null) {
world = plot.getArea().worldname;
} else {
loc = pp.getLocation();
world = loc.getWorld();
location = pp.getLocation();
world = location.getWorld();
}
ArrayList<Chunk> list = map.get(world);
if (list == null) {
continue;
}
if (loc == null) {
loc = pp.getLocation();
if (location == null) {
location = pp.getLocation();
}
int cx = loc.getX() >> 4;
int cz = loc.getZ() >> 4;
int cx = location.getX() >> 4;
int cz = location.getZ() >> 4;
Player player = ((BukkitPlayer) pp).player;
Object entity = this.methodGetHandlePlayer.of(player).call();
@ -105,7 +115,25 @@ public class SendChunk {
Object c = this.methodGetHandleChunk.of(chunk).call();
chunks.remove(chunk);
Object con = this.connection.of(entity).get();
Object packet = this.mapChunk.create(c, true, 65535);
Object packet = null;
if (PS.get().checkVersion(PS.get().IMP.getServerVersion(), BukkitVersion.v1_9_4)) {
try {
packet = this.mapChunk.create(c,65535);
} catch (Exception ignored) {}
} else {
try {
packet = this.mapChunk.create(c, true, 65535);
} catch (ReflectiveOperationException | IllegalArgumentException e) {
try {
packet = this.mapChunk.create(c, true, 65535, 5);
} catch (ReflectiveOperationException | IllegalArgumentException e1) {
e1.printStackTrace();
}
}
}
if (packet == null) {
PS.debug("Error with PacketPlayOutMapChunk reflection.");
}
this.send.of(con).call(packet);
}
}
@ -115,11 +143,11 @@ public class SendChunk {
public void run() {
try {
chunk.unload(true, false);
} catch (Throwable e) {
String worldname = chunk.getWorld().getName();
PS.debug("$4Could not save chunk: " + worldname + ";" + chunk.getX() + ";" + chunk.getZ());
} catch (Throwable ignored) {
String worldName = chunk.getWorld().getName();
PS.debug("$4Could not save chunk: " + worldName + ';' + chunk.getX() + ";" + chunk.getZ());
PS.debug("$3 - $4File may be open in another process (e.g. MCEdit)");
PS.debug("$3 - $4" + worldname + "/level.dat or " + worldname
PS.debug("$3 - $4" + worldName + "/level.dat or " + worldName
+ "/level_old.dat may be corrupt (try repairing or removing these)");
}
}
@ -127,12 +155,12 @@ public class SendChunk {
}
}
public void sendChunk(String worldname, Collection<ChunkLoc> locs) {
World myworld = Bukkit.getWorld(worldname);
public void sendChunk(String worldName, Collection<ChunkLoc> chunkLocations) {
World myWorld = Bukkit.getWorld(worldName);
ArrayList<Chunk> chunks = new ArrayList<>();
for (ChunkLoc loc : locs) {
if (myworld.isChunkLoaded(loc.x, loc.z)) {
chunks.add(myworld.getChunkAt(loc.x, loc.z));
for (ChunkLoc loc : chunkLocations) {
if (myWorld.isChunkLoaded(loc.x, loc.z)) {
chunks.add(myWorld.getChunkAt(loc.x, loc.z));
}
}
sendChunk(chunks);

View File

@ -45,10 +45,10 @@ public class SetGenCB {
}
}
if (!set) {
Iterator<BlockPopulator> iter = world.getPopulators().iterator();
while (iter.hasNext()) {
if (iter.next() instanceof BukkitAugmentedGenerator) {
iter.remove();
Iterator<BlockPopulator> iterator = world.getPopulators().iterator();
while (iterator.hasNext()) {
if (iterator.next() instanceof BukkitAugmentedGenerator) {
iterator.remove();
}
}
}

View File

@ -0,0 +1,187 @@
package com.plotsquared.bukkit.util.block;
import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.block.BasicLocalBlockQueue;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.block.Block;
public class BukkitLocalQueue<T> extends BasicLocalBlockQueue<T> {
public BukkitLocalQueue(String world) {
super(world);
}
@Override
public LocalChunk<T> getLocalChunk(int x, int z) {
return (LocalChunk<T>) new BasicLocalChunk(this, x, z) {
// Custom stuff?
};
}
@Override
public void optimize() {
}
@Override
public PlotBlock getBlock(int x, int y, int z) {
World worldObj = Bukkit.getWorld(getWorld());
Block block = worldObj.getBlockAt(x, y, z);
if (block == null) {
return PlotBlock.get(0, 0);
}
int id = block.getTypeId();
if (id == 0) {
return PlotBlock.get(0, 0);
}
return PlotBlock.get(id, block.getData());
}
@Override
public void refreshChunk(int x, int z) {
World worldObj = Bukkit.getWorld(getWorld());
worldObj.refreshChunk(x, z);
}
@Override
public void fixChunkLighting(int x, int z) {
// Do nothing
}
@Override
public final void regenChunk(int x, int z) {
World worldObj = Bukkit.getWorld(getWorld());
worldObj.regenerateChunk(x, z);
}
@Override
public final void setComponents(LocalChunk<T> lc) {
setBlocks(lc);
setBiomes(lc);
}
public World getBukkitWorld() {
return Bukkit.getWorld(getWorld());
}
public Chunk getChunk(int x, int z) {
return getBukkitWorld().getChunkAt(x, z);
}
public void setBlocks(LocalChunk<T> lc) {
World worldObj = Bukkit.getWorld(getWorld());
Chunk chunk = worldObj.getChunkAt(lc.getX(), lc.getZ());
chunk.load(true);
for (int layer = 0; layer < lc.blocks.length; layer++) {
PlotBlock[] blocksLayer = (PlotBlock[]) lc.blocks[layer];
if (blocksLayer != null) {
for (int j = 0; j < blocksLayer.length; j++) {
PlotBlock block = blocksLayer[j];
if (block != null) {
int x = MainUtil.x_loc[layer][j];
int y = MainUtil.y_loc[layer][j];
int z = MainUtil.z_loc[layer][j];
Block existing = chunk.getBlock(x, y, z);
int existingId = existing.getTypeId();
if (existingId == block.id) {
if (existingId == 0) {
continue;
}
if (existing.getData() == block.data) {
continue;
}
}
existing.setTypeIdAndData(block.id, block.data, false);
}
}
}
}
}
public void setBiomes(LocalChunk<T> lc) {
if (lc.biomes != null) {
World worldObj = Bukkit.getWorld(getWorld());
int bx = lc.getX() << 4;
int bz = lc.getX() << 4;
String last = null;
Biome biome = null;
for (int x = 0; x < lc.biomes.length; x++) {
String[] biomes2 = lc.biomes[x];
if (biomes2 != null) {
for (int y = 0; y < biomes2.length; y++) {
String biomeStr = biomes2[y];
if (biomeStr != null) {
if (last == null || !StringMan.isEqual(last, biomeStr)) {
biome = Biome.valueOf(biomeStr.toUpperCase());
}
worldObj.setBiome(bx, bz, biome);
}
}
}
}
}
}
private Field fieldNeighbors;
private Method chunkGetHandle;
/**
* Exploiting a bug in the vanilla lighting algorithm for faster block placement
* - Could have been achieved without reflection by force unloading specific chunks
* - Much faster just setting the variable manually though
* @param chunk
* @return
*/
protected Object[] disableLighting(Chunk chunk) {
try {
if (chunkGetHandle == null) {
chunkGetHandle = chunk.getClass().getDeclaredMethod("getHandle");
chunkGetHandle.setAccessible(true);
}
Object nmsChunk = chunkGetHandle.invoke(chunk);
if (fieldNeighbors == null) {
fieldNeighbors = nmsChunk.getClass().getDeclaredField("neighbors");
fieldNeighbors.setAccessible(true);
}
Object value = fieldNeighbors.get(nmsChunk);
fieldNeighbors.set(nmsChunk, 0);
return new Object[] {nmsChunk, value};
} catch (Throwable ignore) {}
return null;
}
protected void disableLighting(Object[] disableResult) {
if (disableResult != null) {
try {
fieldNeighbors.set(disableResult[0], 0);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
protected void resetLighting(Object[] disableResult) {
if (disableResult != null) {
try {
fieldNeighbors.set(disableResult[0], disableResult[1]);
} catch (Throwable ignore) {
ignore.printStackTrace();
}
}
}
protected void enableLighting(Object[] disableResult) {
if (disableResult != null) {
try {
fieldNeighbors.set(disableResult[0], 0x739C0);
} catch (Throwable ignore) {}
}
}
}

View File

@ -0,0 +1,130 @@
package com.plotsquared.bukkit.util.block;
import com.intellectualcrafters.plot.object.ChunkWrapper;
import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.ReflectionUtils;
import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.bukkit.util.SendChunk;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.World;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
public class BukkitLocalQueue_1_7 extends BukkitLocalQueue<PlotBlock[]> {
private final ReflectionUtils.RefClass classBlock = getRefClass("{nms}.Block");
private final ReflectionUtils.RefClass classChunk = getRefClass("{nms}.Chunk");
private final ReflectionUtils.RefClass classWorld = getRefClass("{nms}.World");
private final ReflectionUtils.RefClass classCraftWorld = getRefClass("{cb}.CraftWorld");
private final ReflectionUtils.RefMethod methodGetHandle;
private final ReflectionUtils.RefMethod methodGetChunkAt;
private final ReflectionUtils.RefMethod methodA;
private final ReflectionUtils.RefMethod methodGetById;
private final ReflectionUtils.RefMethod methodInitLighting;
private final SendChunk sendChunk;
private final HashMap<ChunkWrapper, Chunk> toUpdate = new HashMap<>();
public BukkitLocalQueue_1_7(String world) throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException {
super(world);
this.methodGetHandle = this.classCraftWorld.getMethod("getHandle");
this.methodGetChunkAt = this.classWorld.getMethod("getChunkAt", int.class, int.class);
this.methodA = this.classChunk.getMethod("a", int.class, int.class, int.class, this.classBlock, int.class);
this.methodGetById = this.classBlock.getMethod("getById", int.class);
this.methodInitLighting = this.classChunk.getMethod("initLighting");
this.sendChunk = new SendChunk();
TaskManager.runTaskRepeat(new Runnable() {
@Override
public void run() {
if (BukkitLocalQueue_1_7.this.toUpdate.isEmpty()) {
return;
}
int count = 0;
ArrayList<Chunk> chunks = new ArrayList<>();
Iterator<Map.Entry<ChunkWrapper, Chunk>> i = BukkitLocalQueue_1_7.this.toUpdate.entrySet().iterator();
while (i.hasNext() && (count < 128)) {
chunks.add(i.next().getValue());
i.remove();
count++;
}
if (count == 0) {
return;
}
update(chunks);
}
}, 1);
MainUtil.initCache();
}
public void update(Collection<Chunk> chunks) {
if (chunks.isEmpty()) {
return;
}
if (!MainUtil.canSendChunk) {
for (Chunk chunk : chunks) {
chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ());
chunk.unload(true, false);
chunk.load();
}
return;
}
try {
this.sendChunk.sendChunk(chunks);
} catch (Throwable e) {
e.printStackTrace();
MainUtil.canSendChunk = false;
}
}
@Override
public void fixChunkLighting(int x, int z) {
Object c = this.methodGetHandle.of(getChunk(x, z)).call();
this.methodInitLighting.of(c).call();
}
@Override
public void setBlocks(LocalChunk<PlotBlock[]> lc) {
Chunk chunk = getChunk(lc.getX(), lc.getZ());
chunk.load(true);
World world = chunk.getWorld();
ChunkWrapper wrapper = new ChunkWrapper(getWorld(), lc.getX(), lc.getZ());
if (!this.toUpdate.containsKey(wrapper)) {
this.toUpdate.put(wrapper, chunk);
}
Object w = this.methodGetHandle.of(world).call();
Object c = this.methodGetChunkAt.of(w).call(lc.getX(), lc.getZ());
for (int i = 0; i < lc.blocks.length; i++) {
PlotBlock[] result2 = lc.blocks[i];
if (result2 == null) {
continue;
}
for (int j = 0; j < 4096; j++) {
int x = MainUtil.x_loc[i][j];
int y = MainUtil.y_loc[i][j];
int z = MainUtil.z_loc[i][j];
PlotBlock newBlock = result2[j];
if (newBlock.id == -1) {
chunk.getBlock(x, y, z).setData(newBlock.data, false);
continue;
}
Object block = this.methodGetById.call(newBlock.id);
this.methodA.of(c).call(x, y, z, block, newBlock.data);
}
}
fixChunkLighting(lc.getX(), lc.getZ());
}
@Override
public void refreshChunk(int x, int z) {
update(Arrays.asList(Bukkit.getWorld(getWorld()).getChunkAt(x, z)));
}
}

View File

@ -1,65 +1,61 @@
package com.plotsquared.bukkit.util.block;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.object.ChunkWrapper;
import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.PlotChunk;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefClass;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefConstructor;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod;
import com.intellectualcrafters.plot.util.SetQueue;
import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper;
import com.intellectualcrafters.plot.util.ReflectionUtils;
import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.bukkit.util.SendChunk;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.block.Block;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Block;
public class FastQueue_1_8 extends SlowQueue {
private final RefMethod methodInitLighting;
private final RefClass classBlock = getRefClass("{nms}.Block");
private final RefClass classBlockPosition = getRefClass("{nms}.BlockPosition");
private final RefClass classIBlockData = getRefClass("{nms}.IBlockData");
private final RefClass classChunk = getRefClass("{nms}.Chunk");
private final RefClass classWorld = getRefClass("{nms}.World");
private final RefClass classCraftWorld = getRefClass("{cb}.CraftWorld");
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
public class BukkitLocalQueue_1_8 extends BukkitLocalQueue<PlotBlock[]> {
private final ReflectionUtils.RefMethod methodInitLighting;
private final ReflectionUtils.RefClass classBlock = getRefClass("{nms}.Block");
private final ReflectionUtils.RefClass classBlockPosition = getRefClass("{nms}.BlockPosition");
private final ReflectionUtils.RefClass classIBlockData = getRefClass("{nms}.IBlockData");
private final ReflectionUtils.RefClass classChunk = getRefClass("{nms}.Chunk");
private final ReflectionUtils.RefClass classWorld = getRefClass("{nms}.World");
private final ReflectionUtils.RefClass classCraftWorld = getRefClass("{cb}.CraftWorld");
private final HashMap<ChunkWrapper, Chunk> toUpdate = new HashMap<>();
private final RefMethod methodGetHandle;
private final RefMethod methodGetChunkAt;
private final RefMethod methodA;
private final RefMethod methodGetByCombinedId;
private final RefConstructor constructorBlockPosition;
private final SendChunk chunksender;
private final ReflectionUtils.RefMethod methodGetHandle;
private final ReflectionUtils.RefMethod methodGetChunkAt;
private final ReflectionUtils.RefMethod methodA;
private final ReflectionUtils.RefMethod methodGetByCombinedId;
private final ReflectionUtils.RefConstructor constructorBlockPosition;
private final SendChunk sendChunk;
public FastQueue_1_8() throws RuntimeException {
public BukkitLocalQueue_1_8(String world) throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException {
super(world);
this.methodInitLighting = this.classChunk.getMethod("initLighting");
this.constructorBlockPosition = this.classBlockPosition.getConstructor(int.class, int.class, int.class);
this.methodGetByCombinedId = this.classBlock.getMethod("getByCombinedId", int.class);
this.methodGetHandle = this.classCraftWorld.getMethod("getHandle");
this.methodGetChunkAt = this.classWorld.getMethod("getChunkAt", int.class, int.class);
this.methodA = this.classChunk.getMethod("a", this.classBlockPosition, this.classIBlockData);
this.chunksender = new SendChunk();
this.sendChunk = new SendChunk();
TaskManager.runTaskRepeat(new Runnable() {
@Override
public void run() {
if (FastQueue_1_8.this.toUpdate.isEmpty()) {
if (BukkitLocalQueue_1_8.this.toUpdate.isEmpty()) {
return;
}
int count = 0;
ArrayList<Chunk> chunks = new ArrayList<Chunk>();
Iterator<Entry<ChunkWrapper, Chunk>> i = FastQueue_1_8.this.toUpdate.entrySet().iterator();
while (i.hasNext() && (count < 128)) {
ArrayList<Chunk> chunks = new ArrayList<>();
Iterator<Map.Entry<ChunkWrapper, Chunk>> i = BukkitLocalQueue_1_8.this.toUpdate.entrySet().iterator();
while (i.hasNext() && count < 128) {
chunks.add(i.next().getValue());
i.remove();
count++;
@ -73,44 +69,25 @@ public class FastQueue_1_8 extends SlowQueue {
MainUtil.initCache();
}
public void update(Collection<Chunk> chunks) {
if (chunks.isEmpty()) {
return;
}
if (!MainUtil.canSendChunk) {
for (Chunk chunk : chunks) {
chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ());
chunk.unload(true, false);
chunk.load();
}
return;
}
try {
this.chunksender.sendChunk(chunks);
} catch (Throwable e) {
e.printStackTrace();
MainUtil.canSendChunk = false;
}
@Override
public void fixChunkLighting(int x, int z) {
Object c = this.methodGetHandle.of(getChunk(x, z)).call();
this.methodInitLighting.of(c).call();
}
/**
* This should be overridden by any specialized queues.
* @param plotChunk
*/
@Override
public void execute(PlotChunk<Chunk> plotChunk) {
SlowChunk sc = (SlowChunk) plotChunk;
Chunk chunk = plotChunk.getChunk();
ChunkWrapper wrapper = plotChunk.getChunkWrapper();
public void setBlocks(LocalChunk<PlotBlock[]> lc) {
Chunk chunk = getChunk(lc.getX(), lc.getZ());
chunk.load(true);
World world = chunk.getWorld();
ChunkWrapper wrapper = new ChunkWrapper(getWorld(), lc.getX(), lc.getZ());
if (!this.toUpdate.containsKey(wrapper)) {
this.toUpdate.put(wrapper, chunk);
}
chunk.load(true);
World world = chunk.getWorld();
Object w = this.methodGetHandle.of(world).call();
Object c = this.methodGetChunkAt.of(w).call(wrapper.x, wrapper.z);
for (int i = 0; i < sc.result.length; i++) {
PlotBlock[] result2 = sc.result[i];
Object c = this.methodGetChunkAt.of(w).call(lc.getX(), lc.getZ());
for (int i = 0; i < lc.blocks.length; i++) {
PlotBlock[] result2 = lc.blocks[i];
if (result2 == null) {
continue;
}
@ -161,7 +138,7 @@ public class FastQueue_1_8 extends SlowQueue {
case 29:
case 33:
case 151:
case 178: {
case 178:
Block block = world.getBlockAt(x, y, z);
if (block.getData() == newBlock.data) {
if (block.getTypeId() != newBlock.id) {
@ -175,7 +152,6 @@ public class FastQueue_1_8 extends SlowQueue {
}
}
continue;
}
}
// Start data value shortcut
@ -263,9 +239,8 @@ public class FastQueue_1_8 extends SlowQueue {
case 189:
case 190:
case 191:
case 192: {
case 192:
continue;
}
}
if (block.getData() == newBlock.data) {
return;
@ -311,73 +286,52 @@ public class FastQueue_1_8 extends SlowQueue {
case 29:
case 33:
case 151:
case 178: {
case 178:
if (block.getData() == newBlock.data) {
block.setTypeId(newBlock.id, false);
} else {
block.setTypeIdAndData(newBlock.id, newBlock.data, false);
}
continue;
}
}
// End blockstate workaround //
// check sign
Object pos = this.constructorBlockPosition.create(x, y, z);
Object pos = null;
try {
pos = this.constructorBlockPosition.create(x, y, z);
} catch (ReflectiveOperationException e) {
e.printStackTrace();
}
Object combined = this.methodGetByCombinedId.call(newBlock.id + (newBlock.data << 12));
this.methodA.of(chunk).call(pos, combined);
}
}
int[][] biomes = sc.biomes;
Biome[] values = Biome.values();
if (biomes != null) {
for (int x = 0; x < 16; x++) {
int[] array = biomes[x];
if (array == null) {
continue;
}
for (int z = 0; z < 16; z++) {
int biome = array[z];
if (biome == 0) {
continue;
}
chunk.getBlock(x, 0, z).setBiome(values[biome]);
}
fixChunkLighting(lc.getX(), lc.getZ());
}
public void update(Collection<Chunk> chunks) {
if (chunks.isEmpty()) {
return;
}
if (!MainUtil.canSendChunk) {
for (Chunk chunk : chunks) {
chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ());
chunk.unload(true, false);
chunk.load();
}
return;
}
try {
this.sendChunk.sendChunk(chunks);
} catch (Throwable e) {
e.printStackTrace();
MainUtil.canSendChunk = false;
}
}
/**
* This should be overridden by any specialized queues.
* @param wrap
*/
@Override
public PlotChunk<Chunk> getChunk(ChunkWrapper wrap) {
return new SlowChunk(wrap);
}
/**
* This should be overridden by any specialized queues.
* @param fixAll
*/
@Override
public boolean fixLighting(PlotChunk<Chunk> chunk, boolean fixAll) {
Object c = this.methodGetHandle.of(chunk.getChunk()).call();
this.methodInitLighting.of(c).call();
return true;
}
/**
* This should be overridden by any specialized queues.
* @param locations
*/
@Override
public void sendChunk(String world, Collection<ChunkLoc> locations) {
World worldObj = BukkitUtil.getWorld(world);
for (ChunkLoc loc : locations) {
ChunkWrapper wrapper = SetQueue.IMP.new ChunkWrapper(world, loc.x, loc.z);
this.toUpdate.remove(wrapper);
}
this.chunksender.sendChunk(world, locations);
public void refreshChunk(int x, int z) {
update(Arrays.asList(Bukkit.getWorld(getWorld()).getChunkAt(x, z)));
}
}

View File

@ -1,80 +1,78 @@
package com.plotsquared.bukkit.util.block;
import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.object.PseudoRandom;
import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.PlotChunk;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefClass;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefConstructor;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefField;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod.RefExecutor;
import com.intellectualcrafters.plot.util.SetQueue;
import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper;
import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.bukkit.util.SendChunk;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
import org.bukkit.Chunk;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.block.Biome;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
public class FastQueue_1_8_3 extends SlowQueue {
import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.object.ChunkWrapper;
import com.intellectualcrafters.plot.object.PseudoRandom;
import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.ReflectionUtils;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.block.BasicLocalBlockQueue;
import com.plotsquared.bukkit.util.SendChunk;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Material;
import org.bukkit.World;
private final SendChunk chunksender;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class BukkitLocalQueue_1_8_3 extends BukkitLocalQueue<char[]> {
private final SendChunk sendChunk;
private final HashMap<ChunkWrapper, Chunk> toUpdate = new HashMap<>();
private final RefMethod methodGetHandleChunk;
private final RefMethod methodInitLighting;
private final RefConstructor classBlockPositionConstructor;
private final RefConstructor classChunkSectionConstructor;
private final RefMethod methodX;
private final RefMethod methodAreNeighborsLoaded;
private final RefField fieldSections;
private final RefField fieldWorld;
private final RefMethod methodGetIdArray;
private final RefMethod methodGetWorld;
private final RefField tileEntityUnload;
private final ReflectionUtils.RefMethod methodGetHandleChunk;
private final ReflectionUtils.RefMethod methodGetHandleWorld;
private final ReflectionUtils.RefMethod methodInitLighting;
private final ReflectionUtils.RefConstructor classBlockPositionConstructor;
private final ReflectionUtils.RefConstructor classChunkSectionConstructor;
private final ReflectionUtils.RefMethod methodX;
private final ReflectionUtils.RefMethod methodAreNeighborsLoaded;
private final ReflectionUtils.RefField fieldSections;
private final ReflectionUtils.RefField fieldWorld;
private final ReflectionUtils.RefMethod methodGetIdArray;
private final ReflectionUtils.RefMethod methodGetWorld;
private final ReflectionUtils.RefField tileEntityListTick;
public FastQueue_1_8_3() throws RuntimeException {
RefClass classCraftChunk = getRefClass("{cb}.CraftChunk");
public BukkitLocalQueue_1_8_3(String world) throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException {
super(world);
ReflectionUtils.RefClass classCraftChunk = getRefClass("{cb}.CraftChunk");
ReflectionUtils.RefClass classCraftWorld = getRefClass("{cb}.CraftWorld");
this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle");
RefClass classChunk = getRefClass("{nms}.Chunk");
ReflectionUtils.RefClass classChunk = getRefClass("{nms}.Chunk");
this.methodInitLighting = classChunk.getMethod("initLighting");
RefClass classBlockPosition = getRefClass("{nms}.BlockPosition");
ReflectionUtils.RefClass classBlockPosition = getRefClass("{nms}.BlockPosition");
this.classBlockPositionConstructor = classBlockPosition.getConstructor(int.class, int.class, int.class);
RefClass classWorld = getRefClass("{nms}.World");
ReflectionUtils.RefClass classWorld = getRefClass("{nms}.World");
this.methodX = classWorld.getMethod("x", classBlockPosition.getRealClass());
this.fieldSections = classChunk.getField("sections");
this.fieldWorld = classChunk.getField("world");
RefClass classChunkSection = getRefClass("{nms}.ChunkSection");
ReflectionUtils.RefClass classChunkSection = getRefClass("{nms}.ChunkSection");
this.methodGetIdArray = classChunkSection.getMethod("getIdArray");
this.methodAreNeighborsLoaded = classChunk.getMethod("areNeighborsLoaded", int.class);
this.classChunkSectionConstructor = classChunkSection.getConstructor(int.class, boolean.class, char[].class);
this.tileEntityUnload = classWorld.getField("c");
this.tileEntityListTick = classWorld.getField("tileEntityList");
this.methodGetHandleWorld = classCraftWorld.getMethod("getHandle");
this.methodGetWorld = classChunk.getMethod("getWorld");
this.chunksender = new SendChunk();
this.sendChunk = new SendChunk();
TaskManager.runTaskRepeat(new Runnable() {
@Override
public void run() {
if (FastQueue_1_8_3.this.toUpdate.isEmpty()) {
if (BukkitLocalQueue_1_8_3.this.toUpdate.isEmpty()) {
return;
}
int count = 0;
ArrayList<Chunk> chunks = new ArrayList<>();
Iterator<Entry<ChunkWrapper, Chunk>> i = FastQueue_1_8_3.this.toUpdate.entrySet().iterator();
Iterator<Map.Entry<ChunkWrapper, Chunk>> i = BukkitLocalQueue_1_8_3.this.toUpdate.entrySet().iterator();
while (i.hasNext() && count < 128) {
chunks.add(i.next().getValue());
i.remove();
@ -89,56 +87,196 @@ public class FastQueue_1_8_3 extends SlowQueue {
MainUtil.initCache();
}
public void update(Collection<Chunk> chunks) {
if (chunks.isEmpty()) {
return;
@Override
public LocalChunk<char[]> getLocalChunk(int x, int z) {
return new CharLocalChunk_1_8_3(this, x, z);
}
public class CharLocalChunk_1_8_3 extends CharLocalChunk {
public short[] count;
public short[] air;
public short[] relight;
public CharLocalChunk_1_8_3(BasicLocalBlockQueue parent, int x, int z) {
super(parent, x, z);
this.count = new short[16];
this.air = new short[16];
this.relight = new short[16];
}
if (!MainUtil.canSendChunk) {
for (Chunk chunk : chunks) {
chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ());
chunk.unload(true, false);
chunk.load();
@Override
public void setBlock(int x, int y, int z, int id, int data) {
int i = MainUtil.CACHE_I[y][x][z];
int j = MainUtil.CACHE_J[y][x][z];
char[] vs = this.blocks[i];
if (vs == null) {
vs = this.blocks[i] = new char[4096];
this.count[i]++;
} else if (vs[j] == 0) {
this.count[i]++;
}
switch (id) {
case 0:
this.air[i]++;
vs[j] = (char) 1;
return;
case 10:
case 11:
case 39:
case 40:
case 51:
case 74:
case 89:
case 122:
case 124:
case 138:
case 169:
this.relight[i]++;
case 2:
case 4:
case 13:
case 14:
case 15:
case 20:
case 21:
case 22:
case 30:
case 32:
case 37:
case 41:
case 42:
case 45:
case 46:
case 47:
case 48:
case 49:
case 55:
case 56:
case 57:
case 58:
case 60:
case 7:
case 8:
case 9:
case 73:
case 78:
case 79:
case 80:
case 81:
case 82:
case 83:
case 85:
case 87:
case 88:
case 101:
case 102:
case 103:
case 110:
case 112:
case 113:
case 121:
case 129:
case 133:
case 165:
case 166:
case 170:
case 172:
case 173:
case 174:
case 181:
case 182:
case 188:
case 189:
case 190:
case 191:
case 192:
vs[j] = (char) (id << 4);
return;
case 130:
case 76:
case 62:
this.relight[i]++;
case 54:
case 146:
case 61:
case 65:
case 68:
case 50:
if (data < 2) {
data = 2;
}
default:
vs[j] = (char) ((id << 4) + data);
return;
}
return;
}
try {
this.chunksender.sendChunk(chunks);
} catch (Throwable e) {
e.printStackTrace();
MainUtil.canSendChunk = false;
public char[] getIdArray(int i) {
return this.blocks[i];
}
public int getCount(int i) {
return this.count[i];
}
public int getAir(int i) {
return this.air[i];
}
public void setCount(int i, short value) {
this.count[i] = value;
}
public int getRelight(int i) {
return this.relight[i];
}
public int getTotalCount() {
int total = 0;
for (int i = 0; i < 16; i++) {
total += this.count[i];
}
return total;
}
public int getTotalRelight() {
if (getTotalCount() == 0) {
Arrays.fill(this.count, (short) 1);
Arrays.fill(this.relight, Short.MAX_VALUE);
return Short.MAX_VALUE;
}
int total = 0;
for (int i = 0; i < 16; i++) {
total += this.relight[i];
}
return total;
}
}
/**
* This should be overridden by any specialized queues.
* @param plotChunk
*/
@Override
public void execute(PlotChunk<Chunk> plotChunk) {
FastChunk_1_8_3 fs = (FastChunk_1_8_3) plotChunk;
Chunk chunk = plotChunk.getChunk();
public void setBlocks(LocalChunk lc) {
CharLocalChunk_1_8_3 fs = (CharLocalChunk_1_8_3) lc;
Chunk chunk = getChunk(lc.getX(), lc.getZ());
chunk.load(true);
World world = chunk.getWorld();
ChunkWrapper wrapper = plotChunk.getChunkWrapper();
ChunkWrapper wrapper = new ChunkWrapper(getWorld(), lc.getX(), lc.getZ());
if (!this.toUpdate.containsKey(wrapper)) {
this.toUpdate.put(wrapper, chunk);
}
chunk.load(true);
try {
boolean flag = world.getEnvironment() == Environment.NORMAL;
boolean flag = world.getEnvironment() == World.Environment.NORMAL;
// Sections
Method getHandle = chunk.getClass().getDeclaredMethod("getHandle");
Object c = getHandle.invoke(chunk);
Object w = methodGetWorld.of(c).call();
Class<? extends Object> clazz = c.getClass();
Object w = this.methodGetWorld.of(c).call();
Class<?> clazz = c.getClass();
Field sections1 = clazz.getDeclaredField("sections");
sections1.setAccessible(true);
Field tileEntities = clazz.getDeclaredField("tileEntities");
Field entitySlices = clazz.getDeclaredField("entitySlices");
Object[] sections = (Object[]) sections1.get(c);
HashMap<?, ?> tiles = (HashMap<?, ?>) tileEntities.get(c);
Collection<Object> tilesUnload = (Collection<Object>) tileEntityUnload.of(w).get();
Collection<?>[] entities = (Collection<?>[]) entitySlices.get(c);
Method getX = null;
@ -146,10 +284,11 @@ public class FastQueue_1_8_3 extends SlowQueue {
Method getZ = null;
// Trim tiles
Set<Entry<?, ?>> entrySet = (Set<Entry<?, ?>>) (Set<?>) tiles.entrySet();
Iterator<Entry<?, ?>> iterator = entrySet.iterator();
boolean removed = false;
Set<Map.Entry<?, ?>> entrySet = (Set<Map.Entry<?, ?>>) (Set<?>) tiles.entrySet();
Iterator<Map.Entry<?, ?>> iterator = entrySet.iterator();
while (iterator.hasNext()) {
Entry<?, ?> tile = iterator.next();
Map.Entry<?, ?> tile = iterator.next();
Object pos = tile.getKey();
if (getX == null) {
Class<? extends Object> clazz2 = pos.getClass().getSuperclass();
@ -167,10 +306,13 @@ public class FastQueue_1_8_3 extends SlowQueue {
continue;
}
if (array[k] != 0) {
tilesUnload.add(tile.getValue());
removed = true;
iterator.remove();
}
}
if (removed) {
((Collection) this.tileEntityListTick.of(w).get()).clear();
}
// Trim entities
for (int i = 0; i < 16; i++) {
@ -215,30 +357,13 @@ public class FastQueue_1_8_3 extends SlowQueue {
}
}
// Clear
} catch (IllegalAccessException | IllegalArgumentException | NoSuchMethodException | SecurityException | InvocationTargetException
| NoSuchFieldException e) {
} catch (IllegalArgumentException | SecurityException | ReflectiveOperationException e) {
e.printStackTrace();
}
int[][] biomes = fs.biomes;
Biome[] values = Biome.values();
if (biomes != null) {
for (int x = 0; x < 16; x++) {
int[] array = biomes[x];
if (array == null) {
continue;
}
for (int z = 0; z < 16; z++) {
int biome = array[z];
if (biome == 0) {
continue;
}
chunk.getBlock(x, 0, z).setBiome(values[biome]);
}
}
}
fixLighting(chunk, fs, true);
}
public Object newChunkSection(int i, boolean flag, char[] ids) {
public Object newChunkSection(int i, boolean flag, char[] ids) throws ReflectiveOperationException {
return this.classChunkSectionConstructor.create(i, flag, ids);
}
@ -246,24 +371,14 @@ public class FastQueue_1_8_3 extends SlowQueue {
return (char[]) this.methodGetIdArray.of(obj).call();
}
/**
* This should be overridden by any specialized queues.
* @param wrap
*/
@Override
public PlotChunk<Chunk> getChunk(ChunkWrapper wrap) {
return new FastChunk_1_8_3(wrap);
public void fixChunkLighting(int x, int z) {
Object c = this.methodGetHandleChunk.of(getChunk(x, z)).call();
this.methodInitLighting.of(c).call();
}
/**
* This should be overridden by any specialized queues
* @param plotChunk
*/
@Override
public boolean fixLighting(PlotChunk<Chunk> plotChunk, boolean fixAll) {
public boolean fixLighting(Chunk chunk, CharLocalChunk_1_8_3 bc, boolean fixAll) {
try {
FastChunk_1_8_3 bc = (FastChunk_1_8_3) plotChunk;
Chunk chunk = bc.getChunk();
if (!chunk.isLoaded()) {
chunk.load(false);
} else {
@ -276,8 +391,7 @@ public class FastQueue_1_8_3 extends SlowQueue {
if (fixAll && !(boolean) this.methodAreNeighborsLoaded.of(c).call(1)) {
World world = chunk.getWorld();
ChunkWrapper wrapper = bc.getChunkWrapper();
String worldName = wrapper.world;
ChunkWrapper wrapper = new ChunkWrapper(getWorld(), chunk.getX(), chunk.getZ());
for (int x = wrapper.x - 1; x <= wrapper.x + 1; x++) {
for (int z = wrapper.z - 1; z <= wrapper.z + 1; z++) {
if (x != 0 && z != 0) {
@ -285,15 +399,15 @@ public class FastQueue_1_8_3 extends SlowQueue {
while (!other.isLoaded()) {
other.load(true);
}
ChunkManager.manager.loadChunk(worldName, new ChunkLoc(x, z), true);
ChunkManager.manager.loadChunk(wrapper.world, new ChunkLoc(x, z), true);
}
}
}
/*
/*
if (!(boolean) methodAreNeighborsLoaded.of(c).call(1)) {
return false;
}
*/
*/
}
this.methodInitLighting.of(c).call();
@ -308,7 +422,7 @@ public class FastQueue_1_8_3 extends SlowQueue {
int X = chunk.getX() << 4;
int Z = chunk.getZ() << 4;
RefExecutor relight = this.methodX.of(w);
ReflectionUtils.RefMethod.RefExecutor relight = this.methodX.of(w);
for (int j = 0; j < sections.length; j++) {
Object section = sections[j];
if (section == null) {
@ -396,17 +510,28 @@ public class FastQueue_1_8_3 extends SlowQueue {
return array[j] >> 4;
}
/**
* This should be overridden by any specialized queues.
* @param world
* @param locations
*/
@Override
public void sendChunk(String world, Collection<ChunkLoc> locations) {
for (ChunkLoc loc : locations) {
ChunkWrapper wrapper = SetQueue.IMP.new ChunkWrapper(world, loc.x, loc.z);
this.toUpdate.remove(wrapper);
public void update(Collection<Chunk> chunks) {
if (chunks.isEmpty()) {
return;
}
this.chunksender.sendChunk(world, locations);
if (!MainUtil.canSendChunk) {
for (Chunk chunk : chunks) {
chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ());
chunk.unload(true, false);
chunk.load();
}
return;
}
try {
this.sendChunk.sendChunk(chunks);
} catch (Throwable e) {
e.printStackTrace();
MainUtil.canSendChunk = false;
}
}
@Override
public void refreshChunk(int x, int z) {
update(Arrays.asList(Bukkit.getWorld(getWorld()).getChunkAt(x, z)));
}
}

View File

@ -0,0 +1,498 @@
package com.plotsquared.bukkit.util.block;
import com.intellectualcrafters.plot.object.ChunkWrapper;
import com.intellectualcrafters.plot.object.PseudoRandom;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.ReflectionUtils;
import com.intellectualcrafters.plot.util.block.BasicLocalBlockQueue;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.bukkit.Chunk;
import org.bukkit.Material;
import org.bukkit.World;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
public class BukkitLocalQueue_1_9 extends BukkitLocalQueue<char[]> {
private final Object air;
// private final HashMap<ChunkWrapper, Chunk> toUpdate = new HashMap<>();
private final ReflectionUtils.RefMethod methodGetHandleChunk;
private final ReflectionUtils.RefMethod methodInitLighting;
private final ReflectionUtils.RefConstructor classBlockPositionConstructor;
private final ReflectionUtils.RefConstructor classChunkSectionConstructor;
private final ReflectionUtils.RefMethod methodW;
private final ReflectionUtils.RefMethod methodAreNeighborsLoaded;
private final ReflectionUtils.RefField fieldSections;
private final ReflectionUtils.RefField fieldWorld;
private final ReflectionUtils.RefMethod methodGetBlocks;
private final ReflectionUtils.RefMethod methodGetType;
private final ReflectionUtils.RefMethod methodSetType;
private final ReflectionUtils.RefMethod methodGetCombinedId;
private final ReflectionUtils.RefMethod methodGetByCombinedId;
private final ReflectionUtils.RefMethod methodGetWorld;
private final ReflectionUtils.RefField tileEntityListTick;
public BukkitLocalQueue_1_9(String world) throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException {
super(world);
ReflectionUtils.RefClass classCraftChunk = getRefClass("{cb}.CraftChunk");
this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle");
ReflectionUtils.RefClass classChunk = getRefClass("{nms}.Chunk");
this.methodInitLighting = classChunk.getMethod("initLighting");
ReflectionUtils.RefClass classBlockPosition = getRefClass("{nms}.BlockPosition");
this.classBlockPositionConstructor = classBlockPosition.getConstructor(int.class, int.class, int.class);
ReflectionUtils.RefClass classWorld = getRefClass("{nms}.World");
this.tileEntityListTick = classWorld.getField("tileEntityListTick");
this.methodGetWorld = classChunk.getMethod("getWorld");
this.methodW = classWorld.getMethod("w", classBlockPosition.getRealClass());
this.fieldSections = classChunk.getField("sections");
this.fieldWorld = classChunk.getField("world");
ReflectionUtils.RefClass classBlock = getRefClass("{nms}.Block");
ReflectionUtils.RefClass classIBlockData = getRefClass("{nms}.IBlockData");
this.methodGetCombinedId = classBlock.getMethod("getCombinedId", classIBlockData.getRealClass());
this.methodGetByCombinedId = classBlock.getMethod("getByCombinedId", int.class);
ReflectionUtils.RefClass classChunkSection = getRefClass("{nms}.ChunkSection");
this.methodGetBlocks = classChunkSection.getMethod("getBlocks");
this.methodGetType = classChunkSection.getMethod("getType", int.class, int.class, int.class);
this.methodSetType = classChunkSection.getMethod("setType", int.class, int.class, int.class, classIBlockData.getRealClass());
this.methodAreNeighborsLoaded = classChunk.getMethod("areNeighborsLoaded", int.class);
this.classChunkSectionConstructor = classChunkSection.getConstructor(int.class, boolean.class, char[].class);
this.air = this.methodGetByCombinedId.call(0);
MainUtil.initCache();
}
@Override
public LocalChunk<char[]> getLocalChunk(int x, int z) {
return new CharLocalChunk_1_8_3(this, x, z);
}
public class CharLocalChunk_1_8_3 extends CharLocalChunk {
public short[] count;
public short[] air;
public short[] relight;
public CharLocalChunk_1_8_3(BasicLocalBlockQueue parent, int x, int z) {
super(parent, x, z);
this.count = new short[16];
this.air = new short[16];
this.relight = new short[16];
}
@Override
public void setBlock(int x, int y, int z, int id, int data) {
int i = MainUtil.CACHE_I[y][x][z];
int j = MainUtil.CACHE_J[y][x][z];
char[] vs = this.blocks[i];
if (vs == null) {
vs = this.blocks[i] = new char[4096];
this.count[i]++;
} else if (vs[j] == 0) {
this.count[i]++;
}
switch (id) {
case 0:
this.air[i]++;
vs[j] = (char) 1;
return;
case 10:
case 11:
case 39:
case 40:
case 51:
case 74:
case 89:
case 122:
case 124:
case 138:
case 169:
this.relight[i]++;
case 2:
case 4:
case 13:
case 14:
case 15:
case 20:
case 21:
case 22:
case 30:
case 32:
case 37:
case 41:
case 42:
case 45:
case 46:
case 47:
case 48:
case 49:
case 55:
case 56:
case 57:
case 58:
case 60:
case 7:
case 8:
case 9:
case 73:
case 78:
case 79:
case 80:
case 81:
case 82:
case 83:
case 85:
case 87:
case 88:
case 101:
case 102:
case 103:
case 110:
case 112:
case 113:
case 121:
case 129:
case 133:
case 165:
case 166:
case 170:
case 172:
case 173:
case 174:
case 181:
case 182:
case 188:
case 189:
case 190:
case 191:
case 192:
vs[j] = (char) (id << 4);
return;
case 130:
case 76:
case 62:
this.relight[i]++;
case 54:
case 146:
case 61:
case 65:
case 68:
case 50:
if (data < 2) {
data = 2;
}
default:
vs[j] = (char) ((id << 4) + data);
return;
}
}
public char[] getIdArray(int i) {
return this.blocks[i];
}
public int getCount(int i) {
return this.count[i];
}
public int getAir(int i) {
return this.air[i];
}
public void setCount(int i, short value) {
this.count[i] = value;
}
public int getRelight(int i) {
return this.relight[i];
}
public int getTotalCount() {
int total = 0;
for (int i = 0; i < 16; i++) {
total += this.count[i];
}
return total;
}
public int getTotalRelight() {
if (getTotalCount() == 0) {
Arrays.fill(this.count, (short) 1);
Arrays.fill(this.relight, Short.MAX_VALUE);
return Short.MAX_VALUE;
}
int total = 0;
for (int i = 0; i < 16; i++) {
total += this.relight[i];
}
return total;
}
}
@Override
public void setBlocks(LocalChunk lc) {
CharLocalChunk_1_8_3 fs = (CharLocalChunk_1_8_3) lc;
Chunk chunk = getChunk(lc.getX(), lc.getZ());
chunk.load(true);
World world = chunk.getWorld();
try {
boolean flag = world.getEnvironment() == World.Environment.NORMAL;
// Sections
Method getHandle = chunk.getClass().getDeclaredMethod("getHandle");
Object c = getHandle.invoke(chunk);
Object w = this.methodGetWorld.of(c).call();
Class<? extends Object> clazz = c.getClass();
Field sf = clazz.getDeclaredField("sections");
sf.setAccessible(true);
Field tf = clazz.getDeclaredField("tileEntities");
Field entitySlices = clazz.getDeclaredField("entitySlices");
Object[] sections = (Object[]) sf.get(c);
HashMap<?, ?> tiles = (HashMap<?, ?>) tf.get(c);
Collection<?>[] entities = (Collection<?>[]) entitySlices.get(c);
Method xm = null;
Method ym = null;
Method zm = null;
// Trim tiles
boolean removed = false;
Set<Map.Entry<?, ?>> entrySet = (Set<Map.Entry<?, ?>>) (Set<?>) tiles.entrySet();
Iterator<Map.Entry<?, ?>> iterator = entrySet.iterator();
while (iterator.hasNext()) {
Map.Entry<?, ?> tile = iterator.next();
Object pos = tile.getKey();
if (xm == null) {
Class<?> clazz2 = pos.getClass().getSuperclass();
xm = clazz2.getDeclaredMethod("getX");
ym = clazz2.getDeclaredMethod("getY");
zm = clazz2.getDeclaredMethod("getZ");
}
int lx = (int) xm.invoke(pos) & 15;
int ly = (int) ym.invoke(pos);
int lz = (int) zm.invoke(pos) & 15;
int j = MainUtil.CACHE_I[ly][lx][lz];
int k = MainUtil.CACHE_J[ly][lx][lz];
char[] array = fs.getIdArray(j);
if (array == null) {
continue;
}
if (array[k] != 0) {
removed = true;
iterator.remove();
}
}
if (removed) {
((Collection) this.tileEntityListTick.of(w).get()).clear();
}
// Trim entities
for (int i = 0; i < 16; i++) {
if (entities[i] != null && fs.getCount(i) >= 4096) {
entities[i].clear();
}
}
// Efficiently merge sections
for (int j = 0; j < sections.length; j++) {
if (fs.getCount(j) == 0) {
continue;
}
char[] newArray = fs.getIdArray(j);
if (newArray == null) {
continue;
}
Object section = sections[j];
if (section == null || fs.getCount(j) >= 4096) {
section = sections[j] = newChunkSection(j << 4, flag, fs.getIdArray(j));
continue;
}
Object currentArray = getBlocks(section);
ReflectionUtils.RefMethod.RefExecutor setType = this.methodSetType.of(section);
boolean fill = true;
for (int k = 0; k < newArray.length; k++) {
char n = newArray[k];
switch (n) {
case 0:
fill = false;
continue;
case 1: {
fill = false;
int x = MainUtil.x_loc[j][k];
int y = MainUtil.y_loc[j][k];
int z = MainUtil.z_loc[j][k];
setType.call(x, y & 15, z, this.air);
continue;
}
default:
int x = MainUtil.x_loc[j][k];
int y = MainUtil.y_loc[j][k];
int z = MainUtil.z_loc[j][k];
int id = n >> 4;
int data = n & 15;
Object iBlock = this.methodGetByCombinedId.call((int) (id & 0xFFF) + (data << 12));
setType.call(x, y & 15, z, iBlock);
}
}
if (fill) {
fs.setCount(j, Short.MAX_VALUE);
}
}
// Clear
} catch (IllegalArgumentException | SecurityException | ReflectiveOperationException e) {
e.printStackTrace();
}
fixLighting(chunk, fs, true);
refreshChunk(fs.getX(), fs.getZ());
}
public Object newChunkSection(int i, boolean flag, char[] ids) throws ReflectiveOperationException {
return this.classChunkSectionConstructor.create(i, flag, ids);
}
public Object getBlocks(Object obj) {
return this.methodGetBlocks.of(obj).call();
}
@Override
public void fixChunkLighting(int x, int z) {
Object c = this.methodGetHandleChunk.of(getChunk(x, z)).call();
this.methodInitLighting.of(c).call();
}
public boolean fixLighting(Chunk chunk, CharLocalChunk_1_8_3 bc, boolean fixAll) {
try {
if (!chunk.isLoaded()) {
chunk.load(false);
} else {
chunk.unload(true, false);
chunk.load(false);
}
// Initialize lighting
Object c = this.methodGetHandleChunk.of(chunk).call();
ChunkWrapper wrapper = new ChunkWrapper(getWorld(), bc.getX(), bc.getZ());
Object[] result = disableLighting(chunk);
enableLighting(result);
this.methodInitLighting.of(c).call();
if (bc.getTotalRelight() != 0 || fixAll) {
Object[] sections = (Object[]) this.fieldSections.of(c).get();
Object w = this.fieldWorld.of(c).get();
int X = chunk.getX() << 4;
int Z = chunk.getZ() << 4;
ReflectionUtils.RefMethod.RefExecutor relight = this.methodW.of(w);
for (int j = 0; j < sections.length; j++) {
Object section = sections[j];
if (section == null) {
continue;
}
if (bc.getRelight(j) == 0 && !fixAll || bc.getCount(j) == 0 || bc.getCount(j) >= 4096 && bc.getAir(j) == 0) {
continue;
}
char[] array = bc.getIdArray(j);
if (array != null) {
int l = PseudoRandom.random.random(2);
for (int k = 0; k < array.length; k++) {
int i = array[k];
if (i < 16) {
continue;
}
short id = (short) (i >> 4);
switch (id) { // Lighting
default:
if (!fixAll) {
continue;
}
if ((k & 1) == l) {
l = 1 - l;
continue;
}
case 10:
case 11:
case 39:
case 40:
case 50:
case 51:
case 62:
case 74:
case 76:
case 89:
case 122:
case 124:
case 130:
case 138:
case 169:
int x = MainUtil.x_loc[j][k];
int y = MainUtil.y_loc[j][k];
int z = MainUtil.z_loc[j][k];
if (isSurrounded(bc.blocks, x, y, z)) {
continue;
}
Object pos = this.classBlockPositionConstructor.create(X + x, y, Z + z);
relight.call(pos);
}
}
}
}
}
resetLighting(result);
return true;
} catch (Throwable e) {
e.printStackTrace();
}
return false;
}
@Override
public void refreshChunk(int x, int z) {
getBukkitWorld().refreshChunk(x, z);
}
public boolean isSurrounded(char[][] sections, int x, int y, int z) {
return isSolid(getId(sections, x, y + 1, z))
&& isSolid(getId(sections, x + 1, y - 1, z))
&& isSolid(getId(sections, x - 1, y, z))
&& isSolid(getId(sections, x, y, z + 1))
&& isSolid(getId(sections, x, y, z - 1));
}
public boolean isSolid(int i) {
if (i != 0) {
Material material = Material.getMaterial(i);
return material != null && Material.getMaterial(i).isOccluding();
}
return false;
}
public int getId(char[] section, int x, int y, int z) {
if (section == null) {
return 0;
}
int j = MainUtil.CACHE_J[y][x][z];
return section[j] >> 4;
}
public int getId(char[][] sections, int x, int y, int z) {
if (x < 0 || x > 15 || z < 0 || z > 15) {
return 1;
}
if (y < 0 || y > 255) {
return 1;
}
int i = MainUtil.CACHE_I[y][x][z];
char[] section = sections[i];
if (section == null) {
return 0;
}
return getId(section, x, y, z);
}
}

View File

@ -1,247 +0,0 @@
package com.plotsquared.bukkit.util.block;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.PlotChunk;
import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper;
import com.plotsquared.bukkit.util.BukkitUtil;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import java.util.Arrays;
public class FastChunk_1_8_3 extends PlotChunk<Chunk> {
public char[][] ids;
public short[] count;
public short[] air;
public short[] relight;
public int[][] biomes;
public Chunk chunk;
public FastChunk_1_8_3(ChunkWrapper chunk) {
super(chunk);
this.ids = new char[16][];
this.count = new short[16];
this.air = new short[16];
this.relight = new short[16];
}
@Override
public Chunk getChunkAbs() {
ChunkWrapper loc = getChunkWrapper();
return BukkitUtil.getWorld(loc.world).getChunkAt(loc.x, loc.z);
}
@Override
public Chunk getChunk() {
if (this.chunk == null) {
ChunkWrapper cl = getChunkWrapper();
this.chunk = Bukkit.getWorld(cl.world).getChunkAt(cl.x, cl.z);
}
return this.chunk;
}
@Override
public void setChunkWrapper(ChunkWrapper loc) {
super.setChunkWrapper(loc);
this.chunk = null;
}
/**
* Get the number of block changes in a specified section.
* @param i
* @return
*/
public int getCount(int i) {
return this.count[i];
}
public int getAir(int i) {
return this.air[i];
}
public void setCount(int i, short value) {
this.count[i] = value;
}
/**
* Get the number of block changes in a specified section.
* @param i
* @return
*/
public int getRelight(int i) {
return this.relight[i];
}
public int getTotalCount() {
int total = 0;
for (int i = 0; i < 16; i++) {
total += this.count[i];
}
return total;
}
public int getTotalRelight() {
if (getTotalCount() == 0) {
Arrays.fill(this.count, (short) 1);
Arrays.fill(this.relight, Short.MAX_VALUE);
return Short.MAX_VALUE;
}
int total = 0;
for (int i = 0; i < 16; i++) {
total += this.relight[i];
}
return total;
}
/**
* Get the raw data for a section.
* @param i
* @return
*/
public char[] getIdArray(int i) {
return this.ids[i];
}
@Override
public void setBlock(int x, int y, int z, int id, byte data) {
int i = MainUtil.CACHE_I[y][x][z];
int j = MainUtil.CACHE_J[y][x][z];
char[] vs = this.ids[i];
if (vs == null) {
vs = this.ids[i] = new char[4096];
this.count[i]++;
} else if (vs[j] == 0) {
this.count[i]++;
}
switch (id) {
case 0:
this.air[i]++;
vs[j] = (char) 1;
return;
case 10:
case 11:
case 39:
case 40:
case 51:
case 74:
case 89:
case 122:
case 124:
case 138:
case 169:
this.relight[i]++;
case 2:
case 4:
case 13:
case 14:
case 15:
case 20:
case 21:
case 22:
case 30:
case 32:
case 37:
case 41:
case 42:
case 45:
case 46:
case 47:
case 48:
case 49:
case 55:
case 56:
case 57:
case 58:
case 60:
case 7:
case 8:
case 9:
case 73:
case 78:
case 79:
case 80:
case 81:
case 82:
case 83:
case 85:
case 87:
case 88:
case 101:
case 102:
case 103:
case 110:
case 112:
case 113:
case 121:
case 129:
case 133:
case 165:
case 166:
case 170:
case 172:
case 173:
case 174:
case 181:
case 182:
case 188:
case 189:
case 190:
case 191:
case 192:
vs[j] = (char) (id << 4);
return;
case 130:
case 76:
case 62:
this.relight[i]++;
case 54:
case 146:
case 61:
case 65:
case 68:
case 50:
if (data < 2) {
data = 2;
}
default:
vs[j] = (char) ((id << 4) + data);
return;
}
}
@Override
public PlotChunk clone() {
FastChunk_1_8_3 toReturn = new FastChunk_1_8_3(getChunkWrapper());
toReturn.air = this.air.clone();
toReturn.count = this.count.clone();
toReturn.relight = this.relight.clone();
toReturn.ids = new char[this.ids.length][];
for (int i = 0; i < this.ids.length; i++) {
char[] matrix = this.ids[i];
if (matrix != null) {
toReturn.ids[i] = new char[matrix.length];
System.arraycopy(matrix, 0, toReturn.ids[i], 0, matrix.length);
}
}
return toReturn;
}
@Override
public PlotChunk shallowClone() {
FastChunk_1_8_3 toReturn = new FastChunk_1_8_3(getChunkWrapper());
toReturn.air = this.air;
toReturn.count = this.count;
toReturn.relight = this.relight;
toReturn.ids = this.ids;
return toReturn;
}
@Override
public void setBiome(int x, int z, int biome) {
if (this.biomes == null) {
this.biomes = new int[16][16];
}
this.biomes[x][z] = biome;
}
}

View File

@ -1,251 +0,0 @@
package com.plotsquared.bukkit.util.block;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.PlotChunk;
import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper;
import com.plotsquared.bukkit.util.BukkitUtil;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import java.util.Arrays;
public class FastChunk_1_9 extends PlotChunk<Chunk> {
public int[][] ids;
public short[] count;
public short[] air;
public short[] relight;
public int[][] biomes;
public Chunk chunk;
public FastChunk_1_9(ChunkWrapper chunk) {
super(chunk);
this.ids = new int[16][];
this.count = new short[16];
this.air = new short[16];
this.relight = new short[16];
}
@Override
public Chunk getChunkAbs() {
ChunkWrapper loc = getChunkWrapper();
return BukkitUtil.getWorld(loc.world).getChunkAt(loc.x, loc.z);
}
@Override
public Chunk getChunk() {
if (this.chunk == null) {
ChunkWrapper cl = getChunkWrapper();
this.chunk = Bukkit.getWorld(cl.world).getChunkAt(cl.x, cl.z);
}
return this.chunk;
}
@Override
public void setChunkWrapper(ChunkWrapper loc) {
super.setChunkWrapper(loc);
this.chunk = null;
}
/**
* Get the number of block changes in a specified section.
* @param i
* @return
*/
public int getCount(int i) {
return this.count[i];
}
public int getAir(int i) {
return this.air[i];
}
public void setCount(int i, short value) {
this.count[i] = value;
}
/**
* Get the number of block changes in a specified section.
* @param i
* @return
*/
public int getRelight(int i) {
return this.relight[i];
}
public int getTotalCount() {
int total = 0;
for (int i = 0; i < 16; i++) {
total += this.count[i];
}
return total;
}
public int getTotalRelight() {
if (getTotalCount() == 0) {
Arrays.fill(this.count, (short) 1);
Arrays.fill(this.relight, Short.MAX_VALUE);
return Short.MAX_VALUE;
}
int total = 0;
for (int i = 0; i < 16; i++) {
total += this.relight[i];
}
return total;
}
/**
* Get the raw data for a section.
* @param i
* @return
*/
public int[] getIdArray(int i) {
return this.ids[i];
}
public int[][] getIdArrays() {
return this.ids;
}
@Override
public void setBlock(int x, int y, int z, int id, byte data) {
int i = MainUtil.CACHE_I[y][x][z];
int j = MainUtil.CACHE_J[y][x][z];
int[] vs = this.ids[i];
if (vs == null) {
vs = this.ids[i] = new int[4096];
this.count[i]++;
} else if (vs[j] == 0) {
this.count[i]++;
}
switch (id) {
case 0:
this.air[i]++;
vs[j] = -1;
return;
case 10:
case 11:
case 39:
case 40:
case 51:
case 74:
case 89:
case 122:
case 124:
case 138:
case 169:
this.relight[i]++;
case 2:
case 4:
case 13:
case 14:
case 15:
case 20:
case 21:
case 22:
case 30:
case 32:
case 37:
case 41:
case 42:
case 45:
case 46:
case 47:
case 48:
case 49:
case 55:
case 56:
case 57:
case 58:
case 60:
case 7:
case 8:
case 9:
case 73:
case 78:
case 79:
case 80:
case 81:
case 82:
case 83:
case 85:
case 87:
case 88:
case 101:
case 102:
case 103:
case 110:
case 112:
case 113:
case 121:
case 129:
case 133:
case 165:
case 166:
case 170:
case 172:
case 173:
case 174:
case 181:
case 182:
case 188:
case 189:
case 190:
case 191:
case 192:
vs[j] = id;
return;
case 130:
case 76:
case 62:
this.relight[i]++;
case 54:
case 146:
case 61:
case 65:
case 68:
case 50:
if (data < 2) {
data = 2;
}
default:
vs[j] = id + (data << 12);
return;
}
}
@Override
public PlotChunk clone() {
FastChunk_1_9 toReturn = new FastChunk_1_9(getChunkWrapper());
toReturn.air = this.air.clone();
toReturn.count = this.count.clone();
toReturn.relight = this.relight.clone();
toReturn.ids = new int[this.ids.length][];
for (int i = 0; i < this.ids.length; i++) {
int[] matrix = this.ids[i];
if (matrix != null) {
toReturn.ids[i] = new int[matrix.length];
System.arraycopy(matrix, 0, toReturn.ids[i], 0, matrix.length);
}
}
return toReturn;
}
@Override
public PlotChunk shallowClone() {
FastChunk_1_9 toReturn = new FastChunk_1_9(getChunkWrapper());
toReturn.air = this.air;
toReturn.count = this.count;
toReturn.relight = this.relight;
toReturn.ids = this.ids;
return toReturn;
}
@Override
public void setBiome(int x, int z, int biome) {
if (this.biomes == null) {
this.biomes = new int[16][16];
}
this.biomes[x][z] = biome;
}
}

View File

@ -1,180 +0,0 @@
package com.plotsquared.bukkit.util.block;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.PlotChunk;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefClass;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod;
import com.intellectualcrafters.plot.util.SetQueue;
import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper;
import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.bukkit.util.SendChunk;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Biome;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
public class FastQueue_1_7 extends SlowQueue {
private final RefClass classBlock = getRefClass("{nms}.Block");
private final RefClass classChunk = getRefClass("{nms}.Chunk");
private final RefClass classWorld = getRefClass("{nms}.World");
private final RefClass classCraftWorld = getRefClass("{cb}.CraftWorld");
private final RefMethod methodGetHandle;
private final RefMethod methodGetChunkAt;
private final RefMethod methodA;
private final RefMethod methodGetById;
private final RefMethod methodInitLighting;
private final SendChunk chunksender;
private final HashMap<ChunkWrapper, Chunk> toUpdate = new HashMap<>();
public FastQueue_1_7() throws RuntimeException {
this.methodGetHandle = this.classCraftWorld.getMethod("getHandle");
this.methodGetChunkAt = this.classWorld.getMethod("getChunkAt", int.class, int.class);
this.methodA = this.classChunk.getMethod("a", int.class, int.class, int.class, this.classBlock, int.class);
this.methodGetById = this.classBlock.getMethod("getById", int.class);
this.methodInitLighting = this.classChunk.getMethod("initLighting");
this.chunksender = new SendChunk();
TaskManager.runTaskRepeat(new Runnable() {
@Override
public void run() {
if (FastQueue_1_7.this.toUpdate.isEmpty()) {
return;
}
int count = 0;
ArrayList<Chunk> chunks = new ArrayList<>();
Iterator<Entry<ChunkWrapper, Chunk>> i = FastQueue_1_7.this.toUpdate.entrySet().iterator();
while (i.hasNext() && (count < 128)) {
chunks.add(i.next().getValue());
i.remove();
count++;
}
if (count == 0) {
return;
}
update(chunks);
}
}, 1);
MainUtil.initCache();
}
public void update(Collection<Chunk> chunks) {
if (chunks.isEmpty()) {
return;
}
if (!MainUtil.canSendChunk) {
for (Chunk chunk : chunks) {
chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ());
chunk.unload(true, false);
chunk.load();
}
return;
}
try {
this.chunksender.sendChunk(chunks);
} catch (Throwable e) {
e.printStackTrace();
MainUtil.canSendChunk = false;
}
}
/**
* This should be overridden by any specialized queues
* @param plotChunk
*/
@Override
public void execute(PlotChunk<Chunk> plotChunk) {
SlowChunk sc = (SlowChunk) plotChunk;
Chunk chunk = plotChunk.getChunk();
ChunkWrapper wrapper = plotChunk.getChunkWrapper();
if (!this.toUpdate.containsKey(wrapper)) {
this.toUpdate.put(wrapper, chunk);
}
chunk.load(true);
World world = chunk.getWorld();
Object w = this.methodGetHandle.of(world).call();
Object c = this.methodGetChunkAt.of(w).call(wrapper.x, wrapper.z);
for (int i = 0; i < sc.result.length; i++) {
PlotBlock[] result2 = sc.result[i];
if (result2 == null) {
continue;
}
for (int j = 0; j < 4096; j++) {
int x = MainUtil.x_loc[i][j];
int y = MainUtil.y_loc[i][j];
int z = MainUtil.z_loc[i][j];
PlotBlock newBlock = result2[j];
if (newBlock.id == -1) {
chunk.getBlock(x, y, z).setData(newBlock.data, false);
continue;
}
Object block = this.methodGetById.call(newBlock.id);
this.methodA.of(c).call(x, y, z, block, newBlock.data);
}
}
int[][] biomes = sc.biomes;
Biome[] values = Biome.values();
if (biomes != null) {
for (int x = 0; x < 16; x++) {
int[] array = biomes[x];
if (array == null) {
continue;
}
for (int z = 0; z < 16; z++) {
int biome = array[z];
if (biome == 0) {
continue;
}
chunk.getBlock(x, 0, z).setBiome(values[biome]);
}
}
}
}
/**
* This should be overridden by any specialized queues
* @param wrap
*/
@Override
public PlotChunk<Chunk> getChunk(ChunkWrapper wrap) {
return new SlowChunk(wrap);
}
/**
* This should be overridden by any specialized queues
* @param chunk
* @param fixAll
*/
@Override
public boolean fixLighting(PlotChunk<Chunk> chunk, boolean fixAll) {
Object c = this.methodGetHandle.of(chunk.getChunk()).call();
this.methodInitLighting.of(c).call();
return true;
}
/**
* This should be overridden by any specialized queues
* @param world
* @param locations
*/
@Override
public void sendChunk(String world, Collection<ChunkLoc> locations) {
World worldObj = BukkitUtil.getWorld(world);
for (ChunkLoc loc : locations) {
ChunkWrapper wrapper = SetQueue.IMP.new ChunkWrapper(world, loc.x, loc.z);
this.toUpdate.remove(wrapper);
}
this.chunksender.sendChunk(world, locations);
}
}

View File

@ -1,469 +0,0 @@
package com.plotsquared.bukkit.util.block;
import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.object.PseudoRandom;
import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.PlotChunk;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefClass;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefConstructor;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefField;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod.RefExecutor;
import com.intellectualcrafters.plot.util.SetQueue;
import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper;
import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.bukkit.util.SendChunk;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
import org.bukkit.Chunk;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.block.Biome;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
public class FastQueue_1_9 extends SlowQueue {
private final Object air;
private final SendChunk chunkSender;
private final HashMap<ChunkWrapper, Chunk> toUpdate = new HashMap<>();
private final RefMethod methodGetHandleChunk;
private final RefMethod methodInitLighting;
private final RefConstructor classBlockPositionConstructor;
private final RefConstructor classChunkSectionConstructor;
private final RefMethod methodW;
private final RefMethod methodAreNeighborsLoaded;
private final RefField fieldSections;
private final RefField fieldWorld;
private final RefMethod methodGetBlocks;
private final RefMethod methodGetType;
private final RefMethod methodSetType;
private final RefMethod methodGetCombinedId;
private final RefMethod methodGetByCombinedId;
private final RefMethod methodGetWorld;
private final RefField tileEntityUnload;
public FastQueue_1_9() throws RuntimeException {
RefClass classCraftChunk = getRefClass("{cb}.CraftChunk");
this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle");
RefClass classChunk = getRefClass("{nms}.Chunk");
this.methodInitLighting = classChunk.getMethod("initLighting");
RefClass classBlockPosition = getRefClass("{nms}.BlockPosition");
this.classBlockPositionConstructor = classBlockPosition.getConstructor(int.class, int.class, int.class);
RefClass classWorld = getRefClass("{nms}.World");
this.tileEntityUnload = classWorld.getField("tileEntityListUnload");
this.methodGetWorld = classChunk.getMethod("getWorld");
this.methodW = classWorld.getMethod("w", classBlockPosition.getRealClass());
this.fieldSections = classChunk.getField("sections");
this.fieldWorld = classChunk.getField("world");
RefClass classBlock = getRefClass("{nms}.Block");
RefClass classIBlockData = getRefClass("{nms}.IBlockData");
this.methodGetCombinedId = classBlock.getMethod("getCombinedId", classIBlockData.getRealClass());
this.methodGetByCombinedId = classBlock.getMethod("getByCombinedId", int.class);
RefClass classChunkSection = getRefClass("{nms}.ChunkSection");
this.methodGetBlocks = classChunkSection.getMethod("getBlocks");
this.methodGetType = classChunkSection.getMethod("getType", int.class, int.class, int.class);
this.methodSetType = classChunkSection.getMethod("setType", int.class, int.class, int.class, classIBlockData.getRealClass());
this.methodAreNeighborsLoaded = classChunk.getMethod("areNeighborsLoaded", int.class);
this.classChunkSectionConstructor = classChunkSection.getConstructor(int.class, boolean.class, char[].class);
this.air = this.methodGetByCombinedId.call(0);
this.chunkSender = new SendChunk();
TaskManager.runTaskRepeat(new Runnable() {
@Override
public void run() {
if (FastQueue_1_9.this.toUpdate.isEmpty()) {
return;
}
int count = 0;
ArrayList<Chunk> chunks = new ArrayList<>();
Iterator<Entry<ChunkWrapper, Chunk>> i = FastQueue_1_9.this.toUpdate.entrySet().iterator();
while (i.hasNext() && count < 128) {
chunks.add(i.next().getValue());
i.remove();
count++;
}
if (count == 0) {
return;
}
update(chunks);
}
}, 1);
MainUtil.initCache();
}
public void update(Collection<Chunk> chunks) {
if (chunks.isEmpty()) {
return;
}
if (!MainUtil.canSendChunk) {
for (Chunk chunk : chunks) {
chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ());
chunk.unload(true, true);
chunk.load();
}
return;
}
try {
this.chunkSender.sendChunk(chunks);
} catch (Throwable e) {
e.printStackTrace();
MainUtil.canSendChunk = false;
}
}
/**
* This should be overridden by any specialized queues
* @param plotChunk
*/
@Override
public void execute(PlotChunk<Chunk> plotChunk) {
FastChunk_1_9 fs = (FastChunk_1_9) plotChunk;
Chunk chunk = plotChunk.getChunk();
World world = chunk.getWorld();
ChunkWrapper wrapper = plotChunk.getChunkWrapper();
if (!this.toUpdate.containsKey(wrapper)) {
this.toUpdate.put(wrapper, chunk);
}
chunk.load(true);
try {
boolean flag = world.getEnvironment() == Environment.NORMAL;
// Sections
Method getHandle = chunk.getClass().getDeclaredMethod("getHandle");
Object c = getHandle.invoke(chunk);
Object w = methodGetWorld.of(c).call();
Class<? extends Object> clazz = c.getClass();
Field sf = clazz.getDeclaredField("sections");
sf.setAccessible(true);
Field tf = clazz.getDeclaredField("tileEntities");
Field entitySlices = clazz.getDeclaredField("entitySlices");
Object[] sections = (Object[]) sf.get(c);
HashMap<?, ?> tiles = (HashMap<?, ?>) tf.get(c);
Collection<Object> tilesUnload = (Collection<Object>) tileEntityUnload.of(w).get();
Collection<?>[] entities = (Collection<?>[]) entitySlices.get(c);
Method xm = null;
Method ym = null;
Method zm = null;
// Trim tiles
Set<Entry<?, ?>> entrySet = (Set<Entry<?, ?>>) (Set<?>) tiles.entrySet();
Iterator<Entry<?, ?>> iterator = entrySet.iterator();
while (iterator.hasNext()) {
Entry<?, ?> tile = iterator.next();
Object pos = tile.getKey();
if (xm == null) {
Class<? extends Object> clazz2 = pos.getClass().getSuperclass();
xm = clazz2.getDeclaredMethod("getX");
ym = clazz2.getDeclaredMethod("getY");
zm = clazz2.getDeclaredMethod("getZ");
}
int lx = (int) xm.invoke(pos) & 15;
int ly = (int) ym.invoke(pos);
int lz = (int) zm.invoke(pos) & 15;
int j = MainUtil.CACHE_I[ly][lx][lz];
int k = MainUtil.CACHE_J[ly][lx][lz];
int[] array = fs.getIdArray(j);
if (array == null) {
continue;
}
if (array[k] != 0) {
tilesUnload.add(tile.getValue());
iterator.remove();
}
}
// Trim entities
for (int i = 0; i < 16; i++) {
if (entities[i] != null && fs.getCount(i) >= 4096) {
entities[i].clear();
}
}
// Efficiently merge sections
for (int j = 0; j < sections.length; j++) {
if (fs.getCount(j) == 0) {
continue;
}
int[] newArray = fs.getIdArray(j);
if (newArray == null) {
continue;
}
Object section = sections[j];
if (section == null || fs.getCount(j) >= 4096) {
char[] array = new char[4096];
for (int i = 0; i < newArray.length; i++) {
int combined = newArray[i];
int id = combined & 4095;
int data = combined >> 12;
array[i] = (char) ((id << 4) + data);
}
section = sections[j] = newChunkSection(j << 4, flag, array);
continue;
}
Object currentArray = getBlocks(section);
RefExecutor setType = this.methodSetType.of(section);
boolean fill = true;
for (int k = 0; k < newArray.length; k++) {
int n = newArray[k];
switch (n) {
case 0:
fill = false;
continue;
case -1: {
fill = false;
int x = MainUtil.x_loc[j][k];
int y = MainUtil.y_loc[j][k];
int z = MainUtil.z_loc[j][k];
setType.call(x, y & 15, z, this.air);
continue;
}
default: {
int x = MainUtil.x_loc[j][k];
int y = MainUtil.y_loc[j][k];
int z = MainUtil.z_loc[j][k];
Object iBlock = this.methodGetByCombinedId.call((int) n);
setType.call(x, y & 15, z, iBlock);
}
}
}
if (fill) {
fs.setCount(j, Short.MAX_VALUE);
}
}
// Clear
} catch (IllegalAccessException | IllegalArgumentException | NoSuchMethodException | SecurityException | InvocationTargetException |
NoSuchFieldException e) {
e.printStackTrace();
}
int[][] biomes = fs.biomes;
Biome[] values = Biome.values();
if (biomes != null) {
for (int x = 0; x < 16; x++) {
int[] array = biomes[x];
if (array == null) {
continue;
}
for (int z = 0; z < 16; z++) {
int biome = array[z];
if (biome == 0) {
continue;
}
chunk.getBlock(x, 0, z).setBiome(values[biome]);
}
}
}
}
public Object newChunkSection(int i, boolean flag, char[] ids) {
return this.classChunkSectionConstructor.create(i, flag, ids);
}
public Object getBlocks(Object obj) {
return this.methodGetBlocks.of(obj).call();
}
/**
* This should be overridden by any specialized queues
* @param wrap
*/
@Override
public PlotChunk<Chunk> getChunk(ChunkWrapper wrap) {
return new FastChunk_1_9(wrap);
}
/**
* This should be overridden by any specialized queues
* @param pc
*/
@Override
public boolean fixLighting(PlotChunk<Chunk> pc, boolean fixAll) {
try {
FastChunk_1_9 bc = (FastChunk_1_9) pc;
Chunk chunk = bc.getChunk();
if (!chunk.isLoaded()) {
chunk.load(false);
} else {
chunk.unload(true, true);
chunk.load(false);
}
// Initialize lighting
Object c = this.methodGetHandleChunk.of(chunk).call();
if (fixAll && !(boolean) this.methodAreNeighborsLoaded.of(c).call(1)) {
World world = chunk.getWorld();
ChunkWrapper wrapper = bc.getChunkWrapper();
String worldname = wrapper.world;
for (int x = wrapper.x - 1; x <= wrapper.x + 1; x++) {
for (int z = wrapper.z - 1; z <= wrapper.z + 1; z++) {
if (x != 0 && z != 0) {
Chunk other = world.getChunkAt(x, z);
while (!other.isLoaded()) {
other.load(true);
}
ChunkManager.manager.loadChunk(worldname, new ChunkLoc(x, z), true);
}
}
}
}
this.methodInitLighting.of(c).call();
if (bc.getTotalRelight() == 0 && !fixAll) {
return true;
}
Object[] sections = (Object[]) this.fieldSections.of(c).get();
Object w = this.fieldWorld.of(c).get();
int X = chunk.getX() << 4;
int Z = chunk.getZ() << 4;
RefExecutor relight = this.methodW.of(w);
for (int j = 0; j < sections.length; j++) {
Object section = sections[j];
if (section == null) {
continue;
}
if (bc.getRelight(j) == 0 && !fixAll || bc.getCount(j) == 0 || bc.getCount(j) >= 4096 && bc.getAir(j) == 0) {
continue;
}
int[] array = bc.getIdArray(j);
if (array != null) {
int l = PseudoRandom.random.random(2);
for (int k = 0; k < array.length; k++) {
int i = array[k];
if (i < 16) {
continue;
}
short id = (short) (i >> 4);
switch (id) { // Lighting
default:
if (!fixAll) {
continue;
}
if ((k & 1) == l) {
l = 1 - l;
continue;
}
case 10:
case 11:
case 39:
case 40:
case 50:
case 51:
case 62:
case 74:
case 76:
case 89:
case 122:
case 124:
case 130:
case 138:
case 169:
int x = MainUtil.x_loc[j][k];
int y = MainUtil.y_loc[j][k];
int z = MainUtil.z_loc[j][k];
if (isSurrounded(bc.getIdArrays(), x, y, z)) {
continue;
}
Object pos = this.classBlockPositionConstructor.create(X + x, y, Z + z);
relight.call(pos);
}
}
}
}
return true;
} catch (Throwable e) {
e.printStackTrace();
}
return false;
}
public boolean isSurrounded(int[][] sections, int x, int y, int z) {
return isSolid(getId(sections, x, y + 1, z))
&& isSolid(getId(sections, x + 1, y - 1, z))
&& isSolid(getId(sections, x - 1, y, z))
&& isSolid(getId(sections, x, y, z + 1))
&& isSolid(getId(sections, x, y, z - 1));
}
public boolean isSolid(int i) {
if (i != 0) {
Material material = Material.getMaterial(i);
return material != null && Material.getMaterial(i).isOccluding();
}
return false;
}
public int getId(int[][] sections, int x, int y, int z) {
if (x < 0 || x > 15 || z < 0 || z > 15) {
return 1;
}
if (y < 0 || y > 255) {
return 1;
}
int i = MainUtil.CACHE_I[y][x][z];
int[] section = sections[i];
if (section == null) {
return 0;
}
int j = MainUtil.CACHE_J[y][x][z];
return section[j];
}
public int getId(Object section, int x, int y, int z) {
int j = MainUtil.CACHE_J[y][x][z];
Object iBlock = this.methodGetType.of(section).call(x, y & 15, z);
return (int) this.methodGetCombinedId.call(iBlock);
}
public int getId(Object[] sections, int x, int y, int z) {
if (x < 0 || x > 15 || z < 0 || z > 15) {
return 1;
}
if (y < 0 || y > 255) {
return 1;
}
int i = MainUtil.CACHE_I[y][x][z];
Object section = sections[i];
if (section == null) {
return 0;
}
// Object array = getBlocks(section);
return getId(section, x, y, z);
}
/**
* This should be overridden by any specialized queues
* @param world
* @param locations
*/
@Override
public void sendChunk(final String world, final Collection<ChunkLoc> locations) {
World worldObj = BukkitUtil.getWorld(world);
for (ChunkLoc loc : locations) {
ChunkWrapper wrapper = SetQueue.IMP.new ChunkWrapper(world, loc.x, loc.z);
this.toUpdate.remove(wrapper);
}
TaskManager.runTaskLater(new Runnable() {
@Override
public void run() {
FastQueue_1_9.this.chunkSender.sendChunk(world, locations);
}
}, 1);
}
}

View File

@ -1,60 +1,103 @@
package com.plotsquared.bukkit.util.block;
import com.intellectualcrafters.plot.object.ChunkWrapper;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.PlotChunk;
import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper;
import com.intellectualcrafters.plot.util.block.ScopedLocalBlockQueue;
import com.plotsquared.bukkit.util.BukkitUtil;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.generator.ChunkGenerator.BiomeGrid;
import org.bukkit.generator.ChunkGenerator.ChunkData;
import org.bukkit.material.MaterialData;
public class GenChunk extends PlotChunk<Chunk> {
public class GenChunk extends ScopedLocalBlockQueue {
public final Biome[] biomes;
public Chunk chunk;
public short[][] result;
public byte[][] result_data;
public ChunkData cd;
public BiomeGrid grid;
public Chunk chunk;
public String world;
public int cx;
public int cz;
public GenChunk(Chunk chunk, ChunkWrapper wrap) {
super(wrap);
if ((this.chunk = chunk) == null && wrap != null) {
World world = BukkitUtil.getWorld(wrap.world);
if (world != null) {
chunk = world.getChunkAt(wrap.x, wrap.z);
}
}
super(null, new Location(null, 0, 0, 0), new Location(null, 15, 255, 15));
this.biomes = Biome.values();
}
@Override
public Chunk getChunkAbs() {
ChunkWrapper wrap = getChunkWrapper();
if (this.chunk == null || wrap.x != this.chunk.getX() || wrap.z != this.chunk.getZ()) {
this.chunk = BukkitUtil.getWorld(wrap.world).getChunkAt(wrap.x, wrap.z);
public void setChunk(Chunk chunk) {
this.chunk = chunk;
}
public void setChunk(ChunkWrapper wrap) {
chunk = null;
world = wrap.world;
cx = wrap.x;
cz = wrap.z;
}
public Chunk getChunk() {
if (chunk == null) {
World worldObj = BukkitUtil.getWorld(world);
if (worldObj != null) {
this.chunk = worldObj.getChunkAt(cx, cz);
}
}
return this.chunk;
return chunk;
}
public ChunkWrapper getChunkWrapper() {
if (chunk == null) {
return new ChunkWrapper(world, cx, cz);
}
return new ChunkWrapper(chunk.getWorld().getName(), chunk.getX(), chunk.getZ());
}
@Override
public void setBiome(int x, int z, int biome) {
this.grid.setBiome(x, z, this.biomes[biome]);
public void fillBiome(String biomeName) {
if (grid == null) {
return;
}
Biome biome = Biome.valueOf(biomeName.toUpperCase());
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
this.grid.setBiome(x, z, biome);
}
}
}
public void setBiome(int x, int z, Biome biome) {
@Override
public boolean setBiome(int x, int z, String biome) {
return setBiome(x, z, Biome.valueOf(biome.toUpperCase()));
}
public boolean setBiome(int x, int z, int biome) {
if (this.grid != null) {
this.grid.setBiome(x, z, this.biomes[biome]);
return true;
}
return false;
}
public boolean setBiome(int x, int z, Biome biome) {
if (this.grid != null) {
this.grid.setBiome(x, z, biome);
return true;
}
return false;
}
@Override
public void setBlock(int x, int y, int z, int id, byte data) {
public boolean setBlock(int x, int y, int z, int id, int data) {
if (this.result == null) {
this.cd.setBlock(x, y, z, id, data);
return;
this.cd.setBlock(x, y, z, id, (byte) data);
return true;
}
int i = MainUtil.CACHE_I[y][x][z];
short[] v = this.result[i];
@ -68,13 +111,59 @@ public class GenChunk extends PlotChunk<Chunk> {
if (vd == null) {
this.result_data[i] = vd = new byte[4096];
}
vd[j] = data;
vd[j] = (byte) data;
}
return true;
}
@Override
public PlotChunk clone() {
GenChunk toReturn = new GenChunk(getChunkAbs(), getChunkWrapper());
public PlotBlock getBlock(int x, int y, int z) {
int i = MainUtil.CACHE_I[y][x][z];
if (result == null) {
MaterialData md = cd.getTypeAndData(x, y, z);
return PlotBlock.get(md.getItemTypeId(), md.getData());
}
short[] array = result[i];
if (array == null) {
return PlotBlock.get(0, 0);
}
int j = MainUtil.CACHE_J[y][x][z];
short id = array[j];
if (id == 0) {
return PlotBlock.get(id, 0);
}
byte[] dataArray = result_data[i];
if (dataArray == null) {
return PlotBlock.get(id, 0);
}
return PlotBlock.get(id, dataArray[j]);
}
public int getX() {
return chunk == null ? cx : chunk.getX();
}
public int getZ() {
return chunk == null ? cz : chunk.getZ();
}
@Override
public String getWorld() {
return chunk == null ? world : chunk.getWorld().getName();
}
@Override
public Location getMax() {
return new Location(getWorld(), 15 + (getX() << 4), 255, 15 + (getZ() << 4));
}
@Override
public Location getMin() {
return new Location(getWorld(), getX() << 4, 0, getZ() << 4);
}
public GenChunk clone() {
GenChunk toReturn = new GenChunk(chunk, new ChunkWrapper(getWorld(), chunk.getX(), chunk.getZ()));
if (this.result != null) {
for (int i = 0; i < this.result.length; i++) {
short[] matrix = this.result[i];
@ -95,9 +184,8 @@ public class GenChunk extends PlotChunk<Chunk> {
return toReturn;
}
@Override
public PlotChunk shallowClone() {
GenChunk toReturn = new GenChunk(getChunkAbs(), getChunkWrapper());
public GenChunk shallowClone() {
GenChunk toReturn = new GenChunk(chunk, new ChunkWrapper(getWorld(), getX(), getZ()));
toReturn.result = this.result;
toReturn.result_data = this.result_data;
toReturn.cd = this.cd;

View File

@ -1,60 +0,0 @@
package com.plotsquared.bukkit.util.block;
import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.PlotChunk;
import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper;
import com.plotsquared.bukkit.util.BukkitUtil;
import org.bukkit.Chunk;
public class SlowChunk extends PlotChunk<Chunk> {
public PlotBlock[][] result = new PlotBlock[16][];
public int[][] biomes;
public SlowChunk(ChunkWrapper chunk) {
super(chunk);
}
@Override
public Chunk getChunkAbs() {
ChunkWrapper loc = getChunkWrapper();
return BukkitUtil.getWorld(loc.world).getChunkAt(loc.x, loc.z);
}
@Override
public void setBiome(int x, int z, int biome) {
if (this.biomes == null) {
this.biomes = new int[16][16];
}
this.biomes[x][z] = biome;
}
@Override
public void setBlock(int x, int y, int z, int id, byte data) {
if (this.result[y >> 4] == null) {
this.result[y >> 4] = new PlotBlock[4096];
}
this.result[MainUtil.CACHE_I[y][x][z]][MainUtil.CACHE_J[y][x][z]] = new PlotBlock((short) id, data);
}
@Override
public PlotChunk clone() {
SlowChunk toReturn = new SlowChunk(getChunkWrapper());
for (int i = 0; i < this.result.length; i++) {
PlotBlock[] matrix = this.result[i];
if (matrix != null) {
toReturn.result[i] = new PlotBlock[matrix.length];
System.arraycopy(matrix, 0, toReturn.result[i], 0, matrix.length);
}
}
return toReturn;
}
@Override
public PlotChunk shallowClone() {
SlowChunk toReturn = new SlowChunk(getChunkWrapper());
toReturn.result = this.result;
return toReturn;
}
}

View File

@ -1,281 +0,0 @@
package com.plotsquared.bukkit.util.block;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.PlotChunk;
import com.intellectualcrafters.plot.util.PlotQueue;
import com.intellectualcrafters.plot.util.SetQueue;
import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper;
import org.bukkit.Chunk;
import org.bukkit.block.Biome;
import org.bukkit.block.Block;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
public class SlowQueue implements PlotQueue<Chunk> {
private final ConcurrentHashMap<ChunkWrapper, PlotChunk<Chunk>> blocks = new ConcurrentHashMap<>();
public SlowQueue() {
MainUtil.initCache();
}
@Override
public boolean setBlock(String world, int x, int y, int z, short id, byte data) {
if (y > 255 || y < 0) {
return false;
}
ChunkWrapper wrap = SetQueue.IMP.new ChunkWrapper(world, x >> 4, z >> 4);
x = x & 15;
z = z & 15;
PlotChunk<Chunk> result = this.blocks.get(wrap);
if (result == null) {
result = getChunk(wrap);
result.setBlock(x, y, z, id, data);
PlotChunk<Chunk> previous = this.blocks.put(wrap, result);
if (previous == null) {
return true;
}
this.blocks.put(wrap, previous);
result = previous;
}
result.setBlock(x, y, z, id, data);
return true;
}
@Override
public void setChunk(PlotChunk<Chunk> chunk) {
this.blocks.put(chunk.getChunkWrapper(), chunk);
}
@Override
public PlotChunk<Chunk> next() {
if (!PS.get().isMainThread(Thread.currentThread())) {
throw new IllegalStateException("Must be called from main thread!");
}
try {
if (this.blocks.isEmpty()) {
return null;
}
Iterator<Entry<ChunkWrapper, PlotChunk<Chunk>>> iter = this.blocks.entrySet().iterator();
PlotChunk<Chunk> toReturn = iter.next().getValue();
if (SetQueue.IMP.isWaiting()) {
return null;
}
iter.remove();
execute(toReturn);
fixLighting(toReturn, true);
return toReturn;
} catch (Throwable e) {
e.printStackTrace();
return null;
}
}
@Override
public PlotChunk<Chunk> next(ChunkWrapper wrap, boolean fixLighting) {
if (!PS.get().isMainThread(Thread.currentThread())) {
throw new IllegalStateException("Must be called from main thread!");
}
try {
if (this.blocks.isEmpty()) {
return null;
}
PlotChunk<Chunk> toReturn = this.blocks.remove(wrap);
if (toReturn == null) {
return null;
}
execute(toReturn);
fixLighting(toReturn, fixLighting);
return toReturn;
} catch (Throwable e) {
e.printStackTrace();
return null;
}
}
@Override
public void clear() {
this.blocks.clear();
}
/**
* This should be overridden by any specialized queues.
* @param plotChunk
*/
public void execute(PlotChunk<Chunk> plotChunk) {
SlowChunk sc = (SlowChunk) plotChunk;
Chunk chunk = plotChunk.getChunk();
chunk.load(true);
for (int i = 0; i < sc.result.length; i++) {
PlotBlock[] result2 = sc.result[i];
if (result2 == null) {
continue;
}
for (int j = 0; j < 4096; j++) {
int x = MainUtil.x_loc[i][j];
int y = MainUtil.y_loc[i][j];
int z = MainUtil.z_loc[i][j];
Block block = chunk.getBlock(x, y, z);
PlotBlock newBlock = result2[j];
if (newBlock == null) {
continue;
}
switch (newBlock.id) {
case -1:
if (block.getData() == newBlock.data) {
continue;
}
block.setData(newBlock.data);
continue;
case 0:
case 2:
case 4:
case 13:
case 14:
case 15:
case 20:
case 21:
case 22:
case 25:
case 30:
case 32:
case 37:
case 39:
case 40:
case 41:
case 42:
case 45:
case 46:
case 47:
case 48:
case 49:
case 51:
case 52:
case 54:
case 55:
case 56:
case 57:
case 58:
case 60:
case 61:
case 62:
case 7:
case 8:
case 9:
case 10:
case 11:
case 73:
case 74:
case 78:
case 79:
case 80:
case 81:
case 82:
case 83:
case 84:
case 85:
case 87:
case 88:
case 101:
case 102:
case 103:
case 110:
case 112:
case 113:
case 117:
case 121:
case 122:
case 123:
case 124:
case 129:
case 133:
case 138:
case 137:
case 140:
case 165:
case 166:
case 169:
case 170:
case 172:
case 173:
case 174:
case 176:
case 177:
case 181:
case 182:
case 188:
case 189:
case 190:
case 191:
case 192:
if (block.getTypeId() == newBlock.id) {
continue;
}
block.setTypeId(newBlock.id, false);
continue;
default:
if (block.getTypeId() == newBlock.id && block.getData() == newBlock.data) {
continue;
}
if (newBlock.data == 0) {
block.setTypeId(newBlock.id, false);
} else {
block.setTypeIdAndData(newBlock.id, newBlock.data, false);
}
continue;
}
}
}
int[][] biomes = sc.biomes;
Biome[] values = Biome.values();
if (biomes != null) {
for (int x = 0; x < 16; x++) {
int[] array = biomes[x];
if (array == null) {
continue;
}
for (int z = 0; z < 16; z++) {
int biome = array[z];
if (biome == 0) {
continue;
}
chunk.getBlock(x, 0, z).setBiome(values[biome]);
}
}
}
}
/**
* This should be overridden by any specialized queues.
* @param wrap
*/
@Override
public PlotChunk<Chunk> getChunk(ChunkWrapper wrap) {
return new SlowChunk(wrap);
}
/**
* This should be overridden by any specialized queues.
* @param fixAll
*/
@Override
public boolean fixLighting(PlotChunk<Chunk> chunk, boolean fixAll) {
// Do nothing
return true;
}
/**
* This should be overridden by any specialized queues.
* @param locations
*/
@Override
public void sendChunk(String world, Collection<ChunkLoc> locations) {
// Do nothing
}
}

View File

@ -0,0 +1,12 @@
package com.plotsquared.bukkit.uuid;
import java.io.File;
import java.io.FilenameFilter;
public class DatFileFilter implements FilenameFilter {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".dat");
}
}

View File

@ -1,28 +1,22 @@
package com.plotsquared.bukkit.uuid;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.Sets;
import com.google.common.io.ByteSource;
import com.google.common.io.InputSupplier;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.object.OfflinePlotPlayer;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.object.StringWrapper;
import com.intellectualcrafters.plot.util.ExpireManager;
import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.util.UUIDHandlerImplementation;
import com.intellectualcrafters.plot.util.expiry.ExpireManager;
import com.intellectualcrafters.plot.uuid.UUIDWrapper;
import com.plotsquared.bukkit.util.NbtFactory;
import org.bukkit.Bukkit;
import org.bukkit.World;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
@ -30,6 +24,8 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.World;
public class FileUUIDHandler extends UUIDHandlerImplementation {
@ -55,10 +51,10 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
@Override
public void run() {
PS.debug(C.PREFIX + "&6Starting player data caching for: " + world);
File uuidfile = new File(PS.get().IMP.getDirectory(), "uuids.txt");
if (uuidfile.exists()) {
File uuidFile = new File(PS.get().IMP.getDirectory(), "uuids.txt");
if (uuidFile.exists()) {
try {
List<String> lines = Files.readAllLines(uuidfile.toPath(), StandardCharsets.UTF_8);
List<String> lines = Files.readAllLines(uuidFile.toPath(), StandardCharsets.UTF_8);
for (String line : lines) {
try {
line = line.trim();
@ -84,18 +80,12 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
e.printStackTrace();
}
}
if (Settings.TWIN_MODE_UUID) {
HashBiMap<StringWrapper, UUID> toAdd = HashBiMap.create(new HashMap<StringWrapper, UUID>());
toAdd.put(new StringWrapper("*"), DBFunc.everyone);
HashBiMap<StringWrapper, UUID> toAdd = HashBiMap.create(new HashMap<StringWrapper, UUID>());
if (Settings.UUID.NATIVE_UUID_PROVIDER) {
HashSet<UUID> all = UUIDHandler.getAllUUIDS();
PS.debug("&aFast mode UUID caching enabled!");
File playerdataFolder = new File(container, world + File.separator + "playerdata");
String[] dat = playerdataFolder.list(new FilenameFilter() {
@Override
public boolean accept(File f, String s) {
return s.endsWith(".dat");
}
});
File playerDataFolder = new File(container, world + File.separator + "playerdata");
String[] dat = playerDataFolder.list(new DatFileFilter());
boolean check = all.isEmpty();
if (dat != null) {
for (String current : dat) {
@ -103,16 +93,20 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
try {
UUID uuid = UUID.fromString(s);
if (check || all.remove(uuid)) {
File file = new File(playerdataFolder + File.separator + current);
InputSupplier<FileInputStream> is = com.google.common.io.Files.newInputStreamSupplier(file);
File file = new File(playerDataFolder, current);
ByteSource is = com.google.common.io.Files.asByteSource(file);
NbtFactory.NbtCompound compound = NbtFactory.fromStream(is, NbtFactory.StreamOptions.GZIP_COMPRESSION);
NbtFactory.NbtCompound bukkit = (NbtFactory.NbtCompound) compound.get("bukkit");
String name = (String) bukkit.get("lastKnownName");
long last = (long) bukkit.get("lastPlayed");
if (ExpireManager.IMP != null) {
ExpireManager.IMP.storeDate(uuid, last);
if (!compound.containsKey("bukkit")) {
PS.debug("ERROR: Player data (" + uuid.toString() + ".dat) does not contain the the key \"bukkit\"");
} else {
NbtFactory.NbtCompound bukkit = (NbtFactory.NbtCompound) compound.get("bukkit");
String name = (String) bukkit.get("lastKnownName");
long last = (long) bukkit.get("lastPlayed");
if (ExpireManager.IMP != null) {
ExpireManager.IMP.storeDate(uuid, last);
}
toAdd.put(new StringWrapper(name), uuid);
}
toAdd.put(new StringWrapper(name), uuid);
}
} catch (Exception e) {
e.printStackTrace();
@ -130,43 +124,29 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
PS.debug("Failed to cache: " + all.size() + " uuids - slowly processing all files");
}
}
HashBiMap<StringWrapper, UUID> toAdd = HashBiMap.create(new HashMap<StringWrapper, UUID>());
toAdd.put(new StringWrapper("*"), DBFunc.everyone);
HashSet<String> worlds = new HashSet<>();
worlds.add(world);
worlds.add("world");
HashSet<String> worlds = Sets.newHashSet(world, "world");
HashSet<UUID> uuids = new HashSet<>();
HashSet<String> names = new HashSet<>();
File playerdataFolder = null;
File playerDataFolder = null;
for (String worldName : worlds) {
// Getting UUIDs
playerdataFolder = new File(container, worldName + File.separator + "playerdata");
String[] dat = playerdataFolder.list(new FilenameFilter() {
@Override
public boolean accept(File f, String s) {
return s.endsWith(".dat");
}
});
playerDataFolder = new File(container, worldName + File.separator + "playerdata");
String[] dat = playerDataFolder.list(new DatFileFilter());
if ((dat != null) && (dat.length != 0)) {
for (String current : dat) {
String s = current.replaceAll(".dat$", "");
try {
UUID uuid = UUID.fromString(s);
uuids.add(uuid);
} catch (Exception e) {
PS.debug(C.PREFIX + "Invalid playerdata: " + current);
} catch (Exception ignored) {
PS.debug(C.PREFIX + "Invalid PlayerData: " + current);
}
}
break;
}
// Getting names
File playersFolder = new File(worldName + File.separator + "players");
dat = playersFolder.list(new FilenameFilter() {
@Override
public boolean accept(File f, String s) {
return s.endsWith(".dat");
}
});
dat = playersFolder.list(new DatFileFilter());
if ((dat != null) && (dat.length != 0)) {
for (String current : dat) {
names.add(current.replaceAll(".dat$", ""));
@ -176,30 +156,37 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
}
for (UUID uuid : uuids) {
try {
File file = new File(playerdataFolder + File.separator + uuid.toString() + ".dat");
File file = new File(playerDataFolder + File.separator + uuid.toString() + ".dat");
if (!file.exists()) {
continue;
}
ByteSource is = com.google.common.io.Files.asByteSource(file);
NbtFactory.NbtCompound compound = NbtFactory.fromStream(is, NbtFactory.StreamOptions.GZIP_COMPRESSION);
NbtFactory.NbtCompound bukkit = (NbtFactory.NbtCompound) compound.get("bukkit");
String name = (String) bukkit.get("lastKnownName");
long last = (long) bukkit.get("lastPlayed");
if (Settings.OFFLINE_MODE) {
if (Settings.UUID_LOWERCASE && !name.toLowerCase().equals(name)) {
uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name);
} else {
long most = (long) compound.get("UUIDMost");
long least = (long) compound.get("UUIDLeast");
uuid = new UUID(most, least);
if (!compound.containsKey("bukkit")) {
PS.debug("ERROR: Player data (" + uuid.toString() + ".dat) does not contain the the key \"bukkit\"");
} else {
NbtFactory.NbtCompound bukkit = (NbtFactory.NbtCompound) compound.get("bukkit");
String name = (String) bukkit.get("lastKnownName");
StringWrapper wrap = new StringWrapper(name);
if (!toAdd.containsKey(wrap)) {
long last = (long) bukkit.get("lastPlayed");
if (Settings.UUID.OFFLINE) {
if (Settings.UUID.FORCE_LOWERCASE && !name.toLowerCase().equals(name)) {
uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name);
} else {
long most = (long) compound.get("UUIDMost");
long least = (long) compound.get("UUIDLeast");
uuid = new UUID(most, least);
}
}
if (ExpireManager.IMP != null) {
ExpireManager.IMP.storeDate(uuid, last);
}
toAdd.put(wrap, uuid);
}
}
if (ExpireManager.IMP != null) {
ExpireManager.IMP.storeDate(uuid, last);
}
toAdd.put(new StringWrapper(name), uuid);
} catch (Throwable e) {
PS.debug(C.PREFIX + "&6Invalid playerdata: " + uuid.toString() + ".dat");
} catch (Exception ignored) {
PS.debug(C.PREFIX + "&6Invalid PlayerData: " + uuid.toString() + ".dat");
}
}
for (String name : names) {
@ -214,10 +201,12 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
if (last != 0) {
String name = op.getName();
StringWrapper wrap = new StringWrapper(name);
UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(op);
toAdd.put(wrap, uuid);
if (ExpireManager.IMP != null) {
ExpireManager.IMP.storeDate(uuid, last);
if (!toAdd.containsKey(wrap)) {
UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(op);
toAdd.put(wrap, uuid);
if (ExpireManager.IMP != null) {
ExpireManager.IMP.storeDate(uuid, last);
}
}
}
}

View File

@ -14,6 +14,7 @@ import org.bukkit.OfflinePlayer;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.UUID;
@ -48,11 +49,9 @@ public class OfflineUUIDWrapper extends UUIDWrapper {
@Override
public OfflinePlotPlayer getOfflinePlayer(UUID uuid) {
BiMap<UUID, StringWrapper> map = UUIDHandler.getUuidMap().inverse();
String name;
try {
String name = null;
if (map.containsKey(uuid)) {
name = map.get(uuid).value;
} catch (NullPointerException e) {
name = null;
}
if (name != null) {
OfflinePlayer op = Bukkit.getOfflinePlayer(name);
@ -81,7 +80,7 @@ public class OfflineUUIDWrapper extends UUIDWrapper {
@SuppressWarnings("unchecked") Collection<? extends Player> p = (Collection<? extends Player>) players;
return p.toArray(new Player[p.size()]);
}
} catch (Exception e) {
} catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException ignored) {
PS.debug("Failed to resolve online players");
this.getOnline = null;
Collection<? extends Player> onlinePlayers = Bukkit.getOnlinePlayers();

View File

@ -4,19 +4,14 @@ import com.google.common.collect.HashBiMap;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.database.SQLite;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.object.StringWrapper;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.util.UUIDHandlerImplementation;
import com.intellectualcrafters.plot.uuid.UUIDWrapper;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
@ -30,6 +25,10 @@ import java.util.ArrayDeque;
import java.util.Collections;
import java.util.HashMap;
import java.util.UUID;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class SQLUUIDHandler extends UUIDHandlerImplementation {
@ -41,7 +40,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
public SQLUUIDHandler(UUIDWrapper wrapper) {
super(wrapper);
this.sqlite = new SQLite("./plugins/PlotSquared/usercache.db");
this.sqlite = new SQLite(MainUtil.getFile(PS.get().IMP.getDirectory(), "usercache.db"));
try {
this.sqlite.openConnection();
} catch (ClassNotFoundException | SQLException e) {
@ -50,7 +49,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
try (PreparedStatement stmt = getConnection().prepareStatement(
"CREATE TABLE IF NOT EXISTS `usercache` (uuid VARCHAR(32) NOT NULL, username VARCHAR(32) NOT NULL, PRIMARY KEY (uuid, username)"
+ ")")) {
+ ')')) {
stmt.execute();
} catch (SQLException e) {
e.printStackTrace();
@ -74,17 +73,15 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
public void run() {
try {
HashBiMap<StringWrapper, UUID> toAdd = HashBiMap.create(new HashMap<StringWrapper, UUID>());
PreparedStatement statement = getConnection().prepareStatement("SELECT `uuid`, `username` FROM `usercache`");
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
StringWrapper username = new StringWrapper(resultSet.getString("username"));
UUID uuid = UUID.fromString(resultSet.getString("uuid"));
toAdd.put(new StringWrapper(username.value), uuid);
try (PreparedStatement statement = getConnection().prepareStatement("SELECT `uuid`, `username` FROM `usercache`");
ResultSet resultSet = statement.executeQuery()) {
while (resultSet.next()) {
StringWrapper username = new StringWrapper(resultSet.getString("username"));
UUID uuid = UUID.fromString(resultSet.getString("uuid"));
toAdd.put(new StringWrapper(username.value), uuid);
}
}
statement.close();
add(toAdd);
add(new StringWrapper("*"), DBFunc.everyone);
// This should be called as long as there are some unknown plots
final ArrayDeque<UUID> toFetch = new ArrayDeque<>();
for (UUID u : UUIDHandler.getAllUUIDS()) {
@ -104,7 +101,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
public void run() {
// If the file based UUID handler didn't cache it, then we can't cache offline mode
// Also, trying to cache based on files again, is useless as that's what the file based uuid cacher does
if (Settings.OFFLINE_MODE) {
if (Settings.UUID.OFFLINE) {
if (whenDone != null) {
whenDone.run();
}
@ -151,7 +148,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
@Override
public void fetchUUID(final String name, final RunnableVal<UUID> ifFetch) {
PS.debug(C.PREFIX + "UUID for '" + name + "' was null. We'll cache this from the mojang servers!");
PS.debug(C.PREFIX + "UUID for '" + name + "' was null. We'll cache this from the Mojang servers!");
if (ifFetch == null) {
return;
}
@ -176,7 +173,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
String id = (String) jsonProfile.get("id");
String name = (String) jsonProfile.get("name");
ifFetch.value = UUID.fromString(
id.substring(0, 8) + "-" + id.substring(8, 12) + "-" + id.substring(12, 16) + "-" + id.substring(16, 20) + "-" + id
id.substring(0, 8) + '-' + id.substring(8, 12) + '-' + id.substring(12, 16) + '-' + id.substring(16, 20) + '-' + id
.substring(20, 32));
} catch (IOException | ParseException e) {
e.printStackTrace();
@ -231,7 +228,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
statement.setString(1, name.value);
statement.setString(2, uuid.toString());
statement.execute();
PS.debug(C.PREFIX + "Name change for '" + uuid + "' to '" + name.value + "'");
PS.debug(C.PREFIX + "Name change for '" + uuid + "' to '" + name.value + '\'');
} catch (SQLException e) {
e.printStackTrace();
}

View File

@ -4,14 +4,14 @@ version: ${version}
load: STARTUP
description: >
Easy, yet powerful Plot World generation and management.
authors: [Citymonstret, Empire92]
authors: [Citymonstret, Empire92, MattBDev]
softdepend: [WorldEdit, BarAPI, CameraAPI, Vault]
loadbefore: [MultiWorld, Multiverse-Core]
database: false
commands:
plots:
description: PlotSquared PlotSquared command.
aliases: [p,plot,ps,plotsquared,p2,2]
description: Plot command.
aliases: [p,plot,ps,plotsquared,p2,2,plotme]
permission: plots.use
permission-message: "You are lacking the permission node 'plots.use'"
permissions:
@ -153,3 +153,156 @@ permissions:
default: op
plots.confirm.bypass:
default: false
plotme.use:
description: Gives default user commands
children:
plots.permpack.basic: true
plots.plot.1: true
plotme.admin:
description: Gives default administrator commands
children:
plots.admin: true
plotme.use.middle:
children:
plots.middle: true
plotme.use.buy:
children:
plots.buy: true
plotme.use.sell:
children:
plots.set: true
plots.flag: true
plots.set.flag: true
plots.set.price.*: true
plotme.use.dispose:
children:
plots.delete: true
plotme.use.done:
children:
plots.done: true
plotme.use.claim:
children:
plots.claim: true
plotme.use.auto:
children:
plots.auto: true
plotme.use.reset:
children:
plots.delete: true
plotme.use.home:
children:
plots.home: true
plotme.use.info:
children:
plots.info: true
plotme.use.biome:
children:
plots.set: true
plots.set.biome: true
plotme.use.clear:
children:
plots.clear: true
plotme.use.list:
children:
plots.list: true
plots.list.forsale: true
plots.list.mine: true
plots.list.shared: true
plotme.use.add:
children:
plots.add: true
plots.trust: true
plots.add.everyone: true
plots.trust.everyone: true
plotme.use.deny:
children:
plots.deny: true
plots.deny.everyone: true
plotme.use.remove:
children:
plots.remove: true
plotme.use.undeny:
children:
plots.remove: true
plotme.use.protect:
children:
plots.set: true
plots.flag: true
plots.set.flag: true
plots.set.keep.*: true
plotme.use.nameplot:
children:
plots.set.alias: true
plotme.limit.*:
children:
plots.plot.*: true
plotme.limit.1:
children:
plots.plot.1: true
plotme.limit.5:
children:
plots.plot.5: true
plotme.limit.10:
children:
plots.plot.10: true
plotme.admin.home.other:
children:
plots.plot.: true
plotme.admin.clear:
children:
plots.admin.command.clear: true
plotme.admin.reset:
children:
plots.admin.command.delete: true
plotme.admin.add:
children:
plots.admin.command.add: true
plotme.admin.deny:
children:
plots.admin.command.deny: true
plotme.admin.remove:
children:
plots.admin.command.remove: true
plotme.admin.undeny:
children:
plots.admin.command.remove: true
plotme.admin.bypassdeny:
children:
plots.admin.entry.denied: true
plotme.admin.setowner:
children:
plots.admin.command.setowner: true
plotme.admin.move:
children:
plots.admin.command.move: true
plotme.admin.weanywhere:
children:
plots.worldedit.bypass: true
plotme.admin.list:
children:
plots.list.world: true
plots.list.world.*: true
plots.list.top: true
plots.list.all: true
plots.list.unowned: true
plots.list.unknown: true
plots.list.player: true
plots.list.done: true
plots.list.expired: true
plots.list.fuzzy: true
plots.list.area: true
plotme.admin.dispose:
children:
plots.admin.command.delete: true
plotme.admin.done:
children:
plots.admin.command.done: true
plotme.admin.expired:
children:
plots.list.expired: true
plotme.admin.buildanywhere:
children:
plots.admin.vehicle.*: true
plots.admin.interact.*: true
plots.admin.build.*: true
plots.admin.destroy.*: true

View File

@ -7,5 +7,5 @@ dependencies {
sourceCompatibility = 1.7
targetCompatibility = 1.7
jar.archiveName="PlotSquared-API-${parent.version}.jar"
jar.archiveName = rootProject.name + "-Core-${parent.version}.jar"
jar.destinationDir = file '../target'

View File

@ -3,80 +3,82 @@ package com.intellectualcrafters.configuration;
import java.util.Map;
/**
* Represents a source of configurable options and settings
* Represents a source of configurable options and settings.
*/
public interface Configuration extends ConfigurationSection {
/**
* Sets the default value of the given path as provided.
* <p>
* If no source {@link Configuration} was provided as a default
*
* <p>If no source {@link Configuration} was provided as a default
* collection, then a new {@link MemoryConfiguration} will be created to
* hold the new default value.
* <p>
* If value is null, the value will be removed from the default
* Configuration source.
* hold the new default value.</p>
*
* <p>If value is null, the value will be removed from the default
* Configuration source.</p>
*
* @param path Path of the value to set.
* @param value Value to set the default to.
* @throws IllegalArgumentException Thrown if path is null.
*/
@Override void addDefault(final String path, final Object value);
@Override void addDefault(String path, Object value);
/**
* Sets the default values of the given paths as provided.
* <p>
* If no source {@link Configuration} was provided as a default
*
* <p>If no source {@link Configuration} was provided as a default
* collection, then a new {@link MemoryConfiguration} will be created to
* hold the new default values.
* hold the new default values.</p>
*
* @param defaults A map of Path->Values to add to defaults.
* @throws IllegalArgumentException Thrown if defaults is null.
*/
void addDefaults(final Map<String, Object> defaults);
void addDefaults(Map<String, Object> defaults);
/**
* Sets the default values of the given paths as provided.
* <p>
* If no source {@link Configuration} was provided as a default
*
* <p>If no source {@link Configuration} was provided as a default
* collection, then a new {@link MemoryConfiguration} will be created to
* hold the new default value.
* <p>
* This method will not hold a reference to the specified Configuration,
* hold the new default value.</p>
*
* <p>This method will not hold a reference to the specified Configuration,
* nor will it automatically update if that Configuration ever changes. If
* you require this, you should set the default source with {@link
* #setDefaults(com.intellectualcrafters.configuration.Configuration)}.
* you check this, you should set the default source with {@link
* #setDefaults(Configuration)}.</p>
*
* @param defaults A configuration holding a list of defaults to copy.
* @throws IllegalArgumentException Thrown if defaults is null or this.
*/
void addDefaults(final Configuration defaults);
/**
* Sets the source of all default values for this {@link Configuration}.
* <p>
* If a previous source was set, or previous default values were defined,
* then they will not be copied to the new source.
*
* @param defaults New source of default values for this configuration.
* @throws IllegalArgumentException Thrown if defaults is null or this.
*/
void setDefaults(final Configuration defaults);
void addDefaults(Configuration defaults);
/**
* Gets the source {@link Configuration} for this configuration.
*
* <p>
* If no configuration source was set, but default values were added, then
* a {@link MemoryConfiguration} will be returned. If no source was set
* and no defaults were set, then this method will return null.
* and no defaults were set, then this method will return null.</p>
*
* @return Configuration source for default values, or null if none exist.
*/
Configuration getDefaults();
/**
* Gets the {@link ConfigurationOptions} for this {@link Configuration}.
* Sets the source of all default values for this {@link Configuration}.
*
* <p>
* All setters through this method are chainable.
* If a previous source was set, or previous default values were defined,
* then they will not be copied to the new source.</p>
*
* @param defaults New source of default values for this configuration.
* @throws IllegalArgumentException Thrown if defaults is null or this.
*/
void setDefaults(Configuration defaults);
/**
* Gets the {@link ConfigurationOptions} for this {@link Configuration}.
*
* <p>All setters through this method are chainable.</p>
*
* @return Options for this configuration
*/

View File

@ -2,14 +2,14 @@ package com.intellectualcrafters.configuration;
/**
* Various settings for controlling the input and output of a {@link
* Configuration}
* Configuration}.
*/
public class ConfigurationOptions {
class ConfigurationOptions {
private final Configuration configuration;
private char pathSeparator = '.';
private boolean copyDefaults = false;
private final Configuration configuration;
protected ConfigurationOptions(final Configuration configuration) {
protected ConfigurationOptions(Configuration configuration) {
this.configuration = configuration;
}
@ -24,9 +24,9 @@ public class ConfigurationOptions {
/**
* Gets the char that will be used to separate {@link
* ConfigurationSection}s
* <p>
* This value does not affect how the {@link Configuration} is stored,
* ConfigurationSection}s.
*
* <p>This value does not affect how the {@link Configuration} is stored,
* only in how you access the data. The default value is '.'.
*
* @return Path separator
@ -37,15 +37,15 @@ public class ConfigurationOptions {
/**
* Sets the char that will be used to separate {@link
* ConfigurationSection}s
* <p>
* This value does not affect how the {@link Configuration} is stored,
* ConfigurationSection}s.
*
* <p>This value does not affect how the {@link Configuration} is stored,
* only in how you access the data. The default value is '.'.
*
* @param value Path separator
* @return This object, for chaining
*/
public ConfigurationOptions pathSeparator(final char value) {
public ConfigurationOptions pathSeparator(char value) {
pathSeparator = value;
return this;
}
@ -53,13 +53,13 @@ public class ConfigurationOptions {
/**
* Checks if the {@link Configuration} should copy values from its default
* {@link Configuration} directly.
* <p>
* If this is true, all values in the default Configuration will be
*
* <p>If this is true, all values in the default Configuration will be
* directly copied, making it impossible to distinguish between values
* that were set and values that are provided by default. As a result,
* {@link ConfigurationSection#contains(java.lang.String)} will always
* {@link ConfigurationSection#contains(String)} will always
* return the same value as {@link
* ConfigurationSection#isSet(java.lang.String)}. The default value is
* ConfigurationSection#isSet(String)}. The default value is
* false.
*
* @return Whether or not defaults are directly copied
@ -71,19 +71,19 @@ public class ConfigurationOptions {
/**
* Sets if the {@link Configuration} should copy values from its default
* {@link Configuration} directly.
* <p>
* If this is true, all values in the default Configuration will be
*
* <p>If this is true, all values in the default Configuration will be
* directly copied, making it impossible to distinguish between values
* that were set and values that are provided by default. As a result,
* {@link ConfigurationSection#contains(java.lang.String)} will always
* {@link ConfigurationSection#contains(String)} will always
* return the same value as {@link
* ConfigurationSection#isSet(java.lang.String)}. The default value is
* ConfigurationSection#isSet(String)}. The default value is
* false.
*
* @param value Whether or not defaults are directly copied
* @return This object, for chaining
*/
public ConfigurationOptions copyDefaults(final boolean value) {
public ConfigurationOptions copyDefaults(boolean value) {
copyDefaults = value;
return this;
}

View File

@ -5,18 +5,18 @@ import java.util.Map;
import java.util.Set;
/**
* Represents a section of a {@link Configuration}
* Represents a section of a {@link Configuration}.
*/
public interface ConfigurationSection {
/**
* Gets a set containing all keys in this section.
* <p>
* If deep is set to true, then this will contain all the keys within any
*
* <p>If deep is set to true, then this will contain all the keys within any
* child {@link ConfigurationSection}s (and their children, etc). These
* will be in a valid path notation for you to use.
* <p>
* If deep is set to false, then this will contain only the keys of any
*
* <p>If deep is set to false, then this will contain only the keys of any
* direct children, and not their own children.
*
* @param deep Whether or not to get a deep list, as opposed to a shallow
@ -27,12 +27,12 @@ public interface ConfigurationSection {
/**
* Gets a Map containing all keys and their values for this section.
* <p>
* If deep is set to true, then this will contain all the keys and values
*
* <p>If deep is set to true, then this will contain all the keys and values
* within any child {@link ConfigurationSection}s (and their children,
* etc). These keys will be in a valid path notation for you to use.
* <p>
* If deep is set to false, then this will contain only the keys and
*
* <p>If deep is set to false, then this will contain only the keys and
* values of any direct children, and not their own children.
*
* @param deep Whether or not to get a deep list, as opposed to a shallow
@ -43,43 +43,44 @@ public interface ConfigurationSection {
/**
* Checks if this {@link ConfigurationSection} contains the given path.
* <p>
* If the value for the requested path does not exist but a default value
*
* <p>If the value for the requested path does not exist but a default value
* has been specified, this will return true.
*
* @param path Path to check for existence.
* @return True if this section contains the requested path, either via
* default or being set.
* @throws IllegalArgumentException Thrown when path is null.
* default or being set.
* @throws IllegalArgumentException Thrown when path is {@code null}.
*/
boolean contains(String path);
/**
* Checks if this {@link ConfigurationSection} has a value set for the
* given path.
* <p>
* If the value for the requested path does not exist but a default value
*
* <p>If the value for the requested path does not exist but a default value
* has been specified, this will still return false.
*
* @param path Path to check for existence.
* @return True if this section contains the requested path, regardless of
* having a default.
* @throws IllegalArgumentException Thrown when path is null.
* @throws IllegalArgumentException Thrown when path is {@code null}.
*/
boolean isSet(String path);
/**
* Gets the path of this {@link ConfigurationSection} from its root {@link
* Configuration}
* <p>
* For any {@link Configuration} themselves, this will return an empty
* Configuration}.
*
* <p>For any {@link Configuration} themselves, this will return an empty
* string.
* <p>
* If the section is no longer contained within its root for any reason,
* such as being replaced with a different value, this may return null.
* <p>
* To retrieve the single name of this section, that is, the final part of
* the path returned by this method, you may use {@link #getName()}.
*
* <p>If the section is no longer contained within its root for any reason,
* such as being replaced with a different value,
* this may return {@code null}.
*
* <p>To retrieve the single name of this section, that is, the final part
* of the path returned by this method, you may use {@link #getName()}.
*
* @return Path of this section relative to its root
*/
@ -88,8 +89,8 @@ public interface ConfigurationSection {
/**
* Gets the name of this individual {@link ConfigurationSection}, in the
* path.
* <p>
* This will always be the final part of {@link #getCurrentPath()}, unless
*
* <p>This will always be the final part of {@link #getCurrentPath()}, unless
* the section is orphaned.
*
* @return Name of this section
@ -99,12 +100,13 @@ public interface ConfigurationSection {
/**
* Gets the root {@link Configuration} that contains this {@link
* ConfigurationSection}
* <p>
* For any {@link Configuration} themselves, this will return its own
*
* <p>For any {@link Configuration} themselves, this will return its own
* object.
* <p>
* If the section is no longer contained within its root for any reason,
* such as being replaced with a different value, this may return null.
*
* <p>If the section is no longer contained within its root for any reason,
* such as being replaced with a different value,
* this may return {@code null}.
*
* @return Root configuration containing this section.
*/
@ -113,11 +115,13 @@ public interface ConfigurationSection {
/**
* Gets the parent {@link ConfigurationSection} that directly contains
* this {@link ConfigurationSection}.
* <p>
* For any {@link Configuration} themselves, this will return null.
* <p>
* If the section is no longer contained within its parent for any reason,
* such as being replaced with a different value, this may return null.
*
* <p>For any {@link Configuration} themselves, this will return
* {@code null}.
*
* <p>If the section is no longer contained within its parent for any
* reason, such as being replaced with a different value, this may
* return {@code null}.
*
* @return Parent section containing this section.
*/
@ -125,10 +129,10 @@ public interface ConfigurationSection {
/**
* Gets the requested Object by path.
* <p>
* If the Object does not exist but a default value has been specified,
*
* <p>If the Object does not exist but a default value has been specified,
* this will return the default value. If the Object does not exist and no
* default value was specified, this will return null.
* default value was specified, this will return {@code null}.
*
* @param path Path of the Object to get.
* @return Requested Object.
@ -138,24 +142,24 @@ public interface ConfigurationSection {
/**
* Gets the requested Object by path, returning a default value if not
* found.
* <p>
* If the Object does not exist then the specified default value will
*
* <p>If the Object does not exist then the specified default value will
* returned regardless of if a default has been identified in the root
* {@link Configuration}.
*
* @param path Path of the Object to get.
* @param def The default value to return if the path is not found.
* @param defaultValue The default value to return if the path is not found.
* @return Requested Object.
*/
Object get(String path, Object def);
Object get(String path, Object defaultValue);
/**
* Sets the specified path to the given value.
* <p>
* If value is null, the entry will be removed. Any existing entry will be
* replaced, regardless of what the new value is.
* <p>
* Some implementations may have limitations on what you may store. See
*
* <p>If value is {@code null}, the entry will be removed. Any
* existing entry will be replaced, regardless of what the new value is.
*
* <p>Some implementations may have limitations on what you may store. See
* their individual javadoc for details. No implementations should allow
* you to store {@link Configuration}s or {@link ConfigurationSection}s,
* please use {@link #createSection(String)} for that.
@ -167,8 +171,8 @@ public interface ConfigurationSection {
/**
* Creates an empty {@link ConfigurationSection} at the specified path.
* <p>
* Any value that was previously set at this path will be overwritten. If
*
* <p>Any value that was previously set at this path will be overwritten. If
* the previous value was itself a {@link ConfigurationSection}, it will
* be orphaned.
*
@ -180,8 +184,8 @@ public interface ConfigurationSection {
/**
* Creates a {@link ConfigurationSection} at the specified path, with
* specified values.
* <p>
* Any value that was previously set at this path will be overwritten. If
*
* <p>Any value that was previously set at this path will be overwritten. If
* the previous value was itself a {@link ConfigurationSection}, it will
* be orphaned.
*
@ -195,10 +199,10 @@ public interface ConfigurationSection {
/**
* Gets the requested String by path.
* <p>
* If the String does not exist but a default value has been specified,
*
* <p>If the String does not exist but a default value has been specified,
* this will return the default value. If the String does not exist and no
* default value was specified, this will return null.
* default value was specified, this will return {@code null}.
*
* @param path Path of the String to get.
* @return Requested String.
@ -208,8 +212,8 @@ public interface ConfigurationSection {
/**
* Gets the requested String by path, returning a default value if not
* found.
* <p>
* If the String does not exist then the specified default value will
*
* <p>If the String does not exist then the specified default value will
* returned regardless of if a default has been identified in the root
* {@link Configuration}.
*
@ -223,10 +227,10 @@ public interface ConfigurationSection {
/**
* Checks if the specified path is a String.
*
* <p> If the path exists but is not a String, this will return false. If the
* path does not exist, this will return false. If the path does not exist
* but a default value has been specified, this will check if that default
* value is a String and return appropriately.</p>
* <p>If the path exists but is not a String, this will return false. If
* the path does not exist, this will return false. If the path does not
* exist but a default value has been specified, this will check if that
* defaultvalue is a String and return appropriately.
*
* @param path Path of the String to check.
* @return Whether or not the specified path is a String.
@ -238,7 +242,7 @@ public interface ConfigurationSection {
*
* <p>If the int does not exist but a default value has been specified, this
* will return the default value. If the int does not exist and no default
* value was specified, this will return 0.</p>
* value was specified, this will return 0.
*
* @param path Path of the int to get.
* @return Requested int.
@ -250,7 +254,7 @@ public interface ConfigurationSection {
*
* <p>If the int does not exist then the specified default value will
* returned regardless of if a default has been identified in the root
* {@link Configuration}.</p>
* {@link Configuration}.
*
* @param path Path of the int to get.
* @param def The default value to return if the path is not found or is
@ -265,7 +269,7 @@ public interface ConfigurationSection {
* <p>If the path exists but is not a int, this will return false. If the
* path does not exist, this will return false. If the path does not exist
* but a default value has been specified, this will check if that default
* value is a int and return appropriately.</p>
* value is a int and return appropriately.
*
* @param path Path of the int to check.
* @return Whether or not the specified path is an int.
@ -274,8 +278,8 @@ public interface ConfigurationSection {
/**
* Gets the requested boolean by path.
* <p>
* If the boolean does not exist but a default value has been specified,
*
* <p>If the boolean does not exist but a default value has been specified,
* this will return the default value. If the boolean does not exist and
* no default value was specified, this will return false.
*
@ -287,22 +291,22 @@ public interface ConfigurationSection {
/**
* Gets the requested boolean by path, returning a default value if not
* found.
* <p>
* If the boolean does not exist then the specified default value will
*
* <p>If the boolean does not exist then the specified default value will
* returned regardless of if a default has been identified in the root
* {@link Configuration}.
*
* @param path Path of the boolean to get.
* @param def The default value to return if the path is not found or is
* @param defaultValue The default value to return if the path is not found or is
* not a boolean.
* @return Requested boolean.
*/
boolean getBoolean(String path, boolean def);
boolean getBoolean(String path, boolean defaultValue);
/**
* Checks if the specified path is a boolean.
* <p>
* If the path exists but is not a boolean, this will return false. If the
*
* <p>If the path exists but is not a boolean, this will return false. If the
* path does not exist, this will return false. If the path does not exist
* but a default value has been specified, this will check if that default
* value is a boolean and return appropriately.
@ -314,8 +318,8 @@ public interface ConfigurationSection {
/**
* Gets the requested double by path.
* <p>
* If the double does not exist but a default value has been specified,
*
* <p>If the double does not exist but a default value has been specified,
* this will return the default value. If the double does not exist and no
* default value was specified, this will return 0.
*
@ -327,22 +331,22 @@ public interface ConfigurationSection {
/**
* Gets the requested double by path, returning a default value if not
* found.
* <p>
* If the double does not exist then the specified default value will
*
* <p>If the double does not exist then the specified default value will
* returned regardless of if a default has been identified in the root
* {@link Configuration}.
*
* @param path Path of the double to get.
* @param def The default value to return if the path is not found or is
* @param defaultValue The default value to return if the path is not found or is
* not a double.
* @return Requested double.
*/
double getDouble(String path, double def);
double getDouble(String path, double defaultValue);
/**
* Checks if the specified path is a double.
* <p>
* If the path exists but is not a double, this will return false. If the
*
* <p>If the path exists but is not a double, this will return false. If the
* path does not exist, this will return false. If the path does not exist
* but a default value has been specified, this will check if that default
* value is a double and return appropriately.
@ -354,8 +358,8 @@ public interface ConfigurationSection {
/**
* Gets the requested long by path.
* <p>
* If the long does not exist but a default value has been specified, this
*
* <p>If the long does not exist but a default value has been specified, this
* will return the default value. If the long does not exist and no
* default value was specified, this will return 0.
*
@ -367,8 +371,8 @@ public interface ConfigurationSection {
/**
* Gets the requested long by path, returning a default value if not
* found.
* <p>
* If the long does not exist then the specified default value will
*
* <p>If the long does not exist then the specified default value will
* returned regardless of if a default has been identified in the root
* {@link Configuration}.
*
@ -381,8 +385,8 @@ public interface ConfigurationSection {
/**
* Checks if the specified path is a long.
* <p>
* If the path exists but is not a long, this will return false. If the
*
* <p>If the path exists but is not a long, this will return false. If the
* path does not exist, this will return false. If the path does not exist
* but a default value has been specified, this will check if that default
* value is a long and return appropriately.
@ -396,8 +400,8 @@ public interface ConfigurationSection {
/**
* Gets the requested List by path.
* <p>
* If the List does not exist but a default value has been specified, this
*
* <p>If the List does not exist but a default value has been specified, this
* will return the default value. If the List does not exist and no
* default value was specified, this will return null.
*
@ -409,8 +413,8 @@ public interface ConfigurationSection {
/**
* Gets the requested List by path, returning a default value if not
* found.
* <p>
* If the List does not exist then the specified default value will
*
* <p>If the List does not exist then the specified default value will
* returned regardless of if a default has been identified in the root
* {@link Configuration}.
*
@ -423,8 +427,8 @@ public interface ConfigurationSection {
/**
* Checks if the specified path is a List.
* <p>
* If the path exists but is not a List, this will return false. If the
*
* <p>If the path exists but is not a List, this will return false. If the
* path does not exist, this will return false. If the path does not exist
* but a default value has been specified, this will check if that default
* value is a List and return appropriately.
@ -436,12 +440,12 @@ public interface ConfigurationSection {
/**
* Gets the requested List of String by path.
* <p>
* If the List does not exist but a default value has been specified, this
* will return the default value. If the List does not exist and no
*
* <p>If the List does not exist but a default value has been specified,
* this will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
* <p>
* This method will attempt to cast any values into a String if possible,
*
* <p>This method will attempt to cast any values into a String if possible,
* but may miss any values out if they are not compatible.
*
* @param path Path of the List to get.
@ -451,13 +455,13 @@ public interface ConfigurationSection {
/**
* Gets the requested List of Integer by path.
* <p>
* If the List does not exist but a default value has been specified, this
* will return the default value. If the List does not exist and no
*
* <p>If the List does not exist but a default value has been specified,
* this will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
* <p>
* This method will attempt to cast any values into a Integer if possible,
* but may miss any values out if they are not compatible.
*
* <p>This method will attempt to cast any values into a Integer if
* possible, but may miss any values out if they are not compatible.
*
* @param path Path of the List to get.
* @return Requested List of Integer.
@ -466,13 +470,13 @@ public interface ConfigurationSection {
/**
* Gets the requested List of Boolean by path.
* <p>
* If the List does not exist but a default value has been specified, this
* will return the default value. If the List does not exist and no
*
* <p>If the List does not exist but a default value has been specified,
* this will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
* <p>
* This method will attempt to cast any values into a Boolean if possible,
* but may miss any values out if they are not compatible.
*
* <p>This method will attempt to cast any values into a Boolean if
* possible, but may miss any values out if they are not compatible.
*
* @param path Path of the List to get.
* @return Requested List of Boolean.
@ -481,12 +485,12 @@ public interface ConfigurationSection {
/**
* Gets the requested List of Double by path.
* <p>
* If the List does not exist but a default value has been specified, this
* will return the default value. If the List does not exist and no
*
* <p>If the List does not exist but a default value has been specified,
* this will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
* <p>
* This method will attempt to cast any values into a Double if possible,
*
* <p>This method will attempt to cast any values into a Double if possible,
* but may miss any values out if they are not compatible.
*
* @param path Path of the List to get.
@ -496,12 +500,12 @@ public interface ConfigurationSection {
/**
* Gets the requested List of Float by path.
* <p>
* If the List does not exist but a default value has been specified, this
* will return the default value. If the List does not exist and no
*
* <p>If the List does not exist but a default value has been specified,
* this will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
* <p>
* This method will attempt to cast any values into a Float if possible,
*
* <p>This method will attempt to cast any values into a Float if possible,
* but may miss any values out if they are not compatible.
*
* @param path Path of the List to get.
@ -511,12 +515,12 @@ public interface ConfigurationSection {
/**
* Gets the requested List of Long by path.
* <p>
* If the List does not exist but a default value has been specified, this
* will return the default value. If the List does not exist and no
*
* <p>If the List does not exist but a default value has been specified,
* this will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
* <p>
* This method will attempt to cast any values into a Long if possible,
*
* <p>This method will attempt to cast any values into a Long if possible,
* but may miss any values out if they are not compatible.
*
* @param path Path of the List to get.
@ -526,12 +530,12 @@ public interface ConfigurationSection {
/**
* Gets the requested List of Byte by path.
* <p>
* If the List does not exist but a default value has been specified, this
* will return the default value. If the List does not exist and no
*
* <p>If the List does not exist but a default value has been specified,
* this will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
* <p>
* This method will attempt to cast any values into a Byte if possible,
*
* <p>This method will attempt to cast any values into a Byte if possible,
* but may miss any values out if they are not compatible.
*
* @param path Path of the List to get.
@ -541,12 +545,12 @@ public interface ConfigurationSection {
/**
* Gets the requested List of Character by path.
* <p>
* If the List does not exist but a default value has been specified, this
* will return the default value. If the List does not exist and no
*
* <p>If the List does not exist but a default value has been specified,
* this will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
* <p>
* This method will attempt to cast any values into a Character if
*
* <p>This method will attempt to cast any values into a Character if
* possible, but may miss any values out if they are not compatible.
*
* @param path Path of the List to get.
@ -556,13 +560,13 @@ public interface ConfigurationSection {
/**
* Gets the requested List of Short by path.
* <p>
* If the List does not exist but a default value has been specified, this
* will return the default value. If the List does not exist and no
*
* <p>If the List does not exist but a default value has been specified,
* this will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
* <p>
* This method will attempt to cast any values into a Short if possible,
* but may miss any values out if they are not compatible.
*
* <p>This method will attempt to cast any values into a Short if
* possible, but may miss any values out if they are not compatible.
*
* @param path Path of the List to get.
* @return Requested List of Short.
@ -571,13 +575,12 @@ public interface ConfigurationSection {
/**
* Gets the requested List of Maps by path.
* <p>
* If the List does not exist but a default value has been specified, this
* will return the default value. If the List does not exist and no
*
* <p>If the List does not exist but a default value has been specified,
* this will return the default value. If the List does not exist and no
* default value was specified, this will return an empty List.
* <p>
* This method will attempt to cast any values into a Map if possible, but
* may miss any values out if they are not compatible.
* <p>This method will attempt to cast any values into a Map if possible,
* but may miss any values out if they are not compatible.
*
* @param path Path of the List to get.
* @return Requested List of Maps.
@ -586,11 +589,11 @@ public interface ConfigurationSection {
/**
* Gets the requested ConfigurationSection by path.
* <p>
* If the ConfigurationSection does not exist but a default value has been
* specified, this will return the default value. If the
*
* <p>If the ConfigurationSection does not exist but a default value has
* been specified, this will return the default value. If the
* ConfigurationSection does not exist and no default value was specified,
* this will return null.
* this will return {@code null}.
*
* @param path Path of the ConfigurationSection to get.
* @return Requested ConfigurationSection.
@ -599,8 +602,8 @@ public interface ConfigurationSection {
/**
* Checks if the specified path is a ConfigurationSection.
* <p>
* If the path exists but is not a ConfigurationSection, this will return
*
* <p>If the path exists but is not a ConfigurationSection, this will return
* false. If the path does not exist, this will return false. If the path
* does not exist but a default value has been specified, this will check
* if that default value is a ConfigurationSection and return
@ -614,10 +617,10 @@ public interface ConfigurationSection {
/**
* Gets the equivalent {@link ConfigurationSection} from the default
* {@link Configuration} defined in {@link #getRoot()}.
* <p>
* If the root contains no defaults, or the defaults doesn't contain a
*
* <p>If the root contains no defaults, or the defaults doesn't contain a
* value for this path, or the value at this path is not a {@link
* ConfigurationSection} then this will return null.
* ConfigurationSection} then this will return {@code null}.
*
* @return Equivalent section in root configuration
*/
@ -625,21 +628,21 @@ public interface ConfigurationSection {
/**
* Sets the default value in the root at the given path as provided.
* <p>
* If no source {@link Configuration} was provided as a default
*
* <p>If no source {@link Configuration} was provided as a default
* collection, then a new {@link MemoryConfiguration} will be created to
* hold the new default value.
* <p>
* If value is null, the value will be removed from the default
* Configuration source.
* <p>
* If the value as returned by {@link #getDefaultSection()} is null, then
* this will create a new section at the path, replacing anything that may
* have existed there previously.
*
* @param path Path of the value to set.
* @param value Value to set the default to.
* @throws IllegalArgumentException Thrown if path is null.
* <p>If value is {@code null}, the value will be removed from the
* default Configuration source.
*
* <p>If the value as returned by {@link #getDefaultSection()} is
* {@code null}, then this will create a new section at the path,
* replacing anything that may have existed there previously.
*
* @param path Path of the value to set
* @param value Value to set the default to
* @throws IllegalArgumentException Thrown if path is {@code null}
*/
void addDefault(String path, Object value);
}

View File

@ -1,7 +1,7 @@
package com.intellectualcrafters.configuration;
/**
* Exception thrown when attempting to load an invalid {@link Configuration}
* Exception thrown when attempting to load an invalid {@link Configuration}.
*/
@SuppressWarnings("serial")
public class InvalidConfigurationException extends Exception {
@ -18,7 +18,7 @@ public class InvalidConfigurationException extends Exception {
*
* @param msg The details of the exception.
*/
public InvalidConfigurationException(final String msg) {
public InvalidConfigurationException(String msg) {
super(msg);
}
@ -28,7 +28,7 @@ public class InvalidConfigurationException extends Exception {
*
* @param cause The cause of the exception.
*/
public InvalidConfigurationException(final Throwable cause) {
public InvalidConfigurationException(Throwable cause) {
super(cause);
}
@ -39,7 +39,7 @@ public class InvalidConfigurationException extends Exception {
* @param cause The cause of the exception.
* @param msg The details of the exception.
*/
public InvalidConfigurationException(final String msg, final Throwable cause) {
public InvalidConfigurationException(String msg, Throwable cause) {
super(msg, cause);
}
}

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