Compare commits

...

210 Commits

Author SHA1 Message Date
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
ff1b7c66b1 What's snow-melt doing there? 2016-03-27 19:38:15 +11:00
3fb6ccbbb6 Fix TNT explosions for sponge 2016-03-27 19:10:08 +11:00
357400c5ac Fix block break road (sponge) 2016-03-27 17:01:49 +11:00
32e10fbff6 Fix permission caching (sponge) 2016-03-27 16:19:56 +11:00
1bf05df706 Try this coolty 2016-03-27 16:01:53 +11:00
e3f5842299 Recover from invalid db entry 2016-03-27 07:31:35 +11:00
53e56a6414 Fix required args 2016-03-27 07:11:09 +11:00
46d3dc609e Update sponge port 2016-03-27 06:47:34 +11:00
056f77a3ba 3.3.2 2016-03-27 03:34:55 +11:00
d4d9a9e148 Change to SubCommand 2016-03-26 20:28:45 +11:00
6a7cf0d56f forgot to push this 2016-03-26 16:44:38 +11:00
1252e004a0 Cancel chat event 2016-03-25 15:56:11 +11:00
2816ceae72 Change chat priority 2016-03-25 15:07:35 +11:00
f74e7bb4cb Fixes #997 for 1.8 2016-03-25 14:50:57 +11:00
30d57d8642 Fixes #997 for 1.9 (TODO fix for 1.8 as well) 2016-03-25 14:25:06 +11:00
ce9ec20b59 Merge pull request #1000 from manuelgu/patch-1
Rename PlotGamemode to PlotGameMode
2016-03-24 23:09:51 -04:00
65d428a989 Rename PlotGamemode to PlotGameMode
@MattBDev I think you just forgot renaming the class
2016-03-24 23:06:45 +01:00
7ab8d22325 Move confirmation to commands.yml 2016-03-25 02:03:36 +11:00
ed62ed2487 Fixes #983 2016-03-24 22:08:07 +11:00
8a42eecc11 Command changes
Legacy commands still need to be cleaned up (after which economy /
confirmation can be centralized)
All command names / usage / description is configurable
Simplifies creating commands
Deeper tab completion / command help
2016-03-24 20:57:59 +11:00
a62b9a334d Cleaning 2016-03-24 00:50:25 -04:00
48f22eaed4 More cleaning 2016-03-23 13:13:09 -04:00
bb4700aa5a More cleaning 2016-03-23 13:09:13 -04:00
9e2c6f2182 Major code reformatting 2016-03-22 21:41:39 -04:00
e18e1d4816 Merge pull request #995 from manuelgu/master
Cleanup
2016-03-22 14:36:41 -04:00
35c7c20874 Track renamed Music.java file 2016-03-22 18:53:56 +01:00
84188f6557 Cleanup 2016-03-22 18:53:17 +01:00
09ee7f3048 Merge remote-tracking branch 'origin/master'
# Conflicts:
#	Core/src/main/java/com/intellectualcrafters/plot/commands/Area.java
#	Core/src/main/java/com/intellectualcrafters/plot/commands/Auto.java
#	Core/src/main/java/com/intellectualcrafters/plot/database/SQLManager.java
#	Core/src/main/java/com/intellectualcrafters/plot/generator/HybridUtils.java
#	Core/src/main/java/com/intellectualcrafters/plot/object/Plot.java
#	Core/src/main/java/com/intellectualcrafters/plot/object/PlotAnalysis.java
2016-03-20 23:03:31 -04:00
029241912b Code Style Cleanup 2016-03-20 22:52:16 -04:00
0e49dd6f62 Merge branch 'manuelgu-feature/rm-redundant-methods' 2016-03-20 19:54:46 -04:00
cb0b59fdb4 Merge branch 'feature/rm-redundant-methods' of https://github.com/manuelgu/PlotSquared into manuelgu-feature/rm-redundant-methods 2016-03-20 19:52:11 -04:00
bb4ecb94a1 Cleanup 2016-03-20 19:35:40 -04:00
df12e53d40 Remove redundant .s() methods 2016-03-20 23:19:37 +01:00
274d819f8c Use Metrics as dependency in Sponge
Unlike Bukkit, we can support Sponge Metrics as a dependency.
2016-03-20 14:00:39 -04:00
2e4f4d0064 Merge pull request #986 from SynergyMC/testing
A small change to /p weanywhere's behavior
2016-03-20 21:50:17 +11:00
712ce74af6 /p weanywhere change
Allows players with "WorldEdit Anywhere" toggled to use the wand
anywhere
2016-03-20 00:26:45 -10:00
015dda21f2 Merge remote-tracking branch 'IntellectualSites/master' into testing 2016-03-19 18:11:36 -10:00
19b6df8268 Cleanup 2016-03-19 14:07:55 -04:00
f16affabcc Merge remote-tracking branch 'IntellectualSites/master' into testing 2016-03-18 23:28:49 -10:00
8074d041b8 Fix "Cleaner reflection" breaking plugin.
Also add method to sort plots by modification date.
2016-03-19 17:32:05 +11:00
d30626d11f Cleaner reflection 2016-03-19 00:39:42 -04:00
f26278f72e Fixes #950 2016-03-19 13:01:10 +11:00
79864d269a Extremely minor text change to LICENSE 2016-03-18 16:50:43 -04:00
ab40d97327 Try this? 2016-03-18 05:08:09 +11:00
fe43143bdb Fixes #972 2016-03-18 03:33:31 +11:00
9e32ce9885 Automatically drop unique_alias for MySQL 2016-03-18 03:05:36 +11:00
3921fdfc3f Fixes #967 2016-03-18 02:18:18 +11:00
e1e5497558 Fixes #871 2016-03-18 02:06:06 +11:00
f9db269813 Various
Close #966
Close #953
(duplicates)
Changes to chunk copying etc to interfere less with world generation
2016-03-18 01:22:51 +11:00
16dac99fed Any reason for breaking it in the last commit? 2016-03-17 20:33:47 +11:00
98c4483535 Various
some sponge stuff
schematic/mca/bo3 uploading rework
fix minor issue with plot visit
fix #956
2016-03-17 20:11:07 +11:00
75bf01c13f Fixed casting issue in FastQueue_1_9 2016-03-16 19:18:09 -04:00
7bbd359be8 Fixed #957 2016-03-16 18:50:55 -04:00
58eeeb16d4 Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared 2016-03-16 10:16:19 -04:00
65ddb12701 Beginning rewrite of Flags and various cleanups 2016-03-16 10:15:38 -04:00
1f42ee6744 Merge pull request #969 from SynergyMC/testing
Implements fire-related flags
2016-03-17 01:06:00 +11:00
4a1c206f98 Revert "Fixed bukkit dependency in maven"
This reverts commit e6f33e7150.
2016-03-15 22:25:31 -10:00
a297d505f8 Pulled files from official repository 2016-03-15 22:15:47 -10:00
a26db46242 Pyromania
Adds block-ignition, which allows fire being set by players,
dispensers, explosions, and fireballs (if their origin is the same as
the plot that they land in)

Adds fire-spread, which allows fire to spread from lava and fire
spreading in general

Adds block-burn, which allows blocks to burn away
2016-03-15 21:59:01 -10:00
3fb64d9811 Added snow-melt flag 2016-03-15 01:16:29 -04:00
bb8883dfaf Added snow-melt flag 2016-03-14 11:01:52 -04:00
bee6f83e79 Various changes 2016-03-14 02:18:04 -04:00
ae885eafca Various changes and Merge Economy Fix 2016-03-13 22:44:59 -04:00
8739f3ef78 Horses aren't hostile. 2016-03-14 12:34:58 +11:00
dfd29f6713 Various changes
Plot class is now more reliable as most fields are private
Cleanup some classes.
Fixes #955
makes progress on #953
2016-03-13 14:09:48 -04:00
e6f33e7150 Fixed bukkit dependency in maven 2016-03-12 23:37:45 -10:00
3fb686608b Merge pull request #951 from Gabscap/fix-static
Make WorldEvents method non-static
2016-03-13 04:00:40 +11:00
a8fd1b49ca Various
sponge changes / documentation / cleanup / event tweak
2016-03-13 03:57:36 +11:00
4c40268e8f Make WorldEvents method non-static 2016-03-12 16:27:03 +01:00
edc43bd53b Update README.md 2016-03-11 09:05:42 -05:00
66da71bc9f Various
Fixes a few typos
Fixes #943
Fixes #944
Fixes metrics (broke in b69e31129d)
Fixes plot setup issue
Fixes some lighting issues
Fixes ChunkListener + cauldron
Tweak some  schematic stuff
2016-03-11 15:33:39 +11:00
c979be2994 Add missing permission to plugin.yml file 2016-03-10 17:12:56 -05:00
33222b25a3 Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared 2016-03-08 21:41:47 -05:00
57fa265b48 Optimizations and cleaning.
Fixes #943 (even though it should be impossible)
2016-03-08 21:18:54 -05:00
fef2bc0cf2 Restore metrics 2016-03-08 16:31:40 +11:00
f391ae444f remove java 8 code 2016-03-08 14:09:50 +11:00
286e5b8b97 Minor performance improvements. 2016-03-07 15:28:59 -05:00
d2c81cbd01 Use Metrics Dependency 2016-03-07 14:56:06 -05:00
e4d460107f Update ISSUE_TEMPLATE.md 2016-03-07 11:24:36 -05:00
b59665b00b Fix #938 2016-03-07 19:37:53 +11:00
62531a42c7 Fix for @Htgan / clear
Possibly fixes #932
2016-03-07 17:34:57 +11:00
05caa2ca8d Fixes #935 2016-03-06 23:46:37 +11:00
00c174fdf1 Various
Progress on #929
Fix area loading from config with negative ids @skroob
2016-03-06 19:08:01 +11:00
b95fdeccca Maybe? 2016-03-06 19:08:01 +11:00
32d4a08db1 Small cleanup 2016-03-04 19:53:31 -05:00
5c60d69fd1 closes #915 2016-03-04 16:37:38 -05:00
780d4e09d5 Delay economy hook #922 2016-03-04 05:04:11 +11:00
2b3fb7b4d0 Fix for explosion 2016-03-03 12:25:57 +11:00
0dc672bcd5 Apparently resetTitles only resets the top part? 2016-03-03 09:12:20 +11:00
6e2256ffcf Update titles 2016-03-03 09:08:43 +11:00
cfcfd87f57 messy nms for 1.9 2016-03-03 08:51:17 +11:00
955f14e2d7 Merge pull request #920 from manuelgu/patch-4
Formatting in pom.xml
2016-03-03 08:12:48 +11:00
4ead7bb9da Formatting in pom.xml
Because that just looks better :P
2016-03-02 22:11:28 +01:00
0408e9a37c Sorry, I'll fix it. 2016-03-03 07:34:59 +11:00
b294ff528f Push file for legacy updater 2016-03-02 17:49:17 +11:00
f00ac79c91 Bump version / misc
Fix regenallroads
Add schematic y_offset
Change visit/list for multi-owner plots
Fix updater (pre-1.7.10)
2016-03-02 17:42:04 +11:00
109715e0d7 Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared 2016-03-02 06:59:05 +11:00
8bf3ceac6f Changes
Plot auto clear confirmation
Add timediff to keep flag
Add expired parameter to list cmd
Fixes some compatibility issues
2016-03-02 06:56:50 +11:00
106c3c5cb4 Temporary fix for 1.9 2016-03-01 14:17:29 +11:00
0bbfd0f49a Begin 1.9 NMS updates 2016-02-29 20:44:58 -05:00
9596544f97 Cleanup Code
I also updated the build.gradle and pom to 1.9 bukkit
2016-02-29 20:13:18 -05:00
5079361fbf Fix negation issue. 2016-02-29 11:50:04 -05:00
b0a3f70cbd Updater now uses GitHub Releases and API 2016-02-29 11:15:51 -05:00
841809b93d Various
Closes #906
Add command confirmation for setowner
Require confirmation delayed by 1 tick
2016-03-01 02:01:52 +11:00
43b7a7aba8 Fixes #910 2016-02-29 15:12:20 +11:00
8906577699 Merge pull request #909 from zombachu/master
Implements the ice-melt flag
2016-02-29 14:08:31 +11:00
224caee56e Implements the ice-melt flag 2016-02-28 15:41:32 -10:00
5c4178b1dd Fixes
Fixes #905
Fixes auto claim limit
2016-02-29 04:09:09 +11:00
911bef974a Stop spectating before being kicked when denied.
Fixes #886
2016-02-27 20:11:18 -05:00
7d340b58b4 Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared 2016-02-27 15:49:45 -05:00
ce8775414a Fix some logic 2016-02-28 07:04:57 +11:00
5da8700f7f Force Core to use Java 7 2016-02-27 13:41:49 -05:00
01710e3ddb Fixes
Notify core of all world loading regardless of generator
Optimize plot area fetching
Fix plot delete not deleting the plot until restart
Fix plot unclaim not removing the owner on any cached plots
Change gradle output directory
Fix plotme conversion sometimes not copying over the floor/main blocks
2016-02-27 21:07:42 +11:00
7d8893b5d7 Fixes #900 2016-02-27 17:07:15 +11:00
7a97c69d4f Fix bed explosion in hell biome when flag not present 2016-02-27 16:44:29 +11:00
1a80b344b9 replace jar with one that's less broken 2016-02-27 16:09:55 +11:00
afe6c5fd69 Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared 2016-02-27 16:05:56 +11:00
f68042bc11 Fixes
Fixes unlink failing if a parameter is provided
Fix plot unlinking not resetting the road biome
Fixes #888
2016-02-27 16:05:21 +11:00
ac77c755d0 Add plot middle permission to plugin.yml 2016-02-26 19:10:59 -05:00
c7870b617c Gradle / maven
Fix archive names (includes project/module name + version)
Generate MD5 hash alongside jar
Improve build time
- asynchronous building
- enable daemon
- change scope of a few statements
- skip building of 3 jars
Add filtering to the plugin.yml (maven/gradle)
Bump version to 3.3.0 in pom
2016-02-26 23:55:21 +11:00
f921db937a Fix plot music duplication when moving between plots in a merged plot 2016-02-26 17:43:49 +11:00
4669f31658 Fixes
Fixes hybridplotworld rotation for stairs
Fixes hybridplotworld skipping non-rotatable blocks on swapped sideroad
schem
Fixes schematic generation using wrong height
Fixes debug spam printed when using download cmd
Fixes pagination having page number instead of total list items
Fixes plot area list page being off by 1
Remove compatibility for a spigot 1.8.0 bug where getting the world name
during initialization crashes the server.
Fixes type 1,2 plot worlds not being fetchable if there are more than 8
plot worlds loaded.
2016-02-26 17:29:31 +11:00
c8ddcd7f54 Fixes
Fix plot cluster command NPE
Fix path iterator (for Plot.getAllCorners()) being off by 1
2016-02-26 04:17:23 +11:00
fb2e949711 Fix rotation for stairs metadata (range:8-15) 2016-02-26 01:21:30 +11:00
7659884e73 Fixes
Fixes #868
Fixes #778
Fixes attributes passing wrong key to persistent meta
Fixes blob compatibility with JDBC driver for persistent meta
Fix stackoverflow from countEntities under certain circumstances
Minor cleanup
2016-02-26 01:17:07 +11:00
efae2c2e63 Finished several core parts of the sponge port
Mass block changes / chunk packet sending
AsyncWorldEdit (buggy)
Fixed world ground cover layers being generated
Fixed tab completion
Fixed plot title color
Fixed worlds unloading when no players are present
Fixed falling blocks not falling where they should
Fixed console color
Fixed chunk regeneration on full plot worlds
Other stuff
2016-02-25 20:13:07 +11:00
d3465b7bde Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared 2016-02-24 05:12:20 +11:00
f73a542b04 Tab completion, fix SpongeUtil.getWorld 2016-02-24 05:12:07 +11:00
6f3485c87d Hard-code version into plugin.yml 2016-02-23 13:08:20 -05:00
bf85ba5833 No they aren't 2016-02-24 04:20:40 +11:00
8a2c44759f Chunk regeneration 2016-02-24 04:04:23 +11:00
882394987b Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared 2016-02-24 03:08:12 +11:00
7a217b2f08 a wild pom appears
fork/pr if you don't like how I've done it
2016-02-24 03:07:49 +11:00
b94e816c55 Sponge changes. 2016-02-23 09:55:40 -05:00
87ee693a49 Fix small Gradle things. 2016-02-22 23:30:49 -05:00
1768651782 Merge pull request #874 from IntellectualSites/gradle
Move from Maven to Gradle
2016-02-22 23:16:03 -05:00
b69e31129d Updated Gradle 2016-02-22 23:11:40 -05:00
7b15d50674 Add PS.get().isPlotWorld() and MainUtil.getPlotID( Location );
@_Cory_
2016-02-23 05:46:57 +11:00
f996b1d95d Using ReflectionUtils simplifies stuff? 2016-02-23 05:38:28 +11:00
14eb3279c0 Revert version 2016-02-23 05:31:35 +11:00
ced342f14e Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared 2016-02-22 17:24:30 +11:00
f5ff82c8cc Sponge / Other
Fix area teleportation for type 0,1 worlds
Add blockstate<>id/data resolving for sponge
Finish world generation for sponge
Add chat color for sponge
Fix economy support for sponge
Fix sponge event system
Other stuff
2016-02-22 17:20:22 +11:00
b255c5db47 Cleanup and Fixes
Fixed StackOverflowError caused by c83378a
2016-02-21 23:29:33 -05:00
ca5e7f4564 Cleanup 2016-02-20 23:07:04 -05:00
ef5846f688 Cleanup 2016-02-20 16:50:10 -05:00
36ebd1983d Use UTF-8 2016-02-19 15:51:04 -05:00
552 changed files with 40296 additions and 41975 deletions

View File

@ -1,12 +1,12 @@
# Bug report template (clear for feature request) # Bug report template (Follow this template unless you are making a feature request.)
**Debug paste link**: **Debug paste link**:
**Description of the problem:** **Description of the problem:**
**How to replicate**: **How to replicate**:
Make sure you've completed the following steps (put X inside of brackets): Make sure you've completed the following steps (put an X between of brackets):
- [ ] Include `/plot debugpaste` - [] Include `/plot debugpaste`
- [ ] Made sure there aren't duplicates of this report [(Use Search)](https://github.com/IntellectualSites/PlotSquared/issues) - [] 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 you're using an updated version of PlotSquared
- [ ] Made sure the bug/error isn't caused by any other plugin - [] Made sure the bug/error isn't caused by any other plugin

4
.gitignore vendored
View File

@ -3,6 +3,9 @@
*.cmd *.cmd
*.sh *.sh
*.prefs *.prefs
Sponge/build
Core/build
Bukkit/build
### Maven ### ### Maven ###
/target/lib /target/lib
@ -59,6 +62,7 @@ hs_err_pid*
# Gradle: # Gradle:
# .idea/gradle.xml # .idea/gradle.xml
# .idea/libraries # .idea/libraries
.gradle
# Mongo Explorer plugin: # Mongo Explorer plugin:
# .idea/mongoSettings.xml # .idea/mongoSettings.xml

38
Bukkit/build.gradle Normal file
View File

@ -0,0 +1,38 @@
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'
}
sourceCompatibility = 1.7
targetCompatibility = 1.7
processResources {
from('src/main/resources') {
include 'plugin.yml'
expand(
name: project.parent.name,
version: project.parent.version
)
}
}
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'
archiveName = "${parent.name}-${project.name}-${parent.version}.jar"
destinationDir = file '../target'
}
shadowJar.doLast {
task ->
ant.checksum file: task.archivePath
}
build.dependsOn(shadowJar);

View File

@ -1,34 +1,8 @@
package com.plotsquared.bukkit; package com.plotsquared.bukkit;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.command.PluginCommand;
import org.bukkit.entity.Entity;
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.java.JavaPlugin;
import com.intellectualcrafters.configuration.ConfigurationSection; import com.intellectualcrafters.configuration.ConfigurationSection;
import com.intellectualcrafters.plot.IPlotMain; import com.intellectualcrafters.plot.IPlotMain;
import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.commands.MainCommand;
import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.ConfigurationNode; import com.intellectualcrafters.plot.config.ConfigurationNode;
import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.config.Settings;
@ -59,7 +33,6 @@ import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.util.UUIDHandlerImplementation; import com.intellectualcrafters.plot.util.UUIDHandlerImplementation;
import com.intellectualcrafters.plot.util.WorldUtil; import com.intellectualcrafters.plot.util.WorldUtil;
import com.intellectualcrafters.plot.uuid.UUIDWrapper; 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.ClassicPlotMeConnector;
import com.plotsquared.bukkit.database.plotme.LikePlotMeConverter; import com.plotsquared.bukkit.database.plotme.LikePlotMeConverter;
import com.plotsquared.bukkit.database.plotme.PlotMeConnector_017; import com.plotsquared.bukkit.database.plotme.PlotMeConnector_017;
@ -67,12 +40,13 @@ import com.plotsquared.bukkit.generator.BukkitPlotGenerator;
import com.plotsquared.bukkit.listeners.ChunkListener; import com.plotsquared.bukkit.listeners.ChunkListener;
import com.plotsquared.bukkit.listeners.ForceFieldListener; import com.plotsquared.bukkit.listeners.ForceFieldListener;
import com.plotsquared.bukkit.listeners.PlayerEvents; 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_8;
import com.plotsquared.bukkit.listeners.PlayerEvents_1_8_3; import com.plotsquared.bukkit.listeners.PlayerEvents_1_9;
import com.plotsquared.bukkit.listeners.PlotPlusListener; import com.plotsquared.bukkit.listeners.PlotPlusListener;
import com.plotsquared.bukkit.listeners.WorldEvents; import com.plotsquared.bukkit.listeners.WorldEvents;
import com.plotsquared.bukkit.listeners.worldedit.WEListener; import com.plotsquared.bukkit.listeners.worldedit.WEListener;
import com.plotsquared.bukkit.titles.DefaultTitle; import com.plotsquared.bukkit.titles.DefaultTitle_19;
import com.plotsquared.bukkit.util.BukkitChatManager; import com.plotsquared.bukkit.util.BukkitChatManager;
import com.plotsquared.bukkit.util.BukkitChunkManager; import com.plotsquared.bukkit.util.BukkitChunkManager;
import com.plotsquared.bukkit.util.BukkitCommand; import com.plotsquared.bukkit.util.BukkitCommand;
@ -91,6 +65,7 @@ import com.plotsquared.bukkit.util.SetGenCB;
import com.plotsquared.bukkit.util.block.FastQueue_1_7; 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;
import com.plotsquared.bukkit.util.block.FastQueue_1_8_3; 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.SlowQueue;
import com.plotsquared.bukkit.uuid.DefaultUUIDWrapper; import com.plotsquared.bukkit.uuid.DefaultUUIDWrapper;
import com.plotsquared.bukkit.uuid.FileUUIDHandler; import com.plotsquared.bukkit.uuid.FileUUIDHandler;
@ -98,24 +73,43 @@ import com.plotsquared.bukkit.uuid.LowerOfflineUUIDWrapper;
import com.plotsquared.bukkit.uuid.OfflineUUIDWrapper; import com.plotsquared.bukkit.uuid.OfflineUUIDWrapper;
import com.plotsquared.bukkit.uuid.SQLUUIDHandler; import com.plotsquared.bukkit.uuid.SQLUUIDHandler;
import com.sk89q.worldedit.bukkit.WorldEditPlugin; 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 org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.command.PluginCommand;
import org.bukkit.entity.Entity;
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.java.JavaPlugin;
public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
public static BukkitMain THIS; public static BukkitMain THIS;
public static WorldEditPlugin worldEdit; public static WorldEditPlugin worldEdit;
private int[] version; private int[] version;
@Override @Override
public int[] getServerVersion() { public int[] getServerVersion() {
if (version == null) { if (this.version == null) {
try { try {
version = new int[3]; this.version = new int[3];
final String[] split = Bukkit.getBukkitVersion().split("-")[0].split("\\."); String[] split = Bukkit.getBukkitVersion().split("-")[0].split("\\.");
version[0] = Integer.parseInt(split[0]); this.version[0] = Integer.parseInt(split[0]);
version[1] = Integer.parseInt(split[1]); this.version[1] = Integer.parseInt(split[1]);
if (split.length == 3) { if (split.length == 3) {
version[2] = Integer.parseInt(split[2]); this.version[2] = Integer.parseInt(split[2]);
} }
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
e.printStackTrace(); e.printStackTrace();
@ -124,81 +118,83 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
return new int[]{Integer.MAX_VALUE, 0, 0}; return new int[]{Integer.MAX_VALUE, 0, 0};
} }
} }
return version; return this.version;
} }
@Override @Override
public void onEnable() { public void onEnable() {
THIS = this; BukkitMain.THIS = this;
new PS(this, "Bukkit"); new PS(this, "Bukkit");
} }
@Override @Override
public void onDisable() { public void onDisable() {
PS.get().disable(); PS.get().disable();
Bukkit.getScheduler().cancelTasks(this); Bukkit.getScheduler().cancelTasks(this);
THIS = null; BukkitMain.THIS = null;
} }
@Override @Override
public void log(String message) { public void log(String message) {
if (message == null) { if (BukkitMain.THIS != null) {
return;
}
if ((THIS != null) && (Bukkit.getServer().getConsoleSender() != null)) {
try { try {
message = C.color(message); message = C.color(message);
if (!Settings.CONSOLE_COLOR) { if (!Settings.CONSOLE_COLOR) {
message = ChatColor.stripColor(message); message = ChatColor.stripColor(message);
} }
Bukkit.getServer().getConsoleSender().sendMessage(message); this.getServer().getConsoleSender().sendMessage(message);
return; return;
} catch (final Throwable e) {} } catch (Throwable ignored) {
//ignored
}
} }
System.out.println(ConsoleColors.fromString(message)); System.out.println(ConsoleColors.fromString(message));
} }
@Override @Override
public void disable() { public void disable() {
if (THIS != null) { if (BukkitMain.THIS != null) {
onDisable(); onDisable();
} }
} }
@Override @Override
public int[] getPluginVersion() { public int[] getPluginVersion() {
final String[] split = getDescription().getVersion().split("\\."); String version = getDescription().getVersion();
return new int[] { Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]) }; if (version.contains("-SNAPSHOT")) {
version = version.split("-SNAPSHOT")[0];
}
String[] split = version.split("\\.");
return new int[]{Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2])};
} }
@Override @Override
public void registerCommands() { public void registerCommands() {
final BukkitCommand bcmd = new BukkitCommand(); BukkitCommand bukkitCommand = new BukkitCommand();
final PluginCommand plotCommand = getCommand("plots"); PluginCommand plotCommand = getCommand("plots");
plotCommand.setExecutor(bcmd); plotCommand.setExecutor(bukkitCommand);
plotCommand.setAliases(Arrays.asList("p", "ps", "plotme", "plot")); plotCommand.setAliases(Arrays.asList("p", "ps", "plotme", "plot"));
plotCommand.setTabCompleter(bcmd); plotCommand.setTabCompleter(bukkitCommand);
MainCommand.getInstance().addCommand(new DebugUUID());
} }
@Override @Override
public File getDirectory() { public File getDirectory() {
return getDataFolder(); return getDataFolder();
} }
@Override @Override
public File getWorldContainer() { public File getWorldContainer() {
return Bukkit.getWorldContainer(); return Bukkit.getWorldContainer();
} }
@Override @Override
public TaskManager getTaskManager() { public TaskManager getTaskManager() {
return new BukkitTaskManager(); return new BukkitTaskManager();
} }
@Override @Override
public void runEntityTask() { public void runEntityTask() {
log(C.PREFIX.s() + "KillAllEntities started."); log(C.PREFIX + "KillAllEntities started.");
TaskManager.runTaskRepeat(new Runnable() { TaskManager.runTaskRepeat(new Runnable() {
@Override @Override
public void run() { public void run() {
@ -211,15 +207,16 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
return; return;
} }
List<Entity> entities = world.getEntities(); List<Entity> entities = world.getEntities();
Iterator<Entity> iter = entities.iterator(); Iterator<Entity> iterator = entities.iterator();
while (iter.hasNext()) { while (iterator.hasNext()) {
Entity entity = iter.next(); Entity entity = iterator.next();
switch (entity.getType()) { switch (entity.getType()) {
case EGG: case EGG:
case ENDER_CRYSTAL: case ENDER_CRYSTAL:
case COMPLEX_PART: case COMPLEX_PART:
case FISHING_HOOK: case FISHING_HOOK:
case ENDER_SIGNAL: case ENDER_SIGNAL:
case AREA_EFFECT_CLOUD:
case EXPERIENCE_ORB: case EXPERIENCE_ORB:
case LEASH_HITCH: case LEASH_HITCH:
case FIREWORK: case FIREWORK:
@ -227,23 +224,23 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
case LIGHTNING: case LIGHTNING:
case WITHER_SKULL: case WITHER_SKULL:
case UNKNOWN: case UNKNOWN:
case PLAYER: { case PLAYER:
// non moving / unremovable // non moving / unmovable
continue; continue;
}
case THROWN_EXP_BOTTLE: case THROWN_EXP_BOTTLE:
case SPLASH_POTION: case SPLASH_POTION:
case SNOWBALL: case SNOWBALL:
case SHULKER_BULLET:
case SPECTRAL_ARROW:
case TIPPED_ARROW:
case ENDER_PEARL: case ENDER_PEARL:
case ARROW: { case ARROW:
// managed elsewhere | projectile // managed elsewhere | projectile
continue; continue;
}
case ARMOR_STAND: case ARMOR_STAND:
case ITEM_FRAME: case ITEM_FRAME:
case PAINTING: { case PAINTING:
// TEMPORARILY CLASSIFY AS VEHICLE // TEMPORARILY CLASSIFY AS VEHICLE
}
case MINECART: case MINECART:
case MINECART_CHEST: case MINECART_CHEST:
case MINECART_COMMAND: case MINECART_COMMAND:
@ -255,11 +252,11 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
if (!Settings.KILL_ROAD_VEHICLES) { if (!Settings.KILL_ROAD_VEHICLES) {
continue; continue;
} }
com.intellectualcrafters.plot.object.Location loc = BukkitUtil.getLocation(entity.getLocation()); com.intellectualcrafters.plot.object.Location location = BukkitUtil.getLocation(entity.getLocation());
Plot plot = loc.getPlot(); Plot plot = location.getPlot();
if (plot == null) { if (plot == null) {
if (loc.isPlotArea()) { if (location.isPlotArea()) {
iter.remove(); iterator.remove();
entity.remove(); entity.remove();
} }
continue; continue;
@ -270,22 +267,21 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
} }
Plot origin = (Plot) meta.get(0).value(); Plot origin = (Plot) meta.get(0).value();
if (!plot.equals(origin.getBasePlot(false))) { if (!plot.equals(origin.getBasePlot(false))) {
iter.remove(); iterator.remove();
entity.remove(); entity.remove();
} }
continue; continue;
} }
case SMALL_FIREBALL: case SMALL_FIREBALL:
case FIREBALL: case FIREBALL:
case DROPPED_ITEM: { case DRAGON_FIREBALL:
case DROPPED_ITEM:
// dropped item // dropped item
continue; continue;
}
case PRIMED_TNT: case PRIMED_TNT:
case FALLING_BLOCK: { case FALLING_BLOCK:
// managed elsewhere // managed elsewhere
continue; continue;
}
case BAT: case BAT:
case BLAZE: case BLAZE:
case CAVE_SPIDER: case CAVE_SPIDER:
@ -318,24 +314,22 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
case WITHER: case WITHER:
case WOLF: case WOLF:
case ZOMBIE: case ZOMBIE:
default: { case SHULKER:
default:
if (!Settings.KILL_ROAD_MOBS) { if (!Settings.KILL_ROAD_MOBS) {
continue; continue;
} }
final Location loc = entity.getLocation(); Location location = entity.getLocation();
if (BukkitUtil.getLocation(loc).isPlotRoad()) { if (BukkitUtil.getLocation(location).isPlotRoad()) {
final Entity passenger = entity.getPassenger(); Entity passenger = entity.getPassenger();
if (!(passenger instanceof Player)) { if (!(passenger instanceof Player) && entity.getMetadata("keep").isEmpty()) {
if (entity.getMetadata("keep").isEmpty()) { iterator.remove();
iter.remove(); entity.remove();
entity.remove();
}
} }
} }
}
} }
} }
} catch (final Throwable e) { } catch (Throwable e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -343,98 +337,95 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
} }
}, 20); }, 20);
} }
@Override @Override
final public ChunkGenerator getDefaultWorldGenerator(final String world, final String id) { public final ChunkGenerator getDefaultWorldGenerator(String world, String id) {
WorldEvents.lastWorld = world; HybridGen result = new HybridGen();
final HybridGen result = new HybridGen();
if (!PS.get().setupPlotWorld(world, id, result)) { if (!PS.get().setupPlotWorld(world, id, result)) {
return null; return null;
} }
TaskManager.runTaskLater(new Runnable() {
@Override
public void run() {
if ((WorldEvents.lastWorld != null) && WorldEvents.lastWorld.equals(world)) {
WorldEvents.lastWorld = null;
}
}
}, 20);
return (ChunkGenerator) result.specify(); return (ChunkGenerator) result.specify();
} }
@Override @Override
public void registerPlayerEvents() { public void registerPlayerEvents() {
getServer().getPluginManager().registerEvents(new PlayerEvents(), this); PlayerEvents main = new PlayerEvents();
getServer().getPluginManager().registerEvents(main, this);
if (PS.get().checkVersion(getServerVersion(), 1, 8, 0)) { if (PS.get().checkVersion(getServerVersion(), 1, 8, 0)) {
getServer().getPluginManager().registerEvents(new PlayerEvents_1_8(), this); getServer().getPluginManager().registerEvents(new PlayerEvents_1_8(), this);
} }
if (PS.get().checkVersion(getServerVersion(), 1, 8, 3)) { if (PS.get().checkVersion(getServerVersion(), 1, 8, 3)) {
getServer().getPluginManager().registerEvents(new PlayerEvents_1_8_3(), this); getServer().getPluginManager().registerEvents(new PlayerEvents183(), this);
}
if (PS.get().checkVersion(getServerVersion(), 1, 9, 0)) {
getServer().getPluginManager().registerEvents(new PlayerEvents_1_9(main), this);
} }
} }
@Override @Override
public void registerInventoryEvents() { public void registerInventoryEvents() {
// Part of PlayerEvents - can be moved if necessary // Part of PlayerEvents - can be moved if necessary
} }
@Override @Override
public void registerPlotPlusEvents() { public void registerPlotPlusEvents() {
PlotPlusListener.startRunnable(this); PlotPlusListener.startRunnable(this);
getServer().getPluginManager().registerEvents(new PlotPlusListener(), this); getServer().getPluginManager().registerEvents(new PlotPlusListener(), this);
} }
@Override @Override
public void registerForceFieldEvents() { public void registerForceFieldEvents() {
getServer().getPluginManager().registerEvents(new ForceFieldListener(), this); getServer().getPluginManager().registerEvents(new ForceFieldListener(), this);
} }
@Override @Override
public boolean initWorldEdit() { public boolean initWorldEdit() {
if (getServer().getPluginManager().getPlugin("WorldEdit") != null) { if (getServer().getPluginManager().getPlugin("WorldEdit") != null) {
BukkitMain.worldEdit = (WorldEditPlugin) getServer().getPluginManager().getPlugin("WorldEdit"); worldEdit = (WorldEditPlugin) getServer().getPluginManager().getPlugin("WorldEdit");
final String version = BukkitMain.worldEdit.getDescription().getVersion(); getServer().getPluginManager().registerEvents(new WEListener(), this);
if ((version != null) && version.startsWith("5.")) { return true;
log("&cThis version of WorldEdit does not support PlotSquared.");
log("&cPlease use WorldEdit 6+ for masking support");
log("&c - http://builds.enginehub.org/job/worldedit");
} else {
getServer().getPluginManager().registerEvents(new WEListener(), this);
return true;
}
} }
return false; return false;
} }
@Override @Override
public EconHandler getEconomyHandler() { public EconHandler getEconomyHandler() {
try { try {
final BukkitEconHandler econ = new BukkitEconHandler(); BukkitEconHandler econ = new BukkitEconHandler();
if (econ.init()) { if (econ.init()) {
return econ; return econ;
} }
} catch (final Throwable ignored) { } catch (Throwable ignored) {
PS.debug("No economy detected!");
} }
return null; return null;
} }
@Override @Override
public PlotQueue initPlotQueue() { public PlotQueue initPlotQueue() {
try { try {
new SendChunk(); new SendChunk();
MainUtil.canSendChunk = true; MainUtil.canSendChunk = true;
} catch (final Throwable e) { } catch (Throwable e) {
e.printStackTrace(); e.printStackTrace();
MainUtil.canSendChunk = false; 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(), 1, 8, 0)) { if (PS.get().checkVersion(getServerVersion(), 1, 8, 0)) {
try { try {
return new FastQueue_1_8_3(); return new FastQueue_1_8_3();
} catch (NoSuchMethodException | RuntimeException e) { } catch (Throwable e) {
e.printStackTrace(); e.printStackTrace();
try { try {
return new FastQueue_1_8(); return new FastQueue_1_8();
} catch (NoSuchMethodException e2) { } catch (Throwable e2) {
e2.printStackTrace(); e2.printStackTrace();
return new SlowQueue(); return new SlowQueue();
} }
@ -442,16 +433,17 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
} }
try { try {
return new FastQueue_1_7(); return new FastQueue_1_7();
} catch (NoSuchMethodException e) { } catch (Throwable e) {
e.printStackTrace();
return new SlowQueue(); return new SlowQueue();
} }
} }
@Override @Override
public WorldUtil initWorldUtil() { public WorldUtil initWorldUtil() {
return new BukkitUtil(); return new BukkitUtil();
} }
@Override @Override
public boolean initPlotMeConverter() { public boolean initPlotMeConverter() {
TaskManager.runTaskLaterAsync(new Runnable() { TaskManager.runTaskLaterAsync(new Runnable() {
@ -468,17 +460,17 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
} }
} }
}, 20); }, 20);
return (Bukkit.getPluginManager().getPlugin("PlotMe") != null) || (Bukkit.getPluginManager().getPlugin("AthionPlots") != null); return Bukkit.getPluginManager().getPlugin("PlotMe") != null || Bukkit.getPluginManager().getPlugin("AthionPlots") != null;
} }
@Override @Override
public GeneratorWrapper<?> getGenerator(final String world, final String name) { public GeneratorWrapper<?> getGenerator(String world, String name) {
if (name == null) { if (name == null) {
return null; return null;
} }
final Plugin gen_plugin = Bukkit.getPluginManager().getPlugin(name); Plugin genPlugin = Bukkit.getPluginManager().getPlugin(name);
if ((gen_plugin != null) && gen_plugin.isEnabled()) { if (genPlugin != null && genPlugin.isEnabled()) {
ChunkGenerator gen = gen_plugin.getDefaultWorldGenerator(world, ""); ChunkGenerator gen = genPlugin.getDefaultWorldGenerator(world, "");
if (gen instanceof GeneratorWrapper<?>) { if (gen instanceof GeneratorWrapper<?>) {
return (GeneratorWrapper<?>) gen; return (GeneratorWrapper<?>) gen;
} }
@ -487,199 +479,172 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
return new BukkitPlotGenerator(new HybridGen()); return new BukkitPlotGenerator(new HybridGen());
} }
} }
@Override @Override
public HybridUtils initHybridUtils() { public HybridUtils initHybridUtils() {
return new BukkitHybridUtils(); return new BukkitHybridUtils();
} }
@Override @Override
public SetupUtils initSetupUtils() { public SetupUtils initSetupUtils() {
return new BukkitSetupUtils(); return new BukkitSetupUtils();
} }
@Override @Override
public UUIDHandlerImplementation initUUIDHandler() { public UUIDHandlerImplementation initUUIDHandler() {
final boolean checkVersion = PS.get().checkVersion(getServerVersion(), 1, 7, 6); boolean checkVersion = PS.get().checkVersion(getServerVersion(), 1, 7, 6);
UUIDWrapper wrapper; UUIDWrapper wrapper;
if (Settings.OFFLINE_MODE) { if (Settings.OFFLINE_MODE) {
if (Settings.UUID_LOWERCASE) { if (Settings.UUID_LOWERCASE) {
wrapper = (new LowerOfflineUUIDWrapper()); wrapper = new LowerOfflineUUIDWrapper();
} else { } else {
wrapper = (new OfflineUUIDWrapper()); wrapper = new OfflineUUIDWrapper();
} }
Settings.OFFLINE_MODE = true; Settings.OFFLINE_MODE = true;
} else if (checkVersion) { } else if (checkVersion) {
wrapper = (new DefaultUUIDWrapper()); wrapper = new DefaultUUIDWrapper();
Settings.OFFLINE_MODE = false; Settings.OFFLINE_MODE = false;
} else { } else {
if (Settings.UUID_LOWERCASE) { if (Settings.UUID_LOWERCASE) {
wrapper = (new LowerOfflineUUIDWrapper()); wrapper = new LowerOfflineUUIDWrapper();
} else { } else {
wrapper = (new OfflineUUIDWrapper()); wrapper = new OfflineUUIDWrapper();
} }
Settings.OFFLINE_MODE = true; Settings.OFFLINE_MODE = true;
} }
if (!checkVersion) { if (!checkVersion) {
log(C.PREFIX.s() + " &c[WARN] Titles are disabled - please update your version of Bukkit to support this feature."); log(C.PREFIX + " &c[WARN] Titles are disabled - please update your version of Bukkit to support this feature.");
Settings.TITLES = false; Settings.TITLES = false;
FlagManager.removeFlag(FlagManager.getFlag("titles")); FlagManager.removeFlag(FlagManager.getFlag("titles"));
} else { } else {
AbstractTitle.TITLE_CLASS = new DefaultTitle(); AbstractTitle.TITLE_CLASS = new DefaultTitle_19();
if (wrapper instanceof DefaultUUIDWrapper || wrapper.getClass() == OfflineUUIDWrapper.class && !Bukkit.getOnlineMode()) { if (wrapper instanceof DefaultUUIDWrapper || wrapper.getClass() == OfflineUUIDWrapper.class && !Bukkit.getOnlineMode()) {
Settings.TWIN_MODE_UUID = true; Settings.TWIN_MODE_UUID = true;
} }
} }
if (Settings.OFFLINE_MODE) { if (Settings.OFFLINE_MODE) {
log(C.PREFIX.s() + " &6PlotSquared is using Offline Mode UUIDs either because of user preference, or because you are using an old version of Bukkit"); log(C.PREFIX
+ " &6PlotSquared is using Offline Mode UUIDs either because of user preference, or because you are using an old version of "
+ "Bukkit");
} else { } else {
log(C.PREFIX.s() + " &6PlotSquared is using online UUIDs"); log(C.PREFIX + " &6PlotSquared is using online UUIDs");
}
if (Settings.USE_SQLUUIDHANDLER) {
return new SQLUUIDHandler(wrapper);
} else {
return new FileUUIDHandler(wrapper);
} }
return Settings.USE_SQLUUIDHANDLER ? new SQLUUIDHandler(wrapper) : new FileUUIDHandler(wrapper);
} }
@Override @Override
public ChunkManager initChunkManager() { public ChunkManager initChunkManager() {
return new BukkitChunkManager(); return new BukkitChunkManager();
} }
@Override @Override
public EventUtil initEventUtil() { public EventUtil initEventUtil() {
return new BukkitEventUtil(); return new BukkitEventUtil();
} }
@Override @Override
public void unregister(final PlotPlayer player) { public void unregister(PlotPlayer player) {
BukkitUtil.removePlayer(player.getName()); BukkitUtil.removePlayer(player.getName());
} }
@Override @Override
public void registerChunkProcessor() { public void registerChunkProcessor() {
getServer().getPluginManager().registerEvents(new ChunkListener(), this); getServer().getPluginManager().registerEvents(new ChunkListener(), this);
} }
@Override @Override
public void registerWorldEvents() { public void registerWorldEvents() {
getServer().getPluginManager().registerEvents(new WorldEvents(), this); getServer().getPluginManager().registerEvents(new WorldEvents(), this);
} }
@Override @Override
public InventoryUtil initInventoryUtil() { public InventoryUtil initInventoryUtil() {
return new BukkitInventoryUtil(); return new BukkitInventoryUtil();
} }
@Override @Override
public String getServerName() { public String getServerName() {
return Bukkit.getServerName(); return Bukkit.getServerName();
} }
@Override @Override
public void startMetrics() { public void startMetrics() {
try { Metrics metrics = new Metrics(this);
final Metrics metrics = new Metrics(this); metrics.start();
metrics.start(); log(C.PREFIX + "&6Metrics enabled.");
log(C.PREFIX.s() + "&6Metrics enabled.");
} catch (IOException e) {
log(C.PREFIX.s() + "&cFailed to load up metrics.");
}
} }
@Override @Override
public void setGenerator(final String worldname) { public void setGenerator(String worldName) {
World world = BukkitUtil.getWorld(worldname); World world = BukkitUtil.getWorld(worldName);
if (world == null) { if (world == null) {
// create world // create world
final ConfigurationSection worldConfig = PS.get().config.getConfigurationSection("worlds." + worldname); ConfigurationSection worldConfig = PS.get().config.getConfigurationSection("worlds." + worldName);
String manager = worldConfig.getString("generator.plugin"); String manager = worldConfig.getString("generator.plugin", "PlotSquared");
if (manager == null) { SetupObject setup = new SetupObject();
manager = "PlotSquared";
}
String generator = worldConfig.getString("generator.init");
if (generator == null) {
generator = manager;
}
final int type = worldConfig.getInt("generator.type");
final int terrain = worldConfig.getInt("generator.terrain");
final SetupObject setup = new SetupObject();
setup.plotManager = manager; setup.plotManager = manager;
setup.setupGenerator = generator; setup.setupGenerator = worldConfig.getString("generator.init", manager);
setup.type = type; setup.type = worldConfig.getInt("generator.type");
setup.terrain = terrain; setup.terrain = worldConfig.getInt("generator.terrain");
setup.step = new ConfigurationNode[0]; setup.step = new ConfigurationNode[0];
setup.world = worldname; setup.world = worldName;
SetupUtils.manager.setupWorld(setup); SetupUtils.manager.setupWorld(setup);
} else { } else {
try { try {
if (!PS.get().hasPlotArea(worldname)) { if (!PS.get().hasPlotArea(worldName)) {
SetGenCB.setGenerator(BukkitUtil.getWorld(worldname)); SetGenCB.setGenerator(BukkitUtil.getWorld(worldName));
} }
} catch (final Exception e) { } catch (Exception e) {
log("Failed to reload world: " + world); log("Failed to reload world: " + world);
Bukkit.getServer().unloadWorld(world, false); Bukkit.getServer().unloadWorld(world, false);
} }
} }
world = Bukkit.getWorld(worldname); world = Bukkit.getWorld(worldName);
final ChunkGenerator gen = world.getGenerator(); ChunkGenerator gen = world.getGenerator();
if (gen instanceof BukkitPlotGenerator) { if (gen instanceof BukkitPlotGenerator) {
PS.get().loadWorld(worldname, (BukkitPlotGenerator) gen); PS.get().loadWorld(worldName, (BukkitPlotGenerator) gen);
} else if (gen != null) { } else if (gen != null) {
PS.get().loadWorld(worldname, new BukkitPlotGenerator(worldname, gen)); PS.get().loadWorld(worldName, new BukkitPlotGenerator(worldName, gen));
} else { } else if (PS.get().config.contains("worlds." + worldName)) {
if (PS.get().config.contains("worlds." + worldname)) { PS.get().loadWorld(worldName, null);
PS.get().loadWorld(worldname, null);
}
} }
} }
@Override @Override
public SchematicHandler initSchematicHandler() { public SchematicHandler initSchematicHandler() {
return new BukkitSchematicHandler(); return new BukkitSchematicHandler();
} }
@Override @Override
public AbstractTitle initTitleManager() { public AbstractTitle initTitleManager() {
// Already initialized in UUID handler // Already initialized in UUID handler
return AbstractTitle.TITLE_CLASS; return AbstractTitle.TITLE_CLASS;
} }
@Override @Override
public PlotPlayer wrapPlayer(final Object obj) { public PlotPlayer wrapPlayer(Object player) {
if (obj instanceof Player) { if (player instanceof Player) {
return BukkitUtil.getPlayer((Player) obj); return BukkitUtil.getPlayer((Player) player);
} else if (obj instanceof OfflinePlayer) { } else if (player instanceof OfflinePlayer) {
return BukkitUtil.getPlayer((OfflinePlayer) obj); return BukkitUtil.getPlayer((OfflinePlayer) player);
} else if (obj instanceof String) { } else if (player instanceof String) {
return UUIDHandler.getPlayer((String) obj); return UUIDHandler.getPlayer((String) player);
} else if (obj instanceof UUID) { } else if (player instanceof UUID) {
return UUIDHandler.getPlayer((UUID) obj); return UUIDHandler.getPlayer((UUID) player);
} }
return null; return null;
} }
@Override @Override
public String getNMSPackage() { public String getNMSPackage() {
final Server server = Bukkit.getServer(); String name = Bukkit.getServer().getClass().getPackage().getName();
final Class<?> bukkitServerClass = server.getClass(); return name.substring(name.lastIndexOf('.') + 1);
String[] pas = bukkitServerClass.getName().split("\\.");
if (pas.length == 5) {
return pas[3];
}
try {
final Method getHandle = bukkitServerClass.getDeclaredMethod("getHandle");
final Object handle = getHandle.invoke(server);
final Class handleServerClass = handle.getClass();
pas = handleServerClass.getName().split("\\.");
if (pas.length == 5) {
return pas[3];
}
} catch (IllegalAccessException | InvocationTargetException | SecurityException | NoSuchMethodException | IllegalArgumentException e) {
e.printStackTrace();
}
PS.debug("Unknown NMS package: " + StringMan.getString(pas));
return "1_8_R3";
} }
@Override @Override
public ChatManager<?> initChatManager() { public ChatManager<?> initChatManager() {
if (Settings.FANCY_CHAT) { if (Settings.FANCY_CHAT) {
@ -688,12 +653,12 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
return new BukkitPlainChatManager(); return new BukkitPlainChatManager();
} }
} }
@Override @Override
public GeneratorWrapper<?> wrapPlotGenerator(IndependentPlotGenerator generator) { public GeneratorWrapper<?> wrapPlotGenerator(IndependentPlotGenerator generator) {
return new BukkitPlotGenerator(generator); return new BukkitPlotGenerator(generator);
} }
@Override @Override
public List<String> getPluginIds() { public List<String> getPluginIds() {
ArrayList<String> names = new ArrayList<>(); ArrayList<String> names = new ArrayList<>();

View File

@ -1,11 +1,11 @@
package com.plotsquared.bukkit.chat; package com.plotsquared.bukkit.chat;
import org.apache.commons.lang.Validate;
import java.lang.reflect.Array; import java.lang.reflect.Array;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import org.apache.commons.lang.Validate;
/** /**
* Represents a wrapper around an array class of an arbitrary reference type, * Represents a wrapper around an array class of an arbitrary reference type,
* which properly implements "value" hash code and equality functions. * which properly implements "value" hash code and equality functions.
@ -17,57 +17,17 @@ import org.apache.commons.lang.Validate;
* @see Arrays * @see Arrays
*/ */
public final class ArrayWrapper<E> { public final class ArrayWrapper<E> {
private E[] array;
/** /**
* Creates an array wrapper with some elements. * Creates an array wrapper with some elements.
* @param elements The elements of the array. * @param elements The elements of the array.
*/ */
public ArrayWrapper(final E... elements) { public ArrayWrapper(E... elements) {
setArray(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(final 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(final Object other) {
if (!(other instanceof ArrayWrapper)) {
return false;
}
return Arrays.equals(_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(_array);
}
/** /**
* Converts an iterable element collection to an array of elements. * 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. * The iteration order of the specified object will be used as the array element order.
@ -76,28 +36,66 @@ public final class ArrayWrapper<E> {
* @return An array of elements in the specified iterable. * @return An array of elements in the specified iterable.
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <T> T[] toArray(final Iterable<? extends T> list, final Class<T> c) { public static <T> T[] toArray(Iterable<? extends T> list, Class<T> c) {
int size = -1; int size = -1;
if (list instanceof Collection<?>) { if (list instanceof Collection<?>) {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes") Collection coll = (Collection) list;
final Collection coll = (Collection) list;
size = coll.size(); size = coll.size();
} }
if (size < 0) { if (size < 0) {
size = 0; size = 0;
// Ugly hack: Count it ourselves // Ugly hack: Count it ourselves
for (@SuppressWarnings("unused") for (@SuppressWarnings("unused") T element : list) {
final T element : list) {
size++; size++;
} }
} }
final T[] result = (T[]) Array.newInstance(c, size); T[] result = (T[]) Array.newInstance(c, size);
int i = 0; int i = 0;
for (final T element : list) { // Assumes iteration order is consistent for (T element : list) { // Assumes iteration order is consistent
result[i++] = element; // Assign array element at index THEN increment counter result[i++] = element; // Assign array element at index THEN increment counter
} }
return result; 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

@ -1,19 +1,19 @@
package com.plotsquared.bukkit.chat; package com.plotsquared.bukkit.chat;
import java.io.IOException;
import com.google.gson.stream.JsonWriter; import com.google.gson.stream.JsonWriter;
import java.io.IOException;
/** /**
* Represents an object that can be serialized to a JSON writer instance. * Represents an object that can be serialized to a JSON writer instance.
*/ */
interface JsonRepresentedObject { interface JsonRepresentedObject {
/** /**
* Writes the JSON representation of this object to the specified writer. * Writes the JSON representation of this object to the specified writer.
* @param writer The JSON writer which will receive the object. * @param writer The JSON writer which will receive the object.
* @throws IOException If an error occurs writing to the stream. * @throws IOException If an error occurs writing to the stream.
*/ */
void writeJson(final JsonWriter writer) throws IOException; void writeJson(JsonWriter writer) throws IOException;
} }

View File

@ -1,47 +1,47 @@
package com.plotsquared.bukkit.chat; package com.plotsquared.bukkit.chat;
import com.google.gson.stream.JsonWriter;
import com.intellectualcrafters.configuration.serialization.ConfigurationSerializable;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import com.google.gson.stream.JsonWriter;
import com.intellectualcrafters.configuration.serialization.ConfigurationSerializable;
/** /**
* Represents a JSON string value. * Represents a JSON string value.
* Writes by this object will not write name values nor begin/end objects in the JSON stream. * Writes by this object will not write name values nor begin/end objects in the JSON stream.
* All writes merely write the represented string value. * All writes merely write the represented string value.
*/ */
final class JsonString implements JsonRepresentedObject, ConfigurationSerializable { final class JsonString implements JsonRepresentedObject, ConfigurationSerializable {
private final String _value; private final String value;
public JsonString(final CharSequence value) { public JsonString(CharSequence value) {
_value = value == null ? null : value.toString(); this.value = value == null ? null : value.toString();
} }
@Override public static JsonString deserialize(Map<String, Object> map) {
public void writeJson(final JsonWriter writer) throws IOException {
writer.value(getValue());
}
public String getValue() {
return _value;
}
@Override
public Map<String, Object> serialize() {
final HashMap<String, Object> theSingleValue = new HashMap<String, Object>();
theSingleValue.put("stringValue", _value);
return theSingleValue;
}
public static JsonString deserialize(final Map<String, Object> map) {
return new JsonString(map.get("stringValue").toString()); return new JsonString(map.get("stringValue").toString());
} }
@Override
public void writeJson(JsonWriter writer) throws IOException {
writer.value(getValue());
}
public String getValue() {
return this.value;
}
@Override
public Map<String, Object> serialize() {
HashMap<String, Object> theSingleValue = new HashMap<>();
theSingleValue.put("stringValue", this.value);
return theSingleValue;
}
@Override @Override
public String toString() { public String toString() {
return _value; return this.value;
} }
} }

View File

@ -22,8 +22,8 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa
static final BiMap<ChatColor, String> stylesToNames; static final BiMap<ChatColor, String> stylesToNames;
static { static {
final ImmutableBiMap.Builder<ChatColor, String> builder = ImmutableBiMap.builder(); ImmutableBiMap.Builder<ChatColor, String> builder = ImmutableBiMap.builder();
for (final ChatColor style : ChatColor.values()) { for (ChatColor style : ChatColor.values()) {
if (!style.isFormat()) { if (!style.isFormat()) {
continue; continue;
} }
@ -51,24 +51,24 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa
} }
ChatColor color = ChatColor.WHITE; ChatColor color = ChatColor.WHITE;
ArrayList<ChatColor> styles = new ArrayList<ChatColor>(); ArrayList<ChatColor> styles = new ArrayList<>();
String clickActionName = null, clickActionData = null, hoverActionName = null; String clickActionName = null, clickActionData = null, hoverActionName = null;
JsonRepresentedObject hoverActionData = null; JsonRepresentedObject hoverActionData = null;
TextualComponent text = null; TextualComponent text = null;
String insertionData = null; String insertionData = null;
ArrayList<JsonRepresentedObject> translationReplacements = new ArrayList<JsonRepresentedObject>(); ArrayList<JsonRepresentedObject> translationReplacements = new ArrayList<>();
MessagePart(final TextualComponent text) { MessagePart(TextualComponent text) {
this.text = text; this.text = text;
} }
MessagePart() { MessagePart() {
text = null; this.text = null;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static MessagePart deserialize(final Map<String, Object> serialized) { public static MessagePart deserialize(Map<String, Object> serialized) {
final MessagePart part = new MessagePart((TextualComponent) serialized.get("text")); MessagePart part = new MessagePart((TextualComponent) serialized.get("text"));
part.styles = (ArrayList<ChatColor>) serialized.get("styles"); part.styles = (ArrayList<ChatColor>) serialized.get("styles");
part.color = ChatColor.getByChar(serialized.get("color").toString()); part.color = ChatColor.getByChar(serialized.get("color").toString());
part.hoverActionName = (String) serialized.get("hoverActionName"); part.hoverActionName = (String) serialized.get("hoverActionName");
@ -81,70 +81,71 @@ final class MessagePart implements JsonRepresentedObject, ConfigurationSerializa
} }
boolean hasText() { boolean hasText() {
return text != null; return this.text != null;
} }
@Override @Override
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public MessagePart clone() throws CloneNotSupportedException { public MessagePart clone() throws CloneNotSupportedException {
final MessagePart obj = (MessagePart) super.clone(); MessagePart obj = (MessagePart) super.clone();
obj.styles = (ArrayList<ChatColor>) styles.clone(); obj.styles = (ArrayList<ChatColor>) this.styles.clone();
if (hoverActionData instanceof JsonString) { if (this.hoverActionData instanceof JsonString) {
obj.hoverActionData = new JsonString(((JsonString) hoverActionData).getValue()); obj.hoverActionData = new JsonString(((JsonString) this.hoverActionData).getValue());
} else if (hoverActionData instanceof FancyMessage) { } else if (this.hoverActionData instanceof FancyMessage) {
obj.hoverActionData = ((FancyMessage) hoverActionData).clone(); obj.hoverActionData = ((FancyMessage) this.hoverActionData).clone();
} }
obj.translationReplacements = (ArrayList<JsonRepresentedObject>) translationReplacements.clone(); obj.translationReplacements = (ArrayList<JsonRepresentedObject>) this.translationReplacements.clone();
return obj; return obj;
} }
@Override @Override
public void writeJson(final JsonWriter json) { public void writeJson(JsonWriter json) {
try { try {
json.beginObject(); json.beginObject();
text.writeJson(json); this.text.writeJson(json);
json.name("color").value(color.name().toLowerCase()); json.name("color").value(this.color.name().toLowerCase());
for (final ChatColor style : styles) { for (ChatColor style : this.styles) {
json.name(stylesToNames.get(style)).value(true); json.name(stylesToNames.get(style)).value(true);
} }
if ((clickActionName != null) && (clickActionData != null)) { if ((this.clickActionName != null) && (this.clickActionData != null)) {
json.name("clickEvent").beginObject().name("action").value(clickActionName).name("value").value(clickActionData).endObject(); json.name("clickEvent").beginObject().name("action").value(this.clickActionName).name("value").value(this.clickActionData)
.endObject();
} }
if ((hoverActionName != null) && (hoverActionData != null)) { if ((this.hoverActionName != null) && (this.hoverActionData != null)) {
json.name("hoverEvent").beginObject().name("action").value(hoverActionName).name("value"); json.name("hoverEvent").beginObject().name("action").value(this.hoverActionName).name("value");
hoverActionData.writeJson(json); this.hoverActionData.writeJson(json);
json.endObject(); json.endObject();
} }
if (insertionData != null) { if (this.insertionData != null) {
json.name("insertion").value(insertionData); json.name("insertion").value(this.insertionData);
} }
if ((!translationReplacements.isEmpty()) && (text != null) && TextualComponent.isTranslatableText(text)) { if (!this.translationReplacements.isEmpty() && (this.text != null) && TextualComponent.isTranslatableText(this.text)) {
json.name("with").beginArray(); json.name("with").beginArray();
for (final JsonRepresentedObject obj : translationReplacements) { for (JsonRepresentedObject obj : this.translationReplacements) {
obj.writeJson(json); obj.writeJson(json);
} }
json.endArray(); json.endArray();
} }
json.endObject(); json.endObject();
} catch (final IOException e) { } catch (IOException e) {
Bukkit.getLogger().log(Level.WARNING, "A problem occurred during writing of JSON string", e); Bukkit.getLogger().log(Level.WARNING, "A problem occurred during writing of JSON string", e);
} }
} }
@Override @Override
public Map<String, Object> serialize() { public Map<String, Object> serialize() {
final HashMap<String, Object> map = new HashMap<String, Object>(); HashMap<String, Object> map = new HashMap<>();
map.put("text", text); map.put("text", this.text);
map.put("styles", styles); map.put("styles", this.styles);
map.put("color", color.getChar()); map.put("color", this.color.getChar());
map.put("hoverActionName", hoverActionName); map.put("hoverActionName", this.hoverActionName);
map.put("hoverActionData", hoverActionData); map.put("hoverActionData", this.hoverActionData);
map.put("clickActionName", clickActionName); map.put("clickActionName", this.clickActionName);
map.put("clickActionData", clickActionData); map.put("clickActionData", this.clickActionData);
map.put("insertion", insertionData); map.put("insertion", this.insertionData);
map.put("translationReplacements", translationReplacements); map.put("translationReplacements", this.translationReplacements);
return map; return map;
} }
} }

View File

@ -1,6 +1,6 @@
package com.plotsquared.bukkit.chat; package com.plotsquared.bukkit.chat;
import org.bukkit.Bukkit; import com.intellectualcrafters.plot.PS;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
@ -29,42 +29,29 @@ public final class Reflection {
* The map maps [types to maps of [method names to maps of [parameter types to method instances]]]. * 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 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. * 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. * 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>. * @return The version string of the OBC and NMS packages, <em>including the trailing dot</em>.
*/ */
public synchronized static String getVersion() { public static synchronized String getVersion() {
if (_versionString == null) { return PS.get().IMP.getNMSPackage();
if (Bukkit.getServer() == null) {
// The server hasn't started, static initializer call?
return null;
}
final 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. * 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. * @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. * @return The class instance representing the specified NMS class, or {@code null} if it could not be loaded.
*/ */
public synchronized static Class<?> getNMSClass(final String className) { public static synchronized Class<?> getNMSClass(String className) {
if (_loadedNMSClasses.containsKey(className)) { if (_loadedNMSClasses.containsKey(className)) {
return _loadedNMSClasses.get(className); return _loadedNMSClasses.get(className);
} }
final String fullName = "net.minecraft.server." + getVersion() + className; String fullName = "net.minecraft.server." + getVersion() + "." + className;
Class<?> clazz; Class<?> clazz;
try { try {
clazz = Class.forName(fullName); clazz = Class.forName(fullName);
@ -76,7 +63,7 @@ public final class Reflection {
_loadedNMSClasses.put(className, clazz); _loadedNMSClasses.put(className, clazz);
return clazz; return clazz;
} }
/** /**
* Gets a {@link Class} object representing a type contained within the {@code org.bukkit.craftbukkit} versioned package. * 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 * The class instances returned by this method are cached, such that no lookup will be done twice (unless multiple threads are accessing this
@ -85,12 +72,12 @@ public final class Reflection {
* .CraftItemStack}. * .CraftItemStack}.
* @return The class instance representing the specified OBC class, or {@code null} if it could not be loaded. * @return The class instance representing the specified OBC class, or {@code null} if it could not be loaded.
*/ */
public synchronized static Class<?> getOBCClass(final String className) { public static synchronized Class<?> getOBCClass(String className) {
if (_loadedOBCClasses.containsKey(className)) { if (_loadedOBCClasses.containsKey(className)) {
return _loadedOBCClasses.get(className); return _loadedOBCClasses.get(className);
} }
final String fullName = "org.bukkit.craftbukkit." + getVersion() + className; String fullName = "org.bukkit.craftbukkit." + getVersion() + "." + className;
Class<?> clazz; Class<?> clazz;
try { try {
clazz = Class.forName(fullName); clazz = Class.forName(fullName);
@ -102,7 +89,7 @@ public final class Reflection {
_loadedOBCClasses.put(className, clazz); _loadedOBCClasses.put(className, clazz);
return clazz; return clazz;
} }
/** /**
* Attempts to get the NMS handle of a CraftBukkit object. * Attempts to get the NMS handle of a CraftBukkit object.
* <p> * <p>
@ -112,25 +99,20 @@ public final class Reflection {
* @param obj The object for which to retrieve an NMS handle. * @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()}. * @return The NMS handle of the specified object, or {@code null} if it could not be retrieved using {@code getHandle()}.
*/ */
public synchronized static Object getHandle(final Object obj) { public static synchronized Object getHandle(Object obj) {
try { try {
return getMethod(obj.getClass(), "getHandle").invoke(obj); return getMethod(obj.getClass(), "getHandle").invoke(obj);
} catch (IllegalAccessException e) { } catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException e) {
e.printStackTrace();
return null;
} catch (IllegalArgumentException e) {
e.printStackTrace();
return null;
} catch (InvocationTargetException e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
} }
/** /**
* Retrieves a {@link Field} instance declared by the specified class with the specified name. * 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 * Java access modifiers are ignored during this retrieval.
* returned will be an instance or static field. * No guarantee is made as to whether the field returned will be an
* instance or static field.
* <p> * <p>
* A global caching mechanism within this class is used to store fields. Combined with synchronization, this guarantees that * 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. * no field will be reflectively looked up twice.
@ -145,7 +127,7 @@ public final class Reflection {
* @return A field object with the specified name declared by the specified class. * @return A field object with the specified name declared by the specified class.
* @see Class#getDeclaredField(String) * @see Class#getDeclaredField(String)
*/ */
public synchronized static Field getField(final Class<?> clazz, final String name) { public static synchronized Field getField(Class<?> clazz, String name) {
Map<String, Field> loaded; Map<String, Field> loaded;
if (!_loadedFields.containsKey(clazz)) { if (!_loadedFields.containsKey(clazz)) {
loaded = new HashMap<>(); loaded = new HashMap<>();
@ -158,17 +140,11 @@ public final class Reflection {
return loaded.get(name); return loaded.get(name);
} }
try { try {
final Field field = clazz.getDeclaredField(name); Field field = clazz.getDeclaredField(name);
field.setAccessible(true); field.setAccessible(true);
loaded.put(name, field); loaded.put(name, field);
return field; return field;
} catch (NoSuchFieldException e) { } catch (NoSuchFieldException | SecurityException e) {
// Error loading
e.printStackTrace();
// Cache field as not existing
loaded.put(name, null);
return null;
} catch (SecurityException e) {
// Error loading // Error loading
e.printStackTrace(); e.printStackTrace();
// Cache field as not existing // Cache field as not existing
@ -176,7 +152,7 @@ public final class Reflection {
return null; return null;
} }
} }
/** /**
* Retrieves a {@link Method} instance declared by the specified class with the specified name and argument types. * Retrieves a {@link Method} instance declared by the specified class with the specified name and argument types.
* Java access modifiers are ignored during this retrieval. No guarantee is made as to whether the field * Java access modifiers are ignored during this retrieval. No guarantee is made as to whether the field
@ -186,9 +162,11 @@ public final class Reflection {
* no method will be reflectively looked up twice. * no method will be reflectively looked up twice.
* </p> * </p>
* <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. * This ensures that callers do not have to check or worry about Java access modifiers when dealing with the returned instance.
* </p> * </p>
*
* <p> * <p>
* This method does <em>not</em> search superclasses of the specified type for methods with the specified signature. * 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...)}. * Callers wishing this behavior should use {@link Class#getDeclaredMethod(String, Class...)}.
@ -197,23 +175,23 @@ public final class Reflection {
* @param args The formal argument types of the method. * @param args The formal argument types of the method.
* @return A method object with the specified name declared by the specified class. * @return A method object with the specified name declared by the specified class.
*/ */
public synchronized static Method getMethod(final Class<?> clazz, final String name, final Class<?>... args) { public static synchronized Method getMethod(Class<?> clazz, String name, Class<?>... args) {
if (!_loadedMethods.containsKey(clazz)) { if (!_loadedMethods.containsKey(clazz)) {
_loadedMethods.put(clazz, new HashMap<String, Map<ArrayWrapper<Class<?>>, Method>>()); _loadedMethods.put(clazz, new HashMap<String, Map<ArrayWrapper<Class<?>>, Method>>());
} }
final Map<String, Map<ArrayWrapper<Class<?>>, Method>> loadedMethodNames = _loadedMethods.get(clazz); Map<String, Map<ArrayWrapper<Class<?>>, Method>> loadedMethodNames = _loadedMethods.get(clazz);
if (!loadedMethodNames.containsKey(name)) { if (!loadedMethodNames.containsKey(name)) {
loadedMethodNames.put(name, new HashMap<ArrayWrapper<Class<?>>, Method>()); loadedMethodNames.put(name, new HashMap<ArrayWrapper<Class<?>>, Method>());
} }
final Map<ArrayWrapper<Class<?>>, Method> loadedSignatures = loadedMethodNames.get(name); Map<ArrayWrapper<Class<?>>, Method> loadedSignatures = loadedMethodNames.get(name);
final ArrayWrapper<Class<?>> wrappedArg = new ArrayWrapper<>(args); ArrayWrapper<Class<?>> wrappedArg = new ArrayWrapper<>(args);
if (loadedSignatures.containsKey(wrappedArg)) { if (loadedSignatures.containsKey(wrappedArg)) {
return loadedSignatures.get(wrappedArg); return loadedSignatures.get(wrappedArg);
} }
for (final Method m : clazz.getMethods()) { for (Method m : clazz.getMethods()) {
if (m.getName().equals(name) && Arrays.equals(args, m.getParameterTypes())) { if (m.getName().equals(name) && Arrays.equals(args, m.getParameterTypes())) {
m.setAccessible(true); m.setAccessible(true);
loadedSignatures.put(wrappedArg, m); loadedSignatures.put(wrappedArg, m);
@ -223,5 +201,5 @@ public final class Reflection {
loadedSignatures.put(wrappedArg, null); loadedSignatures.put(wrappedArg, null);
return null; return null;
} }
} }

View File

@ -23,6 +23,107 @@ public abstract class TextualComponent implements Cloneable {
ConfigurationSerialization.registerClass(TextualComponent.ComplexTextTypeComponent.class); ConfigurationSerialization.registerClass(TextualComponent.ComplexTextTypeComponent.class);
} }
static TextualComponent deserialize(Map<String, Object> map) {
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 */) {
// Complex JSON object
return ComplexTextTypeComponent.deserialize(map);
}
return null;
}
static boolean isTextKey(String key) {
return key.equals("translate") || key.equals("text") || key.equals("score") || key.equals("selector");
}
static boolean isTranslatableText(TextualComponent component) {
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.
* @param textValue The text which will be represented.
* @return The text component representing the specified literal text.
*/
public static TextualComponent rawText(String textValue) {
return new ArbitraryTextTypeComponent("text", textValue);
}
/**
* Create a textual component representing a localized string.
* The client will see this text component as their localized version of the specified string <em>key</em>, which can be overridden by a
* resource pack.
* <p>
* 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.
*/
public static TextualComponent localizedText(String translateKey) {
return new ArbitraryTextTypeComponent("translate", translateKey);
}
private static void throwUnsupportedSnapshot() {
throw new UnsupportedOperationException("This feature is only supported in snapshot releases.");
}
/**
* Create a textual component representing a scoreboard value.
* The client will see their own score 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 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.
*/
public static TextualComponent objectiveScore(String scoreboardObjective) {
return objectiveScore("*", scoreboardObjective);
}
/**
* 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.
*/
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());
}
/**
* Create a textual component representing a player name, retrievable by using a standard minecraft selector.
* The client will see the players or entities captured by the specified selector 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 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.
*/
public static TextualComponent selector(String selector) {
throwUnsupportedSnapshot(); // Remove this line when the feature is released to non-snapshot versions, in addition to updating ALL THE
// OVERLOADS documentation accordingly
return new ArbitraryTextTypeComponent("selector", selector);
}
@Override @Override
public String toString() { public String toString() {
return getReadableString(); return getReadableString();
@ -51,27 +152,7 @@ public abstract class TextualComponent implements Cloneable {
* @param writer The object to which to write the JSON data. * @param writer The object to which to write the JSON data.
* @throws IOException If an error occurs while writing to the stream. * @throws IOException If an error occurs while writing to the stream.
*/ */
public abstract void writeJson(final JsonWriter writer) throws IOException; public abstract void writeJson(JsonWriter writer) throws IOException;
static TextualComponent deserialize(final Map<String, Object> map) {
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 */) {
// Complex JSON object
return ComplexTextTypeComponent.deserialize(map);
}
return null;
}
static boolean isTextKey(final String key) {
return key.equals("translate") || key.equals("text") || key.equals("score") || key.equals("selector");
}
static boolean isTranslatableText(final TextualComponent component) {
return (component instanceof ComplexTextTypeComponent) && ((ComplexTextTypeComponent) component).getKey().equals("translate");
}
/** /**
* Internal class used to represent all types of text components. * Internal class used to represent all types of text components.
@ -79,33 +160,37 @@ public abstract class TextualComponent implements Cloneable {
*/ */
private static final class ArbitraryTextTypeComponent extends TextualComponent implements ConfigurationSerializable { private static final class ArbitraryTextTypeComponent extends TextualComponent implements ConfigurationSerializable {
public ArbitraryTextTypeComponent(final String key, final String value) { private String _key;
private String _value;
public ArbitraryTextTypeComponent(String key, String value) {
setKey(key); setKey(key);
setValue(value); setValue(value);
} }
@Override public static ArbitraryTextTypeComponent deserialize(Map<String, Object> map) {
public String getKey() { return new ArbitraryTextTypeComponent(map.get("key").toString(), map.get("value").toString());
return _key;
} }
public void setKey(final String key) { @Override
public String getKey() {
return this._key;
}
public void setKey(String key) {
Preconditions.checkArgument((key != null) && !key.isEmpty(), "The key must be specified."); Preconditions.checkArgument((key != null) && !key.isEmpty(), "The key must be specified.");
_key = key; this._key = key;
} }
public String getValue() { public String getValue() {
return _value; return this._value;
} }
public void setValue(final String value) { public void setValue(String value) {
Preconditions.checkArgument(value != null, "The value must be specified."); Preconditions.checkArgument(value != null, "The value must be specified.");
_value = value; this._value = value;
} }
private String _key;
private String _value;
@Override @Override
public TextualComponent clone() throws CloneNotSupportedException { public TextualComponent clone() throws CloneNotSupportedException {
// Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone // Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone
@ -113,7 +198,7 @@ public abstract class TextualComponent implements Cloneable {
} }
@Override @Override
public void writeJson(final JsonWriter writer) throws IOException { public void writeJson(JsonWriter writer) throws IOException {
writer.name(getKey()).value(getValue()); writer.name(getKey()).value(getValue());
} }
@ -128,10 +213,6 @@ public abstract class TextualComponent implements Cloneable {
}; };
} }
public static ArbitraryTextTypeComponent deserialize(final Map<String, Object> map) {
return new ArbitraryTextTypeComponent(map.get("key").toString(), map.get("value").toString());
}
@Override @Override
public String getReadableString() { public String getReadableString() {
return getValue(); return getValue();
@ -144,33 +225,46 @@ public abstract class TextualComponent implements Cloneable {
*/ */
private static final class ComplexTextTypeComponent extends TextualComponent implements ConfigurationSerializable { private static final class ComplexTextTypeComponent extends TextualComponent implements ConfigurationSerializable {
public ComplexTextTypeComponent(final String key, final Map<String, String> values) { private String _key;
private Map<String, String> _value;
public ComplexTextTypeComponent(String key, Map<String, String> values) {
setKey(key); setKey(key);
setValue(values); setValue(values);
} }
@Override public static ComplexTextTypeComponent deserialize(Map<String, Object> map) {
public String getKey() { String key = null;
return _key; Map<String, String> value = new HashMap<String, String>();
for (Map.Entry<String, Object> valEntry : map.entrySet()) {
if (valEntry.getKey().equals("key")) {
key = (String) valEntry.getValue();
} else if (valEntry.getKey().startsWith("value.")) {
value.put(valEntry.getKey().substring(6) /* Strips out the value prefix */, valEntry.getValue().toString());
}
}
return new ComplexTextTypeComponent(key, value);
} }
public void setKey(final String key) { @Override
public String getKey() {
return this._key;
}
public void setKey(String key) {
Preconditions.checkArgument((key != null) && !key.isEmpty(), "The key must be specified."); Preconditions.checkArgument((key != null) && !key.isEmpty(), "The key must be specified.");
_key = key; this._key = key;
} }
public Map<String, String> getValue() { public Map<String, String> getValue() {
return _value; return this._value;
} }
public void setValue(final Map<String, String> value) { public void setValue(Map<String, String> value) {
Preconditions.checkArgument(value != null, "The value must be specified."); Preconditions.checkArgument(value != null, "The value must be specified.");
_value = value; this._value = value;
} }
private String _key;
private Map<String, String> _value;
@Override @Override
public TextualComponent clone() throws CloneNotSupportedException { public TextualComponent clone() throws CloneNotSupportedException {
// Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone // Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone
@ -178,10 +272,10 @@ public abstract class TextualComponent implements Cloneable {
} }
@Override @Override
public void writeJson(final JsonWriter writer) throws IOException { public void writeJson(JsonWriter writer) throws IOException {
writer.name(getKey()); writer.name(getKey());
writer.beginObject(); writer.beginObject();
for (final Map.Entry<String, String> jsonPair : _value.entrySet()) { for (Map.Entry<String, String> jsonPair : this._value.entrySet()) {
writer.name(jsonPair.getKey()).value(jsonPair.getValue()); writer.name(jsonPair.getKey()).value(jsonPair.getValue());
} }
writer.endObject(); writer.endObject();
@ -193,101 +287,16 @@ public abstract class TextualComponent implements Cloneable {
return new java.util.HashMap<String, Object>() { return new java.util.HashMap<String, Object>() {
{ {
put("key", getKey()); put("key", getKey());
for (final Map.Entry<String, String> valEntry : getValue().entrySet()) { for (Map.Entry<String, String> valEntry : getValue().entrySet()) {
put("value." + valEntry.getKey(), valEntry.getValue()); put("value." + valEntry.getKey(), valEntry.getValue());
} }
} }
}; };
} }
public static ComplexTextTypeComponent deserialize(final Map<String, Object> map) {
String key = null;
final Map<String, String> value = new HashMap<String, String>();
for (final Map.Entry<String, Object> valEntry : map.entrySet()) {
if (valEntry.getKey().equals("key")) {
key = (String) valEntry.getValue();
} else if (valEntry.getKey().startsWith("value.")) {
value.put(valEntry.getKey().substring(6) /* Strips out the value prefix */, valEntry.getValue().toString());
}
}
return new ComplexTextTypeComponent(key, value);
}
@Override @Override
public String getReadableString() { public String getReadableString() {
return getKey(); return getKey();
} }
} }
/**
* 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.
* @param textValue The text which will be represented.
* @return The text component representing the specified literal text.
*/
public static TextualComponent rawText(final String textValue) {
return new ArbitraryTextTypeComponent("text", textValue);
}
/**
* Create a textual component representing a localized string.
* The client will see this text component as their localized version of the specified string <em>key</em>, which can be overridden by a resource pack.
* <p>
* 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.
*/
public static TextualComponent localizedText(final String translateKey) {
return new ArbitraryTextTypeComponent("translate", translateKey);
}
private static void throwUnsupportedSnapshot() {
throw new UnsupportedOperationException("This feature is only supported in snapshot releases.");
}
/**
* Create a textual component representing a scoreboard value.
* The client will see their own score 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 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.
*/
public static TextualComponent objectiveScore(final String scoreboardObjective) {
return objectiveScore("*", scoreboardObjective);
}
/**
* 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.
*/
public static TextualComponent objectiveScore(final String playerName, final 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());
}
/**
* Create a textual component representing a player name, retrievable by using a standard minecraft selector.
* The client will see the players or entities captured by the specified selector 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 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.
*/
public static TextualComponent selector(final String selector) {
throwUnsupportedSnapshot(); // Remove this line when the feature is released to non-snapshot versions, in addition to updating ALL THE OVERLOADS documentation accordingly
return new ArbitraryTextTypeComponent("selector", selector);
}
} }

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.commands; package com.plotsquared.bukkit.commands;
import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS;
@ -56,23 +36,23 @@ import java.util.Map.Entry;
import java.util.UUID; import java.util.UUID;
@CommandDeclaration( @CommandDeclaration(
command = "uuidconvert", command = "uuidconvert",
permission = "plots.admin", permission = "plots.admin",
description = "Debug UUID conversion", description = "Debug UUID conversion",
usage = "/plot uuidconvert <lower|offline|online>", usage = "/plot uuidconvert <lower|offline|online>",
requiredType = RequiredType.CONSOLE, requiredType = RequiredType.CONSOLE,
category = CommandCategory.DEBUG) category = CommandCategory.DEBUG)
public class DebugUUID extends SubCommand { public class DebugUUID extends SubCommand {
public DebugUUID() { public DebugUUID() {
requiredArguments = new Argument[] { Argument.String }; super(Argument.String);
} }
@Override @Override
public boolean onCommand(final PlotPlayer player, final String[] args) { public boolean onCommand(final PlotPlayer player, String[] args) {
final UUIDWrapper currentUUIDWrapper = UUIDHandler.getUUIDWrapper(); final UUIDWrapper currentUUIDWrapper = UUIDHandler.getUUIDWrapper();
final UUIDWrapper newWrapper; final UUIDWrapper newWrapper;
switch (args[0].toLowerCase()) { switch (args[0].toLowerCase()) {
case "lower": case "lower":
newWrapper = new LowerOfflineUUIDWrapper(); newWrapper = new LowerOfflineUUIDWrapper();
@ -85,7 +65,7 @@ public class DebugUUID extends SubCommand {
break; break;
default: default:
try { try {
final Class<?> clazz = Class.forName(args[0]); Class<?> clazz = Class.forName(args[0]);
newWrapper = (UUIDWrapper) clazz.newInstance(); newWrapper = (UUIDWrapper) clazz.newInstance();
} catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) { } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot uuidconvert <lower|offline|online>"); MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot uuidconvert <lower|offline|online>");
@ -104,7 +84,7 @@ public class DebugUUID extends SubCommand {
MainUtil.sendMessage(player, "&7Retype the command with the override parameter when ready :)"); MainUtil.sendMessage(player, "&7Retype the command with the override parameter when ready :)");
return false; return false;
} }
if (currentUUIDWrapper.getClass().getCanonicalName().equals(newWrapper.getClass().getCanonicalName())) { if (currentUUIDWrapper.getClass().getCanonicalName().equals(newWrapper.getClass().getCanonicalName())) {
MainUtil.sendMessage(player, "&cUUID mode already in use!"); MainUtil.sendMessage(player, "&cUUID mode already in use!");
return false; return false;
@ -114,69 +94,70 @@ public class DebugUUID extends SubCommand {
for (Entry<String, PlotPlayer> entry : UUIDHandler.getPlayers().entrySet()) { 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("PlotSquared UUID conversion has been initiated. You may reconnect when finished.");
} }
MainUtil.sendMessage(player, "&7 - Initializing map"); MainUtil.sendMessage(player, "&7 - Initializing map");
final HashMap<UUID, UUID> uCMap = new HashMap<>(); final HashMap<UUID, UUID> uCMap = new HashMap<>();
final HashMap<UUID, UUID> uCReverse = new HashMap<>(); final HashMap<UUID, UUID> uCReverse = new HashMap<>();
MainUtil.sendMessage(player, "&7 - Collecting playerdata"); MainUtil.sendMessage(player, "&7 - Collecting playerdata");
final HashSet<String> worlds = new HashSet<>(); HashSet<String> worlds = new HashSet<>();
worlds.add(WorldUtil.IMP.getMainWorld()); worlds.add(WorldUtil.IMP.getMainWorld());
worlds.add("world"); worlds.add("world");
final HashSet<UUID> uuids = new HashSet<>(); HashSet<UUID> uuids = new HashSet<>();
final HashSet<String> names = new HashSet<>(); HashSet<String> names = new HashSet<>();
for (final String worldname : worlds) { for (String worldName : worlds) {
final File playerdataFolder = new File(worldname + File.separator + "playerdata"); File playerDataFolder = new File(worldName + File.separator + "playerdata");
String[] dat = playerdataFolder.list(new FilenameFilter() { String[] dat = playerDataFolder.list(new FilenameFilter() {
@Override @Override
public boolean accept(final File f, final String s) { public boolean accept(File f, String s) {
return s.endsWith(".dat");
}
});
if (dat != null)
for (final String current : dat) {
final String s = current.replaceAll(".dat$", "");
try {
final UUID uuid = UUID.fromString(s);
uuids.add(uuid);
} catch (final Exception e) {
MainUtil.sendMessage(player, C.PREFIX.s() + "Invalid playerdata: " + current);
}
}
final File playersFolder = new File(worldname + File.separator + "players");
dat = playersFolder.list(new FilenameFilter() {
@Override
public boolean accept(final File f, final String s) {
return s.endsWith(".dat"); return s.endsWith(".dat");
} }
}); });
if (dat != null) { if (dat != null) {
for (final String current : dat) { for (String current : dat) {
String s = current.replaceAll(".dat$", "");
try {
UUID uuid = UUID.fromString(s);
uuids.add(uuid);
} catch (Exception e) {
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");
}
});
if (dat != null) {
for (String current : dat) {
names.add(current.replaceAll(".dat$", "")); names.add(current.replaceAll(".dat$", ""));
} }
} }
} }
MainUtil.sendMessage(player, "&7 - Populating map"); MainUtil.sendMessage(player, "&7 - Populating map");
UUID uuid2; UUID uuid2;
final UUIDWrapper wrapper = new DefaultUUIDWrapper(); UUIDWrapper wrapper = new DefaultUUIDWrapper();
for (UUID uuid : uuids) { for (UUID uuid : uuids) {
try { try {
final OfflinePlotPlayer op = wrapper.getOfflinePlayer(uuid); OfflinePlotPlayer op = wrapper.getOfflinePlayer(uuid);
uuid = currentUUIDWrapper.getUUID(op); uuid = currentUUIDWrapper.getUUID(op);
uuid2 = newWrapper.getUUID(op); uuid2 = newWrapper.getUUID(op);
if (!uuid.equals(uuid2) && !uCMap.containsKey(uuid) && !uCReverse.containsKey(uuid2)) { if (!uuid.equals(uuid2) && !uCMap.containsKey(uuid) && !uCReverse.containsKey(uuid2)) {
uCMap.put(uuid, uuid2); uCMap.put(uuid, uuid2);
uCReverse.put(uuid2, uuid); uCReverse.put(uuid2, uuid);
} }
} catch (final Throwable e) { } catch (Throwable e) {
MainUtil.sendMessage(player, C.PREFIX.s() + "&6Invalid playerdata: " + uuid.toString() + ".dat"); MainUtil.sendMessage(player, C.PREFIX + "&6Invalid playerdata: " + uuid.toString() + ".dat");
} }
} }
for (final String name : names) { for (String name : names) {
final UUID uuid = currentUUIDWrapper.getUUID(name); UUID uuid = currentUUIDWrapper.getUUID(name);
uuid2 = newWrapper.getUUID(name); uuid2 = newWrapper.getUUID(name);
if (!uuid.equals(uuid2)) { if (!uuid.equals(uuid2)) {
uCMap.put(uuid, uuid2); uCMap.put(uuid, uuid2);
@ -185,11 +166,11 @@ public class DebugUUID extends SubCommand {
} }
if (uCMap.isEmpty()) { if (uCMap.isEmpty()) {
MainUtil.sendMessage(player, "&c - Error! Attempting to repopulate"); MainUtil.sendMessage(player, "&c - Error! Attempting to repopulate");
for (final OfflinePlotPlayer op : currentUUIDWrapper.getOfflinePlayers()) { for (OfflinePlotPlayer op : currentUUIDWrapper.getOfflinePlayers()) {
if (op.getLastPlayed() != 0) { if (op.getLastPlayed() != 0) {
// String name = op.getName(); // String name = op.getName();
// StringWrapper wrap = new StringWrapper(name); // StringWrapper wrap = new StringWrapper(name);
final UUID uuid = currentUUIDWrapper.getUUID(op); UUID uuid = currentUUIDWrapper.getUUID(op);
uuid2 = newWrapper.getUUID(op); uuid2 = newWrapper.getUUID(op);
if (!uuid.equals(uuid2)) { if (!uuid.equals(uuid2)) {
uCMap.put(uuid, uuid2); uCMap.put(uuid, uuid2);
@ -204,24 +185,24 @@ public class DebugUUID extends SubCommand {
MainUtil.sendMessage(player, "&a - Successfully repopulated"); MainUtil.sendMessage(player, "&a - Successfully repopulated");
} }
} }
MainUtil.sendMessage(player, "&7 - Replacing cache"); MainUtil.sendMessage(player, "&7 - Replacing cache");
TaskManager.runTaskAsync(new Runnable() { TaskManager.runTaskAsync(new Runnable() {
@Override @Override
public void run() { public void run() {
for (final Entry<UUID, UUID> entry : uCMap.entrySet()) { for (Entry<UUID, UUID> entry : uCMap.entrySet()) {
final String name = UUIDHandler.getName(entry.getKey()); String name = UUIDHandler.getName(entry.getKey());
if (name != null) { if (name != null) {
UUIDHandler.add(new StringWrapper(name), entry.getValue()); UUIDHandler.add(new StringWrapper(name), entry.getValue());
} }
} }
MainUtil.sendMessage(player, "&7 - Scanning for applicable files (uuids.txt)"); MainUtil.sendMessage(player, "&7 - Scanning for applicable files (uuids.txt)");
final File file = new File(PS.get().IMP.getDirectory(), "uuids.txt"); File file = new File(PS.get().IMP.getDirectory(), "uuids.txt");
if (file.exists()) { if (file.exists()) {
try { try {
final List<String> lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); List<String> lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
for (String line : lines) { for (String line : lines) {
try { try {
line = line.trim(); line = line.trim();
@ -229,35 +210,35 @@ public class DebugUUID extends SubCommand {
continue; continue;
} }
line = line.replaceAll("[\\|][0-9]+[\\|][0-9]+[\\|]", ""); line = line.replaceAll("[\\|][0-9]+[\\|][0-9]+[\\|]", "");
final String[] split = line.split("\\|"); String[] split = line.split("\\|");
final String name = split[0]; String name = split[0];
if (name.isEmpty() || name.length() > 16 || !StringMan.isAlphanumericUnd(name)) { if (name.isEmpty() || name.length() > 16 || !StringMan.isAlphanumericUnd(name)) {
continue; continue;
} }
final UUID old = currentUUIDWrapper.getUUID(name); UUID old = currentUUIDWrapper.getUUID(name);
if (old == null) { if (old == null) {
continue; continue;
} }
final UUID now = newWrapper.getUUID(name); UUID now = newWrapper.getUUID(name);
UUIDHandler.add(new StringWrapper(name), now); UUIDHandler.add(new StringWrapper(name), now);
uCMap.put(old, now); uCMap.put(old, now);
uCReverse.put(now, old); uCReverse.put(now, old);
} catch (final Exception e2) { } catch (Exception e2) {
e2.printStackTrace(); e2.printStackTrace();
} }
} }
} catch (final IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
MainUtil.sendMessage(player, "&7 - Replacing wrapper"); MainUtil.sendMessage(player, "&7 - Replacing wrapper");
UUIDHandler.setUUIDWrapper(newWrapper); UUIDHandler.setUUIDWrapper(newWrapper);
MainUtil.sendMessage(player, "&7 - Updating plot objects"); MainUtil.sendMessage(player, "&7 - Updating plot objects");
for (final Plot plot : PS.get().getPlots()) { for (Plot plot : PS.get().getPlots()) {
final UUID value = uCMap.get(plot.owner); UUID value = uCMap.get(plot.owner);
if (value != null) { if (value != null) {
plot.owner = value; plot.owner = value;
} }
@ -265,19 +246,19 @@ public class DebugUUID extends SubCommand {
plot.getMembers().clear(); plot.getMembers().clear();
plot.getDenied().clear(); plot.getDenied().clear();
} }
MainUtil.sendMessage(player, "&7 - Deleting database"); MainUtil.sendMessage(player, "&7 - Deleting database");
final AbstractDB database = DBFunc.dbManager; final AbstractDB database = DBFunc.dbManager;
final boolean result = database.deleteTables(); boolean result = database.deleteTables();
MainUtil.sendMessage(player, "&7 - Creating tables"); MainUtil.sendMessage(player, "&7 - Creating tables");
try { try {
database.createTables(); database.createTables();
if (!result) { if (!result) {
MainUtil.sendMessage(player, "&cConversion failed! Attempting recovery"); MainUtil.sendMessage(player, "&cConversion failed! Attempting recovery");
for (final Plot plot : PS.get().getPlots()) { for (Plot plot : PS.get().getPlots()) {
final UUID value = uCReverse.get(plot.owner); UUID value = uCReverse.get(plot.owner);
if (value != null) { if (value != null) {
plot.owner = value; plot.owner = value;
} }
@ -290,11 +271,11 @@ public class DebugUUID extends SubCommand {
}); });
return; return;
} }
} catch (final Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return; return;
} }
if (newWrapper instanceof OfflineUUIDWrapper) { if (newWrapper instanceof OfflineUUIDWrapper) {
PS.get().config.set("UUID.force-lowercase", false); PS.get().config.set("UUID.force-lowercase", false);
PS.get().config.set("UUID.offline", true); PS.get().config.set("UUID.offline", true);
@ -305,15 +286,15 @@ public class DebugUUID extends SubCommand {
try { try {
PS.get().config.save(PS.get().configFile); PS.get().config.save(PS.get().configFile);
} catch (IOException e) { } catch (IOException e) {
MainUtil.sendMessage(player, "Could not save configuration. It will need to be manuall set!"); MainUtil.sendMessage(player, "Could not save configuration. It will need to be manual set!");
} }
MainUtil.sendMessage(player, "&7 - Populating tables"); MainUtil.sendMessage(player, "&7 - Populating tables");
TaskManager.runTaskAsync(new Runnable() { TaskManager.runTaskAsync(new Runnable() {
@Override @Override
public void run() { public void run() {
final ArrayList<Plot> plots = new ArrayList<>(PS.get().getPlots()); ArrayList<Plot> plots = new ArrayList<>(PS.get().getPlots());
database.createPlotsAndData(plots, new Runnable() { database.createPlotsAndData(plots, new Runnable() {
@Override @Override
public void run() { public void run() {
@ -322,7 +303,7 @@ public class DebugUUID extends SubCommand {
}); });
} }
}); });
MainUtil.sendMessage(player, "&aIt is now safe for players to join"); MainUtil.sendMessage(player, "&aIt is now safe for players to join");
MainUtil.sendMessage(player, "&cConversion is still in progress, you will be notified when it is complete"); MainUtil.sendMessage(player, "&cConversion is still in progress, you will be notified when it is complete");
} }

View File

@ -0,0 +1,93 @@
package com.plotsquared.bukkit.database.plotme;
import com.intellectualcrafters.configuration.file.FileConfiguration;
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;
import java.util.Collections;
import java.util.HashMap;
abstract class APlotMeConnector {
public abstract Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, String dataFolder);
public abstract HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(Connection connection) throws SQLException;
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);
int plotSize = plotConfig.getInt("worlds." + world + ".PlotSize"); //
PS.get().config.set("worlds." + actualWorldName + ".plot.size", plotSize);
String wallBlock = plotConfig.getString("worlds." + world + ".WallBlockId"); //
PS.get().config.set("worlds." + actualWorldName + ".wall.block", wallBlock);
String floor = plotConfig.getString("worlds." + world + ".PlotFloorBlockId"); //
PS.get().config.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));
String road = plotConfig.getString("worlds." + world + ".RoadMainBlockId");
PS.get().config.set("worlds." + actualWorldName + ".road.block", road);
int height = plotConfig.getInt("worlds." + world + ".RoadHeight"); //
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);
}
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;
return new Location(null, x, 1, z);
}
public void setMerged(HashMap<String, HashMap<PlotId, boolean[]>> merges, String world, PlotId id, int direction) {
HashMap<PlotId, boolean[]> plots = merges.get(world);
PlotId id2 = new PlotId(id.x, id.y);
boolean[] merge1;
if (plots.containsKey(id)) {
merge1 = plots.get(id);
} else {
merge1 = new boolean[] { false, false, false, false };
}
boolean[] merge2;
if (plots.containsKey(id2)) {
merge2 = plots.get(id2);
} else {
merge2 = new boolean[] { false, false, false, false };
}
merge1[direction] = true;
merge2[(direction + 2) % 4] = true;
plots.put(id, merge1);
plots.put(id2, merge1);
}
}

View File

@ -0,0 +1,272 @@
package com.plotsquared.bukkit.database.plotme;
import com.google.common.base.Charsets;
import com.intellectualcrafters.configuration.file.FileConfiguration;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.database.SQLite;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.StringWrapper;
import com.intellectualcrafters.plot.util.UUIDHandler;
import java.io.File;
import java.nio.ByteBuffer;
import java.sql.Connection;
import java.sql.DriverManager;
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 ClassicPlotMeConnector extends APlotMeConnector {
private String plugin;
private String prefix;
@Override
public Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, String dataFolder) {
this.plugin = plugin.toLowerCase();
this.prefix = plotConfig.getString("mySQLprefix", 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();
}
} catch (SQLException | ClassNotFoundException ignored) {
//ignored
ignored.printStackTrace();
}
return null;
}
@Override
public HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(Connection connection) throws SQLException {
HashMap<String, Integer> plotWidth = new HashMap<>();
HashMap<String, Integer> roadWidth = new HashMap<>();
HashMap<String, HashMap<PlotId, Plot>> plots = new HashMap<>();
HashMap<String, HashMap<PlotId, boolean[]>> merges = new HashMap<>();
PreparedStatement statement = connection.prepareStatement("SELECT * FROM `" + this.prefix + "Plots`");
ResultSet resultSet = statement.executeQuery();
String column = null;
boolean checkUUID = DBFunc.hasColumn(resultSet, "ownerid");
boolean checkUUID2 = DBFunc.hasColumn(resultSet, "ownerId");
if (checkUUID) {
column = "ownerid";
} else if (checkUUID2) {
column = "ownerId";
}
boolean merge = !"plotme".equalsIgnoreCase(this.plugin) && Settings.CONVERT_PLOTME;
int missing = 0;
while (resultSet.next()) {
PlotId id = new PlotId(resultSet.getInt("idX"), resultSet.getInt("idZ"));
String name = resultSet.getString("owner");
String world = LikePlotMeConverter.getWorld(resultSet.getString("world"));
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");
plotWidth.put(world, plot);
roadWidth.put(world, path);
merges.put(world, new HashMap<PlotId, boolean[]>());
}
}
if (merge) {
int tx = resultSet.getInt("topX");
int tz = resultSet.getInt("topZ");
int bx = resultSet.getInt("bottomX") - 1;
int bz = resultSet.getInt("bottomZ") - 1;
int path = roadWidth.get(world);
int plot = plotWidth.get(world);
Location top = getPlotTopLocAbs(path, plot, id);
Location bot = getPlotBottomLocAbs(path, plot, id);
if (tx > top.getX()) {
setMerged(merges, world, id, 1);
}
if (tz > top.getZ()) {
setMerged(merges, world, id, 2);
}
if (bx < bot.getX()) {
setMerged(merges, world, id, 3);
}
if (bz > bot.getZ()) {
setMerged(merges, world, id, 0);
}
}
UUID owner = UUIDHandler.getUUID(name, null);
if (owner == null) {
if ("*".equals(name)) {
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();
}
}
if (owner == null) {
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);
}
Plot plot = new Plot(PlotArea.createGeneric(world), id, owner);
plots.get(world).put(id, plot);
}
if (missing > 0) {
PS.log("&cSome names could not be identified:");
PS.log("&7 - Empty quotes mean PlotMe just stored an unowned plot in the database");
PS.log("&7 - Names you have never seen before could be from people mistyping commands");
PS.log("&7 - Converting from a non-uuid version of PlotMe can't identify owners if the playerdata files are deleted (these plots will "
+ "remain unknown until the player connects)");
}
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());
if (plot != null) {
plot.setMerged(entry2.getValue());
}
}
}
resultSet.close();
statement.close();
try {
PS.log(" - " + this.prefix + "Denied");
statement = connection.prepareStatement("SELECT * FROM `" + this.prefix + "Denied`");
resultSet = statement.executeQuery();
while (resultSet.next()) {
PlotId id = new PlotId(resultSet.getInt("idX"), resultSet.getInt("idZ"));
String name = resultSet.getString("player");
String world = LikePlotMeConverter.getWorld(resultSet.getString("world"));
UUID denied = UUIDHandler.getUUID(name, null);
if (denied == null) {
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();
}
}
if (denied == null) {
PS.log("&6Could not identify denied for plot: " + id);
continue;
}
}
HashMap<PlotId, Plot> worldMap = plots.get(world);
if (worldMap != null) {
Plot plot = worldMap.get(id);
if (plot != null) {
plot.getDenied().add(denied);
}
}
}
statement = connection.prepareStatement("SELECT * FROM `" + this.plugin + "Allowed`");
resultSet = statement.executeQuery();
while (resultSet.next()) {
PlotId id = new PlotId(resultSet.getInt("idX"), resultSet.getInt("idZ"));
String name = resultSet.getString("player");
String world = LikePlotMeConverter.getWorld(resultSet.getString("world"));
UUID helper = UUIDHandler.getUUID(name, null);
if (helper == null) {
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();
}
}
if (helper == null) {
PS.log("&6Could not identify helper for plot: " + id);
continue;
}
}
HashMap<PlotId, Plot> worldMap = plots.get(world);
if (worldMap != null) {
Plot plot = worldMap.get(id);
if (plot != null) {
plot.getTrusted().add(helper);
}
}
}
resultSet.close();
statement.close();
} catch (SQLException ignored) {
//ignored
}
return plots;
}
@Override
public boolean accepts(String version) {
return version == null || PS.get().canUpdate(version, "0.17.0") || PS.get().canUpdate("0.999.999", version);
}
}

View File

@ -1,404 +1,377 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// package com.plotsquared.bukkit.database.plotme;
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / import com.intellectualcrafters.configuration.MemorySection;
// / import com.intellectualcrafters.configuration.file.FileConfiguration;
// This program is free software; you can redistribute it and/or modify / import com.intellectualcrafters.configuration.file.YamlConfiguration;
// it under the terms of the GNU General Public License as published by / import com.intellectualcrafters.plot.PS;
// the Free Software Foundation; either version 3 of the License, or / import com.intellectualcrafters.plot.config.Settings;
// (at your option) any later version. / import com.intellectualcrafters.plot.database.DBFunc;
// / import com.intellectualcrafters.plot.generator.HybridGen;
// This program is distributed in the hope that it will be useful, / import com.intellectualcrafters.plot.object.Plot;
// but WITHOUT ANY WARRANTY; without even the implied warranty of / import com.intellectualcrafters.plot.object.PlotArea;
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / import com.intellectualcrafters.plot.object.PlotId;
// GNU General Public License for more details. / import com.intellectualcrafters.plot.util.TaskManager;
// / import com.plotsquared.bukkit.generator.BukkitPlotGenerator;
// You should have received a copy of the GNU General Public License / import org.bukkit.Bukkit;
// along with this program; if not, write to the Free Software Foundation, / import org.bukkit.World;
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / import org.bukkit.WorldCreator;
// / import org.bukkit.command.CommandException;
// You can contact us via: support@intellectualsites.com /
//////////////////////////////////////////////////////////////////////////////////////////////////// import java.io.File;
package com.plotsquared.bukkit.database.plotme; import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.io.File; import java.nio.file.Files;
import java.io.IOException; import java.nio.file.Path;
import java.nio.charset.Charset; import java.nio.file.Paths;
import java.nio.charset.StandardCharsets; import java.sql.Connection;
import java.nio.file.Files; import java.util.ArrayList;
import java.nio.file.Path; import java.util.Collections;
import java.nio.file.Paths; import java.util.HashMap;
import java.sql.Connection; import java.util.Map.Entry;
import java.util.ArrayList; import java.util.Set;
import java.util.Collections; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.HashMap;
import java.util.Map.Entry; public class LikePlotMeConverter {
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean; private final String plugin;
import org.bukkit.Bukkit; /**
import org.bukkit.World; * Constructor.
import org.bukkit.WorldCreator; *
* @param plugin Plugin Used to run the converter
import com.intellectualcrafters.configuration.file.FileConfiguration; */
import com.intellectualcrafters.configuration.file.YamlConfiguration; public LikePlotMeConverter(String plugin) {
import com.intellectualcrafters.plot.PS; this.plugin = plugin;
import com.intellectualcrafters.plot.config.Settings; }
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.generator.HybridGen; public static String getWorld(String world) {
import com.intellectualcrafters.plot.object.Plot; for (World newWorld : Bukkit.getWorlds()) {
import com.intellectualcrafters.plot.object.PlotArea; if (newWorld.getName().equalsIgnoreCase(world)) {
import com.intellectualcrafters.plot.object.PlotId; return newWorld.getName();
import com.intellectualcrafters.plot.util.TaskManager; }
import com.plotsquared.bukkit.generator.BukkitPlotGenerator; }
return world;
/** }
* Created 2014-08-17 for PlotSquared
* private void sendMessage(String message) {
PS.debug("&3PlotMe&8->&3PlotSquared&8: &7" + message);
}
*/
public class LikePlotMeConverter { public String getPlotMePath() {
private final String plugin; return new File(".").getAbsolutePath() + File.separator + "plugins" + File.separator + this.plugin + File.separator;
}
/**
* Constructor public String getAthionPlotsPath() {
* return new File(".").getAbsolutePath() + File.separator + "plugins" + File.separator + this.plugin + File.separator;
* @param plugin Plugin Used to run the converter }
*/
public LikePlotMeConverter(final String plugin) { public FileConfiguration getPlotMeConfig(String dataFolder) {
this.plugin = plugin; File plotMeFile = new File(dataFolder + "config.yml");
} if (!plotMeFile.exists()) {
return null;
public static String getWorld(final String world) { }
for (final World newworld : Bukkit.getWorlds()) { return YamlConfiguration.loadConfiguration(plotMeFile);
if (newworld.getName().equalsIgnoreCase(world)) { }
return newworld.getName();
} public Set<String> getPlotMeWorlds(FileConfiguration plotConfig) {
} return plotConfig.getConfigurationSection("worlds").getKeys(false);
return world; }
}
public void mergeWorldYml(String plugin, FileConfiguration plotConfig) {
private void sendMessage(final String message) { try {
PS.debug("&3PlotMe&8->&3PlotSquared&8: &7" + message); File genConfig =
} new File("plugins" + File.separator + plugin + File.separator + "PlotMe-DefaultGenerator" + File.separator + "config.yml");
if (genConfig.exists()) {
public String getPlotMePath() { YamlConfiguration yml = YamlConfiguration.loadConfiguration(genConfig);
return new File(".").getAbsolutePath() + File.separator + "plugins" + File.separator + plugin + File.separator; for (String key : yml.getKeys(true)) {
} if (!plotConfig.contains(key)) {
Object value = yml.get(key);
public String getAthionPlotsPath() { if (!(value instanceof MemorySection)) {
return new File(".").getAbsolutePath() + File.separator + "plugins" + File.separator + plugin + File.separator; plotConfig.set(key, value);
} }
}
public FileConfiguration getPlotMeConfig(final String dataFolder) { }
final File plotMeFile = new File(dataFolder + "config.yml"); }
if (!plotMeFile.exists()) { } catch (Exception e) {
return null; e.printStackTrace();
} }
return YamlConfiguration.loadConfiguration(plotMeFile); }
}
public void updateWorldYml(String plugin, String location) {
public Set<String> getPlotMeWorlds(final FileConfiguration plotConfig) { try {
return plotConfig.getConfigurationSection("worlds").getKeys(false); Path path = Paths.get(location);
} File file = new File(location);
if (!file.exists()) {
public void mergeWorldYml(final String plugin, FileConfiguration plotConfig) { return;
try { }
File genConfig = new File("plugins" + File.separator + plugin + File.separator + "PlotMe-DefaultGenerator" + File.separator + "config.yml"); String content = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
if (genConfig.exists()) { content = content.replaceAll("PlotMe-DefaultGenerator", "PlotSquared");
YamlConfiguration yml = YamlConfiguration.loadConfiguration(genConfig); content = content.replaceAll(plugin, "PlotSquared");
for (String key : yml.getKeys(true)) { Files.write(path, content.getBytes(StandardCharsets.UTF_8));
if (!plotConfig.contains(key)) { } catch (IOException ignored) {
plotConfig.set(key, yml.get(key)); //ignored
} }
} }
genConfig.delete();
} public boolean run(APlotMeConnector connector) {
} try {
catch (Exception e) { String dataFolder = getPlotMePath();
e.printStackTrace(); FileConfiguration plotConfig = getPlotMeConfig(dataFolder);
} if (plotConfig == null) {
} return false;
}
public void updateWorldYml(final String plugin, final String location) {
try { String version = plotConfig.getString("Version");
final Path path = Paths.get(location); if (version == null) {
final File file = new File(location); version = plotConfig.getString("version");
if (!file.exists()) { }
return; if (!connector.accepts(version)) {
} return false;
final Charset charset = StandardCharsets.UTF_8; }
String content = new String(Files.readAllBytes(path), charset);
content = content.replaceAll("PlotMe-DefaultGenerator", "PlotSquared"); PS.debug("&3Using connector: " + connector.getClass().getCanonicalName());
content = content.replaceAll(plugin, "PlotSquared");
Files.write(path, content.getBytes(charset)); Connection connection = connector.getPlotMeConnection(this.plugin, plotConfig, dataFolder);
} catch (IOException e) {
} if (!connector.isValidConnection(connection)) {
} sendMessage("Cannot connect to PlotMe DB. Conversion process will not continue");
return false;
public boolean run(final APlotMeConnector connector) { }
try {
final String dataFolder = getPlotMePath(); sendMessage(this.plugin + " conversion has started. To disable this, please set 'plotme-convert.enabled' to false in the 'settings.yml'");
final FileConfiguration plotConfig = getPlotMeConfig(dataFolder);
if (plotConfig == null) { mergeWorldYml(this.plugin, plotConfig);
return false;
} sendMessage("Connecting to " + this.plugin + " DB");
String version = plotConfig.getString("Version"); ArrayList<Plot> createdPlots = new ArrayList<>();
if (version == null) {
version = plotConfig.getString("version"); sendMessage("Collecting plot data");
}
if (!connector.accepts(version)) { String dbPrefix = this.plugin.toLowerCase();
return false; sendMessage(" - " + dbPrefix + "Plots");
} final Set<String> worlds = getPlotMeWorlds(plotConfig);
PS.debug("&3Using connector: " + connector.getClass().getCanonicalName()); if (Settings.CONVERT_PLOTME) {
sendMessage("Updating bukkit.yml");
final Connection connection = connector.getPlotMeConnection(plugin, plotConfig, dataFolder); updateWorldYml(this.plugin, "bukkit.yml");
updateWorldYml(this.plugin, "plugins/Multiverse-Core/worlds.yml");
if (!connector.isValidConnection(connection)) { for (String world : plotConfig.getConfigurationSection("worlds").getKeys(false)) {
sendMessage("Cannot connect to PlotMe DB. Conversion process will not continue"); sendMessage("Copying config for: " + world);
return false; try {
} String actualWorldName = getWorld(world);
connector.copyConfig(plotConfig, world, actualWorldName);
sendMessage(plugin + " conversion has started. To disable this, please set 'plotme-convert.enabled' to false in the 'settings.yml'"); PS.get().config.save(PS.get().configFile);
} catch (IOException e) {
mergeWorldYml(plugin, plotConfig); e.printStackTrace();
sendMessage("&c-- &lFailed to save configuration for world '" + world
sendMessage("Connecting to " + plugin + " DB"); + "'\nThis will need to be done using the setup command, or manually");
}
int plotCount = 0; }
final ArrayList<Plot> createdPlots = new ArrayList<>(); }
HashMap<String, HashMap<PlotId, Plot>> plots = connector.getPlotMePlots(connection);
sendMessage("Collecting plot data"); int plotCount = 0;
for (Entry<String, HashMap<PlotId, Plot>> entry : plots.entrySet()) {
final String dbPrefix = plugin.toLowerCase(); plotCount += entry.getValue().size();
sendMessage(" - " + dbPrefix + "Plots"); }
final Set<String> worlds = getPlotMeWorlds(plotConfig); if (!Settings.CONVERT_PLOTME) {
return false;
if (Settings.CONVERT_PLOTME) { }
sendMessage("Updating bukkit.yml");
updateWorldYml(plugin, "bukkit.yml"); sendMessage(" - " + dbPrefix + "Allowed");
updateWorldYml(plugin, "plugins/Multiverse-Core/worlds.yml");
for (final String world : plotConfig.getConfigurationSection("worlds").getKeys(false)) { sendMessage("Collected " + plotCount + " plots from PlotMe");
sendMessage("Copying config for: " + world); File plotmeDgFile = new File(dataFolder + File.separator + "PlotMe-DefaultGenerator" + File.separator + "config.yml");
try { if (plotmeDgFile.exists()) {
final String actualWorldName = getWorld(world); YamlConfiguration plotmeDgYml = YamlConfiguration.loadConfiguration(plotmeDgFile);
connector.copyConfig(plotConfig, world, actualWorldName); try {
PS.get().config.save(PS.get().configFile); for (String world : plots.keySet()) {
} catch (final Exception e) { String actualWorldName = getWorld(world);
e.printStackTrace(); String plotMeWorldName = world.toLowerCase();
sendMessage("&c-- &lFailed to save configuration for world '" + world + "'\nThis will need to be done using the setup command, or manually"); Integer pathwidth = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".PathWidth"); //
} /*
} * TODO: dead code
} *
final HashMap<String, HashMap<PlotId, Plot>> plots = connector.getPlotMePlots(connection); if (pathwidth == null) {
for (final Entry<String, HashMap<PlotId, Plot>> entry : plots.entrySet()) { pathwidth = 7;
plotCount += entry.getValue().size(); }
} */
if (!Settings.CONVERT_PLOTME) { PS.get().config.set("worlds." + world + ".road.width", pathwidth);
return false;
} Integer pathheight = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".RoadHeight"); //
if (pathheight == 0) {
sendMessage(" - " + dbPrefix + "Allowed"); pathheight = 64;
}
sendMessage("Collected " + plotCount + " plots from PlotMe"); PS.get().config.set("worlds." + world + ".road.height", pathheight);
final File PLOTME_DG_FILE = new File(dataFolder + File.separator + "PlotMe-DefaultGenerator" + File.separator + "config.yml"); PS.get().config.set("worlds." + world + ".wall.height", pathheight);
if (PLOTME_DG_FILE.exists()) { PS.get().config.set("worlds." + world + ".plot.height", pathheight);
final YamlConfiguration PLOTME_DG_YML = YamlConfiguration.loadConfiguration(PLOTME_DG_FILE); Integer plotSize = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".PlotSize"); //
try { if (plotSize == 0) {
for (final String world : plots.keySet()) { plotSize = 32;
final String actualWorldName = getWorld(world); }
final String plotMeWorldName = world.toLowerCase(); PS.get().config.set("worlds." + world + ".plot.size", plotSize);
Integer pathwidth = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".PathWidth"); // String wallblock = plotmeDgYml.getString("worlds." + plotMeWorldName + ".WallBlock", "44"); //
/* PS.get().config.set("worlds." + world + ".wall.block", wallblock);
* TODO: dead code String floor = plotmeDgYml.getString("worlds." + plotMeWorldName + ".PlotFloorBlock", "2"); //
* PS.get().config.set("worlds." + world + ".plot.floor", Collections.singletonList(floor));
if (pathwidth == null) { String filling = plotmeDgYml.getString("worlds." + plotMeWorldName + ".FillBlock", "3"); //
pathwidth = 7; 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);
PS.get().config.set("worlds." + world + ".road.width", pathwidth); Integer height = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".RoadHeight"); //
if (height == 0) {
Integer pathheight = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".RoadHeight"); // height = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".GroundHeight"); //
if ((pathheight == null) || (pathheight == 0)) { if (height == 0) {
pathheight = 64; height = 64;
} }
PS.get().config.set("worlds." + world + ".road.height", pathheight); }
PS.get().config.set("worlds." + world + ".wall.height", pathheight); PS.get().config.set("worlds." + actualWorldName + ".road.height", height);
PS.get().config.set("worlds." + world + ".plot.height", pathheight); PS.get().config.set("worlds." + actualWorldName + ".plot.height", height);
Integer plotsize = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".PlotSize"); // PS.get().config.set("worlds." + actualWorldName + ".wall.height", height);
if ((plotsize == null) || (plotsize == 0)) { PS.get().config.save(PS.get().configFile);
plotsize = 32; }
} } catch (IOException ignored) {
PS.get().config.set("worlds." + world + ".plot.size", plotsize); //ignored
String wallblock = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".WallBlock"); // }
if (wallblock == null) { }
wallblock = "44"; for (Entry<String, HashMap<PlotId, Plot>> entry : plots.entrySet()) {
} String world = entry.getKey();
PS.get().config.set("worlds." + world + ".wall.block", wallblock); PlotArea area = PS.get().getPlotArea(world, null);
String floor = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".PlotFloorBlock"); // int duplicate = 0;
if (floor == null) { if (area != null) {
floor = "2"; for (Entry<PlotId, Plot> entry2 : entry.getValue().entrySet()) {
} if (area.getOwnedPlotAbs(entry2.getKey()) != null) {
PS.get().config.set("worlds." + world + ".plot.floor", Collections.singletonList(floor)); duplicate++;
String filling = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".FillBlock"); // } else {
if (filling == null) { createdPlots.add(entry2.getValue());
filling = "3"; }
} }
PS.get().config.set("worlds." + world + ".plot.filling", Collections.singletonList(filling)); if (duplicate > 0) {
String road = PLOTME_DG_YML.getString("worlds." + plotMeWorldName + ".RoadMainBlock"); PS.debug("&c[WARNING] Found " + duplicate + " duplicate plots already in DB for world: '" + world
if (road == null) { + "'. Have you run the converter already?");
road = "5"; }
} } else {
PS.get().config.set("worlds." + world + ".road.block", road); if (PS.get().plots_tmp != null) {
Integer height = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".RoadHeight"); // HashMap<PlotId, Plot> map = PS.get().plots_tmp.get(world);
if (height == 0) { if (map != null) {
height = PLOTME_DG_YML.getInt("worlds." + plotMeWorldName + ".GroundHeight"); // for (Entry<PlotId, Plot> entry2 : entry.getValue().entrySet()) {
if (height == 0) { if (map.containsKey(entry2.getKey())) {
height = 64; duplicate++;
} } else {
} createdPlots.add(entry2.getValue());
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); if (duplicate > 0) {
PS.get().config.save(PS.get().configFile); PS.debug("&c[WARNING] Found " + duplicate + " duplicate plots already in DB for world: '" + world
} + "'. Have you run the converter already?");
} catch (IOException e) { }
} continue;
} }
for (Entry<String, HashMap<PlotId, Plot>> entry : plots.entrySet()) { }
String world = entry.getKey(); createdPlots.addAll(entry.getValue().values());
PlotArea area = PS.get().getPlotArea(world, null); }
int duplicate = 0; }
if (area != null) { sendMessage("Creating plot DB");
for (Entry<PlotId, Plot> entry2 : entry.getValue().entrySet()) { Thread.sleep(1000);
if (area.getOwnedPlotAbs(entry2.getKey()) != null) { final AtomicBoolean done = new AtomicBoolean(false);
duplicate++; DBFunc.createPlotsAndData(createdPlots, new Runnable() {
} else { @Override
createdPlots.add(entry2.getValue()); public void run() {
} if (done.get()) {
} done();
if (duplicate > 0) { sendMessage("&aDatabase conversion is now complete!");
PS.debug("&c[WARNING] Found " + duplicate + " duplicate plots already in DB for world: '" + world + "'. Have you run the converter already?"); PS.debug("&c - Stop the server");
} PS.debug("&c - Disable 'plotme-convert.enabled' and 'plotme-convert.cache-uuids' in the settings.yml");
} else { PS.debug("&c - Correct any generator settings that haven't copied to 'settings.yml' properly");
if (PS.get().plots_tmp != null) { PS.debug("&c - Start the server");
HashMap<PlotId, Plot> map = PS.get().plots_tmp.get(world); PS.get().setPlots(DBFunc.getPlots());
if (map != null) { } else {
for (Entry<PlotId, Plot> entry2 : entry.getValue().entrySet()) { sendMessage("&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!");
if (map.containsKey(entry2.getKey())) { done.set(true);
duplicate++; }
} else { }
createdPlots.add(entry2.getValue()); });
} sendMessage("Saving configuration...");
} try {
if (duplicate > 0) { PS.get().config.save(PS.get().configFile);
PS.debug("&c[WARNING] Found " + duplicate + " duplicate plots already in DB for world: '" + world + "'. Have you run the converter already?"); } catch (IOException e) {
} sendMessage(" - &cFailed to save configuration.");
continue; }
} TaskManager.runTask(new Runnable() {
} @Override
createdPlots.addAll(entry.getValue().values()); public void run() {
} try {
} boolean mv = false;
sendMessage("Creating plot DB"); boolean mw = false;
Thread.sleep(1000); if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) && Bukkit.getPluginManager().getPlugin("Multiverse-Core")
final AtomicBoolean done = new AtomicBoolean(false); .isEnabled()) {
DBFunc.createPlotsAndData(createdPlots, new Runnable() { mv = true;
@Override } else if ((Bukkit.getPluginManager().getPlugin("MultiWorld") != null) && Bukkit.getPluginManager().getPlugin("MultiWorld")
public void run() { .isEnabled()) {
if (done.get()) { mw = true;
done(); }
sendMessage("&aDatabase conversion is now complete!"); for (String worldName : worlds) {
PS.debug("&c - Stop the server"); World world = Bukkit.getWorld(getWorld(worldName));
PS.debug("&c - Disable 'plotme-convert.enabled' and 'plotme-convert.cache-uuids' in the settings.yml"); if (world == null) {
PS.debug("&c - Correct any generator settings that haven't copied to 'settings.yml' properly"); sendMessage("&cInvalid world in PlotMe configuration: " + worldName);
PS.debug("&c - Start the server"); }
PS.get().setPlots(DBFunc.getPlots()); String actualWorldName = world.getName();
} else { sendMessage("Reloading generator for world: '" + actualWorldName + "'...");
sendMessage("&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!"); PS.get().removePlotAreas(actualWorldName);
done.set(true); if (mv) {
} // unload world with MV
} Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv unload " + actualWorldName);
}); try {
sendMessage("Saving configuration..."); Thread.sleep(1000);
try { } catch (InterruptedException ex) {
PS.get().config.save(PS.get().configFile); Thread.currentThread().interrupt();
} catch (final IOException e) { }
sendMessage(" - &cFailed to save configuration."); // load world with MV
} Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
TaskManager.runTask(new Runnable() { "mv import " + actualWorldName + " normal -g PlotSquared");
@Override } else if (mw) {
public void run() { // unload world with MW
try { Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw unload " + actualWorldName);
boolean MV = false; try {
boolean MW = false; Thread.sleep(1000);
if ((Bukkit.getPluginManager().getPlugin("Multiverse-Core") != null) && Bukkit.getPluginManager().getPlugin("Multiverse-Core").isEnabled()) { } catch (InterruptedException ex) {
MV = true; Thread.currentThread().interrupt();
} else if ((Bukkit.getPluginManager().getPlugin("MultiWorld") != null) && Bukkit.getPluginManager().getPlugin("MultiWorld").isEnabled()) { }
MW = true; // load world with MW
} Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(),
for (final String worldname : worlds) { "mw create " + actualWorldName + " plugin:PlotSquared");
final World world = Bukkit.getWorld(getWorld(worldname)); } else {
if (world == null) { // Load using Bukkit API
sendMessage("&cInvalid world in PlotMe configuration: " + worldname); // - User must set generator manually
} Bukkit.getServer().unloadWorld(world, true);
final String actualWorldName = world.getName(); World myWorld = WorldCreator.name(actualWorldName).generator(new BukkitPlotGenerator(new HybridGen())).createWorld();
sendMessage("Reloading generator for world: '" + actualWorldName + "'..."); myWorld.save();
PS.get().removePlotAreas(actualWorldName); }
if (MV) { }
// unload world with MV } catch (CommandException e) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv unload " + actualWorldName); e.printStackTrace();
try { }
Thread.sleep(1000); if (done.get()) {
} catch (final InterruptedException ex) { done();
Thread.currentThread().interrupt(); sendMessage("&aDatabase conversion is now complete!");
} PS.debug("&c - Stop the server");
// load world with MV PS.debug("&c - Disable 'plotme-convert.enabled' and 'plotme-convert.cache-uuids' in the settings.yml");
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv import " + actualWorldName + " normal -g PlotSquared"); PS.debug("&c - Correct any generator settings that haven't copied to 'settings.yml' properly");
} else if (MW) { PS.debug("&c - Start the server");
// unload world with MW } else {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw unload " + actualWorldName); sendMessage("&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!");
try { done.set(true);
Thread.sleep(1000); }
} catch (final InterruptedException ex) { }
Thread.currentThread().interrupt(); });
} } catch (Exception e) {
// load world with MW e.printStackTrace();
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw create " + actualWorldName + " plugin:PlotSquared"); PS.debug("&/end/");
} else { }
// Load using Bukkit API return true;
// - User must set generator manually }
Bukkit.getServer().unloadWorld(world, true);
final World myworld = WorldCreator.name(actualWorldName).generator(new BukkitPlotGenerator(new HybridGen())).createWorld(); public void done() {
myworld.save(); PS.get().setPlots(DBFunc.getPlots());
} }
} }
} catch (final Exception e) {
e.printStackTrace();
}
if (done.get()) {
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 - Correct any generator settings that haven't copied to 'settings.yml' properly");
PS.debug("&c - Start the server");
} else {
sendMessage("&cPlease wait until database conversion is complete. You will be notified with instructions when this happens!");
done.set(true);
}
}
});
} catch (final Exception e) {
e.printStackTrace();
PS.debug("&/end/");
}
return true;
}
public void done() {
PS.get().setPlots(DBFunc.getPlots());
}
}

View File

@ -23,41 +23,43 @@ import java.util.Map.Entry;
import java.util.UUID; import java.util.UUID;
public class PlotMeConnector_017 extends APlotMeConnector { public class PlotMeConnector_017 extends APlotMeConnector {
private String plugin; private String plugin;
private String prefix;
@Override @Override
public Connection getPlotMeConnection(final String plugin, final FileConfiguration plotConfig, final String dataFolder) { public Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, String dataFolder) {
this.plugin = plugin.toLowerCase(); this.plugin = plugin.toLowerCase();
prefix = plugin + "core_";
try { try {
if (plotConfig.getBoolean("usemySQL")) { if (plotConfig.getBoolean("usemySQL")) {
final String user = plotConfig.getString("mySQLuname"); String user = plotConfig.getString("mySQLuname");
final String password = plotConfig.getString("mySQLpass"); String password = plotConfig.getString("mySQLpass");
final String con = plotConfig.getString("mySQLconn"); String con = plotConfig.getString("mySQLconn");
return DriverManager.getConnection(con, user, password); return DriverManager.getConnection(con, user, password);
} else { } else {
final File file = new File(dataFolder + File.separator + "plotmecore.db"); File file = new File(dataFolder + File.separator + "plotmecore.db");
if (file.exists()) { if (file.exists()) {
return new SQLite(dataFolder + File.separator + "plotmecore.db").openConnection(); return new SQLite(dataFolder + File.separator + "plotmecore.db").openConnection();
} }
return new SQLite(dataFolder + File.separator + "plots.db").openConnection(); return new SQLite(dataFolder + File.separator + "plots.db").openConnection();
} }
} catch (SQLException | ClassNotFoundException e) {} } catch (SQLException | ClassNotFoundException ignored) {
//ignored
ignored.printStackTrace();
}
return null; return null;
} }
@Override @Override
public HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(final Connection connection) throws SQLException { public HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(Connection connection) throws SQLException {
ResultSet r; ResultSet resultSet;
PreparedStatement stmt; PreparedStatement statement;
final HashMap<String, Integer> plotWidth = new HashMap<>(); HashMap<String, Integer> plotWidth = new HashMap<>();
final HashMap<String, Integer> roadWidth = new HashMap<>(); HashMap<String, Integer> roadWidth = new HashMap<>();
final HashMap<Integer, Plot> plots = new HashMap<>(); HashMap<Integer, Plot> plots = new HashMap<>();
final HashMap<String, HashMap<PlotId, boolean[]>> merges = new HashMap<>(); HashMap<String, HashMap<PlotId, boolean[]>> merges = new HashMap<>();
try { try {
stmt = connection.prepareStatement("SELECT * FROM `" + plugin + "core_plots`"); statement = connection.prepareStatement("SELECT * FROM `" + this.plugin + "core_plots`");
r = stmt.executeQuery(); resultSet = statement.executeQuery();
} catch (SQLException e) { } catch (SQLException e) {
PS.debug("========= Table does not exist ========="); PS.debug("========= Table does not exist =========");
e.printStackTrace(); e.printStackTrace();
@ -66,31 +68,29 @@ public class PlotMeConnector_017 extends APlotMeConnector {
PS.debug("&8 - &7Please correct this, or if you are unsure, the most common is 0.16.3"); PS.debug("&8 - &7Please correct this, or if you are unsure, the most common is 0.16.3");
return null; return null;
} }
final boolean checkUUID = DBFunc.hasColumn(r, "ownerID"); boolean checkUUID = DBFunc.hasColumn(resultSet, "ownerID");
final boolean merge = !plugin.equals("plotme") && Settings.CONVERT_PLOTME; boolean merge = !this.plugin.equals("plotme") && Settings.CONVERT_PLOTME;
while (r.next()) { while (resultSet.next()) {
final int key = r.getInt("plot_id"); int key = resultSet.getInt("plot_id");
final PlotId id = new PlotId(r.getInt("plotX"), r.getInt("plotZ")); PlotId id = new PlotId(resultSet.getInt("plotX"), resultSet.getInt("plotZ"));
final String name = r.getString("owner"); String name = resultSet.getString("owner");
final String world = LikePlotMeConverter.getWorld(r.getString("world")); String world = LikePlotMeConverter.getWorld(resultSet.getString("world"));
if (!plots.containsKey(world)) { if (!plots.containsKey(world) && merge) {
if (merge) { int plot = PS.get().config.getInt("worlds." + world + ".plot.size");
final int plot = PS.get().config.getInt("worlds." + world + ".plot.size"); int path = PS.get().config.getInt("worlds." + world + ".road.width");
final int path = PS.get().config.getInt("worlds." + world + ".road.width"); plotWidth.put(world, plot);
plotWidth.put(world, plot); roadWidth.put(world, path);
roadWidth.put(world, path); merges.put(world, new HashMap<PlotId, boolean[]>());
merges.put(world, new HashMap<PlotId, boolean[]>());
}
} }
if (merge) { if (merge) {
final int tx = r.getInt("topX"); int tx = resultSet.getInt("topX");
final int tz = r.getInt("topZ"); int tz = resultSet.getInt("topZ");
final int bx = r.getInt("bottomX") - 1; int bx = resultSet.getInt("bottomX") - 1;
final int bz = r.getInt("bottomZ") - 1; int bz = resultSet.getInt("bottomZ") - 1;
final int path = roadWidth.get(world); int path = roadWidth.get(world);
final int plot = plotWidth.get(world); int plot = plotWidth.get(world);
final Location top = getPlotTopLocAbs(path, plot, id); Location top = getPlotTopLocAbs(path, plot, id);
final Location bot = getPlotBottomLocAbs(path, plot, id); Location bot = getPlotBottomLocAbs(path, plot, id);
if (tx > top.getX()) { if (tx > top.getX()) {
setMerged(merges, world, id, 1); setMerged(merges, world, id, 1);
} }
@ -111,12 +111,12 @@ public class PlotMeConnector_017 extends APlotMeConnector {
} else { } else {
if (checkUUID) { if (checkUUID) {
try { try {
final byte[] bytes = r.getBytes("ownerid"); byte[] bytes = resultSet.getBytes("ownerid");
if (bytes != null) { if (bytes != null) {
owner = UUID.nameUUIDFromBytes(bytes); owner = UUID.nameUUIDFromBytes(bytes);
UUIDHandler.add(new StringWrapper(name), owner); UUIDHandler.add(new StringWrapper(name), owner);
} }
} catch (final Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -128,60 +128,60 @@ public class PlotMeConnector_017 extends APlotMeConnector {
} else { } else {
UUIDHandler.add(new StringWrapper(name), owner); UUIDHandler.add(new StringWrapper(name), owner);
} }
final Plot plot = new Plot(PlotArea.createGeneric(world), id, owner); Plot plot = new Plot(PlotArea.createGeneric(world), id, owner);
plots.put(key, plot); plots.put(key, plot);
} }
for (final Entry<Integer, Plot> entry : plots.entrySet()) { for (Entry<Integer, Plot> entry : plots.entrySet()) {
final Plot plot = entry.getValue(); Plot plot = entry.getValue();
final HashMap<PlotId, boolean[]> mergeMap = merges.get(plot.getArea().worldname); HashMap<PlotId, boolean[]> mergeMap = merges.get(plot.getArea().worldname);
if (mergeMap != null) { if (mergeMap != null) {
if (mergeMap.containsKey(plot.getId())) { if (mergeMap.containsKey(plot.getId())) {
plot.setMerged(mergeMap.get(plot.getId())); plot.setMerged(mergeMap.get(plot.getId()));
} }
} }
} }
r.close(); resultSet.close();
stmt.close(); statement.close();
try { try {
PS.log(" - " + plugin + "core_denied"); PS.log(" - " + this.plugin + "core_denied");
stmt = connection.prepareStatement("SELECT * FROM `" + plugin + "core_denied`"); statement = connection.prepareStatement("SELECT * FROM `" + this.plugin + "core_denied`");
r = stmt.executeQuery(); resultSet = statement.executeQuery();
while (r.next()) { while (resultSet.next()) {
final int key = r.getInt("plot_id"); int key = resultSet.getInt("plot_id");
final Plot plot = plots.get(key); Plot plot = plots.get(key);
if (plot == null) { if (plot == null) {
PS.log("&6Denied (" + key + ") references deleted plot; ignoring entry."); PS.log("&6Denied (" + key + ") references deleted plot; ignoring entry.");
continue; continue;
} }
final UUID denied = UUID.fromString(r.getString("player")); UUID denied = UUID.fromString(resultSet.getString("player"));
plot.getDenied().add(denied); plot.getDenied().add(denied);
} }
PS.log(" - " + plugin + "core_allowed"); PS.log(" - " + this.plugin + "core_allowed");
stmt = connection.prepareStatement("SELECT * FROM `" + plugin + "core_allowed`"); statement = connection.prepareStatement("SELECT * FROM `" + this.plugin + "core_allowed`");
r = stmt.executeQuery(); resultSet = statement.executeQuery();
while (r.next()) { while (resultSet.next()) {
final int key = r.getInt("plot_id"); int key = resultSet.getInt("plot_id");
final Plot plot = plots.get(key); Plot plot = plots.get(key);
if (plot == null) { if (plot == null) {
PS.log("&6Allowed (" + key + ") references deleted plot; ignoring entry."); PS.log("&6Allowed (" + key + ") references deleted plot; ignoring entry.");
continue; continue;
} }
final UUID allowed = UUID.fromString(r.getString("player")); UUID allowed = UUID.fromString(resultSet.getString("player"));
plot.getTrusted().add(allowed); plot.getTrusted().add(allowed);
} }
r.close(); resultSet.close();
stmt.close(); statement.close();
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
final HashMap<String, HashMap<PlotId, Plot>> processed = new HashMap<>(); HashMap<String, HashMap<PlotId, Plot>> processed = new HashMap<>();
for (final Entry<Integer, Plot> entry : plots.entrySet()) { for (Entry<Integer, Plot> entry : plots.entrySet()) {
final Plot plot = entry.getValue(); Plot plot = entry.getValue();
HashMap<PlotId, Plot> map = processed.get(plot.getArea().worldname); HashMap<PlotId, Plot> map = processed.get(plot.getArea().worldname);
if (map == null) { if (map == null) {
map = new HashMap<>(); map = new HashMap<>();
@ -191,9 +191,9 @@ public class PlotMeConnector_017 extends APlotMeConnector {
} }
return processed; return processed;
} }
@Override @Override
public boolean accepts(final String version) { public boolean accepts(String version) {
if (version == null) { if (version == null) {
return false; return false;
} }

View File

@ -0,0 +1,66 @@
package com.plotsquared.bukkit.events;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.object.PlotCluster;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/**
* Called when a flag is removed from a plot.
*/
public class ClusterFlagRemoveEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final PlotCluster cluster;
private final Flag flag;
private boolean cancelled;
/**
* PlotFlagRemoveEvent: Called when a flag is removed from a plot.
*
* @param flag Flag that was removed
* @param cluster PlotCluster from which the flag was removed
*/
public ClusterFlagRemoveEvent(Flag flag, PlotCluster cluster) {
this.cluster = cluster;
this.flag = flag;
}
public static HandlerList getHandlerList() {
return handlers;
}
/**
* Get the cluster involved.
*
* @return PlotCluster
*/
public PlotCluster getCluster() {
return this.cluster;
}
/**
* Get the flag involved.
*
* @return Flag
*/
public Flag getFlag() {
return this.flag;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
@Override
public boolean isCancelled() {
return this.cancelled;
}
@Override
public void setCancelled(boolean b) {
this.cancelled = b;
}
}

View File

@ -0,0 +1,62 @@
package com.plotsquared.bukkit.events;
import com.intellectualcrafters.plot.object.Plot;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerEvent;
public class PlayerClaimPlotEvent extends PlayerEvent implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final Plot plot;
private final boolean auto;
private boolean cancelled;
/**
* PlayerClaimPlotEvent: Called when a plot is claimed.
*
* @param player Player that claimed the plot
* @param plot Plot that was claimed
*/
public PlayerClaimPlotEvent(Player player, Plot plot, boolean auto) {
super(player);
this.plot = plot;
this.auto = auto;
}
public static HandlerList getHandlerList() {
return handlers;
}
/**
* Get the plot involved
*
* @return Plot
*/
public Plot getPlot() {
return this.plot;
}
/**
* @return true if it was an automated claim, else false
*/
public boolean wasAuto() {
return this.auto;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
@Override
public boolean isCancelled() {
return this.cancelled;
}
@Override
public void setCancelled(boolean b) {
this.cancelled = b;
}
}

View File

@ -0,0 +1,41 @@
package com.plotsquared.bukkit.events;
import com.intellectualcrafters.plot.object.Plot;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerEvent;
public class PlayerEnterPlotEvent extends PlayerEvent {
private static final HandlerList handlers = new HandlerList();
private final Plot plot;
/**
* Called when a player leaves a plot.
*
* @param player Player that entered the plot
* @param plot Plot that was entered
*/
public PlayerEnterPlotEvent(Player player, Plot plot) {
super(player);
this.plot = plot;
}
public static HandlerList getHandlerList() {
return handlers;
}
/**
* Get the plot involved.
*
* @return Plot
*/
public Plot getPlot() {
return this.plot;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
}

View File

@ -0,0 +1,45 @@
package com.plotsquared.bukkit.events;
import com.intellectualcrafters.plot.object.Plot;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerEvent;
/**
*/
public class PlayerLeavePlotEvent extends PlayerEvent {
private static final HandlerList handlers = new HandlerList();
private final Plot plot;
/**
* PlayerLeavePlotEvent: Called when a player leaves a plot
*
* @param player Player that left the plot
* @param plot Plot that was left
*/
public PlayerLeavePlotEvent(Player player, Plot plot) {
super(player);
this.plot = plot;
}
public static HandlerList getHandlerList() {
return handlers;
}
/**
* Get the plot involved
*
* @return Plot
*/
public Plot getPlot() {
return this.plot;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
}

View File

@ -0,0 +1,66 @@
package com.plotsquared.bukkit.events;
import com.intellectualcrafters.plot.object.Plot;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import java.util.UUID;
public class PlayerPlotDeniedEvent extends PlotEvent {
private static final HandlerList handlers = new HandlerList();
private final Player initiator;
private final boolean added;
private final UUID player;
/**
* PlayerPlotDeniedEvent: Called when the denied UUID list is modified for a plot.
*
* @param initiator Player that initiated the event
* @param plot Plot in which the event occurred
* @param player Player that was denied/un-denied
* @param added true of add to deny list, false if removed
*/
public PlayerPlotDeniedEvent(Player initiator, Plot plot, UUID player, boolean added) {
super(plot);
this.initiator = initiator;
this.added = added;
this.player = player;
}
public static HandlerList getHandlerList() {
return handlers;
}
/**
* If a user was added.
*
* @return boolean
*/
public boolean wasAdded() {
return this.added;
}
/**
* The player added/removed.
*
* @return UUID
*/
public UUID getPlayer() {
return this.player;
}
/**
* The player initiating the action.
*
* @return Player
*/
public Player getInitiator() {
return this.initiator;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
}

View File

@ -0,0 +1,70 @@
package com.plotsquared.bukkit.events;
import com.intellectualcrafters.plot.object.Plot;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import java.util.UUID;
/**
*/
public class PlayerPlotHelperEvent extends PlotEvent {
private static final HandlerList handlers = new HandlerList();
private final Player initiator;
private final boolean added;
private final UUID player;
/**
* PlayerPlotHelperEvent: Called when a plot helper is added/removed
*
* @param initiator Player that initiated the event
* @param plot Plot in which the event occurred
* @param player Player that was added/removed from the helper list
* @param added true of the player was added, false if the player was removed
*/
public PlayerPlotHelperEvent(Player initiator, Plot plot, UUID player, boolean added) {
super(plot);
this.initiator = initiator;
this.added = added;
this.player = player;
}
public static HandlerList getHandlerList() {
return handlers;
}
/**
* If a player was added
*
* @return boolean
*/
public boolean wasAdded() {
return this.added;
}
/**
* The UUID added/removed
*
* @return UUID
*/
public UUID getPlayer() {
return this.player;
}
/**
* The player initiating the action
*
* @return Player
*/
public Player getInitiator() {
return this.initiator;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
}

View File

@ -0,0 +1,70 @@
package com.plotsquared.bukkit.events;
import com.intellectualcrafters.plot.object.Plot;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import java.util.UUID;
/**
*/
public class PlayerPlotTrustedEvent extends PlotEvent {
private static final HandlerList handlers = new HandlerList();
private final Player initiator;
private final boolean added;
private final UUID player;
/**
* PlayerPlotTrustedEvent: Called when a plot trusted user is added/removed
*
* @param initiator Player that initiated the event
* @param plot Plot in which the event occurred
* @param player Player that was added/removed from the trusted list
* @param added true of the player was added, false if the player was removed
*/
public PlayerPlotTrustedEvent(Player initiator, Plot plot, UUID player, boolean added) {
super(plot);
this.initiator = initiator;
this.added = added;
this.player = player;
}
public static HandlerList getHandlerList() {
return handlers;
}
/**
* If a player was added
*
* @return boolean
*/
public boolean wasAdded() {
return this.added;
}
/**
* The UUID added/removed
*
* @return UUID
*/
public UUID getPlayer() {
return this.player;
}
/**
* The player initiating the action
*
* @return Player
*/
public Player getInitiator() {
return this.initiator;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
}

View File

@ -0,0 +1,72 @@
package com.plotsquared.bukkit.events;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerEvent;
/**
* Called when a player teleports to a plot
*
*/
public class PlayerTeleportToPlotEvent extends PlayerEvent implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final Location from;
private final Plot plot;
private boolean cancelled;
/**
* PlayerTeleportToPlotEvent: Called when a player teleports to a plot
*
* @param player That was teleported
* @param from Start location
* @param plot Plot to which the player was teleported
*/
public PlayerTeleportToPlotEvent(Player player, Location from, Plot plot) {
super(player);
this.from = from;
this.plot = plot;
}
public static HandlerList getHandlerList() {
return handlers;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
/**
* Get the from location
*
* @return Location
*/
public Location getFrom() {
return this.from;
}
/**
* Get the plot involved
*
* @return Plot
*/
public Plot getPlot() {
return this.plot;
}
@Override
public boolean isCancelled() {
return this.cancelled;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
}

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.Cancellable;
import org.bukkit.event.HandlerList;
/**
* Called when a plot is cleared
*
*/
public class PlotClearEvent extends PlotEvent implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private boolean cancelled;
public PlotClearEvent(Plot plot) {
super(plot);
}
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;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
@Override
public boolean isCancelled() {
return this.cancelled;
}
@Override
public void setCancelled(boolean b) {
this.cancelled = b;
}
}

View File

@ -0,0 +1,45 @@
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 is deleted
*
*/
public class PlotDeleteEvent extends PlotEvent {
private static final HandlerList handlers = new HandlerList();
public PlotDeleteEvent(Plot plot) {
super(plot);
}
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;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
}

View File

@ -1,19 +1,18 @@
package com.plotsquared.bukkit.events; package com.plotsquared.bukkit.events;
import com.intellectualcrafters.plot.object.Plot;
import org.bukkit.event.Event; import org.bukkit.event.Event;
import com.intellectualcrafters.plot.object.Plot;
public abstract class PlotEvent extends Event { public abstract class PlotEvent extends Event {
private final Plot plot; private final Plot plot;
public PlotEvent(final Plot plot) { public PlotEvent(Plot plot) {
this.plot = plot; this.plot = plot;
} }
public final Plot getPlot() { public final Plot getPlot() {
return plot; return this.plot;
} }
} }

View File

@ -0,0 +1,56 @@
package com.plotsquared.bukkit.events;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.object.Plot;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
/**
* Called when a Flag is added to a plot.
*
*/
public class PlotFlagAddEvent extends PlotEvent implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final Flag flag;
private boolean cancelled;
/**
* PlotFlagAddEvent: Called when a Flag is added to a plot.
*
* @param flag Flag that was added
* @param plot Plot to which the flag was added
*/
public PlotFlagAddEvent(Flag flag, Plot plot) {
super(plot);
this.flag = flag;
}
public static HandlerList getHandlerList() {
return handlers;
}
/**
* Get the flag involved.
*
* @return Flag
*/
public Flag getFlag() {
return this.flag;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
@Override
public final boolean isCancelled() {
return this.cancelled;
}
@Override
public final void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
}

View File

@ -0,0 +1,56 @@
package com.plotsquared.bukkit.events;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.object.Plot;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
/**
* Called when a flag is removed from a plot
*
*/
public class PlotFlagRemoveEvent extends PlotEvent implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final Flag flag;
private boolean cancelled;
/**
* PlotFlagRemoveEvent: Called when a flag is removed from a plot
*
* @param flag Flag that was removed
* @param plot Plot from which the flag was removed
*/
public PlotFlagRemoveEvent(Flag flag, Plot plot) {
super(plot);
this.flag = flag;
}
public static HandlerList getHandlerList() {
return handlers;
}
/**
* Get the flag involved
*
* @return Flag
*/
public Flag getFlag() {
return this.flag;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
@Override
public final boolean isCancelled() {
return this.cancelled;
}
@Override
public final void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
}

View File

@ -0,0 +1,62 @@
package com.plotsquared.bukkit.events;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotId;
import org.bukkit.World;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
import java.util.ArrayList;
public class PlotMergeEvent extends PlotEvent implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final ArrayList<PlotId> plots;
private final World world;
private boolean cancelled;
/**
* PlotMergeEvent: Called when plots are merged
*
* @param world World in which the event occurred
* @param plot Plot that was merged
* @param plots A list of plots involved in the event
*/
public PlotMergeEvent(World world, Plot plot, ArrayList<PlotId> plots) {
super(plot);
this.world = world;
this.plots = plots;
}
public static HandlerList getHandlerList() {
return handlers;
}
/**
* Get the plots being added.
*
* @return Plot
*/
public ArrayList<PlotId> getPlots() {
return this.plots;
}
public World getWorld() {
return this.world;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
@Override
public boolean isCancelled() {
return this.cancelled;
}
@Override
public void setCancelled(boolean b) {
this.cancelled = b;
}
}

View File

@ -1,46 +1,41 @@
package com.plotsquared.bukkit.events; package com.plotsquared.bukkit.events;
import org.bukkit.event.HandlerList;
import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.Rating; import com.intellectualcrafters.plot.object.Rating;
import org.bukkit.event.HandlerList;
/**
* Created 2015-07-13 for PlotSquaredGit
*
*/
public class PlotRateEvent extends PlotEvent { public class PlotRateEvent extends PlotEvent {
private static HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
private final PlotPlayer rater; private final PlotPlayer rater;
private Rating rating; private Rating rating;
public PlotRateEvent(final PlotPlayer rater, final Rating rating, final Plot plot) { public PlotRateEvent(PlotPlayer rater, Rating rating, Plot plot) {
super(plot); super(plot);
this.rater = rater; this.rater = rater;
this.rating = rating; this.rating = rating;
} }
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
public PlotPlayer getRater() { public PlotPlayer getRater() {
return rater; return this.rater;
} }
public void setRating(final Rating rating) { public Rating getRating() {
return this.rating;
}
public void setRating(Rating rating) {
this.rating = rating; this.rating = rating;
} }
public Rating getRating() {
return rating;
}
@Override @Override
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
} }

View File

@ -0,0 +1,67 @@
package com.plotsquared.bukkit.events;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotId;
import org.bukkit.World;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import java.util.ArrayList;
public class PlotUnlinkEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private final ArrayList<PlotId> plots;
private final World world;
private final PlotArea area;
private boolean cancelled;
/**
* Called when a mega-plot is unlinked.
*
* @param world World in which the event occurred
* @param plots Plots that are involved in the event
*/
public PlotUnlinkEvent(World world, PlotArea area, ArrayList<PlotId> plots) {
this.plots = plots;
this.world = world;
this.area = area;
}
public static HandlerList getHandlerList() {
return handlers;
}
/**
* Get the plots involved.
*
* @return The {@link PlotId}'s of the plots involved
*/
public ArrayList<PlotId> getPlots() {
return this.plots;
}
public World getWorld() {
return this.world;
}
public PlotArea getArea() {
return this.area;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
@Override
public boolean isCancelled() {
return this.cancelled;
}
@Override
public void setCancelled(boolean b) {
this.cancelled = b;
}
}

View File

@ -10,8 +10,6 @@ import java.util.Random;
public class BukkitAugmentedGenerator extends BlockPopulator { public class BukkitAugmentedGenerator extends BlockPopulator {
private static BukkitAugmentedGenerator generator; private static BukkitAugmentedGenerator generator;
private BukkitAugmentedGenerator() {}
public static BukkitAugmentedGenerator get(World world) { public static BukkitAugmentedGenerator get(World world) {
for (BlockPopulator populator : world.getPopulators()) { for (BlockPopulator populator : world.getPopulators()) {
@ -27,7 +25,7 @@ public class BukkitAugmentedGenerator extends BlockPopulator {
} }
@Override @Override
public void populate(final World world, Random r, final Chunk chunk) { public void populate(World world, Random r, Chunk chunk) {
AugmentedUtils.generate(world.getName(), chunk.getX(), chunk.getZ(), null); AugmentedUtils.generate(world.getName(), chunk.getX(), chunk.getZ(), null);
} }
} }

View File

@ -1,36 +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.generator; package com.plotsquared.bukkit.generator;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.generator.BlockPopulator;
import org.bukkit.generator.ChunkGenerator;
import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.generator.GeneratorWrapper; import com.intellectualcrafters.plot.generator.GeneratorWrapper;
import com.intellectualcrafters.plot.generator.HybridGen; import com.intellectualcrafters.plot.generator.HybridGen;
@ -44,9 +13,17 @@ import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.PlotChunk; import com.intellectualcrafters.plot.util.PlotChunk;
import com.intellectualcrafters.plot.util.SetQueue; import com.intellectualcrafters.plot.util.SetQueue;
import com.plotsquared.bukkit.listeners.WorldEvents;
import com.plotsquared.bukkit.util.BukkitUtil; import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.bukkit.util.block.GenChunk; import com.plotsquared.bukkit.util.block.GenChunk;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.generator.BlockPopulator;
import org.bukkit.generator.ChunkGenerator;
public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrapper<ChunkGenerator> { public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrapper<ChunkGenerator> {
@ -54,22 +31,17 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
private final PseudoRandom random = new PseudoRandom(); private final PseudoRandom random = new PseudoRandom();
private final IndependentPlotGenerator plotGenerator; private final IndependentPlotGenerator plotGenerator;
private final List<BlockPopulator> populators = new ArrayList<>(); private final List<BlockPopulator> populators = new ArrayList<>();
private final ChunkGenerator platformGenerator;
private final boolean full;
private boolean loaded = false; private boolean loaded = false;
private ChunkGenerator platformGenerator;
private boolean full;
public BukkitPlotGenerator(IndependentPlotGenerator generator) { public BukkitPlotGenerator(IndependentPlotGenerator generator) {
this.plotGenerator = generator; this.plotGenerator = generator;
this.platformGenerator = this; this.platformGenerator = this;
populators.add(new BlockPopulator() { this.populators.add(new BlockPopulator() {
@Override @Override
public void populate(World world, Random r, Chunk c) { public void populate(World world, Random r, Chunk c) {
if (!(chunkSetter instanceof GenChunk)) { GenChunk result = (GenChunk) BukkitPlotGenerator.this.chunkSetter;
PS.debug("Current PlotChunk is not relevant to population?");
PS.stacktrace();
return;
}
GenChunk result = (GenChunk) chunkSetter;
if (result.result_data != null) { if (result.result_data != null) {
for (int i = 0; i < result.result_data.length; i++) { for (int i = 0; i < result.result_data.length; i++) {
byte[] section = result.result_data[i]; byte[] section = result.result_data[i];
@ -84,9 +56,16 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
} }
} }
} }
random.state = c.getX() << 16 | c.getZ() & 0xFFFF;
PlotArea area = PS.get().getPlotArea(world.getName(), null);
SetQueue.ChunkWrapper wrap = SetQueue.IMP.new ChunkWrapper(area.worldname, c.getX(), c.getZ());
PlotChunk<?> chunk = SetQueue.IMP.queue.getChunk(wrap);
if (plotGenerator.populateChunk(chunk, area, random)) {
chunk.addToQueue();
}
} }
}); });
chunkSetter = new GenChunk(null, null); this.chunkSetter = new GenChunk(null, null);
this.full = true; this.full = true;
MainUtil.initCache(); MainUtil.initCache();
} }
@ -96,10 +75,9 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
throw new IllegalArgumentException("ChunkGenerator: " + cg.getClass().getName() + " is already a BukkitPlotGenerator!"); throw new IllegalArgumentException("ChunkGenerator: " + cg.getClass().getName() + " is already a BukkitPlotGenerator!");
} }
this.full = false; this.full = false;
WorldEvents.lastWorld = world; PS.debug("BukkitPlotGenerator does not fully support: " + cg);
PS.get().debug("BukkitPlotGenerator does not fully support: " + cg); this.platformGenerator = cg;
platformGenerator = cg; this.plotGenerator = new IndependentPlotGenerator() {
plotGenerator = new IndependentPlotGenerator() {
@Override @Override
public void processSetup(SetupObject setup) {} public void processSetup(SetupObject setup) {}
@ -122,7 +100,7 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
} }
@Override @Override
public void generateChunk(final PlotChunk<?> result, final PlotArea settings, final PseudoRandom random) { public void generateChunk(final PlotChunk<?> result, PlotArea settings, PseudoRandom random) {
World w = BukkitUtil.getWorld(world); World w = BukkitUtil.getWorld(world);
Random r = new Random(result.getChunkWrapper().hashCode()); Random r = new Random(result.getChunkWrapper().hashCode());
BiomeGrid grid = new BiomeGrid() { BiomeGrid grid = new BiomeGrid() {
@ -142,8 +120,9 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
if (data != null) { if (data != null) {
return; return;
} }
} catch (Throwable e) {
//ignored
} }
catch (Throwable e) {}
// Populator spillage // Populator spillage
short[][] tmp = cg.generateExtBlockSections(w, r, result.getX(), result.getZ(), grid); short[][] tmp = cg.generateExtBlockSections(w, r, result.getX(), result.getZ(), grid);
if (tmp != null) { if (tmp != null) {
@ -174,9 +153,9 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
} }
} }
}; };
chunkSetter = new GenChunk(null, SetQueue.IMP.new ChunkWrapper(world, 0, 0)); this.chunkSetter = new GenChunk(null, SetQueue.IMP.new ChunkWrapper(world, 0, 0));
if (cg != null) { if (cg != null) {
populators.addAll(cg.getDefaultPopulators(BukkitUtil.getWorld(world))); this.populators.addAll(cg.getDefaultPopulators(BukkitUtil.getWorld(world)));
} }
MainUtil.initCache(); MainUtil.initCache();
} }
@ -188,24 +167,26 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
@Override @Override
public boolean isFull() { public boolean isFull() {
return full; return this.full;
} }
@Override @Override
public IndependentPlotGenerator getPlotGenerator() { public IndependentPlotGenerator getPlotGenerator() {
return plotGenerator; return this.plotGenerator;
} }
@Override @Override
public ChunkGenerator getPlatformGenerator() { public ChunkGenerator getPlatformGenerator() {
return platformGenerator; return this.platformGenerator;
} }
@Override @Override
public List<BlockPopulator> getDefaultPopulators(final World world) { public List<BlockPopulator> getDefaultPopulators(World world) {
try { try {
if (!loaded) { if (!this.loaded) {
final String name = WorldEvents.getName(world); String name = world.getName();
PS.get().loadWorld(name, this); PS.get().loadWorld(name, this);
Set<PlotArea> areas = PS.get().getPlotAreas(name); Set<PlotArea> areas = PS.get().getPlotAreas(name);
if (!areas.isEmpty()) { if (!areas.isEmpty()) {
@ -226,32 +207,39 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
world.setWaterAnimalSpawnLimit(-1); world.setWaterAnimalSpawnLimit(-1);
} }
} }
loaded = true; this.loaded = true;
} }
} catch (final Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
return populators; if (world == null) {
return populators;
}
ArrayList<BlockPopulator> toAdd = new ArrayList<BlockPopulator>();
List<BlockPopulator> existing = world.getPopulators();
for (BlockPopulator populator : populators) {
if (!existing.contains(populator)) {
toAdd.add(populator);
}
}
return toAdd;
} }
@Override @Override
public ChunkData generateChunkData(World world, Random random, int cx, int cz, BiomeGrid grid) { public ChunkData generateChunkData(World world, Random random, int cx, int cz, BiomeGrid grid) {
if (!(chunkSetter instanceof GenChunk)) { GenChunk result = (GenChunk) this.chunkSetter;
PS.debug("Current PlotChunk is not relevant to generation?");
PS.stacktrace();
return null;
}
GenChunk result = (GenChunk) chunkSetter;
// Set the chunk location // Set the chunk location
result.setChunkWrapper(SetQueue.IMP.new ChunkWrapper(world.getName(), cx, cz)); result.setChunkWrapper(SetQueue.IMP.new ChunkWrapper(world.getName(), cx, cz));
// Set the result data // Set the result data
result.cd = createChunkData(world); result.cd = createChunkData(world);
result.grid = grid; result.grid = grid;
// Catch any exceptions (as exceptions usually thrown result.result = null;
result.result_data = null;
// Catch any exceptions (as exceptions usually thrown)
try { try {
// Fill the result data if necessary // Fill the result data if necessary
if (platformGenerator != this) { if (this.platformGenerator != this) {
return platformGenerator.generateChunkData(world, random, cx, cz, grid); return this.platformGenerator.generateChunkData(world, random, cx, cz, grid);
} else { } else {
generate(world, cx, cz, result); generate(world, cx, cz, result);
} }
@ -264,42 +252,37 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
public void generate(World world, int cx, int cz, GenChunk result) { public void generate(World world, int cx, int cz, GenChunk result) {
// Load if improperly loaded // Load if improperly loaded
if (!loaded) { if (!this.loaded) {
final String name = WorldEvents.getName(world); String name = world.getName();
PS.get().loadWorld(name, this); PS.get().loadWorld(name, this);
loaded = true; this.loaded = true;
} }
// Set random seed // Set random seed
this.random.state = (cx << 16) | (cz & 0xFFFF); this.random.state = cx << 16 | cz & 0xFFFF;
// Process the chunk // Process the chunk
result.modified = false; if (ChunkManager.preProcessChunk(result)) {
ChunkManager.preProcessChunk(result);
if (result.modified) {
return; return;
} }
PlotArea area = PS.get().getPlotArea(world.getName(), null); PlotArea area = PS.get().getPlotArea(world.getName(), null);
plotGenerator.generateChunk(chunkSetter, area, this.random); this.plotGenerator.generateChunk(this.chunkSetter, area, this.random);
ChunkManager.postProcessChunk(result); ChunkManager.postProcessChunk(result);
return;
} }
@Override @Override
public short[][] generateExtBlockSections(final World world, final Random r, final int cx, final int cz, final BiomeGrid grid) { public short[][] generateExtBlockSections(World world, Random r, int cx, int cz, BiomeGrid grid) {
if (!(chunkSetter instanceof GenChunk)) { GenChunk result = (GenChunk) this.chunkSetter;
PS.stacktrace();
return new short[16][];
}
GenChunk result = (GenChunk) chunkSetter;
// Set the chunk location // Set the chunk location
result.setChunkWrapper(SetQueue.IMP.new ChunkWrapper(world.getName(), cx, cz)); result.setChunkWrapper(SetQueue.IMP.new ChunkWrapper(world.getName(), cx, cz));
// Set the result data // Set the result data
result.result = new short[16][]; result.result = new short[16][];
result.result_data = new byte[16][]; result.result_data = new byte[16][];
// Catch any exceptions (as exceptions usually thrown result.grid = grid;
result.cd = null;
// Catch any exceptions (as exceptions usually thrown)
try { try {
// Fill the result data // Fill the result data
if (platformGenerator != this) { if (this.platformGenerator != this) {
return platformGenerator.generateExtBlockSections(world, r, cx, cz, grid); return this.platformGenerator.generateExtBlockSections(world, r, cx, cz, grid);
} else { } else {
generate(world, cx, cz, result); generate(world, cx, cz, result);
} }
@ -311,19 +294,27 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
} }
/** /**
* Allow spawning everywhere * Allow spawning everywhere.
* @param world Ignored
* @param x Ignored
* @param z Ignored
* @return always true
*/ */
@Override @Override
public boolean canSpawn(final World world, final int x, final int z) { public boolean canSpawn(World world, int x, int z) {
return true; return true;
} }
@Override @Override
public String toString() { public String toString() {
if (platformGenerator == this) { if (this.platformGenerator == this) {
return "" + plotGenerator; return "" + this.plotGenerator;
}
if (this.platformGenerator == null) {
return "null";
} else {
return this.platformGenerator.getClass().getName();
} }
return platformGenerator == null ? "null" : platformGenerator.getClass().getName();
} }
@Override @Override
@ -331,6 +322,6 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
if (obj == null) { if (obj == null) {
return false; return false;
} }
return (toString().equals(obj.toString()) || toString().equals(obj.getClass().getName())); return toString().equals(obj.toString()) || toString().equals(obj.getClass().getName());
} }
} }

View File

@ -36,36 +36,37 @@ import java.util.HashMap;
import java.util.Map.Entry; import java.util.Map.Entry;
public class ChunkListener implements Listener { public class ChunkListener implements Listener {
private final RefClass classChunk = getRefClass("{nms}.Chunk");
private final RefClass classCraftChunk = getRefClass("{cb}.CraftChunk");
private final RefField mustSave = classChunk.getField("mustSave");
private Chunk lastChunk = null;
private RefMethod methodGetHandleChunk; private RefMethod methodGetHandleChunk;
private RefField mustSave;
private Chunk lastChunk;
public ChunkListener() { public ChunkListener() {
RefMethod method; if (Settings.CHUNK_PROCESSOR_GC || Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE) {
try { try {
method = classCraftChunk.getMethod("getHandle"); RefClass classChunk = getRefClass("{nms}.Chunk");
} catch (final Exception e) { RefClass classCraftChunk = getRefClass("{cb}.CraftChunk");
method = null; this.mustSave = classChunk.getField("mustSave");
e.printStackTrace(); 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;
}
} }
methodGetHandleChunk = method;
if (!Settings.CHUNK_PROCESSOR_GC) { if (!Settings.CHUNK_PROCESSOR_GC) {
return; return;
} }
TaskManager.runTask(new Runnable() { TaskManager.runTask(new Runnable() {
@Override @Override
public void run() { public void run() {
final int distance = Bukkit.getViewDistance() + 2; int distance = Bukkit.getViewDistance() + 2;
final HashMap<String, HashMap<ChunkLoc, Integer>> players = new HashMap<>(); HashMap<String, HashMap<ChunkLoc, Integer>> players = new HashMap<>();
for (final Entry<String, PlotPlayer> entry : UUIDHandler.getPlayers().entrySet()) { for (Entry<String, PlotPlayer> entry : UUIDHandler.getPlayers().entrySet()) {
final PlotPlayer pp = entry.getValue(); PlotPlayer pp = entry.getValue();
final Location loc = pp.getLocation(); Location location = pp.getLocation();
final String world = loc.getWorld(); String world = location.getWorld();
if (!PS.get().hasPlotArea(world)) { if (!PS.get().hasPlotArea(world)) {
continue; continue;
} }
@ -74,7 +75,7 @@ public class ChunkListener implements Listener {
map = new HashMap<>(); map = new HashMap<>();
players.put(world, map); players.put(world, map);
} }
final ChunkLoc origin = new ChunkLoc(loc.getX() >> 4, loc.getZ() >> 4); ChunkLoc origin = new ChunkLoc(location.getX() >> 4, location.getZ() >> 4);
Integer val = map.get(origin); Integer val = map.get(origin);
int check; int check;
if (val != null) { if (val != null) {
@ -94,8 +95,8 @@ public class ChunkListener implements Listener {
if (z >= check || -z >= check) { if (z >= check || -z >= check) {
continue; continue;
} }
final int weight = distance - Math.max(Math.abs(x), Math.abs(z)); int weight = distance - Math.max(Math.abs(x), Math.abs(z));
final ChunkLoc chunk = new ChunkLoc(x + origin.x, z + origin.z); ChunkLoc chunk = new ChunkLoc(x + origin.x, z + origin.z);
val = map.get(chunk); val = map.get(chunk);
if (val == null || val < weight) { if (val == null || val < weight) {
map.put(chunk, weight); map.put(chunk, weight);
@ -105,24 +106,24 @@ public class ChunkListener implements Listener {
} }
} }
int time = 300; int time = 300;
for (final World world : Bukkit.getWorlds()) { for (World world : Bukkit.getWorlds()) {
final String name = world.getName(); String name = world.getName();
if (!PS.get().hasPlotArea(name)) { if (!PS.get().hasPlotArea(name)) {
continue; continue;
} }
final boolean autosave = world.isAutoSave(); boolean autoSave = world.isAutoSave();
if (autosave) { if (autoSave) {
world.setAutoSave(false); world.setAutoSave(false);
} }
final HashMap<ChunkLoc, Integer> map = players.get(name); HashMap<ChunkLoc, Integer> map = players.get(name);
if (map == null || map.isEmpty()) { if (map == null || map.isEmpty()) {
continue; continue;
} }
Chunk[] chunks = world.getLoadedChunks(); Chunk[] chunks = world.getLoadedChunks();
ArrayDeque<Chunk> toUnload = new ArrayDeque<>(); ArrayDeque<Chunk> toUnload = new ArrayDeque<>();
for (final Chunk chunk : chunks) { for (Chunk chunk : chunks) {
final int x = chunk.getX(); int x = chunk.getX();
final int z = chunk.getZ(); int z = chunk.getZ();
if (!map.containsKey(new ChunkLoc(x, z))) { if (!map.containsKey(new ChunkLoc(x, z))) {
toUnload.add(chunk); toUnload.add(chunk);
} }
@ -141,7 +142,7 @@ public class ChunkListener implements Listener {
time = 1; time = 1;
} }
} }
if (!Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE && autosave) { if (!Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE && autoSave) {
world.setAutoSave(true); world.setAutoSave(true);
} }
} }
@ -149,15 +150,14 @@ public class ChunkListener implements Listener {
} }
}); });
} }
public boolean unloadChunk(final String world, final Chunk chunk) { public boolean unloadChunk(String world, Chunk chunk) {
final int X = chunk.getX(); int X = chunk.getX();
final int Z = chunk.getZ(); int Z = chunk.getZ();
final int x = X << 4; int x = X << 4;
final int z = Z << 4; int z = Z << 4;
final int x2 = x + 15; int x2 = x + 15;
final int z2 = z + 15; int z2 = z + 15;
Thread thread = new Thread();
Plot plot = new Location(world, x, 1, z).getOwnedPlotAbs(); Plot plot = new Location(world, x, 1, z).getOwnedPlotAbs();
if (plot != null && plot.hasOwner()) { if (plot != null && plot.hasOwner()) {
return false; return false;
@ -178,8 +178,8 @@ public class ChunkListener implements Listener {
if (plot != null && plot.hasOwner()) { if (plot != null && plot.hasOwner()) {
return false; return false;
} }
final Object c = methodGetHandleChunk.of(chunk).call(); Object c = this.methodGetHandleChunk.of(chunk).call();
mustSave.of(c).set(false); this.mustSave.of(c).set(false);
if (chunk.isLoaded()) { if (chunk.isLoaded()) {
chunk.unload(false, false); chunk.unload(false, false);
} }
@ -187,10 +187,10 @@ public class ChunkListener implements Listener {
} }
@EventHandler @EventHandler
public void onChunkUnload(final ChunkUnloadEvent event) { public void onChunkUnload(ChunkUnloadEvent event) {
if (Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE) { if (Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE) {
final Chunk chunk = event.getChunk(); Chunk chunk = event.getChunk();
final String world = chunk.getWorld().getName(); String world = chunk.getWorld().getName();
if (PS.get().hasPlotArea(world)) { if (PS.get().hasPlotArea(world)) {
if (unloadChunk(world, chunk)) { if (unloadChunk(world, chunk)) {
return; return;
@ -203,15 +203,15 @@ public class ChunkListener implements Listener {
} }
@EventHandler @EventHandler
public void onChunkLoad(final ChunkLoadEvent event) { public void onChunkLoad(ChunkLoadEvent event) {
processChunk(event.getChunk(), false); processChunk(event.getChunk(), false);
} }
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void onItemSpawn(final ItemSpawnEvent event) { public void onItemSpawn(ItemSpawnEvent event) {
final Item entity = event.getEntity(); Item entity = event.getEntity();
final Chunk chunk = entity.getLocation().getChunk(); Chunk chunk = entity.getLocation().getChunk();
if (chunk == lastChunk) { if (chunk == this.lastChunk) {
event.getEntity().remove(); event.getEntity().remove();
event.setCancelled(true); event.setCancelled(true);
return; return;
@ -219,28 +219,28 @@ public class ChunkListener implements Listener {
if (!PS.get().hasPlotArea(chunk.getWorld().getName())) { if (!PS.get().hasPlotArea(chunk.getWorld().getName())) {
return; return;
} }
final Entity[] entities = chunk.getEntities(); Entity[] entities = chunk.getEntities();
if (entities.length > Settings.CHUNK_PROCESSOR_MAX_ENTITIES) { if (entities.length > Settings.CHUNK_PROCESSOR_MAX_ENTITIES) {
event.getEntity().remove(); event.getEntity().remove();
event.setCancelled(true); event.setCancelled(true);
lastChunk = chunk; this.lastChunk = chunk;
} else { } else {
lastChunk = null; this.lastChunk = null;
} }
} }
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockPhysics(final BlockPhysicsEvent event) { public void onBlockPhysics(BlockPhysicsEvent event) {
if (Settings.CHUNK_PROCESSOR_DISABLE_PHYSICS) { if (Settings.CHUNK_PROCESSOR_DISABLE_PHYSICS) {
event.setCancelled(true); event.setCancelled(true);
} }
} }
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void onEntitySpawn(final CreatureSpawnEvent event) { public void onEntitySpawn(CreatureSpawnEvent event) {
final LivingEntity entity = event.getEntity(); LivingEntity entity = event.getEntity();
final Chunk chunk = entity.getLocation().getChunk(); Chunk chunk = entity.getLocation().getChunk();
if (chunk == lastChunk) { if (chunk == this.lastChunk) {
event.getEntity().remove(); event.getEntity().remove();
event.setCancelled(true); event.setCancelled(true);
return; return;
@ -248,20 +248,20 @@ public class ChunkListener implements Listener {
if (!PS.get().hasPlotArea(chunk.getWorld().getName())) { if (!PS.get().hasPlotArea(chunk.getWorld().getName())) {
return; return;
} }
final Entity[] entities = chunk.getEntities(); Entity[] entities = chunk.getEntities();
if (entities.length > Settings.CHUNK_PROCESSOR_MAX_ENTITIES) { if (entities.length > Settings.CHUNK_PROCESSOR_MAX_ENTITIES) {
event.getEntity().remove(); event.getEntity().remove();
event.setCancelled(true); event.setCancelled(true);
lastChunk = chunk; this.lastChunk = chunk;
} else { } else {
lastChunk = null; this.lastChunk = null;
} }
} }
public void cleanChunk(final Chunk chunk) { private void cleanChunk(final Chunk chunk) {
TaskManager.index.incrementAndGet(); TaskManager.index.incrementAndGet();
final Integer currentIndex = TaskManager.index.get(); final Integer currentIndex = TaskManager.index.get();
final Integer task = TaskManager.runTaskRepeat(new Runnable() { Integer task = TaskManager.runTaskRepeat(new Runnable() {
@Override @Override
public void run() { public void run() {
if (!chunk.isLoaded()) { if (!chunk.isLoaded()) {
@ -271,7 +271,7 @@ public class ChunkListener implements Listener {
chunk.unload(true, true); chunk.unload(true, true);
return; return;
} }
final BlockState[] tiles = chunk.getTileEntities(); BlockState[] tiles = chunk.getTileEntities();
if (tiles.length == 0) { if (tiles.length == 0) {
Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex)); Bukkit.getScheduler().cancelTask(TaskManager.tasks.get(currentIndex));
TaskManager.tasks.remove(currentIndex); TaskManager.tasks.remove(currentIndex);
@ -279,7 +279,7 @@ public class ChunkListener implements Listener {
chunk.unload(true, true); chunk.unload(true, true);
return; return;
} }
final long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
int i = 0; int i = 0;
while (System.currentTimeMillis() - start < 250) { while (System.currentTimeMillis() - start < 250) {
if (i >= tiles.length) { if (i >= tiles.length) {
@ -296,15 +296,15 @@ public class ChunkListener implements Listener {
}, 5); }, 5);
TaskManager.tasks.put(currentIndex, task); TaskManager.tasks.put(currentIndex, task);
} }
public boolean processChunk(final Chunk chunk, final boolean unload) { public boolean processChunk(Chunk chunk, boolean unload) {
if (!PS.get().hasPlotArea(chunk.getWorld().getName())) { if (!PS.get().hasPlotArea(chunk.getWorld().getName())) {
return false; return false;
} }
final Entity[] entities = chunk.getEntities(); Entity[] entities = chunk.getEntities();
final BlockState[] tiles = chunk.getTileEntities(); BlockState[] tiles = chunk.getTileEntities();
if (entities.length > Settings.CHUNK_PROCESSOR_MAX_ENTITIES) { if (entities.length > Settings.CHUNK_PROCESSOR_MAX_ENTITIES) {
for (final Entity ent : entities) { for (Entity ent : entities) {
if (!(ent instanceof Player)) { if (!(ent instanceof Player)) {
ent.remove(); ent.remove();
} }
@ -317,7 +317,7 @@ public class ChunkListener implements Listener {
cleanChunk(chunk); cleanChunk(chunk);
return true; return true;
} }
for (final BlockState tile : tiles) { for (BlockState tile : tiles) {
tile.getBlock().setType(Material.AIR, false); tile.getBlock().setType(Material.AIR, false);
} }
} }

View File

@ -0,0 +1,105 @@
package com.plotsquared.bukkit.listeners;
import com.intellectualcrafters.plot.flag.FlagManager;
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 {
private 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())) {
continue;
}
if (!plot.isAdded(pp.getUUID())) {
players.add(pp);
}
}
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())) {
continue;
}
if (plot.isAdded(pp.getUUID())) {
return pp;
}
}
return null;
}
public Vector calculateVelocity(PlotPlayer pp, PlotPlayer e) {
Location playerLocation = pp.getLocationFull();
Location oPlayerLocation = e.getLocation();
double playerX = playerLocation.getX();
double playerY = playerLocation.getY();
double playerZ = playerLocation.getZ();
double oPlayerX = oPlayerLocation.getX();
double oPlayerY = oPlayerLocation.getY();
double oPlayerZ = oPlayerLocation.getZ();
double x = 0d;
if (playerX < oPlayerX) {
x = 1.0d;
} else if (playerX > oPlayerX) {
x = -1.0d;
}
double y = 0d;
if (playerY < oPlayerY) {
y = 0.5d;
} else if (playerY > oPlayerY) {
y = -0.5d;
}
double z = 0d;
if (playerZ < oPlayerZ) {
z = 1.0d;
} else if (playerZ > oPlayerZ) {
z = -1.0d;
}
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));
}
}
}
}
}

View File

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

View File

@ -1,9 +1,15 @@
package com.plotsquared.bukkit.listeners; package com.plotsquared.bukkit.listeners;
import java.util.HashSet; import com.intellectualcrafters.plot.PS;
import java.util.List; import com.intellectualcrafters.plot.config.C;
import java.util.UUID; import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.listener.PlotListener;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.block.BlockState; import org.bukkit.block.BlockState;
import org.bukkit.entity.ArmorStand; import org.bukkit.entity.ArmorStand;
@ -20,48 +26,41 @@ import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import com.intellectualcrafters.plot.PS; import java.util.HashSet;
import com.intellectualcrafters.plot.config.C; import java.util.List;
import com.intellectualcrafters.plot.object.Location; import java.util.UUID;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.listener.PlotListener;
public class PlayerEvents_1_8 extends PlotListener implements Listener { public class PlayerEvents_1_8 extends PlotListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onInventoryClick(final InventoryClickEvent event) { public void onInventoryClick(InventoryClickEvent event) {
if (!event.isLeftClick() || (event.getAction() != InventoryAction.PLACE_ALL) || event.isShiftClick()) { if (!event.isLeftClick() || (event.getAction() != InventoryAction.PLACE_ALL) || event.isShiftClick()) {
return; return;
} }
final HumanEntity entity = event.getWhoClicked(); HumanEntity entity = event.getWhoClicked();
if (!(entity instanceof Player) || !PS.get().hasPlotArea(entity.getWorld().getName())) { if (!(entity instanceof Player) || !PS.get().hasPlotArea(entity.getWorld().getName())) {
return; return;
} }
final Player player = (Player) entity; Player player = (Player) entity;
final PlayerInventory inv = player.getInventory(); PlayerInventory inv = player.getInventory();
final int slot = inv.getHeldItemSlot(); int slot = inv.getHeldItemSlot();
if ((slot != event.getSlot()) || (slot > 8) || !event.getEventName().equals("InventoryCreativeEvent")) { if ((slot != event.getSlot()) || (slot > 8) || !event.getEventName().equals("InventoryCreativeEvent")) {
return; return;
} }
final ItemStack current = inv.getItemInHand(); ItemStack current = inv.getItemInHand();
final ItemStack newItem = event.getCursor(); ItemStack newItem = event.getCursor();
final ItemMeta newMeta = newItem.getItemMeta(); ItemMeta newMeta = newItem.getItemMeta();
final ItemMeta oldMeta = newItem.getItemMeta(); ItemMeta oldMeta = newItem.getItemMeta();
String newLore = ""; String newLore = "";
if (newMeta != null) { if (newMeta != null) {
final List<String> lore = newMeta.getLore(); List<String> lore = newMeta.getLore();
if (lore != null) { if (lore != null) {
newLore = lore.toString(); newLore = lore.toString();
} }
} }
String oldLore = ""; String oldLore = "";
if (oldMeta != null) { if (oldMeta != null) {
final List<String> lore = oldMeta.getLore(); List<String> lore = oldMeta.getLore();
if (lore != null) { if (lore != null) {
oldLore = lore.toString(); oldLore = lore.toString();
} }
@ -69,86 +68,82 @@ public class PlayerEvents_1_8 extends PlotListener implements Listener {
if (!newLore.equals("[(+NBT)]") || (current.equals(newItem) && newLore.equals(oldLore))) { if (!newLore.equals("[(+NBT)]") || (current.equals(newItem) && newLore.equals(oldLore))) {
return; return;
} }
final HashSet<Byte> blocks = null; HashSet<Byte> blocks = null;
final Block block = player.getTargetBlock(blocks, 7); Block block = player.getTargetBlock(blocks, 7);
final BlockState state = block.getState(); BlockState state = block.getState();
if (state == null) { if (state == null) {
return; return;
} }
if (state.getType() != newItem.getType()) { if (state.getType() != newItem.getType()) {
return; return;
} }
final Location l = BukkitUtil.getLocation(state.getLocation()); Location l = BukkitUtil.getLocation(state.getLocation());
PlotArea area = l.getPlotArea(); PlotArea area = l.getPlotArea();
if (area == null) { if (area == null) {
return; return;
} }
final Plot plot = area.getPlotAbs(l); Plot plot = area.getPlotAbs(l);
final PlotPlayer pp = BukkitUtil.getPlayer(player); PlotPlayer pp = BukkitUtil.getPlayer(player);
boolean cancelled = false; boolean cancelled = false;
if (plot == null) { if (plot == null) {
if (!Permissions.hasPermission(pp, "plots.admin.interact.road")) { if (!Permissions.hasPermission(pp, "plots.admin.interact.road")) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.road"); MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.road");
cancelled = true; cancelled = true;
} }
} else if (!plot.hasOwner()) {
if (!Permissions.hasPermission(pp, "plots.admin.interact.unowned")) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.unowned");
cancelled = true;
}
} else { } else {
if (!plot.hasOwner()) { UUID uuid = pp.getUUID();
if (!Permissions.hasPermission(pp, "plots.admin.interact.unowned")) { if (!plot.isAdded(uuid)) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.unowned"); if (!Permissions.hasPermission(pp, "plots.admin.interact.other")) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.other");
cancelled = true; cancelled = true;
} }
} else {
final UUID uuid = pp.getUUID();
if (!plot.isAdded(uuid)) {
if (!Permissions.hasPermission(pp, "plots.admin.interact.other")) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.other");
cancelled = true;
}
}
} }
} }
if (cancelled) { if (cancelled) {
if ((current.getTypeId() == newItem.getTypeId()) && (current.getDurability() == newItem.getDurability())) { if ((current.getType() == newItem.getType()) && (current.getDurability() == newItem.getDurability())) {
event.setCursor(new ItemStack(newItem.getTypeId(), newItem.getAmount(), newItem.getDurability())); event.setCursor(new ItemStack(newItem.getType(), newItem.getAmount(), newItem.getDurability()));
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
event.setCursor(new ItemStack(newItem.getTypeId(), newItem.getAmount(), newItem.getDurability())); event.setCursor(new ItemStack(newItem.getType(), newItem.getAmount(), newItem.getDurability()));
} }
} }
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onInteract(final PlayerInteractAtEntityEvent e) { public void onInteract(PlayerInteractAtEntityEvent e) {
final Entity entity = e.getRightClicked(); Entity entity = e.getRightClicked();
if (!(entity instanceof ArmorStand)) { if (!(entity instanceof ArmorStand)) {
return; return;
} }
final Location l = BukkitUtil.getLocation(e.getRightClicked().getLocation()); Location l = BukkitUtil.getLocation(e.getRightClicked().getLocation());
final PlotArea area = l.getPlotArea(); PlotArea area = l.getPlotArea();
if (area == null) { if (area == null) {
return; return;
} }
final Plot plot = area.getPlotAbs(l); Plot plot = area.getPlotAbs(l);
final PlotPlayer pp = BukkitUtil.getPlayer(e.getPlayer()); PlotPlayer pp = BukkitUtil.getPlayer(e.getPlayer());
if (plot == null) { if (plot == null) {
if (!Permissions.hasPermission(pp, "plots.admin.interact.road")) { if (!Permissions.hasPermission(pp, "plots.admin.interact.road")) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.road"); MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.road");
e.setCancelled(true); e.setCancelled(true);
} }
} else if (!plot.hasOwner()) {
if (!Permissions.hasPermission(pp, "plots.admin.interact.unowned")) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.unowned");
e.setCancelled(true);
}
} else { } else {
if (!plot.hasOwner()) { UUID uuid = pp.getUUID();
if (!Permissions.hasPermission(pp, "plots.admin.interact.unowned")) { if (!plot.isAdded(uuid)) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.unowned"); if (!Permissions.hasPermission(pp, "plots.admin.interact.other")) {
MainUtil.sendMessage(pp, C.NO_PERMISSION_EVENT, "plots.admin.interact.other");
e.setCancelled(true); e.setCancelled(true);
} }
} else {
final UUID uuid = pp.getUUID();
if (!plot.isAdded(uuid)) {
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,34 @@
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;
/**
* Created by Jesse on 3/30/2016.
*/
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

@ -0,0 +1,190 @@
package com.plotsquared.bukkit.listeners;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.plotsquared.bukkit.events.PlayerEnterPlotEvent;
import com.plotsquared.bukkit.events.PlayerLeavePlotEvent;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.listener.PlotListener;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
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.BlockDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.UUID;
public class PlotPlusListener extends PlotListener implements Listener {
private static final HashMap<String, Interval> feedRunnable = new HashMap<>();
private static final HashMap<String, Interval> healRunnable = new HashMap<>();
public static void startRunnable(JavaPlugin plugin) {
plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
@Override
public void run() {
if (!healRunnable.isEmpty()) {
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) {
iterator.remove();
continue;
}
double level = player.getHealth();
if (level != value.max) {
player.setHealth(Math.min(level + value.amount, value.max));
}
}
}
}
if (!feedRunnable.isEmpty()) {
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) {
iterator.remove();
continue;
}
int level = player.getFoodLevel();
if (level != value.max) {
player.setFoodLevel(Math.min(level + value.amount, value.max));
}
}
}
}
}
}, 0L, 20L);
}
@EventHandler(priority = EventPriority.HIGH)
public void onInteract(BlockDamageEvent event) {
Player player = event.getPlayer();
if (player.getGameMode() != GameMode.SURVIVAL) {
return;
}
Plot plot = BukkitUtil.getLocation(player).getOwnedPlot();
if (plot == null) {
return;
}
if (FlagManager.isBooleanFlag(plot, "instabreak", false)) {
event.getBlock().breakNaturally();
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onDamage(EntityDamageEvent event) {
if (event.getEntityType() != EntityType.PLAYER) {
return;
}
Player player = (Player) event.getEntity();
Plot plot = BukkitUtil.getLocation(player).getOwnedPlot();
if (plot == null) {
return;
}
if (FlagManager.isBooleanFlag(plot, "invincible", false)) {
event.setCancelled(true);
}
}
@EventHandler
public void onItemPickup(PlayerPickupItemEvent event) {
Player player = event.getPlayer();
PlotPlayer pp = BukkitUtil.getPlayer(player);
Plot plot = BukkitUtil.getLocation(player).getOwnedPlot();
if (plot == null) {
return;
}
UUID uuid = pp.getUUID();
if (plot.isAdded(uuid) && FlagManager.isBooleanFlag(plot, "drop-protection", false)) {
event.setCancelled(true);
}
}
@EventHandler
public void onItemDrop(PlayerDropItemEvent event) {
Player player = event.getPlayer();
PlotPlayer pp = BukkitUtil.getPlayer(player);
Plot plot = BukkitUtil.getLocation(player).getOwnedPlot();
if (plot == null) {
return;
}
UUID uuid = pp.getUUID();
if (plot.isAdded(uuid) && FlagManager.isBooleanFlag(plot, "item-drop", false)) {
event.setCancelled(true);
}
}
@EventHandler
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();
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();
healRunnable.put(player.getName(), new Interval(value[0], value[1], 20));
}
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event) {
Player player = event.getPlayer();
String name = player.getName();
feedRunnable.remove(name);
healRunnable.remove(name);
}
@EventHandler
public void onPlotLeave(PlayerLeavePlotEvent event) {
Player leaver = event.getPlayer();
Plot plot = event.getPlot();
if (!plot.hasOwner()) {
return;
}
BukkitUtil.getPlayer(leaver);
String name = leaver.getName();
feedRunnable.remove(name);
healRunnable.remove(name);
}
private static class Interval {
final int interval;
final int amount;
final int max;
public int count = 0;
Interval(int interval, int amount, int max) {
this.interval = interval;
this.amount = amount;
this.max = max;
}
}
}

View File

@ -1,5 +1,8 @@
package com.plotsquared.bukkit.listeners; package com.plotsquared.bukkit.listeners;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.generator.GeneratorWrapper;
import com.plotsquared.bukkit.generator.BukkitPlotGenerator;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
@ -7,34 +10,17 @@ import org.bukkit.event.Listener;
import org.bukkit.event.world.WorldInitEvent; import org.bukkit.event.world.WorldInitEvent;
import org.bukkit.generator.ChunkGenerator; import org.bukkit.generator.ChunkGenerator;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.generator.GeneratorWrapper;
import com.plotsquared.bukkit.generator.BukkitPlotGenerator;
public class WorldEvents implements Listener { public class WorldEvents implements Listener {
public static String lastWorld = null;
public static String getName(final World world) {
if ((lastWorld != null) && !lastWorld.equals("CheckingPlotSquaredGenerator")) {
return lastWorld;
} else {
return world.getName();
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public static void onWorldInit(final WorldInitEvent event) { public void onWorldInit(WorldInitEvent event) {
final World world = event.getWorld(); World world = event.getWorld();
final String name = getName(world); String name = world.getName();
final ChunkGenerator gen = world.getGenerator(); ChunkGenerator gen = world.getGenerator();
if (gen instanceof GeneratorWrapper) { if (gen instanceof GeneratorWrapper) {
PS.get().loadWorld(name, (GeneratorWrapper<?>) gen); PS.get().loadWorld(name, (GeneratorWrapper<?>) gen);
} else { } else {
if (PS.get().config.contains("worlds." + name)) { PS.get().loadWorld(name, new BukkitPlotGenerator(name, gen));
PS.get().loadWorld(name, new BukkitPlotGenerator(name, gen));
}
} }
lastWorld = null;
} }
} }

View File

@ -1,19 +1,5 @@
package com.plotsquared.bukkit.listeners.worldedit; package com.plotsquared.bukkit.listeners.worldedit;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
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 com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.config.Settings;
@ -29,35 +15,39 @@ import com.plotsquared.listener.WEManager;
import com.sk89q.worldedit.BlockVector; import com.sk89q.worldedit.BlockVector;
import com.sk89q.worldedit.bukkit.WorldEditPlugin; import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import com.sk89q.worldedit.bukkit.selections.Selection; 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 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> 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 = 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_1 = new HashSet<>(Arrays.asList("hcyl", "cyl"));
public final HashSet<String> rad2_2 = new HashSet<>(Arrays.asList("sphere", "pyramid")); 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> 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_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> 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", public final HashSet<String> region = new HashSet<>(
"regen", "copy", "cut", "green", "setbiome")); 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> regionExtend = new HashSet<>(Collections.singletonList("stack"));
public final HashSet<String> unregioned = new HashSet<>(Arrays.asList("paste", "redo", "undo", "rotate", "flip", "generate", "schematic", "schem"));
public final HashSet<String> unsafe1 = new HashSet<>(Arrays.asList("cs", ".s", "restore", "snapshot", "delchunks", "listchunks"));
public final HashSet<String> restricted = new HashSet<>(Collections.singletonList("up")); public final HashSet<String> restricted = new HashSet<>(Collections.singletonList("up"));
public final HashSet<String> other = new HashSet<>(Arrays.asList("undo", "redo")); public final HashSet<String> other = new HashSet<>(Arrays.asList("undo", "redo"));
public boolean checkCommand(final List<String> list, final String cmd) { public String reduceCmd(String cmd, boolean single) {
for (final String identifier : list) {
if (("/" + identifier).equals(cmd) || ("//" + identifier).equals(cmd) || ("/worldedit:/" + identifier).equals(cmd) || ("/worldedit:" + identifier).equals(cmd)) {
return true;
}
}
return false;
}
public String reduceCmd(final String cmd, final boolean single) {
if (cmd.startsWith("/worldedit:/")) { if (cmd.startsWith("/worldedit:/")) {
return cmd.substring(12); return cmd.substring(12);
} }
@ -72,24 +62,24 @@ public class WEListener implements Listener {
} }
return cmd; return cmd;
} }
public int getInt(final String s) { public int getInt(String s) {
try { try {
int max = 0; int max = 0;
final String[] split = s.split(","); String[] split = s.split(",");
for (final String rad : split) { for (String rad : split) {
final int val = Integer.parseInt(rad); int val = Integer.parseInt(rad);
if (val > max) { if (val > max) {
max = val; max = val;
} }
} }
return max; return max;
} catch (final NumberFormatException e) { } catch (NumberFormatException e) {
return 0; return 0;
} }
} }
public boolean checkVolume(final PlotPlayer player, final long volume, final long max, final Cancellable e) { public boolean checkVolume(PlotPlayer player, long volume, long max, Cancellable e) {
if (volume > max) { if (volume > max) {
MainUtil.sendMessage(player, C.WORLDEDIT_VOLUME.s().replaceAll("%current%", volume + "").replaceAll("%max%", max + "")); MainUtil.sendMessage(player, C.WORLDEDIT_VOLUME.s().replaceAll("%current%", volume + "").replaceAll("%max%", max + ""));
e.setCancelled(true); e.setCancelled(true);
@ -99,16 +89,16 @@ public class WEListener implements Listener {
} }
return true; return true;
} }
public boolean checkSelection(final Player p, final PlotPlayer pp, final int modifier, final long max, final Cancellable e) { public boolean checkSelection(Player p, PlotPlayer pp, int modifier, long max, Cancellable e) {
final Selection selection = BukkitMain.worldEdit.getSelection(p); Selection selection = BukkitMain.worldEdit.getSelection(p);
if (selection == null) { if (selection == null) {
return true; return true;
} }
final BlockVector pos1 = selection.getNativeMinimumPoint().toBlockVector(); BlockVector pos1 = selection.getNativeMinimumPoint().toBlockVector();
final BlockVector pos2 = selection.getNativeMaximumPoint().toBlockVector(); BlockVector pos2 = selection.getNativeMaximumPoint().toBlockVector();
final HashSet<RegionWrapper> mask = WEManager.getMask(pp); HashSet<RegionWrapper> mask = WEManager.getMask(pp);
final RegionWrapper region = new RegionWrapper(pos1.getBlockX(), pos2.getBlockX(), pos1.getBlockZ(), pos2.getBlockZ()); RegionWrapper region = new RegionWrapper(pos1.getBlockX(), pos2.getBlockX(), pos1.getBlockZ(), pos2.getBlockZ());
if (Settings.REQUIRE_SELECTION) { if (Settings.REQUIRE_SELECTION) {
String arg = null; String arg = null;
if (!WEManager.regionContains(region, mask)) { if (!WEManager.regionContains(region, mask)) {
@ -135,15 +125,16 @@ public class WEListener implements Listener {
return true; return true;
} }
} }
final long volume = Math.abs((pos1.getBlockX() - pos2.getBlockX()) * (pos1.getBlockY() - pos2.getBlockY()) * (pos1.getBlockZ() - pos2.getBlockZ())) * modifier; long volume = Math.abs((pos1.getBlockX() - pos2.getBlockX()) * (pos1.getBlockY() - pos2.getBlockY()) * (pos1.getBlockZ() - pos2.getBlockZ()))
* modifier;
return checkVolume(pp, volume, max, e); return checkVolume(pp, volume, max, e);
} }
public boolean delay(final Player player, final String command, final boolean delayed) { public boolean delay(final Player player, final String command, boolean delayed) {
if (!Settings.QUEUE_COMMANDS || !Settings.EXPERIMENTAL_FAST_ASYNC_WORLDEDIT) { if (!Settings.QUEUE_COMMANDS || !Settings.EXPERIMENTAL_FAST_ASYNC_WORLDEDIT) {
return false; return false;
} }
final boolean free = SetQueue.IMP.addTask(null); boolean free = SetQueue.IMP.addTask(null);
if (free) { if (free) {
if (delayed) { if (delayed) {
MainUtil.sendMessage(BukkitUtil.getPlayer(player), C.WORLDEDIT_RUN, command); MainUtil.sendMessage(BukkitUtil.getPlayer(player), C.WORLDEDIT_RUN, command);
@ -164,84 +155,85 @@ public class WEListener implements Listener {
} }
return true; return true;
} }
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public boolean onPlayerCommand(final PlayerCommandPreprocessEvent e) { public boolean onPlayerCommand(PlayerCommandPreprocessEvent e) {
final WorldEditPlugin worldedit = BukkitMain.worldEdit; WorldEditPlugin worldedit = BukkitMain.worldEdit;
if (worldedit == null) { if (worldedit == null) {
HandlerList.unregisterAll(this); HandlerList.unregisterAll(this);
return true; return true;
} }
final Player p = e.getPlayer(); Player p = e.getPlayer();
final PlotPlayer pp = BukkitUtil.getPlayer(p); PlotPlayer pp = BukkitUtil.getPlayer(p);
if (!PS.get().hasPlotArea(p.getWorld().getName())) { if (!PS.get().hasPlotArea(p.getWorld().getName())) {
return true; return true;
} }
final String message = e.getMessage(); String message = e.getMessage();
final String cmd = message.toLowerCase(); String cmd = message.toLowerCase();
final boolean single = true; String[] split = cmd.split(" ");
final String[] split = cmd.split(" ");
long maxVolume = Settings.WE_MAX_VOLUME;
final long maxVolume = Settings.WE_MAX_VOLUME; long maxIterations = Settings.WE_MAX_ITERATIONS;
final long maxIterations = Settings.WE_MAX_ITERATIONS;
if (pp.getAttribute("worldedit")) { if (pp.getAttribute("worldedit")) {
return true; return true;
} }
boolean single = true;
if (split.length >= 2) { if (split.length >= 2) {
final String reduced = reduceCmd(split[0], single); String reduced = reduceCmd(split[0], single);
final String reduced2 = reduceCmd(split[0] + " " + split[1], single); String reduced2 = reduceCmd(split[0] + " " + split[1], single);
if (rad1.contains(reduced)) { if (this.rad1.contains(reduced)) {
if (delay(p, message, false)) { if (delay(p, message, false)) {
e.setCancelled(true); e.setCancelled(true);
return true; return true;
} }
final long volume = getInt(split[1]) * 256; long volume = getInt(split[1]) * 256;
return checkVolume(pp, volume, maxVolume, e); return checkVolume(pp, volume, maxVolume, e);
} }
if (rad2.contains(reduced)) { if (this.rad2.contains(reduced)) {
if (delay(p, message, false)) { if (delay(p, message, false)) {
e.setCancelled(true); e.setCancelled(true);
return true; return true;
} }
if (split.length >= 3) { if (split.length >= 3) {
final long volume = getInt(split[2]) * 256; long volume = getInt(split[2]) * 256;
return checkVolume(pp, volume, maxVolume, e); return checkVolume(pp, volume, maxVolume, e);
} }
return true; return true;
} }
if (rad2_1.contains(reduced)) { if (this.rad2_1.contains(reduced)) {
if (delay(p, message, false)) { if (delay(p, message, false)) {
e.setCancelled(true); e.setCancelled(true);
return true; return true;
} }
if (split.length >= 4) { if (split.length >= 4) {
final long volume = getInt(split[2]) * getInt(split[3]); long volume = getInt(split[2]) * getInt(split[3]);
return checkVolume(pp, volume, maxVolume, e); return checkVolume(pp, volume, maxVolume, e);
} }
return true; return true;
} }
if (rad2_2.contains(reduced)) { if (this.rad2_2.contains(reduced)) {
if (delay(p, message, false)) { if (delay(p, message, false)) {
e.setCancelled(true); e.setCancelled(true);
return true; return true;
} }
if (split.length >= 3) { if (split.length >= 3) {
final long radius = getInt(split[2]); long radius = getInt(split[2]);
final long volume = radius * radius; long volume = radius * radius;
return checkVolume(pp, volume, maxVolume, e); return checkVolume(pp, volume, maxVolume, e);
} }
return true; return true;
} }
if (rad2_3.contains(reduced2)) { if (this.rad2_3.contains(reduced2)) {
if (delay(p, message, false)) { if (delay(p, message, false)) {
e.setCancelled(true); e.setCancelled(true);
return true; return true;
} }
if (split.length >= 3) { if (split.length >= 3) {
if (split.length == 4) { if (split.length == 4) {
final int iterations = getInt(split[3]); int iterations = getInt(split[3]);
if (iterations > maxIterations) { if (iterations > maxIterations) {
MainUtil.sendMessage(pp, C.WORLDEDIT_ITERATIONS.s().replaceAll("%current%", iterations + "").replaceAll("%max%", maxIterations + "")); MainUtil.sendMessage(pp,
C.WORLDEDIT_ITERATIONS.s().replaceAll("%current%", iterations + "").replaceAll("%max%", maxIterations + ""));
e.setCancelled(true); e.setCancelled(true);
if (Permissions.hasPermission(pp, "plots.worldedit.bypass")) { if (Permissions.hasPermission(pp, "plots.worldedit.bypass")) {
MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASS); MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASS);
@ -249,13 +241,13 @@ public class WEListener implements Listener {
return true; return true;
} }
} }
final long radius = getInt(split[2]); long radius = getInt(split[2]);
final long volume = radius * radius; long volume = radius * radius;
return checkVolume(pp, volume, maxVolume, e); return checkVolume(pp, volume, maxVolume, e);
} }
return true; return true;
} }
if (rad3_1.contains(reduced2)) { if (this.rad3_1.contains(reduced2)) {
if (delay(p, message, false)) { if (delay(p, message, false)) {
e.setCancelled(true); e.setCancelled(true);
return true; return true;
@ -265,13 +257,13 @@ public class WEListener implements Listener {
if (split[i].equalsIgnoreCase("-h")) { if (split[i].equalsIgnoreCase("-h")) {
i = 3; i = 3;
} }
final long radius = getInt(split[i]); long radius = getInt(split[i]);
final long volume = radius * radius; long volume = radius * radius;
return checkVolume(pp, volume, maxVolume, e); return checkVolume(pp, volume, maxVolume, e);
} }
return true; return true;
} }
if (rad3_2.contains(reduced2)) { if (this.rad3_2.contains(reduced2)) {
if (delay(p, message, false)) { if (delay(p, message, false)) {
e.setCancelled(true); e.setCancelled(true);
return true; return true;
@ -281,13 +273,13 @@ public class WEListener implements Listener {
if (split[i].equalsIgnoreCase("-h")) { if (split[i].equalsIgnoreCase("-h")) {
i = 4; i = 4;
} }
final long radius = getInt(split[i]); long radius = getInt(split[i]);
final long volume = radius * radius; long volume = radius * radius;
return checkVolume(pp, volume, maxVolume, e); return checkVolume(pp, volume, maxVolume, e);
} }
return true; return true;
} }
if (regionExtend.contains(reduced)) { if (this.regionExtend.contains(reduced)) {
if (delay(p, message, false)) { if (delay(p, message, false)) {
e.setCancelled(true); e.setCancelled(true);
return true; return true;
@ -295,7 +287,7 @@ public class WEListener implements Listener {
return checkSelection(p, pp, getInt(split[1]), maxVolume, e); return checkSelection(p, pp, getInt(split[1]), maxVolume, e);
} }
} }
final String reduced = reduceCmd(split[0], single); String reduced = reduceCmd(split[0], single);
if (Settings.WE_BLACKLIST.contains(reduced)) { if (Settings.WE_BLACKLIST.contains(reduced)) {
MainUtil.sendMessage(pp, C.WORLDEDIT_UNSAFE); MainUtil.sendMessage(pp, C.WORLDEDIT_UNSAFE);
e.setCancelled(true); e.setCancelled(true);
@ -303,8 +295,8 @@ public class WEListener implements Listener {
MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASS); MainUtil.sendMessage(pp, C.WORLDEDIT_BYPASS);
} }
} }
if (restricted.contains(reduced)) { if (this.restricted.contains(reduced)) {
final Plot plot = pp.getCurrentPlot(); Plot plot = pp.getCurrentPlot();
if ((plot != null) && plot.isAdded(pp.getUUID())) { if ((plot != null) && plot.isAdded(pp.getUUID())) {
if (delay(p, message, false)) { if (delay(p, message, false)) {
e.setCancelled(true); e.setCancelled(true);
@ -319,14 +311,14 @@ public class WEListener implements Listener {
} }
return true; return true;
} }
if (region.contains(reduced)) { if (this.region.contains(reduced)) {
if (delay(p, message, false)) { if (delay(p, message, false)) {
e.setCancelled(true); e.setCancelled(true);
return true; return true;
} }
return checkSelection(p, pp, 1, maxVolume, e); return checkSelection(p, pp, 1, maxVolume, e);
} }
if (other.contains(reduced)) { if (this.other.contains(reduced)) {
if (delay(p, message, false)) { if (delay(p, message, false)) {
e.setCancelled(true); e.setCancelled(true);
return true; return true;

View File

@ -1,40 +1,39 @@
package com.plotsquared.bukkit.object; package com.plotsquared.bukkit.object;
import org.bukkit.block.Block;
import com.intellectualcrafters.plot.object.LazyBlock; import com.intellectualcrafters.plot.object.LazyBlock;
import com.intellectualcrafters.plot.object.PlotBlock; import com.intellectualcrafters.plot.object.PlotBlock;
import org.bukkit.block.Block;
public class BukkitLazyBlock extends LazyBlock { public class BukkitLazyBlock extends LazyBlock {
private int id; private int id;
private Block block; private Block block;
private PlotBlock pb; private PlotBlock pb;
public BukkitLazyBlock(final int id, final Block block) { public BukkitLazyBlock(int id, Block block) {
this.id = id; this.id = id;
this.block = block; this.block = block;
} }
public BukkitLazyBlock(final PlotBlock pb) { public BukkitLazyBlock(PlotBlock pb) {
id = pb.id; this.id = pb.id;
this.pb = pb; this.pb = pb;
} }
public BukkitLazyBlock(final Block block) { public BukkitLazyBlock(Block block) {
this.block = block; this.block = block;
} }
@Override @Override
public PlotBlock getPlotBlock() { public PlotBlock getPlotBlock() {
if (pb != null) { if (this.pb != null) {
return pb; return this.pb;
} }
if (id == 0) { if (this.id == 0) {
id = block.getTypeId(); this.id = this.block.getTypeId();
} }
byte data; byte data;
switch (id) { switch (this.id) {
case 0: case 0:
case 2: case 2:
case 4: case 4:
@ -120,20 +119,20 @@ public class BukkitLazyBlock extends LazyBlock {
data = 0; data = 0;
break; break;
default: default:
data = block.getData(); data = this.block.getData();
break; break;
} }
pb = new PlotBlock((short) id, data); this.pb = new PlotBlock((short) this.id, data);
return pb; return this.pb;
} }
@Override @Override
public int getId() { public int getId() {
if (id == 0) { if (this.id == 0) {
id = block.getTypeId(); this.id = this.block.getTypeId();
} }
return id; return this.id;
} }
} }

View File

@ -1,40 +1,41 @@
package com.plotsquared.bukkit.object; package com.plotsquared.bukkit.object;
import com.intellectualcrafters.plot.object.OfflinePlotPlayer;
import org.bukkit.OfflinePlayer;
import java.util.UUID; import java.util.UUID;
import org.bukkit.OfflinePlayer;
import com.intellectualcrafters.plot.object.OfflinePlotPlayer;
public class BukkitOfflinePlayer implements OfflinePlotPlayer { public class BukkitOfflinePlayer implements OfflinePlotPlayer {
public final OfflinePlayer player; public final OfflinePlayer player;
/** /**
* 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.</p>
*
* @param player * @param player
*/ */
public BukkitOfflinePlayer(final OfflinePlayer player) { public BukkitOfflinePlayer(OfflinePlayer player) {
this.player = player; this.player = player;
} }
@Override @Override
public UUID getUUID() { public UUID getUUID() {
return player.getUniqueId(); return this.player.getUniqueId();
} }
@Override @Override
public long getLastPlayed() { public long getLastPlayed() {
return player.getLastPlayed(); return this.player.getLastPlayed();
} }
@Override @Override
public boolean isOnline() { public boolean isOnline() {
return player.isOnline(); return this.player.isOnline();
} }
@Override @Override
public String getName() { public String getName() {
return player.getName(); return this.player.getName();
} }
} }

View File

@ -0,0 +1,201 @@
package com.plotsquared.bukkit.object;
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.UUIDHandler;
import com.plotsquared.bukkit.util.BukkitUtil;
import org.bukkit.Effect;
import org.bukkit.GameMode;
import org.bukkit.WeatherType;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import java.util.UUID;
public class BukkitPlayer extends PlotPlayer {
public final Player player;
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>
* @param player
*/
public BukkitPlayer(Player player) {
this.player = player;
super.populatePersistentMetaMap();
}
public BukkitPlayer(Player player, boolean offline) {
this.player = player;
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();
return location == null ? BukkitUtil.getLocation(this.player) : location;
}
@Override
public UUID getUUID() {
if (this.uuid == null) {
this.uuid = UUIDHandler.getUUID(this);
}
return this.uuid;
}
@Override
public boolean hasPermission(String permission) {
if (this.offline && EconHandler.manager != null) {
return EconHandler.manager.hasPermission(getName(), permission);
}
return this.player.hasPermission(permission);
}
@Override
public void sendMessage(String message) {
this.player.sendMessage(message);
}
@Override
public void teleport(Location location) {
if (Math.abs(location.getX()) >= 30000000 || Math.abs(location.getZ()) >= 30000000) {
return;
}
this.player.teleport(
new org.bukkit.Location(BukkitUtil.getWorld(location.getWorld()), location.getX() + 0.5, location.getY(), location.getZ() + 0.5,
location.getYaw(), location.getPitch()), TeleportCause.COMMAND);
}
@Override
public String getName() {
if (this.name == null) {
this.name = this.player.getName();
}
return this.name;
}
@Override
public boolean isOnline() {
return !this.offline && this.player.isOnline();
}
@Override
public void setCompassTarget(Location location) {
this.player.setCompassTarget(
new org.bukkit.Location(BukkitUtil.getWorld(location.getWorld()), location.getX(), location.getY(), location.getZ()));
}
@Override
public Location getLocationFull() {
return BukkitUtil.getLocationFull(this.player);
}
@Override
public void setWeather(PlotWeather weather) {
switch (weather) {
case CLEAR:
this.player.setPlayerWeather(WeatherType.CLEAR);
break;
case RAIN:
this.player.setPlayerWeather(WeatherType.DOWNFALL);
break;
case RESET:
this.player.resetPlayerWeather();
break;
default:
this.player.resetPlayerWeather();
break;
}
}
@Override
public PlotGameMode getGameMode() {
switch (this.player.getGameMode()) {
case ADVENTURE:
return PlotGameMode.ADVENTURE;
case CREATIVE:
return PlotGameMode.CREATIVE;
case SPECTATOR:
return PlotGameMode.SPECTATOR;
case SURVIVAL:
return PlotGameMode.SURVIVAL;
default:
return PlotGameMode.NOT_SET;
}
}
@Override
public void setGameMode(PlotGameMode gameMode) {
switch (gameMode) {
case ADVENTURE:
this.player.setGameMode(GameMode.ADVENTURE);
break;
case CREATIVE:
this.player.setGameMode(GameMode.CREATIVE);
break;
case SPECTATOR:
this.player.setGameMode(GameMode.SPECTATOR);
break;
case SURVIVAL:
this.player.setGameMode(GameMode.SURVIVAL);
break;
default:
this.player.setGameMode(GameMode.SURVIVAL);
break;
}
}
@Override
public void setTime(long time) {
if (time != Long.MAX_VALUE) {
this.player.setPlayerTime(time, false);
} else {
this.player.resetPlayerTime();
}
}
@Override
public void setFlight(boolean fly) {
this.player.setAllowFlight(fly);
}
@Override
public void playMusic(Location location, int id) {
this.player.playEffect(BukkitUtil.getLocation(location), Effect.RECORD_PLAY, id);
}
@Override
public void kick(String message) {
this.player.kickPlayer(message);
}
@Override public void stopSpectating() {
if (getGameMode() == PlotGameMode.SPECTATOR) {
this.player.setSpectatorTarget(null);
}
}
@Override
public boolean isBanned() {
return this.player.isBanned();
}
}

View File

@ -0,0 +1,16 @@
package com.plotsquared.bukkit.object.entity;
public 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;
}

View File

@ -34,6 +34,7 @@ import org.bukkit.util.Vector;
public class EntityWrapper { public class EntityWrapper {
private final int hash;
public EntityType type; public EntityType type;
public float yaw; public float yaw;
public float pitch; public float pitch;
@ -54,34 +55,32 @@ public class EntityWrapper {
private HorseStats horse; private HorseStats horse;
private ArmorStandStats stand; private ArmorStandStats stand;
private int hash;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public EntityWrapper(final org.bukkit.entity.Entity entity, final short depth) { public EntityWrapper(Entity entity, short depth) {
hash = entity.getEntityId(); this.hash = entity.getEntityId();
this.depth = depth; this.depth = depth;
final Location loc = entity.getLocation(); Location loc = entity.getLocation();
yaw = loc.getYaw(); this.yaw = loc.getYaw();
pitch = loc.getPitch(); this.pitch = loc.getPitch();
x = loc.getX(); this.x = loc.getX();
y = loc.getY(); this.y = loc.getY();
z = loc.getZ(); this.z = loc.getZ();
type = entity.getType(); this.type = entity.getType();
if (depth == 0) { if (depth == 0) {
return; return;
} }
base = new EntityBaseStats(); this.base = new EntityBaseStats();
final Entity p = entity.getPassenger(); Entity p = entity.getPassenger();
if (p != null) { if (p != null) {
base.passenger = new EntityWrapper(p, depth); this.base.passenger = new EntityWrapper(p, depth);
} }
base.fall = entity.getFallDistance(); this.base.fall = entity.getFallDistance();
base.fire = (short) entity.getFireTicks(); this.base.fire = (short) entity.getFireTicks();
base.age = entity.getTicksLived(); this.base.age = entity.getTicksLived();
final Vector velocity = entity.getVelocity(); Vector velocity = entity.getVelocity();
base.v_x = velocity.getX(); this.base.v_x = velocity.getX();
base.v_y = velocity.getY(); this.base.v_y = velocity.getY();
base.v_z = velocity.getZ(); this.base.v_z = velocity.getZ();
if (depth == 1) { if (depth == 1) {
return; return;
} }
@ -114,58 +113,55 @@ public class EntityWrapper {
case THROWN_EXP_BOTTLE: case THROWN_EXP_BOTTLE:
case WEATHER: case WEATHER:
case WITHER_SKULL: 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 // Do this stuff later
return; return;
} default:
default: {
PS.debug("&cCOULD NOT IDENTIFY ENTITY: " + entity.getType()); PS.debug("&cCOULD NOT IDENTIFY ENTITY: " + entity.getType());
return; return;
}
// MISC // // MISC //
case DROPPED_ITEM: { case DROPPED_ITEM:
final Item item = (Item) entity; Item item = (Item) entity;
stack = item.getItemStack(); this.stack = item.getItemStack();
return; return;
} case ITEM_FRAME:
case ITEM_FRAME: { ItemFrame itemframe = (ItemFrame) entity;
final ItemFrame itemframe = (ItemFrame) entity; this.x = Math.floor(this.x);
x = Math.floor(x); this.y = Math.floor(this.y);
y = Math.floor(y); this.z = Math.floor(this.z);
z = Math.floor(z); this.dataByte = getOrdinal(Rotation.values(), itemframe.getRotation());
dataByte = getOrdinal(Rotation.values(), itemframe.getRotation()); this.stack = itemframe.getItem().clone();
stack = itemframe.getItem().clone();
return; return;
} case PAINTING:
case PAINTING: { Painting painting = (Painting) entity;
final Painting painting = (Painting) entity; this.x = Math.floor(this.x);
x = Math.floor(x); this.y = Math.floor(this.y);
y = Math.floor(y); this.z = Math.floor(this.z);
z = Math.floor(z); Art a = painting.getArt();
final Art a = painting.getArt(); this.dataByte = getOrdinal(BlockFace.values(), painting.getFacing());
dataByte = getOrdinal(BlockFace.values(), painting.getFacing()); int h = a.getBlockHeight();
final int h = a.getBlockHeight(); if (h % 2 == 0) {
if ((h % 2) == 0) { this.y -= 1;
y -= 1;
} }
dataString = a.name(); this.dataString = a.name();
return; return;
}
// END MISC // // END MISC //
// INVENTORY HOLDER // // INVENTORY HOLDER //
case MINECART_CHEST: { case MINECART_CHEST:
case MINECART_HOPPER:
storeInventory((InventoryHolder) entity); storeInventory((InventoryHolder) entity);
return; return;
}
case MINECART_HOPPER: {
storeInventory((InventoryHolder) entity);
return;
}
// START LIVING ENTITY // // START LIVING ENTITY //
// START AGEABLE // // START AGEABLE //
// START TAMEABLE // // START TAMEABLE //
case HORSE: { case HORSE:
final Horse horse = (Horse) entity; Horse horse = (Horse) entity;
this.horse = new HorseStats(); this.horse = new HorseStats();
this.horse.jump = horse.getJumpStrength(); this.horse.jump = horse.getJumpStrength();
this.horse.chest = horse.isCarryingChest(); this.horse.chest = horse.isCarryingChest();
@ -177,83 +173,77 @@ public class EntityWrapper {
storeLiving((LivingEntity) entity); storeLiving((LivingEntity) entity);
storeInventory((InventoryHolder) entity); storeInventory((InventoryHolder) entity);
return; return;
}
// END INVENTORY HOLDER // // END INVENTORY HOLDER //
case WOLF: case WOLF:
case OCELOT: { case OCELOT:
storeTameable((Tameable) entity); storeTameable((Tameable) entity);
storeAgeable((Ageable) entity); storeAgeable((Ageable) entity);
storeLiving((LivingEntity) entity); storeLiving((LivingEntity) entity);
return; return;
} // END TAMEABLE //
// END AMEABLE // case SHEEP:
case SHEEP: { Sheep sheep = (Sheep) entity;
final Sheep sheep = (Sheep) entity; this.dataByte = (byte) (sheep.isSheared() ? 1 : 0);
dataByte = (byte) ((sheep).isSheared() ? 1 : 0); this.dataByte2 = sheep.getColor().getDyeData();
dataByte2 = sheep.getColor().getDyeData();
storeAgeable((Ageable) entity); storeAgeable((Ageable) entity);
storeLiving((LivingEntity) entity); storeLiving((LivingEntity) entity);
return; return;
}
case VILLAGER: case VILLAGER:
case CHICKEN: case CHICKEN:
case COW: case COW:
case MUSHROOM_COW: case MUSHROOM_COW:
case PIG: { case PIG:
storeAgeable((Ageable) entity);
storeLiving((LivingEntity) entity);
return;
case RABBIT: // NEW
this.dataByte = getOrdinal(Type.values(), ((Rabbit) entity).getRabbitType());
storeAgeable((Ageable) entity); storeAgeable((Ageable) entity);
storeLiving((LivingEntity) entity); storeLiving((LivingEntity) entity);
return; return;
}
// END AGEABLE // // END AGEABLE //
case RABBIT: { // NEW case GUARDIAN: // NEW
dataByte = getOrdinal(Type.values(), ((Rabbit) entity).getRabbitType()); this.dataByte = (byte) (((Guardian) entity).isElder() ? 1 : 0);
storeAgeable((Ageable) entity);
storeLiving((LivingEntity) entity); storeLiving((LivingEntity) entity);
return; return;
} case SKELETON: // NEW
case GUARDIAN: { // NEW this.dataByte = (byte) ((Skeleton) entity).getSkeletonType().getId();
dataByte = (byte) (((Guardian) entity).isElder() ? 1 : 0);
storeLiving((LivingEntity) entity); storeLiving((LivingEntity) entity);
return; return;
} case ARMOR_STAND: // NEW
case SKELETON: { // NEW // CHECK positions
dataByte = (byte) ((Skeleton) entity).getSkeletonType().getId(); ArmorStand stand = (ArmorStand) entity;
storeLiving((LivingEntity) entity); this.inventory = new ItemStack[]{stand.getItemInHand().clone(), stand.getHelmet().clone(), stand.getChestplate().clone(),
return; stand.getLeggings().clone(), stand.getBoots().clone()};
}
case ARMOR_STAND: { // NEW
// CHECK positions
final ArmorStand stand = (ArmorStand) entity;
inventory = new ItemStack[] { stand.getItemInHand().clone(), stand.getHelmet().clone(), stand.getChestplate().clone(), stand.getLeggings().clone(), stand.getBoots().clone() };
storeLiving((LivingEntity) entity); storeLiving((LivingEntity) entity);
this.stand = new ArmorStandStats(); this.stand = new ArmorStandStats();
final EulerAngle head = stand.getHeadPose(); EulerAngle head = stand.getHeadPose();
this.stand.head[0] = (float) head.getX(); this.stand.head[0] = (float) head.getX();
this.stand.head[1] = (float) head.getY(); this.stand.head[1] = (float) head.getY();
this.stand.head[2] = (float) head.getZ(); this.stand.head[2] = (float) head.getZ();
final EulerAngle body = stand.getBodyPose(); EulerAngle body = stand.getBodyPose();
this.stand.body[0] = (float) body.getX(); this.stand.body[0] = (float) body.getX();
this.stand.body[1] = (float) body.getY(); this.stand.body[1] = (float) body.getY();
this.stand.body[2] = (float) body.getZ(); this.stand.body[2] = (float) body.getZ();
final EulerAngle leftLeg = stand.getLeftLegPose(); EulerAngle leftLeg = stand.getLeftLegPose();
this.stand.leftLeg[0] = (float) leftLeg.getX(); this.stand.leftLeg[0] = (float) leftLeg.getX();
this.stand.leftLeg[1] = (float) leftLeg.getY(); this.stand.leftLeg[1] = (float) leftLeg.getY();
this.stand.leftLeg[2] = (float) leftLeg.getZ(); this.stand.leftLeg[2] = (float) leftLeg.getZ();
final EulerAngle rightLeg = stand.getRightLegPose(); EulerAngle rightLeg = stand.getRightLegPose();
this.stand.rightLeg[0] = (float) rightLeg.getX(); this.stand.rightLeg[0] = (float) rightLeg.getX();
this.stand.rightLeg[1] = (float) rightLeg.getY(); this.stand.rightLeg[1] = (float) rightLeg.getY();
this.stand.rightLeg[2] = (float) rightLeg.getZ(); this.stand.rightLeg[2] = (float) rightLeg.getZ();
final EulerAngle leftArm = stand.getLeftArmPose(); EulerAngle leftArm = stand.getLeftArmPose();
this.stand.leftArm[0] = (float) leftArm.getX(); this.stand.leftArm[0] = (float) leftArm.getX();
this.stand.leftArm[1] = (float) leftArm.getY(); this.stand.leftArm[1] = (float) leftArm.getY();
this.stand.leftArm[2] = (float) leftArm.getZ(); this.stand.leftArm[2] = (float) leftArm.getZ();
final EulerAngle rightArm = stand.getRightArmPose(); EulerAngle rightArm = stand.getRightArmPose();
this.stand.rightArm[0] = (float) rightArm.getX(); this.stand.rightArm[0] = (float) rightArm.getX();
this.stand.rightArm[1] = (float) rightArm.getY(); this.stand.rightArm[1] = (float) rightArm.getY();
this.stand.rightArm[2] = (float) rightArm.getZ(); this.stand.rightArm[2] = (float) rightArm.getZ();
@ -274,7 +264,6 @@ public class EntityWrapper {
this.stand.small = true; this.stand.small = true;
} }
return; return;
}
case ENDERMITE: // NEW case ENDERMITE: // NEW
case BAT: case BAT:
case ENDER_DRAGON: case ENDER_DRAGON:
@ -292,49 +281,48 @@ public class EntityWrapper {
case ENDERMAN: case ENDERMAN:
case CREEPER: case CREEPER:
case BLAZE: case BLAZE:
case SHULKER:
case SNOWMAN: case SNOWMAN:
case IRON_GOLEM: { case IRON_GOLEM:
storeLiving((LivingEntity) entity); storeLiving((LivingEntity) entity);
return; // END LIVING //
}
// END LIVING //
} }
} }
@Override @Override
public boolean equals(final Object obj) { public boolean equals(Object obj) {
return hash == obj.hashCode(); return this.hash == obj.hashCode();
} }
@Override @Override
public int hashCode() { public int hashCode() {
return hash; return this.hash;
} }
public void storeInventory(final InventoryHolder held) { public void storeInventory(InventoryHolder held) {
inventory = held.getInventory().getContents().clone(); this.inventory = held.getInventory().getContents().clone();
} }
private void restoreLiving(final LivingEntity entity) { private void restoreLiving(LivingEntity entity) {
entity.setCanPickupItems(lived.loot); entity.setCanPickupItems(this.lived.loot);
if (lived.name != null) { if (this.lived.name != null) {
entity.setCustomName(lived.name); entity.setCustomName(this.lived.name);
entity.setCustomNameVisible(lived.visible); entity.setCustomNameVisible(this.lived.visible);
} }
if ((lived.potions != null) && (!lived.potions.isEmpty())) { if (this.lived.potions != null && !this.lived.potions.isEmpty()) {
entity.addPotionEffects(lived.potions); entity.addPotionEffects(this.lived.potions);
} }
entity.setRemainingAir(lived.air); entity.setRemainingAir(this.lived.air);
entity.setRemoveWhenFarAway(lived.persistent); entity.setRemoveWhenFarAway(this.lived.persistent);
if (lived.equipped) { if (this.lived.equipped) {
final EntityEquipment equipment = entity.getEquipment(); EntityEquipment equipment = entity.getEquipment();
equipment.setItemInHand(lived.hands); equipment.setItemInHand(this.lived.hands);
equipment.setHelmet(lived.helmet); equipment.setHelmet(this.lived.helmet);
equipment.setChestplate(lived.chestplate); equipment.setChestplate(this.lived.chestplate);
equipment.setLeggings(lived.leggings); equipment.setLeggings(this.lived.leggings);
equipment.setBoots(lived.boots); equipment.setBoots(this.lived.boots);
} }
if (lived.leashed) { if (this.lived.leashed) {
// TODO leashes // TODO leashes
// World world = entity.getWorld(); // World world = entity.getWorld();
// Entity leash = world.spawnEntity(new Location(world, Math.floor(x) + lived.leash_x, Math.floor(y) + lived.leash_y, Math // Entity leash = world.spawnEntity(new Location(world, Math.floor(x) + lived.leash_x, Math.floor(y) + lived.leash_y, Math
@ -343,11 +331,11 @@ public class EntityWrapper {
} }
} }
private void restoreInventory(final InventoryHolder entity) { private void restoreInventory(InventoryHolder entity) {
entity.getInventory().setContents(inventory); entity.getInventory().setContents(this.inventory);
} }
public void storeLiving(final LivingEntity lived) { public void storeLiving(LivingEntity lived) {
this.lived = new LivingEntityStats(); this.lived = new LivingEntityStats();
this.lived.potions = lived.getActivePotionEffects(); this.lived.potions = lived.getActivePotionEffects();
this.lived.loot = lived.getCanPickupItems(); this.lived.loot = lived.getCanPickupItems();
@ -358,12 +346,12 @@ public class EntityWrapper {
this.lived.persistent = lived.getRemoveWhenFarAway(); this.lived.persistent = lived.getRemoveWhenFarAway();
this.lived.leashed = lived.isLeashed(); this.lived.leashed = lived.isLeashed();
if (this.lived.leashed) { if (this.lived.leashed) {
final Location loc = lived.getLeashHolder().getLocation(); Location loc = lived.getLeashHolder().getLocation();
this.lived.leash_x = (short) (x - loc.getBlockX()); this.lived.leash_x = (short) (this.x - loc.getBlockX());
this.lived.leash_y = (short) (y - loc.getBlockY()); this.lived.leash_y = (short) (this.y - loc.getBlockY());
this.lived.leash_z = (short) (z - loc.getBlockZ()); this.lived.leash_z = (short) (this.z - loc.getBlockZ());
} }
final EntityEquipment equipment = lived.getEquipment(); EntityEquipment equipment = lived.getEquipment();
this.lived.equipped = equipment != null; this.lived.equipped = equipment != null;
if (this.lived.equipped) { if (this.lived.equipped) {
this.lived.hands = equipment.getItemInHand().clone(); this.lived.hands = equipment.getItemInHand().clone();
@ -374,86 +362,83 @@ public class EntityWrapper {
} }
} }
private void restoreTameable(final Tameable entity) { private void restoreTameable(Tameable entity) {
if (tamed.tamed) { if (this.tamed.tamed) {
if (tamed.owner != null) { if (this.tamed.owner != null) {
entity.setTamed(true); entity.setTamed(true);
entity.setOwner(tamed.owner); entity.setOwner(this.tamed.owner);
} }
} }
} }
private void restoreAgeable(final Ageable entity) { private void restoreAgeable(Ageable entity) {
if (!aged.adult) { if (!this.aged.adult) {
entity.setBaby(); entity.setBaby();
} }
entity.setAgeLock(aged.locked); entity.setAgeLock(this.aged.locked);
if (aged.age > 0) { if (this.aged.age > 0) {
entity.setAge(aged.age); entity.setAge(this.aged.age);
} }
} }
public void storeAgeable(final Ageable aged) { public void storeAgeable(Ageable aged) {
this.aged = new AgeableStats(); this.aged = new AgeableStats();
this.aged.age = aged.getAge(); this.aged.age = aged.getAge();
this.aged.locked = aged.getAgeLock(); this.aged.locked = aged.getAgeLock();
this.aged.adult = aged.isAdult(); this.aged.adult = aged.isAdult();
} }
public void storeTameable(final Tameable tamed) { public void storeTameable(Tameable tamed) {
this.tamed = new TameableStats(); this.tamed = new TameableStats();
this.tamed.owner = tamed.getOwner(); this.tamed.owner = tamed.getOwner();
this.tamed.tamed = tamed.isTamed(); this.tamed.tamed = tamed.isTamed();
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public Entity spawn(final World world, final int x_offset, final int z_offset) { public Entity spawn(World world, int x_offset, int z_offset) {
final Location loc = new Location(world, x + x_offset, y, z + z_offset); Location loc = new Location(world, this.x + x_offset, this.y, this.z + z_offset);
loc.setYaw(yaw); loc.setYaw(this.yaw);
loc.setPitch(pitch); loc.setPitch(this.pitch);
if (type.isSpawnable()) { if (!this.type.isSpawnable()) {
return null; return null;
} }
Entity entity; Entity entity;
switch (type) { switch (this.type) {
case DROPPED_ITEM: { case DROPPED_ITEM:
return world.dropItem(loc, stack); return world.dropItem(loc, this.stack);
}
case PLAYER: case PLAYER:
case LEASH_HITCH: { case LEASH_HITCH:
return null; return null;
} case ITEM_FRAME:
case ITEM_FRAME: {
entity = world.spawn(loc, ItemFrame.class); entity = world.spawn(loc, ItemFrame.class);
break; break;
} case PAINTING:
case PAINTING: {
entity = world.spawn(loc, Painting.class); entity = world.spawn(loc, Painting.class);
break; break;
}
default: default:
entity = world.spawnEntity(loc, type); entity = world.spawnEntity(loc, this.type);
break; break;
} }
if (depth == 0) { if (this.depth == 0) {
return entity; return entity;
} }
if (base.passenger != null) { if (this.base.passenger != null) {
try { try {
entity.setPassenger(base.passenger.spawn(world, x_offset, z_offset)); entity.setPassenger(this.base.passenger.spawn(world, x_offset, z_offset));
} catch (final Exception e) {} } catch (Exception e) {
}
} }
if (base.fall != 0) { if (this.base.fall != 0) {
entity.setFallDistance(base.fall); entity.setFallDistance(this.base.fall);
} }
if (base.fire != 0) { if (this.base.fire != 0) {
entity.setFireTicks(base.fire); entity.setFireTicks(this.base.fire);
} }
if (base.age != 0) { if (this.base.age != 0) {
entity.setTicksLived(base.age); entity.setTicksLived(this.base.age);
} }
entity.setVelocity(new Vector(base.v_x, base.v_y, base.v_z)); entity.setVelocity(new Vector(this.base.v_x, this.base.v_y, this.base.v_z));
if (depth == 1) { if (this.depth == 1) {
return entity; return entity;
} }
switch (entity.getType()) { switch (entity.getType()) {
@ -485,42 +470,34 @@ public class EntityWrapper {
case WEATHER: case WEATHER:
case WITHER_SKULL: case WITHER_SKULL:
case MINECART_FURNACE: case MINECART_FURNACE:
case UNKNOWN: { case UNKNOWN:
// Do this stuff later // Do this stuff later
return entity; return entity;
} default:
default: {
PS.debug("&cCOULD NOT IDENTIFY ENTITY: " + entity.getType()); PS.debug("&cCOULD NOT IDENTIFY ENTITY: " + entity.getType());
return entity; return entity;
}
// MISC // // MISC //
case ITEM_FRAME: { case ITEM_FRAME:
final ItemFrame itemframe = (ItemFrame) entity; ItemFrame itemframe = (ItemFrame) entity;
itemframe.setRotation(Rotation.values()[dataByte]); itemframe.setRotation(Rotation.values()[this.dataByte]);
itemframe.setItem(stack); itemframe.setItem(this.stack);
return entity; return entity;
} case PAINTING:
case PAINTING: { Painting painting = (Painting) entity;
final Painting painting = (Painting) entity; painting.setFacingDirection(BlockFace.values()[this.dataByte], true);
painting.setFacingDirection(BlockFace.values()[dataByte], true); painting.setArt(Art.getByName(this.dataString), true);
painting.setArt(Art.getByName(dataString), true);
return entity; return entity;
}
// END MISC // // END MISC //
// INVENTORY HOLDER // // INVENTORY HOLDER //
case MINECART_CHEST: { case MINECART_CHEST:
case MINECART_HOPPER:
restoreInventory((InventoryHolder) entity); restoreInventory((InventoryHolder) entity);
return entity; return entity;
}
case MINECART_HOPPER: {
restoreInventory((InventoryHolder) entity);
return entity;
}
// START LIVING ENTITY // // START LIVING ENTITY //
// START AGEABLE // // START AGEABLE //
// START TAMEABLE // // START TAMEABLE //
case HORSE: { case HORSE:
final Horse horse = (Horse) entity; Horse horse = (Horse) entity;
horse.setJumpStrength(this.horse.jump); horse.setJumpStrength(this.horse.jump);
horse.setCarryingChest(this.horse.chest); horse.setCarryingChest(this.horse.chest);
horse.setVariant(Variant.values()[this.horse.variant]); horse.setVariant(Variant.values()[this.horse.variant]);
@ -531,100 +508,93 @@ public class EntityWrapper {
restoreLiving((LivingEntity) entity); restoreLiving((LivingEntity) entity);
restoreInventory((InventoryHolder) entity); restoreInventory((InventoryHolder) entity);
return entity; return entity;
}
// END INVENTORY HOLDER // // END INVENTORY HOLDER //
case WOLF: case WOLF:
case OCELOT: { case OCELOT:
restoreTameable((Tameable) entity); restoreTameable((Tameable) entity);
restoreAgeable((Ageable) entity); restoreAgeable((Ageable) entity);
restoreLiving((LivingEntity) entity); restoreLiving((LivingEntity) entity);
return entity; return entity;
}
// END AGEABLE // // END AGEABLE //
case SHEEP: { case SHEEP:
final Sheep sheep = (Sheep) entity; Sheep sheep = (Sheep) entity;
if (dataByte == 1) { if (this.dataByte == 1) {
sheep.setSheared(true); sheep.setSheared(true);
} }
if (dataByte2 != 0) { if (this.dataByte2 != 0) {
sheep.setColor(DyeColor.getByDyeData(dataByte2)); sheep.setColor(DyeColor.getByDyeData(this.dataByte2));
} }
restoreAgeable((Ageable) entity); restoreAgeable((Ageable) entity);
restoreLiving((LivingEntity) entity); restoreLiving((LivingEntity) entity);
return entity; return entity;
}
case VILLAGER: case VILLAGER:
case CHICKEN: case CHICKEN:
case COW: case COW:
case MUSHROOM_COW: case MUSHROOM_COW:
case PIG: { case PIG:
restoreAgeable((Ageable) entity); restoreAgeable((Ageable) entity);
restoreLiving((LivingEntity) entity); restoreLiving((LivingEntity) entity);
return entity; return entity;
}
// END AGEABLE // // END AGEABLE //
case RABBIT: { // NEW case RABBIT: // NEW
if (dataByte != 0) { if (this.dataByte != 0) {
((Rabbit) entity).setRabbitType(Type.values()[dataByte]); ((Rabbit) entity).setRabbitType(Type.values()[this.dataByte]);
} }
restoreAgeable((Ageable) entity); restoreAgeable((Ageable) entity);
restoreLiving((LivingEntity) entity); restoreLiving((LivingEntity) entity);
return entity; return entity;
} case GUARDIAN: // NEW
case GUARDIAN: { // NEW if (this.dataByte != 0) {
if (dataByte != 0) {
((Guardian) entity).setElder(true); ((Guardian) entity).setElder(true);
} }
restoreLiving((LivingEntity) entity); restoreLiving((LivingEntity) entity);
return entity; return entity;
} case SKELETON: // NEW
case SKELETON: { // NEW if (this.dataByte != 0) {
if (dataByte != 0) { ((Skeleton) entity).setSkeletonType(SkeletonType.values()[this.dataByte]);
((Skeleton) entity).setSkeletonType(SkeletonType.values()[dataByte]);
} }
storeLiving((LivingEntity) entity); storeLiving((LivingEntity) entity);
return entity; return entity;
} case ARMOR_STAND: // NEW
case ARMOR_STAND: { // NEW // CHECK positions
// CHECK positions ArmorStand stand = (ArmorStand) entity;
final ArmorStand stand = (ArmorStand) entity; if (this.inventory[0] != null) {
if (inventory[0] != null) { stand.setItemInHand(this.inventory[0]);
stand.setItemInHand(inventory[0]);
} }
if (inventory[1] != null) { if (this.inventory[1] != null) {
stand.setHelmet(inventory[1]); stand.setHelmet(this.inventory[1]);
} }
if (inventory[2] != null) { if (this.inventory[2] != null) {
stand.setChestplate(inventory[2]); stand.setChestplate(this.inventory[2]);
} }
if (inventory[3] != null) { if (this.inventory[3] != null) {
stand.setLeggings(inventory[3]); stand.setLeggings(this.inventory[3]);
} }
if (inventory[4] != null) { if (this.inventory[4] != null) {
stand.setBoots(inventory[4]); 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) {
final EulerAngle pose = new EulerAngle(this.stand.head[0], this.stand.head[1], this.stand.head[2]); EulerAngle pose = new EulerAngle(this.stand.head[0], this.stand.head[1], this.stand.head[2]);
stand.setHeadPose(pose); 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) {
final EulerAngle pose = new EulerAngle(this.stand.body[0], this.stand.body[1], this.stand.body[2]); EulerAngle pose = new EulerAngle(this.stand.body[0], this.stand.body[1], this.stand.body[2]);
stand.setBodyPose(pose); 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) {
final EulerAngle pose = new EulerAngle(this.stand.leftLeg[0], this.stand.leftLeg[1], this.stand.leftLeg[2]); EulerAngle pose = new EulerAngle(this.stand.leftLeg[0], this.stand.leftLeg[1], this.stand.leftLeg[2]);
stand.setLeftLegPose(pose); 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) {
final EulerAngle pose = new EulerAngle(this.stand.rightLeg[0], this.stand.rightLeg[1], this.stand.rightLeg[2]); EulerAngle pose = new EulerAngle(this.stand.rightLeg[0], this.stand.rightLeg[1], this.stand.rightLeg[2]);
stand.setRightLegPose(pose); 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) {
final EulerAngle pose = new EulerAngle(this.stand.leftArm[0], this.stand.leftArm[1], this.stand.leftArm[2]); EulerAngle pose = new EulerAngle(this.stand.leftArm[0], this.stand.leftArm[1], this.stand.leftArm[2]);
stand.setLeftArmPose(pose); 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) {
final EulerAngle pose = new EulerAngle(this.stand.rightArm[0], this.stand.rightArm[1], this.stand.rightArm[2]); EulerAngle pose = new EulerAngle(this.stand.rightArm[0], this.stand.rightArm[1], this.stand.rightArm[2]);
stand.setRightArmPose(pose); stand.setRightArmPose(pose);
} }
if (this.stand.invisible) { if (this.stand.invisible) {
@ -644,7 +614,6 @@ public class EntityWrapper {
} }
restoreLiving((LivingEntity) entity); restoreLiving((LivingEntity) entity);
return entity; return entity;
}
case ENDERMITE: // NEW case ENDERMITE: // NEW
case BAT: case BAT:
case ENDER_DRAGON: case ENDER_DRAGON:
@ -663,15 +632,14 @@ public class EntityWrapper {
case CREEPER: case CREEPER:
case BLAZE: case BLAZE:
case SNOWMAN: case SNOWMAN:
case IRON_GOLEM: { case IRON_GOLEM:
restoreLiving((LivingEntity) entity); restoreLiving((LivingEntity) entity);
return entity; return entity;
}
// END LIVING // // END LIVING //
} }
} }
private byte getOrdinal(final Object[] list, final Object value) { private byte getOrdinal(Object[] list, Object value) {
for (byte i = 0; i < list.length; i++) { for (byte i = 0; i < list.length; i++) {
if (list[i].equals(value)) { if (list[i].equals(value)) {
return i; return i;

View File

@ -0,0 +1,146 @@
package com.plotsquared.bukkit.object.schematic;
import com.intellectualcrafters.jnbt.ByteTag;
import com.intellectualcrafters.jnbt.CompoundTag;
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.util.MathMan;
import com.plotsquared.bukkit.util.BukkitUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
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;
public class StateWrapper {
public BlockState state = null;
public CompoundTag tag = null;
public StateWrapper(BlockState state) {
this.state = state;
}
public StateWrapper(CompoundTag tag) {
this.tag = tag;
}
public boolean restoreTag(String worldName, int x, int y, int z) {
if (this.tag == null) {
return false;
}
switch (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;
} else {
}
}
}
return false;
}
public CompoundTag getTag() {
if (this.tag != null) {
return this.tag;
}
if (this.state instanceof InventoryHolder) {
InventoryHolder inv = (InventoryHolder) this.state;
ItemStack[] contents = inv.getInventory().getContents();
Map<String, Tag> values = new HashMap<>();
values.put("Items", new ListTag("Items", CompoundTag.class, serializeInventory(contents)));
return new CompoundTag(values);
}
return null;
}
public String getId() {
return "Chest";
}
public List<CompoundTag> serializeInventory(ItemStack[] items) {
List<CompoundTag> tags = new ArrayList<>();
for (int i = 0; i < items.length; ++i) {
if (items[i] != null) {
Map<String, Tag> tagData = serializeItem(items[i]);
tagData.put("Slot", new ByteTag("Slot", (byte) i));
tags.add(new CompoundTag(tagData));
}
}
return tags;
}
/*
* TODO: Move this into the sponge module!
*
public Map<String, Tag> serializeItem(final org.spongepowered.api.item.inventory.ItemStack item) {
final Map<String, Tag> data = new HashMap<String, Tag>();
// FIXME serialize sponge item
return data;
}
*/
public Map<String, Tag> serializeItem(ItemStack item) {
Map<String, Tag> data = new HashMap<>();
data.put("id", new ShortTag("id", (short) item.getTypeId()));
data.put("Damage", new ShortTag("Damage", item.getDurability()));
data.put("Count", new ByteTag("Count", (byte) item.getAmount()));
if (!item.getEnchantments().isEmpty()) {
List<CompoundTag> enchantmentList = new ArrayList<>();
for (Entry<Enchantment, Integer> entry : item.getEnchantments().entrySet()) {
Map<String, Tag> enchantment = new HashMap<>();
enchantment.put("id", new ShortTag("id", (short) entry.getKey().getId()));
enchantment.put("lvl", new ShortTag("lvl", entry.getValue().shortValue()));
enchantmentList.add(new CompoundTag(enchantment));
}
Map<String, Tag> auxData = new HashMap<>();
auxData.put("ench", new ListTag("ench", CompoundTag.class, enchantmentList));
data.put("tag", new CompoundTag("tag", auxData));
}
return data;
}
}

View File

@ -5,12 +5,13 @@ import com.intellectualcrafters.plot.util.AbstractTitle;
import com.plotsquared.bukkit.object.BukkitPlayer; import com.plotsquared.bukkit.object.BukkitPlayer;
public class DefaultTitle extends AbstractTitle { public class DefaultTitle extends AbstractTitle {
@Override @Override
public void sendTitle(final PlotPlayer player, final String head, final String sub, final int in, final int delay, final int out) { public void sendTitle(PlotPlayer player, String head, String sub, int in, int delay, int out) {
try { try {
final DefaultTitleManager title = new DefaultTitleManager(head, sub, in, delay, out); DefaultTitleManager title = new DefaultTitleManager(head, sub, in, delay, out);
title.send(((BukkitPlayer) player).player); title.send(((BukkitPlayer) player).player);
} catch (Exception e) { } catch (Throwable e) {
AbstractTitle.TITLE_CLASS = new DefaultTitle_183(); AbstractTitle.TITLE_CLASS = new DefaultTitle_183();
AbstractTitle.TITLE_CLASS.sendTitle(player, head, sub, in, delay, out); AbstractTitle.TITLE_CLASS.sendTitle(player, head, sub, in, delay, out);
} }

View File

@ -0,0 +1,379 @@
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();
}
/**
* 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(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.
*/
private 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 {
if (this.packetTitle != null) {
// First reset previous settings
resetTitle(player);
// 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, Integer.TYPE, Integer.TYPE, Integer.TYPE)
.newInstance(actions[2], null, 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) {
sendPacket.invoke(connection, packet);
}
// Send title
Object serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.title) + "\",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()) {
// Send subtitle if present
serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.subtitle) + "\",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 {
// 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 Exception
*/
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 (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) {
try {
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field;
} catch (NoSuchFieldException e) {
e.printStackTrace();
return null;
} catch (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

@ -0,0 +1,373 @@
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.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;
/**
* Create a new 1.8 title
*
* @param title
* Title
* @throws ClassNotFoundException
*/
public DefaultTitleManager_183(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_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.
*/
private 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 Exception
*/
public void send(Player player) throws Exception {
if (this.packetTitle != null) {
// First reset previous settings
resetTitle(player);
// 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, Integer.TYPE, Integer.TYPE, Integer.TYPE)
.newInstance(actions[2], null,
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)) {
sendPacket.invoke(connection, packet);
}
// Send title
Object serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.title) + "\",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()) {
// Send subtitle if present
serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.subtitle) + "\",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 {
// 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 Exception
*/
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

@ -5,12 +5,13 @@ import com.intellectualcrafters.plot.util.AbstractTitle;
import com.plotsquared.bukkit.object.BukkitPlayer; import com.plotsquared.bukkit.object.BukkitPlayer;
public class DefaultTitle_183 extends AbstractTitle { public class DefaultTitle_183 extends AbstractTitle {
@Override @Override
public void sendTitle(final PlotPlayer player, final String head, final String sub, final int in, final int delay, final int out) { public void sendTitle(PlotPlayer player, String head, String sub, int in, int delay, int out) {
try { try {
final DefaultTitleManager_183 title = new DefaultTitleManager_183(head, sub, in, delay, out); DefaultTitleManager_183 title = new DefaultTitleManager_183(head, sub, in, delay, out);
title.send(((BukkitPlayer) player).player); title.send(((BukkitPlayer) player).player);
} catch (final Throwable e) { } catch (Throwable e) {
AbstractTitle.TITLE_CLASS = new HackTitle(); AbstractTitle.TITLE_CLASS = new HackTitle();
AbstractTitle.TITLE_CLASS.sendTitle(player, head, sub, in, delay, out); AbstractTitle.TITLE_CLASS.sendTitle(player, head, sub, in, delay, out);
} }

View File

@ -0,0 +1,27 @@
package com.plotsquared.bukkit.titles;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.AbstractTitle;
import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.bukkit.object.BukkitPlayer;
import org.bukkit.entity.Player;
public class DefaultTitle_19 extends AbstractTitle {
@Override
public void sendTitle(PlotPlayer player, String head, String sub, int in, int delay, int out) {
try {
final Player playerObj = ((BukkitPlayer) player).player;
playerObj.sendTitle(head, sub);
TaskManager.runTaskLater(new Runnable() {
@Override
public void run() {
playerObj.sendTitle("", "");
}
}, delay * 20);
} catch (Throwable e) {
AbstractTitle.TITLE_CLASS = new DefaultTitle();
AbstractTitle.TITLE_CLASS.sendTitle(player, head, sub, in, delay, out);
}
}
}

View File

@ -7,12 +7,13 @@ import com.intellectualcrafters.plot.util.AbstractTitle;
import com.plotsquared.bukkit.object.BukkitPlayer; import com.plotsquared.bukkit.object.BukkitPlayer;
public class HackTitle extends AbstractTitle { public class HackTitle extends AbstractTitle {
@Override @Override
public void sendTitle(final PlotPlayer player, final String head, final String sub, final int in, final int delay, final int out) { public void sendTitle(PlotPlayer player, String head, String sub, int in, int delay, int out) {
try { try {
final HackTitleManager title = new HackTitleManager(head, sub, in, delay, out); HackTitleManager title = new HackTitleManager(head, sub, in, delay, out);
title.send(((BukkitPlayer) player).player); title.send(((BukkitPlayer) player).player);
} catch (final Throwable e) { } catch (Throwable e) {
PS.debug("&cYour server version does not support titles!"); PS.debug("&cYour server version does not support titles!");
Settings.TITLES = false; Settings.TITLES = false;
AbstractTitle.TITLE_CLASS = null; AbstractTitle.TITLE_CLASS = null;

View File

@ -0,0 +1,420 @@
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;
/**
* 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();
}
/**
* 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 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;
}
/**
* Load spigot and NMS classes.
*/
private 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 {
if ((getProtocolVersion(player) >= 47) && isSpigot() && (this.packetTitle != null)) {
// First reset previous settings
resetTitle(player);
// 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, Integer.TYPE, Integer.TYPE, Integer.TYPE).newInstance(actions[2],
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)) {
sendPacket.invoke(connection, packet);
}
// Send title
Object serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.title) + "\",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()) {
// Send subtitle if present
serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.subtitle) + "\",color:" + this.subtitleColor.name()
.toLowerCase() + "}");
packet = this.packetTitle.getConstructor(this.packetActions, Reflection.getNMSClass("IChatBaseComponent"))
.newInstance(actions[1], serialized);
sendPacket.invoke(connection, packet);
}
}
}
/**
* 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 {
if ((getProtocolVersion(player) >= 47) && isSpigot()) {
// 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).newInstance(actions[3]);
sendPacket.invoke(connection, packet);
}
}
/**
* Reset the title settings.
*
* @param player Player
* @throws Exception on NMS error.
*/
public void resetTitle(Player player) throws Exception {
if ((getProtocolVersion(player) >= 47) && isSpigot()) {
// 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).newInstance(actions[4]);
sendPacket.invoke(connection, packet);
}
}
/**
* Get the protocol version of the player.
*
* @param player Player
* @return Protocol version
* @throws Exception on NMS Error
*/
private int getProtocolVersion(Player player) throws Exception {
Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object networkManager = getValue("networkManager", connection);
return (Integer) getMethod("getVersion", networkManager.getClass()).invoke(networkManager);
}
/**
* Check if running spigot.
*
* @return Spigot
*/
private boolean isSpigot() {
return Bukkit.getVersion().contains("Spigot");
}
/**
* Get class by url.
*
* @param namespace Namespace url
* @return Class
*/
private Class<?> getClass(String namespace) {
try {
return Class.forName(namespace);
} catch (ClassNotFoundException ignored) {
}
return null;
}
private Field getField(String name, Class<?> clazz) throws Exception {
return clazz.getDeclaredField(name);
}
private Object getValue(String name, Object obj) throws Exception {
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);
field.setAccessible(true);
return field;
} catch (SecurityException | NoSuchFieldException 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

@ -20,31 +20,31 @@ public class BukkitChatManager extends ChatManager<FancyMessage> {
} }
@Override @Override
public void color(final PlotMessage m, final String color) { public void color(PlotMessage m, String color) {
m.$(this).color(ChatColor.getByChar(C.color(color).substring(1))); m.$(this).color(ChatColor.getByChar(C.color(color).substring(1)));
} }
@Override @Override
public void tooltip(final PlotMessage m, final PlotMessage... tooltips) { public void tooltip(PlotMessage m, PlotMessage... tooltips) {
final List<FancyMessage> lines = new ArrayList<>(); List<FancyMessage> lines = new ArrayList<>();
for (final PlotMessage tooltip : tooltips) { for (PlotMessage tooltip : tooltips) {
lines.add(tooltip.$(this)); lines.add(tooltip.$(this));
} }
m.$(this).formattedTooltip(lines); m.$(this).formattedTooltip(lines);
} }
@Override @Override
public void command(final PlotMessage m, final String command) { public void command(PlotMessage m, String command) {
m.$(this).command(command); m.$(this).command(command);
} }
@Override @Override
public void text(final PlotMessage m, final String text) { public void text(PlotMessage m, String text) {
m.$(this).then(ChatColor.stripColor(text)); m.$(this).then(ChatColor.stripColor(text));
} }
@Override @Override
public void send(final PlotMessage m, final PlotPlayer player) { public void send(PlotMessage m, PlotPlayer player) {
if (ConsolePlayer.isConsole(player)) { if (ConsolePlayer.isConsole(player)) {
player.sendMessage(m.$(this).toOldMessageFormat()); player.sendMessage(m.$(this).toOldMessageFormat());
} else { } else {
@ -53,7 +53,7 @@ public class BukkitChatManager extends ChatManager<FancyMessage> {
} }
@Override @Override
public void suggest(final PlotMessage m, final String command) { public void suggest(PlotMessage m, String command) {
m.$(this).suggest(command); m.$(this).suggest(command);
} }

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,77 @@
package com.plotsquared.bukkit.util;
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.Bukkit;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
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;
public class BukkitCommand implements CommandExecutor, TabCompleter {
public BukkitCommand() {
new DebugUUID();
}
@Override
public boolean onCommand(final CommandSender commandSender, org.bukkit.command.Command command, final String commandLabel, String[] args) {
if (commandSender instanceof Player) {
return MainCommand.onCommand(BukkitUtil.getPlayer((Player) commandSender), args);
}
if (commandSender.getClass() == Bukkit.getConsoleSender().getClass()) {
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;
}
@Override
public List<String> onTabComplete(CommandSender commandSender, org.bukkit.command.Command command, String s, String[] args) {
if (!(commandSender instanceof Player)) {
return null;
}
PlotPlayer player = BukkitUtil.getPlayer((Player) commandSender);
if (args.length == 0) {
return Collections.singletonList("plots");
}
Collection objects = MainCommand.getInstance().tab(player, args, s.endsWith(" "));
if (objects == null) {
return null;
}
List<String> result = new ArrayList<>();
for (Object o : objects) {
result.add(o.toString());
}
return result.size() == 0 ? null : result;
}
}

View File

@ -0,0 +1,88 @@
package com.plotsquared.bukkit.util;
import com.intellectualcrafters.plot.object.OfflinePlotPlayer;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.EconHandler;
import com.plotsquared.bukkit.object.BukkitOfflinePlayer;
import com.plotsquared.bukkit.object.BukkitPlayer;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.permission.Permission;
import org.bukkit.Bukkit;
import org.bukkit.plugin.RegisteredServiceProvider;
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();
setupEconomy();
}
return this.econ != null && this.perms != null;
}
private boolean setupPermissions() {
RegisteredServiceProvider<Permission> permissionProvider = Bukkit.getServer().getServicesManager().getRegistration(Permission.class);
if (permissionProvider != null) {
this.perms = permissionProvider.getProvider();
}
return this.perms != null;
}
private boolean setupEconomy() {
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();
}
return this.econ != null;
}
@Override
public double getMoney(PlotPlayer player) {
double bal = super.getMoney(player);
if (Double.isNaN(bal)) {
return this.econ.getBalance(((BukkitPlayer) player).player);
}
return bal;
}
@Override
public void withdrawMoney(PlotPlayer player, double amount) {
this.econ.withdrawPlayer(((BukkitPlayer) player).player, amount);
}
@Override
public void depositMoney(PlotPlayer player, double amount) {
this.econ.depositPlayer(((BukkitPlayer) player).player, amount);
}
@Override
public void depositMoney(OfflinePlotPlayer player, double amount) {
this.econ.depositPlayer(((BukkitOfflinePlayer) player).player, amount);
}
@Override
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());
}
}

View File

@ -35,91 +35,91 @@ import java.util.UUID;
public class BukkitEventUtil extends EventUtil { public class BukkitEventUtil extends EventUtil {
public Player getPlayer(final PlotPlayer player) { public Player getPlayer(PlotPlayer player) {
if (player instanceof BukkitPlayer) { if (player instanceof BukkitPlayer) {
return ((BukkitPlayer) player).player; return ((BukkitPlayer) player).player;
} }
return null; return null;
} }
public boolean callEvent(final Event event) { public boolean callEvent(Event event) {
Bukkit.getServer().getPluginManager().callEvent(event); Bukkit.getServer().getPluginManager().callEvent(event);
return !(event instanceof Cancellable) || !((Cancellable) event).isCancelled(); return !(event instanceof Cancellable) || !((Cancellable) event).isCancelled();
} }
@Override @Override
public boolean callClaim(final PlotPlayer player, final Plot plot, final boolean auto) { public boolean callClaim(PlotPlayer player, Plot plot, boolean auto) {
return callEvent(new PlayerClaimPlotEvent(getPlayer(player), plot, auto)); return callEvent(new PlayerClaimPlotEvent(getPlayer(player), plot, auto));
} }
@Override @Override
public boolean callTeleport(final PlotPlayer player, final Location from, final Plot plot) { public boolean callTeleport(PlotPlayer player, Location from, Plot plot) {
return callEvent(new PlayerTeleportToPlotEvent(getPlayer(player), from, plot)); return callEvent(new PlayerTeleportToPlotEvent(getPlayer(player), from, plot));
} }
@Override @Override
public boolean callClear(final Plot plot) { public boolean callClear(Plot plot) {
return callEvent(new PlotClearEvent(plot)); return callEvent(new PlotClearEvent(plot));
} }
@Override @Override
public void callDelete(final Plot plot) { public void callDelete(Plot plot) {
callEvent(new PlotDeleteEvent(plot)); callEvent(new PlotDeleteEvent(plot));
} }
@Override @Override
public boolean callFlagAdd(final Flag flag, final Plot plot) { public boolean callFlagAdd(Flag flag, Plot plot) {
return callEvent(new PlotFlagAddEvent(flag, plot)); return callEvent(new PlotFlagAddEvent(flag, plot));
} }
@Override @Override
public boolean callFlagRemove(final Flag flag, final Plot plot) { public boolean callFlagRemove(Flag flag, Plot plot) {
return callEvent(new PlotFlagRemoveEvent(flag, plot)); return callEvent(new PlotFlagRemoveEvent(flag, plot));
} }
@Override @Override
public boolean callMerge(final Plot plot, final ArrayList<PlotId> plots) { public boolean callMerge(Plot plot, ArrayList<PlotId> plots) {
return callEvent(new PlotMergeEvent(BukkitUtil.getWorld(plot.getArea().worldname), plot, plots)); return callEvent(new PlotMergeEvent(BukkitUtil.getWorld(plot.getArea().worldname), plot, plots));
} }
@Override @Override
public boolean callUnlink(final PlotArea area, final ArrayList<PlotId> plots) { public boolean callUnlink(PlotArea area, ArrayList<PlotId> plots) {
return callEvent(new PlotUnlinkEvent(BukkitUtil.getWorld(area.worldname), area, plots)); return callEvent(new PlotUnlinkEvent(BukkitUtil.getWorld(area.worldname), area, plots));
} }
@Override @Override
public void callEntry(final PlotPlayer player, final Plot plot) { public void callEntry(PlotPlayer player, Plot plot) {
callEvent(new PlayerEnterPlotEvent(getPlayer(player), plot)); callEvent(new PlayerEnterPlotEvent(getPlayer(player), plot));
} }
@Override @Override
public void callLeave(final PlotPlayer player, final Plot plot) { public void callLeave(PlotPlayer player, Plot plot) {
callEvent(new PlayerLeavePlotEvent(getPlayer(player), plot)); callEvent(new PlayerLeavePlotEvent(getPlayer(player), plot));
} }
@Override @Override
public void callDenied(final PlotPlayer initiator, final Plot plot, final UUID player, final boolean added) { public void callDenied(PlotPlayer initiator, Plot plot, UUID player, boolean added) {
callEvent(new PlayerPlotDeniedEvent(getPlayer(initiator), plot, player, added)); callEvent(new PlayerPlotDeniedEvent(getPlayer(initiator), plot, player, added));
} }
@Override @Override
public void callTrusted(final PlotPlayer initiator, final Plot plot, final UUID player, final boolean added) { public void callTrusted(PlotPlayer initiator, Plot plot, UUID player, boolean added) {
callEvent(new PlayerPlotHelperEvent(getPlayer(initiator), plot, player, added)); callEvent(new PlayerPlotHelperEvent(getPlayer(initiator), plot, player, added));
} }
@Override @Override
public void callMember(final PlotPlayer initiator, final Plot plot, final UUID player, final boolean added) { public void callMember(PlotPlayer initiator, Plot plot, UUID player, boolean added) {
callEvent(new PlayerPlotTrustedEvent(getPlayer(initiator), plot, player, added)); callEvent(new PlayerPlotTrustedEvent(getPlayer(initiator), plot, player, added));
} }
@Override @Override
public boolean callFlagRemove(final Flag flag, final PlotCluster cluster) { public boolean callFlagRemove(Flag flag, PlotCluster cluster) {
return callEvent(new ClusterFlagRemoveEvent(flag, cluster)); return callEvent(new ClusterFlagRemoveEvent(flag, cluster));
} }
@Override @Override
public Rating callRating(final PlotPlayer player, final Plot plot, final Rating rating) { public Rating callRating(PlotPlayer player, Plot plot, Rating rating) {
final PlotRateEvent event = new PlotRateEvent(player, rating, plot); PlotRateEvent event = new PlotRateEvent(player, rating, plot);
Bukkit.getServer().getPluginManager().callEvent(event); Bukkit.getServer().getPluginManager().callEvent(event);
return event.getRating(); return event.getRating();
} }

View File

@ -1,18 +1,5 @@
package com.plotsquared.bukkit.util; package com.plotsquared.bukkit.util;
import java.util.HashSet;
import java.util.Random;
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;
import org.bukkit.material.MaterialData;
import com.intellectualcrafters.plot.generator.HybridUtils; import com.intellectualcrafters.plot.generator.HybridUtils;
import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.PlotAnalysis; import com.intellectualcrafters.plot.object.PlotAnalysis;
@ -23,6 +10,18 @@ import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.MathMan; import com.intellectualcrafters.plot.util.MathMan;
import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.TaskManager;
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;
import org.bukkit.material.MaterialData;
import java.util.HashSet;
import java.util.Random;
public class BukkitHybridUtils extends HybridUtils { public class BukkitHybridUtils extends HybridUtils {
@ -50,11 +49,11 @@ public class BukkitHybridUtils extends HybridUtils {
} }
final BiomeGrid nullBiomeGrid = new BiomeGrid() { final BiomeGrid nullBiomeGrid = new BiomeGrid() {
@Override @Override
public void setBiome(final int a, final int b, final Biome c) { public void setBiome(int a, int b, Biome c) {
} }
@Override @Override
public Biome getBiome(final int a, final int b) { public Biome getBiome(int a, int b) {
return null; return null;
} }
}; };
@ -72,13 +71,13 @@ public class BukkitHybridUtils extends HybridUtils {
final int ctz = tz >> 4; final int ctz = tz >> 4;
final Random r = new Random(); final Random r = new Random();
MainUtil.initCache(); MainUtil.initCache();
final int width = (tx - bx) + 1; final int width = tx - bx + 1;
final int length = (tz - bz) + 1; final int length = tz - bz + 1;
System.gc(); System.gc();
System.gc(); System.gc();
final short[][][] oldblocks = new short[256][width][length]; final short[][][] oldBlocks = new short[256][width][length];
final short[][][] newblocks = new short[256][width][length]; final short[][][] newBlocks = new short[256][width][length];
final Runnable run = new Runnable() { final Runnable run = new Runnable() {
@Override @Override
@ -87,38 +86,38 @@ public class BukkitHybridUtils extends HybridUtils {
@Override @Override
public void run(int[] value) { public void run(int[] value) {
// [chunkx, chunkz, pos1x, pos1z, pos2x, pos2z, isedge] // [chunkx, chunkz, pos1x, pos1z, pos2x, pos2z, isedge]
final int X = value[0]; int X = value[0];
final int Z = value[1]; int Z = value[1];
final short[][] result = gen.generateExtBlockSections(worldObj, r, X, Z, nullBiomeGrid); short[][] result = gen.generateExtBlockSections(worldObj, r, X, Z, nullBiomeGrid);
final int xb = ((X) << 4) - bx; int xb = (X << 4) - bx;
final int zb = ((Z) << 4) - bz; int zb = (Z << 4) - bz;
for (int i = 0; i < result.length; i++) { for (int i = 0; i < result.length; i++) {
if (result[i] == null) { if (result[i] == null) {
for (int j = 0; j < 4096; j++) { for (int j = 0; j < 4096; j++) {
final int x = MainUtil.x_loc[i][j] + xb; int x = MainUtil.x_loc[i][j] + xb;
if ((x < 0) || (x >= width)) { if (x < 0 || x >= width) {
continue; continue;
} }
final int z = MainUtil.z_loc[i][j] + zb; int z = MainUtil.z_loc[i][j] + zb;
if ((z < 0) || (z >= length)) { if (z < 0 || z >= length) {
continue; continue;
} }
final int y = MainUtil.y_loc[i][j]; int y = MainUtil.y_loc[i][j];
oldblocks[y][x][z] = 0; oldBlocks[y][x][z] = 0;
} }
continue; continue;
} }
for (int j = 0; j < result[i].length; j++) { for (int j = 0; j < result[i].length; j++) {
final int x = MainUtil.x_loc[i][j] + xb; int x = MainUtil.x_loc[i][j] + xb;
if ((x < 0) || (x >= width)) { if (x < 0 || x >= width) {
continue; continue;
} }
final int z = MainUtil.z_loc[i][j] + zb; int z = MainUtil.z_loc[i][j] + zb;
if ((z < 0) || (z >= length)) { if (z < 0 || z >= length) {
continue; continue;
} }
final int y = MainUtil.y_loc[i][j]; int y = MainUtil.y_loc[i][j];
oldblocks[y][x][z] = result[i][j]; oldBlocks[y][x][z] = result[i][j];
} }
} }
@ -129,19 +128,19 @@ public class BukkitHybridUtils extends HybridUtils {
TaskManager.runTaskAsync(new Runnable() { TaskManager.runTaskAsync(new Runnable() {
@Override @Override
public void run() { public void run() {
final int size = width * length; int size = width * length;
final int[] changes = new int[size]; int[] changes = new int[size];
final int[] faces = new int[size]; int[] faces = new int[size];
final int[] data = new int[size]; int[] data = new int[size];
final int[] air = new int[size]; int[] air = new int[size];
final int[] variety = new int[size]; int[] variety = new int[size];
int i = 0; int i = 0;
for (int x = 0; x < width; x++) { for (int x = 0; x < width; x++) {
for (int z = 0; z < length; z++) { for (int z = 0; z < length; z++) {
final HashSet<Short> types = new HashSet<>(); HashSet<Short> types = new HashSet<>();
for (int y = 0; y < 256; y++) { for (int y = 0; y < 256; y++) {
final short old = oldblocks[y][x][z]; short old = oldBlocks[y][x][z];
final short now = newblocks[y][x][z]; short now = newBlocks[y][x][z];
if (old != now) { if (old != now) {
changes[i]++; changes[i]++;
} }
@ -150,29 +149,29 @@ public class BukkitHybridUtils extends HybridUtils {
} else { } else {
// check vertices // check vertices
// modifications_adjacent // modifications_adjacent
if ((x > 0) && (z > 0) && (y > 0) && (x < (width - 1)) && (z < (length - 1)) && (y < 255)) { if (x > 0 && z > 0 && y > 0 && x < width - 1 && z < length - 1 && y < 255) {
if (newblocks[y - 1][x][z] == 0) { if (newBlocks[y - 1][x][z] == 0) {
faces[i]++; faces[i]++;
} }
if (newblocks[y][x - 1][z] == 0) { if (newBlocks[y][x - 1][z] == 0) {
faces[i]++; faces[i]++;
} }
if (newblocks[y][x][z - 1] == 0) { if (newBlocks[y][x][z - 1] == 0) {
faces[i]++; faces[i]++;
} }
if (newblocks[y + 1][x][z] == 0) { if (newBlocks[y + 1][x][z] == 0) {
faces[i]++; faces[i]++;
} }
if (newblocks[y][x + 1][z] == 0) { if (newBlocks[y][x + 1][z] == 0) {
faces[i]++; faces[i]++;
} }
if (newblocks[y][x][z + 1] == 0) { if (newBlocks[y][x][z + 1] == 0) {
faces[i]++; faces[i]++;
} }
} }
final Material material = Material.getMaterial(now); Material material = Material.getMaterial(now);
final Class<? extends MaterialData> md = material.getData(); Class<? extends MaterialData> md = material.getData();
if (md.equals(Directional.class)) { if (md.equals(Directional.class)) {
data[i] += 8; data[i] += 8;
} else if (!md.equals(MaterialData.class)) { } else if (!md.equals(MaterialData.class)) {
@ -189,18 +188,18 @@ public class BukkitHybridUtils extends HybridUtils {
// put in analysis obj // put in analysis obj
// run whenDone // run whenDone
final PlotAnalysis analysis = new PlotAnalysis(); PlotAnalysis analysis = new PlotAnalysis();
analysis.changes = (int) (MathMan.getMean(changes) * 100); analysis.changes = (int) (MathMan.getMean(changes) * 100);
analysis.faces = (int) (MathMan.getMean(faces) * 100); analysis.faces = (int) (MathMan.getMean(faces) * 100);
analysis.data = (int) (MathMan.getMean(data) * 100); analysis.data = (int) (MathMan.getMean(data) * 100);
analysis.air = (int) (MathMan.getMean(air) * 100); analysis.air = (int) (MathMan.getMean(air) * 100);
analysis.variety = (int) (MathMan.getMean(variety) * 100); analysis.variety = (int) (MathMan.getMean(variety) * 100);
analysis.changes_sd = (int) (MathMan.getSD(changes, analysis.changes)); analysis.changes_sd = (int) MathMan.getSD(changes, analysis.changes);
analysis.faces_sd = (int) (MathMan.getSD(faces, analysis.faces)); analysis.faces_sd = (int) MathMan.getSD(faces, analysis.faces);
analysis.data_sd = (int) (MathMan.getSD(data, analysis.data)); analysis.data_sd = (int) MathMan.getSD(data, analysis.data);
analysis.air_sd = (int) (MathMan.getSD(air, analysis.air)); analysis.air_sd = (int) MathMan.getSD(air, analysis.air);
analysis.variety_sd = (int) (MathMan.getSD(variety, analysis.variety)); analysis.variety_sd = (int) MathMan.getSD(variety, analysis.variety);
System.gc(); System.gc();
System.gc(); System.gc();
whenDone.value = analysis; whenDone.value = analysis;
@ -218,48 +217,48 @@ public class BukkitHybridUtils extends HybridUtils {
@Override @Override
public void run(int[] value) { public void run(int[] value) {
final int X = value[0]; int X = value[0];
final int Z = value[1]; int Z = value[1];
worldObj.loadChunk(X, Z); worldObj.loadChunk(X, Z);
int minX; int minX;
int minZ;
int maxX;
int maxZ;
if (X == cbx) { if (X == cbx) {
minX = bx & 15; minX = bx & 15;
} else { } else {
minX = 0; minX = 0;
} }
int minZ;
if (Z == cbz) { if (Z == cbz) {
minZ = bz & 15; minZ = bz & 15;
} else { } else {
minZ = 0; minZ = 0;
} }
int maxX;
if (X == ctx) { if (X == ctx) {
maxX = tx & 15; maxX = tx & 15;
} else { } else {
maxX = 16; maxX = 16;
} }
int maxZ;
if (Z == ctz) { if (Z == ctz) {
maxZ = tz & 15; maxZ = tz & 15;
} else { } else {
maxZ = 16; maxZ = 16;
} }
final int cbx = X << 4; int cbx = X << 4;
final int cbz = Z << 4; int cbz = Z << 4;
final int xb = (cbx) - bx; int xb = cbx - bx;
final int zb = (cbz) - bz; int zb = cbz - bz;
for (int x = minX; x <= maxX; x++) { for (int x = minX; x <= maxX; x++) {
final int xx = cbx + x; int xx = cbx + x;
for (int z = minZ; z <= maxZ; z++) { for (int z = minZ; z <= maxZ; z++) {
final int zz = cbz + z; int zz = cbz + z;
for (int y = 0; y < 256; y++) { for (int y = 0; y < 256; y++) {
final Block block = worldObj.getBlockAt(xx, y, zz); Block block = worldObj.getBlockAt(xx, y, zz);
final int xr = xb + x; int xr = xb + x;
final int zr = zb + z; int zr = zb + z;
newblocks[y][xr][zr] = (short) block.getTypeId(); newBlocks[y][xr][zr] = (short) block.getTypeId();
} }
} }
} }
@ -276,17 +275,17 @@ public class BukkitHybridUtils extends HybridUtils {
} }
@Override @Override
public int checkModified(final String worldname, final int x1, final int x2, final int y1, final int y2, final int z1, final int z2, public int checkModified(String worldName, int x1, int x2, int y1, int y2, int z1, int z2,
final PlotBlock[] blocks) { PlotBlock[] blocks) {
final World world = BukkitUtil.getWorld(worldname); World world = BukkitUtil.getWorld(worldName);
int count = 0; int count = 0;
for (int y = y1; y <= y2; y++) { for (int y = y1; y <= y2; y++) {
for (int x = x1; x <= x2; x++) { for (int x = x1; x <= x2; x++) {
for (int z = z1; z <= z2; z++) { for (int z = z1; z <= z2; z++) {
final Block block = world.getBlockAt(x, y, z); Block block = world.getBlockAt(x, y, z);
final int id = block.getTypeId(); int id = block.getTypeId();
boolean same = false; boolean same = false;
for (final PlotBlock p : blocks) { for (PlotBlock p : blocks) {
if (id == p.id) { if (id == p.id) {
same = true; same = true;
break; break;
@ -302,16 +301,16 @@ public class BukkitHybridUtils extends HybridUtils {
} }
@Override @Override
public int get_ey(final String worldname, final int sx, final int ex, final int sz, final int ez, final int sy) { public int get_ey(String worldName, int sx, int ex, int sz, int ez, int sy) {
final World world = BukkitUtil.getWorld(worldname); World world = BukkitUtil.getWorld(worldName);
final int maxY = world.getMaxHeight(); int maxY = world.getMaxHeight();
int ey = sy; int ey = sy;
for (int x = sx; x <= ex; x++) { for (int x = sx; x <= ex; x++) {
for (int z = sz; z <= ez; z++) { for (int z = sz; z <= ez; z++) {
for (int y = sy; y < maxY; y++) { for (int y = sy; y < maxY; y++) {
if (y > ey) { if (y > ey) {
final Block block = world.getBlockAt(x, y, z); Block block = world.getBlockAt(x, y, z);
if (block.getTypeId() != 0) { if (!block.getType().equals(Material.AIR)) {
ey = y; ey = y;
} }
} }

View File

@ -19,11 +19,11 @@ import java.util.List;
public class BukkitInventoryUtil extends InventoryUtil { public class BukkitInventoryUtil extends InventoryUtil {
public static ItemStack getItem(final PlotItemStack item) { public static ItemStack getItem(PlotItemStack item) {
if (item == null) { if (item == null) {
return null; return null;
} }
final ItemStack stack = new ItemStack(item.id, item.amount, item.data); ItemStack stack = new ItemStack(item.id, item.amount, item.data);
ItemMeta meta = null; ItemMeta meta = null;
if (item.name != null) { if (item.name != null) {
meta = stack.getItemMeta(); meta = stack.getItemMeta();
@ -33,8 +33,8 @@ public class BukkitInventoryUtil extends InventoryUtil {
if (meta == null) { if (meta == null) {
meta = stack.getItemMeta(); meta = stack.getItemMeta();
} }
final List<String> lore = new ArrayList<>(); List<String> lore = new ArrayList<>();
for (final String entry : item.lore) { for (String entry : item.lore) {
lore.add(ChatColor.translateAlternateColorCodes('&', entry)); lore.add(ChatColor.translateAlternateColorCodes('&', entry));
} }
meta.setLore(lore); meta.setLore(lore);
@ -46,12 +46,12 @@ public class BukkitInventoryUtil extends InventoryUtil {
} }
@Override @Override
public void open(final PlotInventory inv) { public void open(PlotInventory inv) {
final BukkitPlayer bp = (BukkitPlayer) inv.player; BukkitPlayer bp = (BukkitPlayer) inv.player;
final Inventory inventory = Bukkit.createInventory(null, inv.size * 9, inv.getTitle()); Inventory inventory = Bukkit.createInventory(null, inv.size * 9, inv.getTitle());
final PlotItemStack[] items = inv.getItems(); PlotItemStack[] items = inv.getItems();
for (int i = 0; i < inv.size * 9; i++) { for (int i = 0; i < inv.size * 9; i++) {
final PlotItemStack item = items[i]; PlotItemStack item = items[i];
if (item != null) { if (item != null) {
inventory.setItem(i, getItem(item)); inventory.setItem(i, getItem(item));
} }
@ -61,19 +61,19 @@ public class BukkitInventoryUtil extends InventoryUtil {
} }
@Override @Override
public void close(final PlotInventory inv) { public void close(PlotInventory inv) {
if (!inv.isOpen()) { if (!inv.isOpen()) {
return; return;
} }
inv.player.deleteMeta("inventory"); inv.player.deleteMeta("inventory");
final BukkitPlayer bp = (BukkitPlayer) inv.player; BukkitPlayer bp = (BukkitPlayer) inv.player;
bp.player.closeInventory(); bp.player.closeInventory();
} }
@Override @Override
public void setItem(final PlotInventory inv, final int index, final PlotItemStack item) { public void setItem(PlotInventory inv, int index, PlotItemStack item) {
final BukkitPlayer bp = (BukkitPlayer) inv.player; BukkitPlayer bp = (BukkitPlayer) inv.player;
final InventoryView opened = bp.player.getOpenInventory(); InventoryView opened = bp.player.getOpenInventory();
if (!inv.isOpen()) { if (!inv.isOpen()) {
return; return;
} }
@ -81,22 +81,22 @@ public class BukkitInventoryUtil extends InventoryUtil {
bp.player.updateInventory(); bp.player.updateInventory();
} }
public PlotItemStack getItem(final ItemStack item) { public PlotItemStack getItem(ItemStack item) {
if (item == null) { if (item == null) {
return null; return null;
} }
final int id = item.getTypeId(); int id = item.getTypeId();
final short data = item.getDurability(); short data = item.getDurability();
final int amount = item.getAmount(); int amount = item.getAmount();
String name = null; String name = null;
String[] lore = null; String[] lore = null;
if (item.hasItemMeta()) { if (item.hasItemMeta()) {
final ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
if (meta.hasDisplayName()) { if (meta.hasDisplayName()) {
name = meta.getDisplayName(); name = meta.getDisplayName();
} }
if (meta.hasLore()) { if (meta.hasLore()) {
final List<String> itemLore = meta.getLore(); List<String> itemLore = meta.getLore();
lore = itemLore.toArray(new String[itemLore.size()]); lore = itemLore.toArray(new String[itemLore.size()]);
} }
} }
@ -104,10 +104,10 @@ public class BukkitInventoryUtil extends InventoryUtil {
} }
@Override @Override
public PlotItemStack[] getItems(final PlotPlayer player) { public PlotItemStack[] getItems(PlotPlayer player) {
final BukkitPlayer bp = (BukkitPlayer) player; BukkitPlayer bp = (BukkitPlayer) player;
final PlayerInventory inv = bp.player.getInventory(); PlayerInventory inv = bp.player.getInventory();
final PlotItemStack[] items = new PlotItemStack[36]; PlotItemStack[] items = new PlotItemStack[36];
for (int i = 0; i < 36; i++) { for (int i = 0; i < 36; i++) {
items[i] = getItem(inv.getItem(i)); items[i] = getItem(inv.getItem(i));
} }
@ -115,12 +115,12 @@ public class BukkitInventoryUtil extends InventoryUtil {
} }
@Override @Override
public boolean isOpen(final PlotInventory inv) { public boolean isOpen(PlotInventory inv) {
if (!inv.isOpen()) { if (!inv.isOpen()) {
return false; return false;
} }
final BukkitPlayer bp = (BukkitPlayer) inv.player; BukkitPlayer bp = (BukkitPlayer) inv.player;
final InventoryView opened = bp.player.getOpenInventory(); InventoryView opened = bp.player.getOpenInventory();
return inv.isOpen() && opened.getType() == InventoryType.CRAFTING && opened.getTitle() == null; return inv.isOpen() && opened.getType() == InventoryType.CRAFTING && opened.getTitle() == null;
} }
} }

View File

@ -16,35 +16,35 @@ public class BukkitPlainChatManager extends ChatManager<List<StringBuilder>> {
} }
@Override @Override
public void color(final PlotMessage m, final String color) { public void color(PlotMessage m, String color) {
final List<StringBuilder> parts = m.$(this); List<StringBuilder> parts = m.$(this);
parts.get(parts.size() - 1).insert(0, color); parts.get(parts.size() - 1).insert(0, color);
} }
@Override @Override
public void tooltip(final PlotMessage m, final PlotMessage... tooltips) { public void tooltip(PlotMessage m, PlotMessage... tooltips) {
} }
@Override @Override
public void command(final PlotMessage m, final String command) { public void command(PlotMessage m, String command) {
} }
@Override @Override
public void text(final PlotMessage m, final String text) { public void text(PlotMessage m, String text) {
m.$(this).add(new StringBuilder(ChatColor.stripColor(text))); m.$(this).add(new StringBuilder(ChatColor.stripColor(text)));
} }
@Override @Override
public void send(final PlotMessage m, final PlotPlayer player) { public void send(PlotMessage m, PlotPlayer player) {
final StringBuilder built = new StringBuilder(); StringBuilder built = new StringBuilder();
for (final StringBuilder sb : m.$(this)) { for (StringBuilder sb : m.$(this)) {
built.append(sb); built.append(sb);
} }
player.sendMessage(built.toString()); player.sendMessage(built.toString());
} }
@Override @Override
public void suggest(final PlotMessage m, final String command) { public void suggest(PlotMessage m, String command) {
} }
} }

View File

@ -1,340 +1,309 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// package com.plotsquared.bukkit.util;
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / import com.intellectualcrafters.jnbt.ByteArrayTag;
// / import com.intellectualcrafters.jnbt.CompoundTag;
// This program is free software; you can redistribute it and/or modify / import com.intellectualcrafters.jnbt.IntTag;
// it under the terms of the GNU General Public License as published by / import com.intellectualcrafters.jnbt.ListTag;
// the Free Software Foundation; either version 3 of the License, or / import com.intellectualcrafters.jnbt.ShortTag;
// (at your option) any later version. / import com.intellectualcrafters.jnbt.StringTag;
// / import com.intellectualcrafters.jnbt.Tag;
// This program is distributed in the hope that it will be useful, / import com.intellectualcrafters.plot.object.ChunkLoc;
// but WITHOUT ANY WARRANTY; without even the implied warranty of / import com.intellectualcrafters.plot.object.Location;
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / import com.intellectualcrafters.plot.object.RegionWrapper;
// GNU General Public License for more details. / import com.intellectualcrafters.plot.object.RunnableVal;
// / import com.intellectualcrafters.plot.util.MainUtil;
// You should have received a copy of the GNU General Public License / import com.intellectualcrafters.plot.util.SchematicHandler;
// along with this program; if not, write to the Free Software Foundation, / import com.intellectualcrafters.plot.util.TaskManager;
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / import com.plotsquared.bukkit.object.schematic.StateWrapper;
// / import org.bukkit.Bukkit;
// You can contact us via: support@intellectualsites.com / import org.bukkit.Chunk;
//////////////////////////////////////////////////////////////////////////////////////////////////// import org.bukkit.World;
package com.plotsquared.bukkit.util; import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import java.util.ArrayDeque;
import java.util.ArrayList; import java.util.ArrayDeque;
import java.util.HashMap; import java.util.ArrayList;
import java.util.List; import java.util.HashMap;
import java.util.Map; import java.util.List;
import java.util.Map.Entry; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.bukkit.Bukkit; /**
import org.bukkit.Chunk; * Schematic Handler.
import org.bukkit.World; */
import org.bukkit.block.Block; public class BukkitSchematicHandler extends SchematicHandler {
import org.bukkit.block.BlockState;
@Override
import com.intellectualcrafters.jnbt.ByteArrayTag; public void getCompoundTag(final String world, final Set<RegionWrapper> regions, final RunnableVal<CompoundTag> whenDone) {
import com.intellectualcrafters.jnbt.CompoundTag; // async
import com.intellectualcrafters.jnbt.IntTag; TaskManager.runTaskAsync(new Runnable() {
import com.intellectualcrafters.jnbt.ListTag; @Override
import com.intellectualcrafters.jnbt.ShortTag; public void run() {
import com.intellectualcrafters.jnbt.StringTag; // Main positions
import com.intellectualcrafters.jnbt.Tag; Location[] corners = MainUtil.getCorners(world, regions);
import com.intellectualcrafters.plot.object.ChunkLoc; final Location bot = corners[0];
import com.intellectualcrafters.plot.object.Location; Location top = corners[1];
import com.intellectualcrafters.plot.object.RegionWrapper;
import com.intellectualcrafters.plot.object.RunnableVal; final int width = top.getX() - bot.getX() + 1;
import com.intellectualcrafters.plot.util.MainUtil; int height = top.getY() - bot.getY() + 1;
import com.intellectualcrafters.plot.util.SchematicHandler; final int length = top.getZ() - bot.getZ() + 1;
import com.intellectualcrafters.plot.util.TaskManager; // Main Schematic tag
import com.plotsquared.bukkit.object.schematic.StateWrapper; final HashMap<String, Tag> schematic = new HashMap<>();
schematic.put("Width", new ShortTag("Width", (short) width));
/** schematic.put("Length", new ShortTag("Length", (short) length));
* Schematic Handler schematic.put("Height", new ShortTag("Height", (short) height));
* schematic.put("Materials", new StringTag("Materials", "Alpha"));
schematic.put("WEOriginX", new IntTag("WEOriginX", 0));
schematic.put("WEOriginY", new IntTag("WEOriginY", 0));
*/ schematic.put("WEOriginZ", new IntTag("WEOriginZ", 0));
public class BukkitSchematicHandler extends SchematicHandler { schematic.put("WEOffsetX", new IntTag("WEOffsetX", 0));
schematic.put("WEOffsetY", new IntTag("WEOffsetY", 0));
@Override schematic.put("WEOffsetZ", new IntTag("WEOffsetZ", 0));
public void getCompoundTag(final String world, final Set<RegionWrapper> regions, final RunnableVal<CompoundTag> whenDone) { // Arrays of data types
// async final List<CompoundTag> tileEntities = new ArrayList<>();
TaskManager.runTaskAsync(new Runnable() { final byte[] blocks = new byte[width * height * length];
@Override final byte[] blockData = new byte[width * height * length];
public void run() { // Queue
// Main positions final ArrayDeque<RegionWrapper> queue = new ArrayDeque<>(regions);
Location[] corners = MainUtil.getCorners(world, regions); TaskManager.runTask(new Runnable() {
final Location bot = corners[0]; @Override
final Location top = corners[1]; public void run() {
if (queue.isEmpty()) {
final int width = (top.getX() - bot.getX()) + 1; TaskManager.runTaskAsync(new Runnable() {
final int height = (top.getY() - bot.getY()) + 1; @Override
final int length = (top.getZ() - bot.getZ()) + 1; public void run() {
// Main Schematic tag schematic.put("Blocks", new ByteArrayTag("Blocks", blocks));
final HashMap<String, Tag> schematic = new HashMap<>(); schematic.put("Data", new ByteArrayTag("Data", blockData));
schematic.put("Width", new ShortTag("Width", (short) width)); schematic.put("Entities", new ListTag("Entities", CompoundTag.class, new ArrayList<Tag>()));
schematic.put("Length", new ShortTag("Length", (short) length)); schematic.put("TileEntities", new ListTag("TileEntities", CompoundTag.class, tileEntities));
schematic.put("Height", new ShortTag("Height", (short) height)); whenDone.value = new CompoundTag("Schematic", schematic);
schematic.put("Materials", new StringTag("Materials", "Alpha")); TaskManager.runTask(whenDone);
schematic.put("WEOriginX", new IntTag("WEOriginX", 0)); System.gc();
schematic.put("WEOriginY", new IntTag("WEOriginY", 0)); System.gc();
schematic.put("WEOriginZ", new IntTag("WEOriginZ", 0)); }
schematic.put("WEOffsetX", new IntTag("WEOffsetX", 0)); });
schematic.put("WEOffsetY", new IntTag("WEOffsetY", 0)); return;
schematic.put("WEOffsetZ", new IntTag("WEOffsetZ", 0)); }
// Arrays of data types final Runnable regionTask = this;
final List<Tag> tileEntities = new ArrayList<>(); RegionWrapper region = queue.poll();
final byte[] blocks = new byte[width * height * length]; Location pos1 = new Location(world, region.minX, region.minY, region.minZ);
final byte[] blockData = new byte[width * height * length]; Location pos2 = new Location(world, region.maxX, region.maxY, region.maxZ);
// Queue final int bx = bot.getX();
final ArrayDeque<RegionWrapper> queue = new ArrayDeque<>(regions); final int bz = bot.getZ();
TaskManager.runTask(new Runnable() { final int p1x = pos1.getX();
@Override final int p1z = pos1.getZ();
public void run() { final int p2x = pos2.getX();
if (queue.isEmpty()) { final int p2z = pos2.getZ();
TaskManager.runTaskAsync(new Runnable() { final int bcx = p1x >> 4;
@Override final int bcz = p1z >> 4;
public void run() { final int tcx = p2x >> 4;
schematic.put("Blocks", new ByteArrayTag("Blocks", blocks)); final int tcz = p2z >> 4;
schematic.put("Data", new ByteArrayTag("Data", blockData)); final int sy = pos1.getY();
schematic.put("Entities", new ListTag("Entities", CompoundTag.class, new ArrayList<Tag>())); final int ey = pos2.getY();
schematic.put("TileEntities", new ListTag("TileEntities", CompoundTag.class, tileEntities)); // Generate list of chunks
whenDone.value = new CompoundTag("Schematic", schematic); final ArrayList<ChunkLoc> chunks = new ArrayList<>();
TaskManager.runTask(whenDone); for (int x = bcx; x <= tcx; x++) {
System.gc(); for (int z = bcz; z <= tcz; z++) {
System.gc(); chunks.add(new ChunkLoc(x, z));
} }
}); }
return; final World worldObj = Bukkit.getWorld(world);
} // Main thread
final Runnable regionTask = this; TaskManager.runTask(new Runnable() {
RegionWrapper region = queue.poll(); @Override
Location pos1 = new Location(world, region.minX, region.minY, region.minZ); public void run() {
Location pos2 = new Location(world, region.maxX, region.maxY, region.maxZ); long start = System.currentTimeMillis();
final int bx = bot.getX(); while (!chunks.isEmpty() && System.currentTimeMillis() - start < 20) {
final int bz = bot.getZ(); // save schematics
final int p1x = pos1.getX(); ChunkLoc chunk = chunks.remove(0);
final int p1z = pos1.getZ(); Chunk bc = worldObj.getChunkAt(chunk.x, chunk.z);
final int p2x = pos2.getX(); if (!bc.load(false)) {
final int p2z = pos2.getZ(); continue;
final int bcx = p1x >> 4; }
final int bcz = p1z >> 4; int X = chunk.x;
final int tcx = p2x >> 4; int Z = chunk.z;
final int tcz = p2z >> 4; int xxb = X << 4;
final int sy = pos1.getY(); int zzb = Z << 4;
final int ey = pos2.getY(); int xxt = xxb + 15;
// Generate list of chunks int zzt = zzb + 15;
final ArrayList<ChunkLoc> chunks = new ArrayList<>();
for (int x = bcx; x <= tcx; x++) { if (X == bcx) {
for (int z = bcz; z <= tcz; z++) { xxb = p1x;
chunks.add(new ChunkLoc(x, z)); }
} if (X == tcx) {
} xxt = p2x;
final World worldObj = Bukkit.getWorld(world); }
// Main thread if (Z == bcz) {
TaskManager.runTask(new Runnable() { zzb = p1z;
@Override }
public void run() { if (Z == tcz) {
final long start = System.currentTimeMillis(); zzt = p2z;
while ((!chunks.isEmpty()) && ((System.currentTimeMillis() - start) < 20)) { }
// save schematics for (int y = sy; y <= Math.min(255, ey); y++) {
final ChunkLoc chunk = chunks.remove(0); int ry = y - sy;
final Chunk bc = worldObj.getChunkAt(chunk.x, chunk.z); int i1 = ry * width * length;
if (!bc.load(false)) { for (int z = zzb; z <= zzt; z++) {
continue; int rz = z - bz;
} int i2 = i1 + rz * width;
final int X = chunk.x; for (int x = xxb; x <= xxt; x++) {
final int Z = chunk.z; int rx = x - bx;
int xxb = X << 4; int index = i2 + rx;
int zzb = Z << 4; Block block = worldObj.getBlockAt(x, y, z);
int xxt = xxb + 15; int id = block.getTypeId();
int zzt = zzb + 15; switch (id) {
case 0:
if (X == bcx) { case 2:
xxb = p1x; case 4:
} case 13:
if (X == tcx) { case 14:
xxt = p2x; case 15:
} case 20:
if (Z == bcz) { case 21:
zzb = p1z; case 22:
} case 24:
if (Z == tcz) { case 30:
zzt = p2z; case 32:
} case 37:
for (int y = sy; y <= Math.min(255, ey); y++) { case 39:
final int ry = y - sy; case 40:
final int i1 = (ry * width * length); case 41:
for (int z = zzb; z <= zzt; z++) { case 42:
final int rz = z - bz; case 45:
final int i2 = i1 + (rz * width); case 46:
for (int x = xxb; x <= xxt; x++) { case 47:
final int rx = x - bx; case 48:
final int index = i2 + rx; case 49:
final Block block = worldObj.getBlockAt(x, y, z); case 51:
final int id = block.getTypeId(); case 55:
switch (id) { case 56:
case 0: case 57:
case 2: case 58:
case 4: case 60:
case 13: case 7:
case 14: case 8:
case 15: case 9:
case 20: case 10:
case 21: case 11:
case 22: case 73:
case 24: case 74:
case 30: case 78:
case 32: case 79:
case 37: case 80:
case 39: case 81:
case 40: case 82:
case 41: case 83:
case 42: case 85:
case 45: case 87:
case 46: case 88:
case 47: case 101:
case 48: case 102:
case 49: case 103:
case 51: case 110:
case 55: case 112:
case 56: case 113:
case 57: case 121:
case 58: case 122:
case 60: case 129:
case 7: case 133:
case 8: case 165:
case 9: case 166:
case 10: case 169:
case 11: case 170:
case 73: case 172:
case 74: case 173:
case 78: case 174:
case 79: case 181:
case 80: case 182:
case 81: case 188:
case 82: case 189:
case 83: case 190:
case 85: case 191:
case 87: case 192:
case 88: break;
case 101: case 54:
case 102: case 130:
case 103: case 142:
case 110: case 27:
case 112: case 137:
case 113: case 52:
case 121: case 154:
case 122: case 84:
case 129: case 25:
case 133: case 144:
case 165: case 138:
case 166: case 176:
case 169: case 177:
case 170: case 63:
case 172: case 68:
case 173: case 323:
case 174: case 117:
case 181: case 116:
case 182: case 28:
case 188: case 66:
case 189: case 157:
case 190: case 61:
case 191: case 62:
case 192: { case 140:
break; case 146:
} case 149:
case 54: case 150:
case 130: case 158:
case 142: case 23:
case 27: case 123:
case 137: case 124:
case 52: case 29:
case 154: case 33:
case 84: case 151:
case 25: case 178:
case 144: // TODO implement fully
case 138: BlockState state = block.getState();
case 176: if (state != null) {
case 177: StateWrapper wrapper = new StateWrapper(state);
case 63: CompoundTag rawTag = wrapper.getTag();
case 68: if (rawTag != null) {
case 323: Map<String, Tag> values = new HashMap<>(rawTag.getValue());
case 117: values.put("id", new StringTag("id", wrapper.getId()));
case 116: values.put("x", new IntTag("x", x));
case 28: values.put("y", new IntTag("y", y));
case 66: values.put("z", new IntTag("z", z));
case 157: CompoundTag tileEntityTag = new CompoundTag(values);
case 61: tileEntities.add(tileEntityTag);
case 62: }
case 140: }
case 146: default:
case 149: blockData[index] = block.getData();
case 150: }
case 158: // For optimization reasons, we are not supporting custom data types
case 23: // Especially since the most likely reason beyond this range is modded servers in which the blocks
case 123: // have NBT
case 124: // if (type > 255) {
case 29: // if (addBlocks == null) {
case 33: // addBlocks = new byte[(blocks.length >> 1) + 1];
case 151: // }
case 178: { // addBlocks[index >> 1] = (byte) (((index & 1) == 0) ?
// TODO implement fully // (addBlocks[index >> 1] & 0xF0) | ((type >> 8) & 0xF) : (addBlocks[index >> 1] & 0xF) | (((type
final BlockState state = block.getState(); // >> 8) & 0xF) << 4));
if (state != null) { // }
final StateWrapper wrapper = new StateWrapper(state); blocks[index] = (byte) id;
final CompoundTag rawTag = wrapper.getTag(); }
if (rawTag != null) { }
final Map<String, Tag> values = new HashMap<String, Tag>(); }
for (final Entry<String, Tag> entry : rawTag.getValue().entrySet()) { }
values.put(entry.getKey(), entry.getValue()); if (!chunks.isEmpty()) {
} TaskManager.runTaskLater(this, 1);
values.put("id", new StringTag("id", wrapper.getId())); } else {
values.put("x", new IntTag("x", x)); regionTask.run();
values.put("y", new IntTag("y", y)); }
values.put("z", new IntTag("z", z)); }
final CompoundTag tileEntityTag = new CompoundTag(values); });
tileEntities.add(tileEntityTag); }
} });
} }
} });
default: { }
blockData[index] = block.getData();
} @Override
} public void restoreTile(String world, CompoundTag ct, int x, int y, int z) {
// For optimization reasons, we are not supporting custom data types new StateWrapper(ct).restoreTag(world, x, y, z);
// Especially since the most likely reason beyond this range is modded servers in which the blocks }
// have NBT }
// if (type > 255) {
// if (addBlocks == null) {
// addBlocks = new byte[(blocks.length >> 1) + 1];
// }
// addBlocks[index >> 1] = (byte) (((index & 1) == 0) ?
// (addBlocks[index >> 1] & 0xF0) | ((type >> 8) & 0xF) : (addBlocks[index >> 1] & 0xF) | (((type
// >> 8) & 0xF) << 4));
// }
blocks[index] = (byte) id;
}
}
}
}
if (!chunks.isEmpty()) {
TaskManager.runTaskLater(this, 1);
} else {
regionTask.run();
}
}
});
}
});
}
});
}
@Override
public void restoreTag(CompoundTag ct, short x, short y, short z, Schematic schem) {
new StateWrapper(ct).restoreTag(x, y, z, schem);
}
}

View File

@ -29,13 +29,13 @@ public class BukkitSetupUtils extends SetupUtils {
if (!SetupUtils.generators.isEmpty()) { if (!SetupUtils.generators.isEmpty()) {
return; return;
} }
final String testWorld = "CheckingPlotSquaredGenerator"; String testWorld = "CheckingPlotSquaredGenerator";
for (final Plugin plugin : Bukkit.getPluginManager().getPlugins()) { for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
if (plugin.isEnabled()) { if (plugin.isEnabled()) {
final ChunkGenerator generator = plugin.getDefaultWorldGenerator(testWorld, ""); ChunkGenerator generator = plugin.getDefaultWorldGenerator(testWorld, "");
if (generator != null) { if (generator != null) {
PS.get().removePlotAreas(testWorld); PS.get().removePlotAreas(testWorld);
final String name = plugin.getDescription().getName(); String name = plugin.getDescription().getName();
GeneratorWrapper<?> wrapped; GeneratorWrapper<?> wrapped;
if (generator instanceof GeneratorWrapper<?>) { if (generator instanceof GeneratorWrapper<?>) {
wrapped = (GeneratorWrapper<?>) generator; wrapped = (GeneratorWrapper<?>) generator;
@ -49,10 +49,10 @@ public class BukkitSetupUtils extends SetupUtils {
} }
@Override @Override
public String setupWorld(final SetupObject object) { public String setupWorld(SetupObject object) {
SetupUtils.manager.updateGenerators(); SetupUtils.manager.updateGenerators();
ConfigurationNode[] steps = object.step == null ? new ConfigurationNode[0] : object.step; ConfigurationNode[] steps = object.step == null ? new ConfigurationNode[0] : object.step;
final String world = object.world; String world = object.world;
int type = object.type; int type = object.type;
String worldPath = "worlds." + object.world; String worldPath = "worlds." + object.world;
if (!PS.get().config.contains(worldPath)) { if (!PS.get().config.contains(worldPath)) {
@ -62,20 +62,20 @@ public class BukkitSetupUtils extends SetupUtils {
switch (type) { switch (type) {
case 2: { case 2: {
if (object.id != null) { if (object.id != null) {
String areaname = object.id + "-" + object.min + "-" + object.max; String areaName = object.id + "-" + object.min + "-" + object.max;
String areaPath = "areas." + areaname; String areaPath = "areas." + areaName;
if (!worldSection.contains(areaPath)) { if (!worldSection.contains(areaPath)) {
worldSection.createSection(areaPath); worldSection.createSection(areaPath);
} }
ConfigurationSection areaSection = worldSection.getConfigurationSection(areaPath); ConfigurationSection areaSection = worldSection.getConfigurationSection(areaPath);
HashMap<String, Object> options = new HashMap<>(); HashMap<String, Object> options = new HashMap<>();
for (final ConfigurationNode step : steps) { for (ConfigurationNode step : steps) {
options.put(step.getConstant(), step.getValue()); options.put(step.getConstant(), step.getValue());
} }
options.put("generator.type", object.type); options.put("generator.type", object.type);
options.put("generator.terrain", object.terrain); options.put("generator.terrain", object.terrain);
options.put("generator.plugin", object.plotManager); 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); options.put("generator.init", object.setupGenerator);
} }
for (Entry<String, Object> entry : options.entrySet()) { for (Entry<String, Object> entry : options.entrySet()) {
@ -91,42 +91,40 @@ public class BukkitSetupUtils extends SetupUtils {
} }
} }
} }
GeneratorWrapper<?> gen = generators.get(object.setupGenerator); GeneratorWrapper<?> gen = SetupUtils.generators.get(object.setupGenerator);
if ((gen != null) && gen.isFull()) { if (gen != null && gen.isFull()) {
object.setupGenerator = null; object.setupGenerator = null;
} }
break; break;
} }
case 1: { case 1:
for (final ConfigurationNode step : steps) { for (ConfigurationNode step : steps) {
worldSection.set(step.getConstant(), step.getValue()); worldSection.set(step.getConstant(), step.getValue());
} }
PS.get().config.set("worlds." + world + "." + "generator.type", object.type); 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.terrain", object.terrain);
PS.get().config.set("worlds." + world + "." + "generator.plugin", object.plotManager); PS.get().config.set("worlds." + world + "." + "generator.plugin", object.plotManager);
if ((object.setupGenerator != null) && !object.setupGenerator.equals(object.plotManager)) { if (object.setupGenerator != null && !object.setupGenerator.equals(object.plotManager)) {
PS.get().config.set("worlds." + world + "." + "generator.init", object.setupGenerator); PS.get().config.set("worlds." + world + "." + "generator.init", object.setupGenerator);
} }
GeneratorWrapper<?> gen = generators.get(object.setupGenerator); GeneratorWrapper<?> gen = SetupUtils.generators.get(object.setupGenerator);
if ((gen != null) && gen.isFull()) { if (gen != null && gen.isFull()) {
object.setupGenerator = null; object.setupGenerator = null;
} }
break; break;
} case 0:
case 0: { for (ConfigurationNode step : steps) {
for (final ConfigurationNode step : steps) {
worldSection.set(step.getConstant(), step.getValue()); worldSection.set(step.getConstant(), step.getValue());
} }
break; break;
}
} }
try { try {
PS.get().config.save(PS.get().configFile); PS.get().config.save(PS.get().configFile);
} catch (final IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
if (object.setupGenerator != null) { 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()) { .isEnabled()) {
Bukkit.getServer() Bukkit.getServer()
.dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv create " + world + " normal -g " + object.setupGenerator); .dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv create " + world + " normal -g " + object.setupGenerator);
@ -135,27 +133,27 @@ public class BukkitSetupUtils extends SetupUtils {
return world; 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); Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw create " + world + " plugin:" + object.setupGenerator);
setGenerator(world, object.setupGenerator); setGenerator(world, object.setupGenerator);
if (Bukkit.getWorld(world) != null) { if (Bukkit.getWorld(world) != null) {
return world; return world;
} }
} }
final WorldCreator wc = new WorldCreator(object.world); WorldCreator wc = new WorldCreator(object.world);
wc.generator(object.setupGenerator); wc.generator(object.setupGenerator);
wc.environment(Environment.NORMAL); wc.environment(Environment.NORMAL);
Bukkit.createWorld(wc); Bukkit.createWorld(wc);
setGenerator(world, object.setupGenerator); setGenerator(world, object.setupGenerator);
} else { } 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()) { .isEnabled()) {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv create " + world + " normal"); Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv create " + world + " normal");
if (Bukkit.getWorld(world) != null) { if (Bukkit.getWorld(world) != null) {
return world; 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); Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw create " + world);
if (Bukkit.getWorld(world) != null) { if (Bukkit.getWorld(world) != null) {
return world; return world;
@ -166,34 +164,34 @@ public class BukkitSetupUtils extends SetupUtils {
return object.world; return object.world;
} }
public void setGenerator(final String world, final String generator) { public void setGenerator(String world, String generator) {
if ((Bukkit.getWorlds().isEmpty()) || !Bukkit.getWorlds().get(0).getName().equals(world)) { if (Bukkit.getWorlds().isEmpty() || !Bukkit.getWorlds().get(0).getName().equals(world)) {
return; return;
} }
final File file = new File("bukkit.yml").getAbsoluteFile(); File file = new File("bukkit.yml").getAbsoluteFile();
final YamlConfiguration yml = YamlConfiguration.loadConfiguration(file); YamlConfiguration yml = YamlConfiguration.loadConfiguration(file);
yml.set("worlds." + world + ".generator", generator); yml.set("worlds." + world + ".generator", generator);
try { try {
yml.save(file); yml.save(file);
} catch (final IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@Override @Override
public String getGenerator(final PlotArea plotworld) { public String getGenerator(PlotArea plotworld) {
if (SetupUtils.generators.isEmpty()) { if (SetupUtils.generators.isEmpty()) {
updateGenerators(); updateGenerators();
} }
final World world = Bukkit.getWorld(plotworld.worldname); World world = Bukkit.getWorld(plotworld.worldname);
if (world == null) { if (world == null) {
return null; return null;
} }
final ChunkGenerator generator = world.getGenerator(); ChunkGenerator generator = world.getGenerator();
if (!(generator instanceof BukkitPlotGenerator)) { if (!(generator instanceof BukkitPlotGenerator)) {
return null; return null;
} }
for (final Entry<String, GeneratorWrapper<?>> entry : generators.entrySet()) { for (Entry<String, GeneratorWrapper<?>> entry : SetupUtils.generators.entrySet()) {
GeneratorWrapper<?> current = entry.getValue(); GeneratorWrapper<?> current = entry.getValue();
if (current.equals(generator)) { if (current.equals(generator)) {
return entry.getKey(); return entry.getKey();

View File

@ -7,37 +7,38 @@ import org.bukkit.Bukkit;
public class BukkitTaskManager extends TaskManager { public class BukkitTaskManager extends TaskManager {
@Override @Override
public int taskRepeat(final Runnable r, final int interval) { public int taskRepeat(Runnable runnable, int interval) {
return BukkitMain.THIS.getServer().getScheduler().scheduleSyncRepeatingTask(BukkitMain.THIS, r, interval, interval); return BukkitMain.THIS.getServer().getScheduler().scheduleSyncRepeatingTask(BukkitMain.THIS, runnable, interval, interval);
} }
@SuppressWarnings("deprecation") @Override @SuppressWarnings("deprecation")
public int taskRepeatAsync(final Runnable r, final int interval) { @Override
return BukkitMain.THIS.getServer().getScheduler().scheduleAsyncRepeatingTask(BukkitMain.THIS, r, interval, interval); public int taskRepeatAsync(Runnable runnable, int interval) {
return BukkitMain.THIS.getServer().getScheduler().scheduleAsyncRepeatingTask(BukkitMain.THIS, runnable, interval, interval);
} }
@Override @Override
public void taskAsync(final Runnable r) { public void taskAsync(Runnable runnable) {
BukkitMain.THIS.getServer().getScheduler().runTaskAsynchronously(BukkitMain.THIS, r).getTaskId(); BukkitMain.THIS.getServer().getScheduler().runTaskAsynchronously(BukkitMain.THIS, runnable).getTaskId();
} }
@Override @Override
public void task(final Runnable r) { public void task(Runnable runnable) {
BukkitMain.THIS.getServer().getScheduler().runTask(BukkitMain.THIS, r).getTaskId(); BukkitMain.THIS.getServer().getScheduler().runTask(BukkitMain.THIS, runnable).getTaskId();
} }
@Override @Override
public void taskLater(final Runnable r, final int delay) { public void taskLater(Runnable runnable, int delay) {
BukkitMain.THIS.getServer().getScheduler().runTaskLater(BukkitMain.THIS, r, delay).getTaskId(); BukkitMain.THIS.getServer().getScheduler().runTaskLater(BukkitMain.THIS, runnable, delay).getTaskId();
} }
@Override @Override
public void taskLaterAsync(final Runnable r, final int delay) { public void taskLaterAsync(Runnable runnable, int delay) {
BukkitMain.THIS.getServer().getScheduler().runTaskLaterAsynchronously(BukkitMain.THIS, r, delay); BukkitMain.THIS.getServer().getScheduler().runTaskLaterAsynchronously(BukkitMain.THIS, runnable, delay);
} }
@Override @Override
public void cancelTask(final int task) { public void cancelTask(int task) {
if (task != -1) { if (task != -1) {
Bukkit.getScheduler().cancelTask(task); Bukkit.getScheduler().cancelTask(task);
} }

View File

@ -12,6 +12,8 @@ import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler; import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.util.WorldUtil; import com.intellectualcrafters.plot.util.WorldUtil;
import com.plotsquared.bukkit.object.BukkitPlayer; import com.plotsquared.bukkit.object.BukkitPlayer;
import java.util.Arrays;
import java.util.List;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
@ -32,9 +34,6 @@ import org.bukkit.material.Tree;
import org.bukkit.material.WoodenStep; import org.bukkit.material.WoodenStep;
import org.bukkit.material.Wool; import org.bukkit.material.Wool;
import java.util.Arrays;
import java.util.List;
public class BukkitUtil extends WorldUtil { public class BukkitUtil extends WorldUtil {
private static String lastString = null; private static String lastString = null;
@ -43,26 +42,26 @@ public class BukkitUtil extends WorldUtil {
private static Player lastPlayer = null; private static Player lastPlayer = null;
private static PlotPlayer lastPlotPlayer = null; private static PlotPlayer lastPlotPlayer = null;
public static void removePlayer(final String plr) { public static void removePlayer(String plr) {
lastPlayer = null; lastPlayer = null;
lastPlotPlayer = null; lastPlotPlayer = null;
} }
public static PlotPlayer getPlayer(final OfflinePlayer op) { public static PlotPlayer getPlayer(OfflinePlayer op) {
if (op.isOnline()) { if (op.isOnline()) {
return getPlayer(op.getPlayer()); return getPlayer(op.getPlayer());
} }
final Player player = OfflinePlayerUtil.loadPlayer(op); Player player = OfflinePlayerUtil.loadPlayer(op);
player.loadData(); player.loadData();
return new BukkitPlayer(player, true); return new BukkitPlayer(player, true);
} }
public static PlotPlayer getPlayer(final Player player) { public static PlotPlayer getPlayer(Player player) {
if (player == lastPlayer) { if (player == lastPlayer) {
return lastPlotPlayer; return lastPlotPlayer;
} }
final String name = player.getName(); String name = player.getName();
final PlotPlayer pp = UUIDHandler.getPlayer(name); PlotPlayer pp = UUIDHandler.getPlayer(name);
if (pp != null) { if (pp != null) {
return pp; return pp;
} }
@ -72,63 +71,64 @@ public class BukkitUtil extends WorldUtil {
return lastPlotPlayer; return lastPlotPlayer;
} }
public static Location getLocation(final org.bukkit.Location loc) { public static Location getLocation(org.bukkit.Location location) {
return new Location(loc.getWorld().getName(), MathMan.roundInt(loc.getX()), MathMan.roundInt(loc.getY()), MathMan.roundInt(loc.getZ())); return new Location(location.getWorld().getName(), MathMan.roundInt(location.getX()), MathMan.roundInt(location.getY()),
MathMan.roundInt(location.getZ()));
} }
public static org.bukkit.Location getLocation(final Location loc) { public static org.bukkit.Location getLocation(Location location) {
return new org.bukkit.Location(getWorld(loc.getWorld()), loc.getX(), loc.getY(), loc.getZ()); return new org.bukkit.Location(getWorld(location.getWorld()), location.getX(), location.getY(), location.getZ());
} }
public static World getWorld(final String string) { public static World getWorld(String string) {
if (StringMan.isEqual(string, lastString)) { if (StringMan.isEqual(string, lastString)) {
if (lastWorld != null) { if (lastWorld != null) {
return lastWorld; return lastWorld;
} }
} }
final World world = Bukkit.getWorld(string); World world = Bukkit.getWorld(string);
lastString = string; lastString = string;
lastWorld = world; lastWorld = world;
return world; return world;
} }
public static String getWorld(final Entity entity) { public static String getWorld(Entity entity) {
return entity.getWorld().getName(); return entity.getWorld().getName();
} }
public static List<Entity> getEntities(final String worldname) { public static List<Entity> getEntities(String worldName) {
return getWorld(worldname).getEntities(); return getWorld(worldName).getEntities();
} }
public static Location getLocation(final Entity entity) { public static Location getLocation(Entity entity) {
final org.bukkit.Location loc = entity.getLocation(); org.bukkit.Location loc = entity.getLocation();
final String world = loc.getWorld().getName(); String world = loc.getWorld().getName();
return new Location(world, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); return new Location(world, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ());
} }
public static Location getLocationFull(final Entity entity) { public static Location getLocationFull(Entity entity) {
final org.bukkit.Location loc = entity.getLocation(); org.bukkit.Location loc = entity.getLocation();
return new Location(loc.getWorld().getName(), MathMan.roundInt(loc.getX()), MathMan.roundInt(loc.getY()), MathMan.roundInt(loc.getZ()), return new Location(loc.getWorld().getName(), MathMan.roundInt(loc.getX()), MathMan.roundInt(loc.getY()), MathMan.roundInt(loc.getZ()),
loc.getYaw(), loc.getPitch()); loc.getYaw(), loc.getPitch());
} }
@Override @Override
public boolean isWorld(final String world) { public boolean isWorld(String worldName) {
return getWorld(world) != null; return getWorld(worldName) != null;
} }
@Override @Override
public String getBiome(final String world, final int x, final int z) { public String getBiome(String world, int x, int z) {
return getWorld(world).getBiome(x, z).name(); return getWorld(world).getBiome(x, z).name();
} }
@Override @Override
public void setSign(final String worldname, final int x, final int y, final int z, final String[] lines) { public void setSign(String worldName, int x, int y, int z, String[] lines) {
final World world = getWorld(worldname); World world = getWorld(worldName);
final Block block = world.getBlockAt(x, y, z); Block block = world.getBlockAt(x, y, z);
// block.setType(Material.AIR); // block.setType(Material.AIR);
block.setTypeIdAndData(Material.WALL_SIGN.getId(), (byte) 2, false); block.setTypeIdAndData(Material.WALL_SIGN.getId(), (byte) 2, false);
final BlockState blockstate = block.getState(); BlockState blockstate = block.getState();
if (blockstate instanceof Sign) { if (blockstate instanceof Sign) {
final Sign sign = (Sign) blockstate; final Sign sign = (Sign) blockstate;
for (int i = 0; i < lines.length; i++) { for (int i = 0; i < lines.length; i++) {
@ -145,11 +145,11 @@ public class BukkitUtil extends WorldUtil {
} }
@Override @Override
public String[] getSign(final Location loc) { public String[] getSign(Location location) {
final Block block = getWorld(loc.getWorld()).getBlockAt(loc.getX(), loc.getY(), loc.getZ()); Block block = getWorld(location.getWorld()).getBlockAt(location.getX(), location.getY(), location.getZ());
if (block != null) { if (block != null) {
if (block.getState() instanceof Sign) { if (block.getState() instanceof Sign) {
final Sign sign = (Sign) block.getState(); Sign sign = (Sign) block.getState();
return sign.getLines(); return sign.getLines();
} }
} }
@ -157,33 +157,51 @@ public class BukkitUtil extends WorldUtil {
} }
@Override @Override
public Location getSpawn(final String world) { public Location getSpawn(PlotPlayer pp) {
final org.bukkit.Location temp = getWorld(world).getSpawnLocation(); return getLocation(((BukkitPlayer) pp).player.getBedSpawnLocation());
}
@Override
public Location getSpawn(String world) {
org.bukkit.Location temp = getWorld(world).getSpawnLocation();
return new Location(world, temp.getBlockX(), temp.getBlockY(), temp.getBlockZ(), temp.getYaw(), temp.getPitch()); return new Location(world, temp.getBlockX(), temp.getBlockY(), temp.getBlockZ(), temp.getYaw(), temp.getPitch());
} }
@Override @Override
public int getHighestBlock(final String world, final int x, final int z) { public void setSpawn(Location location) {
World world = getWorld(location.getWorld());
if (world != null) {
world.setSpawnLocation(location.getX(), location.getY(), location.getZ());
}
}
@Override
public void saveWorld(String worldName) {
World world = getWorld(worldName);
if (world != null) {
world.save();
}
}
@Override
public int getHighestBlock(String world, int x, int z) {
return getWorld(world).getHighestBlockAt(x, z).getY(); return getWorld(world).getHighestBlockAt(x, z).getY();
} }
@Override @Override
public int getBiomeFromString(final String biomeStr) { public int getBiomeFromString(String biomeStr) {
try { try {
final Biome biome = Biome.valueOf(biomeStr.toUpperCase()); Biome biome = Biome.valueOf(biomeStr.toUpperCase());
if (biome == null) {
return -1;
}
return Arrays.asList(Biome.values()).indexOf(biome); return Arrays.asList(Biome.values()).indexOf(biome);
} catch (final IllegalArgumentException e) { } catch (IllegalArgumentException e) {
return -1; return -1;
} }
} }
@Override @Override
public String[] getBiomeList() { public String[] getBiomeList() {
final Biome[] biomes = Biome.values(); Biome[] biomes = Biome.values();
final String[] list = new String[biomes.length]; String[] list = new String[biomes.length];
for (int i = 0; i < biomes.length; i++) { for (int i = 0; i < biomes.length; i++) {
list[i] = biomes[i].name(); list[i] = biomes[i].name();
} }
@ -191,18 +209,18 @@ public class BukkitUtil extends WorldUtil {
} }
@Override @Override
public boolean addItems(final String worldname, final PlotItem items) { public boolean addItems(String worldName, PlotItem items) {
final World world = getWorld(worldname); World world = getWorld(worldName);
final Block block = world.getBlockAt(items.x, items.y, items.z); Block block = world.getBlockAt(items.x, items.y, items.z);
if (block == null) { if (block == null) {
return false; return false;
} }
final BlockState state = block.getState(); BlockState state = block.getState();
if (state instanceof InventoryHolder) { if (state instanceof InventoryHolder) {
final InventoryHolder holder = (InventoryHolder) state; InventoryHolder holder = (InventoryHolder) state;
final Inventory inv = holder.getInventory(); Inventory inv = holder.getInventory();
for (int i = 0; i < items.id.length; i++) { for (int i = 0; i < items.id.length; i++) {
final ItemStack item = new ItemStack(items.id[i], items.amount[i], items.data[i]); ItemStack item = new ItemStack(items.id[i], items.amount[i], items.data[i]);
inv.addItem(item); inv.addItem(item);
} }
state.update(true); state.update(true);
@ -212,11 +230,11 @@ public class BukkitUtil extends WorldUtil {
} }
@Override @Override
public boolean isBlockSolid(final PlotBlock block) { public boolean isBlockSolid(PlotBlock block) {
try { try {
final Material material = Material.getMaterial(block.id); Material material = Material.getMaterial(block.id);
if (material.isBlock() && material.isSolid() && !material.hasGravity()) { if (material.isBlock() && material.isSolid() && !material.hasGravity()) {
final Class<? extends MaterialData> data = material.getData(); Class<? extends MaterialData> data = material.getData();
if (data.equals(MaterialData.class) && !material.isTransparent() && material.isOccluding() if (data.equals(MaterialData.class) && !material.isTransparent() && material.isOccluding()
|| data.equals(Tree.class) || data.equals(Tree.class)
|| data.equals(Sandstone.class) || data.equals(Sandstone.class)
@ -233,16 +251,16 @@ public class BukkitUtil extends WorldUtil {
} }
} }
return false; return false;
} catch (final Exception e) { } catch (Exception e) {
return false; return false;
} }
} }
@Override @Override
public String getClosestMatchingName(final PlotBlock block) { public String getClosestMatchingName(PlotBlock block) {
try { try {
return Material.getMaterial(block.id).name(); return Material.getMaterial(block.id).name();
} catch (final Exception e) { } catch (Exception e) {
return null; return null;
} }
} }
@ -250,13 +268,14 @@ public class BukkitUtil extends WorldUtil {
@Override @Override
public StringComparison<PlotBlock>.ComparisonResult getClosestBlock(String name) { public StringComparison<PlotBlock>.ComparisonResult getClosestBlock(String name) {
try { try {
final Material material = Material.valueOf(name.toUpperCase()); Material material = Material.valueOf(name.toUpperCase());
return new StringComparison<PlotBlock>().new ComparisonResult(0, new PlotBlock((short) material.getId(), (byte) 0)); return new StringComparison<PlotBlock>().new ComparisonResult(0, new PlotBlock((short) material.getId(), (byte) 0));
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
//ignored
} }
try { try {
byte data; byte data;
final String[] split = name.split(":"); String[] split = name.split(":");
if (split.length == 2) { if (split.length == 2) {
data = Byte.parseByte(split[1]); data = Byte.parseByte(split[1]);
name = split[0]; name = split[0];
@ -269,23 +288,24 @@ public class BukkitUtil extends WorldUtil {
id = Short.parseShort(split[0]); id = Short.parseShort(split[0]);
match = 0; match = 0;
} else { } else {
final StringComparison<Material>.ComparisonResult comparison = new StringComparison<>(name, Material.values()).getBestMatchAdvanced(); StringComparison<Material>.ComparisonResult comparison = new StringComparison<>(name, Material.values()).getBestMatchAdvanced();
match = comparison.match; match = comparison.match;
id = (short) comparison.best.getId(); id = (short) comparison.best.getId();
} }
final PlotBlock block = new PlotBlock(id, data); PlotBlock block = new PlotBlock(id, data);
final StringComparison<PlotBlock> outer = new StringComparison<>(); StringComparison<PlotBlock> outer = new StringComparison<>();
return outer.new ComparisonResult(match, block); return outer.new ComparisonResult(match, block);
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
//ignored
} }
return null; return null;
} }
@Override @Override
public void setBiomes(final String worldname, RegionWrapper region, final String biomeStr) { public void setBiomes(String worldName, RegionWrapper region, String biomeStr) {
final World world = getWorld(worldname); World world = getWorld(worldName);
final Biome biome = Biome.valueOf(biomeStr.toUpperCase()); Biome biome = Biome.valueOf(biomeStr.toUpperCase());
for (int x = region.minX; x <= region.maxX; x++) { for (int x = region.minX; x <= region.maxX; x++) {
for (int z = region.minZ; z <= region.maxZ; z++) { for (int z = region.minZ; z <= region.maxZ; z++) {
world.setBiome(x, z, biome); world.setBiome(x, z, biome);
@ -294,11 +314,11 @@ public class BukkitUtil extends WorldUtil {
} }
@Override @Override
public PlotBlock getBlock(final Location loc) { public PlotBlock getBlock(Location location) {
final World world = getWorld(loc.getWorld()); World world = getWorld(location.getWorld());
final Block block = world.getBlockAt(loc.getX(), loc.getY(), loc.getZ()); Block block = world.getBlockAt(location.getX(), location.getY(), location.getZ());
if (block == null) { if (block == null) {
return new PlotBlock((short) 0, (byte) 0); return PlotBlock.EVERYTHING;
} }
return new PlotBlock((short) block.getTypeId(), block.getData()); return new PlotBlock((short) block.getTypeId(), block.getData());
} }

View File

@ -1,25 +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.plotsquared.bukkit.util; package com.plotsquared.bukkit.util;
import com.intellectualcrafters.plot.PS;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.scheduler.BukkitTask;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
@ -41,109 +28,74 @@ import java.util.UUID;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.zip.GZIPOutputStream; import java.util.zip.GZIPOutputStream;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.scheduler.BukkitTask;
import com.intellectualcrafters.configuration.InvalidConfigurationException;
import com.intellectualcrafters.configuration.file.YamlConfiguration;
import com.intellectualcrafters.plot.PS;
public class Metrics { public class Metrics {
/** /**
* The current revision number * The current revision number.
*/ */
private final static int REVISION = 7; private static final int REVISION = 7;
/** /**
* The base url of the metrics domain * The base url of the metrics domain.
*/ */
private static final String BASE_URL = "http://report.mcstats.org"; 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"; 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; private static final int PING_INTERVAL = 15;
/** /**
* The plugin this metrics submits for * The plugin this metrics submits for.
*/ */
private final Plugin plugin; private final Plugin plugin;
/** /**
* All of the custom graphs to submit to metrics * All of the custom graphs to submit to metrics.
*/ */
private final Set<Graph> graphs = Collections.synchronizedSet(new HashSet<Graph>()); private final Set<Graph> graphs = Collections.synchronizedSet(new HashSet<Graph>());
/** /**
* The plugin configuration file * Unique server id.
*/
private final YamlConfiguration configuration;
/**
* The plugin configuration file
*/
private final File configurationFile;
/**
* Unique server id
*/ */
private final String guid; private final String guid;
/** /**
* Debug mode * Debug mode.
*/ */
private final boolean debug; private final boolean debug;
/** /**
* Lock for synchronization * The scheduled task.
*/
private final Object optOutLock = new Object();
/**
* The scheduled task
*/ */
private volatile BukkitTask task = null; private volatile BukkitTask task = null;
public Metrics(final Plugin plugin) throws IOException { public Metrics(Plugin plugin) {
if (plugin == null) { if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null"); throw new IllegalArgumentException("Plugin cannot be null");
} }
this.plugin = plugin; this.plugin = plugin;
// load the config this.guid = UUID.randomUUID().toString();
configurationFile = getConfigFile(); this.debug = false;
configuration = YamlConfiguration.loadConfiguration(configurationFile);
// add some defaults
configuration.addDefault("opt-out", false);
configuration.addDefault("guid", UUID.randomUUID().toString());
configuration.addDefault("debug", false);
// Do we need to create the file?
if (configuration.get("guid", null) == null) {
configuration.options().header("http://mcstats.org").copyDefaults(true);
configuration.save(configurationFile);
}
// Load the guid then
guid = configuration.getString("guid");
debug = configuration.getBoolean("debug", false);
} }
/** /**
* GZip compress a string of bytes * GZip compress a string of bytes.
* *
* @param input * @param input
* *
* @return byte[] the file as a byte array * @return byte[] the file as a byte array
*/ */
public static byte[] gzip(final String input) { public static byte[] gzip(String input) {
final ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = null; GZIPOutputStream gzos = null;
try { try {
gzos = new GZIPOutputStream(baos); gzos = new GZIPOutputStream(baos);
gzos.write(input.getBytes("UTF-8")); gzos.write(input.getBytes("UTF-8"));
} catch (final IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
if (gzos != null) { if (gzos != null) {
try { try {
gzos.close(); gzos.close();
} catch (final IOException ignore) { } catch (IOException ignore) {
} }
} }
} }
@ -157,16 +109,15 @@ public class Metrics {
* @param key * @param key
* @param value * @param value
* *
* @throws UnsupportedEncodingException
*/ */
private static void appendJSONPair(final StringBuilder json, final String key, final String value) { private static void appendJSONPair(StringBuilder json, String key, String value) {
boolean isValueNumeric = false; boolean isValueNumeric = false;
try { try {
if (value.equals("0") || !value.endsWith("0")) { if (value.equals("0") || !value.endsWith("0")) {
Double.parseDouble(value); Double.parseDouble(value);
isValueNumeric = true; isValueNumeric = true;
} }
} catch (final NumberFormatException e) { } catch (NumberFormatException e) {
isValueNumeric = false; isValueNumeric = false;
} }
if (json.charAt(json.length() - 1) != '{') { if (json.charAt(json.length() - 1) != '{') {
@ -188,11 +139,11 @@ public class Metrics {
* *
* @return String * @return String
*/ */
private static String escapeJSON(final String text) { private static String escapeJSON(String text) {
final StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
builder.append('"'); builder.append('"');
for (int index = 0; index < text.length(); index++) { for (int index = 0; index < text.length(); index++) {
final char chr = text.charAt(index); char chr = text.charAt(index);
switch (chr) { switch (chr) {
case '"': case '"':
case '\\': case '\\':
@ -213,7 +164,7 @@ public class Metrics {
break; break;
default: default:
if (chr < ' ') { if (chr < ' ') {
final String t = "000" + Integer.toHexString(chr); String t = "000" + Integer.toHexString(chr);
builder.append("\\u" + t.substring(t.length() - 4)); builder.append("\\u" + t.substring(t.length() - 4));
} else { } else {
builder.append(chr); builder.append(chr);
@ -232,7 +183,7 @@ public class Metrics {
* *
* @return the encoded text, as UTF-8 * @return the encoded text, as UTF-8
*/ */
private static String urlEncode(final String text) throws UnsupportedEncodingException { private static String urlEncode(String text) throws UnsupportedEncodingException {
return URLEncoder.encode(text, "UTF-8"); return URLEncoder.encode(text, "UTF-8");
} }
@ -244,14 +195,14 @@ public class Metrics {
* *
* @return Graph object created. Will never return NULL under normal circumstances unless bad parameters are given * @return Graph object created. Will never return NULL under normal circumstances unless bad parameters are given
*/ */
public Graph createGraph(final String name) { public Graph createGraph(String name) {
if (name == null) { if (name == null) {
throw new IllegalArgumentException("Graph name cannot be null"); throw new IllegalArgumentException("Graph name cannot be null");
} }
// Construct the graph object // Construct the graph object
final Graph graph = new Graph(name); Graph graph = new Graph(name);
// Now we can add our graph // Now we can add our graph
graphs.add(graph); this.graphs.add(graph);
// and return back // and return back
return graph; return graph;
} }
@ -261,11 +212,11 @@ public class Metrics {
* *
* @param graph The name of the graph * @param graph The name of the graph
*/ */
public void addGraph(final Graph graph) { public void addGraph(Graph graph) {
if (graph == null) { if (graph == null) {
throw new IllegalArgumentException("Graph cannot be null"); throw new IllegalArgumentException("Graph cannot be null");
} }
graphs.add(graph); this.graphs.add(graph);
} }
/** /**
@ -276,86 +227,31 @@ public class Metrics {
* @return True if statistics measuring is running, otherwise false. * @return True if statistics measuring is running, otherwise false.
*/ */
public boolean start() { public boolean start() {
synchronized (optOutLock) { // Is metrics already running?
// Did we opt out? if (this.task != null) {
if (isOptOut()) {
return false;
}
// Is metrics already running?
if (task != null) {
return true;
}
// Begin hitting the server with glorious data
task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() {
private boolean firstPost = true;
@Override
public void run() {
try {
// This has to be synchronized or it can collide
// with
// the disable method.
synchronized (optOutLock) {
// Disable Task, if it is running and the
// server
// owner decided to opt-out
if (isOptOut() && task != null) {
task.cancel();
task = null;
// Tell all plotters to stop gathering
// information.
for (final Graph graph : graphs) {
graph.onOptOut();
}
}
}
// We use the inverse of firstPost because if it
// is the
// first time we are posting,
// it is not a interval ping, so it evaluates to
// FALSE
// Each time thereafter it will evaluate to
// TRUE, i.e
// PING!
postPlugin(!firstPost);
// After the first post we set firstPost to
// false
// Each post thereafter will be a ping
firstPost = false;
} catch (final IOException e) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage());
}
}
}
}, 0, PING_INTERVAL * 1200);
return true; return true;
} }
} // Begin hitting the server with glorious data
this.task = this.plugin.getServer().getScheduler().runTaskTimerAsynchronously(this.plugin, new Runnable() {
private boolean firstPost = true;
/** @Override
* Has the server owner denied plugin metrics? public void run() {
* try {
* @return true if metrics should be opted out of it postPlugin(!this.firstPost);
*/ // After the first post we set firstPost to
public boolean isOptOut() { // false
synchronized (optOutLock) { // Each post thereafter will be a ping
try { this.firstPost = false;
// Reload the metrics file } catch (IOException e) {
configuration.load(getConfigFile()); e.printStackTrace();
} catch (final IOException ex) { if (Metrics.this.debug) {
if (debug) { Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage());
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); }
} }
return true;
} catch (final InvalidConfigurationException ex) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
}
return true;
} }
return configuration.getBoolean("opt-out", false); }, 0, PING_INTERVAL * 1200);
} return true;
} }
/** /**
@ -363,48 +259,28 @@ public class Metrics {
* *
* @throws java.io.IOException * @throws java.io.IOException
*/ */
public void enable() throws IOException { public void enable() {
// This has to be synchronized or it can collide with the check in the // Enable Task, if it is not running
// task. if (this.task == null) {
synchronized (optOutLock) { start();
// Check if the server owner has already set opt-out, if not, set
// it.
if (isOptOut()) {
configuration.set("opt-out", false);
configuration.save(configurationFile);
}
// Enable Task, if it is not running
if (task == null) {
start();
}
} }
} }
/** /**
* Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task. * Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task.
* *
* @throws java.io.IOException
*/ */
public void disable() throws IOException { public void disable() {
// This has to be synchronized or it can collide with the check in the // Disable Task, if it is running
// task. if (this.task != null) {
synchronized (optOutLock) { this.task.cancel();
// Check if the server owner has already set opt-out, if not, set this.task = null;
// it.
if (!isOptOut()) {
configuration.set("opt-out", true);
configuration.save(configurationFile);
}
// Disable Task, if it is running
if (task != null) {
task.cancel();
task = null;
}
} }
} }
/** /**
* Gets the File object of the config file that should be used to store data such as the GUID and opt-out status * 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 * @return the File object for the config file
*/ */
@ -415,26 +291,21 @@ public class Metrics {
// plugin.getDataFolder() => base/plugins/PluginA/ // plugin.getDataFolder() => base/plugins/PluginA/
// pluginsFolder => base/plugins/ // pluginsFolder => base/plugins/
// The base is not necessarily relative to the startup directory. // The base is not necessarily relative to the startup directory.
final File pluginsFolder = plugin.getDataFolder().getParentFile(); File pluginsFolder = this.plugin.getDataFolder().getParentFile();
// return => base/plugins/PluginMetrics/config.yml // return => base/plugins/PluginMetrics/config.yml
return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml"); return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml");
} }
/** /**
* Generic method that posts a plugin to the metrics website * Generic method that posts a plugin to the metrics website.
*/ */
private void postPlugin(final boolean isPing) throws IOException { private void postPlugin(boolean isPing) throws IOException {
// Server software specific section // Server software specific section
final PluginDescriptionFile description = plugin.getDescription(); PluginDescriptionFile description = this.plugin.getDescription();
final String pluginName = description.getName(); String pluginName = description.getName();
final boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE if online mode is enabled
// if String pluginVersion = description.getVersion();
// online String serverVersion = Bukkit.getVersion();
// mode
// is
// enabled
final String pluginVersion = description.getVersion();
final String serverVersion = Bukkit.getVersion();
int playersOnline = 0; int playersOnline = 0;
try { try {
if (Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).getReturnType() == Collection.class) { if (Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).getReturnType() == Collection.class) {
@ -443,24 +314,24 @@ public class Metrics {
playersOnline = ((Player[]) Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).invoke(null)).length; playersOnline = ((Player[]) Bukkit.class.getMethod("getOnlinePlayers", new Class<?>[0]).invoke(null)).length;
} }
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) { } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
ex.printStackTrace();
} }
// END server software specific section -- all code below does not use // END server software specific section -- all code below does not use
// any code outside of this class / Java // any code outside of this class / Java
// Construct the post data // Construct the post data
final StringBuilder json = new StringBuilder(1024); StringBuilder json = new StringBuilder(1024);
json.append('{'); json.append('{');
// The plugin's description file containg all of the plugin data such as // The plugin's description file containing all of the plugin data such as name, version, author, etc
// name, version, author, etc appendJSONPair(json, "guid", this.guid);
appendJSONPair(json, "guid", guid);
appendJSONPair(json, "plugin_version", pluginVersion); appendJSONPair(json, "plugin_version", pluginVersion);
appendJSONPair(json, "server_version", serverVersion); appendJSONPair(json, "server_version", serverVersion);
appendJSONPair(json, "players_online", Integer.toString(playersOnline)); appendJSONPair(json, "players_online", Integer.toString(playersOnline));
// New data as of R6 // New data as of R6
final String osname = System.getProperty("os.name"); String osname = System.getProperty("os.name");
String osarch = System.getProperty("os.arch"); String osarch = System.getProperty("os.arch");
final String osversion = System.getProperty("os.version"); String osversion = System.getProperty("os.version");
final String java_version = System.getProperty("java.version"); String java_version = System.getProperty("java.version");
final int coreCount = Runtime.getRuntime().availableProcessors(); int coreCount = Runtime.getRuntime().availableProcessors();
// normalize os arch .. amd64 -> x86_64 // normalize os arch .. amd64 -> x86_64
if (osarch.equals("amd64")) { if (osarch.equals("amd64")) {
osarch = "x86_64"; osarch = "x86_64";
@ -475,8 +346,8 @@ public class Metrics {
if (isPing) { if (isPing) {
appendJSONPair(json, "ping", "1"); appendJSONPair(json, "ping", "1");
} }
if (!graphs.isEmpty()) { if (!this.graphs.isEmpty()) {
synchronized (graphs) { synchronized (this.graphs) {
json.append(','); json.append(',');
json.append('"'); json.append('"');
json.append("graphs"); json.append("graphs");
@ -484,10 +355,10 @@ public class Metrics {
json.append(':'); json.append(':');
json.append('{'); json.append('{');
boolean firstGraph = true; boolean firstGraph = true;
for (final Graph graph : graphs) { for (Graph graph : this.graphs) {
final StringBuilder graphJson = new StringBuilder(); StringBuilder graphJson = new StringBuilder();
graphJson.append('{'); graphJson.append('{');
for (final Plotter plotter : graph.getPlotters()) { for (Plotter plotter : graph.getPlotters()) {
appendJSONPair(graphJson, plotter.getColumnName(), Integer.toString(plotter.getValue())); appendJSONPair(graphJson, plotter.getColumnName(), Integer.toString(plotter.getValue()));
} }
graphJson.append('}'); graphJson.append('}');
@ -505,7 +376,7 @@ public class Metrics {
// close json // close json
json.append('}'); json.append('}');
// Create the url // Create the url
final URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName))); URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName)));
// Connect to the website // Connect to the website
URLConnection connection; URLConnection connection;
// Mineshafter creates a socks proxy, so we can safely bypass it // Mineshafter creates a socks proxy, so we can safely bypass it
@ -515,8 +386,8 @@ public class Metrics {
} else { } else {
connection = url.openConnection(); connection = url.openConnection();
} }
final byte[] uncompressed = json.toString().getBytes(); byte[] uncompressed = json.toString().getBytes();
final byte[] compressed = gzip(json.toString()); byte[] compressed = gzip(json.toString());
// Headers // Headers
connection.addRequestProperty("User-Agent", "MCStats/" + REVISION); connection.addRequestProperty("User-Agent", "MCStats/" + REVISION);
connection.addRequestProperty("Content-Type", "application/json"); connection.addRequestProperty("Content-Type", "application/json");
@ -525,36 +396,44 @@ public class Metrics {
connection.addRequestProperty("Accept", "application/json"); connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close"); connection.addRequestProperty("Connection", "close");
connection.setDoOutput(true); connection.setDoOutput(true);
if (debug) { if (this.debug) {
PS.debug("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" + compressed.length); PS.debug("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" + compressed.length);
} }
// Write the data try {
String response; try (OutputStream os = connection.getOutputStream()) {
try (OutputStream os = connection.getOutputStream(); os.write(compressed);
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { os.flush();
os.write(compressed);
os.flush();
// Now read the response
response = reader.readLine();
}
if (response == null || response.startsWith("ERR") || response.startsWith("7")) {
if (response == null) {
response = "null";
} else if (response.startsWith("7")) {
response = response.substring(response.startsWith("7,") ? 2 : 1);
} }
throw new IOException(response); String response;
} else { try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
// Is this the first update this hour? response = reader.readLine();
if ("1".equals(response) || response.contains("This is your first update this hour")) { if (this.debug) {
synchronized (graphs) { PS.debug("[Metrics] Response for " + pluginName + ": " + response);
for (final Graph graph : graphs) { }
for (final Plotter plotter : graph.getPlotters()) { }
plotter.reset(); if (response == null || response.startsWith("ERR") || response.startsWith("7")) {
if (response == null) {
response = "null";
} else if (response.startsWith("7")) {
response = response.substring(response.startsWith("7,") ? 2 : 1);
}
throw new IOException(response);
} else {
// Is this the first update this hour?
if ("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();
}
} }
} }
@ -587,7 +466,7 @@ public class Metrics {
*/ */
private final Set<Plotter> plotters = new LinkedHashSet<>(); private final Set<Plotter> plotters = new LinkedHashSet<>();
private Graph(final String name) { private Graph(String name) {
this.name = name; this.name = name;
} }
@ -597,7 +476,7 @@ public class Metrics {
* @return the Graph's name * @return the Graph's name
*/ */
public String getName() { public String getName() {
return name; return this.name;
} }
/** /**
@ -605,8 +484,8 @@ public class Metrics {
* *
* @param plotter the plotter to add to the graph * @param plotter the plotter to add to the graph
*/ */
public void addPlotter(final Plotter plotter) { public void addPlotter(Plotter plotter) {
plotters.add(plotter); this.plotters.add(plotter);
} }
/** /**
@ -614,8 +493,8 @@ public class Metrics {
* *
* @param plotter the plotter to remove from the graph * @param plotter the plotter to remove from the graph
*/ */
public void removePlotter(final Plotter plotter) { public void removePlotter(Plotter plotter) {
plotters.remove(plotter); this.plotters.remove(plotter);
} }
/** /**
@ -624,21 +503,21 @@ public class Metrics {
* @return an unmodifiable {@link java.util.Set} of the plotter objects * @return an unmodifiable {@link java.util.Set} of the plotter objects
*/ */
public Set<Plotter> getPlotters() { public Set<Plotter> getPlotters() {
return Collections.unmodifiableSet(plotters); return Collections.unmodifiableSet(this.plotters);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return name.hashCode(); return this.name.hashCode();
} }
@Override @Override
public boolean equals(final Object object) { public boolean equals(Object object) {
if (!(object instanceof Graph)) { if (!(object instanceof Graph)) {
return false; return false;
} }
final Graph graph = (Graph) object; Graph graph = (Graph) object;
return graph.name.equals(name); return graph.name.equals(this.name);
} }
/** /**
@ -651,7 +530,7 @@ public class Metrics {
/** /**
* Interface used to collect custom data for a plugin * Interface used to collect custom data for a plugin
*/ */
public static abstract class Plotter { public abstract static class Plotter {
/** /**
* The plot's name * The plot's name
@ -670,7 +549,7 @@ public class Metrics {
* *
* @param name the name of the plotter to use, which will show up on the website * @param name the name of the plotter to use, which will show up on the website
*/ */
public Plotter(final String name) { public Plotter(String name) {
this.name = name; this.name = name;
} }
@ -689,7 +568,7 @@ public class Metrics {
* @return the plotted point's column name * @return the plotted point's column name
*/ */
public String getColumnName() { public String getColumnName() {
return name; return this.name;
} }
/** /**
@ -704,12 +583,12 @@ public class Metrics {
} }
@Override @Override
public boolean equals(final Object object) { public boolean equals(Object object) {
if (!(object instanceof Plotter)) { if (!(object instanceof Plotter)) {
return false; return false;
} }
final Plotter plotter = (Plotter) object; Plotter plotter = (Plotter) object;
return plotter.name.equals(name) && plotter.getValue() == getValue(); return plotter.name.equals(this.name) && plotter.getValue() == getValue();
} }
} }
} }

View File

@ -6,9 +6,9 @@ import com.google.common.collect.HashBiMap;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.common.collect.MapMaker; import com.google.common.collect.MapMaker;
import com.google.common.io.ByteSink; import com.google.common.io.ByteSink;
import com.google.common.io.ByteSource;
import com.google.common.io.Closeables; import com.google.common.io.Closeables;
import com.google.common.io.Files; import com.google.common.io.Files;
import com.google.common.io.InputSupplier;
import com.google.common.primitives.Primitives; import com.google.common.primitives.Primitives;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Material; import org.bukkit.Material;
@ -63,39 +63,43 @@ public class NbtFactory {
// Loading/saving compounds // Loading/saving compounds
private LoadCompoundMethod LOAD_COMPOUND; private LoadCompoundMethod LOAD_COMPOUND;
private Method SAVE_COMPOUND; private Method SAVE_COMPOUND;
/** /**
* Construct an instance of the NBT factory by deducing the class of NBTBase. * Construct an instance of the NBT factory by deducing the class of NBTBase.
*/ */
private NbtFactory() { private NbtFactory() {
if (BASE_CLASS == null) { if (this.BASE_CLASS == null) {
try { try {
// Keep in mind that I do use hard-coded field names - but it's okay as long as we're dealing // Keep in mind that I do use hard-coded field names - but it's okay as long as we're dealing
// with CraftBukkit or its derivatives. This does not work in MCPC+ however. // with CraftBukkit or its derivatives. This does not work in MCPC+ however.
final ClassLoader loader = NbtFactory.class.getClassLoader(); ClassLoader loader = NbtFactory.class.getClassLoader();
final String packageName = getPackageName(); String packageName = getPackageName();
final Class<?> offlinePlayer = loader.loadClass(packageName + ".CraftOfflinePlayer"); Class<?> offlinePlayer = loader.loadClass(packageName + ".CraftOfflinePlayer");
// Prepare NBT // Prepare NBT
COMPOUND_CLASS = getMethod(0, Modifier.STATIC, offlinePlayer, "getData").getReturnType(); this.COMPOUND_CLASS = getMethod(0, Modifier.STATIC, offlinePlayer, "getData").getReturnType();
BASE_CLASS = COMPOUND_CLASS.getSuperclass(); this.BASE_CLASS = this.COMPOUND_CLASS.getSuperclass();
NBT_GET_TYPE = getMethod(0, Modifier.STATIC, BASE_CLASS, "getTypeId"); this.NBT_GET_TYPE = getMethod(0, Modifier.STATIC, this.BASE_CLASS, "getTypeId");
NBT_CREATE_TAG = getMethod(Modifier.STATIC, 0, BASE_CLASS, "createTag", byte.class); this.NBT_CREATE_TAG = getMethod(Modifier.STATIC, 0, this.BASE_CLASS, "createTag", byte.class);
// Prepare CraftItemStack // Prepare CraftItemStack
CRAFT_STACK = loader.loadClass(packageName + ".inventory.CraftItemStack"); this.CRAFT_STACK = loader.loadClass(packageName + ".inventory.CraftItemStack");
CRAFT_HANDLE = getField(null, CRAFT_STACK, "handle"); this.CRAFT_HANDLE = getField(null, this.CRAFT_STACK, "handle");
STACK_TAG = getField(null, CRAFT_HANDLE.getType(), "tag"); this.STACK_TAG = getField(null, this.CRAFT_HANDLE.getType(), "tag");
// Loading/saving // Loading/saving
final String nmsPackage = BASE_CLASS.getPackage().getName(); String nmsPackage = this.BASE_CLASS.getPackage().getName();
initializeNMS(loader, nmsPackage); initializeNMS(loader, nmsPackage);
LOAD_COMPOUND = READ_LIMITER_CLASS != null ? new LoadMethodSkinUpdate(STREAM_TOOLS, READ_LIMITER_CLASS) : if (this.READ_LIMITER_CLASS != null) {
new LoadMethodWorldUpdate(STREAM_TOOLS); this.LOAD_COMPOUND = new LoadMethodSkinUpdate(this.STREAM_TOOLS, this.READ_LIMITER_CLASS);
SAVE_COMPOUND = getMethod(Modifier.STATIC, 0, STREAM_TOOLS, null, BASE_CLASS, DataOutput.class); } else {
this.LOAD_COMPOUND = new LoadMethodWorldUpdate(this.STREAM_TOOLS);
}
this.SAVE_COMPOUND = getMethod(Modifier.STATIC, 0, this.STREAM_TOOLS, null, this.BASE_CLASS, DataOutput.class);
} catch (final ClassNotFoundException e) { } catch (ClassNotFoundException e) {
throw new IllegalStateException("Unable to find offline player.", e); throw new IllegalStateException("Unable to find offline player.", e);
} }
} }
@ -116,7 +120,7 @@ public class NbtFactory {
* Construct a new NBT list of an unspecified type. * Construct a new NBT list of an unspecified type.
* @return The NBT list. * @return The NBT list.
*/ */
public static NbtList createList(final Object... content) { public static NbtList createList(Object... content) {
return createList(Arrays.asList(content)); return createList(Arrays.asList(content));
} }
@ -124,11 +128,11 @@ public class NbtFactory {
* Construct a new NBT list of an unspecified type. * Construct a new NBT list of an unspecified type.
* @return The NBT list. * @return The NBT list.
*/ */
public static NbtList createList(final Iterable<? extends Object> iterable) { public static NbtList createList(Iterable<? extends Object> iterable) {
final NbtList list = get().new NbtList(INSTANCE.createNbtTag(NbtType.TAG_LIST, null)); NbtList list = get().new NbtList(INSTANCE.createNbtTag(NbtType.TAG_LIST, null));
// Add the content as well // Add the content as well
for (final Object obj : iterable) { for (Object obj : iterable) {
list.add(obj); list.add(obj);
} }
return list; return list;
@ -136,7 +140,6 @@ public class NbtFactory {
/** /**
* Construct a new NBT compound. * Construct a new NBT compound.
* <p>
* *
* @return The NBT compound. * @return The NBT compound.
*/ */
@ -149,29 +152,33 @@ public class NbtFactory {
* @param nmsList - the NBT list. * @param nmsList - the NBT list.
* @return The wrapper. * @return The wrapper.
*/ */
public static NbtList fromList(final Object nmsList) { public static NbtList fromList(Object nmsList) {
return get().new NbtList(nmsList); return get().new NbtList(nmsList);
} }
/** /**
* Load the content of a file from a stream. * Load the content of a file from a stream.
* <p> *
* Use {@link Files#newInputStreamSupplier(java.io.File)} to provide a stream from a file. * Use {@link Files#newInputStreamSupplier(java.io.File)} to provide a stream from a file.
* @param stream - the stream supplier. * @param stream - the stream supplier.
* @param option - whether or not to decompress the input stream. * @param option - whether or not to decompress the input stream.
* @return The decoded NBT compound. * @return The decoded NBT compound.
* @throws IOException If anything went wrong. * @throws IOException If anything went wrong.
*/ */
public static NbtCompound fromStream(final ByteSource stream, final StreamOptions option) throws IOException { public static NbtCompound fromStream(InputSupplier<? extends InputStream> stream, StreamOptions option) throws IOException {
InputStream input = null; InputStream input = null;
DataInputStream data = null; DataInputStream data = null;
boolean suppress = true; boolean suppress = true;
try { try {
input = stream.openStream(); input = stream.getInput();
data = new DataInputStream(new BufferedInputStream(option == StreamOptions.GZIP_COMPRESSION ? new GZIPInputStream(input) : input)); if (option == StreamOptions.GZIP_COMPRESSION) {
data = new DataInputStream(new BufferedInputStream(new GZIPInputStream(input)));
} else {
data = new DataInputStream(new BufferedInputStream(input));
}
final NbtCompound result = fromCompound(get().LOAD_COMPOUND.loadNbt(data)); NbtCompound result = fromCompound(get().LOAD_COMPOUND.loadNbt(data));
suppress = false; suppress = false;
return result; return result;
@ -186,14 +193,14 @@ public class NbtFactory {
/** /**
* Save the content of a NBT compound to a stream. * 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. * Use {@link Files#newOutputStreamSupplier(java.io.File)} to provide a stream supplier to a file.
* @param source - the NBT compound to save. * @param source - the NBT compound to save.
* @param stream - the stream. * @param stream - the stream.
* @param option - whether or not to compress the output. * @param option - whether or not to compress the output.
* @throws IOException If anything went wrong. * @throws IOException If anything went wrong.
*/ */
public static void saveStream(final NbtCompound source, final ByteSink stream, final StreamOptions option) throws IOException { public static void saveStream(NbtCompound source, ByteSink stream, StreamOptions option) throws IOException {
OutputStream output = null; OutputStream output = null;
DataOutputStream data = null; DataOutputStream data = null;
boolean suppress = true; boolean suppress = true;
@ -216,10 +223,10 @@ public class NbtFactory {
/** /**
* Construct a new NBT wrapper from a compound. * Construct a new NBT wrapper from a compound.
* @param nmsCompound - the NBT compund. * @param nmsCompound - the NBT compound.
* @return The wrapper. * @return The wrapper.
*/ */
public static NbtCompound fromCompound(final Object nmsCompound) { public static NbtCompound fromCompound(Object nmsCompound) {
return get().new NbtCompound(nmsCompound); return get().new NbtCompound(nmsCompound);
} }
@ -230,9 +237,9 @@ public class NbtFactory {
* @param compound - the new NBT compound, or NULL to remove it. * @param compound - the new NBT compound, or NULL to remove it.
* @throws IllegalArgumentException If the stack is not a CraftItemStack, or it represents air. * @throws IllegalArgumentException If the stack is not a CraftItemStack, or it represents air.
*/ */
public static void setItemTag(final ItemStack stack, final NbtCompound compound) { public static void setItemTag(ItemStack stack, NbtCompound compound) {
checkItemStack(stack); checkItemStack(stack);
final Object nms = getFieldValue(get().CRAFT_HANDLE, stack); Object nms = getFieldValue(get().CRAFT_HANDLE, stack);
// Now update the tag compound // Now update the tag compound
setFieldValue(get().STACK_TAG, nms, compound.getHandle()); setFieldValue(get().STACK_TAG, nms, compound.getHandle());
@ -240,21 +247,21 @@ public class NbtFactory {
/** /**
* Construct a wrapper for an NBT tag stored (in memory) in an item stack. This is where * 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. * material, damage value or count.
* <p> * <p>
* The item stack must be a wrapper for a CraftItemStack. * The item stack must be a wrapper for a CraftItemStack.
* @param stack - the item stack. * @param stack - the item stack.
* @return A wrapper for its NBT tag. * @return A wrapper for its NBT tag.
*/ */
public static NbtCompound fromItemTag(final ItemStack stack) { public static NbtCompound fromItemTag(ItemStack stack) {
checkItemStack(stack); checkItemStack(stack);
final Object nms = getFieldValue(get().CRAFT_HANDLE, stack); Object nms = getFieldValue(get().CRAFT_HANDLE, stack);
final Object tag = getFieldValue(get().STACK_TAG, nms); Object tag = getFieldValue(get().STACK_TAG, nms);
// Create the tag if it doesn't exist // Create the tag if it doesn't exist
if (tag == null) { if (tag == null) {
final NbtCompound compound = createCompound(); NbtCompound compound = createCompound();
setItemTag(stack, compound); setItemTag(stack, compound);
return compound; return compound;
} }
@ -266,17 +273,17 @@ public class NbtFactory {
* @param stack - the stack to convert. * @param stack - the stack to convert.
* @return The CraftItemStack version. * @return The CraftItemStack version.
*/ */
public static ItemStack getCraftItemStack(final ItemStack stack) { public static ItemStack getCraftItemStack(ItemStack stack) {
// Any need to convert? // Any need to convert?
if ((stack == null) || get().CRAFT_STACK.isAssignableFrom(stack.getClass())) { if ((stack == null) || get().CRAFT_STACK.isAssignableFrom(stack.getClass())) {
return stack; return stack;
} }
try { try {
// Call the private constructor // Call the private constructor
final Constructor<?> caller = INSTANCE.CRAFT_STACK.getDeclaredConstructor(ItemStack.class); Constructor<?> caller = INSTANCE.CRAFT_STACK.getDeclaredConstructor(ItemStack.class);
caller.setAccessible(true); caller.setAccessible(true);
return (ItemStack) caller.newInstance(stack); return (ItemStack) caller.newInstance(stack);
} catch (final Exception e) { } catch (Exception e) {
throw new IllegalStateException("Unable to convert " + stack + " + to a CraftItemStack."); throw new IllegalStateException("Unable to convert " + stack + " + to a CraftItemStack.");
} }
} }
@ -285,7 +292,7 @@ public class NbtFactory {
* Ensure that the given stack can store arbitrary NBT information. * Ensure that the given stack can store arbitrary NBT information.
* @param stack - the stack to check. * @param stack - the stack to check.
*/ */
private static void checkItemStack(final ItemStack stack) { private static void checkItemStack(ItemStack stack) {
if (stack == null) { if (stack == null) {
throw new IllegalArgumentException("Stack cannot be NULL."); throw new IllegalArgumentException("Stack cannot be NULL.");
} }
@ -304,32 +311,32 @@ public class NbtFactory {
* @param params - the parameters to supply. * @param params - the parameters to supply.
* @return The result of the method. * @return The result of the method.
*/ */
private static Object invokeMethod(final Method method, final Object target, final Object... params) { private static Object invokeMethod(Method method, Object target, Object... params) {
try { try {
return method.invoke(target, params); return method.invoke(target, params);
} catch (final Exception e) { } catch (Exception e) {
throw new RuntimeException("Unable to invoke method " + method + " for " + target, e); throw new RuntimeException("Unable to invoke method " + method + " for " + target, e);
} }
} }
private static void setFieldValue(final Field field, final Object target, final Object value) { private static void setFieldValue(Field field, Object target, Object value) {
try { try {
field.set(target, value); field.set(target, value);
} catch (final Exception e) { } catch (Exception e) {
throw new RuntimeException("Unable to set " + field + " for " + target, e); throw new RuntimeException("Unable to set " + field + " for " + target, e);
} }
} }
private static Object getFieldValue(final Field field, final Object target) { private static Object getFieldValue(Field field, Object target) {
try { try {
return field.get(target); return field.get(target);
} catch (final Exception e) { } catch (Exception e) {
throw new RuntimeException("Unable to retrieve " + field + " for " + target, 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 requireMod - modifiers that are required.
* @param bannedMod - modifiers that are banned. * @param bannedMod - modifiers that are banned.
* @param clazz - a class to start with. * @param clazz - a class to start with.
@ -338,9 +345,9 @@ public class NbtFactory {
* @return The first method by this name. * @return The first method by this name.
* @throws IllegalStateException If we cannot find this method. * @throws IllegalStateException If we cannot find this method.
*/ */
private static Method getMethod(final int requireMod, final int bannedMod, final Class<?> clazz, final String methodName, private static Method getMethod(int requireMod, int bannedMod, Class<?> clazz, String methodName,
final Class<?>... params) { Class<?>... params) {
for (final Method method : clazz.getDeclaredMethods()) { for (Method method : clazz.getDeclaredMethods()) {
// Limitation: Doesn't handle overloads // Limitation: Doesn't handle overloads
if (((method.getModifiers() & requireMod) == requireMod) if (((method.getModifiers() & requireMod) == requireMod)
&& ((method.getModifiers() & bannedMod) == 0) && ((method.getModifiers() & bannedMod) == 0)
@ -359,19 +366,19 @@ 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 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 clazz - an optional class to start with, or NULL to deduce it from instance.
* @param fieldName - the field name. * @param fieldName - the field name.
* @return The first field by this name. * @return The first field by this name.
* @throws IllegalStateException If we cannot find this field. * @throws IllegalStateException If we cannot find this field.
*/ */
private static Field getField(final Object instance, Class<?> clazz, final String fieldName) { private static Field getField(Object instance, Class<?> clazz, String fieldName) {
if (clazz == null) { if (clazz == null) {
clazz = instance.getClass(); clazz = instance.getClass();
} }
// Ignore access rules // Ignore access rules
for (final Field field : clazz.getDeclaredFields()) { for (Field field : clazz.getDeclaredFields()) {
if (field.getName().equals(fieldName)) { if (field.getName().equals(fieldName)) {
field.setAccessible(true); field.setAccessible(true);
return field; return field;
@ -384,18 +391,18 @@ public class NbtFactory {
throw new IllegalStateException("Unable to find field " + fieldName + " in " + instance); throw new IllegalStateException("Unable to find field " + fieldName + " in " + instance);
} }
private void initializeNMS(final ClassLoader loader, final String nmsPackage) { private void initializeNMS(ClassLoader loader, String nmsPackage) {
try { try {
STREAM_TOOLS = loader.loadClass(nmsPackage + ".NBTCompressedStreamTools"); this.STREAM_TOOLS = loader.loadClass(nmsPackage + ".NBTCompressedStreamTools");
READ_LIMITER_CLASS = loader.loadClass(nmsPackage + ".NBTReadLimiter"); this.READ_LIMITER_CLASS = loader.loadClass(nmsPackage + ".NBTReadLimiter");
} catch (final ClassNotFoundException e) { } catch (ClassNotFoundException e) {
// Ignore - we will detect this later // Ignore - we will detect this later
} }
} }
private String getPackageName() { private String getPackageName() {
final Server server = Bukkit.getServer(); Server server = Bukkit.getServer();
final String name = server != null ? server.getClass().getPackage().getName() : null; String name = server != null ? server.getClass().getPackage().getName() : null;
if ((name != null) && name.contains("craftbukkit")) { if ((name != null) && name.contains("craftbukkit")) {
return name; return name;
@ -406,12 +413,12 @@ public class NbtFactory {
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private Map<String, Object> getDataMap(final Object handle) { private Map<String, Object> getDataMap(Object handle) {
return (Map<String, Object>) getFieldValue(getDataField(NbtType.TAG_COMPOUND, handle), handle); return (Map<String, Object>) getFieldValue(getDataField(NbtType.TAG_COMPOUND, handle), handle);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private List<Object> getDataList(final Object handle) { private List<Object> getDataList(Object handle) {
return (List<Object>) getFieldValue(getDataField(NbtType.TAG_LIST, handle), handle); return (List<Object>) getFieldValue(getDataField(NbtType.TAG_LIST, handle), handle);
} }
@ -420,7 +427,7 @@ public class NbtFactory {
* @param value - the value of the element to create. Can be a List or a Map. * @param value - the value of the element to create. Can be a List or a Map.
* @return The NBT element. * @return The NBT element.
*/ */
private Object unwrapValue(final Object value) { private Object unwrapValue(Object value) {
if (value == null) { if (value == null) {
return null; return null;
} }
@ -445,13 +452,13 @@ public class NbtFactory {
* @param nms - the NBT element. * @param nms - the NBT element.
* @return The wrapper equivalent. * @return The wrapper equivalent.
*/ */
private Object wrapNative(final Object nms) { private Object wrapNative(Object nms) {
if (nms == null) { if (nms == null) {
return null; return null;
} }
if (BASE_CLASS.isAssignableFrom(nms.getClass())) { if (this.BASE_CLASS.isAssignableFrom(nms.getClass())) {
final NbtType type = getNbtType(nms); NbtType type = getNbtType(nms);
// Handle the different types // Handle the different types
switch (type) { switch (type) {
@ -472,8 +479,8 @@ public class NbtFactory {
* @param value - the value, or NULL to keep the original value. * @param value - the value, or NULL to keep the original value.
* @return The created tag. * @return The created tag.
*/ */
private Object createNbtTag(final NbtType type, final Object value) { private Object createNbtTag(NbtType type, Object value) {
final Object tag = invokeMethod(NBT_CREATE_TAG, null, (byte) type.id); Object tag = invokeMethod(this.NBT_CREATE_TAG, null, (byte) type.id);
if (value != null) { if (value != null) {
setFieldValue(getDataField(type, tag), tag, value); setFieldValue(getDataField(type, tag), tag, value);
@ -487,11 +494,11 @@ public class NbtFactory {
* @param nms - the NBT class instance. * @param nms - the NBT class instance.
* @return The corresponding field. * @return The corresponding field.
*/ */
private Field getDataField(final NbtType type, final Object nms) { private Field getDataField(NbtType type, Object nms) {
if (DATA_FIELD[type.id] == null) { if (this.DATA_FIELD[type.id] == null) {
DATA_FIELD[type.id] = getField(nms, null, type.getFieldName()); this.DATA_FIELD[type.id] = getField(nms, null, type.getFieldName());
} }
return DATA_FIELD[type.id]; return this.DATA_FIELD[type.id];
} }
/** /**
@ -499,8 +506,8 @@ public class NbtFactory {
* @param nms - the native NBT tag. * @param nms - the native NBT tag.
* @return The corresponding type. * @return The corresponding type.
*/ */
private NbtType getNbtType(final Object nms) { private NbtType getNbtType(Object nms) {
final int type = (Byte) invokeMethod(NBT_GET_TYPE, nms); int type = (Byte) invokeMethod(this.NBT_GET_TYPE, nms);
return NBT_ENUM.get(type); return NBT_ENUM.get(type);
} }
@ -509,8 +516,8 @@ public class NbtFactory {
* @param primitive - the primitive type. * @param primitive - the primitive type.
* @return The corresponding type. * @return The corresponding type.
*/ */
private NbtType getPrimitiveType(final Object primitive) { private NbtType getPrimitiveType(Object primitive) {
final NbtType type = NBT_ENUM.get(NBT_CLASS.inverse().get(Primitives.unwrap(primitive.getClass()))); NbtType type = NBT_ENUM.get(NBT_CLASS.inverse().get(Primitives.unwrap(primitive.getClass())));
// Display the illegal value at least // Display the illegal value at least
if (type == null) { if (type == null) {
@ -544,7 +551,7 @@ public class NbtFactory {
// Unique NBT type // Unique NBT type
public final int id; public final int id;
NbtType(final int id, final Class<?> type) { NbtType(int id, Class<?> type) {
this.id = id; this.id = id;
NBT_CLASS.put(id, type); NBT_CLASS.put(id, type);
NBT_ENUM.put(id, this); NBT_ENUM.put(id, this);
@ -582,9 +589,9 @@ public class NbtFactory {
protected Method staticMethod; protected Method staticMethod;
protected void setMethod(final Method method) { protected void setMethod(Method method) {
staticMethod = method; this.staticMethod = method;
staticMethod.setAccessible(true); this.staticMethod.setAccessible(true);
} }
/** /**
@ -592,7 +599,7 @@ public class NbtFactory {
* @param input - the input stream. * @param input - the input stream.
* @return The loaded NBT compound. * @return The loaded NBT compound.
*/ */
public abstract Object loadNbt(final DataInput input); public abstract Object loadNbt(DataInput input);
} }
/** /**
@ -600,13 +607,13 @@ public class NbtFactory {
*/ */
private static class LoadMethodWorldUpdate extends LoadCompoundMethod { private static class LoadMethodWorldUpdate extends LoadCompoundMethod {
public LoadMethodWorldUpdate(final Class<?> streamClass) { public LoadMethodWorldUpdate(Class<?> streamClass) {
setMethod(getMethod(Modifier.STATIC, 0, streamClass, null, DataInput.class)); setMethod(getMethod(Modifier.STATIC, 0, streamClass, null, DataInput.class));
} }
@Override @Override
public Object loadNbt(final DataInput input) { public Object loadNbt(DataInput input) {
return invokeMethod(staticMethod, null, input); return invokeMethod(this.staticMethod, null, input);
} }
} }
@ -617,15 +624,15 @@ public class NbtFactory {
private Object readLimiter; private Object readLimiter;
public LoadMethodSkinUpdate(final Class<?> streamClass, final Class<?> readLimiterClass) { public LoadMethodSkinUpdate(Class<?> streamClass, Class<?> readLimiterClass) {
setMethod(getMethod(Modifier.STATIC, 0, streamClass, null, DataInput.class, readLimiterClass)); setMethod(getMethod(Modifier.STATIC, 0, streamClass, null, DataInput.class, readLimiterClass));
// Find the unlimited read limiter // Find the unlimited read limiter
for (final Field field : readLimiterClass.getDeclaredFields()) { for (Field field : readLimiterClass.getDeclaredFields()) {
if (readLimiterClass.isAssignableFrom(field.getType())) { if (readLimiterClass.isAssignableFrom(field.getType())) {
try { try {
readLimiter = field.get(null); this.readLimiter = field.get(null);
} catch (final Exception e) { } catch (Exception e) {
throw new RuntimeException("Cannot retrieve read limiter.", e); throw new RuntimeException("Cannot retrieve read limiter.", e);
} }
} }
@ -633,8 +640,8 @@ public class NbtFactory {
} }
@Override @Override
public Object loadNbt(final DataInput input) { public Object loadNbt(DataInput input) {
return invokeMethod(staticMethod, null, input, readLimiter); return invokeMethod(this.staticMethod, null, input, this.readLimiter);
} }
} }
@ -658,44 +665,44 @@ public class NbtFactory {
*/ */
public final class NbtCompound extends ConvertedMap { public final class NbtCompound extends ConvertedMap {
private NbtCompound(final Object handle) { private NbtCompound(Object handle) {
super(handle, getDataMap(handle)); super(handle, getDataMap(handle));
} }
// Simplifiying access to each value // Simplifying access to each value
public Byte getByte(final String key, final Byte defaultValue) { public Byte getByte(String key, Byte defaultValue) {
return containsKey(key) ? (Byte) get(key) : defaultValue; return containsKey(key) ? (Byte) get(key) : defaultValue;
} }
public Short getShort(final String key, final Short defaultValue) { public Short getShort(String key, Short defaultValue) {
return containsKey(key) ? (Short) get(key) : defaultValue; return containsKey(key) ? (Short) get(key) : defaultValue;
} }
public Integer getInteger(final String key, final Integer defaultValue) { public Integer getInteger(String key, Integer defaultValue) {
return containsKey(key) ? (Integer) get(key) : defaultValue; return containsKey(key) ? (Integer) get(key) : defaultValue;
} }
public Long getLong(final String key, final Long defaultValue) { public Long getLong(String key, Long defaultValue) {
return containsKey(key) ? (Long) get(key) : defaultValue; return containsKey(key) ? (Long) get(key) : defaultValue;
} }
public Float getFloat(final String key, final Float defaultValue) { public Float getFloat(String key, Float defaultValue) {
return containsKey(key) ? (Float) get(key) : defaultValue; return containsKey(key) ? (Float) get(key) : defaultValue;
} }
public Double getDouble(final String key, final Double defaultValue) { public Double getDouble(String key, Double defaultValue) {
return containsKey(key) ? (Double) get(key) : defaultValue; return containsKey(key) ? (Double) get(key) : defaultValue;
} }
public String getString(final String key, final String defaultValue) { public String getString(String key, String defaultValue) {
return containsKey(key) ? (String) get(key) : defaultValue; return containsKey(key) ? (String) get(key) : defaultValue;
} }
public byte[] getByteArray(final String key, final byte[] defaultValue) { public byte[] getByteArray(String key, byte[] defaultValue) {
return containsKey(key) ? (byte[]) get(key) : defaultValue; return containsKey(key) ? (byte[]) get(key) : defaultValue;
} }
public int[] getIntegerArray(final String key, final int[] defaultValue) { public int[] getIntegerArray(String key, int[] defaultValue) {
return containsKey(key) ? (int[]) get(key) : defaultValue; return containsKey(key) ? (int[]) get(key) : defaultValue;
} }
@ -705,7 +712,7 @@ public class NbtFactory {
* @param createNew - whether or not to create a new list if its missing. * @param createNew - whether or not to create a new list if its missing.
* @return An existing list, a new list or NULL. * @return An existing list, a new list or NULL.
*/ */
public NbtList getList(final String key, final boolean createNew) { public NbtList getList(String key, boolean createNew) {
NbtList list = (NbtList) get(key); NbtList list = (NbtList) get(key);
if ((list == null) && createNew) { if ((list == null) && createNew) {
@ -720,7 +727,7 @@ public class NbtFactory {
* @param createNew - whether or not to create a new map if its missing. * @param createNew - whether or not to create a new map if its missing.
* @return An existing map, a new map or NULL. * @return An existing map, a new map or NULL.
*/ */
public NbtCompound getMap(final String key, final boolean createNew) { public NbtCompound getMap(String key, boolean createNew) {
return getMap(Collections.singletonList(key), createNew); return getMap(Collections.singletonList(key), createNew);
} }
@ -735,9 +742,9 @@ public class NbtFactory {
* @param value - the new value of this entry. * @param value - the new value of this entry.
* @return This compound, for chaining. * @return This compound, for chaining.
*/ */
public NbtCompound putPath(final String path, final Object value) { public NbtCompound putPath(String path, Object value) {
final List<String> entries = getPathElements(path); List<String> entries = getPathElements(path);
final Map<String, Object> map = getMap(entries.subList(0, entries.size() - 1), true); Map<String, Object> map = getMap(entries.subList(0, entries.size() - 1), true);
map.put(entries.get(entries.size() - 1), value); map.put(entries.get(entries.size() - 1), value);
return this; return this;
@ -752,9 +759,9 @@ public class NbtFactory {
* @return The value, or NULL if not found. * @return The value, or NULL if not found.
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <T> T getPath(final String path) { public <T> T getPath(String path) {
final List<String> entries = getPathElements(path); List<String> entries = getPathElements(path);
final NbtCompound map = getMap(entries.subList(0, entries.size() - 1), false); NbtCompound map = getMap(entries.subList(0, entries.size() - 1), false);
if (map != null) { if (map != null) {
return (T) map.get(entries.get(entries.size() - 1)); return (T) map.get(entries.get(entries.size() - 1));
@ -770,7 +777,7 @@ public class NbtFactory {
* @param option - whether or not to compress the output. * @param option - whether or not to compress the output.
* @throws IOException If anything went wrong. * @throws IOException If anything went wrong.
*/ */
public void saveTo(final ByteSink stream, final StreamOptions option) throws IOException { public void saveTo(ByteSink stream, StreamOptions option) throws IOException {
saveStream(this, stream, option); saveStream(this, stream, option);
} }
@ -780,10 +787,10 @@ public class NbtFactory {
* @param createNew - whether or not to create new compounds on the way. * @param createNew - whether or not to create new compounds on the way.
* @return The map at this location. * @return The map at this location.
*/ */
private NbtCompound getMap(final Iterable<String> path, final boolean createNew) { private NbtCompound getMap(Iterable<String> path, boolean createNew) {
NbtCompound current = this; NbtCompound current = this;
for (final String entry : path) { for (String entry : path) {
NbtCompound child = (NbtCompound) current.get(entry); NbtCompound child = (NbtCompound) current.get(entry);
if (child == null) { if (child == null) {
@ -802,7 +809,7 @@ public class NbtFactory {
* @param path - the path to split. * @param path - the path to split.
* @return The elements. * @return The elements.
*/ */
private List<String> getPathElements(final String path) { private List<String> getPathElements(String path) {
return Lists.newArrayList(Splitter.on(".").omitEmptyStrings().split(path)); return Lists.newArrayList(Splitter.on(".").omitEmptyStrings().split(path));
} }
} }
@ -818,7 +825,7 @@ public class NbtFactory {
*/ */
public final class NbtList extends ConvertedList { public final class NbtList extends ConvertedList {
private NbtList(final Object handle) { private NbtList(Object handle) {
super(handle, getDataList(handle)); super(handle, getDataList(handle));
} }
} }
@ -832,15 +839,15 @@ public class NbtFactory {
// Don't recreate wrapper objects // Don't recreate wrapper objects
private final ConcurrentMap<Object, Object> cache = new MapMaker().weakKeys().makeMap(); private final ConcurrentMap<Object, Object> cache = new MapMaker().weakKeys().makeMap();
public Object wrap(final Object value) { public Object wrap(Object value) {
Object current = cache.get(value); Object current = this.cache.get(value);
if (current == null) { if (current == null) {
current = wrapNative(value); current = wrapNative(value);
// Only cache composite objects // Only cache composite objects
if ((current instanceof ConvertedMap) || (current instanceof ConvertedList)) { if ((current instanceof ConvertedMap) || (current instanceof ConvertedList)) {
cache.put(value, current); this.cache.put(value, current);
} }
} }
return current; return current;
@ -859,57 +866,57 @@ public class NbtFactory {
private final CachedNativeWrapper cache = new CachedNativeWrapper(); private final CachedNativeWrapper cache = new CachedNativeWrapper();
public ConvertedMap(final Object handle, final Map<String, Object> original) { public ConvertedMap(Object handle, Map<String, Object> original) {
this.handle = handle; this.handle = handle;
this.original = original; this.original = original;
} }
// For converting back and forth // For converting back and forth
protected Object wrapOutgoing(final Object value) { protected Object wrapOutgoing(Object value) {
return cache.wrap(value); return this.cache.wrap(value);
} }
protected Object unwrapIncoming(final Object wrapped) { protected Object unwrapIncoming(Object wrapped) {
return unwrapValue(wrapped); return unwrapValue(wrapped);
} }
// Modification // Modification
@Override @Override
public Object put(final String key, final Object value) { public Object put(String key, Object value) {
return wrapOutgoing(original.put(key, unwrapIncoming(value))); return wrapOutgoing(this.original.put(key, unwrapIncoming(value)));
} }
// Performance // Performance
@Override @Override
public Object get(final Object key) { public Object get(Object key) {
return wrapOutgoing(original.get(key)); return wrapOutgoing(this.original.get(key));
} }
@Override @Override
public Object remove(final Object key) { public Object remove(Object key) {
return wrapOutgoing(original.remove(key)); return wrapOutgoing(this.original.remove(key));
} }
@Override @Override
public boolean containsKey(final Object key) { public boolean containsKey(Object key) {
return original.containsKey(key); return this.original.containsKey(key);
} }
@Override @Override
public Set<Entry<String, Object>> entrySet() { public Set<Entry<String, Object>> entrySet() {
return new AbstractSet<Entry<String, Object>>() { return new AbstractSet<Entry<String, Object>>() {
@Override @Override
public boolean add(final Entry<String, Object> e) { public boolean add(Entry<String, Object> e) {
final String key = e.getKey(); String key = e.getKey();
final Object value = e.getValue(); Object value = e.getValue();
original.put(key, unwrapIncoming(value)); ConvertedMap.this.original.put(key, unwrapIncoming(value));
return true; return true;
} }
@Override @Override
public int size() { public int size() {
return original.size(); return ConvertedMap.this.original.size();
} }
@Override @Override
@ -920,7 +927,7 @@ public class NbtFactory {
} }
private Iterator<Entry<String, Object>> iterator() { private Iterator<Entry<String, Object>> iterator() {
final Iterator<Entry<String, Object>> proxy = original.entrySet().iterator(); final Iterator<Entry<String, Object>> proxy = this.original.entrySet().iterator();
return new Iterator<Entry<String, Object>>() { return new Iterator<Entry<String, Object>>() {
@Override @Override
@ -930,7 +937,7 @@ public class NbtFactory {
@Override @Override
public Entry<String, Object> next() { public Entry<String, Object> next() {
final Entry<String, Object> entry = proxy.next(); Entry<String, Object> entry = proxy.next();
return new SimpleEntry<String, Object>(entry.getKey(), wrapOutgoing(entry.getValue())); return new SimpleEntry<String, Object>(entry.getKey(), wrapOutgoing(entry.getValue()));
} }
@ -944,7 +951,7 @@ public class NbtFactory {
@Override @Override
public Object getHandle() { public Object getHandle() {
return handle; return this.handle;
} }
} }
@ -960,61 +967,61 @@ public class NbtFactory {
private final List<Object> original; private final List<Object> original;
private final CachedNativeWrapper cache = new CachedNativeWrapper(); private final CachedNativeWrapper cache = new CachedNativeWrapper();
public ConvertedList(final Object handle, final List<Object> original) { public ConvertedList(Object handle, List<Object> original) {
if (NBT_LIST_TYPE == null) { if (NbtFactory.this.NBT_LIST_TYPE == null) {
NBT_LIST_TYPE = getField(handle, null, "type"); NbtFactory.this.NBT_LIST_TYPE = getField(handle, null, "type");
} }
this.handle = handle; this.handle = handle;
this.original = original; this.original = original;
} }
protected Object wrapOutgoing(final Object value) { protected Object wrapOutgoing(Object value) {
return cache.wrap(value); return this.cache.wrap(value);
} }
protected Object unwrapIncoming(final Object wrapped) { protected Object unwrapIncoming(Object wrapped) {
return unwrapValue(wrapped); return unwrapValue(wrapped);
} }
@Override @Override
public Object get(final int index) { public Object get(int index) {
return wrapOutgoing(original.get(index)); return wrapOutgoing(this.original.get(index));
} }
@Override @Override
public int size() { public int size() {
return original.size(); return this.original.size();
} }
@Override @Override
public Object set(final int index, final Object element) { public Object set(int index, Object element) {
return wrapOutgoing(original.set(index, unwrapIncoming(element))); return wrapOutgoing(this.original.set(index, unwrapIncoming(element)));
} }
@Override @Override
public void add(final int index, final Object element) { public void add(int index, Object element) {
final Object nbt = unwrapIncoming(element); Object nbt = unwrapIncoming(element);
// Set the list type if its the first element // Set the list type if its the first element
if (size() == 0) { if (size() == 0) {
setFieldValue(NBT_LIST_TYPE, handle, (byte) getNbtType(nbt).id); setFieldValue(NbtFactory.this.NBT_LIST_TYPE, this.handle, (byte) getNbtType(nbt).id);
} }
original.add(index, nbt); this.original.add(index, nbt);
} }
@Override @Override
public Object remove(final int index) { public Object remove(int index) {
return wrapOutgoing(original.remove(index)); return wrapOutgoing(this.original.remove(index));
} }
@Override @Override
public boolean remove(final Object o) { public boolean remove(Object o) {
return original.remove(unwrapIncoming(o)); return this.original.remove(unwrapIncoming(o));
} }
@Override @Override
public Object getHandle() { public Object getHandle() {
return handle; return this.handle;
} }
} }
} }

View File

@ -19,15 +19,15 @@ import java.util.UUID;
public class OfflinePlayerUtil { public class OfflinePlayerUtil {
public static Player loadPlayer(final String name) { public static Player loadPlayer(String name) {
return loadPlayer(Bukkit.getOfflinePlayer(name)); return loadPlayer(Bukkit.getOfflinePlayer(name));
} }
public static Player loadPlayer(final UUID id) { public static Player loadPlayer(UUID id) {
return loadPlayer(Bukkit.getOfflinePlayer(id)); return loadPlayer(Bukkit.getOfflinePlayer(id));
} }
public static Player loadPlayer(final OfflinePlayer player) { public static Player loadPlayer(OfflinePlayer player) {
if (player == null) { if (player == null) {
return null; return null;
} }
@ -37,26 +37,26 @@ public class OfflinePlayerUtil {
return loadPlayer(player.getUniqueId(), player.getName()); return loadPlayer(player.getUniqueId(), player.getName());
} }
private static Player loadPlayer(final UUID id, final String name) { private static Player loadPlayer(UUID id, String name) {
final Object server = getMinecraftServer(); Object server = getMinecraftServer();
final Object interactManager = newPlayerInteractManager(); Object interactManager = newPlayerInteractManager();
final Object worldServer = getWorldServer(); Object worldServer = getWorldServer();
final Object profile = newGameProfile(id, name); Object profile = newGameProfile(id, name);
final Class<?> entityPlayerClass = getNmsClass("EntityPlayer"); Class<?> entityPlayerClass = getNmsClass("EntityPlayer");
final Constructor entityPlayerConstructor = makeConstructor(entityPlayerClass, getNmsClass("MinecraftServer"), getNmsClass("WorldServer"), Constructor entityPlayerConstructor = makeConstructor(entityPlayerClass, getNmsClass("MinecraftServer"), getNmsClass("WorldServer"),
getUtilClass("com.mojang.authlib.GameProfile"), getUtilClass("com.mojang.authlib.GameProfile"),
getNmsClass("PlayerInteractManager")); getNmsClass("PlayerInteractManager"));
final Object entityPlayer = callConstructor(entityPlayerConstructor, server, worldServer, profile, interactManager); Object entityPlayer = callConstructor(entityPlayerConstructor, server, worldServer, profile, interactManager);
return (Player) getBukkitEntity(entityPlayer); return (Player) getBukkitEntity(entityPlayer);
} }
private static Object newGameProfile(final UUID id, final String name) { private static Object newGameProfile(UUID id, String name) {
final Class<?> gameProfileClass = getUtilClass("com.mojang.authlib.GameProfile"); Class<?> gameProfileClass = getUtilClass("com.mojang.authlib.GameProfile");
if (gameProfileClass == null) { //Before uuids if (gameProfileClass == null) { //Before uuids
return name; return name;
} }
Constructor gameProfileConstructor = makeConstructor(gameProfileClass, UUID.class, String.class); 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); gameProfileConstructor = makeConstructor(gameProfileClass, String.class, String.class);
return callConstructor(gameProfileConstructor, id.toString(), name); return callConstructor(gameProfileConstructor, id.toString(), name);
} else { //Version has uuid constructor } else { //Version has uuid constructor
@ -65,17 +65,17 @@ public class OfflinePlayerUtil {
} }
private static Object newPlayerInteractManager() { private static Object newPlayerInteractManager() {
final Object worldServer = getWorldServer(); Object worldServer = getWorldServer();
final Class<?> playerInteractClass = getNmsClass("PlayerInteractManager"); Class<?> playerInteractClass = getNmsClass("PlayerInteractManager");
final Class<?> worldClass = getNmsClass("World"); Class<?> worldClass = getNmsClass("World");
final Constructor c = makeConstructor(playerInteractClass, worldClass); Constructor c = makeConstructor(playerInteractClass, worldClass);
return callConstructor(c, worldServer); return callConstructor(c, worldServer);
} }
private static Object getWorldServer() { private static Object getWorldServer() {
final Object server = getMinecraftServer(); Object server = getMinecraftServer();
final Class<?> minecraftServerClass = getNmsClass("MinecraftServer"); Class<?> minecraftServerClass = getNmsClass("MinecraftServer");
final Method getWorldServer = makeMethod(minecraftServerClass, "getWorldServer", int.class); Method getWorldServer = makeMethod(minecraftServerClass, "getWorldServer", int.class);
return callMethod(getWorldServer, server, 0); return callMethod(getWorldServer, server, 0);
} }
@ -85,8 +85,8 @@ public class OfflinePlayerUtil {
return callMethod(makeMethod(getCbClass("CraftServer"), "getServer"), Bukkit.getServer()); return callMethod(makeMethod(getCbClass("CraftServer"), "getServer"), Bukkit.getServer());
} }
private static Entity getBukkitEntity(final Object o) { private static Entity getBukkitEntity(Object o) {
final Method getBukkitEntity = makeMethod(o.getClass(), "getBukkitEntity"); Method getBukkitEntity = makeMethod(o.getClass(), "getBukkitEntity");
return callMethod(getBukkitEntity, o); return callMethod(getBukkitEntity, o);
} }
} }

View File

@ -0,0 +1,140 @@
package com.plotsquared.bukkit.util;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
import com.intellectualcrafters.plot.PS;
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.RefConstructor;
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 com.plotsquared.bukkit.object.BukkitPlayer;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
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)
*
*/
public class SendChunk {
private final RefMethod methodGetHandlePlayer;
private final RefMethod methodGetHandleChunk;
private final RefConstructor mapChunk;
private final RefField connection;
private final RefMethod send;
private final RefMethod methodInitLighting;
/**
* Constructor
*/
public SendChunk() {
RefClass classCraftPlayer = getRefClass("{cb}.entity.CraftPlayer");
this.methodGetHandlePlayer = classCraftPlayer.getMethod("getHandle");
RefClass classCraftChunk = getRefClass("{cb}.CraftChunk");
this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle");
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);
RefClass classEntityPlayer = getRefClass("{nms}.EntityPlayer");
this.connection = classEntityPlayer.getField("playerConnection");
RefClass classPacket = getRefClass("{nms}.Packet");
RefClass classConnection = getRefClass("{nms}.PlayerConnection");
this.send = classConnection.getMethod("sendPacket", classPacket.getRealClass());
}
public void sendChunk(Collection<Chunk> input) {
HashSet<Chunk> chunks = new HashSet<Chunk>(input);
HashMap<String, ArrayList<Chunk>> map = new HashMap<>();
int view = Bukkit.getServer().getViewDistance();
for (Chunk chunk : chunks) {
String world = chunk.getWorld().getName();
ArrayList<Chunk> list = map.get(world);
if (list == null) {
list = new ArrayList<>();
map.put(world, list);
}
list.add(chunk);
Object c = this.methodGetHandleChunk.of(chunk).call();
this.methodInitLighting.of(c).call();
}
for (Entry<String, PlotPlayer> entry : UUIDHandler.getPlayers().entrySet()) {
PlotPlayer pp = entry.getValue();
Plot plot = pp.getCurrentPlot();
Location loc = null;
String world;
if (plot != null) {
world = plot.getArea().worldname;
} else {
loc = pp.getLocation();
world = loc.getWorld();
}
ArrayList<Chunk> list = map.get(world);
if (list == null) {
continue;
}
if (loc == null) {
loc = pp.getLocation();
}
int cx = loc.getX() >> 4;
int cz = loc.getZ() >> 4;
Player player = ((BukkitPlayer) pp).player;
Object entity = this.methodGetHandlePlayer.of(player).call();
for (Chunk chunk : list) {
int dx = Math.abs(cx - chunk.getX());
int dz = Math.abs(cz - chunk.getZ());
if ((dx > view) || (dz > view)) {
continue;
}
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);
this.send.of(con).call(packet);
}
}
for (final Chunk chunk : chunks) {
TaskManager.runTask(new Runnable() {
@Override
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());
PS.debug("$3 - $4File may be open in another process (e.g. MCEdit)");
PS.debug("$3 - $4" + worldName + "/level.dat or " + worldName
+ "/level_old.dat may be corrupt (try repairing or removing these)");
}
}
});
}
}
public void sendChunk(String worldName, Collection<ChunkLoc> chunkLocations) {
World myWorld = Bukkit.getWorld(worldName);
ArrayList<Chunk> chunks = new ArrayList<>();
for (ChunkLoc loc : chunkLocations) {
if (myWorld.isChunkLoaded(loc.x, loc.z)) {
chunks.add(myWorld.getChunkAt(loc.x, loc.z));
}
}
sendChunk(chunks);
}
}

View File

@ -14,24 +14,24 @@ import java.util.Iterator;
public class SetGenCB { public class SetGenCB {
public static void setGenerator(final World world) throws Exception { public static void setGenerator(World world) throws Exception {
SetupUtils.manager.updateGenerators(); SetupUtils.manager.updateGenerators();
PS.get().removePlotAreas(world.getName()); PS.get().removePlotAreas(world.getName());
final ChunkGenerator gen = world.getGenerator(); ChunkGenerator gen = world.getGenerator();
if (gen == null) { if (gen == null) {
return; return;
} }
final String name = gen.getClass().getCanonicalName(); String name = gen.getClass().getCanonicalName();
boolean set = false; boolean set = false;
for (final GeneratorWrapper<?> wrapper : SetupUtils.generators.values()) { for (GeneratorWrapper<?> wrapper : SetupUtils.generators.values()) {
ChunkGenerator newGen = (ChunkGenerator) wrapper.getPlatformGenerator(); ChunkGenerator newGen = (ChunkGenerator) wrapper.getPlatformGenerator();
if (newGen == null) { if (newGen == null) {
newGen = (ChunkGenerator) wrapper; newGen = (ChunkGenerator) wrapper;
} }
if (newGen.getClass().getCanonicalName().equals(name)) { if (newGen.getClass().getCanonicalName().equals(name)) {
// set generator // set generator
final Field generator = world.getClass().getDeclaredField("generator"); Field generator = world.getClass().getDeclaredField("generator");
final Field populators = world.getClass().getDeclaredField("populators"); Field populators = world.getClass().getDeclaredField("populators");
generator.setAccessible(true); generator.setAccessible(true);
populators.setAccessible(true); populators.setAccessible(true);
// Set populators (just in case) // Set populators (just in case)
@ -45,10 +45,10 @@ public class SetGenCB {
} }
} }
if (!set) { if (!set) {
final Iterator<BlockPopulator> iter = world.getPopulators().iterator(); Iterator<BlockPopulator> iterator = world.getPopulators().iterator();
while (iter.hasNext()) { while (iterator.hasNext()) {
if (iter.next() instanceof BukkitAugmentedGenerator) { if (iterator.next() instanceof BukkitAugmentedGenerator) {
iter.remove(); iterator.remove();
} }
} }
} }

View File

@ -17,12 +17,13 @@ public class FastChunk_1_8_3 extends PlotChunk<Chunk> {
public short[] relight; public short[] relight;
public int[][] biomes; public int[][] biomes;
public Chunk chunk; public Chunk chunk;
public FastChunk_1_8_3(final ChunkWrapper chunk) {
public FastChunk_1_8_3(ChunkWrapper chunk) {
super(chunk); super(chunk);
ids = new char[16][]; this.ids = new char[16][];
count = new short[16]; this.count = new short[16];
air = new short[16]; this.air = new short[16];
relight = new short[16]; this.relight = new short[16];
} }
@Override @Override
@ -33,89 +34,89 @@ public class FastChunk_1_8_3 extends PlotChunk<Chunk> {
@Override @Override
public Chunk getChunk() { public Chunk getChunk() {
if (chunk == null) { if (this.chunk == null) {
final ChunkWrapper cl = getChunkWrapper(); ChunkWrapper cl = getChunkWrapper();
chunk = Bukkit.getWorld(cl.world).getChunkAt(cl.x, cl.z); this.chunk = Bukkit.getWorld(cl.world).getChunkAt(cl.x, cl.z);
} }
return chunk; return this.chunk;
} }
@Override @Override
public void setChunkWrapper(final ChunkWrapper loc) { public void setChunkWrapper(ChunkWrapper loc) {
super.setChunkWrapper(loc); super.setChunkWrapper(loc);
chunk = null; this.chunk = null;
} }
/** /**
* Get the number of block changes in a specified section * Get the number of block changes in a specified section.
* @param i * @param i
* @return * @return
*/ */
public int getCount(final int i) { public int getCount(int i) {
return count[i]; return this.count[i];
} }
public int getAir(final int i) { public int getAir(int i) {
return air[i]; return this.air[i];
} }
public void setCount(int i, short value) { public void setCount(int i, short value) {
count[i] = value; this.count[i] = value;
} }
/** /**
* Get the number of block changes in a specified section * Get the number of block changes in a specified section.
* @param i * @param i
* @return * @return
*/ */
public int getRelight(final int i) { public int getRelight(int i) {
return relight[i]; return this.relight[i];
} }
public int getTotalCount() { public int getTotalCount() {
int total = 0; int total = 0;
for (int i = 0; i < 16; i++) { for (int i = 0; i < 16; i++) {
total += count[i]; total += this.count[i];
} }
return total; return total;
} }
public int getTotalRelight() { public int getTotalRelight() {
if (getTotalCount() == 0) { if (getTotalCount() == 0) {
Arrays.fill(count, (short) 1); Arrays.fill(this.count, (short) 1);
Arrays.fill(relight, Short.MAX_VALUE); Arrays.fill(this.relight, Short.MAX_VALUE);
return Short.MAX_VALUE; return Short.MAX_VALUE;
} }
int total = 0; int total = 0;
for (int i = 0; i < 16; i++) { for (int i = 0; i < 16; i++) {
total += relight[i]; total += this.relight[i];
} }
return total; return total;
} }
/** /**
* Get the raw data for a section * Get the raw data for a section.
* @param i * @param i
* @return * @return
*/ */
public char[] getIdArray(final int i) { public char[] getIdArray(int i) {
return ids[i]; return this.ids[i];
} }
@Override @Override
public void setBlock(final int x, final int y, final int z, final int id, byte data) { public void setBlock(int x, int y, int z, int id, byte data) {
final int i = MainUtil.CACHE_I[y][x][z]; int i = MainUtil.CACHE_I[y][x][z];
final int j = MainUtil.CACHE_J[y][x][z]; int j = MainUtil.CACHE_J[y][x][z];
char[] vs = ids[i]; char[] vs = this.ids[i];
if (vs == null) { if (vs == null) {
vs = ids[i] = new char[4096]; vs = this.ids[i] = new char[4096];
count[i]++; this.count[i]++;
} else if (vs[j] == 0) { } else if (vs[j] == 0) {
count[i]++; this.count[i]++;
} }
switch (id) { switch (id) {
case 0: case 0:
air[i]++; this.air[i]++;
vs[j] = (char) 1; vs[j] = (char) 1;
return; return;
case 10: case 10:
@ -129,7 +130,7 @@ public class FastChunk_1_8_3 extends PlotChunk<Chunk> {
case 124: case 124:
case 138: case 138:
case 169: case 169:
relight[i]++; this.relight[i]++;
case 2: case 2:
case 4: case 4:
case 13: case 13:
@ -193,7 +194,7 @@ public class FastChunk_1_8_3 extends PlotChunk<Chunk> {
case 130: case 130:
case 76: case 76:
case 62: case 62:
relight[i]++; this.relight[i]++;
case 54: case 54:
case 146: case 146:
case 61: case 61:
@ -212,12 +213,12 @@ public class FastChunk_1_8_3 extends PlotChunk<Chunk> {
@Override @Override
public PlotChunk clone() { public PlotChunk clone() {
FastChunk_1_8_3 toReturn = new FastChunk_1_8_3(getChunkWrapper()); FastChunk_1_8_3 toReturn = new FastChunk_1_8_3(getChunkWrapper());
toReturn.air = air.clone(); toReturn.air = this.air.clone();
toReturn.count = count.clone(); toReturn.count = this.count.clone();
toReturn.relight = relight.clone(); toReturn.relight = this.relight.clone();
toReturn.ids = new char[ids.length][]; toReturn.ids = new char[this.ids.length][];
for (int i = 0; i < ids.length; i++) { for (int i = 0; i < this.ids.length; i++) {
char[] matrix = ids[i]; char[] matrix = this.ids[i];
if (matrix != null) { if (matrix != null) {
toReturn.ids[i] = new char[matrix.length]; toReturn.ids[i] = new char[matrix.length];
System.arraycopy(matrix, 0, toReturn.ids[i], 0, matrix.length); System.arraycopy(matrix, 0, toReturn.ids[i], 0, matrix.length);
@ -229,18 +230,18 @@ public class FastChunk_1_8_3 extends PlotChunk<Chunk> {
@Override @Override
public PlotChunk shallowClone() { public PlotChunk shallowClone() {
FastChunk_1_8_3 toReturn = new FastChunk_1_8_3(getChunkWrapper()); FastChunk_1_8_3 toReturn = new FastChunk_1_8_3(getChunkWrapper());
toReturn.air = air; toReturn.air = this.air;
toReturn.count = count; toReturn.count = this.count;
toReturn.relight = relight; toReturn.relight = this.relight;
toReturn.ids = ids; toReturn.ids = this.ids;
return toReturn; return toReturn;
} }
@Override @Override
public void setBiome(int x, int z, int biome) { public void setBiome(int x, int z, int biome) {
if (biomes == null) { if (this.biomes == null) {
biomes = new int[16][16]; this.biomes = new int[16][16];
} }
biomes[x][z] = biome; this.biomes[x][z] = biome;
} }
} }

View File

@ -0,0 +1,251 @@
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

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

View File

@ -27,39 +27,39 @@ import java.util.Map.Entry;
public class FastQueue_1_8 extends SlowQueue { public class FastQueue_1_8 extends SlowQueue {
public final RefMethod methodInitLighting; private final RefMethod methodInitLighting;
private final RefClass classBlock = getRefClass("{nms}.Block"); private final RefClass classBlock = getRefClass("{nms}.Block");
private final RefClass classBlockPosition = getRefClass("{nms}.BlockPosition"); private final RefClass classBlockPosition = getRefClass("{nms}.BlockPosition");
private final RefClass classIBlockData = getRefClass("{nms}.IBlockData"); private final RefClass classIBlockData = getRefClass("{nms}.IBlockData");
private final RefClass classChunk = getRefClass("{nms}.Chunk"); private final RefClass classChunk = getRefClass("{nms}.Chunk");
private final RefClass classWorld = getRefClass("{nms}.World"); private final RefClass classWorld = getRefClass("{nms}.World");
private final RefClass classCraftWorld = getRefClass("{cb}.CraftWorld"); private final RefClass classCraftWorld = getRefClass("{cb}.CraftWorld");
public HashMap<ChunkWrapper, Chunk> toUpdate = new HashMap<>(); private final HashMap<ChunkWrapper, Chunk> toUpdate = new HashMap<>();
private RefMethod methodGetHandle; private final RefMethod methodGetHandle;
private RefMethod methodGetChunkAt; private final RefMethod methodGetChunkAt;
private RefMethod methodA; private final RefMethod methodA;
private RefMethod methodGetByCombinedId; private final RefMethod methodGetByCombinedId;
private RefConstructor constructorBlockPosition; private final RefConstructor constructorBlockPosition;
private SendChunk chunksender; private final SendChunk sendChunk;
public FastQueue_1_8() throws NoSuchMethodException, RuntimeException { public FastQueue_1_8() throws RuntimeException {
methodInitLighting = classChunk.getMethod("initLighting"); this.methodInitLighting = this.classChunk.getMethod("initLighting");
constructorBlockPosition = classBlockPosition.getConstructor(int.class, int.class, int.class); this.constructorBlockPosition = this.classBlockPosition.getConstructor(int.class, int.class, int.class);
methodGetByCombinedId = classBlock.getMethod("getByCombinedId", int.class); this.methodGetByCombinedId = this.classBlock.getMethod("getByCombinedId", int.class);
methodGetHandle = classCraftWorld.getMethod("getHandle"); this.methodGetHandle = this.classCraftWorld.getMethod("getHandle");
methodGetChunkAt = classWorld.getMethod("getChunkAt", int.class, int.class); this.methodGetChunkAt = this.classWorld.getMethod("getChunkAt", int.class, int.class);
methodA = classChunk.getMethod("a", classBlockPosition, classIBlockData); this.methodA = this.classChunk.getMethod("a", this.classBlockPosition, this.classIBlockData);
chunksender = new SendChunk(); this.sendChunk = new SendChunk();
TaskManager.runTaskRepeat(new Runnable() { TaskManager.runTaskRepeat(new Runnable() {
@Override @Override
public void run() { public void run() {
if (toUpdate.isEmpty()) { if (FastQueue_1_8.this.toUpdate.isEmpty()) {
return; return;
} }
int count = 0; int count = 0;
final ArrayList<Chunk> chunks = new ArrayList<Chunk>(); ArrayList<Chunk> chunks = new ArrayList<Chunk>();
final Iterator<Entry<ChunkWrapper, Chunk>> i = toUpdate.entrySet().iterator(); Iterator<Entry<ChunkWrapper, Chunk>> i = FastQueue_1_8.this.toUpdate.entrySet().iterator();
while (i.hasNext() && (count < 128)) { while (i.hasNext() && count < 128) {
chunks.add(i.next().getValue()); chunks.add(i.next().getValue());
i.remove(); i.remove();
count++; count++;
@ -73,12 +73,12 @@ public class FastQueue_1_8 extends SlowQueue {
MainUtil.initCache(); MainUtil.initCache();
} }
public void update(final Collection<Chunk> chunks) { public void update(Collection<Chunk> chunks) {
if (chunks.isEmpty()) { if (chunks.isEmpty()) {
return; return;
} }
if (!MainUtil.canSendChunk) { if (!MainUtil.canSendChunk) {
for (final Chunk chunk : chunks) { for (Chunk chunk : chunks) {
chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ()); chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ());
chunk.unload(true, false); chunk.unload(true, false);
chunk.load(); chunk.load();
@ -86,38 +86,38 @@ public class FastQueue_1_8 extends SlowQueue {
return; return;
} }
try { try {
chunksender.sendChunk(chunks); this.sendChunk.sendChunk(chunks);
} catch (final Throwable e) { } catch (Throwable e) {
e.printStackTrace(); e.printStackTrace();
MainUtil.canSendChunk = false; MainUtil.canSendChunk = false;
} }
} }
/** /**
* This should be overriden by any specialized queues * This should be overridden by any specialized queues.
* @param pc * @param plotChunk
*/ */
@Override @Override
public void execute(PlotChunk<Chunk> pc) { public void execute(PlotChunk<Chunk> plotChunk) {
SlowChunk sc = (SlowChunk) pc; SlowChunk sc = (SlowChunk) plotChunk;
Chunk chunk = pc.getChunk(); Chunk chunk = plotChunk.getChunk();
ChunkWrapper wrapper = pc.getChunkWrapper(); ChunkWrapper wrapper = plotChunk.getChunkWrapper();
if (!toUpdate.containsKey(wrapper)) { if (!this.toUpdate.containsKey(wrapper)) {
toUpdate.put(wrapper, chunk); this.toUpdate.put(wrapper, chunk);
} }
chunk.load(true); chunk.load(true);
World world = chunk.getWorld(); World world = chunk.getWorld();
final Object w = methodGetHandle.of(world).call(); Object w = this.methodGetHandle.of(world).call();
final Object c = methodGetChunkAt.of(w).call(wrapper.x, wrapper.z); Object c = this.methodGetChunkAt.of(w).call(wrapper.x, wrapper.z);
for (int i = 0; i < sc.result.length; i++) { for (int i = 0; i < sc.result.length; i++) {
PlotBlock[] result2 = sc.result[i]; PlotBlock[] result2 = sc.result[i];
if (result2 == null) { if (result2 == null) {
continue; continue;
} }
for (int j = 0; j < 4096; j++) { for (int j = 0; j < 4096; j++) {
final int x = MainUtil.x_loc[i][j]; int x = MainUtil.x_loc[i][j];
final int y = MainUtil.y_loc[i][j]; int y = MainUtil.y_loc[i][j];
final int z = MainUtil.z_loc[i][j]; int z = MainUtil.z_loc[i][j];
PlotBlock newBlock = result2[j]; PlotBlock newBlock = result2[j];
if (newBlock.id == -1) { if (newBlock.id == -1) {
chunk.getBlock(x, y, z).setData(newBlock.data, false); chunk.getBlock(x, y, z).setData(newBlock.data, false);
@ -161,8 +161,8 @@ public class FastQueue_1_8 extends SlowQueue {
case 29: case 29:
case 33: case 33:
case 151: case 151:
case 178: { case 178:
final Block block = world.getBlockAt(x, y, z); Block block = world.getBlockAt(x, y, z);
if (block.getData() == newBlock.data) { if (block.getData() == newBlock.data) {
if (block.getTypeId() != newBlock.id) { if (block.getTypeId() != newBlock.id) {
block.setTypeId(newBlock.id, false); block.setTypeId(newBlock.id, false);
@ -175,12 +175,11 @@ public class FastQueue_1_8 extends SlowQueue {
} }
} }
continue; continue;
}
} }
// Start data value shortcut // Start data value shortcut
final Block block = world.getBlockAt(x, y, z); Block block = world.getBlockAt(x, y, z);
final int currentId = block.getTypeId(); int currentId = block.getTypeId();
if (currentId == newBlock.id) { if (currentId == newBlock.id) {
switch (newBlock.id) { switch (newBlock.id) {
case 0: case 0:
@ -263,9 +262,8 @@ public class FastQueue_1_8 extends SlowQueue {
case 189: case 189:
case 190: case 190:
case 191: case 191:
case 192: { case 192:
continue; continue;
}
} }
if (block.getData() == newBlock.data) { if (block.getData() == newBlock.data) {
return; return;
@ -311,21 +309,20 @@ public class FastQueue_1_8 extends SlowQueue {
case 29: case 29:
case 33: case 33:
case 151: case 151:
case 178: { case 178:
if (block.getData() == newBlock.data) { if (block.getData() == newBlock.data) {
block.setTypeId(newBlock.id, false); block.setTypeId(newBlock.id, false);
} else { } else {
block.setTypeIdAndData(newBlock.id, newBlock.data, false); block.setTypeIdAndData(newBlock.id, newBlock.data, false);
} }
continue; continue;
}
} }
// End blockstate workaround // // End blockstate workaround //
// check sign // check sign
final Object pos = constructorBlockPosition.create(x, y, z); Object pos = this.constructorBlockPosition.create(x, y, z);
final Object combined = methodGetByCombinedId.call(newBlock.id + (newBlock.data << 12)); Object combined = this.methodGetByCombinedId.call(newBlock.id + (newBlock.data << 12));
methodA.of(chunk).call(pos, combined); this.methodA.of(chunk).call(pos, combined);
} }
} }
int[][] biomes = sc.biomes; int[][] biomes = sc.biomes;
@ -348,7 +345,7 @@ public class FastQueue_1_8 extends SlowQueue {
} }
/** /**
* This should be overridden by any specialized queues * This should be overridden by any specialized queues.
* @param wrap * @param wrap
*/ */
@Override @Override
@ -357,28 +354,27 @@ public class FastQueue_1_8 extends SlowQueue {
} }
/** /**
* This should be overridden by any specialized queues * This should be overridden by any specialized queues.
* @param fixAll * @param fixAll
*/ */
@Override @Override
public boolean fixLighting(PlotChunk<Chunk> chunk, boolean fixAll) { public boolean fixLighting(PlotChunk<Chunk> chunk, boolean fixAll) {
Object c = methodGetHandle.of(chunk.getChunk()).call(); Object c = this.methodGetHandle.of(chunk.getChunk()).call();
methodInitLighting.of(c).call(); this.methodInitLighting.of(c).call();
return true; return true;
} }
/** /**
* This should be overridden by any specialized queues * This should be overridden by any specialized queues.
* @param locs * @param locations
*/ */
@Override @Override
public void sendChunk(String world, Collection<ChunkLoc> locs) { public void sendChunk(String world, Collection<ChunkLoc> locations) {
World worldObj = BukkitUtil.getWorld(world); World worldObj = BukkitUtil.getWorld(world);
for (ChunkLoc loc : locs) { for (ChunkLoc loc : locations) {
ChunkWrapper wrapper = SetQueue.IMP.new ChunkWrapper(world, loc.x, loc.z); ChunkWrapper wrapper = SetQueue.IMP.new ChunkWrapper(world, loc.x, loc.z);
if (!toUpdate.containsKey(wrapper)) { this.toUpdate.remove(wrapper);
toUpdate.put(wrapper, worldObj.getChunkAt(loc.x, loc.z));
}
} }
this.sendChunk.sendChunk(world, locations);
} }
} }

View File

@ -1,7 +1,5 @@
package com.plotsquared.bukkit.util.block; 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.ChunkLoc;
import com.intellectualcrafters.plot.object.PseudoRandom; import com.intellectualcrafters.plot.object.PseudoRandom;
import com.intellectualcrafters.plot.util.ChunkManager; import com.intellectualcrafters.plot.util.ChunkManager;
@ -15,14 +13,7 @@ import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod.RefExecutor;
import com.intellectualcrafters.plot.util.SetQueue; import com.intellectualcrafters.plot.util.SetQueue;
import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper; import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper;
import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.bukkit.util.SendChunk; import com.plotsquared.bukkit.util.SendChunk;
import org.bukkit.Chunk;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.block.Biome;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
@ -30,64 +21,61 @@ import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Set; 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 { public class FastQueue_1_8_3 extends SlowQueue {
public final SendChunk chunksender; private final SendChunk sendChunk;
private final RefClass classEntityPlayer = getRefClass("{nms}.EntityPlayer"); private final HashMap<ChunkWrapper, Chunk> toUpdate = new HashMap<>();
private final RefClass classMapChunk = getRefClass("{nms}.PacketPlayOutMapChunk"); private final RefMethod methodGetHandleChunk;
private final RefClass classPacket = getRefClass("{nms}.Packet"); private final RefMethod methodInitLighting;
private final RefClass classConnection = getRefClass("{nms}.PlayerConnection"); private final RefConstructor classBlockPositionConstructor;
private final RefClass classChunk = getRefClass("{nms}.Chunk"); private final RefConstructor classChunkSectionConstructor;
private final RefClass classCraftPlayer = getRefClass("{cb}.entity.CraftPlayer"); private final RefMethod methodX;
private final RefClass classCraftChunk = getRefClass("{cb}.CraftChunk"); private final RefMethod methodAreNeighborsLoaded;
private final RefClass classWorld = getRefClass("{nms}.World"); private final RefField fieldSections;
private final RefField mustSave = classChunk.getField("mustSave"); private final RefField fieldWorld;
private final RefClass classBlockPosition = getRefClass("{nms}.BlockPosition"); private final RefMethod methodGetIdArray;
private final RefClass classChunkSection = getRefClass("{nms}.ChunkSection"); private final RefMethod methodGetWorld;
public HashMap<ChunkWrapper, Chunk> toUpdate = new HashMap<>(); private final RefField tileEntityListTick;
private RefMethod methodGetHandlePlayer;
private RefMethod methodGetHandleChunk;
private RefConstructor MapChunk;
private RefField connection;
private RefMethod send;
private RefMethod methodInitLighting;
private RefConstructor classBlockPositionConstructor;
private RefConstructor classChunkSectionConstructor;
private RefMethod methodX;
private RefMethod methodAreNeighborsLoaded;
private RefField fieldSections;
private RefField fieldWorld;
private RefMethod methodGetIdArray;
public FastQueue_1_8_3() throws NoSuchMethodException, RuntimeException { public FastQueue_1_8_3() throws RuntimeException {
methodGetHandlePlayer = classCraftPlayer.getMethod("getHandle"); RefClass classCraftChunk = getRefClass("{cb}.CraftChunk");
methodGetHandleChunk = classCraftChunk.getMethod("getHandle"); this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle");
methodInitLighting = classChunk.getMethod("initLighting"); RefClass classChunk = getRefClass("{nms}.Chunk");
MapChunk = classMapChunk.getConstructor(classChunk.getRealClass(), boolean.class, int.class); this.methodInitLighting = classChunk.getMethod("initLighting");
connection = classEntityPlayer.getField("playerConnection"); RefClass classBlockPosition = getRefClass("{nms}.BlockPosition");
send = classConnection.getMethod("sendPacket", classPacket.getRealClass()); this.classBlockPositionConstructor = classBlockPosition.getConstructor(int.class, int.class, int.class);
classBlockPositionConstructor = classBlockPosition.getConstructor(int.class, int.class, int.class); RefClass classWorld = getRefClass("{nms}.World");
methodX = classWorld.getMethod("x", classBlockPosition.getRealClass()); this.methodX = classWorld.getMethod("x", classBlockPosition.getRealClass());
fieldSections = classChunk.getField("sections"); this.fieldSections = classChunk.getField("sections");
fieldWorld = classChunk.getField("world"); this.fieldWorld = classChunk.getField("world");
methodGetIdArray = classChunkSection.getMethod("getIdArray"); RefClass classChunkSection = getRefClass("{nms}.ChunkSection");
methodAreNeighborsLoaded = classChunk.getMethod("areNeighborsLoaded", int.class); this.methodGetIdArray = classChunkSection.getMethod("getIdArray");
classChunkSectionConstructor = classChunkSection.getConstructor(int.class, boolean.class, char[].class); this.methodAreNeighborsLoaded = classChunk.getMethod("areNeighborsLoaded", int.class);
chunksender = new SendChunk(); this.classChunkSectionConstructor = classChunkSection.getConstructor(int.class, boolean.class, char[].class);
this.tileEntityListTick = classWorld.getField("tileEntityList");
this.methodGetWorld = classChunk.getMethod("getWorld");
this.sendChunk = new SendChunk();
TaskManager.runTaskRepeat(new Runnable() { TaskManager.runTaskRepeat(new Runnable() {
@Override @Override
public void run() { public void run() {
if (toUpdate.isEmpty()) { if (FastQueue_1_8_3.this.toUpdate.isEmpty()) {
return; return;
} }
int count = 0; int count = 0;
final ArrayList<Chunk> chunks = new ArrayList<Chunk>(); ArrayList<Chunk> chunks = new ArrayList<>();
final Iterator<Entry<ChunkWrapper, Chunk>> i = toUpdate.entrySet().iterator(); Iterator<Entry<ChunkWrapper, Chunk>> i = FastQueue_1_8_3.this.toUpdate.entrySet().iterator();
while (i.hasNext() && (count < 128)) { while (i.hasNext() && count < 128) {
chunks.add(i.next().getValue()); chunks.add(i.next().getValue());
i.remove(); i.remove();
count++; count++;
@ -101,12 +89,12 @@ public class FastQueue_1_8_3 extends SlowQueue {
MainUtil.initCache(); MainUtil.initCache();
} }
public void update(final Collection<Chunk> chunks) { public void update(Collection<Chunk> chunks) {
if (chunks.isEmpty()) { if (chunks.isEmpty()) {
return; return;
} }
if (!MainUtil.canSendChunk) { if (!MainUtil.canSendChunk) {
for (final Chunk chunk : chunks) { for (Chunk chunk : chunks) {
chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ()); chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ());
chunk.unload(true, false); chunk.unload(true, false);
chunk.load(); chunk.load();
@ -114,72 +102,77 @@ public class FastQueue_1_8_3 extends SlowQueue {
return; return;
} }
try { try {
chunksender.sendChunk(chunks); this.sendChunk.sendChunk(chunks);
} catch (final Throwable e) { } catch (Throwable e) {
e.printStackTrace(); e.printStackTrace();
MainUtil.canSendChunk = false; MainUtil.canSendChunk = false;
} }
} }
/** /**
* This should be overridden by any specialized queues * This should be overridden by any specialized queues.
* @param pc * @param plotChunk
*/ */
@Override @Override
public void execute(PlotChunk<Chunk> pc) { public void execute(PlotChunk<Chunk> plotChunk) {
FastChunk_1_8_3 fs = (FastChunk_1_8_3) pc; FastChunk_1_8_3 fs = (FastChunk_1_8_3) plotChunk;
Chunk chunk = pc.getChunk(); Chunk chunk = plotChunk.getChunk();
final World world = chunk.getWorld(); World world = chunk.getWorld();
ChunkWrapper wrapper = pc.getChunkWrapper(); ChunkWrapper wrapper = plotChunk.getChunkWrapper();
if (!toUpdate.containsKey(wrapper)) { if (!this.toUpdate.containsKey(wrapper)) {
toUpdate.put(wrapper, chunk); this.toUpdate.put(wrapper, chunk);
} }
chunk.load(true); chunk.load(true);
try { try {
final boolean flag = world.getEnvironment() == Environment.NORMAL; boolean flag = world.getEnvironment() == Environment.NORMAL;
// Sections // Sections
final Method getHandele = chunk.getClass().getDeclaredMethod("getHandle"); Method getHandle = chunk.getClass().getDeclaredMethod("getHandle");
final Object c = getHandele.invoke(chunk); Object c = getHandle.invoke(chunk);
final Class<? extends Object> clazz = c.getClass(); Object w = this.methodGetWorld.of(c).call();
final Field sf = clazz.getDeclaredField("sections"); Class<? extends Object> clazz = c.getClass();
sf.setAccessible(true); Field sections1 = clazz.getDeclaredField("sections");
final Field tf = clazz.getDeclaredField("tileEntities"); sections1.setAccessible(true);
final Field ef = clazz.getDeclaredField("entitySlices"); Field tileEntities = clazz.getDeclaredField("tileEntities");
Field entitySlices = clazz.getDeclaredField("entitySlices");
Object[] sections = (Object[]) sections1.get(c);
HashMap<?, ?> tiles = (HashMap<?, ?>) tileEntities.get(c);
Collection<?>[] entities = (Collection<?>[]) entitySlices.get(c);
final Object[] sections = (Object[]) sf.get(c); Method getX = null;
final HashMap<?, ?> tiles = (HashMap<?, ?>) tf.get(c); Method getY = null;
final List<?>[] entities = (List<?>[]) ef.get(c); Method getZ = null;
Method xm = null;
Method ym = null;
Method zm = null;
// Trim tiles // Trim tiles
final Set<Entry<?, ?>> entryset = (Set<Entry<?, ?>>) (Set<?>) tiles.entrySet(); boolean removed = false;
final Iterator<Entry<?, ?>> iter = entryset.iterator(); Set<Entry<?, ?>> entrySet = (Set<Entry<?, ?>>) (Set<?>) tiles.entrySet();
while (iter.hasNext()) { Iterator<Entry<?, ?>> iterator = entrySet.iterator();
final Entry<?, ?> tile = iter.next(); while (iterator.hasNext()) {
final Object pos = tile.getKey(); Entry<?, ?> tile = iterator.next();
if (xm == null) { Object pos = tile.getKey();
final Class<? extends Object> clazz2 = pos.getClass().getSuperclass(); if (getX == null) {
xm = clazz2.getDeclaredMethod("getX"); Class<? extends Object> clazz2 = pos.getClass().getSuperclass();
ym = clazz2.getDeclaredMethod("getY"); getX = clazz2.getDeclaredMethod("getX");
zm = clazz2.getDeclaredMethod("getZ"); getY = clazz2.getDeclaredMethod("getY");
getZ = clazz2.getDeclaredMethod("getZ");
} }
final int lx = (int) xm.invoke(pos) & 15; int lx = (int) getX.invoke(pos) & 15;
final int ly = (int) ym.invoke(pos); int ly = (int) getY.invoke(pos);
final int lz = (int) zm.invoke(pos) & 15; int lz = (int) getZ.invoke(pos) & 15;
final int j = MainUtil.CACHE_I[ly][lx][lz]; int j = MainUtil.CACHE_I[ly][lx][lz];
final int k = MainUtil.CACHE_J[ly][lx][lz]; int k = MainUtil.CACHE_J[ly][lx][lz];
final char[] array = fs.getIdArray(j); char[] array = fs.getIdArray(j);
if (array == null) { if (array == null) {
continue; continue;
} }
if (array[k] != 0) { if (array[k] != 0) {
iter.remove(); removed = true;
iterator.remove();
} }
} }
if (removed) {
((Collection) this.tileEntityListTick.of(w).get()).clear();
}
// Trim entities // Trim entities
for (int i = 0; i < 16; i++) { for (int i = 0; i < 16; i++) {
@ -193,7 +186,7 @@ public class FastQueue_1_8_3 extends SlowQueue {
if (fs.getCount(j) == 0) { if (fs.getCount(j) == 0) {
continue; continue;
} }
final char[] newArray = fs.getIdArray(j); char[] newArray = fs.getIdArray(j);
if (newArray == null) { if (newArray == null) {
continue; continue;
} }
@ -202,10 +195,10 @@ public class FastQueue_1_8_3 extends SlowQueue {
section = sections[j] = newChunkSection(j << 4, flag, newArray); section = sections[j] = newChunkSection(j << 4, flag, newArray);
continue; continue;
} }
final char[] currentArray = getIdArray(section); char[] currentArray = getIdArray(section);
boolean fill = true; boolean fill = true;
for (int k = 0; k < newArray.length; k++) { for (int k = 0; k < newArray.length; k++) {
final char n = newArray[k]; char n = newArray[k];
switch (n) { switch (n) {
case 0: case 0:
fill = false; fill = false;
@ -224,8 +217,8 @@ public class FastQueue_1_8_3 extends SlowQueue {
} }
} }
// Clear // Clear
} catch (IllegalAccessException | IllegalArgumentException | NoSuchMethodException | SecurityException | InvocationTargetException | } catch (IllegalAccessException | IllegalArgumentException | NoSuchMethodException | SecurityException | InvocationTargetException
NoSuchFieldException e) { | NoSuchFieldException e) {
e.printStackTrace(); e.printStackTrace();
} }
int[][] biomes = fs.biomes; int[][] biomes = fs.biomes;
@ -247,16 +240,16 @@ public class FastQueue_1_8_3 extends SlowQueue {
} }
} }
public Object newChunkSection(final int i, final boolean flag, final char[] ids) { public Object newChunkSection(int i, boolean flag, char[] ids) {
return classChunkSectionConstructor.create(i, flag, ids); return this.classChunkSectionConstructor.create(i, flag, ids);
} }
public char[] getIdArray(final Object obj) { public char[] getIdArray(Object obj) {
return (char[]) methodGetIdArray.of(obj).call(); return (char[]) this.methodGetIdArray.of(obj).call();
} }
/** /**
* This should be overridden by any specialized queues * This should be overridden by any specialized queues.
* @param wrap * @param wrap
*/ */
@Override @Override
@ -266,13 +259,13 @@ public class FastQueue_1_8_3 extends SlowQueue {
/** /**
* This should be overridden by any specialized queues * This should be overridden by any specialized queues
* @param pc * @param plotChunk
*/ */
@Override @Override
public boolean fixLighting(PlotChunk<Chunk> pc, boolean fixAll) { public boolean fixLighting(PlotChunk<Chunk> plotChunk, boolean fixAll) {
try { try {
FastChunk_1_8_3 bc = (FastChunk_1_8_3) pc; FastChunk_1_8_3 bc = (FastChunk_1_8_3) plotChunk;
final Chunk chunk = bc.getChunk(); Chunk chunk = bc.getChunk();
if (!chunk.isLoaded()) { if (!chunk.isLoaded()) {
chunk.load(false); chunk.load(false);
} else { } else {
@ -281,12 +274,12 @@ public class FastQueue_1_8_3 extends SlowQueue {
} }
// Initialize lighting // Initialize lighting
final Object c = methodGetHandleChunk.of(chunk).call(); Object c = this.methodGetHandleChunk.of(chunk).call();
if (fixAll && !(boolean) methodAreNeighborsLoaded.of(c).call(1)) { if (fixAll && !(boolean) this.methodAreNeighborsLoaded.of(c).call(1)) {
World world = chunk.getWorld(); World world = chunk.getWorld();
ChunkWrapper wrapper = bc.getChunkWrapper(); ChunkWrapper wrapper = bc.getChunkWrapper();
String worldname = wrapper.world; String worldName = wrapper.world;
for (int x = wrapper.x - 1; x <= wrapper.x + 1; x++) { for (int x = wrapper.x - 1; x <= wrapper.x + 1; x++) {
for (int z = wrapper.z - 1; z <= wrapper.z + 1; z++) { for (int z = wrapper.z - 1; z <= wrapper.z + 1; z++) {
if (x != 0 && z != 0) { if (x != 0 && z != 0) {
@ -294,44 +287,46 @@ public class FastQueue_1_8_3 extends SlowQueue {
while (!other.isLoaded()) { while (!other.isLoaded()) {
other.load(true); other.load(true);
} }
ChunkManager.manager.loadChunk(worldname, new ChunkLoc(x, z), true); ChunkManager.manager.loadChunk(worldName, new ChunkLoc(x, z), true);
} }
} }
} }
/*
if (!(boolean) methodAreNeighborsLoaded.of(c).call(1)) { if (!(boolean) methodAreNeighborsLoaded.of(c).call(1)) {
return false; return false;
} }
*/
} }
methodInitLighting.of(c).call(); this.methodInitLighting.of(c).call();
if ((bc.getTotalRelight() == 0 && !fixAll)) { if (bc.getTotalRelight() == 0 && !fixAll) {
return true; return true;
} }
final Object[] sections = (Object[]) fieldSections.of(c).get(); Object[] sections = (Object[]) this.fieldSections.of(c).get();
final Object w = fieldWorld.of(c).get(); Object w = this.fieldWorld.of(c).get();
final int X = chunk.getX() << 4; int X = chunk.getX() << 4;
final int Z = chunk.getZ() << 4; int Z = chunk.getZ() << 4;
RefExecutor relight = methodX.of(w); RefExecutor relight = this.methodX.of(w);
for (int j = 0; j < sections.length; j++) { for (int j = 0; j < sections.length; j++) {
final Object section = sections[j]; Object section = sections[j];
if (section == null) { if (section == null) {
continue; continue;
} }
if ((bc.getRelight(j) == 0 && !fixAll) || bc.getCount(j) == 0 || (bc.getCount(j) >= 4096 && bc.getAir(j) == 0)) { if ((bc.getRelight(j) == 0 && !fixAll) || bc.getCount(j) == 0 || (bc.getCount(j) >= 4096 && bc.getAir(j) == 0)) {
continue; continue;
} }
final char[] array = getIdArray(section); char[] array = getIdArray(section);
int l = PseudoRandom.random.random(2); int l = PseudoRandom.random.random(2);
for (int k = 0; k < array.length; k++) { for (int k = 0; k < array.length; k++) {
final int i = array[k]; int i = array[k];
if (i < 16) { if (i < 16) {
continue; continue;
} }
final short id = (short) (i >> 4); short id = (short) (i >> 4);
switch (id) { // Lighting switch (id) { // Lighting
default: default:
if (!fixAll) { if (!fixAll) {
@ -356,19 +351,19 @@ public class FastQueue_1_8_3 extends SlowQueue {
case 130: case 130:
case 138: case 138:
case 169: case 169:
final int x = MainUtil.x_loc[j][k]; int x = MainUtil.x_loc[j][k];
final int y = MainUtil.y_loc[j][k]; int y = MainUtil.y_loc[j][k];
final int z = MainUtil.z_loc[j][k]; int z = MainUtil.z_loc[j][k];
if (isSurrounded(sections, x, y, z)) { if (isSurrounded(sections, x, y, z)) {
continue; continue;
} }
final Object pos = classBlockPositionConstructor.create(X + x, y, Z + z); Object pos = this.classBlockPositionConstructor.create(X + x, y, Z + z);
relight.call(pos); relight.call(pos);
} }
} }
} }
return true; return true;
} catch (final Throwable e) { } catch (Throwable e) {
e.printStackTrace(); e.printStackTrace();
} }
return false; return false;
@ -404,18 +399,16 @@ public class FastQueue_1_8_3 extends SlowQueue {
} }
/** /**
* This should be overridden by any specialized queues * This should be overridden by any specialized queues.
* @param world * @param world
* @param locs * @param locations
*/ */
@Override @Override
public void sendChunk(String world, Collection<ChunkLoc> locs) { public void sendChunk(String world, Collection<ChunkLoc> locations) {
World worldObj = BukkitUtil.getWorld(world); for (ChunkLoc loc : locations) {
for (ChunkLoc loc : locs) {
ChunkWrapper wrapper = SetQueue.IMP.new ChunkWrapper(world, loc.x, loc.z); ChunkWrapper wrapper = SetQueue.IMP.new ChunkWrapper(world, loc.x, loc.z);
if (!toUpdate.containsKey(wrapper)) { this.toUpdate.remove(wrapper);
toUpdate.put(wrapper, worldObj.getChunkAt(loc.x, loc.z));
}
} }
this.sendChunk.sendChunk(world, locations);
} }
} }

View File

@ -0,0 +1,422 @@
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.ChunkWrapper;
import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.bukkit.util.BukkitUtil;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
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.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 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 tileEntityListTick;
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.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");
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);
MainUtil.initCache();
}
/**
* This should be overridden by any specialized queues
* @param plotChunk
*/
@Override
public void execute(final PlotChunk<Chunk> plotChunk) {
final FastChunk_1_9 fs = (FastChunk_1_9) plotChunk;
Chunk chunk = plotChunk.getChunk();
World world = chunk.getWorld();
ChunkWrapper wrapper = plotChunk.getChunkWrapper();
chunk.load(true);
try {
boolean flag = world.getEnvironment() == 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<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) {
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;
}
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]);
}
}
}
TaskManager.runTaskLater(new Runnable() {
@Override
public void run() {
sendChunk(fs.getChunkWrapper().world, Arrays.asList(new ChunkLoc(fs.getX(), fs.getZ())));
}
}, 1);
}
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;
}
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) {
worldObj.refreshChunk(loc.x, loc.z);
}
}
}

View File

@ -17,12 +17,11 @@ public class GenChunk extends PlotChunk<Chunk> {
public short[][] result; public short[][] result;
public byte[][] result_data; public byte[][] result_data;
public ChunkData cd; public ChunkData cd;
public boolean modified = false;
public BiomeGrid grid; public BiomeGrid grid;
public GenChunk(Chunk chunk, ChunkWrapper wrap) { public GenChunk(Chunk chunk, ChunkWrapper wrap) {
super(wrap); super(wrap);
if ((this.chunk = chunk) == null) { if ((this.chunk = chunk) == null && wrap != null) {
World world = BukkitUtil.getWorld(wrap.world); World world = BukkitUtil.getWorld(wrap.world);
if (world != null) { if (world != null) {
chunk = world.getChunkAt(wrap.x, wrap.z); chunk = world.getChunkAt(wrap.x, wrap.z);
@ -34,72 +33,74 @@ public class GenChunk extends PlotChunk<Chunk> {
@Override @Override
public Chunk getChunkAbs() { public Chunk getChunkAbs() {
ChunkWrapper wrap = getChunkWrapper(); ChunkWrapper wrap = getChunkWrapper();
if (wrap.x != chunk.getX() || wrap.z != chunk.getZ()) { if (this.chunk == null || wrap.x != this.chunk.getX() || wrap.z != this.chunk.getZ()) {
chunk = BukkitUtil.getWorld(wrap.world).getChunkAt(wrap.x, wrap.z); this.chunk = BukkitUtil.getWorld(wrap.world).getChunkAt(wrap.x, wrap.z);
} }
return chunk; return this.chunk;
} }
@Override @Override
public void setBiome(int x, int z, int biome) { public void setBiome(int x, int z, int biome) {
modified = true; this.grid.setBiome(x, z, this.biomes[biome]);
grid.setBiome(x, z, biomes[biome]);
} }
public void setBiome(int x, int z, Biome biome) { public void setBiome(int x, int z, Biome biome) {
if (grid != null) { if (this.grid != null) {
grid.setBiome(x, z, biome); this.grid.setBiome(x, z, biome);
} }
} }
@Override @Override
public void setBlock(int x, int y, int z, int id, byte data) { public void setBlock(int x, int y, int z, int id, byte data) {
if (result == null) { if (this.result == null) {
modified = true; this.cd.setBlock(x, y, z, id, data);
cd.setBlock(x, y, z, id, data);
return; return;
} }
int i = MainUtil.CACHE_I[y][x][z]; int i = MainUtil.CACHE_I[y][x][z];
short[] v = result[i]; short[] v = this.result[i];
if (v == null) { if (v == null) {
modified = true; this.result[i] = v = new short[4096];
result[i] = v = new short[4096];
} }
v[MainUtil.CACHE_J[y][x][z]] = (short) id; int j = MainUtil.CACHE_J[y][x][z];
v[j] = (short) id;
if (data != 0) { if (data != 0) {
getChunk().getBlock(x, y, z).setData(data); byte[] vd = this.result_data[i];
if (vd == null) {
this.result_data[i] = vd = new byte[4096];
}
vd[j] = data;
} }
} }
@Override @Override
public PlotChunk clone() { public PlotChunk clone() {
GenChunk toReturn = new GenChunk(getChunkAbs(), getChunkWrapper()); GenChunk toReturn = new GenChunk(getChunkAbs(), getChunkWrapper());
if (result != null) { if (this.result != null) {
for (int i = 0; i < result.length; i++) { for (int i = 0; i < this.result.length; i++) {
short[] matrix = result[i]; short[] matrix = this.result[i];
if (matrix != null) { if (matrix != null) {
toReturn.result[i] = new short[matrix.length]; toReturn.result[i] = new short[matrix.length];
System.arraycopy(matrix, 0, toReturn.result[i], 0, matrix.length); System.arraycopy(matrix, 0, toReturn.result[i], 0, matrix.length);
} }
} }
for (int i = 0; i < result_data.length; i++) { for (int i = 0; i < this.result_data.length; i++) {
byte[] matrix = result_data[i]; byte[] matrix = this.result_data[i];
if (matrix != null) { if (matrix != null) {
toReturn.result_data[i] = new byte[matrix.length]; toReturn.result_data[i] = new byte[matrix.length];
System.arraycopy(matrix, 0, toReturn.result_data[i], 0, matrix.length); System.arraycopy(matrix, 0, toReturn.result_data[i], 0, matrix.length);
} }
} }
} }
toReturn.cd = cd; toReturn.cd = this.cd;
return toReturn; return toReturn;
} }
@Override @Override
public PlotChunk shallowClone() { public PlotChunk shallowClone() {
GenChunk toReturn = new GenChunk(getChunkAbs(), getChunkWrapper()); GenChunk toReturn = new GenChunk(getChunkAbs(), getChunkWrapper());
toReturn.result = result; toReturn.result = this.result;
toReturn.result_data = result_data; toReturn.result_data = this.result_data;
toReturn.cd = cd; toReturn.cd = this.cd;
return toReturn; return toReturn;
} }
} }

View File

@ -11,7 +11,7 @@ public class SlowChunk extends PlotChunk<Chunk> {
public PlotBlock[][] result = new PlotBlock[16][]; public PlotBlock[][] result = new PlotBlock[16][];
public int[][] biomes; public int[][] biomes;
private PlotBlock lastBlock;
public SlowChunk(ChunkWrapper chunk) { public SlowChunk(ChunkWrapper chunk) {
super(chunk); super(chunk);
} }
@ -24,29 +24,25 @@ public class SlowChunk extends PlotChunk<Chunk> {
@Override @Override
public void setBiome(int x, int z, int biome) { public void setBiome(int x, int z, int biome) {
if (biomes == null) { if (this.biomes == null) {
biomes = new int[16][16]; this.biomes = new int[16][16];
} }
biomes[x][z] = biome; this.biomes[x][z] = biome;
} }
@Override @Override
public void setBlock(int x, int y, int z, int id, byte data) { public void setBlock(int x, int y, int z, int id, byte data) {
if (result[y >> 4] == null) { if (this.result[y >> 4] == null) {
result[y >> 4] = new PlotBlock[4096]; this.result[y >> 4] = new PlotBlock[4096];
}
if (id == lastBlock.id && data == lastBlock.data) {
result[MainUtil.CACHE_I[x][y][z]][MainUtil.CACHE_J[x][y][z]] = lastBlock;
} else {
result[MainUtil.CACHE_I[x][y][z]][MainUtil.CACHE_J[x][y][z]] = new PlotBlock((short) id, data);
} }
this.result[MainUtil.CACHE_I[y][x][z]][MainUtil.CACHE_J[y][x][z]] = new PlotBlock((short) id, data);
} }
@Override @Override
public PlotChunk clone() { public PlotChunk clone() {
SlowChunk toReturn = new SlowChunk(getChunkWrapper()); SlowChunk toReturn = new SlowChunk(getChunkWrapper());
for (int i = 0; i < result.length; i++) { for (int i = 0; i < this.result.length; i++) {
PlotBlock[] matrix = result[i]; PlotBlock[] matrix = this.result[i];
if (matrix != null) { if (matrix != null) {
toReturn.result[i] = new PlotBlock[matrix.length]; toReturn.result[i] = new PlotBlock[matrix.length];
System.arraycopy(matrix, 0, toReturn.result[i], 0, matrix.length); System.arraycopy(matrix, 0, toReturn.result[i], 0, matrix.length);
@ -58,7 +54,7 @@ public class SlowChunk extends PlotChunk<Chunk> {
@Override @Override
public PlotChunk shallowClone() { public PlotChunk shallowClone() {
SlowChunk toReturn = new SlowChunk(getChunkWrapper()); SlowChunk toReturn = new SlowChunk(getChunkWrapper());
toReturn.result = result; toReturn.result = this.result;
return toReturn; return toReturn;
} }
} }

View File

@ -8,14 +8,13 @@ import com.intellectualcrafters.plot.util.PlotChunk;
import com.intellectualcrafters.plot.util.PlotQueue; import com.intellectualcrafters.plot.util.PlotQueue;
import com.intellectualcrafters.plot.util.SetQueue; import com.intellectualcrafters.plot.util.SetQueue;
import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper; 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.Collection;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import org.bukkit.Chunk;
import org.bukkit.block.Biome;
import org.bukkit.block.Block;
public class SlowQueue implements PlotQueue<Chunk> { public class SlowQueue implements PlotQueue<Chunk> {
@ -30,18 +29,18 @@ public class SlowQueue implements PlotQueue<Chunk> {
if (y > 255 || y < 0) { if (y > 255 || y < 0) {
return false; return false;
} }
final ChunkWrapper wrap = SetQueue.IMP.new ChunkWrapper(world, x >> 4, z >> 4); ChunkWrapper wrap = SetQueue.IMP.new ChunkWrapper(world, x >> 4, z >> 4);
x = x & 15; x = x & 15;
z = z & 15; z = z & 15;
PlotChunk<Chunk> result = blocks.get(wrap); PlotChunk<Chunk> result = this.blocks.get(wrap);
if (result == null) { if (result == null) {
result = getChunk(wrap); result = getChunk(wrap);
result.setBlock(x, y, z, id, data); result.setBlock(x, y, z, id, data);
final PlotChunk<Chunk> previous = blocks.put(wrap, result); PlotChunk<Chunk> previous = this.blocks.put(wrap, result);
if (previous == null) { if (previous == null) {
return true; return true;
} }
blocks.put(wrap, previous); this.blocks.put(wrap, previous);
result = previous; result = previous;
} }
result.setBlock(x, y, z, id, data); result.setBlock(x, y, z, id, data);
@ -50,7 +49,7 @@ public class SlowQueue implements PlotQueue<Chunk> {
@Override @Override
public void setChunk(PlotChunk<Chunk> chunk) { public void setChunk(PlotChunk<Chunk> chunk) {
blocks.put(chunk.getChunkWrapper(), chunk); this.blocks.put(chunk.getChunkWrapper(), chunk);
} }
@Override @Override
@ -59,19 +58,19 @@ public class SlowQueue implements PlotQueue<Chunk> {
throw new IllegalStateException("Must be called from main thread!"); throw new IllegalStateException("Must be called from main thread!");
} }
try { try {
if (blocks.isEmpty()) { if (this.blocks.isEmpty()) {
return null; return null;
} }
final Iterator<Entry<ChunkWrapper, PlotChunk<Chunk>>> iter = blocks.entrySet().iterator(); Iterator<Entry<ChunkWrapper, PlotChunk<Chunk>>> iterator = this.blocks.entrySet().iterator();
final PlotChunk<Chunk> toReturn = iter.next().getValue(); PlotChunk<Chunk> toReturn = iterator.next().getValue();
if (SetQueue.IMP.isWaiting()) { if (SetQueue.IMP.isWaiting()) {
return null; return null;
} }
iter.remove(); iterator.remove();
execute(toReturn); execute(toReturn);
fixLighting(toReturn, true); fixLighting(toReturn, true);
return toReturn; return toReturn;
} catch (final Throwable e) { } catch (Throwable e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
@ -83,17 +82,17 @@ public class SlowQueue implements PlotQueue<Chunk> {
throw new IllegalStateException("Must be called from main thread!"); throw new IllegalStateException("Must be called from main thread!");
} }
try { try {
if (blocks.isEmpty()) { if (this.blocks.isEmpty()) {
return null; return null;
} }
final PlotChunk<Chunk> toReturn = blocks.remove(wrap); PlotChunk<Chunk> toReturn = this.blocks.remove(wrap);
if (toReturn == null) { if (toReturn == null) {
return null; return null;
} }
execute(toReturn); execute(toReturn);
fixLighting(toReturn, fixLighting); fixLighting(toReturn, fixLighting);
return toReturn; return toReturn;
} catch (final Throwable e) { } catch (Throwable e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
@ -101,16 +100,16 @@ public class SlowQueue implements PlotQueue<Chunk> {
@Override @Override
public void clear() { public void clear() {
blocks.clear(); this.blocks.clear();
} }
/** /**
* This should be overriden by any specialized queues * This should be overridden by any specialized queues.
* @param pc * @param plotChunk
*/ */
public void execute(PlotChunk<Chunk> pc) { public void execute(PlotChunk<Chunk> plotChunk) {
SlowChunk sc = (SlowChunk) pc; SlowChunk sc = (SlowChunk) plotChunk;
Chunk chunk = pc.getChunk(); Chunk chunk = plotChunk.getChunk();
chunk.load(true); chunk.load(true);
for (int i = 0; i < sc.result.length; i++) { for (int i = 0; i < sc.result.length; i++) {
PlotBlock[] result2 = sc.result[i]; PlotBlock[] result2 = sc.result[i];
@ -118,11 +117,14 @@ public class SlowQueue implements PlotQueue<Chunk> {
continue; continue;
} }
for (int j = 0; j < 4096; j++) { for (int j = 0; j < 4096; j++) {
final int x = MainUtil.x_loc[i][j]; int x = MainUtil.x_loc[i][j];
final int y = MainUtil.y_loc[i][j]; int y = MainUtil.y_loc[i][j];
final int z = MainUtil.z_loc[i][j]; int z = MainUtil.z_loc[i][j];
Block block = chunk.getBlock(x, y, z); Block block = chunk.getBlock(x, y, z);
PlotBlock newBlock = result2[j]; PlotBlock newBlock = result2[j];
if (newBlock == null) {
continue;
}
switch (newBlock.id) { switch (newBlock.id) {
case -1: case -1:
if (block.getData() == newBlock.data) { if (block.getData() == newBlock.data) {
@ -249,7 +251,7 @@ public class SlowQueue implements PlotQueue<Chunk> {
} }
/** /**
* This should be overriden by any specialized queues * This should be overridden by any specialized queues.
* @param wrap * @param wrap
*/ */
@Override @Override
@ -258,7 +260,7 @@ public class SlowQueue implements PlotQueue<Chunk> {
} }
/** /**
* This should be overriden by any specialized queues * This should be overridden by any specialized queues.
* @param fixAll * @param fixAll
*/ */
@Override @Override
@ -268,11 +270,11 @@ public class SlowQueue implements PlotQueue<Chunk> {
} }
/** /**
* This should be overriden by any specialized queues * This should be overridden by any specialized queues.
* @param locs * @param locations
*/ */
@Override @Override
public void sendChunk(String world, Collection<ChunkLoc> locs) { public void sendChunk(String world, Collection<ChunkLoc> locations) {
// Do nothing // Do nothing
} }
} }

View File

@ -1,47 +1,47 @@
package com.plotsquared.bukkit.uuid; package com.plotsquared.bukkit.uuid;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import com.intellectualcrafters.plot.object.OfflinePlotPlayer; import com.intellectualcrafters.plot.object.OfflinePlotPlayer;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.uuid.UUIDWrapper; import com.intellectualcrafters.plot.uuid.UUIDWrapper;
import com.plotsquared.bukkit.object.BukkitOfflinePlayer; import com.plotsquared.bukkit.object.BukkitOfflinePlayer;
import com.plotsquared.bukkit.object.BukkitPlayer; import com.plotsquared.bukkit.object.BukkitPlayer;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import java.util.UUID;
public class DefaultUUIDWrapper extends UUIDWrapper { public class DefaultUUIDWrapper extends UUIDWrapper {
@Override @Override
public UUID getUUID(final PlotPlayer player) { public UUID getUUID(PlotPlayer player) {
return ((BukkitPlayer) player).player.getUniqueId(); return ((BukkitPlayer) player).player.getUniqueId();
} }
@Override @Override
public UUID getUUID(final OfflinePlotPlayer player) { public UUID getUUID(OfflinePlotPlayer player) {
return player.getUUID(); return player.getUUID();
} }
@Override @Override
public OfflinePlotPlayer getOfflinePlayer(final UUID uuid) { public OfflinePlotPlayer getOfflinePlayer(UUID uuid) {
return new BukkitOfflinePlayer(Bukkit.getOfflinePlayer(uuid)); return new BukkitOfflinePlayer(Bukkit.getOfflinePlayer(uuid));
} }
@Override @Override
public UUID getUUID(final String name) { public UUID getUUID(String name) {
return Bukkit.getOfflinePlayer(name).getUniqueId(); return Bukkit.getOfflinePlayer(name).getUniqueId();
} }
@Override @Override
public OfflinePlotPlayer[] getOfflinePlayers() { public OfflinePlotPlayer[] getOfflinePlayers() {
final OfflinePlayer[] ops = Bukkit.getOfflinePlayers(); OfflinePlayer[] ops = Bukkit.getOfflinePlayers();
final BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length]; BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length];
for (int i = 0; i < ops.length; i++) { for (int i = 0; i < ops.length; i++) {
toReturn[i] = new BukkitOfflinePlayer(ops[i]); toReturn[i] = new BukkitOfflinePlayer(ops[i]);
} }
return toReturn; return toReturn;
} }
@Override @Override
public OfflinePlotPlayer getOfflinePlayer(String name) { public OfflinePlotPlayer getOfflinePlayer(String name) {
return new BukkitOfflinePlayer(Bukkit.getOfflinePlayer(name)); return new BukkitOfflinePlayer(Bukkit.getOfflinePlayer(name));

View File

@ -2,6 +2,7 @@ package com.plotsquared.bukkit.uuid;
import com.google.common.collect.HashBiMap; import com.google.common.collect.HashBiMap;
import com.google.common.io.ByteSource; import com.google.common.io.ByteSource;
import com.google.common.io.InputSupplier;
import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.config.Settings;
@ -20,6 +21,7 @@ import org.bukkit.Bukkit;
import org.bukkit.World; import org.bukkit.World;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter; import java.io.FilenameFilter;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
@ -30,19 +32,19 @@ import java.util.List;
import java.util.UUID; import java.util.UUID;
public class FileUUIDHandler extends UUIDHandlerImplementation { public class FileUUIDHandler extends UUIDHandlerImplementation {
public FileUUIDHandler(final UUIDWrapper wrapper) { public FileUUIDHandler(UUIDWrapper wrapper) {
super(wrapper); super(wrapper);
} }
@Override @Override
public boolean startCaching(final Runnable whenDone) { public boolean startCaching(Runnable whenDone) {
return super.startCaching(whenDone) && cache(whenDone); return super.startCaching(whenDone) && cache(whenDone);
} }
public boolean cache(final Runnable whenDone) { public boolean cache(final Runnable whenDone) {
final File container = Bukkit.getWorldContainer(); final File container = Bukkit.getWorldContainer();
final List<World> worlds = Bukkit.getWorlds(); List<World> worlds = Bukkit.getWorlds();
final String world; final String world;
if (worlds.isEmpty()) { if (worlds.isEmpty()) {
world = "world"; world = "world";
@ -52,11 +54,11 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
TaskManager.runTaskAsync(new Runnable() { TaskManager.runTaskAsync(new Runnable() {
@Override @Override
public void run() { public void run() {
PS.debug(C.PREFIX.s() + "&6Starting player data caching for: " + world); PS.debug(C.PREFIX + "&6Starting player data caching for: " + world);
final File uuidfile = new File(PS.get().IMP.getDirectory(), "uuids.txt"); File uuidFile = new File(PS.get().IMP.getDirectory(), "uuids.txt");
if (uuidfile.exists()) { if (uuidFile.exists()) {
try { try {
final List<String> lines = Files.readAllLines(uuidfile.toPath(), StandardCharsets.UTF_8); List<String> lines = Files.readAllLines(uuidFile.toPath(), StandardCharsets.UTF_8);
for (String line : lines) { for (String line : lines) {
try { try {
line = line.trim(); line = line.trim();
@ -64,55 +66,57 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
continue; continue;
} }
line = line.replaceAll("[\\|][0-9]+[\\|][0-9]+[\\|]", ""); line = line.replaceAll("[\\|][0-9]+[\\|][0-9]+[\\|]", "");
final String[] split = line.split("\\|"); String[] split = line.split("\\|");
final String name = split[0]; String name = split[0];
if ((name.isEmpty()) || (name.length() > 16) || !StringMan.isAlphanumericUnd(name)) { if (name.isEmpty() || (name.length() > 16) || !StringMan.isAlphanumericUnd(name)) {
continue; continue;
} }
final UUID uuid = uuidWrapper.getUUID(name); UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name);
if (uuid == null) { if (uuid == null) {
continue; continue;
} }
UUIDHandler.add(new StringWrapper(name), uuid); UUIDHandler.add(new StringWrapper(name), uuid);
} catch (final Exception e2) { } catch (Exception e2) {
e2.printStackTrace(); e2.printStackTrace();
} }
} }
} catch (final IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
if (Settings.TWIN_MODE_UUID) { if (Settings.TWIN_MODE_UUID) {
final HashBiMap<StringWrapper, UUID> toAdd = HashBiMap.create(new HashMap<StringWrapper, UUID>()); HashBiMap<StringWrapper, UUID> toAdd = HashBiMap.create(new HashMap<StringWrapper, UUID>());
toAdd.put(new StringWrapper("*"), DBFunc.everyone); toAdd.put(new StringWrapper("*"), DBFunc.everyone);
final HashSet<UUID> all = UUIDHandler.getAllUUIDS(); HashSet<UUID> all = UUIDHandler.getAllUUIDS();
PS.debug("&aFast mode UUID caching enabled!"); PS.debug("&aFast mode UUID caching enabled!");
final File playerdataFolder = new File(container, world + File.separator + "playerdata"); File playerDataFolder = new File(container, world + File.separator + "playerdata");
final String[] dat = playerdataFolder.list(new FilenameFilter() { String[] dat = playerDataFolder.list(new FilenameFilter() {
@Override @Override
public boolean accept(final File f, final String s) { public boolean accept(File f, String s) {
return s.endsWith(".dat"); return s.endsWith(".dat");
} }
}); });
final boolean check = all.isEmpty(); boolean check = all.isEmpty();
if (dat != null) { if (dat != null) {
for (final String current : dat) { for (String current : dat) {
final String s = current.replaceAll(".dat$", ""); String s = current.replaceAll(".dat$", "");
try { try {
final UUID uuid = UUID.fromString(s); UUID uuid = UUID.fromString(s);
if (check || all.remove(uuid)) { if (check || all.remove(uuid)) {
final File file = new File(playerdataFolder + File.separator + current); File file = new File(playerDataFolder + File.separator + current);
final ByteSource is = com.google.common.io.Files.asByteSource(file); InputSupplier<FileInputStream> is = com.google.common.io.Files.newInputStreamSupplier(file);
final NbtFactory.NbtCompound compound = NbtFactory.fromStream(is, NbtFactory.StreamOptions.GZIP_COMPRESSION); NbtFactory.NbtCompound compound = NbtFactory.fromStream(is, NbtFactory.StreamOptions.GZIP_COMPRESSION);
final NbtFactory.NbtCompound bukkit = (NbtFactory.NbtCompound) compound.get("bukkit"); NbtFactory.NbtCompound bukkit = (NbtFactory.NbtCompound) compound.get("bukkit");
final String name = (String) bukkit.get("lastKnownName"); String name = (String) bukkit.get("lastKnownName");
final long last = (long) bukkit.get("lastPlayed"); long last = (long) bukkit.get("lastPlayed");
ExpireManager.dates.put(uuid, last); if (ExpireManager.IMP != null) {
ExpireManager.IMP.storeDate(uuid, last);
}
toAdd.put(new StringWrapper(name), uuid); toAdd.put(new StringWrapper(name), uuid);
} }
} catch (final Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
PS.debug(C.PREFIX.s() + "Invalid playerdata: " + current); PS.debug(C.PREFIX + "Invalid playerdata: " + current);
} }
} }
} }
@ -126,45 +130,45 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
PS.debug("Failed to cache: " + all.size() + " uuids - slowly processing all files"); PS.debug("Failed to cache: " + all.size() + " uuids - slowly processing all files");
} }
} }
final HashBiMap<StringWrapper, UUID> toAdd = HashBiMap.create(new HashMap<StringWrapper, UUID>()); HashBiMap<StringWrapper, UUID> toAdd = HashBiMap.create(new HashMap<StringWrapper, UUID>());
toAdd.put(new StringWrapper("*"), DBFunc.everyone); toAdd.put(new StringWrapper("*"), DBFunc.everyone);
final HashSet<String> worlds = new HashSet<>(); HashSet<String> worlds = new HashSet<>();
worlds.add(world); worlds.add(world);
worlds.add("world"); worlds.add("world");
final HashSet<UUID> uuids = new HashSet<>(); HashSet<UUID> uuids = new HashSet<>();
final HashSet<String> names = new HashSet<>(); HashSet<String> names = new HashSet<>();
File playerdataFolder = null; File playerDataFolder = null;
for (final String worldname : worlds) { for (String worldName : worlds) {
// Getting UUIDs // Getting UUIDs
playerdataFolder = new File(container, worldname + File.separator + "playerdata"); playerDataFolder = new File(container, worldName + File.separator + "playerdata");
String[] dat = playerdataFolder.list(new FilenameFilter() { String[] dat = playerDataFolder.list(new FilenameFilter() {
@Override @Override
public boolean accept(final File f, final String s) { public boolean accept(File f, String s) {
return s.endsWith(".dat"); return s.endsWith(".dat");
} }
}); });
if ((dat != null) && (dat.length != 0)) { if ((dat != null) && (dat.length != 0)) {
for (final String current : dat) { for (String current : dat) {
final String s = current.replaceAll(".dat$", ""); String s = current.replaceAll(".dat$", "");
try { try {
final UUID uuid = UUID.fromString(s); UUID uuid = UUID.fromString(s);
uuids.add(uuid); uuids.add(uuid);
} catch (final Exception e) { } catch (Exception e) {
PS.debug(C.PREFIX.s() + "Invalid playerdata: " + current); PS.debug(C.PREFIX + "Invalid PlayerData: " + current);
} }
} }
break; break;
} }
// Getting names // Getting names
final File playersFolder = new File(worldname + File.separator + "players"); File playersFolder = new File(worldName + File.separator + "players");
dat = playersFolder.list(new FilenameFilter() { dat = playersFolder.list(new FilenameFilter() {
@Override @Override
public boolean accept(final File f, final String s) { public boolean accept(File f, String s) {
return s.endsWith(".dat"); return s.endsWith(".dat");
} }
}); });
if ((dat != null) && (dat.length != 0)) { if ((dat != null) && (dat.length != 0)) {
for (final String current : dat) { for (String current : dat) {
names.add(current.replaceAll(".dat$", "")); names.add(current.replaceAll(".dat$", ""));
} }
break; break;
@ -172,42 +176,49 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
} }
for (UUID uuid : uuids) { for (UUID uuid : uuids) {
try { try {
final File file = new File(playerdataFolder + File.separator + uuid.toString() + ".dat"); File file = new File(playerDataFolder + File.separator + uuid.toString() + ".dat");
final ByteSource is = com.google.common.io.Files.asByteSource(file); if (!file.exists()) {
final NbtFactory.NbtCompound compound = NbtFactory.fromStream(is, NbtFactory.StreamOptions.GZIP_COMPRESSION); continue;
final NbtFactory.NbtCompound bukkit = (NbtFactory.NbtCompound) compound.get("bukkit"); }
final String name = (String) bukkit.get("lastKnownName"); ByteSource is = com.google.common.io.Files.asByteSource(file);
final long last = (long) bukkit.get("lastPlayed"); 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.OFFLINE_MODE) {
if (Settings.UUID_LOWERCASE && !name.toLowerCase().equals(name)) { if (Settings.UUID_LOWERCASE && !name.toLowerCase().equals(name)) {
uuid = uuidWrapper.getUUID(name); uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name);
} else { } else {
final long most = (long) compound.get("UUIDMost"); long most = (long) compound.get("UUIDMost");
final long least = (long) compound.get("UUIDLeast"); long least = (long) compound.get("UUIDLeast");
uuid = new UUID(most, least); uuid = new UUID(most, least);
} }
} }
ExpireManager.dates.put(uuid, last); if (ExpireManager.IMP != null) {
ExpireManager.IMP.storeDate(uuid, last);
}
toAdd.put(new StringWrapper(name), uuid); toAdd.put(new StringWrapper(name), uuid);
} catch (final Throwable e) { } catch (Throwable e) {
PS.debug(C.PREFIX.s() + "&6Invalid playerdata: " + uuid.toString() + ".dat"); PS.debug(C.PREFIX + "&6Invalid PlayerData: " + uuid.toString() + ".dat");
} }
} }
for (final String name : names) { for (String name : names) {
final UUID uuid = uuidWrapper.getUUID(name); UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(name);
final StringWrapper nameWrap = new StringWrapper(name); StringWrapper nameWrap = new StringWrapper(name);
toAdd.put(nameWrap, uuid); toAdd.put(nameWrap, uuid);
} }
if (getUUIDMap().isEmpty()) { if (getUUIDMap().isEmpty()) {
for (final OfflinePlotPlayer op : uuidWrapper.getOfflinePlayers()) { for (OfflinePlotPlayer op : FileUUIDHandler.this.uuidWrapper.getOfflinePlayers()) {
final long last = op.getLastPlayed(); long last = op.getLastPlayed();
if (last != 0) { if (last != 0) {
final String name = op.getName(); String name = op.getName();
final StringWrapper wrap = new StringWrapper(name); StringWrapper wrap = new StringWrapper(name);
final UUID uuid = uuidWrapper.getUUID(op); UUID uuid = FileUUIDHandler.this.uuidWrapper.getUUID(op);
toAdd.put(wrap, uuid); toAdd.put(wrap, uuid);
ExpireManager.dates.put(uuid, last); if (ExpireManager.IMP != null) {
ExpireManager.IMP.storeDate(uuid, last);
}
} }
} }
} }
@ -219,13 +230,13 @@ public class FileUUIDHandler extends UUIDHandlerImplementation {
}); });
return true; return true;
} }
@Override @Override
public void fetchUUID(final String name, final RunnableVal<UUID> ifFetch) { public void fetchUUID(final String name, final RunnableVal<UUID> ifFetch) {
TaskManager.runTaskAsync(new Runnable() { TaskManager.runTaskAsync(new Runnable() {
@Override @Override
public void run() { public void run() {
ifFetch.value = uuidWrapper.getUUID(name); ifFetch.value = FileUUIDHandler.this.uuidWrapper.getUUID(name);
TaskManager.runTask(ifFetch); TaskManager.runTask(ifFetch);
} }
}); });

View File

@ -0,0 +1,32 @@
package com.plotsquared.bukkit.uuid;
import com.google.common.base.Charsets;
import com.intellectualcrafters.plot.object.OfflinePlotPlayer;
import com.intellectualcrafters.plot.object.PlotPlayer;
import org.bukkit.OfflinePlayer;
import java.util.UUID;
public class LowerOfflineUUIDWrapper extends OfflineUUIDWrapper {
@Override
public UUID getUUID(PlotPlayer player) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8));
}
@Override
public UUID getUUID(OfflinePlotPlayer player) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8));
}
@Override
public UUID getUUID(OfflinePlayer player) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName().toLowerCase()).getBytes(Charsets.UTF_8));
}
@Override
public UUID getUUID(String name) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + name.toLowerCase()).getBytes(Charsets.UTF_8));
}
}

View File

@ -1,14 +1,5 @@
package com.plotsquared.bukkit.uuid; package com.plotsquared.bukkit.uuid;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import com.google.common.base.Charsets; import com.google.common.base.Charsets;
import com.google.common.collect.BiMap; import com.google.common.collect.BiMap;
import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS;
@ -18,93 +9,101 @@ import com.intellectualcrafters.plot.object.StringWrapper;
import com.intellectualcrafters.plot.util.UUIDHandler; import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.uuid.UUIDWrapper; import com.intellectualcrafters.plot.uuid.UUIDWrapper;
import com.plotsquared.bukkit.object.BukkitOfflinePlayer; import com.plotsquared.bukkit.object.BukkitOfflinePlayer;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.UUID;
public class OfflineUUIDWrapper extends UUIDWrapper { public class OfflineUUIDWrapper extends UUIDWrapper {
private Method getOnline = null;
private final Object[] arg = new Object[0]; private final Object[] arg = new Object[0];
private Method getOnline = null;
public OfflineUUIDWrapper() { public OfflineUUIDWrapper() {
try { try {
getOnline = Server.class.getMethod("getOnlinePlayers"); this.getOnline = Server.class.getMethod("getOnlinePlayers");
} catch (final NoSuchMethodException | SecurityException e) { } catch (NoSuchMethodException | SecurityException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@Override @Override
public UUID getUUID(final PlotPlayer player) { public UUID getUUID(PlotPlayer player) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8)); return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8));
} }
@Override @Override
public UUID getUUID(final OfflinePlotPlayer player) { public UUID getUUID(OfflinePlotPlayer player) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8)); return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8));
} }
public UUID getUUID(final OfflinePlayer player) { public UUID getUUID(OfflinePlayer player) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8)); return UUID.nameUUIDFromBytes(("OfflinePlayer:" + player.getName()).getBytes(Charsets.UTF_8));
} }
@Override @Override
public OfflinePlotPlayer getOfflinePlayer(final UUID uuid) { public OfflinePlotPlayer getOfflinePlayer(UUID uuid) {
final BiMap<UUID, StringWrapper> map = UUIDHandler.getUuidMap().inverse(); BiMap<UUID, StringWrapper> map = UUIDHandler.getUuidMap().inverse();
String name; String name;
try { try {
name = map.get(uuid).value; name = map.get(uuid).value;
} catch (final NullPointerException e) { } catch (NullPointerException e) {
name = null; name = null;
} }
if (name != null) { if (name != null) {
final OfflinePlayer op = Bukkit.getOfflinePlayer(name); OfflinePlayer op = Bukkit.getOfflinePlayer(name);
if (op.hasPlayedBefore()) { if (op.hasPlayedBefore()) {
return new BukkitOfflinePlayer(op); return new BukkitOfflinePlayer(op);
} }
} }
for (final OfflinePlayer player : Bukkit.getOfflinePlayers()) { for (OfflinePlayer player : Bukkit.getOfflinePlayers()) {
if (getUUID(player).equals(uuid)) { if (getUUID(player).equals(uuid)) {
return new BukkitOfflinePlayer(player); return new BukkitOfflinePlayer(player);
} }
} }
return null; return null;
} }
public Player[] getOnlinePlayers() { public Player[] getOnlinePlayers() {
if (getOnline == null) { if (this.getOnline == null) {
Collection<? extends Player> onlinePlayers = Bukkit.getOnlinePlayers(); Collection<? extends Player> onlinePlayers = Bukkit.getOnlinePlayers();
return onlinePlayers.toArray(new Player[onlinePlayers.size()]); return onlinePlayers.toArray(new Player[onlinePlayers.size()]);
} }
try { try {
final Object players = getOnline.invoke(Bukkit.getServer(), arg); Object players = this.getOnline.invoke(Bukkit.getServer(), this.arg);
if (players instanceof Player[]) { if (players instanceof Player[]) {
return (Player[]) players; return (Player[]) players;
} else { } else {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked") Collection<? extends Player> p = (Collection<? extends Player>) players;
final Collection<? extends Player> p = (Collection<? extends Player>) players;
return p.toArray(new Player[p.size()]); return p.toArray(new Player[p.size()]);
} }
} catch (final Exception e) { } catch (Exception e) {
PS.debug("Failed to resolve online players"); PS.debug("Failed to resolve online players");
getOnline = null; this.getOnline = null;
Collection<? extends Player> onlinePlayers = Bukkit.getOnlinePlayers(); Collection<? extends Player> onlinePlayers = Bukkit.getOnlinePlayers();
return onlinePlayers.toArray(new Player[onlinePlayers.size()]); return onlinePlayers.toArray(new Player[onlinePlayers.size()]);
} }
} }
@Override @Override
public UUID getUUID(final String name) { public UUID getUUID(String name) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8)); return UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8));
} }
@Override @Override
public OfflinePlotPlayer[] getOfflinePlayers() { public OfflinePlotPlayer[] getOfflinePlayers() {
final OfflinePlayer[] ops = Bukkit.getOfflinePlayers(); OfflinePlayer[] ops = Bukkit.getOfflinePlayers();
final BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length]; BukkitOfflinePlayer[] toReturn = new BukkitOfflinePlayer[ops.length];
for (int i = 0; i < ops.length; i++) { for (int i = 0; i < ops.length; i++) {
toReturn[i] = new BukkitOfflinePlayer(ops[i]); toReturn[i] = new BukkitOfflinePlayer(ops[i]);
} }
return toReturn; return toReturn;
} }
@Override @Override
public OfflinePlotPlayer getOfflinePlayer(String name) { public OfflinePlotPlayer getOfflinePlayer(String name) {
return new BukkitOfflinePlayer(Bukkit.getOfflinePlayer(name)); return new BukkitOfflinePlayer(Bukkit.getOfflinePlayer(name));

View File

@ -1,22 +1,5 @@
package com.plotsquared.bukkit.uuid; package com.plotsquared.bukkit.uuid;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
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 com.google.common.collect.HashBiMap; import com.google.common.collect.HashBiMap;
import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.C;
@ -29,41 +12,58 @@ import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler; import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.util.UUIDHandlerImplementation; import com.intellectualcrafters.plot.util.UUIDHandlerImplementation;
import com.intellectualcrafters.plot.uuid.UUIDWrapper; 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;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayDeque;
import java.util.Collections;
import java.util.HashMap;
import java.util.UUID;
public class SQLUUIDHandler extends UUIDHandlerImplementation { public class SQLUUIDHandler extends UUIDHandlerImplementation {
final String PROFILE_URL = "https://sessionserver.mojang.com/session/minecraft/profile/";
final int MAX_REQUESTS = 500;
final int INTERVAL = 12000;
final JSONParser jsonParser = new JSONParser();
private final SQLite _sqLite;
public SQLUUIDHandler(final UUIDWrapper wrapper) { final int MAX_REQUESTS = 500;
private final String PROFILE_URL = "https://sessionserver.mojang.com/session/minecraft/profile/";
private final int INTERVAL = 12000;
private final JSONParser jsonParser = new JSONParser();
private final SQLite sqlite;
public SQLUUIDHandler(UUIDWrapper wrapper) {
super(wrapper); super(wrapper);
_sqLite = new SQLite("./plugins/PlotSquared/usercache.db"); this.sqlite = new SQLite("./plugins/PlotSquared/usercache.db");
try { try {
_sqLite.openConnection(); this.sqlite.openConnection();
} catch (final Exception e) { } catch (ClassNotFoundException | SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
try { try (PreparedStatement stmt = getConnection().prepareStatement(
final PreparedStatement stmt = getConnection().prepareStatement( "CREATE TABLE IF NOT EXISTS `usercache` (uuid VARCHAR(32) NOT NULL, username VARCHAR(32) NOT NULL, PRIMARY KEY (uuid, username)"
"CREATE TABLE IF NOT EXISTS `usercache` (uuid VARCHAR(32) NOT NULL, username VARCHAR(32) NOT NULL, PRIMARY KEY (uuid, username))"); + ")")) {
stmt.execute(); stmt.execute();
stmt.close(); } catch (SQLException e) {
} catch (final SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
startCaching(null); startCaching(null);
} }
private Connection getConnection() { private Connection getConnection() {
synchronized (_sqLite) { synchronized (this.sqlite) {
return _sqLite.getConnection(); return this.sqlite.getConnection();
} }
} }
@Override @Override
public boolean startCaching(final Runnable whenDone) { public boolean startCaching(final Runnable whenDone) {
if (!super.startCaching(whenDone)) { if (!super.startCaching(whenDone)) {
@ -73,14 +73,12 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
@Override @Override
public void run() { public void run() {
try { try {
final HashBiMap<StringWrapper, UUID> toAdd = HashBiMap.create(new HashMap<StringWrapper, UUID>()); HashBiMap<StringWrapper, UUID> toAdd = HashBiMap.create(new HashMap<StringWrapper, UUID>());
final PreparedStatement statement = getConnection().prepareStatement("SELECT `uuid`, `username` FROM `usercache`"); PreparedStatement statement = getConnection().prepareStatement("SELECT `uuid`, `username` FROM `usercache`");
final ResultSet resultSet = statement.executeQuery(); ResultSet resultSet = statement.executeQuery();
StringWrapper username;
UUID uuid;
while (resultSet.next()) { while (resultSet.next()) {
username = new StringWrapper(resultSet.getString("username")); StringWrapper username = new StringWrapper(resultSet.getString("username"));
uuid = UUID.fromString(resultSet.getString("uuid")); UUID uuid = UUID.fromString(resultSet.getString("uuid"));
toAdd.put(new StringWrapper(username.value), uuid); toAdd.put(new StringWrapper(username.value), uuid);
} }
statement.close(); statement.close();
@ -89,7 +87,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
// This should be called as long as there are some unknown plots // This should be called as long as there are some unknown plots
final ArrayDeque<UUID> toFetch = new ArrayDeque<>(); final ArrayDeque<UUID> toFetch = new ArrayDeque<>();
for (final UUID u : UUIDHandler.getAllUUIDS()) { for (UUID u : UUIDHandler.getAllUUIDS()) {
if (!uuidExists(u)) { if (!uuidExists(u)) {
toFetch.add(u); toFetch.add(u);
} }
@ -100,7 +98,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
} }
return; return;
} }
final FileUUIDHandler fileHandler = new FileUUIDHandler(SQLUUIDHandler.this.uuidWrapper); FileUUIDHandler fileHandler = new FileUUIDHandler(SQLUUIDHandler.this.uuidWrapper);
fileHandler.startCaching(new Runnable() { fileHandler.startCaching(new Runnable() {
@Override @Override
public void run() { public void run() {
@ -125,80 +123,35 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
} }
for (int i = 0; i < Math.min(500, toFetch.size()); i++) { for (int i = 0; i < Math.min(500, toFetch.size()); i++) {
UUID uuid = toFetch.pop(); UUID uuid = toFetch.pop();
HttpURLConnection connection = (HttpURLConnection) new URL(PROFILE_URL + uuid.toString().replace("-", "")).openConnection(); HttpURLConnection connection =
(HttpURLConnection) new URL(SQLUUIDHandler.this.PROFILE_URL + uuid.toString().replace("-", ""))
.openConnection();
InputStreamReader reader = new InputStreamReader(connection.getInputStream()); InputStreamReader reader = new InputStreamReader(connection.getInputStream());
JSONObject response = (JSONObject) jsonParser.parse(reader); JSONObject response = (JSONObject) SQLUUIDHandler.this.jsonParser.parse(reader);
String name = (String) response.get("name"); String name = (String) response.get("name");
if (name != null) { if (name != null) {
add(new StringWrapper(name), uuid); add(new StringWrapper(name), uuid);
} }
} }
} catch (Exception e) { } catch (IOException | ParseException e) {
e.printStackTrace(); e.printStackTrace();
} }
TaskManager.runTaskLaterAsync(this, INTERVAL); TaskManager.runTaskLaterAsync(this, SQLUUIDHandler.this.INTERVAL);
} }
}); });
/*
* This API is no longer accessible.
*/
// if (!Settings.OFFLINE_MODE) {
// PS.debug(C.PREFIX.s() + "&cWill fetch &6" + toFetch.size() + "&c from mojang!");
//
// int i = 0;
// final Iterator<UUID> iterator = toFetch.iterator();
// while (iterator.hasNext()) {
// final StringBuilder url = new StringBuilder("http://api.intellectualsites.com/uuid/?user=");
// final List<UUID> currentIteration = new ArrayList<>();
// while ((i++ <= 15) && iterator.hasNext()) {
// final UUID _uuid = iterator.next();
// url.append(_uuid.toString());
// if (iterator.hasNext()) {
// url.append(",");
// }
// currentIteration.add(_uuid);
// }
// PS.debug(C.PREFIX.s() + "&cWill attempt to fetch &6" + currentIteration.size() + "&c uuids from: &6" + url.toString());
// try {
// final HttpURLConnection connection = (HttpURLConnection) new URL(url.toString()).openConnection();
// connection.setRequestProperty("User-Agent", "Mozilla/5.0");
// final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
// String line;
// final StringBuilder rawJSON = new StringBuilder();
// while ((line = reader.readLine()) != null) {
// rawJSON.append(line);
// }
// reader.close();
// final JSONObject object = new JSONObject(rawJSON.toString());
// for (final UUID _u : currentIteration) {
// final Object o = object.getJSONObject(_u.toString().replace("-", "")).get("username");
// if ((o == null) || !(o instanceof String)) {
// continue;
// }
// add(new StringWrapper(o.toString()), _u);
// }
// } catch (final Exception e) {
// e.printStackTrace();
// }
// i = 0;
// }
// }
// if (whenDone != null) {
// whenDone.run();
// }
} }
}); });
} catch (final SQLException e) { } catch (SQLException e) {
throw new SQLUUIDHandlerException("Couldn't select :s", e); throw new SQLUUIDHandlerException("Couldn't select :s", e);
} }
} }
}); });
return true; return true;
} }
@Override @Override
public void fetchUUID(final String name, final RunnableVal<UUID> ifFetch) { public void fetchUUID(final String name, final RunnableVal<UUID> ifFetch) {
PS.debug(C.PREFIX.s() + "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) { if (ifFetch == null) {
return; return;
} }
@ -206,7 +159,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
@Override @Override
public void run() { public void run() {
try { try {
URL url = new URL(PROFILE_URL); URL url = new URL(SQLUUIDHandler.this.PROFILE_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST"); connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Content-Type", "application/json");
@ -218,29 +171,31 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
stream.write(body.getBytes()); stream.write(body.getBytes());
stream.flush(); stream.flush();
stream.close(); stream.close();
JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream())); JSONArray array = (JSONArray) SQLUUIDHandler.this.jsonParser.parse(new InputStreamReader(connection.getInputStream()));
JSONObject jsonProfile = (JSONObject) array.get(0); JSONObject jsonProfile = (JSONObject) array.get(0);
String id = (String) jsonProfile.get("id"); String id = (String) jsonProfile.get("id");
String name = (String) jsonProfile.get("name"); 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.substring(20, 32)); ifFetch.value = UUID.fromString(
} catch (Exception e) { 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(); e.printStackTrace();
} }
TaskManager.runTask(ifFetch); TaskManager.runTask(ifFetch);
} }
}); });
} }
@Override @Override
public void handleShutdown() { public void handleShutdown() {
super.handleShutdown(); super.handleShutdown();
try { try {
getConnection().close(); getConnection().close();
} catch (final SQLException e) { } catch (SQLException e) {
throw new SQLUUIDHandlerException("Couldn't close database connection", e); throw new SQLUUIDHandlerException("Couldn't close database connection", e);
} }
} }
@Override @Override
public boolean add(final StringWrapper name, final UUID uuid) { public boolean add(final StringWrapper name, final UUID uuid) {
// Ignoring duplicates // Ignoring duplicates
@ -248,13 +203,12 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
TaskManager.runTaskAsync(new Runnable() { TaskManager.runTaskAsync(new Runnable() {
@Override @Override
public void run() { public void run() {
try { try (PreparedStatement statement = getConnection().prepareStatement("REPLACE INTO usercache (`uuid`, `username`) VALUES(?, ?)")) {
final PreparedStatement statement = getConnection().prepareStatement("REPLACE INTO usercache (`uuid`, `username`) VALUES(?, ?)");
statement.setString(1, uuid.toString()); statement.setString(1, uuid.toString());
statement.setString(2, name.toString()); statement.setString(2, name.toString());
statement.execute(); statement.execute();
PS.debug(C.PREFIX.s() + "&cAdded '&6" + uuid + "&c' - '&6" + name + "&c'"); PS.debug(C.PREFIX + "&cAdded '&6" + uuid + "&c' - '&6" + name + "&c'");
} catch (final SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -263,7 +217,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
} }
return false; return false;
} }
/** /**
* This is useful for name changes * This is useful for name changes
*/ */
@ -273,13 +227,12 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
TaskManager.runTaskAsync(new Runnable() { TaskManager.runTaskAsync(new Runnable() {
@Override @Override
public void run() { public void run() {
try { try (PreparedStatement statement = getConnection().prepareStatement("UPDATE usercache SET `username`=? WHERE `uuid`=?")) {
final PreparedStatement statement = getConnection().prepareStatement("UPDATE usercache SET `username`=? WHERE `uuid`=?");
statement.setString(1, name.value); statement.setString(1, name.value);
statement.setString(2, uuid.toString()); statement.setString(2, uuid.toString());
statement.execute(); statement.execute();
PS.debug(C.PREFIX.s() + "Name change for '" + uuid + "' to '" + name.value + "'"); PS.debug(C.PREFIX + "Name change for '" + uuid + "' to '" + name.value + "'");
} catch (final SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -288,7 +241,7 @@ public class SQLUUIDHandler extends UUIDHandlerImplementation {
private class SQLUUIDHandlerException extends RuntimeException { private class SQLUUIDHandlerException extends RuntimeException {
SQLUUIDHandlerException(final String s, final Throwable c) { SQLUUIDHandlerException(String s, Throwable c) {
super("SQLUUIDHandler caused an exception: " + s, c); super("SQLUUIDHandler caused an exception: " + s, c);
} }
} }

View File

@ -1,6 +1,6 @@
name: ${project.name} name: ${name}
main: com.plotsquared.bukkit.BukkitMain main: com.plotsquared.bukkit.BukkitMain
version: ${project.version} version: ${version}
load: STARTUP load: STARTUP
description: > description: >
Easy, yet powerful Plot World generation and management. Easy, yet powerful Plot World generation and management.
@ -146,7 +146,10 @@ permissions:
plots.save: true plots.save: true
plots.done: true plots.done: true
plots.continue: true plots.continue: true
plots.middle: true
plots.worldedit.bypass: plots.worldedit.bypass:
default: false default: false
plots.gamemode.bypass: plots.gamemode.bypass:
default: op default: op
plots.confirm.bypass:
default: false

11
Core/build.gradle Normal file
View File

@ -0,0 +1,11 @@
dependencies {
testCompile 'junit:junit:4.12'
compile 'org.yaml:snakeyaml:1.16'
compile 'com.google.code.gson:gson:2.2.4'
}
sourceCompatibility = 1.7
targetCompatibility = 1.7
jar.archiveName="PlotSquared-API-${parent.version}.jar"
jar.destinationDir = file '../target'

View File

@ -20,8 +20,7 @@ public interface Configuration extends ConfigurationSection {
* @param value Value to set the default to. * @param value Value to set the default to.
* @throws IllegalArgumentException Thrown if path is null. * @throws IllegalArgumentException Thrown if path is null.
*/ */
@Override @Override void addDefault(final String path, final Object value);
public void addDefault(final String path, final Object value);
/** /**
* Sets the default values of the given paths as provided. * Sets the default values of the given paths as provided.
@ -33,7 +32,7 @@ public interface Configuration extends ConfigurationSection {
* @param defaults A map of Path->Values to add to defaults. * @param defaults A map of Path->Values to add to defaults.
* @throws IllegalArgumentException Thrown if defaults is null. * @throws IllegalArgumentException Thrown if defaults is null.
*/ */
public void addDefaults(final Map<String, Object> defaults); void addDefaults(final Map<String, Object> defaults);
/** /**
* Sets the default values of the given paths as provided. * Sets the default values of the given paths as provided.
@ -50,7 +49,7 @@ public interface Configuration extends ConfigurationSection {
* @param defaults A configuration holding a list of defaults to copy. * @param defaults A configuration holding a list of defaults to copy.
* @throws IllegalArgumentException Thrown if defaults is null or this. * @throws IllegalArgumentException Thrown if defaults is null or this.
*/ */
public void addDefaults(final Configuration defaults); void addDefaults(final Configuration defaults);
/** /**
* Sets the source of all default values for this {@link Configuration}. * Sets the source of all default values for this {@link Configuration}.
@ -61,7 +60,7 @@ public interface Configuration extends ConfigurationSection {
* @param defaults New source of default values for this configuration. * @param defaults New source of default values for this configuration.
* @throws IllegalArgumentException Thrown if defaults is null or this. * @throws IllegalArgumentException Thrown if defaults is null or this.
*/ */
public void setDefaults(final Configuration defaults); void setDefaults(final Configuration defaults);
/** /**
* Gets the source {@link Configuration} for this configuration. * Gets the source {@link Configuration} for this configuration.
@ -72,7 +71,7 @@ public interface Configuration extends ConfigurationSection {
* *
* @return Configuration source for default values, or null if none exist. * @return Configuration source for default values, or null if none exist.
*/ */
public Configuration getDefaults(); Configuration getDefaults();
/** /**
* Gets the {@link ConfigurationOptions} for this {@link Configuration}. * Gets the {@link ConfigurationOptions} for this {@link Configuration}.
@ -81,5 +80,5 @@ public interface Configuration extends ConfigurationSection {
* *
* @return Options for this configuration * @return Options for this configuration
*/ */
public ConfigurationOptions options(); ConfigurationOptions options();
} }

View File

@ -8,6 +8,7 @@ import java.util.Set;
* Represents a section of a {@link Configuration} * Represents a section of a {@link Configuration}
*/ */
public interface ConfigurationSection { public interface ConfigurationSection {
/** /**
* Gets a set containing all keys in this section. * Gets a set containing all keys in this section.
* <p> * <p>
@ -22,8 +23,8 @@ public interface ConfigurationSection {
* list. * list.
* @return Set of keys contained within this ConfigurationSection. * @return Set of keys contained within this ConfigurationSection.
*/ */
public Set<String> getKeys(final boolean deep); Set<String> getKeys(boolean deep);
/** /**
* Gets a Map containing all keys and their values for this section. * Gets a Map containing all keys and their values for this section.
* <p> * <p>
@ -38,8 +39,8 @@ public interface ConfigurationSection {
* list. * list.
* @return Map of keys and values of this section. * @return Map of keys and values of this section.
*/ */
public Map<String, Object> getValues(final boolean deep); Map<String, Object> getValues(boolean deep);
/** /**
* Checks if this {@link ConfigurationSection} contains the given path. * Checks if this {@link ConfigurationSection} contains the given path.
* <p> * <p>
@ -51,8 +52,8 @@ public interface ConfigurationSection {
* default or being set. * default or being set.
* @throws IllegalArgumentException Thrown when path is null. * @throws IllegalArgumentException Thrown when path is null.
*/ */
public boolean contains(final String path); boolean contains(String path);
/** /**
* Checks if this {@link ConfigurationSection} has a value set for the * Checks if this {@link ConfigurationSection} has a value set for the
* given path. * given path.
@ -65,8 +66,8 @@ public interface ConfigurationSection {
* having a default. * having a default.
* @throws IllegalArgumentException Thrown when path is null. * @throws IllegalArgumentException Thrown when path is null.
*/ */
public boolean isSet(final String path); boolean isSet(String path);
/** /**
* Gets the path of this {@link ConfigurationSection} from its root {@link * Gets the path of this {@link ConfigurationSection} from its root {@link
* Configuration} * Configuration}
@ -82,8 +83,8 @@ public interface ConfigurationSection {
* *
* @return Path of this section relative to its root * @return Path of this section relative to its root
*/ */
public String getCurrentPath(); String getCurrentPath();
/** /**
* Gets the name of this individual {@link ConfigurationSection}, in the * Gets the name of this individual {@link ConfigurationSection}, in the
* path. * path.
@ -93,8 +94,8 @@ public interface ConfigurationSection {
* *
* @return Name of this section * @return Name of this section
*/ */
public String getName(); String getName();
/** /**
* Gets the root {@link Configuration} that contains this {@link * Gets the root {@link Configuration} that contains this {@link
* ConfigurationSection} * ConfigurationSection}
@ -107,8 +108,8 @@ public interface ConfigurationSection {
* *
* @return Root configuration containing this section. * @return Root configuration containing this section.
*/ */
public Configuration getRoot(); Configuration getRoot();
/** /**
* Gets the parent {@link ConfigurationSection} that directly contains * Gets the parent {@link ConfigurationSection} that directly contains
* this {@link ConfigurationSection}. * this {@link ConfigurationSection}.
@ -120,8 +121,8 @@ public interface ConfigurationSection {
* *
* @return Parent section containing this section. * @return Parent section containing this section.
*/ */
public ConfigurationSection getParent(); ConfigurationSection getParent();
/** /**
* Gets the requested Object by path. * Gets the requested Object by path.
* <p> * <p>
@ -132,8 +133,8 @@ public interface ConfigurationSection {
* @param path Path of the Object to get. * @param path Path of the Object to get.
* @return Requested Object. * @return Requested Object.
*/ */
public Object get(final String path); Object get(String path);
/** /**
* Gets the requested Object by path, returning a default value if not * Gets the requested Object by path, returning a default value if not
* found. * found.
@ -146,8 +147,8 @@ public interface ConfigurationSection {
* @param def The default value to return if the path is not found. * @param def The default value to return if the path is not found.
* @return Requested Object. * @return Requested Object.
*/ */
public Object get(final String path, final Object def); Object get(String path, Object def);
/** /**
* Sets the specified path to the given value. * Sets the specified path to the given value.
* <p> * <p>
@ -162,8 +163,8 @@ public interface ConfigurationSection {
* @param path Path of the object to set. * @param path Path of the object to set.
* @param value New value to set the path to. * @param value New value to set the path to.
*/ */
public void set(final String path, final Object value); void set(String path, Object value);
/** /**
* Creates an empty {@link ConfigurationSection} at the specified path. * Creates an empty {@link ConfigurationSection} at the specified path.
* <p> * <p>
@ -174,8 +175,8 @@ public interface ConfigurationSection {
* @param path Path to create the section at. * @param path Path to create the section at.
* @return Newly created section * @return Newly created section
*/ */
public ConfigurationSection createSection(final String path); ConfigurationSection createSection(String path);
/** /**
* Creates a {@link ConfigurationSection} at the specified path, with * Creates a {@link ConfigurationSection} at the specified path, with
* specified values. * specified values.
@ -188,9 +189,10 @@ public interface ConfigurationSection {
* @param map The values to used. * @param map The values to used.
* @return Newly created section * @return Newly created section
*/ */
public ConfigurationSection createSection(final String path, final Map<?, ?> map); ConfigurationSection createSection(String path, Map<?, ?> map);
// Primitives // Primitives
/** /**
* Gets the requested String by path. * Gets the requested String by path.
* <p> * <p>
@ -201,8 +203,8 @@ public interface ConfigurationSection {
* @param path Path of the String to get. * @param path Path of the String to get.
* @return Requested String. * @return Requested String.
*/ */
public String getString(final String path); String getString(String path);
/** /**
* Gets the requested String by path, returning a default value if not * Gets the requested String by path, returning a default value if not
* found. * found.
@ -216,60 +218,60 @@ public interface ConfigurationSection {
* not a String. * not a String.
* @return Requested String. * @return Requested String.
*/ */
public String getString(final String path, final String def); String getString(String path, String def);
/** /**
* Checks if the specified path is a String. * Checks if the specified path is a String.
* <p> *
* If the path exists but is not a String, this will return false. If the * <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 * 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 * but a default value has been specified, this will check if that default
* value is a String and return appropriately. * value is a String and return appropriately.</p>
* *
* @param path Path of the String to check. * @param path Path of the String to check.
* @return Whether or not the specified path is a String. * @return Whether or not the specified path is a String.
*/ */
public boolean isString(final String path); boolean isString(String path);
/** /**
* Gets the requested int by path. * Gets the requested int by path.
* <p> *
* If the int does not exist but a default value has been specified, this * <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 * will return the default value. If the int does not exist and no default
* value was specified, this will return 0. * value was specified, this will return 0.</p>
* *
* @param path Path of the int to get. * @param path Path of the int to get.
* @return Requested int. * @return Requested int.
*/ */
public int getInt(final String path); int getInt(String path);
/** /**
* Gets the requested int by path, returning a default value if not found. * Gets the requested int by path, returning a default value if not found.
* <p> *
* If the int does not exist then the specified default value will * <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 * returned regardless of if a default has been identified in the root
* {@link Configuration}. * {@link Configuration}.</p>
* *
* @param path Path of the int to get. * @param path Path of the int to get.
* @param def The default value to return if the path is not found or is * @param def The default value to return if the path is not found or is
* not an int. * not an int.
* @return Requested int. * @return Requested int.
*/ */
public int getInt(final String path, final int def); int getInt(String path, int def);
/** /**
* Checks if the specified path is an int. * Checks if the specified path is an int.
* <p> *
* If the path exists but is not a int, this will return false. If the * <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 * 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 * but a default value has been specified, this will check if that default
* value is a int and return appropriately. * value is a int and return appropriately.</p>
* *
* @param path Path of the int to check. * @param path Path of the int to check.
* @return Whether or not the specified path is an int. * @return Whether or not the specified path is an int.
*/ */
public boolean isInt(final String path); boolean isInt(String path);
/** /**
* Gets the requested boolean by path. * Gets the requested boolean by path.
* <p> * <p>
@ -280,8 +282,8 @@ public interface ConfigurationSection {
* @param path Path of the boolean to get. * @param path Path of the boolean to get.
* @return Requested boolean. * @return Requested boolean.
*/ */
public boolean getBoolean(final String path); boolean getBoolean(String path);
/** /**
* Gets the requested boolean by path, returning a default value if not * Gets the requested boolean by path, returning a default value if not
* found. * found.
@ -295,8 +297,8 @@ public interface ConfigurationSection {
* not a boolean. * not a boolean.
* @return Requested boolean. * @return Requested boolean.
*/ */
public boolean getBoolean(final String path, final boolean def); boolean getBoolean(String path, boolean def);
/** /**
* Checks if the specified path is a boolean. * Checks if the specified path is a boolean.
* <p> * <p>
@ -308,8 +310,8 @@ public interface ConfigurationSection {
* @param path Path of the boolean to check. * @param path Path of the boolean to check.
* @return Whether or not the specified path is a boolean. * @return Whether or not the specified path is a boolean.
*/ */
public boolean isBoolean(final String path); boolean isBoolean(String path);
/** /**
* Gets the requested double by path. * Gets the requested double by path.
* <p> * <p>
@ -320,8 +322,8 @@ public interface ConfigurationSection {
* @param path Path of the double to get. * @param path Path of the double to get.
* @return Requested double. * @return Requested double.
*/ */
public double getDouble(final String path); double getDouble(String path);
/** /**
* Gets the requested double by path, returning a default value if not * Gets the requested double by path, returning a default value if not
* found. * found.
@ -335,8 +337,8 @@ public interface ConfigurationSection {
* not a double. * not a double.
* @return Requested double. * @return Requested double.
*/ */
public double getDouble(final String path, final double def); double getDouble(String path, double def);
/** /**
* Checks if the specified path is a double. * Checks if the specified path is a double.
* <p> * <p>
@ -348,8 +350,8 @@ public interface ConfigurationSection {
* @param path Path of the double to check. * @param path Path of the double to check.
* @return Whether or not the specified path is a double. * @return Whether or not the specified path is a double.
*/ */
public boolean isDouble(final String path); boolean isDouble(String path);
/** /**
* Gets the requested long by path. * Gets the requested long by path.
* <p> * <p>
@ -360,8 +362,8 @@ public interface ConfigurationSection {
* @param path Path of the long to get. * @param path Path of the long to get.
* @return Requested long. * @return Requested long.
*/ */
public long getLong(final String path); long getLong(String path);
/** /**
* Gets the requested long by path, returning a default value if not * Gets the requested long by path, returning a default value if not
* found. * found.
@ -375,8 +377,8 @@ public interface ConfigurationSection {
* not a long. * not a long.
* @return Requested long. * @return Requested long.
*/ */
public long getLong(final String path, final long def); long getLong(String path, long def);
/** /**
* Checks if the specified path is a long. * Checks if the specified path is a long.
* <p> * <p>
@ -388,9 +390,10 @@ public interface ConfigurationSection {
* @param path Path of the long to check. * @param path Path of the long to check.
* @return Whether or not the specified path is a long. * @return Whether or not the specified path is a long.
*/ */
public boolean isLong(final String path); boolean isLong(String path);
// Java // Java
/** /**
* Gets the requested List by path. * Gets the requested List by path.
* <p> * <p>
@ -401,8 +404,8 @@ public interface ConfigurationSection {
* @param path Path of the List to get. * @param path Path of the List to get.
* @return Requested List. * @return Requested List.
*/ */
public List<?> getList(final String path); List<?> getList(String path);
/** /**
* Gets the requested List by path, returning a default value if not * Gets the requested List by path, returning a default value if not
* found. * found.
@ -416,8 +419,8 @@ public interface ConfigurationSection {
* not a List. * not a List.
* @return Requested List. * @return Requested List.
*/ */
public List<?> getList(final String path, final List<?> def); List<?> getList(String path, List<?> def);
/** /**
* Checks if the specified path is a List. * Checks if the specified path is a List.
* <p> * <p>
@ -429,8 +432,8 @@ public interface ConfigurationSection {
* @param path Path of the List to check. * @param path Path of the List to check.
* @return Whether or not the specified path is a List. * @return Whether or not the specified path is a List.
*/ */
public boolean isList(final String path); boolean isList(String path);
/** /**
* Gets the requested List of String by path. * Gets the requested List of String by path.
* <p> * <p>
@ -444,8 +447,8 @@ public interface ConfigurationSection {
* @param path Path of the List to get. * @param path Path of the List to get.
* @return Requested List of String. * @return Requested List of String.
*/ */
public List<String> getStringList(final String path); List<String> getStringList(String path);
/** /**
* Gets the requested List of Integer by path. * Gets the requested List of Integer by path.
* <p> * <p>
@ -459,8 +462,8 @@ public interface ConfigurationSection {
* @param path Path of the List to get. * @param path Path of the List to get.
* @return Requested List of Integer. * @return Requested List of Integer.
*/ */
public List<Integer> getIntegerList(final String path); List<Integer> getIntegerList(String path);
/** /**
* Gets the requested List of Boolean by path. * Gets the requested List of Boolean by path.
* <p> * <p>
@ -474,8 +477,8 @@ public interface ConfigurationSection {
* @param path Path of the List to get. * @param path Path of the List to get.
* @return Requested List of Boolean. * @return Requested List of Boolean.
*/ */
public List<Boolean> getBooleanList(final String path); List<Boolean> getBooleanList(String path);
/** /**
* Gets the requested List of Double by path. * Gets the requested List of Double by path.
* <p> * <p>
@ -489,8 +492,8 @@ public interface ConfigurationSection {
* @param path Path of the List to get. * @param path Path of the List to get.
* @return Requested List of Double. * @return Requested List of Double.
*/ */
public List<Double> getDoubleList(final String path); List<Double> getDoubleList(String path);
/** /**
* Gets the requested List of Float by path. * Gets the requested List of Float by path.
* <p> * <p>
@ -504,8 +507,8 @@ public interface ConfigurationSection {
* @param path Path of the List to get. * @param path Path of the List to get.
* @return Requested List of Float. * @return Requested List of Float.
*/ */
public List<Float> getFloatList(final String path); List<Float> getFloatList(String path);
/** /**
* Gets the requested List of Long by path. * Gets the requested List of Long by path.
* <p> * <p>
@ -519,8 +522,8 @@ public interface ConfigurationSection {
* @param path Path of the List to get. * @param path Path of the List to get.
* @return Requested List of Long. * @return Requested List of Long.
*/ */
public List<Long> getLongList(final String path); List<Long> getLongList(String path);
/** /**
* Gets the requested List of Byte by path. * Gets the requested List of Byte by path.
* <p> * <p>
@ -534,8 +537,8 @@ public interface ConfigurationSection {
* @param path Path of the List to get. * @param path Path of the List to get.
* @return Requested List of Byte. * @return Requested List of Byte.
*/ */
public List<Byte> getByteList(final String path); List<Byte> getByteList(String path);
/** /**
* Gets the requested List of Character by path. * Gets the requested List of Character by path.
* <p> * <p>
@ -549,8 +552,8 @@ public interface ConfigurationSection {
* @param path Path of the List to get. * @param path Path of the List to get.
* @return Requested List of Character. * @return Requested List of Character.
*/ */
public List<Character> getCharacterList(final String path); List<Character> getCharacterList(String path);
/** /**
* Gets the requested List of Short by path. * Gets the requested List of Short by path.
* <p> * <p>
@ -564,8 +567,8 @@ public interface ConfigurationSection {
* @param path Path of the List to get. * @param path Path of the List to get.
* @return Requested List of Short. * @return Requested List of Short.
*/ */
public List<Short> getShortList(final String path); List<Short> getShortList(String path);
/** /**
* Gets the requested List of Maps by path. * Gets the requested List of Maps by path.
* <p> * <p>
@ -579,8 +582,8 @@ public interface ConfigurationSection {
* @param path Path of the List to get. * @param path Path of the List to get.
* @return Requested List of Maps. * @return Requested List of Maps.
*/ */
public List<Map<?, ?>> getMapList(final String path); List<Map<?, ?>> getMapList(String path);
/** /**
* Gets the requested ConfigurationSection by path. * Gets the requested ConfigurationSection by path.
* <p> * <p>
@ -592,8 +595,8 @@ public interface ConfigurationSection {
* @param path Path of the ConfigurationSection to get. * @param path Path of the ConfigurationSection to get.
* @return Requested ConfigurationSection. * @return Requested ConfigurationSection.
*/ */
public ConfigurationSection getConfigurationSection(final String path); ConfigurationSection getConfigurationSection(String path);
/** /**
* Checks if the specified path is a ConfigurationSection. * Checks if the specified path is a ConfigurationSection.
* <p> * <p>
@ -606,8 +609,8 @@ public interface ConfigurationSection {
* @param path Path of the ConfigurationSection to check. * @param path Path of the ConfigurationSection to check.
* @return Whether or not the specified path is a ConfigurationSection. * @return Whether or not the specified path is a ConfigurationSection.
*/ */
public boolean isConfigurationSection(final String path); boolean isConfigurationSection(String path);
/** /**
* Gets the equivalent {@link ConfigurationSection} from the default * Gets the equivalent {@link ConfigurationSection} from the default
* {@link Configuration} defined in {@link #getRoot()}. * {@link Configuration} defined in {@link #getRoot()}.
@ -618,8 +621,8 @@ public interface ConfigurationSection {
* *
* @return Equivalent section in root configuration * @return Equivalent section in root configuration
*/ */
public ConfigurationSection getDefaultSection(); ConfigurationSection getDefaultSection();
/** /**
* Sets the default value in the root at the given path as provided. * Sets the default value in the root at the given path as provided.
* <p> * <p>
@ -638,5 +641,5 @@ public interface ConfigurationSection {
* @param value Value to set the default to. * @param value Value to set the default to.
* @throws IllegalArgumentException Thrown if path is null. * @throws IllegalArgumentException Thrown if path is null.
*/ */
public void addDefault(final String path, final Object value); void addDefault(String path, Object value);
} }

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