Compare commits

..

262 Commits

Author SHA1 Message Date
9fa28e1179 * 2016-06-20 01:50:43 +10:00
c3dd28caeb Fix clear done flag requirements 2016-06-20 01:49:35 +10:00
0888940307 bump version 2016-06-20 01:37:27 +10:00
ce7468e63a Fix economy NPE 2016-06-20 00:52:05 +10:00
f5e7d08ace Allow duplicates after 5s 2016-06-19 16:14:13 +10:00
3ce225c044 Bump version 2016-06-19 15:51:46 +10:00
c2f10a7065 Update desc for debugpaste 2016-06-19 13:44:14 +10:00
8512adf9d6 Fix for augmented 2016-06-19 13:01:30 +10:00
b2c885e8d1 Merge pull request #1197 from manuelgu/patch-1
Fix #1196
2016-06-19 00:15:20 +02:00
5eabf863d6 Fix #1196 2016-06-19 00:11:21 +02:00
cff30a1db4 Fix scripting initialization 2016-06-18 16:29:51 +10:00
ab51d27e49 Remove pointless thread dump 2016-06-18 15:01:42 +10:00
6375922808 I can't count + fix variable scope 2016-06-18 13:54:35 +10:00
29ce4af350 Fixes #987 and #299 (untested)
Example usage:
claim: 50*{arg}
2016-06-18 13:43:34 +10:00
3ced832b80 Fix biome stripes (whoops) 2016-06-18 13:15:50 +10:00
91c742c141 Fixes #590 2016-06-18 13:13:36 +10:00
232091454a Fix augmented 2016-06-18 12:44:56 +10:00
600d060b6e Fix sponge compile issue 2016-06-17 22:05:06 +10:00
081081b36e Fixes #1063 2016-06-17 15:42:23 +10:00
4319300b34 Fixes #1126 2016-06-17 13:46:13 +10:00
b2b90a8d17 Fixes #1064 2016-06-17 13:33:47 +10:00
480453b716 Various
Fixes #1177
Additional check for left click with milk on adult entity
Add setting for enabling persistent meta
Only set fly persistent meta if it differs from the current gamemode fly
mode.
2016-06-16 20:16:48 +10:00
28ad14500a Fixes #1172 2016-06-16 17:59:39 +10:00
2bbfec1a32 Fix load / flush queue before sending message 2016-06-16 17:31:02 +10:00
b2997b7c7b Don't send duplicate messages 2016-06-16 10:31:33 +10:00
472aadcd01 Add suggestion for flags when invalid flag name was given :] 2016-06-16 02:30:16 +02:00
5b103d49c0 Fixes #1171 2016-06-16 02:08:01 +02:00
ae5e15e434 Fix invalid record type error 2016-06-13 15:05:38 -04:00
341967cbfc Reclassify armor stand as vehicle 2016-06-13 15:35:33 +10:00
b238bdbd21 Fix armor stand / hangings being considered vehicles 2016-06-13 15:32:13 +10:00
4f0ede646e Chat / Merge blocks placer / generator 2016-06-13 14:47:50 +10:00
506455ae40 Remove debug 2016-06-12 15:33:56 +10:00
15c7957d0e Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared 2016-06-12 15:27:23 +10:00
6165469e76 Fix scripting 2016-06-12 15:26:58 +10:00
a7087f314f Merge remote-tracking branch 'origin/master' 2016-06-11 19:25:27 -04:00
0cfef63376 Fix backwards compatibility 2016-06-11 19:25:13 -04:00
bfd9b53555 Update pom 2016-06-11 11:58:11 +10:00
5bdb2263dc CheckStyle code tweaks 2016-06-10 14:04:55 -04:00
76bcb76905 Merge remote-tracking branch 'origin/master' 2016-06-10 13:31:41 -04:00
93deebf4ca 1.10 fixes 2016-06-10 13:31:28 -04:00
482f4d6815 Modify Setting and Storage class names. 2016-06-10 13:00:34 -04:00
0d47e4599f Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared 2016-06-09 18:06:08 +10:00
f41c7dc1f6 Fix NPE 2016-06-09 18:06:00 +10:00
8fe381d098 Fix SpongeCommand 2016-06-08 19:06:07 -04:00
12c01760a6 Tweaks and small memory improvement. 2016-06-06 01:43:06 -04:00
880e084006 Register expiry tasks 2016-06-06 12:47:54 +10:00
f1f6b2781e Fix INSTABREAK flag 2016-06-06 06:34:05 +10:00
237a0d8b6b Always cache * uuid 2016-06-05 20:11:02 +10:00
a1c722aa9e Fix player location/current plot 2016-06-05 20:03:05 +10:00
960ad50070 Use DBFunc instead of dbManager 2016-06-05 19:54:33 +10:00
7d44850bb0 Mask getBlock 2016-06-05 19:46:52 +10:00
7427d83ae2 final primitives are final 2016-06-05 19:39:51 +10:00
48cf381ed6 * 2016-06-05 18:57:11 +10:00
0114dd7558 Fix convert 2016-06-05 18:42:34 +10:00
48382e0c4e Remove null version from storage 2016-06-05 18:23:24 +10:00
ce23ad5615 Fix NPE 2016-06-05 18:07:41 +10:00
0b1153da21 Include other config files in DebugPaste 2016-06-05 17:43:40 +10:00
386157edc1 fix reserved flags 2016-06-05 17:35:44 +10:00
b7a8c8ecd6 Don't need this 2016-06-05 17:33:06 +10:00
951a6b82a2 simplify config / multiple expiry tasks / block cache fix 2016-06-05 17:28:43 +10:00
70aaa984e2 Documentation and Flag Changes. 2016-06-04 17:19:37 -04:00
17ff6a7e1d Merge pull request #1157 from MisterErwin/master
Fixed invalid condition
2016-06-05 04:34:47 +10:00
281f60a4ef Fixed invalid condition 2016-06-04 20:26:32 +02:00
ca5d3a818b PlotBlock cache / events / flags 2016-06-04 06:20:13 +10:00
f84766074e Fixes #1145 2016-06-04 03:36:39 +10:00
7dba332455 Debug a player is added to the known list. 2016-06-03 11:17:08 -04:00
b4707c94c4 Fix #579
Also tweaks to deprecation for development purposes.
2016-06-03 10:57:25 -04:00
0147690eba Make Sponge compile
It doesn't work but it allows the project to compile.
2016-06-02 19:38:35 -04:00
cee970e3d9 Tweaked some things 2016-06-02 13:42:32 -04:00
da58c7b411 Beautify code 2016-06-02 11:38:47 -04:00
8e306a92e3 Condense HttpUtil 2016-06-02 09:59:54 -04:00
89c4ce24ef Merge branch 'fix/forcefieldflag' of https://github.com/manuelgu/PlotSquared into manuelgu-fix/forcefieldflag 2016-06-02 09:52:30 -04:00
e6433a24ab Fix grow flags 2016-06-02 00:33:50 -04:00
f21d159911 Various fixes and tweaks. 2016-06-01 16:50:35 -04:00
042d8950ee Fix #1139 2016-05-29 20:48:14 -04:00
8d6565c32c Fix NPE 2016-05-29 19:38:31 +02:00
def33bc9ad Fix IntellectualSites/PlotSquared#1140 2016-05-29 11:59:16 +02:00
53e4b728a6 Merge remote-tracking branch 'origin/master' 2016-05-28 22:38:10 -04:00
4af846967c Fix #958 2016-05-28 22:37:56 -04:00
9ae4f02205 Fix forcefield flag 2016-05-28 01:16:01 +02:00
85055320c2 Merge pull request #1134 from manuelgu/feature/componentevent
[WIP] Implement PlotComponentSetEvent
2016-05-28 09:13:04 +10:00
d7b2881778 Don't * import 2016-05-28 01:12:05 +02:00
a7c965c6b0 Merge branch 'feature/componentevent' of https://github.com/manuelgu/PlotSquared into feature/componentevent 2016-05-28 01:09:25 +02:00
ec4839ec3f Move event calling to Plot class 2016-05-28 01:09:13 +02:00
b5cc6eeb0c Merge remote-tracking branch 'origin/master'
# Conflicts:
#	Sponge/src/main/java/com/plotsquared/sponge/SpongeMain.java
2016-05-28 08:45:35 +10:00
4078f0708b Proper javadoc for event 2016-05-28 00:29:27 +02:00
28a5c9f597 Remove pre-init logging 2016-05-28 02:01:50 +10:00
604f62dbd3 Remove dumb log statement 2016-05-27 11:10:36 -04:00
6c40ed7718 Fix Titles 2016-05-27 10:54:06 -04:00
e615fb4c44 Merge remote-tracking branch 'origin/master' 2016-05-26 09:19:50 -04:00
cc2d99849b Optimizations and javadoc tweaks 2016-05-26 09:19:38 -04:00
ceb8fb9fa3 Implement PlotComponentSetEvent 2016-05-25 21:49:55 +02:00
d44ca23abd Minor change to issue template (#1132) 2016-05-25 15:14:16 -04:00
ef60aeb017 Minor change to issue template 2016-05-25 20:54:26 +02:00
88ad051637 Direction/chance for bo3 2016-05-26 04:14:47 +10:00
465f7f4504 Tweaks and doc updates. 2016-05-24 22:08:45 -04:00
83f664129f Fixes #1130 2016-05-23 17:27:40 +10:00
a2a43816ad *And this 2016-05-23 04:41:25 +10:00
7bdcde6d24 Why was this made private? 2016-05-23 04:12:11 +10:00
89442a0e77 Fix visit 2016-05-22 07:13:59 +10:00
b8afbe8a00 Optimize auto trim + command cost/confirmation 2016-05-22 05:29:27 +10:00
e2182260d9 Fix Sponge Errors 2016-05-21 12:55:06 -04:00
6f26e42251 Fix Sponge Errors 2016-05-21 12:54:50 -04:00
13b7a798e6 ignored exception 2016-05-21 11:54:00 -04:00
8af30667e4 ignored exception 2016-05-21 11:18:35 -04:00
4bd83ab298 Logger changes 2016-05-21 11:16:21 -04:00
7ae5042c32 Recover from bad data file
Closes #1122
2016-05-22 01:16:04 +10:00
3ea2d06e70 Closes #1124 2016-05-22 01:11:27 +10:00
4ceb54b566 Add logger 2016-05-22 00:47:14 +10:00
dc4776d16b Sponge changes. 2016-05-21 10:39:06 -04:00
b51d659ff9 Merge remote-tracking branch 'origin/master' 2016-05-20 20:29:32 -04:00
1768943360 Register flags 2016-05-20 20:29:16 -04:00
6b1298a5e6 *Fix version check 2016-05-20 05:10:46 +10:00
b125ef6668 Add git revision hash to version 2016-05-20 03:32:35 +10:00
82e162ae00 * 2016-05-20 03:29:51 +10:00
5665e9b709 Fix merging sometimes not removing intersection 2016-05-20 03:25:45 +10:00
6bad640cec Fixes #1037 2016-05-19 18:53:07 +10:00
7873bcf592 Fixes #1102 2016-05-19 18:28:06 +10:00
75c7fe969c Fixes #1008 2016-05-19 18:20:23 +10:00
1df9ae77ab Fixes #1111 2016-05-19 18:13:37 +10:00
78796ca7b4 Fixes #1117 2016-05-19 18:09:12 +10:00
1ece792e2b Create parent directory for bo3 2016-05-18 16:35:37 +10:00
1b9c92fd4a Fix #1067 2016-05-17 21:52:36 -04:00
18e3a7553e Fix #1085
Fix #1085
2016-05-15 22:05:52 -04:00
64f3e8f79b Fixes #1116 2016-05-15 01:54:12 +10:00
c70c2283a2 Recover from failed event registration 2016-05-14 23:50:43 +10:00
4b962c35ab Merge pull request #1118 from manuelgu/apilocationremoval
Remove unused API Location that got printed on startup
2016-05-14 21:46:20 +10:00
72096db8d6 Remove unused API Location that got printed on startup 2016-05-14 12:33:52 +02:00
2039cb2891 Merge pull request #1112 from manuelgu/stuffnthings
Method renaming, util class and logic change
2016-05-14 15:04:11 +10:00
a5a001130c Fetch latest vesion on command
PS.get().update would return the URL of the latest update at the time
the server was started. Not everybody is restarting their servers daily
so it might end up in people not noticing an update in a long while
2016-05-13 19:09:40 +02:00
c1bc3dfc29 Add HttpUtil utility class 2016-05-13 19:07:56 +02:00
7701e7f05f Beautify listing of plot areas 2016-05-13 19:05:50 +02:00
2c0743b7e9 Proper method name 2016-05-13 19:04:55 +02:00
00340d5154 Important fix 2016-05-14 01:13:08 +10:00
d47eeff23b Cleaning and Fix #1108 2016-05-12 18:00:38 -04:00
0958b57e46 Tidy code. 2016-05-12 17:09:35 -04:00
7947c3fdd7 Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared 2016-05-12 15:43:44 -04:00
0095af0ce5 Flag info 2016-05-13 03:38:32 +10:00
dee8072d83 Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared
# Conflicts:

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

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

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

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

View File

@ -7,6 +7,6 @@
Make sure you've completed the following steps (put an X between 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?utf8=%E2%9C%93&q=is%3Aissue)
- [] 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

View File

@ -1,8 +1,8 @@
dependencies { dependencies {
compile project(':Core') compile project(':Core')
compile 'org.bukkit:bukkit:1.9-R0.1-SNAPSHOT' compile 'org.bukkit:bukkit:1.10-R0.1-SNAPSHOT'
compile 'org.mcstats.bukkit:metrics:R7' compile 'org.mcstats.bukkit:metrics:R7'
compile 'net.milkbowl.vault:VaultAPI:1.5' compile 'net.milkbowl.vault:VaultAPI:1.6'
} }
sourceCompatibility = 1.7 sourceCompatibility = 1.7

View File

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

View File

@ -6,7 +6,6 @@ import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.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;
import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.generator.GeneratorWrapper; import com.intellectualcrafters.plot.generator.GeneratorWrapper;
import com.intellectualcrafters.plot.generator.HybridGen; import com.intellectualcrafters.plot.generator.HybridGen;
import com.intellectualcrafters.plot.generator.HybridUtils; import com.intellectualcrafters.plot.generator.HybridUtils;
@ -24,7 +23,6 @@ import com.intellectualcrafters.plot.util.EconHandler;
import com.intellectualcrafters.plot.util.EventUtil; import com.intellectualcrafters.plot.util.EventUtil;
import com.intellectualcrafters.plot.util.InventoryUtil; import com.intellectualcrafters.plot.util.InventoryUtil;
import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.PlotQueue;
import com.intellectualcrafters.plot.util.SchematicHandler; import com.intellectualcrafters.plot.util.SchematicHandler;
import com.intellectualcrafters.plot.util.SetupUtils; import com.intellectualcrafters.plot.util.SetupUtils;
import com.intellectualcrafters.plot.util.StringMan; import com.intellectualcrafters.plot.util.StringMan;
@ -32,8 +30,8 @@ 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.util.WorldUtil; import com.intellectualcrafters.plot.util.WorldUtil;
import com.intellectualcrafters.plot.util.block.QueueProvider;
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;
@ -43,9 +41,9 @@ 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.PlayerEvents183;
import com.plotsquared.bukkit.listeners.PlayerEvents_1_8; import com.plotsquared.bukkit.listeners.PlayerEvents_1_8;
import com.plotsquared.bukkit.listeners.PlayerEvents_1_9;
import com.plotsquared.bukkit.listeners.PlotPlusListener; import com.plotsquared.bukkit.listeners.PlotPlusListener;
import com.plotsquared.bukkit.listeners.WorldEvents; import com.plotsquared.bukkit.listeners.WorldEvents;
import com.plotsquared.bukkit.listeners.worldedit.WEListener;
import com.plotsquared.bukkit.titles.DefaultTitle_19; 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;
@ -62,17 +60,17 @@ import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.bukkit.util.Metrics; import com.plotsquared.bukkit.util.Metrics;
import com.plotsquared.bukkit.util.SendChunk; import com.plotsquared.bukkit.util.SendChunk;
import com.plotsquared.bukkit.util.SetGenCB; import com.plotsquared.bukkit.util.SetGenCB;
import com.plotsquared.bukkit.util.block.FastQueue_1_7; import com.plotsquared.bukkit.util.block.BukkitLocalQueue;
import com.plotsquared.bukkit.util.block.FastQueue_1_8; import com.plotsquared.bukkit.util.block.BukkitLocalQueue_1_7;
import com.plotsquared.bukkit.util.block.FastQueue_1_8_3; import com.plotsquared.bukkit.util.block.BukkitLocalQueue_1_8;
import com.plotsquared.bukkit.util.block.FastQueue_1_9; import com.plotsquared.bukkit.util.block.BukkitLocalQueue_1_8_3;
import com.plotsquared.bukkit.util.block.SlowQueue; import com.plotsquared.bukkit.util.block.BukkitLocalQueue_1_9;
import com.plotsquared.bukkit.uuid.DefaultUUIDWrapper; import com.plotsquared.bukkit.uuid.DefaultUUIDWrapper;
import com.plotsquared.bukkit.uuid.FileUUIDHandler; import com.plotsquared.bukkit.uuid.FileUUIDHandler;
import com.plotsquared.bukkit.uuid.LowerOfflineUUIDWrapper; 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.WorldEdit;
import java.io.File; import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@ -86,6 +84,7 @@ import org.bukkit.OfflinePlayer;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.command.PluginCommand; import org.bukkit.command.PluginCommand;
import org.bukkit.entity.Entity; import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.generator.ChunkGenerator; import org.bukkit.generator.ChunkGenerator;
@ -93,10 +92,9 @@ import org.bukkit.metadata.MetadataValue;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
public class BukkitMain extends JavaPlugin implements Listener, IPlotMain { public final class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
public static BukkitMain THIS; public static WorldEdit worldEdit;
public static WorldEditPlugin worldEdit;
private int[] version; private int[] version;
@ -115,7 +113,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
e.printStackTrace(); e.printStackTrace();
PS.debug(StringMan.getString(Bukkit.getBukkitVersion())); PS.debug(StringMan.getString(Bukkit.getBukkitVersion()));
PS.debug(StringMan.getString(Bukkit.getBukkitVersion().split("-")[0].split("\\."))); PS.debug(StringMan.getString(Bukkit.getBukkitVersion().split("-")[0].split("\\.")));
return new int[]{Integer.MAX_VALUE, 0, 0}; return new int[]{1, 9, 2};
} }
} }
return this.version; return this.version;
@ -123,7 +121,6 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
@Override @Override
public void onEnable() { public void onEnable() {
THIS = this;
new PS(this, "Bukkit"); new PS(this, "Bukkit");
} }
@ -131,47 +128,43 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
public void onDisable() { public void onDisable() {
PS.get().disable(); PS.get().disable();
Bukkit.getScheduler().cancelTasks(this); Bukkit.getScheduler().cancelTasks(this);
THIS = null;
} }
@Override @Override
public void log(String message) { public void log(String message) {
if (THIS != null) { try {
try { message = C.color(message);
message = C.color(message); if (!Settings.Chat.CONSOLE_COLOR) {
if (!Settings.CONSOLE_COLOR) { message = ChatColor.stripColor(message);
message = ChatColor.stripColor(message);
}
this.getServer().getConsoleSender().sendMessage(message);
return;
} catch (Throwable ignored) {
//ignored
} }
this.getServer().getConsoleSender().sendMessage(message);
} catch (Throwable ignored) {
System.out.println(ConsoleColors.fromString(message));
} }
System.out.println(ConsoleColors.fromString(message));
} }
@Override @Override
public void disable() { public void disable() {
if (THIS != null) { onDisable();
onDisable();
}
} }
@Override @Override
public int[] getPluginVersion() { public int[] getPluginVersion() {
String[] split = getDescription().getVersion().split("\\."); String ver = getDescription().getVersion();
if (ver.contains("-")) {
ver = ver.split("-")[0];
}
String[] split = ver.split("\\.");
return new int[]{Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2])}; return new int[]{Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2])};
} }
@Override @Override
public void registerCommands() { public void registerCommands() {
BukkitCommand bcmd = new BukkitCommand(); BukkitCommand bukkitCommand = new BukkitCommand();
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);
new DebugUUID();
} }
@Override @Override
@ -186,19 +179,19 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
@Override @Override
public TaskManager getTaskManager() { public TaskManager getTaskManager() {
return new BukkitTaskManager(); return new BukkitTaskManager(this);
} }
@Override @Override
public void runEntityTask() { public void runEntityTask() {
log(C.PREFIX + "KillAllEntities started."); PS.log(C.PREFIX + "KillAllEntities started.");
TaskManager.runTaskRepeat(new Runnable() { TaskManager.runTaskRepeat(new Runnable() {
@Override @Override
public void run() { public void run() {
PS.get().foreachPlotArea(new RunnableVal<PlotArea>() { PS.get().foreachPlotArea(new RunnableVal<PlotArea>() {
@Override @Override
public void run(PlotArea pw) { public void run(PlotArea plotArea) {
World world = Bukkit.getWorld(pw.worldname); World world = Bukkit.getWorld(plotArea.worldname);
try { try {
if (world == null) { if (world == null) {
return; return;
@ -213,6 +206,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
case COMPLEX_PART: case COMPLEX_PART:
case FISHING_HOOK: case FISHING_HOOK:
case ENDER_SIGNAL: case ENDER_SIGNAL:
case LINGERING_POTION:
case AREA_EFFECT_CLOUD: case AREA_EFFECT_CLOUD:
case EXPERIENCE_ORB: case EXPERIENCE_ORB:
case LEASH_HITCH: case LEASH_HITCH:
@ -221,10 +215,9 @@ 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:
@ -232,15 +225,15 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
case SPECTRAL_ARROW: case SPECTRAL_ARROW:
case TIPPED_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 ITEM_FRAME: case ITEM_FRAME:
case PAINTING: { case PAINTING:
// TEMPORARILY CLASSIFY AS VEHICLE // Not vehicles
} continue;
case ARMOR_STAND:
// Tempirarily classify as vehicle
case MINECART: case MINECART:
case MINECART_CHEST: case MINECART_CHEST:
case MINECART_COMMAND: case MINECART_COMMAND:
@ -249,7 +242,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
case MINECART_MOB_SPAWNER: case MINECART_MOB_SPAWNER:
case MINECART_TNT: case MINECART_TNT:
case BOAT: { case BOAT: {
if (!Settings.KILL_ROAD_VEHICLES) { if (!Settings.Enabled_Components.KILL_ROAD_VEHICLES) {
continue; continue;
} }
com.intellectualcrafters.plot.object.Location location = BukkitUtil.getLocation(entity.getLocation()); com.intellectualcrafters.plot.object.Location location = BukkitUtil.getLocation(entity.getLocation());
@ -275,15 +268,13 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
case SMALL_FIREBALL: case SMALL_FIREBALL:
case FIREBALL: case FIREBALL:
case DRAGON_FIREBALL: case DRAGON_FIREBALL:
case DROPPED_ITEM: { 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:
@ -317,19 +308,29 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
case WOLF: case WOLF:
case ZOMBIE: case ZOMBIE:
case SHULKER: case SHULKER:
default: { default:
if (!Settings.KILL_ROAD_MOBS) { if (!Settings.Enabled_Components.KILL_ROAD_MOBS) {
continue; continue;
} }
Location location = entity.getLocation(); Location location = entity.getLocation();
if (BukkitUtil.getLocation(location).isPlotRoad()) { if (BukkitUtil.getLocation(location).isPlotRoad()) {
Entity passenger = entity.getPassenger(); if (entity instanceof LivingEntity) {
if (!(passenger instanceof Player) && entity.getMetadata("keep").isEmpty()) { LivingEntity livingEntity = (LivingEntity) entity;
iterator.remove(); if (!livingEntity.isLeashed() || !entity.hasMetadata("keep")) {
entity.remove(); Entity passenger = entity.getPassenger();
if (!(passenger instanceof Player) && entity.getMetadata("keep").isEmpty()) {
iterator.remove();
entity.remove();
}
}
} else {
Entity passenger = entity.getPassenger();
if (!(passenger instanceof Player) && entity.getMetadata("keep").isEmpty()) {
iterator.remove();
entity.remove();
}
} }
} }
}
} }
} }
} catch (Throwable e) { } catch (Throwable e) {
@ -352,12 +353,28 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
@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); try {
getServer().getPluginManager().registerEvents(new PlayerEvents_1_8(), this);
} catch (Throwable e) {
e.printStackTrace();
}
} }
if (PS.get().checkVersion(getServerVersion(), 1, 8, 3)) { if (PS.get().checkVersion(getServerVersion(), 1, 8, 3)) {
getServer().getPluginManager().registerEvents(new PlayerEvents183(), this); try {
getServer().getPluginManager().registerEvents(new PlayerEvents183(), this);
} catch (Throwable e) {
e.printStackTrace();
}
}
if (PS.get().checkVersion(getServerVersion(), 1, 9, 0)) {
try {
getServer().getPluginManager().registerEvents(new PlayerEvents_1_9(main), this);
} catch (Throwable e) {
e.printStackTrace();
}
} }
} }
@ -380,8 +397,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
@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 = WorldEdit.getInstance();
getServer().getPluginManager().registerEvents(new WEListener(), this);
return true; return true;
} }
return false; return false;
@ -394,49 +410,31 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
if (econ.init()) { if (econ.init()) {
return econ; return econ;
} }
System.out.println("ECONOMY ENABLED!");
} catch (Throwable ignored) { } catch (Throwable ignored) {
ignored.printStackTrace(); PS.debug("No economy detected!");
} }
return null; return null;
} }
@Override @Override
public PlotQueue initPlotQueue() { public QueueProvider initBlockQueue() {
try { try {
new SendChunk(); new SendChunk();
MainUtil.canSendChunk = true; MainUtil.canSendChunk = true;
} catch (Throwable e) { } catch (ClassNotFoundException | NoSuchFieldException | NoSuchMethodException e) {
e.printStackTrace(); e.printStackTrace();
MainUtil.canSendChunk = false; MainUtil.canSendChunk = false;
} }
if (PS.get().checkVersion(getServerVersion(), 1, 9, 0)) { if (PS.get().checkVersion(getServerVersion(), 1, 9, 0)) {
try { return QueueProvider.of(BukkitLocalQueue_1_9.class, BukkitLocalQueue.class);
return new FastQueue_1_9(); }
} catch (Throwable e) { if (PS.get().checkVersion(getServerVersion(), 1, 8, 3)) {
e.printStackTrace(); return QueueProvider.of(BukkitLocalQueue_1_8_3.class, BukkitLocalQueue.class);
return new SlowQueue();
}
} }
if (PS.get().checkVersion(getServerVersion(), 1, 8, 0)) { if (PS.get().checkVersion(getServerVersion(), 1, 8, 0)) {
try { return QueueProvider.of(BukkitLocalQueue_1_8.class, BukkitLocalQueue.class);
return new FastQueue_1_8_3();
} catch (Throwable e) {
e.printStackTrace();
try {
return new FastQueue_1_8();
} catch (Throwable e2) {
e2.printStackTrace();
return new SlowQueue();
}
}
}
try {
return new FastQueue_1_7();
} catch (Throwable e) {
e.printStackTrace();
return new SlowQueue();
} }
return QueueProvider.of(BukkitLocalQueue_1_7.class, BukkitLocalQueue.class);
} }
@Override @Override
@ -455,12 +453,9 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
if (new LikePlotMeConverter("PlotMe").run(new PlotMeConnector_017())) { if (new LikePlotMeConverter("PlotMe").run(new PlotMeConnector_017())) {
return; return;
} }
if (new LikePlotMeConverter("AthionPlots").run(new ClassicPlotMeConnector())) {
return;
}
} }
}, 20); }, 20);
return Bukkit.getPluginManager().getPlugin("PlotMe") != null || Bukkit.getPluginManager().getPlugin("AthionPlots") != null; return Bukkit.getPluginManager().getPlugin("PlotMe") != null;
} }
@Override @Override
@ -494,42 +489,41 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
public UUIDHandlerImplementation initUUIDHandler() { public UUIDHandlerImplementation initUUIDHandler() {
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.UUID.OFFLINE) {
if (Settings.UUID_LOWERCASE) { if (Settings.UUID.FORCE_LOWERCASE) {
wrapper = new LowerOfflineUUIDWrapper(); wrapper = new LowerOfflineUUIDWrapper();
} else { } else {
wrapper = new OfflineUUIDWrapper(); wrapper = new OfflineUUIDWrapper();
} }
Settings.OFFLINE_MODE = true; Settings.UUID.OFFLINE = true;
} else if (checkVersion) { } else if (checkVersion) {
wrapper = new DefaultUUIDWrapper(); wrapper = new DefaultUUIDWrapper();
Settings.OFFLINE_MODE = false; Settings.UUID.OFFLINE = false;
} else { } else {
if (Settings.UUID_LOWERCASE) { if (Settings.UUID.FORCE_LOWERCASE) {
wrapper = new LowerOfflineUUIDWrapper(); wrapper = new LowerOfflineUUIDWrapper();
} else { } else {
wrapper = new OfflineUUIDWrapper(); wrapper = new OfflineUUIDWrapper();
} }
Settings.OFFLINE_MODE = true; Settings.UUID.OFFLINE = true;
} }
if (!checkVersion) { if (!checkVersion) {
log(C.PREFIX + " &c[WARN] Titles are disabled - please update your version of Bukkit to support this feature."); PS.log(C.PREFIX + " &c[WARN] Titles are disabled - please update your version of Bukkit to support this feature.");
Settings.TITLES = false; Settings.TITLES = false;
FlagManager.removeFlag(FlagManager.getFlag("titles"));
} else { } else {
AbstractTitle.TITLE_CLASS = new DefaultTitle_19(); 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.UUID.NATIVE_UUID_PROVIDER = true;
} }
} }
if (Settings.OFFLINE_MODE) { if (Settings.UUID.OFFLINE) {
log(C.PREFIX PS.log(C.PREFIX
+ " &6PlotSquared is using Offline Mode UUIDs either because of user preference, or because you are using an old version of " + " &6PlotSquared is using Offline Mode UUIDs either because of user preference, or because you are using an old version of "
+ "Bukkit"); + "Bukkit");
} else { } else {
log(C.PREFIX + " &6PlotSquared is using online UUIDs"); PS.log(C.PREFIX + " &6PlotSquared is using online UUIDs");
} }
if (Settings.USE_SQLUUIDHANDLER) { if (Settings.UUID.USE_SQLUUIDHANDLER) {
return new SQLUUIDHandler(wrapper); return new SQLUUIDHandler(wrapper);
} else { } else {
return new FileUUIDHandler(wrapper); return new FileUUIDHandler(wrapper);
@ -575,7 +569,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
public void startMetrics() { public void startMetrics() {
Metrics metrics = new Metrics(this); Metrics metrics = new Metrics(this);
metrics.start(); metrics.start();
log(C.PREFIX + "&6Metrics enabled."); PS.log(C.PREFIX + "&6Metrics enabled.");
} }
@Override @Override
@ -583,7 +577,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
World world = BukkitUtil.getWorld(worldName); World world = BukkitUtil.getWorld(worldName);
if (world == null) { if (world == null) {
// create world // create world
ConfigurationSection worldConfig = PS.get().config.getConfigurationSection("worlds." + worldName); ConfigurationSection worldConfig = PS.get().worlds.getConfigurationSection("worlds." + worldName);
String manager = worldConfig.getString("generator.plugin", "PlotSquared"); String manager = worldConfig.getString("generator.plugin", "PlotSquared");
SetupObject setup = new SetupObject(); SetupObject setup = new SetupObject();
setup.plotManager = manager; setup.plotManager = manager;
@ -598,8 +592,8 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
if (!PS.get().hasPlotArea(worldName)) { if (!PS.get().hasPlotArea(worldName)) {
SetGenCB.setGenerator(BukkitUtil.getWorld(worldName)); SetGenCB.setGenerator(BukkitUtil.getWorld(worldName));
} }
} catch (Exception e) { } catch (Exception ignored) {
log("Failed to reload world: " + world); PS.log("Failed to reload world: " + world);
Bukkit.getServer().unloadWorld(world, false); Bukkit.getServer().unloadWorld(world, false);
} }
} }
@ -609,7 +603,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
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 if (PS.get().config.contains("worlds." + worldName)) { } else if (PS.get().worlds.contains("worlds." + worldName)) {
PS.get().loadWorld(worldName, null); PS.get().loadWorld(worldName, null);
} }
} }
@ -629,11 +623,14 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
public PlotPlayer wrapPlayer(Object player) { public PlotPlayer wrapPlayer(Object player) {
if (player instanceof Player) { if (player instanceof Player) {
return BukkitUtil.getPlayer((Player) player); return BukkitUtil.getPlayer((Player) player);
} else if (player instanceof OfflinePlayer) { }
if (player instanceof OfflinePlayer) {
return BukkitUtil.getPlayer((OfflinePlayer) player); return BukkitUtil.getPlayer((OfflinePlayer) player);
} else if (player instanceof String) { }
if (player instanceof String) {
return UUIDHandler.getPlayer((String) player); return UUIDHandler.getPlayer((String) player);
} else if (player instanceof UUID) { }
if (player instanceof UUID) {
return UUIDHandler.getPlayer((UUID) player); return UUIDHandler.getPlayer((UUID) player);
} }
return null; return null;
@ -647,7 +644,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
@Override @Override
public ChatManager<?> initChatManager() { public ChatManager<?> initChatManager() {
if (Settings.FANCY_CHAT) { if (Settings.Chat.INTERACTIVE) {
return new BukkitChatManager(); return new BukkitChatManager();
} else { } else {
return new BukkitPlainChatManager(); return new BukkitPlainChatManager();
@ -663,7 +660,7 @@ public class BukkitMain extends JavaPlugin implements Listener, IPlotMain {
public List<String> getPluginIds() { public List<String> getPluginIds() {
ArrayList<String> names = new ArrayList<>(); ArrayList<String> names = new ArrayList<>();
for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) { for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
names.add(plugin.getName() + ";" + plugin.getDescription().getVersion() + ":" + plugin.isEnabled()); names.add(plugin.getName() + ';' + plugin.getDescription().getVersion() + ':' + plugin.isEnabled());
} }
return names; return names;
} }

View File

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

View File

@ -9,11 +9,11 @@ import java.io.IOException;
*/ */
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(JsonWriter writer) throws IOException; public void writeJson(JsonWriter writer) throws IOException;
} }

View File

@ -1,12 +1,12 @@
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 org.bukkit.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.
@ -14,34 +14,34 @@ import java.util.Map;
*/ */
final class JsonString implements JsonRepresentedObject, ConfigurationSerializable { final class JsonString implements JsonRepresentedObject, ConfigurationSerializable {
private final String _value; private String _value;
public JsonString(CharSequence value) { public JsonString(CharSequence value) {
this._value = value == null ? null : value.toString(); _value = value == null ? null : value.toString();
} }
public static JsonString deserialize(Map<String, Object> map) { @Override
return new JsonString(map.get("stringValue").toString()); public void writeJson(JsonWriter writer) throws IOException {
} writer.value(getValue());
}
@Override public String getValue() {
public void writeJson(JsonWriter writer) throws IOException { return _value;
writer.value(getValue()); }
}
public String getValue() { public Map<String, Object> serialize() {
return this._value; HashMap<String, Object> theSingleValue = new HashMap<String, Object>();
} theSingleValue.put("stringValue", _value);
return theSingleValue;
}
@Override public static JsonString deserialize(Map<String, Object> map) {
public Map<String, Object> serialize() { return new JsonString(map.get("stringValue").toString());
HashMap<String, Object> theSingleValue = new HashMap<>(); }
theSingleValue.put("stringValue", this._value);
return theSingleValue; @Override
} public String toString() {
return _value;
}
@Override
public String toString() {
return this._value;
}
} }

View File

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

View File

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

View File

@ -3,8 +3,8 @@ package com.plotsquared.bukkit.chat;
import com.google.common.base.Preconditions; import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.gson.stream.JsonWriter; import com.google.gson.stream.JsonWriter;
import com.intellectualcrafters.configuration.serialization.ConfigurationSerializable; import org.bukkit.configuration.serialization.ConfigurationSerializable;
import com.intellectualcrafters.configuration.serialization.ConfigurationSerialization; import org.bukkit.configuration.serialization.ConfigurationSerialization;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
@ -18,285 +18,280 @@ import java.util.Map;
*/ */
public abstract class TextualComponent implements Cloneable { public abstract class TextualComponent implements Cloneable {
static { static {
ConfigurationSerialization.registerClass(TextualComponent.ArbitraryTextTypeComponent.class); ConfigurationSerialization.registerClass(TextualComponent.ArbitraryTextTypeComponent.class);
ConfigurationSerialization.registerClass(TextualComponent.ComplexTextTypeComponent.class); ConfigurationSerialization.registerClass(TextualComponent.ComplexTextTypeComponent.class);
} }
static TextualComponent deserialize(Map<String, Object> map) { @Override
if (map.containsKey("key") && (map.size() == 2) && map.containsKey("value")) { public String toString() {
// Arbitrary text component return getReadableString();
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; /**
} * @return The JSON key used to represent text components of this type.
*/
public abstract String getKey();
static boolean isTextKey(String key) { /**
return key.equals("translate") || key.equals("text") || key.equals("score") || key.equals("selector"); * @return A readable String
} */
public abstract String getReadableString();
static boolean isTranslatableText(TextualComponent component) { /**
return (component instanceof ComplexTextTypeComponent) && component.getKey().equals("translate"); * Clones a textual component instance.
} * The returned object should not reference this textual component instance, but should maintain the same key and value.
*/
@Override
public abstract TextualComponent clone() throws CloneNotSupportedException;
/** /**
* Create a textual component representing a string literal. * Writes the text data represented by this textual component to the specified JSON writer object.
* This is the default type of textual component when a single string literal is given to a method. * A new object within the writer is not started.
* @param textValue The text which will be represented. *
* @return The text component representing the specified literal text. * @param writer The object to which to write the JSON data.
*/ * @throws IOException If an error occurs while writing to the stream.
public static TextualComponent rawText(String textValue) { */
return new ArbitraryTextTypeComponent("text", textValue); public abstract void writeJson(JsonWriter writer) throws IOException;
}
/** static TextualComponent deserialize(Map<String, Object> map) {
* Create a textual component representing a localized string. if (map.containsKey("key") && map.size() == 2 && map.containsKey("value")) {
* The client will see this text component as their localized version of the specified string <em>key</em>, which can be overridden by a // Arbitrary text component
* resource pack. return ArbitraryTextTypeComponent.deserialize(map);
* <p> } else if (map.size() >= 2 && map.containsKey("key") && !map.containsKey("value") /* It contains keys that START WITH value */) {
* If the specified translation key is not present on the client resource pack, the translation key will be displayed as a string literal to // Complex JSON object
* the client. return ComplexTextTypeComponent.deserialize(map);
* </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() { return null;
throw new UnsupportedOperationException("This feature is only supported in snapshot releases."); }
}
/** static boolean isTextKey(String key) {
* Create a textual component representing a scoreboard value. return key.equals("translate") || key.equals("text") || key.equals("score") || key.equals("selector");
* 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);
}
/** static boolean isTranslatableText(TextualComponent component) {
* Create a textual component representing a scoreboard value. return component instanceof ComplexTextTypeComponent && ((ComplexTextTypeComponent) component).getKey().equals("translate");
* 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()); * Internal class used to represent all types of text components.
} * Exception validating done is on keys and values.
*/
private static final class ArbitraryTextTypeComponent extends TextualComponent implements ConfigurationSerializable {
/** public ArbitraryTextTypeComponent(String key, String value) {
* Create a textual component representing a player name, retrievable by using a standard minecraft selector. setKey(key);
* The client will see the players or entities captured by the specified selector as the text represented by this component. setValue(value);
* <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
} public String getKey() {
return _key;
}
@Override public void setKey(String key) {
public String toString() { Preconditions.checkArgument(key != null && !key.isEmpty(), "The key must be specified.");
return getReadableString(); _key = key;
} }
/** public String getValue() {
* @return The JSON key used to represent text components of this type. return _value;
*/ }
public abstract String getKey();
/** public void setValue(String value) {
* @return A readable String Preconditions.checkArgument(value != null, "The value must be specified.");
*/ _value = value;
public abstract String getReadableString(); }
/** private String _key;
* Clones a textual component instance. private String _value;
* The returned object should not reference this textual component instance, but should maintain the same key and value.
*/
@Override
public abstract TextualComponent clone() throws CloneNotSupportedException;
/** @Override
* Writes the text data represented by this textual component to the specified JSON writer object. public TextualComponent clone() throws CloneNotSupportedException {
* A new object within the writer is not started. // Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone
* @param writer The object to which to write the JSON data. return new ArbitraryTextTypeComponent(getKey(), getValue());
* @throws IOException If an error occurs while writing to the stream. }
*/
public abstract void writeJson(JsonWriter writer) throws IOException;
/** @Override
* Internal class used to represent all types of text components. public void writeJson(JsonWriter writer) throws IOException {
* Exception validating done is on keys and values. writer.name(getKey()).value(getValue());
*/ }
private static final class ArbitraryTextTypeComponent extends TextualComponent implements ConfigurationSerializable {
private String _key; @SuppressWarnings("serial")
private String _value; public Map<String, Object> serialize() {
return new HashMap<String, Object>() {{
put("key", getKey());
put("value", getValue());
}};
}
public ArbitraryTextTypeComponent(String key, String value) { public static ArbitraryTextTypeComponent deserialize(Map<String, Object> map) {
setKey(key); return new ArbitraryTextTypeComponent(map.get("key").toString(), map.get("value").toString());
setValue(value); }
}
public static ArbitraryTextTypeComponent deserialize(Map<String, Object> map) { @Override
return new ArbitraryTextTypeComponent(map.get("key").toString(), map.get("value").toString()); public String getReadableString() {
} return getValue();
}
}
@Override /**
public String getKey() { * Internal class used to represent a text component with a nested JSON value.
return this._key; * Exception validating done is on keys and values.
} */
private static final class ComplexTextTypeComponent extends TextualComponent implements ConfigurationSerializable {
public void setKey(String key) { public ComplexTextTypeComponent(String key, Map<String, String> values) {
Preconditions.checkArgument((key != null) && !key.isEmpty(), "The key must be specified."); setKey(key);
this._key = key; setValue(values);
} }
public String getValue() { @Override
return this._value; public String getKey() {
} return _key;
}
public void setValue(String value) { public void setKey(String key) {
Preconditions.checkArgument(value != null, "The value must be specified."); Preconditions.checkArgument(key != null && !key.isEmpty(), "The key must be specified.");
this._value = value; _key = key;
} }
@Override public Map<String, String> getValue() {
public TextualComponent clone() throws CloneNotSupportedException { return _value;
// Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone }
return new ArbitraryTextTypeComponent(getKey(), getValue());
}
@Override public void setValue(Map<String, String> value) {
public void writeJson(JsonWriter writer) throws IOException { Preconditions.checkArgument(value != null, "The value must be specified.");
writer.name(getKey()).value(getValue()); _value = value;
} }
@Override private String _key;
@SuppressWarnings("serial") private Map<String, String> _value;
public Map<String, Object> serialize() {
return new HashMap<String, Object>() {
{
put("key", getKey());
put("value", getValue());
}
};
}
@Override @Override
public String getReadableString() { public TextualComponent clone() throws CloneNotSupportedException {
return getValue(); // Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone
} return new ComplexTextTypeComponent(getKey(), getValue());
} }
/** @Override
* Internal class used to represent a text component with a nested JSON value. public void writeJson(JsonWriter writer) throws IOException {
* Exception validating done is on keys and values. writer.name(getKey());
*/ writer.beginObject();
private static final class ComplexTextTypeComponent extends TextualComponent implements ConfigurationSerializable { for (Map.Entry<String, String> jsonPair : _value.entrySet()) {
writer.name(jsonPair.getKey()).value(jsonPair.getValue());
}
writer.endObject();
}
private String _key; @SuppressWarnings("serial")
private Map<String, String> _value; public Map<String, Object> serialize() {
return new java.util.HashMap<String, Object>() {{
put("key", getKey());
for (Map.Entry<String, String> valEntry : getValue().entrySet()) {
put("value." + valEntry.getKey(), valEntry.getValue());
}
}};
}
public ComplexTextTypeComponent(String key, Map<String, String> values) { public static ComplexTextTypeComponent deserialize(Map<String, Object> map) {
setKey(key); String key = null;
setValue(values); 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(((String) valEntry.getKey()).substring(6) /* Strips out the value prefix */, valEntry.getValue().toString());
}
}
return new ComplexTextTypeComponent(key, value);
}
public static ComplexTextTypeComponent deserialize(Map<String, Object> map) { @Override
String key = null; public String getReadableString() {
Map<String, String> value = new HashMap<String, String>(); return getKey();
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);
}
@Override /**
public String getKey() { * Create a textual component representing a string literal.
return this._key; * 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);
}
public void setKey(String key) {
Preconditions.checkArgument((key != null) && !key.isEmpty(), "The key must be specified.");
this._key = key;
}
public Map<String, String> getValue() { /**
return this._value; * 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);
}
public void setValue(Map<String, String> value) { private static void throwUnsupportedSnapshot() {
Preconditions.checkArgument(value != null, "The value must be specified."); throw new UnsupportedOperationException("This feature is only supported in snapshot releases.");
this._value = value; }
}
@Override /**
public TextualComponent clone() throws CloneNotSupportedException { * Create a textual component representing a scoreboard value.
// Since this is a private and final class, we can just reinstantiate this class instead of casting super.clone * The client will see their own score for the specified objective as the text represented by this component.
return new ComplexTextTypeComponent(getKey(), getValue()); * <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);
}
@Override /**
public void writeJson(JsonWriter writer) throws IOException { * Create a textual component representing a scoreboard value.
writer.name(getKey()); * The client will see the score of the specified player for the specified objective as the text represented by this component.
writer.beginObject(); * <p>
for (Map.Entry<String, String> jsonPair : this._value.entrySet()) { * <b>This method is currently guaranteed to throw an {@code UnsupportedOperationException} as it is only supported on snapshot clients.</b>
writer.name(jsonPair.getKey()).value(jsonPair.getValue()); * </p>
} *
writer.endObject(); * @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
@Override return new ComplexTextTypeComponent("score", ImmutableMap.<String, String>builder()
@SuppressWarnings("serial") .put("name", playerName)
public Map<String, Object> serialize() { .put("objective", scoreboardObjective)
return new java.util.HashMap<String, Object>() { .build());
{ }
put("key", getKey());
for (Map.Entry<String, String> valEntry : getValue().entrySet()) {
put("value." + valEntry.getKey(), valEntry.getValue());
}
}
};
}
@Override /**
public String getReadableString() { * Create a textual component representing a player name, retrievable by using a standard minecraft selector.
return getKey(); * 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);
}
} }

View File

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

View File

@ -5,8 +5,6 @@ import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotId; import com.intellectualcrafters.plot.object.PlotId;
import org.bukkit.Bukkit;
import org.bukkit.World;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
@ -15,55 +13,48 @@ import java.util.HashMap;
public abstract class APlotMeConnector { public abstract class APlotMeConnector {
public abstract Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, String dataFolder); public abstract Connection getPlotMeConnection(FileConfiguration plotConfig, String dataFolder);
public abstract HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(Connection connection) throws SQLException; public abstract HashMap<String, HashMap<PlotId, Plot>> getPlotMePlots(Connection connection) throws SQLException;
public abstract boolean accepts(String version); 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) { public boolean isValidConnection(Connection connection) {
return connection != null; return connection != null;
} }
public void copyConfig(FileConfiguration plotConfig, String world, String actualWorldName) { public void copyConfig(FileConfiguration plotConfig, String world, String actualWorldName) {
int pathWidth = plotConfig.getInt("worlds." + world + ".PathWidth"); // int pathWidth = plotConfig.getInt("worlds." + world + ".PathWidth"); //
PS.get().config.set("worlds." + actualWorldName + ".road.width", pathWidth); PS.get().worlds.set("worlds." + actualWorldName + ".road.width", pathWidth);
int plotSize = plotConfig.getInt("worlds." + world + ".PlotSize"); // int plotSize = plotConfig.getInt("worlds." + world + ".PlotSize"); //
PS.get().config.set("worlds." + actualWorldName + ".plot.size", plotSize); PS.get().worlds.set("worlds." + actualWorldName + ".plot.size", plotSize);
String wallBlock = plotConfig.getString("worlds." + world + ".WallBlockId"); // String wallBlock = plotConfig.getString("worlds." + world + ".WallBlockId"); //
PS.get().config.set("worlds." + actualWorldName + ".wall.block", wallBlock); PS.get().worlds.set("worlds." + actualWorldName + ".wall.block", wallBlock);
String floor = plotConfig.getString("worlds." + world + ".PlotFloorBlockId"); // String floor = plotConfig.getString("worlds." + world + ".PlotFloorBlockId"); //
PS.get().config.set("worlds." + actualWorldName + ".plot.floor", Collections.singletonList(floor)); PS.get().worlds.set("worlds." + actualWorldName + ".plot.floor", Collections.singletonList(floor));
String filling = plotConfig.getString("worlds." + world + ".PlotFillingBlockId"); // String filling = plotConfig.getString("worlds." + world + ".PlotFillingBlockId"); //
PS.get().config.set("worlds." + actualWorldName + ".plot.filling", Collections.singletonList(filling)); PS.get().worlds.set("worlds." + actualWorldName + ".plot.filling", Collections.singletonList(filling));
String road = plotConfig.getString("worlds." + world + ".RoadMainBlockId"); String road = plotConfig.getString("worlds." + world + ".RoadMainBlockId");
PS.get().config.set("worlds." + actualWorldName + ".road.block", road); PS.get().worlds.set("worlds." + actualWorldName + ".road.block", road);
int height = plotConfig.getInt("worlds." + world + ".RoadHeight"); // int height = plotConfig.getInt("worlds." + world + ".RoadHeight"); //
PS.get().config.set("worlds." + actualWorldName + ".road.height", height); PS.get().worlds.set("worlds." + actualWorldName + ".road.height", height);
PS.get().worlds.set("worlds." + actualWorldName + ".plot.height", height);
PS.get().worlds.set("worlds." + actualWorldName + ".wall.height", height);
} }
public Location getPlotTopLocAbs(int path, int plot, PlotId plotid) { public Location getPlotTopLocAbs(int path, int plot, PlotId plotId) {
int px = plotid.x; int px = plotId.x;
int pz = plotid.y; int pz = plotId.y;
int x = (px * (path + plot)) - (int) Math.floor(path / 2) - 1; int x = px * (path + plot) - (int) Math.floor(path / 2) - 1;
int z = (pz * (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); return new Location(null, x, 256, z);
} }
public Location getPlotBottomLocAbs(int path, int plot, PlotId plotid) { public Location getPlotBottomLocAbs(int path, int plot, PlotId plotId) {
int px = plotid.x; int px = plotId.x;
int pz = plotid.y; int pz = plotId.y;
int x = (px * (path + plot)) - plot - (int) Math.floor(path / 2) - 1; int x = px * (path + plot) - plot - (int) Math.floor(path / 2) - 1;
int z = (pz * (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); return new Location(null, x, 1, z);
} }

View File

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

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.database.plotme; package com.plotsquared.bukkit.database.plotme;
import com.intellectualcrafters.configuration.MemorySection; import com.intellectualcrafters.configuration.MemorySection;
@ -44,6 +24,7 @@ import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
@ -55,19 +36,14 @@ public class LikePlotMeConverter {
private final String plugin; private final String plugin;
/**
* Constructor.
*
* @param plugin Plugin Used to run the converter
*/
public LikePlotMeConverter(String plugin) { public LikePlotMeConverter(String plugin) {
this.plugin = plugin; this.plugin = plugin;
} }
public static String getWorld(String world) { public static String getWorld(String world) {
for (World newworld : Bukkit.getWorlds()) { for (World newWorld : Bukkit.getWorlds()) {
if (newworld.getName().equalsIgnoreCase(world)) { if (newWorld.getName().equalsIgnoreCase(world)) {
return newworld.getName(); return newWorld.getName();
} }
} }
return world; return world;
@ -78,11 +54,7 @@ public class LikePlotMeConverter {
} }
public String getPlotMePath() { public String getPlotMePath() {
return new File(".").getAbsolutePath() + File.separator + "plugins" + File.separator + this.plugin + File.separator; return new File(".").getAbsolutePath() + File.separator + "plugins" + File.separator + plugin + File.separator;
}
public String getAthionPlotsPath() {
return new File(".").getAbsolutePath() + File.separator + "plugins" + File.separator + this.plugin + File.separator;
} }
public FileConfiguration getPlotMeConfig(String dataFolder) { public FileConfiguration getPlotMeConfig(String dataFolder) {
@ -97,7 +69,7 @@ public class LikePlotMeConverter {
return plotConfig.getConfigurationSection("worlds").getKeys(false); return plotConfig.getConfigurationSection("worlds").getKeys(false);
} }
public void mergeWorldYml(String plugin, FileConfiguration plotConfig) { public void mergeWorldYml(FileConfiguration plotConfig) {
try { try {
File genConfig = File genConfig =
new File("plugins" + File.separator + plugin + File.separator + "PlotMe-DefaultGenerator" + File.separator + "config.yml"); new File("plugins" + File.separator + plugin + File.separator + "PlotMe-DefaultGenerator" + File.separator + "config.yml");
@ -117,7 +89,7 @@ public class LikePlotMeConverter {
} }
} }
public void updateWorldYml(String plugin, String location) { public void updateWorldYml(String location) {
try { try {
Path path = Paths.get(location); Path path = Paths.get(location);
File file = new File(location); File file = new File(location);
@ -125,12 +97,12 @@ public class LikePlotMeConverter {
return; return;
} }
String content = new String(Files.readAllBytes(path), StandardCharsets.UTF_8); String content = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
content = content.replaceAll("PlotMe-DefaultGenerator", "PlotSquared"); content = content.replace("PlotMe-DefaultGenerator", "PlotSquared");
content = content.replaceAll(plugin, "PlotSquared"); content = content.replace("PlotMe", "PlotSquared");
content = content.replace("AthionPlots", "PlotSquared");
content = content.replace("PlotZWorld", "PlotSquared");
Files.write(path, content.getBytes(StandardCharsets.UTF_8)); Files.write(path, content.getBytes(StandardCharsets.UTF_8));
} catch (IOException ignored) { } catch (IOException ignored) {}
//ignored
}
} }
public boolean run(APlotMeConnector connector) { public boolean run(APlotMeConnector connector) {
@ -151,37 +123,37 @@ public class LikePlotMeConverter {
PS.debug("&3Using connector: " + connector.getClass().getCanonicalName()); PS.debug("&3Using connector: " + connector.getClass().getCanonicalName());
Connection connection = connector.getPlotMeConnection(this.plugin, plotConfig, dataFolder); Connection connection = connector.getPlotMeConnection(plotConfig, dataFolder);
if (!connector.isValidConnection(connection)) { if (!connector.isValidConnection(connection)) {
sendMessage("Cannot connect to PlotMe DB. Conversion process will not continue"); sendMessage("Cannot connect to PlotMe DB. Conversion process will not continue");
return false; return false;
} }
sendMessage(this.plugin + " conversion has started. To disable this, please set 'plotme-convert.enabled' to false in the 'settings.yml'"); sendMessage("PlotMe conversion has started. To disable this, please set 'plotme-convert.enabled' to false in the 'settings.yml'");
mergeWorldYml(this.plugin, plotConfig); mergeWorldYml(plotConfig);
sendMessage("Connecting to " + this.plugin + " DB"); sendMessage("Connecting to PlotMe DB");
ArrayList<Plot> createdPlots = new ArrayList<>(); ArrayList<Plot> createdPlots = new ArrayList<>();
sendMessage("Collecting plot data"); sendMessage("Collecting plot data");
String dbPrefix = this.plugin.toLowerCase(); String dbPrefix = "PlotMe".toLowerCase();
sendMessage(" - " + dbPrefix + "Plots"); sendMessage(" - " + dbPrefix + "Plots");
final Set<String> worlds = getPlotMeWorlds(plotConfig); final Set<String> worlds = getPlotMeWorlds(plotConfig);
if (Settings.CONVERT_PLOTME) { if (Settings.Enabled_Components.PLOTME_CONVERTER) {
sendMessage("Updating bukkit.yml"); sendMessage("Updating bukkit.yml");
updateWorldYml(this.plugin, "bukkit.yml"); updateWorldYml("bukkit.yml");
updateWorldYml(this.plugin, "plugins/Multiverse-Core/worlds.yml"); updateWorldYml("plugins/Multiverse-Core/worlds.yml");
for (String world : plotConfig.getConfigurationSection("worlds").getKeys(false)) { for (String world : plotConfig.getConfigurationSection("worlds").getKeys(false)) {
sendMessage("Copying config for: " + world); sendMessage("Copying config for: " + world);
try { try {
String actualWorldName = getWorld(world); String actualWorldName = getWorld(world);
connector.copyConfig(plotConfig, world, actualWorldName); connector.copyConfig(plotConfig, world, actualWorldName);
PS.get().config.save(PS.get().configFile); PS.get().worlds.save(PS.get().worldsFile);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
sendMessage("&c-- &lFailed to save configuration for world '" + world sendMessage("&c-- &lFailed to save configuration for world '" + world
@ -194,7 +166,7 @@ public class LikePlotMeConverter {
for (Entry<String, HashMap<PlotId, Plot>> entry : plots.entrySet()) { for (Entry<String, HashMap<PlotId, Plot>> entry : plots.entrySet()) {
plotCount += entry.getValue().size(); plotCount += entry.getValue().size();
} }
if (!Settings.CONVERT_PLOTME) { if (!Settings.Enabled_Components.PLOTME_CONVERTER) {
return false; return false;
} }
@ -208,51 +180,33 @@ public class LikePlotMeConverter {
for (String world : plots.keySet()) { for (String world : plots.keySet()) {
String actualWorldName = getWorld(world); String actualWorldName = getWorld(world);
String plotMeWorldName = world.toLowerCase(); String plotMeWorldName = world.toLowerCase();
Integer pathwidth = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".PathWidth"); // Integer pathWidth = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".PathWidth"); //
/* PS.get().worlds.set("worlds." + world + ".road.width", pathWidth);
* TODO: dead code
*
if (pathwidth == null) {
pathwidth = 7;
}
*/
PS.get().config.set("worlds." + world + ".road.width", pathwidth);
Integer pathheight = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".RoadHeight"); // int pathHeight = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".RoadHeight", 64); //
if (pathheight == 0) { PS.get().worlds.set("worlds." + world + ".road.height", pathHeight);
pathheight = 64; PS.get().worlds.set("worlds." + world + ".wall.height", pathHeight);
} PS.get().worlds.set("worlds." + world + ".plot.height", pathHeight);
PS.get().config.set("worlds." + world + ".road.height", pathheight); int plotSize = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".PlotSize", 32); //
PS.get().config.set("worlds." + world + ".wall.height", pathheight); PS.get().worlds.set("worlds." + world + ".plot.size", plotSize);
PS.get().config.set("worlds." + world + ".plot.height", pathheight);
Integer plotsize = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".PlotSize"); //
if (plotsize == 0) {
plotsize = 32;
}
PS.get().config.set("worlds." + world + ".plot.size", plotsize);
String wallblock = plotmeDgYml.getString("worlds." + plotMeWorldName + ".WallBlock", "44"); // String wallblock = plotmeDgYml.getString("worlds." + plotMeWorldName + ".WallBlock", "44"); //
PS.get().config.set("worlds." + world + ".wall.block", wallblock); PS.get().worlds.set("worlds." + world + ".wall.block", wallblock);
String floor = plotmeDgYml.getString("worlds." + plotMeWorldName + ".PlotFloorBlock", "2"); // String floor = plotmeDgYml.getString("worlds." + plotMeWorldName + ".PlotFloorBlock", "2"); //
PS.get().config.set("worlds." + world + ".plot.floor", Collections.singletonList(floor)); PS.get().worlds.set("worlds." + world + ".plot.floor", Collections.singletonList(floor));
String filling = plotmeDgYml.getString("worlds." + plotMeWorldName + ".FillBlock", "3"); // String filling = plotmeDgYml.getString("worlds." + plotMeWorldName + ".FillBlock", "3"); //
PS.get().config.set("worlds." + world + ".plot.filling", Collections.singletonList(filling)); PS.get().worlds.set("worlds." + world + ".plot.filling", Collections.singletonList(filling));
String road = plotmeDgYml.getString("worlds." + plotMeWorldName + ".RoadMainBlock", "5"); String road = plotmeDgYml.getString("worlds." + plotMeWorldName + ".RoadMainBlock", "5");
PS.get().config.set("worlds." + world + ".road.block", road); PS.get().worlds.set("worlds." + world + ".road.block", road);
Integer height = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".RoadHeight"); // int height = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".RoadHeight"); //
if (height == 0) { if (height == 0) {
height = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".GroundHeight"); // height = plotmeDgYml.getInt("worlds." + plotMeWorldName + ".GroundHeight", 64); //
if (height == 0) {
height = 64;
}
} }
PS.get().config.set("worlds." + actualWorldName + ".road.height", height); PS.get().worlds.set("worlds." + actualWorldName + ".road.height", height);
PS.get().config.set("worlds." + actualWorldName + ".plot.height", height); PS.get().worlds.set("worlds." + actualWorldName + ".plot.height", height);
PS.get().config.set("worlds." + actualWorldName + ".wall.height", height); PS.get().worlds.set("worlds." + actualWorldName + ".wall.height", height);
PS.get().config.save(PS.get().configFile); PS.get().worlds.save(PS.get().worldsFile);
} }
} catch (IOException ignored) { } catch (IOException ignored) {}
//ignored
}
} }
for (Entry<String, HashMap<PlotId, Plot>> entry : plots.entrySet()) { for (Entry<String, HashMap<PlotId, Plot>> entry : plots.entrySet()) {
String world = entry.getKey(); String world = entry.getKey();
@ -313,8 +267,8 @@ public class LikePlotMeConverter {
}); });
sendMessage("Saving configuration..."); sendMessage("Saving configuration...");
try { try {
PS.get().config.save(PS.get().configFile); PS.get().worlds.save(PS.get().worldsFile);
} catch (IOException e) { } catch (IOException ignored) {
sendMessage(" - &cFailed to save configuration."); sendMessage(" - &cFailed to save configuration.");
} }
TaskManager.runTask(new Runnable() { TaskManager.runTask(new Runnable() {
@ -330,10 +284,10 @@ public class LikePlotMeConverter {
.isEnabled()) { .isEnabled()) {
mw = true; mw = true;
} }
for (String worldname : worlds) { for (String worldName : worlds) {
World world = Bukkit.getWorld(getWorld(worldname)); World world = Bukkit.getWorld(getWorld(worldName));
if (world == null) { if (world == null) {
sendMessage("&cInvalid world in PlotMe configuration: " + worldname); sendMessage("&cInvalid world in PlotMe configuration: " + worldName);
} }
String actualWorldName = world.getName(); String actualWorldName = world.getName();
sendMessage("Reloading generator for world: '" + actualWorldName + "'..."); sendMessage("Reloading generator for world: '" + actualWorldName + "'...");
@ -343,7 +297,7 @@ public class LikePlotMeConverter {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv unload " + actualWorldName); Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv unload " + actualWorldName);
try { try {
Thread.sleep(1000); Thread.sleep(1000);
} catch (InterruptedException ex) { } catch (InterruptedException ignored) {
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
} }
// load world with MV // load world with MV
@ -354,7 +308,7 @@ public class LikePlotMeConverter {
Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw unload " + actualWorldName); Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mw unload " + actualWorldName);
try { try {
Thread.sleep(1000); Thread.sleep(1000);
} catch (InterruptedException ex) { } catch (InterruptedException ignored) {
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
} }
// load world with MW // load world with MW
@ -364,8 +318,8 @@ public class LikePlotMeConverter {
// Load using Bukkit API // Load using Bukkit API
// - User must set generator manually // - User must set generator manually
Bukkit.getServer().unloadWorld(world, true); Bukkit.getServer().unloadWorld(world, true);
World myworld = WorldCreator.name(actualWorldName).generator(new BukkitPlotGenerator(new HybridGen())).createWorld(); World myWorld = WorldCreator.name(actualWorldName).generator(new BukkitPlotGenerator(new HybridGen())).createWorld();
myworld.save(); myWorld.save();
} }
} }
} catch (CommandException e) { } catch (CommandException e) {
@ -384,7 +338,7 @@ public class LikePlotMeConverter {
} }
} }
}); });
} catch (Exception e) { } catch (InterruptedException | SQLException e) {
e.printStackTrace(); e.printStackTrace();
PS.debug("&/end/"); PS.debug("&/end/");
} }

View File

@ -19,7 +19,6 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.HashMap; import java.util.HashMap;
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 {
@ -27,8 +26,8 @@ public class PlotMeConnector_017 extends APlotMeConnector {
private String plugin; private String plugin;
@Override @Override
public Connection getPlotMeConnection(String plugin, FileConfiguration plotConfig, String dataFolder) { public Connection getPlotMeConnection(FileConfiguration plotConfig, String dataFolder) {
this.plugin = plugin.toLowerCase(); this.plugin = this.plugin.toLowerCase();
try { try {
if (plotConfig.getBoolean("usemySQL")) { if (plotConfig.getBoolean("usemySQL")) {
String user = plotConfig.getString("mySQLuname"); String user = plotConfig.getString("mySQLuname");
@ -38,12 +37,12 @@ public class PlotMeConnector_017 extends APlotMeConnector {
} else { } else {
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(file).openConnection();
} }
return new SQLite(dataFolder + File.separator + "plots.db").openConnection(); return new SQLite(new File(dataFolder + File.separator + "plots.db")).openConnection();
} }
} catch (SQLException | ClassNotFoundException ignored) { } catch (SQLException | ClassNotFoundException e) {
//ignored e.printStackTrace();
} }
return null; return null;
} }
@ -68,15 +67,15 @@ public class PlotMeConnector_017 extends APlotMeConnector {
return null; return null;
} }
boolean checkUUID = DBFunc.hasColumn(resultSet, "ownerID"); boolean checkUUID = DBFunc.hasColumn(resultSet, "ownerID");
boolean merge = !this.plugin.equals("plotme") && Settings.CONVERT_PLOTME; boolean merge = !this.plugin.equals("plotme") && Settings.Enabled_Components.PLOTME_CONVERTER;
while (resultSet.next()) { while (resultSet.next()) {
int key = resultSet.getInt("plot_id"); int key = resultSet.getInt("plot_id");
PlotId id = new PlotId(resultSet.getInt("plotX"), resultSet.getInt("plotZ")); PlotId id = new PlotId(resultSet.getInt("plotX"), resultSet.getInt("plotZ"));
String name = resultSet.getString("owner"); String name = resultSet.getString("owner");
String world = LikePlotMeConverter.getWorld(resultSet.getString("world")); String world = LikePlotMeConverter.getWorld(resultSet.getString("world"));
if (!plots.containsKey(world) && merge) { if (!plots.containsKey(world) && merge) {
int plot = PS.get().config.getInt("worlds." + world + ".plot.size"); int plot = PS.get().worlds.getInt("worlds." + world + ".plot.size");
int path = PS.get().config.getInt("worlds." + world + ".road.width"); int path = PS.get().worlds.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[]>());
@ -109,18 +108,14 @@ public class PlotMeConnector_017 extends APlotMeConnector {
owner = DBFunc.everyone; owner = DBFunc.everyone;
} else { } else {
if (checkUUID) { if (checkUUID) {
try { byte[] bytes = resultSet.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 (Exception e) {
e.printStackTrace();
} }
} }
if (owner == null) { if (owner == null) {
PS.log("&cCould not identify owner for plot: " + id + " -> '" + name + "'"); PS.log("&cCould not identify owner for plot: " + id + " -> '" + name + '\'');
continue; continue;
} }
} }
@ -130,8 +125,7 @@ public class PlotMeConnector_017 extends APlotMeConnector {
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 (Entry<Integer, Plot> entry : plots.entrySet()) { for (Plot plot : plots.values()) {
Plot plot = entry.getValue();
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())) {
@ -179,8 +173,7 @@ public class PlotMeConnector_017 extends APlotMeConnector {
} }
HashMap<String, HashMap<PlotId, Plot>> processed = new HashMap<>(); HashMap<String, HashMap<PlotId, Plot>> processed = new HashMap<>();
for (Entry<Integer, Plot> entry : plots.entrySet()) { for (Plot plot : plots.values()) {
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<>();

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,29 +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.generator; package com.plotsquared.bukkit.generator;
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;
import com.intellectualcrafters.plot.generator.IndependentPlotGenerator; import com.intellectualcrafters.plot.generator.IndependentPlotGenerator;
import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.object.ChunkWrapper;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.PlotArea; import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotId; import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotManager; import com.intellectualcrafters.plot.object.PlotManager;
@ -31,41 +14,69 @@ import com.intellectualcrafters.plot.object.PseudoRandom;
import com.intellectualcrafters.plot.object.SetupObject; import com.intellectualcrafters.plot.object.SetupObject;
import com.intellectualcrafters.plot.util.ChunkManager; 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.MathMan;
import com.intellectualcrafters.plot.util.SetQueue; import com.intellectualcrafters.plot.util.block.GlobalBlockQueue;
import com.intellectualcrafters.plot.util.block.LocalBlockQueue;
import com.intellectualcrafters.plot.util.block.ScopedLocalBlockQueue;
import com.plotsquared.bukkit.util.BukkitUtil; import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.bukkit.util.block.GenChunk; import com.plotsquared.bukkit.util.block.GenChunk;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.Set;
import org.bukkit.Chunk; import org.bukkit.Chunk;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.block.Biome; import org.bukkit.block.Biome;
import org.bukkit.generator.BlockPopulator; import org.bukkit.generator.BlockPopulator;
import org.bukkit.generator.ChunkGenerator; import org.bukkit.generator.ChunkGenerator;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;
public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrapper<ChunkGenerator> { public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrapper<ChunkGenerator> {
private final PlotChunk<Chunk> chunkSetter; private final GenChunk chunkSetter;
private final PseudoRandom random = new PseudoRandom(); private final 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 ChunkGenerator platformGenerator;
private final boolean full; private final boolean full;
private final HashMap<ChunkLoc, byte[][]> dataMap = new HashMap<>();
private boolean loaded = false; private boolean loaded = false;
public BukkitPlotGenerator(IndependentPlotGenerator generator) { public BukkitPlotGenerator(IndependentPlotGenerator generator) {
if (generator == null) {
throw new IllegalArgumentException("Generator may not be null!");
}
this.plotGenerator = generator; this.plotGenerator = generator;
this.platformGenerator = this; this.platformGenerator = this;
this.populators.add(new BlockPopulator() { this.populators.add(new BlockPopulator() {
private LocalBlockQueue queue;
@Override @Override
public void populate(World world, Random r, Chunk c) { public void populate(World world, Random r, Chunk c) {
GenChunk result = (GenChunk) BukkitPlotGenerator.this.chunkSetter; if (queue == null) {
if (result.result_data != null) { queue = GlobalBlockQueue.IMP.getNewQueue(world.getName(), false);
for (int i = 0; i < result.result_data.length; i++) { }
byte[] section = result.result_data[i]; ChunkLoc loc = new ChunkLoc(c.getX(), c.getZ());
byte[][] resultData;
if (!BukkitPlotGenerator.this.dataMap.containsKey(loc)) {
GenChunk result = BukkitPlotGenerator.this.chunkSetter;
// Set the chunk location
result.setChunk(c);
// Set the result data
result.result = new short[16][];
result.result_data = new byte[16][];
result.grid = null;
result.cd = null;
// Catch any exceptions (as exceptions usually thrown)
generate(world, loc.x, loc.z, result);
resultData = result.result_data;
} else {
resultData = BukkitPlotGenerator.this.dataMap.remove(loc);
}
if (resultData != null) {
for (int i = 0; i < resultData.length; i++) {
byte[] section = resultData[i];
if (section == null) { if (section == null) {
continue; continue;
} }
@ -77,6 +88,13 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
} }
} }
} }
BukkitPlotGenerator.this.random.state = c.getX() << 16 | c.getZ() & 0xFFFF;
PlotArea area = PS.get().getPlotArea(world.getName(), null);
ChunkWrapper wrap = new ChunkWrapper(area.worldname, c.getX(), c.getZ());
ScopedLocalBlockQueue chunk = queue.getForChunk(wrap.x, wrap.z);
if (BukkitPlotGenerator.this.plotGenerator.populateChunk(chunk, area, BukkitPlotGenerator.this.random)) {
queue.flush();
}
} }
}); });
this.chunkSetter = new GenChunk(null, null); this.chunkSetter = new GenChunk(null, null);
@ -114,13 +132,16 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
} }
@Override @Override
public void generateChunk(final PlotChunk<?> result, PlotArea settings, PseudoRandom random) { public void generateChunk(final ScopedLocalBlockQueue result, PlotArea settings, PseudoRandom random) {
World w = BukkitUtil.getWorld(world); World w = BukkitUtil.getWorld(world);
Random r = new Random(result.getChunkWrapper().hashCode()); Location min = result.getMin();
int cx = min.getX() >> 4;
int cz = min.getZ() >> 4;
Random r = new Random(MathMan.pair((short) cx, (short) cz));
BiomeGrid grid = new BiomeGrid() { BiomeGrid grid = new BiomeGrid() {
@Override @Override
public void setBiome(int x, int z, Biome biome) { public void setBiome(int x, int z, Biome biome) {
result.setBiome(x, z, biome.ordinal()); result.setBiome(x, z, biome.name());
} }
@Override @Override
@ -130,15 +151,13 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
}; };
try { try {
// ChunkData will spill a bit // ChunkData will spill a bit
ChunkData data = cg.generateChunkData(w, r, result.getX(), result.getZ(), grid); ChunkData data = cg.generateChunkData(w, r, cx, cz, grid);
if (data != null) { if (data != null) {
return; return;
} }
} catch (Throwable e) { } catch (Throwable ignored) {}
//ignored
}
// Populator spillage // Populator spillage
short[][] tmp = cg.generateExtBlockSections(w, r, result.getX(), result.getZ(), grid); short[][] tmp = cg.generateExtBlockSections(w, r, cx, cz, grid);
if (tmp != null) { if (tmp != null) {
for (int i = 0; i < tmp.length; i++) { for (int i = 0; i < tmp.length; i++) {
short[] section = tmp[i]; short[] section = tmp[i];
@ -163,11 +182,11 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
} }
} }
for (BlockPopulator populator : cg.getDefaultPopulators(w)) { for (BlockPopulator populator : cg.getDefaultPopulators(w)) {
populator.populate(w, r, (Chunk) result.getChunk()); populator.populate(w, r, w.getChunkAt(cx, cz));
} }
} }
}; };
this.chunkSetter = new GenChunk(null, SetQueue.IMP.new ChunkWrapper(world, 0, 0)); this.chunkSetter = new GenChunk(null, new ChunkWrapper(world, 0, 0));
if (cg != null) { if (cg != null) {
this.populators.addAll(cg.getDefaultPopulators(BukkitUtil.getWorld(world))); this.populators.addAll(cg.getDefaultPopulators(BukkitUtil.getWorld(world)));
} }
@ -224,20 +243,27 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
return this.populators; ArrayList<BlockPopulator> toAdd = new ArrayList<>();
List<BlockPopulator> existing = world.getPopulators();
for (BlockPopulator populator : this.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) {
GenChunk result = (GenChunk) this.chunkSetter; GenChunk result = (GenChunk) this.chunkSetter;
// Set the chunk location // Set the chunk location
result.setChunkWrapper(SetQueue.IMP.new ChunkWrapper(world.getName(), cx, cz)); result.setChunk(new ChunkWrapper(world.getName(), cx, cz));
// Set the result data // Set the result data
result.cd = createChunkData(world); result.cd = createChunkData(world);
result.grid = grid; result.grid = grid;
result.result = null; result.result = null;
result.result_data = null; result.result_data = null;
// Catch any exceptions (as exceptions usually thrown // Catch any exceptions (as exceptions usually thrown)
try { try {
// Fill the result data if necessary // Fill the result data if necessary
if (this.platformGenerator != this) { if (this.platformGenerator != this) {
@ -252,7 +278,7 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
return result.cd; return result.cd;
} }
public void generate(World world, int cx, int cz, GenChunk result) { public void generate(World world, int cx, int cz, ScopedLocalBlockQueue result) {
// Load if improperly loaded // Load if improperly loaded
if (!this.loaded) { if (!this.loaded) {
String name = world.getName(); String name = world.getName();
@ -266,7 +292,12 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
return; return;
} }
PlotArea area = PS.get().getPlotArea(world.getName(), null); PlotArea area = PS.get().getPlotArea(world.getName(), null);
this.plotGenerator.generateChunk(this.chunkSetter, area, this.random); try {
this.plotGenerator.generateChunk(this.chunkSetter, area, this.random);
} catch (Throwable e) {
// Recover from generator error
e.printStackTrace();
}
ChunkManager.postProcessChunk(result); ChunkManager.postProcessChunk(result);
} }
@ -274,19 +305,21 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
public short[][] generateExtBlockSections(World world, Random r, int cx, int cz, BiomeGrid grid) { public short[][] generateExtBlockSections(World world, Random r, int cx, int cz, BiomeGrid grid) {
GenChunk result = (GenChunk) this.chunkSetter; GenChunk result = (GenChunk) this.chunkSetter;
// Set the chunk location // Set the chunk location
result.setChunkWrapper(SetQueue.IMP.new ChunkWrapper(world.getName(), cx, cz)); result.setChunk(new ChunkWrapper(world.getName(), cx, cz));
// Set the result data // 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][];
result.grid = grid; result.grid = grid;
result.cd = null; result.cd = null;
// Catch any exceptions (as exceptions usually thrown // Catch any exceptions (as exceptions usually thrown)
try { try {
// Fill the result data // Fill the result data
if (this.platformGenerator != this) { if (this.platformGenerator != this) {
return this.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);
this.dataMap.put(new ChunkLoc(cx, cz), result.result_data);
} }
} catch (Throwable e) { } catch (Throwable e) {
e.printStackTrace(); e.printStackTrace();
@ -310,7 +343,7 @@ public class BukkitPlotGenerator extends ChunkGenerator implements GeneratorWrap
@Override @Override
public String toString() { public String toString() {
if (this.platformGenerator == this) { if (this.platformGenerator == this) {
return "" + this.plotGenerator; return this.plotGenerator.getName();
} }
if (this.platformGenerator == null) { if (this.platformGenerator == null) {
return "null"; return "null";

View File

@ -4,15 +4,12 @@ import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.object.ChunkLoc;
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.PlotPlayer;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefClass; import com.intellectualcrafters.plot.util.ReflectionUtils.RefClass;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefField; import com.intellectualcrafters.plot.util.ReflectionUtils.RefField;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod; import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod;
import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Chunk; import org.bukkit.Chunk;
import org.bukkit.Material; import org.bukkit.Material;
@ -31,9 +28,8 @@ import org.bukkit.event.entity.ItemSpawnEvent;
import org.bukkit.event.world.ChunkLoadEvent; import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.event.world.ChunkUnloadEvent; import org.bukkit.event.world.ChunkUnloadEvent;
import java.util.ArrayDeque; import java.lang.reflect.Method;
import java.util.HashMap; import java.util.HashSet;
import java.util.Map.Entry;
public class ChunkListener implements Listener { public class ChunkListener implements Listener {
@ -43,139 +39,69 @@ public class ChunkListener implements Listener {
public ChunkListener() { public ChunkListener() {
if (Settings.CHUNK_PROCESSOR_GC || Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE) { if (Settings.Chunk_Processor.AUTO_TRIM) {
try { try {
RefClass classChunk = getRefClass("{nms}.Chunk"); RefClass classChunk = getRefClass("{nms}.Chunk");
RefClass classCraftChunk = getRefClass("{cb}.CraftChunk"); RefClass classCraftChunk = getRefClass("{cb}.CraftChunk");
this.mustSave = classChunk.getField("mustSave"); this.mustSave = classChunk.getField("mustSave");
this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle"); this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle");
} catch (Throwable e) { } catch (Throwable ignored) {
PS.debug("PlotSquared/Server not compatible for chunk processor trim/gc"); PS.debug("PlotSquared/Server not compatible for chunk processor trim/gc");
Settings.CHUNK_PROCESSOR_GC = false; Settings.Chunk_Processor.AUTO_TRIM = false;
Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE = false;
} }
} }
if (!Settings.CHUNK_PROCESSOR_GC) { if (!Settings.Chunk_Processor.AUTO_TRIM) {
return; return;
} }
TaskManager.runTask(new Runnable() { for (World world : Bukkit.getWorlds()) {
world.setAutoSave(false);
}
TaskManager.runTaskRepeat(new Runnable() {
@Override @Override
public void run() { public void run() {
int distance = Bukkit.getViewDistance() + 2; try {
HashMap<String, HashMap<ChunkLoc, Integer>> players = new HashMap<>(); HashSet<Chunk> toUnload = new HashSet<>();
for (Entry<String, PlotPlayer> entry : UUIDHandler.getPlayers().entrySet()) { for (World world : Bukkit.getWorlds()) {
PlotPlayer pp = entry.getValue(); String worldName = world.getName();
Location location = pp.getLocation(); if (!PS.get().hasPlotArea(worldName)) {
String world = location.getWorld();
if (!PS.get().hasPlotArea(world)) {
continue;
}
HashMap<ChunkLoc, Integer> map = players.get(world);
if (map == null) {
map = new HashMap<>();
players.put(world, map);
}
ChunkLoc origin = new ChunkLoc(location.getX() >> 4, location.getZ() >> 4);
Integer val = map.get(origin);
int check;
if (val != null) {
if (val == distance) {
continue; continue;
} }
check = distance - val; Object w = world.getClass().getDeclaredMethod("getHandle").invoke(world);
} else { Object chunkMap = w.getClass().getDeclaredMethod("getPlayerChunkMap").invoke(w);
check = distance; Method methodIsChunkInUse = chunkMap.getClass().getDeclaredMethod("isChunkInUse", int.class, int.class);
map.put(origin, distance); Chunk[] chunks = world.getLoadedChunks();
} for (Chunk chunk : chunks) {
for (int x = -distance; x <= distance; x++) { if ((boolean) methodIsChunkInUse.invoke(chunkMap, chunk.getX(), chunk.getZ())) {
if (x >= check || -x >= check) {
continue;
}
for (int z = -distance; z <= distance; z++) {
if (z >= check || -z >= check) {
continue; continue;
} }
int weight = distance - Math.max(Math.abs(x), Math.abs(z)); int x = chunk.getX();
ChunkLoc chunk = new ChunkLoc(x + origin.x, z + origin.z); int z = chunk.getZ();
val = map.get(chunk); if (!shouldSave(worldName, x, z)) {
if (val == null || val < weight) { unloadChunk(worldName, chunk, false);
map.put(chunk, weight); continue;
} }
}
}
}
int time = 300;
for (World world : Bukkit.getWorlds()) {
String name = world.getName();
if (!PS.get().hasPlotArea(name)) {
continue;
}
boolean autosave = world.isAutoSave();
if (autosave) {
world.setAutoSave(false);
}
HashMap<ChunkLoc, Integer> map = players.get(name);
if (map == null || map.isEmpty()) {
continue;
}
Chunk[] chunks = world.getLoadedChunks();
ArrayDeque<Chunk> toUnload = new ArrayDeque<>();
for (Chunk chunk : chunks) {
int x = chunk.getX();
int z = chunk.getZ();
if (!map.containsKey(new ChunkLoc(x, z))) {
toUnload.add(chunk); toUnload.add(chunk);
} }
} }
if (!toUnload.isEmpty()) { if (toUnload.isEmpty()) {
long start = System.currentTimeMillis(); return;
Chunk chunk;
while ((chunk = toUnload.poll()) != null && System.currentTimeMillis() - start < 5) {
if (!Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE || !unloadChunk(name, chunk)) {
if (chunk.isLoaded()) {
chunk.unload(true, false);
}
}
}
if (!toUnload.isEmpty()) {
time = 1;
}
} }
if (!Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE && autosave) { long start = System.currentTimeMillis();
world.setAutoSave(true); for (Chunk chunk : toUnload) {
if (System.currentTimeMillis() - start > 5) {
return;
}
chunk.unload(true, false);
} }
} catch (Throwable e) {
e.printStackTrace();
} }
TaskManager.runTaskLater(this, time);
} }
}); }, 1);
} }
public boolean unloadChunk(String world, Chunk chunk) { public boolean unloadChunk(String world, Chunk chunk, boolean safe) {
int X = chunk.getX(); if (safe && shouldSave(world, chunk.getX(), chunk.getZ())) {
int Z = chunk.getZ();
int x = X << 4;
int z = Z << 4;
int x2 = x + 15;
int z2 = z + 15;
Plot plot = new Location(world, x, 1, z).getOwnedPlotAbs();
if (plot != null && plot.hasOwner()) {
return false;
}
plot = new Location(world, x2, 1, z2).getOwnedPlotAbs();
if (plot != null && plot.hasOwner()) {
return false;
}
plot = new Location(world, x2, 1, z).getOwnedPlotAbs();
if (plot != null && plot.hasOwner()) {
return false;
}
plot = new Location(world, x, 1, z2).getOwnedPlotAbs();
if (plot != null && plot.hasOwner()) {
return false;
}
plot = new Location(world, x + 7, 1, z + 7).getOwnedPlotAbs();
if (plot != null && plot.hasOwner()) {
return false; return false;
} }
Object c = this.methodGetHandleChunk.of(chunk).call(); Object c = this.methodGetHandleChunk.of(chunk).call();
@ -186,13 +112,38 @@ public class ChunkListener implements Listener {
return true; return true;
} }
public boolean shouldSave(String world, int X, int Z) {
int x = X << 4;
int z = Z << 4;
int x2 = x + 15;
int z2 = z + 15;
Plot plot = new Location(world, x, 1, z).getOwnedPlotAbs();
if (plot != null && plot.hasOwner()) {
return true;
}
plot = new Location(world, x2, 1, z2).getOwnedPlotAbs();
if (plot != null && plot.hasOwner()) {
return true;
}
plot = new Location(world, x2, 1, z).getOwnedPlotAbs();
if (plot != null && plot.hasOwner()) {
return true;
}
plot = new Location(world, x, 1, z2).getOwnedPlotAbs();
if (plot != null && plot.hasOwner()) {
return true;
}
plot = new Location(world, x + 7, 1, z + 7).getOwnedPlotAbs();
return plot != null && plot.hasOwner();
}
@EventHandler @EventHandler
public void onChunkUnload(ChunkUnloadEvent event) { public void onChunkUnload(ChunkUnloadEvent event) {
if (Settings.CHUNK_PROCESSOR_TRIM_ON_SAVE) { if (Settings.Chunk_Processor.AUTO_TRIM) {
Chunk chunk = event.getChunk(); Chunk chunk = event.getChunk();
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, true)) {
return; return;
} }
} }
@ -220,7 +171,7 @@ public class ChunkListener implements Listener {
return; return;
} }
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);
this.lastChunk = chunk; this.lastChunk = chunk;
@ -231,7 +182,7 @@ public class ChunkListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockPhysics(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);
} }
} }
@ -249,7 +200,7 @@ public class ChunkListener implements Listener {
return; return;
} }
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);
this.lastChunk = chunk; this.lastChunk = chunk;
@ -303,7 +254,7 @@ public class ChunkListener implements Listener {
} }
Entity[] entities = chunk.getEntities(); Entity[] entities = chunk.getEntities();
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 (Entity ent : entities) { for (Entity ent : entities) {
if (!(ent instanceof Player)) { if (!(ent instanceof Player)) {
ent.remove(); ent.remove();
@ -311,7 +262,7 @@ public class ChunkListener implements Listener {
} }
PS.debug("[PlotSquared] &a detected unsafe chunk and processed: " + (chunk.getX() << 4) + "," + (chunk.getX() << 4)); PS.debug("[PlotSquared] &a detected unsafe chunk and processed: " + (chunk.getX() << 4) + "," + (chunk.getX() << 4));
} }
if (tiles.length > Settings.CHUNK_PROCESSOR_MAX_BLOCKSTATES) { if (tiles.length > Settings.Chunk_Processor.MAX_TILES) {
if (unload) { if (unload) {
PS.debug("[PlotSquared] &c detected unsafe chunk: " + (chunk.getX() << 4) + "," + (chunk.getX() << 4)); PS.debug("[PlotSquared] &c detected unsafe chunk: " + (chunk.getX() << 4) + "," + (chunk.getX() << 4));
cleanChunk(chunk); cleanChunk(chunk);

View File

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

View File

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

View File

@ -32,6 +32,7 @@ import java.util.UUID;
public class PlayerEvents_1_8 extends PlotListener implements Listener { public class PlayerEvents_1_8 extends PlotListener implements Listener {
@SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onInventoryClick(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()) {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,21 +1,18 @@
package com.plotsquared.bukkit.object; package com.plotsquared.bukkit.object;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.EconHandler; import com.intellectualcrafters.plot.util.EconHandler;
import com.intellectualcrafters.plot.util.PlotGameMode; import com.intellectualcrafters.plot.util.PlotGameMode;
import com.intellectualcrafters.plot.util.PlotWeather; import com.intellectualcrafters.plot.util.PlotWeather;
import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.UUIDHandler; import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.bukkit.util.BukkitUtil; import com.plotsquared.bukkit.util.BukkitUtil;
import org.bukkit.Bukkit;
import org.bukkit.Effect; import org.bukkit.Effect;
import org.bukkit.GameMode; import org.bukkit.GameMode;
import org.bukkit.WeatherType; import org.bukkit.WeatherType;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.permissions.Permission;
import org.bukkit.plugin.PluginManager;
import java.util.UUID; import java.util.UUID;
@ -25,11 +22,10 @@ public class BukkitPlayer extends PlotPlayer {
public boolean offline; public boolean offline;
private UUID uuid; private UUID uuid;
private String name; private String name;
private long last = 0;
/** /**
* <p>Please do not use this method. Instead use BukkitUtil.getPlayer(Player), * <p>Please do not use this method. Instead use
* as it caches player objects.</p> * BukkitUtil.getPlayer(Player), as it caches player objects.</p>
* @param player * @param player
*/ */
public BukkitPlayer(Player player) { public BukkitPlayer(Player player) {
@ -43,14 +39,6 @@ public class BukkitPlayer extends PlotPlayer {
super.populatePersistentMetaMap(); super.populatePersistentMetaMap();
} }
@Override
public long getPreviousLogin() {
if (this.last == 0) {
this.last = this.player.getLastPlayed();
}
return this.last;
}
@Override @Override
public Location getLocation() { public Location getLocation() {
Location location = super.getLocation(); Location location = super.getLocation();
@ -65,6 +53,10 @@ public class BukkitPlayer extends PlotPlayer {
return this.uuid; return this.uuid;
} }
@Override public long getLastPlayed() {
return this.player.getLastPlayed();
}
@Override @Override
public boolean hasPermission(String permission) { public boolean hasPermission(String permission) {
if (this.offline && EconHandler.manager != null) { if (this.offline && EconHandler.manager != null) {
@ -73,32 +65,13 @@ public class BukkitPlayer extends PlotPlayer {
return this.player.hasPermission(permission); return this.player.hasPermission(permission);
} }
public Permission getPermission(String node) {
PluginManager manager = Bukkit.getPluginManager();
Permission perm = manager.getPermission(node);
if (perm == null) {
String[] nodes = node.split("\\.");
perm = new Permission(node);
StringBuilder n = new StringBuilder();
for (int i = 0; i < nodes.length - 1; i++) {
n.append(nodes[i]).append(".");
if (!node.equals(n + C.PERMISSION_STAR.s())) {
Permission parent = getPermission(n + C.PERMISSION_STAR.s());
if (parent != null) {
perm.addParent(parent, true);
}
}
}
manager.addPermission(perm);
}
manager.recalculatePermissionDefaults(perm);
perm.recalculatePermissibles();
return perm;
}
@Override @Override
public void sendMessage(String message) { public void sendMessage(String message) {
this.player.sendMessage(message); if (!StringMan.isEqual(this.<String>getMeta("lastMessage"), message) || (System.currentTimeMillis() - this.<Long>getMeta("lastMessageTime") > 5000)) {
setMeta("lastMessage", message);
setMeta("lastMessageTime", System.currentTimeMillis());
this.player.sendMessage(message);
}
} }
@Override @Override
@ -166,7 +139,7 @@ public class BukkitPlayer extends PlotPlayer {
case SURVIVAL: case SURVIVAL:
return PlotGameMode.SURVIVAL; return PlotGameMode.SURVIVAL;
default: default:
return PlotGameMode.SURVIVAL; return PlotGameMode.NOT_SET;
} }
} }
@ -205,8 +178,14 @@ public class BukkitPlayer extends PlotPlayer {
this.player.setAllowFlight(fly); this.player.setAllowFlight(fly);
} }
@Override
public boolean getFlight() {
return player.getAllowFlight();
}
@Override @Override
public void playMusic(Location location, int id) { public void playMusic(Location location, int id) {
//noinspection deprecation
this.player.playEffect(BukkitUtil.getLocation(location), Effect.RECORD_PLAY, id); this.player.playEffect(BukkitUtil.getLocation(location), Effect.RECORD_PLAY, id);
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -11,7 +11,7 @@ public class DefaultTitle extends AbstractTitle {
try { try {
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 (Throwable e) { } catch (Exception ignored) {
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

@ -1,89 +1,13 @@
package com.plotsquared.bukkit.titles; package com.plotsquared.bukkit.titles;
import com.plotsquared.bukkit.chat.Reflection; import com.plotsquared.bukkit.chat.Reflection;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/** public class DefaultTitleManager extends TitleManager {
* [ 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. * Create a new 1.8 title.
@ -93,144 +17,22 @@ public class DefaultTitleManager {
* @param fadeInTime Fade in time * @param fadeInTime Fade in time
* @param stayTime Stay on screen time * @param stayTime Stay on screen time
* @param fadeOutTime Fade out time * @param fadeOutTime Fade out time
* @throws ClassNotFoundException
*/ */
public DefaultTitleManager(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) public DefaultTitleManager(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) {
throws ClassNotFoundException { super(title, subtitle, fadeInTime, stayTime, fadeOutTime);
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 * Load spigot and NMS classes.
* @throws ClassNotFoundException
*/ */
private void loadClasses() throws ClassNotFoundException { @Override void loadClasses() {
this.packetTitle = Reflection.getNMSClass("PacketPlayOutTitle"); this.packetTitle = Reflection.getNMSClass("PacketPlayOutTitle");
this.packetActions = Reflection.getNMSClass("EnumTitleAction"); this.packetActions = Reflection.getNMSClass("EnumTitleAction");
this.chatBaseComponent = Reflection.getNMSClass("IChatBaseComponent"); this.chatBaseComponent = Reflection.getNMSClass("IChatBaseComponent");
this.nmsChatSerializer = Reflection.getNMSClass("ChatSerializer"); this.nmsChatSerializer = Reflection.getNMSClass("ChatSerializer");
} }
/** @Override public void send(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
* 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) { if (this.packetTitle != null) {
// First reset previous settings // First reset previous settings
resetTitle(player); resetTitle(player);
@ -248,38 +50,23 @@ public class DefaultTitleManager {
} }
// Send title // Send title
Object serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, Object serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.title) + "\",color:" + this.titleColor.name().toLowerCase() + "}"); "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getTitle()) + "\",color:" + this.titleColor.name().toLowerCase()
+ '}');
packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[0], serialized); packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[0], serialized);
sendPacket.invoke(connection, packet); sendPacket.invoke(connection, packet);
if (!this.subtitle.isEmpty()) { if (!this.getSubtitle().isEmpty()) {
// Send subtitle if present // Send subtitle if present
serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.subtitle) + "\",color:" + this.subtitleColor.name() "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getSubtitle()) + "\",color:" + this.subtitleColor.name()
.toLowerCase() + "}"); .toLowerCase() + '}');
packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[1], serialized); packet = this.packetTitle.getConstructor(this.packetActions, this.chatBaseComponent).newInstance(actions[1], serialized);
sendPacket.invoke(connection, packet); sendPacket.invoke(connection, packet);
} }
} }
} }
/** @Override
* Broadcast the title to all players. public void clearTitle(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
*
* @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 // Send timings first
Object handle = getHandle(player); Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle); Object connection = getField(handle.getClass(), "playerConnection").get(handle);
@ -293,9 +80,12 @@ public class DefaultTitleManager {
* Reset the title settings. * Reset the title settings.
* *
* @param player Player * @param player Player
* @throws Exception * @throws SecurityException
* @throws ReflectiveOperationException
* @throws SecurityException
*/ */
public void resetTitle(Player player) throws Exception { @Override
public void resetTitle(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
// Send timings first // Send timings first
Object handle = getHandle(player); Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle); Object connection = getField(handle.getClass(), "playerConnection").get(handle);
@ -305,54 +95,12 @@ public class DefaultTitleManager {
sendPacket.invoke(connection, packet); sendPacket.invoke(connection, packet);
} }
private Class<?> getPrimitiveType(Class<?> clazz) { Field getField(Class<?> clazz, String name) {
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 { try {
Field field = clazz.getDeclaredField(name); Field field = clazz.getDeclaredField(name);
field.setAccessible(true); field.setAccessible(true);
return field; return field;
} catch (NoSuchFieldException e) { } catch (NoSuchFieldException | SecurityException e) {
e.printStackTrace();
return null;
} catch (SecurityException e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
@ -368,7 +116,7 @@ public class DefaultTitleManager {
return null; return null;
} }
private boolean ClassListEqual(Class<?>[] l1, Class<?>[] l2) { boolean ClassListEqual(Class<?>[] l1, Class<?>[] l2) {
if (l1.length != l2.length) { if (l1.length != l2.length) {
return false; return false;
} }

View File

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

View File

@ -11,7 +11,7 @@ public class DefaultTitle_183 extends AbstractTitle {
try { try {
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 (Throwable e) { } catch (Exception ignored) {
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

@ -19,7 +19,7 @@ public class DefaultTitle_19 extends AbstractTitle {
playerObj.sendTitle("", ""); playerObj.sendTitle("", "");
} }
}, delay * 20); }, delay * 20);
} catch (Throwable e) { } catch (Throwable ignored) {
AbstractTitle.TITLE_CLASS = new DefaultTitle(); AbstractTitle.TITLE_CLASS = new DefaultTitle();
AbstractTitle.TITLE_CLASS.sendTitle(player, head, sub, in, delay, out); AbstractTitle.TITLE_CLASS.sendTitle(player, head, sub, in, delay, out);
} }

View File

@ -13,7 +13,7 @@ public class HackTitle extends AbstractTitle {
try { try {
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 (Throwable e) { } catch (Exception ignored) {
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

@ -6,80 +6,9 @@ import org.bukkit.ChatColor;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/** public class HackTitleManager extends TitleManager {
* 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. * Create a new 1.8 title.
@ -89,141 +18,22 @@ public class HackTitleManager {
* @param fadeInTime Fade in time * @param fadeInTime Fade in time
* @param stayTime Stay on screen time * @param stayTime Stay on screen time
* @param fadeOutTime Fade out time * @param fadeOutTime Fade out time
* @throws ClassNotFoundException NMS error
*/ */
public HackTitleManager(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) throws ClassNotFoundException { public HackTitleManager(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) {
this.title = title; super(title, subtitle, fadeInTime, stayTime, fadeOutTime);
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. * Load spigot and NMS classes.
* @throws ClassNotFoundException Spigot Error.
*/ */
private void loadClasses() throws ClassNotFoundException { @Override
void loadClasses() {
this.packetTitle = getClass("org.spigotmc.ProtocolInjector$PacketTitle"); this.packetTitle = getClass("org.spigotmc.ProtocolInjector$PacketTitle");
this.packetActions = getClass("org.spigotmc.ProtocolInjector$PacketTitle$Action"); this.packetActions = getClass("org.spigotmc.ProtocolInjector$PacketTitle$Action");
this.nmsChatSerializer = Reflection.getNMSClass("ChatSerializer"); this.nmsChatSerializer = Reflection.getNMSClass("ChatSerializer");
} }
/** @Override public void send(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
* 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)) { if ((getProtocolVersion(player) >= 47) && isSpigot() && (this.packetTitle != null)) {
// First reset previous settings // First reset previous settings
resetTitle(player); resetTitle(player);
@ -242,14 +52,15 @@ public class HackTitleManager {
} }
// Send title // Send title
Object serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, Object serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.title) + "\",color:" + this.titleColor.name().toLowerCase() + "}"); "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getTitle()) + "\",color:" + this.titleColor.name().toLowerCase()
+ "}");
packet = this.packetTitle.getConstructor(this.packetActions, Reflection.getNMSClass("IChatBaseComponent")) packet = this.packetTitle.getConstructor(this.packetActions, Reflection.getNMSClass("IChatBaseComponent"))
.newInstance(actions[0], serialized); .newInstance(actions[0], serialized);
sendPacket.invoke(connection, packet); sendPacket.invoke(connection, packet);
if (!this.subtitle.isEmpty()) { if (!this.getSubtitle().isEmpty()) {
// Send subtitle if present // Send subtitle if present
serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null,
"{text:\"" + ChatColor.translateAlternateColorCodes('&', this.subtitle) + "\",color:" + this.subtitleColor.name() "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.getSubtitle()) + "\",color:" + this.subtitleColor.name()
.toLowerCase() + "}"); .toLowerCase() + "}");
packet = this.packetTitle.getConstructor(this.packetActions, Reflection.getNMSClass("IChatBaseComponent")) packet = this.packetTitle.getConstructor(this.packetActions, Reflection.getNMSClass("IChatBaseComponent"))
.newInstance(actions[1], serialized); .newInstance(actions[1], serialized);
@ -258,23 +69,7 @@ public class HackTitleManager {
} }
} }
/** @Override public void clearTitle(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
* 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()) { if ((getProtocolVersion(player) >= 47) && isSpigot()) {
// Send timings first // Send timings first
Object handle = getHandle(player); Object handle = getHandle(player);
@ -286,13 +81,7 @@ public class HackTitleManager {
} }
} }
/** @Override public void resetTitle(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
* Reset the title settings.
*
* @param player Player
* @throws Exception on NMS error.
*/
public void resetTitle(Player player) throws Exception {
if ((getProtocolVersion(player) >= 47) && isSpigot()) { if ((getProtocolVersion(player) >= 47) && isSpigot()) {
// Send timings first // Send timings first
Object handle = getHandle(player); Object handle = getHandle(player);
@ -309,9 +98,11 @@ public class HackTitleManager {
* *
* @param player Player * @param player Player
* @return Protocol version * @return Protocol version
* @throws Exception on NMS Error * @throws IllegalArgumentException
* @throws ReflectiveOperationException
* @throws SecurityException
*/ */
private int getProtocolVersion(Player player) throws Exception { private int getProtocolVersion(Player player) throws IllegalArgumentException, ReflectiveOperationException, SecurityException {
Object handle = getHandle(player); Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle); Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object networkManager = getValue("networkManager", connection); Object networkManager = getValue("networkManager", connection);
@ -336,54 +127,20 @@ public class HackTitleManager {
private Class<?> getClass(String namespace) { private Class<?> getClass(String namespace) {
try { try {
return Class.forName(namespace); return Class.forName(namespace);
} catch (ClassNotFoundException ignored) { } catch (ClassNotFoundException ignored) {}
}
return null; return null;
} }
private Field getField(String name, Class<?> clazz) throws Exception { private Field getField(String name, Class<?> clazz) throws NoSuchFieldException, SecurityException {
return clazz.getDeclaredField(name); return clazz.getDeclaredField(name);
} }
private Object getValue(String name, Object obj) throws Exception { private Object getValue(String name, Object obj) throws ReflectiveOperationException, SecurityException, IllegalArgumentException {
Field f = getField(name, obj.getClass()); Field f = getField(name, obj.getClass());
f.setAccessible(true); f.setAccessible(true);
return f.get(obj); 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) { private Field getField(Class<?> clazz, String name) {
try { try {
Field field = clazz.getDeclaredField(name); Field field = clazz.getDeclaredField(name);
@ -418,4 +175,5 @@ public class HackTitleManager {
} }
return equal; return equal;
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -55,15 +55,15 @@ public class BukkitSetupUtils extends SetupUtils {
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().worlds.contains(worldPath)) {
PS.get().config.createSection(worldPath); PS.get().worlds.createSection(worldPath);
} }
ConfigurationSection worldSection = PS.get().config.getConfigurationSection(worldPath); ConfigurationSection worldSection = PS.get().worlds.getConfigurationSection(worldPath);
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);
} }
@ -75,7 +75,7 @@ public class BukkitSetupUtils extends SetupUtils {
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 (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().worlds.set("worlds." + world + ".generator.type", object.type);
PS.get().config.set("worlds." + world + "." + "generator.terrain", object.terrain); PS.get().worlds.set("worlds." + world + ".generator.terrain", object.terrain);
PS.get().config.set("worlds." + world + "." + "generator.plugin", object.plotManager); PS.get().worlds.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().worlds.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 (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().worlds.save(PS.get().worldsFile);
} catch (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,7 +133,7 @@ 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) {
@ -148,14 +146,14 @@ public class BukkitSetupUtils extends SetupUtils {
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;
@ -181,11 +179,11 @@ public class BukkitSetupUtils extends SetupUtils {
} }
@Override @Override
public String getGenerator(PlotArea plotworld) { public String getGenerator(PlotArea plotArea) {
if (SetupUtils.generators.isEmpty()) { if (SetupUtils.generators.isEmpty()) {
updateGenerators(); updateGenerators();
} }
World world = Bukkit.getWorld(plotworld.worldname); World world = Bukkit.getWorld(plotArea.worldname);
if (world == null) { if (world == null) {
return null; return null;
} }
@ -193,7 +191,7 @@ public class BukkitSetupUtils extends SetupUtils {
if (!(generator instanceof BukkitPlotGenerator)) { if (!(generator instanceof BukkitPlotGenerator)) {
return null; return null;
} }
for (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

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

View File

@ -8,10 +8,11 @@ import com.intellectualcrafters.plot.object.schematic.PlotItem;
import com.intellectualcrafters.plot.util.MathMan; import com.intellectualcrafters.plot.util.MathMan;
import com.intellectualcrafters.plot.util.StringComparison; import com.intellectualcrafters.plot.util.StringComparison;
import com.intellectualcrafters.plot.util.StringMan; import com.intellectualcrafters.plot.util.StringMan;
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 +33,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,7 +41,7 @@ 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(String plr) { public static void removePlayer(String player) {
lastPlayer = null; lastPlayer = null;
lastPlotPlayer = null; lastPlotPlayer = null;
} }
@ -62,9 +60,9 @@ public class BukkitUtil extends WorldUtil {
return lastPlotPlayer; return lastPlotPlayer;
} }
String name = player.getName(); String name = player.getName();
PlotPlayer pp = UUIDHandler.getPlayer(name); PlotPlayer plotPlayer = UUIDHandler.getPlayer(name);
if (pp != null) { if (plotPlayer != null) {
return pp; return plotPlayer;
} }
lastPlotPlayer = new BukkitPlayer(player); lastPlotPlayer = new BukkitPlayer(player);
UUIDHandler.getPlayers().put(name, lastPlotPlayer); UUIDHandler.getPlayers().put(name, lastPlotPlayer);
@ -97,25 +95,25 @@ public class BukkitUtil extends WorldUtil {
return entity.getWorld().getName(); return entity.getWorld().getName();
} }
public static List<Entity> getEntities(String worldname) { public static List<Entity> getEntities(String worldName) {
return getWorld(worldname).getEntities(); return getWorld(worldName).getEntities();
} }
public static Location getLocation(Entity entity) { public static Location getLocation(Entity entity) {
org.bukkit.Location loc = entity.getLocation(); org.bukkit.Location location = entity.getLocation();
String world = loc.getWorld().getName(); String world = location.getWorld().getName();
return new Location(world, loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); return new Location(world, location.getBlockX(), location.getBlockY(), location.getBlockZ());
} }
public static Location getLocationFull(Entity entity) { public static Location getLocationFull(Entity entity) {
org.bukkit.Location loc = entity.getLocation(); org.bukkit.Location location = entity.getLocation();
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()),
loc.getYaw(), loc.getPitch()); location.getYaw(), location.getPitch());
} }
@Override @Override
public boolean isWorld(String world) { public boolean isWorld(String worldName) {
return getWorld(world) != null; return getWorld(worldName) != null;
} }
@Override @Override
@ -124,8 +122,8 @@ public class BukkitUtil extends WorldUtil {
} }
@Override @Override
public void setSign(String worldname, int x, int y, int z, String[] lines) { public void setSign(String worldName, int x, int y, int z, String[] lines) {
World world = getWorld(worldname); World world = getWorld(worldName);
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);
@ -136,12 +134,6 @@ public class BukkitUtil extends WorldUtil {
sign.setLine(i, lines[i]); sign.setLine(i, lines[i]);
} }
sign.update(true); sign.update(true);
TaskManager.runTaskLater(new Runnable() {
@Override
public void run() {
sign.update(true);
}
}, 20);
} }
} }
@ -157,6 +149,11 @@ public class BukkitUtil extends WorldUtil {
return null; return null;
} }
@Override
public Location getSpawn(PlotPlayer player) {
return getLocation(((BukkitPlayer) player).player.getBedSpawnLocation());
}
@Override @Override
public Location getSpawn(String world) { public Location getSpawn(String world) {
org.bukkit.Location temp = getWorld(world).getSpawnLocation(); org.bukkit.Location temp = getWorld(world).getSpawnLocation();
@ -172,8 +169,8 @@ public class BukkitUtil extends WorldUtil {
} }
@Override @Override
public void saveWorld(String worldname) { public void saveWorld(String worldName) {
World world = getWorld(worldname); World world = getWorld(worldName);
if (world != null) { if (world != null) {
world.save(); world.save();
} }
@ -185,11 +182,11 @@ public class BukkitUtil extends WorldUtil {
} }
@Override @Override
public int getBiomeFromString(String biomeStr) { public int getBiomeFromString(String biomeString) {
try { try {
Biome biome = Biome.valueOf(biomeStr.toUpperCase()); Biome biome = Biome.valueOf(biomeString.toUpperCase());
return Arrays.asList(Biome.values()).indexOf(biome); return Arrays.asList(Biome.values()).indexOf(biome);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException ignored) {
return -1; return -1;
} }
} }
@ -247,7 +244,7 @@ public class BukkitUtil extends WorldUtil {
} }
} }
return false; return false;
} catch (Exception e) { } catch (Exception ignored) {
return false; return false;
} }
} }
@ -256,7 +253,7 @@ public class BukkitUtil extends WorldUtil {
public String getClosestMatchingName(PlotBlock block) { public String getClosestMatchingName(PlotBlock block) {
try { try {
return Material.getMaterial(block.id).name(); return Material.getMaterial(block.id).name();
} catch (Exception e) { } catch (Exception ignored) {
return null; return null;
} }
} }
@ -265,10 +262,8 @@ public class BukkitUtil extends WorldUtil {
public StringComparison<PlotBlock>.ComparisonResult getClosestBlock(String name) { public StringComparison<PlotBlock>.ComparisonResult getClosestBlock(String name) {
try { try {
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, PlotBlock.get((short) material.getId(), (byte) 0));
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException ignored) {}
//ignored
}
try { try {
byte data; byte data;
String[] split = name.split(":"); String[] split = name.split(":");
@ -288,20 +283,18 @@ public class BukkitUtil extends WorldUtil {
match = comparison.match; match = comparison.match;
id = (short) comparison.best.getId(); id = (short) comparison.best.getId();
} }
PlotBlock block = new PlotBlock(id, data); PlotBlock block = PlotBlock.get(id, data);
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 ignored) {}
//ignored
}
return null; return null;
} }
@Override @Override
public void setBiomes(String worldName, RegionWrapper region, String biomeStr) { public void setBiomes(String worldName, RegionWrapper region, String biomeString) {
World world = getWorld(worldName); World world = getWorld(worldName);
Biome biome = Biome.valueOf(biomeStr.toUpperCase()); Biome biome = Biome.valueOf(biomeString.toUpperCase());
for (int x = region.minX; x <= region.maxX; x++) { for (int 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);
@ -316,7 +309,7 @@ public class BukkitUtil extends WorldUtil {
if (block == null) { if (block == null) {
return PlotBlock.EVERYTHING; return PlotBlock.EVERYTHING;
} }
return new PlotBlock((short) block.getTypeId(), block.getData()); return PlotBlock.get((short) block.getTypeId(), block.getData());
} }
@Override @Override

View File

@ -1,23 +1,3 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// /
// This program is free software; you can redistribute it and/or modify /
// it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. /
// /
// This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. /
// /
// You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// /
// You can contact us via: support@intellectualsites.com /
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.plotsquared.bukkit.util; package com.plotsquared.bukkit.util;
import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS;
@ -51,39 +31,39 @@ import java.util.zip.GZIPOutputStream;
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>());
/** /**
* Unique server id * Unique server id.
*/ */
private final String guid; private final String guid;
/** /**
* Debug mode * Debug mode.
*/ */
private final boolean debug; private final boolean debug;
/** /**
* The scheduled task * The scheduled task.
*/ */
private volatile BukkitTask task = null; private volatile BukkitTask task = null;
@ -97,7 +77,7 @@ public class Metrics {
} }
/** /**
* GZip compress a string of bytes * GZip compress a string of bytes.
* *
* @param input * @param input
* *
@ -115,8 +95,7 @@ public class Metrics {
if (gzos != null) { if (gzos != null) {
try { try {
gzos.close(); gzos.close();
} catch (IOException ignore) { } catch (IOException ignore) {}
}
} }
} }
return baos.toByteArray(); return baos.toByteArray();
@ -129,7 +108,6 @@ public class Metrics {
* @param key * @param key
* @param value * @param value
* *
* @throws UnsupportedEncodingException
*/ */
private static void appendJSONPair(StringBuilder json, String key, String value) { private static void appendJSONPair(StringBuilder json, String key, String value) {
boolean isValueNumeric = false; boolean isValueNumeric = false;
@ -138,7 +116,7 @@ public class Metrics {
Double.parseDouble(value); Double.parseDouble(value);
isValueNumeric = true; isValueNumeric = true;
} }
} catch (NumberFormatException e) { } catch (NumberFormatException ignored) {
isValueNumeric = false; isValueNumeric = false;
} }
if (json.charAt(json.length() - 1) != '{') { if (json.charAt(json.length() - 1) != '{') {
@ -277,8 +255,6 @@ public class Metrics {
/** /**
* Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task. * Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task.
*
* @throws java.io.IOException
*/ */
public void enable() { public void enable() {
// Enable Task, if it is not running // Enable Task, if it is not running
@ -289,7 +265,6 @@ public class Metrics {
/** /**
* 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.
*
*/ */
public void disable() { public void disable() {
// Disable Task, if it is running // Disable Task, if it is running
@ -342,7 +317,7 @@ public class Metrics {
// Construct the post data // Construct the post data
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 name, version, author, etc // The plugin's description file containing all of the plugin data such as name, version, author, etc
appendJSONPair(json, "guid", this.guid); appendJSONPair(json, "guid", this.guid);
appendJSONPair(json, "plugin_version", pluginVersion); appendJSONPair(json, "plugin_version", pluginVersion);
appendJSONPair(json, "server_version", serverVersion); appendJSONPair(json, "server_version", serverVersion);
@ -467,7 +442,7 @@ public class Metrics {
try { try {
Class.forName("mineshafter.MineServer"); Class.forName("mineshafter.MineServer");
return true; return true;
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException ignored) {
return false; return false;
} }
} }
@ -521,7 +496,7 @@ public class Metrics {
/** /**
* Gets an <b>unmodifiable</b> set of the plotter objects in the graph * Gets an <b>unmodifiable</b> set of the plotter objects in the graph
* *
* @return an unmodifiable {@link java.util.Set} of the plotter objects * @return an unmodifiable {@link Set} of the plotter objects
*/ */
public Set<Plotter> getPlotters() { public Set<Plotter> getPlotters() {
return Collections.unmodifiableSet(this.plotters); return Collections.unmodifiableSet(this.plotters);
@ -541,11 +516,6 @@ public class Metrics {
return graph.name.equals(this.name); return graph.name.equals(this.name);
} }
/**
* Called when the server owner decides to opt-out of BukkitMetrics while the server is running.
*/
protected void onOptOut() {
}
} }
/** /**
@ -595,8 +565,7 @@ public class Metrics {
/** /**
* Called after the website graphs have been updated * Called after the website graphs have been updated
*/ */
public void reset() { public void reset() {}
}
@Override @Override
public int hashCode() { public int hashCode() {

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;
@ -20,11 +20,13 @@ import java.io.DataInput;
import java.io.DataInputStream; import java.io.DataInputStream;
import java.io.DataOutput; import java.io.DataOutput;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.util.AbstractList; import java.util.AbstractList;
@ -159,19 +161,19 @@ public class NbtFactory {
/** /**
* Load the content of a file from a stream. * Load the content of a file from a stream.
* *
* Use {@link Files#newInputStreamSupplier(java.io.File)} to provide a stream from a file. * Use {@link Files#newInputStreamSupplier(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(InputSupplier<? extends InputStream> stream, StreamOptions option) throws IOException { public static NbtCompound fromStream(ByteSource 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.getInput(); input = stream.openStream();
if (option == StreamOptions.GZIP_COMPRESSION) { if (option == StreamOptions.GZIP_COMPRESSION) {
data = new DataInputStream(new BufferedInputStream(new GZIPInputStream(input))); data = new DataInputStream(new BufferedInputStream(new GZIPInputStream(input)));
} else { } else {
@ -194,7 +196,7 @@ public class NbtFactory {
/** /**
* Save the content of a NBT compound to a stream. * Save the content of a NBT compound to a stream.
* *
* Use {@link Files#newOutputStreamSupplier(java.io.File)} to provide a stream supplier to a file. * Use {@link Files#newOutputStreamSupplier(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.
@ -223,7 +225,7 @@ 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(Object nmsCompound) { public static NbtCompound fromCompound(Object nmsCompound) {
@ -247,7 +249,7 @@ 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.
@ -283,7 +285,7 @@ public class NbtFactory {
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 (Exception e) { } catch (Exception ignored) {
throw new IllegalStateException("Unable to convert " + stack + " + to a CraftItemStack."); throw new IllegalStateException("Unable to convert " + stack + " + to a CraftItemStack.");
} }
} }
@ -314,7 +316,7 @@ public class NbtFactory {
private static Object invokeMethod(Method method, Object target, 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 (Exception e) { } catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException e) {
throw new RuntimeException("Unable to invoke method " + method + " for " + target, e); throw new RuntimeException("Unable to invoke method " + method + " for " + target, e);
} }
} }
@ -322,7 +324,7 @@ public class NbtFactory {
private static void setFieldValue(Field field, Object target, Object value) { private static void setFieldValue(Field field, Object target, Object value) {
try { try {
field.set(target, value); field.set(target, value);
} catch (Exception e) { } catch (IllegalAccessException | IllegalArgumentException e) {
throw new RuntimeException("Unable to set " + field + " for " + target, e); throw new RuntimeException("Unable to set " + field + " for " + target, e);
} }
} }
@ -330,13 +332,13 @@ public class NbtFactory {
private static Object getFieldValue(Field field, Object target) { private static Object getFieldValue(Field field, Object target) {
try { try {
return field.get(target); return field.get(target);
} catch (Exception e) { } catch (IllegalAccessException | IllegalArgumentException 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.
@ -366,7 +368,7 @@ public class NbtFactory {
} }
/** /**
* Search for the first publically and privately defined field of the given name. * Search for the first publicly and privately defined field of the given name.
* @param instance - an instance of the class with the field. * @param 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.
@ -395,9 +397,7 @@ public class NbtFactory {
try { try {
this.STREAM_TOOLS = loader.loadClass(nmsPackage + ".NBTCompressedStreamTools"); this.STREAM_TOOLS = loader.loadClass(nmsPackage + ".NBTCompressedStreamTools");
this.READ_LIMITER_CLASS = loader.loadClass(nmsPackage + ".NBTReadLimiter"); this.READ_LIMITER_CLASS = loader.loadClass(nmsPackage + ".NBTReadLimiter");
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException ignored) {}
// Ignore - we will detect this later
}
} }
private String getPackageName() { private String getPackageName() {
@ -434,12 +434,10 @@ public class NbtFactory {
if (value instanceof Wrapper) { if (value instanceof Wrapper) {
return ((Wrapper) value).getHandle(); return ((Wrapper) value).getHandle();
} else if (value instanceof List) { } else if (value instanceof List) {
throw new IllegalArgumentException("Can only insert a WrappedList."); throw new IllegalArgumentException("Can only insert a WrappedList.");
} else if (value instanceof Map) { } else if (value instanceof Map) {
throw new IllegalArgumentException("Can only insert a WrappedCompound."); throw new IllegalArgumentException("Can only insert a WrappedCompound.");
} else { } else {
return createNbtTag(getPrimitiveType(value), value); return createNbtTag(getPrimitiveType(value), value);
} }
@ -651,7 +649,7 @@ public class NbtFactory {
* All changes to this map will be reflected in the underlying NBT compound. Values may only be one of the following: * All changes to this map will be reflected in the underlying NBT compound. Values may only be one of the following:
* <ul> * <ul>
* <li>Primitive types</li> * <li>Primitive types</li>
* <li>{@link java.lang.String String}</li> * <li>{@link String String}</li>
* <li>{@link NbtList}</li> * <li>{@link NbtList}</li>
* <li>{@link NbtCompound}</li> * <li>{@link NbtCompound}</li>
* </ul> * </ul>
@ -669,7 +667,7 @@ public class NbtFactory {
super(handle, getDataMap(handle)); super(handle, getDataMap(handle));
} }
// Simplifiying access to each value // Simplifying access to each value
public Byte getByte(String key, Byte defaultValue) { public Byte getByte(String key, Byte defaultValue) {
return containsKey(key) ? (Byte) get(key) : defaultValue; return containsKey(key) ? (Byte) get(key) : defaultValue;
} }
@ -772,7 +770,7 @@ public class NbtFactory {
/** /**
* Save the content of a NBT compound to a stream. * Save the content of a NBT compound to a stream.
* <p> * <p>
* Use {@link Files#newOutputStreamSupplier(java.io.File)} to provide a stream supplier to a file. * Use {@link Files#newOutputStreamSupplier(File)} to provide a stream supplier to a file.
* @param stream - the output stream. * @param stream - the output 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.

View File

@ -56,7 +56,7 @@ public class OfflinePlayerUtil {
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

View File

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

View File

@ -45,10 +45,10 @@ public class SetGenCB {
} }
} }
if (!set) { if (!set) {
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

@ -0,0 +1,127 @@
package com.plotsquared.bukkit.util.block;
import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.block.BasicLocalBlockQueue;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.block.Block;
public class BukkitLocalQueue<T> extends BasicLocalBlockQueue<T> {
public BukkitLocalQueue(String world) {
super(world);
}
@Override
public LocalChunk<T> getLocalChunk(int x, int z) {
return (LocalChunk<T>) new BasicLocalChunk(this, x, z) {
// Custom stuff?
};
}
@Override
public void optimize() {
}
@Override
public PlotBlock getBlock(int x, int y, int z) {
World worldObj = Bukkit.getWorld(getWorld());
Block block = worldObj.getBlockAt(x, y, z);
if (block == null) {
return PlotBlock.get(0, 0);
}
int id = block.getTypeId();
if (id == 0) {
return PlotBlock.get(0, 0);
}
return PlotBlock.get(id, block.getData());
}
@Override
public void refreshChunk(int x, int z) {
World worldObj = Bukkit.getWorld(getWorld());
worldObj.refreshChunk(x, z);
}
@Override
public void fixChunkLighting(int x, int z) {
// Do nothing
}
@Override
public final void regenChunk(int x, int z) {
World worldObj = Bukkit.getWorld(getWorld());
worldObj.regenerateChunk(x, z);
}
@Override
public final void setComponents(LocalChunk<T> lc) {
setBlocks(lc);
setBiomes(lc);
}
public World getBukkitWorld() {
return Bukkit.getWorld(getWorld());
}
public Chunk getChunk(int x, int z) {
return getBukkitWorld().getChunkAt(x, z);
}
public void setBlocks(LocalChunk<T> lc) {
World worldObj = Bukkit.getWorld(getWorld());
Chunk chunk = worldObj.getChunkAt(lc.getX(), lc.getZ());
chunk.load(true);
for (int layer = 0; layer < lc.blocks.length; layer++) {
PlotBlock[] blocksLayer = (PlotBlock[]) lc.blocks[layer];
if (blocksLayer != null) {
for (int j = 0; j < blocksLayer.length; j++) {
PlotBlock block = blocksLayer[j];
int x = MainUtil.x_loc[layer][j];
int y = MainUtil.y_loc[layer][j];
int z = MainUtil.y_loc[layer][j];
Block existing = chunk.getBlock(x, y, z);
int existingId = existing.getTypeId();
if (existingId == block.id) {
if (existingId == 0) {
continue;
}
if (existing.getData() == block.data) {
continue;
}
}
existing.setTypeIdAndData(block.id, block.data, false);
}
}
}
}
public void setBiomes(LocalChunk<T> lc) {
if (lc.biomes != null) {
World worldObj = Bukkit.getWorld(getWorld());
int bx = lc.getX() << 4;
int bz = lc.getX() << 4;
String last = null;
Biome biome = null;
for (int x = 0; x < lc.biomes.length; x++) {
String[] biomes2 = lc.biomes[x];
if (biomes2 != null) {
for (int y = 0; y < biomes2.length; y++) {
String biomeStr = biomes2[y];
if (biomeStr != null) {
if (last == null || !StringMan.isEqual(last, biomeStr)) {
biome = Biome.valueOf(biomeStr.toUpperCase());
}
worldObj.setBiome(bx, bz, biome);
}
}
}
}
}
}
}

View File

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

View File

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

View File

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

View File

@ -1,171 +1,276 @@
package com.plotsquared.bukkit.util.block; package com.plotsquared.bukkit.util.block;
import com.intellectualcrafters.plot.object.ChunkLoc; import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.object.ChunkWrapper;
import com.intellectualcrafters.plot.object.PseudoRandom; import com.intellectualcrafters.plot.object.PseudoRandom;
import com.intellectualcrafters.plot.util.ChunkManager; 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.ReflectionUtils;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefClass; import com.intellectualcrafters.plot.util.block.BasicLocalBlockQueue;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefConstructor;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefField;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod;
import com.intellectualcrafters.plot.util.ReflectionUtils.RefMethod.RefExecutor;
import com.intellectualcrafters.plot.util.SetQueue;
import com.intellectualcrafters.plot.util.SetQueue.ChunkWrapper;
import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.bukkit.util.BukkitUtil;
import com.plotsquared.bukkit.util.SendChunk;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.ArrayList; import java.util.Arrays;
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.Map.Entry; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.bukkit.Chunk; import org.bukkit.Chunk;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.block.Biome;
import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass; import static com.intellectualcrafters.plot.util.ReflectionUtils.getRefClass;
public class FastQueue_1_9 extends SlowQueue { public class BukkitLocalQueue_1_9 extends BukkitLocalQueue<char[]> {
private final Object air; private final Object air;
private final SendChunk chunkSender; // private final HashMap<ChunkWrapper, Chunk> toUpdate = new HashMap<>();
private final HashMap<ChunkWrapper, Chunk> toUpdate = new HashMap<>(); private final ReflectionUtils.RefMethod methodGetHandleChunk;
private final RefMethod methodGetHandleChunk; private final ReflectionUtils.RefMethod methodInitLighting;
private final RefMethod methodInitLighting; private final ReflectionUtils.RefConstructor classBlockPositionConstructor;
private final RefConstructor classBlockPositionConstructor; private final ReflectionUtils.RefConstructor classChunkSectionConstructor;
private final RefConstructor classChunkSectionConstructor; private final ReflectionUtils.RefMethod methodW;
private final RefMethod methodW; private final ReflectionUtils.RefMethod methodAreNeighborsLoaded;
private final RefMethod methodAreNeighborsLoaded; private final ReflectionUtils.RefField fieldSections;
private final RefField fieldSections; private final ReflectionUtils.RefField fieldWorld;
private final RefField fieldWorld; private final ReflectionUtils.RefMethod methodGetBlocks;
private final RefMethod methodGetBlocks; private final ReflectionUtils.RefMethod methodGetType;
private final RefMethod methodGetType; private final ReflectionUtils.RefMethod methodSetType;
private final RefMethod methodSetType; private final ReflectionUtils.RefMethod methodGetCombinedId;
private final RefMethod methodGetCombinedId; private final ReflectionUtils.RefMethod methodGetByCombinedId;
private final RefMethod methodGetByCombinedId; private final ReflectionUtils.RefMethod methodGetWorld;
private final RefMethod methodGetWorld;
private final RefField tileEntityUnload;
private final ReflectionUtils.RefField tileEntityListTick;
public FastQueue_1_9() throws RuntimeException { public BukkitLocalQueue_1_9(String world) throws NoSuchMethodException, ClassNotFoundException, NoSuchFieldException {
RefClass classCraftChunk = getRefClass("{cb}.CraftChunk"); super(world);
ReflectionUtils.RefClass classCraftChunk = getRefClass("{cb}.CraftChunk");
this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle"); this.methodGetHandleChunk = classCraftChunk.getMethod("getHandle");
RefClass classChunk = getRefClass("{nms}.Chunk"); ReflectionUtils.RefClass classChunk = getRefClass("{nms}.Chunk");
this.methodInitLighting = classChunk.getMethod("initLighting"); this.methodInitLighting = classChunk.getMethod("initLighting");
RefClass classBlockPosition = getRefClass("{nms}.BlockPosition"); ReflectionUtils.RefClass classBlockPosition = getRefClass("{nms}.BlockPosition");
this.classBlockPositionConstructor = classBlockPosition.getConstructor(int.class, int.class, int.class); this.classBlockPositionConstructor = classBlockPosition.getConstructor(int.class, int.class, int.class);
RefClass classWorld = getRefClass("{nms}.World"); ReflectionUtils.RefClass classWorld = getRefClass("{nms}.World");
this.tileEntityUnload = classWorld.getField("tileEntityListUnload"); this.tileEntityListTick = classWorld.getField("tileEntityListTick");
this.methodGetWorld = classChunk.getMethod("getWorld"); this.methodGetWorld = classChunk.getMethod("getWorld");
this.methodW = classWorld.getMethod("w", classBlockPosition.getRealClass()); this.methodW = classWorld.getMethod("w", classBlockPosition.getRealClass());
this.fieldSections = classChunk.getField("sections"); this.fieldSections = classChunk.getField("sections");
this.fieldWorld = classChunk.getField("world"); this.fieldWorld = classChunk.getField("world");
RefClass classBlock = getRefClass("{nms}.Block"); ReflectionUtils.RefClass classBlock = getRefClass("{nms}.Block");
RefClass classIBlockData = getRefClass("{nms}.IBlockData"); ReflectionUtils.RefClass classIBlockData = getRefClass("{nms}.IBlockData");
this.methodGetCombinedId = classBlock.getMethod("getCombinedId", classIBlockData.getRealClass()); this.methodGetCombinedId = classBlock.getMethod("getCombinedId", classIBlockData.getRealClass());
this.methodGetByCombinedId = classBlock.getMethod("getByCombinedId", int.class); this.methodGetByCombinedId = classBlock.getMethod("getByCombinedId", int.class);
RefClass classChunkSection = getRefClass("{nms}.ChunkSection"); ReflectionUtils.RefClass classChunkSection = getRefClass("{nms}.ChunkSection");
this.methodGetBlocks = classChunkSection.getMethod("getBlocks"); this.methodGetBlocks = classChunkSection.getMethod("getBlocks");
this.methodGetType = classChunkSection.getMethod("getType", int.class, int.class, int.class); 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.methodSetType = classChunkSection.getMethod("setType", int.class, int.class, int.class, classIBlockData.getRealClass());
this.methodAreNeighborsLoaded = classChunk.getMethod("areNeighborsLoaded", int.class); this.methodAreNeighborsLoaded = classChunk.getMethod("areNeighborsLoaded", int.class);
this.classChunkSectionConstructor = classChunkSection.getConstructor(int.class, boolean.class, char[].class); this.classChunkSectionConstructor = classChunkSection.getConstructor(int.class, boolean.class, char[].class);
this.air = this.methodGetByCombinedId.call(0); this.air = this.methodGetByCombinedId.call(0);
this.chunkSender = new SendChunk();
TaskManager.runTaskRepeat(new Runnable() {
@Override
public void run() {
if (FastQueue_1_9.this.toUpdate.isEmpty()) {
return;
}
int count = 0;
ArrayList<Chunk> chunks = new ArrayList<>();
Iterator<Entry<ChunkWrapper, Chunk>> i = FastQueue_1_9.this.toUpdate.entrySet().iterator();
while (i.hasNext() && count < 128) {
chunks.add(i.next().getValue());
i.remove();
count++;
}
if (count == 0) {
return;
}
update(chunks);
}
}, 1);
MainUtil.initCache(); MainUtil.initCache();
} }
public void update(Collection<Chunk> chunks) { @Override
if (chunks.isEmpty()) { public LocalChunk<char[]> getLocalChunk(int x, int z) {
return; return new CharLocalChunk_1_8_3(this, x, z);
}
public class CharLocalChunk_1_8_3 extends CharLocalChunk {
public short[] count;
public short[] air;
public short[] relight;
public CharLocalChunk_1_8_3(BasicLocalBlockQueue parent, int x, int z) {
super(parent, x, z);
this.count = new short[16];
this.air = new short[16];
this.relight = new short[16];
} }
if (!MainUtil.canSendChunk) {
for (Chunk chunk : chunks) { @Override
chunk.getWorld().refreshChunk(chunk.getX(), chunk.getZ()); public void setBlock(int x, int y, int z, int id, int data) {
chunk.unload(true, true); int i = MainUtil.CACHE_I[y][x][z];
chunk.load(); int j = MainUtil.CACHE_J[y][x][z];
char[] vs = this.blocks[i];
if (vs == null) {
vs = this.blocks[i] = new char[4096];
this.count[i]++;
} else if (vs[j] == 0) {
this.count[i]++;
}
switch (id) {
case 0:
this.air[i]++;
vs[j] = (char) 1;
return;
case 10:
case 11:
case 39:
case 40:
case 51:
case 74:
case 89:
case 122:
case 124:
case 138:
case 169:
this.relight[i]++;
case 2:
case 4:
case 13:
case 14:
case 15:
case 20:
case 21:
case 22:
case 30:
case 32:
case 37:
case 41:
case 42:
case 45:
case 46:
case 47:
case 48:
case 49:
case 55:
case 56:
case 57:
case 58:
case 60:
case 7:
case 8:
case 9:
case 73:
case 78:
case 79:
case 80:
case 81:
case 82:
case 83:
case 85:
case 87:
case 88:
case 101:
case 102:
case 103:
case 110:
case 112:
case 113:
case 121:
case 129:
case 133:
case 165:
case 166:
case 170:
case 172:
case 173:
case 174:
case 181:
case 182:
case 188:
case 189:
case 190:
case 191:
case 192:
vs[j] = (char) (id << 4);
return;
case 130:
case 76:
case 62:
this.relight[i]++;
case 54:
case 146:
case 61:
case 65:
case 68:
case 50:
if (data < 2) {
data = 2;
}
default:
vs[j] = (char) ((id << 4) + data);
return;
} }
return;
} }
try {
this.chunkSender.sendChunk(chunks); public char[] getIdArray(int i) {
} catch (Throwable e) { return this.blocks[i];
e.printStackTrace(); }
MainUtil.canSendChunk = false;
public int getCount(int i) {
return this.count[i];
}
public int getAir(int i) {
return this.air[i];
}
public void setCount(int i, short value) {
this.count[i] = value;
}
public int getRelight(int i) {
return this.relight[i];
}
public int getTotalCount() {
int total = 0;
for (int i = 0; i < 16; i++) {
total += this.count[i];
}
return total;
}
public int getTotalRelight() {
if (getTotalCount() == 0) {
Arrays.fill(this.count, (short) 1);
Arrays.fill(this.relight, Short.MAX_VALUE);
return Short.MAX_VALUE;
}
int total = 0;
for (int i = 0; i < 16; i++) {
total += this.relight[i];
}
return total;
} }
} }
/**
* This should be overridden by any specialized queues
* @param plotChunk
*/
@Override @Override
public void execute(PlotChunk<Chunk> plotChunk) { public void setBlocks(LocalChunk lc) {
FastChunk_1_9 fs = (FastChunk_1_9) plotChunk; CharLocalChunk_1_8_3 fs = (CharLocalChunk_1_8_3) lc;
Chunk chunk = plotChunk.getChunk(); Chunk chunk = getChunk(lc.getX(), lc.getZ());
World world = chunk.getWorld();
ChunkWrapper wrapper = plotChunk.getChunkWrapper();
if (!this.toUpdate.containsKey(wrapper)) {
this.toUpdate.put(wrapper, chunk);
}
chunk.load(true); chunk.load(true);
World world = chunk.getWorld();
try { try {
boolean flag = world.getEnvironment() == Environment.NORMAL; boolean flag = world.getEnvironment() == World.Environment.NORMAL;
// Sections // Sections
Method getHandle = chunk.getClass().getDeclaredMethod("getHandle"); Method getHandle = chunk.getClass().getDeclaredMethod("getHandle");
Object c = getHandle.invoke(chunk); Object c = getHandle.invoke(chunk);
Object w = methodGetWorld.of(c).call(); Object w = this.methodGetWorld.of(c).call();
Class<? extends Object> clazz = c.getClass(); Class<? extends Object> clazz = c.getClass();
Field sf = clazz.getDeclaredField("sections"); Field sf = clazz.getDeclaredField("sections");
sf.setAccessible(true); sf.setAccessible(true);
Field tf = clazz.getDeclaredField("tileEntities"); Field tf = clazz.getDeclaredField("tileEntities");
Field entitySlices = clazz.getDeclaredField("entitySlices"); Field entitySlices = clazz.getDeclaredField("entitySlices");
Object[] sections = (Object[]) sf.get(c); Object[] sections = (Object[]) sf.get(c);
HashMap<?, ?> tiles = (HashMap<?, ?>) tf.get(c); HashMap<?, ?> tiles = (HashMap<?, ?>) tf.get(c);
Collection<Object> tilesUnload = (Collection<Object>) tileEntityUnload.of(w).get();
Collection<?>[] entities = (Collection<?>[]) entitySlices.get(c); Collection<?>[] entities = (Collection<?>[]) entitySlices.get(c);
Method xm = null; Method xm = null;
Method ym = null; Method ym = null;
Method zm = null; Method zm = null;
// Trim tiles // Trim tiles
Set<Entry<?, ?>> entrySet = (Set<Entry<?, ?>>) (Set<?>) tiles.entrySet(); boolean removed = false;
Iterator<Entry<?, ?>> iterator = entrySet.iterator(); Set<Map.Entry<?, ?>> entrySet = (Set<Map.Entry<?, ?>>) (Set<?>) tiles.entrySet();
Iterator<Map.Entry<?, ?>> iterator = entrySet.iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
Entry<?, ?> tile = iterator.next(); Map.Entry<?, ?> tile = iterator.next();
Object pos = tile.getKey(); Object pos = tile.getKey();
if (xm == null) { if (xm == null) {
Class<? extends Object> clazz2 = pos.getClass().getSuperclass(); Class<?> clazz2 = pos.getClass().getSuperclass();
xm = clazz2.getDeclaredMethod("getX"); xm = clazz2.getDeclaredMethod("getX");
ym = clazz2.getDeclaredMethod("getY"); ym = clazz2.getDeclaredMethod("getY");
zm = clazz2.getDeclaredMethod("getZ"); zm = clazz2.getDeclaredMethod("getZ");
@ -175,15 +280,18 @@ public class FastQueue_1_9 extends SlowQueue {
int lz = (int) zm.invoke(pos) & 15; int lz = (int) zm.invoke(pos) & 15;
int j = MainUtil.CACHE_I[ly][lx][lz]; int j = MainUtil.CACHE_I[ly][lx][lz];
int k = MainUtil.CACHE_J[ly][lx][lz]; int k = MainUtil.CACHE_J[ly][lx][lz];
int[] 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) {
tilesUnload.add(tile.getValue()); removed = true;
iterator.remove(); 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++) {
@ -197,32 +305,25 @@ public class FastQueue_1_9 extends SlowQueue {
if (fs.getCount(j) == 0) { if (fs.getCount(j) == 0) {
continue; continue;
} }
int[] newArray = fs.getIdArray(j); char[] newArray = fs.getIdArray(j);
if (newArray == null) { if (newArray == null) {
continue; continue;
} }
Object section = sections[j]; Object section = sections[j];
if (section == null || fs.getCount(j) >= 4096) { if (section == null || fs.getCount(j) >= 4096) {
char[] array = new char[4096]; section = sections[j] = newChunkSection(j << 4, flag, fs.getIdArray(j));
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; continue;
} }
Object currentArray = getBlocks(section); Object currentArray = getBlocks(section);
RefExecutor setType = this.methodSetType.of(section); ReflectionUtils.RefMethod.RefExecutor setType = this.methodSetType.of(section);
boolean fill = true; boolean fill = true;
for (int k = 0; k < newArray.length; k++) { for (int k = 0; k < newArray.length; k++) {
int n = newArray[k]; char n = newArray[k];
switch (n) { switch (n) {
case 0: case 0:
fill = false; fill = false;
continue; continue;
case -1: { case 1: {
fill = false; fill = false;
int x = MainUtil.x_loc[j][k]; int x = MainUtil.x_loc[j][k];
int y = MainUtil.y_loc[j][k]; int y = MainUtil.y_loc[j][k];
@ -230,13 +331,14 @@ public class FastQueue_1_9 extends SlowQueue {
setType.call(x, y & 15, z, this.air); setType.call(x, y & 15, z, this.air);
continue; continue;
} }
default: { default:
int x = MainUtil.x_loc[j][k]; int x = MainUtil.x_loc[j][k];
int y = MainUtil.y_loc[j][k]; int y = MainUtil.y_loc[j][k];
int z = MainUtil.z_loc[j][k]; int z = MainUtil.z_loc[j][k];
Object iBlock = this.methodGetByCombinedId.call((int) n); int id = n >> 4;
int data = n & 15;
Object iBlock = this.methodGetByCombinedId.call((int) (id & 0xFFF) + (data << 12));
setType.call(x, y & 15, z, iBlock); setType.call(x, y & 15, z, iBlock);
}
} }
} }
if (fill) { if (fill) {
@ -244,30 +346,14 @@ public class FastQueue_1_9 extends SlowQueue {
} }
} }
// Clear // Clear
} catch (IllegalAccessException | IllegalArgumentException | NoSuchMethodException | SecurityException | InvocationTargetException | } catch (IllegalArgumentException | SecurityException | ReflectiveOperationException e) {
NoSuchFieldException e) {
e.printStackTrace(); e.printStackTrace();
} }
int[][] biomes = fs.biomes; fixLighting(chunk, fs, true);
Biome[] values = Biome.values(); refreshChunk(fs.getX(), fs.getZ());
if (biomes != null) {
for (int x = 0; x < 16; x++) {
int[] array = biomes[x];
if (array == null) {
continue;
}
for (int z = 0; z < 16; z++) {
int biome = array[z];
if (biome == 0) {
continue;
}
chunk.getBlock(x, 0, z).setBiome(values[biome]);
}
}
}
} }
public Object newChunkSection(int i, boolean flag, char[] ids) { public Object newChunkSection(int i, boolean flag, char[] ids) throws ReflectiveOperationException {
return this.classChunkSectionConstructor.create(i, flag, ids); return this.classChunkSectionConstructor.create(i, flag, ids);
} }
@ -275,38 +361,27 @@ public class FastQueue_1_9 extends SlowQueue {
return this.methodGetBlocks.of(obj).call(); return this.methodGetBlocks.of(obj).call();
} }
/**
* This should be overridden by any specialized queues
* @param wrap
*/
@Override @Override
public PlotChunk<Chunk> getChunk(ChunkWrapper wrap) { public void fixChunkLighting(int x, int z) {
return new FastChunk_1_9(wrap); Object c = this.methodGetHandleChunk.of(getChunk(x, z)).call();
this.methodInitLighting.of(c).call();
} }
/** public boolean fixLighting(Chunk chunk, CharLocalChunk_1_8_3 bc, boolean fixAll) {
* This should be overridden by any specialized queues
* @param pc
*/
@Override
public boolean fixLighting(PlotChunk<Chunk> pc, boolean fixAll) {
try { try {
FastChunk_1_9 bc = (FastChunk_1_9) pc;
Chunk chunk = bc.getChunk();
if (!chunk.isLoaded()) { if (!chunk.isLoaded()) {
chunk.load(false); chunk.load(false);
} else { } else {
chunk.unload(true, true); chunk.unload(true, false);
chunk.load(false); chunk.load(false);
} }
// Initialize lighting // Initialize lighting
Object c = this.methodGetHandleChunk.of(chunk).call(); Object c = this.methodGetHandleChunk.of(chunk).call();
ChunkWrapper wrapper = new ChunkWrapper(getWorld(), bc.getX(), bc.getZ());
if (fixAll && !(boolean) this.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();
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) {
@ -314,7 +389,7 @@ public class FastQueue_1_9 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(getWorld(), new ChunkLoc(x, z), true);
} }
} }
} }
@ -332,7 +407,7 @@ public class FastQueue_1_9 extends SlowQueue {
int X = chunk.getX() << 4; int X = chunk.getX() << 4;
int Z = chunk.getZ() << 4; int Z = chunk.getZ() << 4;
RefExecutor relight = this.methodW.of(w); ReflectionUtils.RefMethod.RefExecutor relight = this.methodW.of(w);
for (int j = 0; j < sections.length; j++) { for (int j = 0; j < sections.length; j++) {
Object section = sections[j]; Object section = sections[j];
if (section == null) { if (section == null) {
@ -341,7 +416,7 @@ public class FastQueue_1_9 extends SlowQueue {
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;
} }
int[] array = bc.getIdArray(j); char[] array = bc.getIdArray(j);
if (array != null) { if (array != null) {
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++) {
@ -377,7 +452,7 @@ public class FastQueue_1_9 extends SlowQueue {
int x = MainUtil.x_loc[j][k]; int x = MainUtil.x_loc[j][k];
int y = MainUtil.y_loc[j][k]; int y = MainUtil.y_loc[j][k];
int z = MainUtil.z_loc[j][k]; int z = MainUtil.z_loc[j][k];
if (isSurrounded(bc.getIdArrays(), x, y, z)) { if (isSurrounded(bc.blocks, x, y, z)) {
continue; continue;
} }
Object pos = this.classBlockPositionConstructor.create(X + x, y, Z + z); Object pos = this.classBlockPositionConstructor.create(X + x, y, Z + z);
@ -393,7 +468,12 @@ public class FastQueue_1_9 extends SlowQueue {
return false; return false;
} }
public boolean isSurrounded(int[][] sections, int x, int y, int z) { @Override
public void refreshChunk(int x, int z) {
getBukkitWorld().refreshChunk(x, z);
}
public boolean isSurrounded(char[][] sections, int x, int y, int z) {
return isSolid(getId(sections, x, y + 1, z)) return isSolid(getId(sections, x, y + 1, z))
&& isSolid(getId(sections, x + 1, y - 1, z)) && isSolid(getId(sections, x + 1, y - 1, z))
&& isSolid(getId(sections, x - 1, y, z)) && isSolid(getId(sections, x - 1, y, z))
@ -409,7 +489,15 @@ public class FastQueue_1_9 extends SlowQueue {
return false; return false;
} }
public int getId(int[][] sections, int x, int y, int z) { public int getId(char[] section, int x, int y, int z) {
if (section == null) {
return 0;
}
int j = MainUtil.CACHE_J[y][x][z];
return section[j] >> 4;
}
public int getId(char[][] sections, int x, int y, int z) {
if (x < 0 || x > 15 || z < 0 || z > 15) { if (x < 0 || x > 15 || z < 0 || z > 15) {
return 1; return 1;
} }
@ -417,53 +505,10 @@ public class FastQueue_1_9 extends SlowQueue {
return 1; return 1;
} }
int i = MainUtil.CACHE_I[y][x][z]; int i = MainUtil.CACHE_I[y][x][z];
int[] section = sections[i]; char[] section = sections[i];
if (section == null) { if (section == null) {
return 0; return 0;
} }
int j = MainUtil.CACHE_J[y][x][z];
return section[j];
}
public int getId(Object section, int x, int y, int z) {
int j = MainUtil.CACHE_J[y][x][z];
Object iBlock = this.methodGetType.of(section).call(x, y & 15, z);
return (int) this.methodGetCombinedId.call(iBlock);
}
public int getId(Object[] sections, int x, int y, int z) {
if (x < 0 || x > 15 || z < 0 || z > 15) {
return 1;
}
if (y < 0 || y > 255) {
return 1;
}
int i = MainUtil.CACHE_I[y][x][z];
Object section = sections[i];
if (section == null) {
return 0;
}
// Object array = getBlocks(section);
return getId(section, x, y, z); return getId(section, x, y, z);
} }
/**
* This should be overridden by any specialized queues
* @param world
* @param locations
*/
@Override
public void sendChunk(final String world, final Collection<ChunkLoc> locations) {
World worldObj = BukkitUtil.getWorld(world);
for (ChunkLoc loc : locations) {
ChunkWrapper wrapper = SetQueue.IMP.new ChunkWrapper(world, loc.x, loc.z);
this.toUpdate.remove(wrapper);
}
TaskManager.runTaskLater(new Runnable() {
@Override
public void run() {
FastQueue_1_9.this.chunkSender.sendChunk(world, locations);
}
}, 1);
}
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -4,7 +4,7 @@ version: ${version}
load: STARTUP load: STARTUP
description: > description: >
Easy, yet powerful Plot World generation and management. Easy, yet powerful Plot World generation and management.
authors: [Citymonstret, Empire92] authors: [Citymonstret, Empire92, MattBDev]
softdepend: [WorldEdit, BarAPI, CameraAPI, Vault] softdepend: [WorldEdit, BarAPI, CameraAPI, Vault]
loadbefore: [MultiWorld, Multiverse-Core] loadbefore: [MultiWorld, Multiverse-Core]
database: false database: false

View File

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

View File

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

View File

@ -4,10 +4,10 @@ package com.intellectualcrafters.configuration;
* Various settings for controlling the input and output of a {@link * Various settings for controlling the input and output of a {@link
* Configuration} * Configuration}
*/ */
public class ConfigurationOptions { class ConfigurationOptions {
private final Configuration configuration;
private char pathSeparator = '.'; private char pathSeparator = '.';
private boolean copyDefaults = false; private boolean copyDefaults = false;
private final Configuration configuration;
protected ConfigurationOptions(final Configuration configuration) { protected ConfigurationOptions(final Configuration configuration) {
this.configuration = configuration; this.configuration = configuration;
@ -57,9 +57,9 @@ public class ConfigurationOptions {
* If this is true, all values in the default Configuration will be * If this is true, all values in the default Configuration will be
* directly copied, making it impossible to distinguish between values * directly copied, making it impossible to distinguish between values
* that were set and values that are provided by default. As a result, * that were set and values that are provided by default. As a result,
* {@link ConfigurationSection#contains(java.lang.String)} will always * {@link ConfigurationSection#contains(String)} will always
* return the same value as {@link * return the same value as {@link
* ConfigurationSection#isSet(java.lang.String)}. The default value is * ConfigurationSection#isSet(String)}. The default value is
* false. * false.
* *
* @return Whether or not defaults are directly copied * @return Whether or not defaults are directly copied
@ -75,9 +75,9 @@ public class ConfigurationOptions {
* If this is true, all values in the default Configuration will be * If this is true, all values in the default Configuration will be
* directly copied, making it impossible to distinguish between values * directly copied, making it impossible to distinguish between values
* that were set and values that are provided by default. As a result, * that were set and values that are provided by default. As a result,
* {@link ConfigurationSection#contains(java.lang.String)} will always * {@link ConfigurationSection#contains(String)} will always
* return the same value as {@link * return the same value as {@link
* ConfigurationSection#isSet(java.lang.String)}. The default value is * ConfigurationSection#isSet(String)}. The default value is
* false. * false.
* *
* @param value Whether or not defaults are directly copied * @param value Whether or not defaults are directly copied

View File

@ -144,10 +144,10 @@ public interface ConfigurationSection {
* {@link Configuration}. * {@link Configuration}.
* *
* @param path Path of the Object to get. * @param path Path of the Object to get.
* @param def The default value to return if the path is not found. * @param defaultValue The default value to return if the path is not found.
* @return Requested Object. * @return Requested Object.
*/ */
Object get(String path, Object def); Object get(String path, Object defaultValue);
/** /**
* Sets the specified path to the given value. * Sets the specified path to the given value.
@ -293,11 +293,11 @@ public interface ConfigurationSection {
* {@link Configuration}. * {@link Configuration}.
* *
* @param path Path of the boolean to get. * @param path Path of the boolean to get.
* @param def The default value to return if the path is not found or is * @param defaultValue The default value to return if the path is not found or is
* not a boolean. * not a boolean.
* @return Requested boolean. * @return Requested boolean.
*/ */
boolean getBoolean(String path, boolean def); boolean getBoolean(String path, boolean defaultValue);
/** /**
* Checks if the specified path is a boolean. * Checks if the specified path is a boolean.
@ -333,11 +333,11 @@ public interface ConfigurationSection {
* {@link Configuration}. * {@link Configuration}.
* *
* @param path Path of the double to get. * @param path Path of the double to get.
* @param def The default value to return if the path is not found or is * @param defaultValue The default value to return if the path is not found or is
* not a double. * not a double.
* @return Requested double. * @return Requested double.
*/ */
double getDouble(String path, double def); double getDouble(String path, double defaultValue);
/** /**
* Checks if the specified path is a double. * Checks if the specified path is a double.

View File

@ -23,35 +23,35 @@ public class MemoryConfiguration extends MemorySection implements Configuration
* @param defaults Default value provider * @param defaults Default value provider
* @throws IllegalArgumentException Thrown if defaults is null * @throws IllegalArgumentException Thrown if defaults is null
*/ */
public MemoryConfiguration(final Configuration defaults) { public MemoryConfiguration(Configuration defaults) {
this.defaults = defaults; this.defaults = defaults;
} }
@Override @Override
public void addDefault(final String path, final Object value) { public void addDefault(String path, Object value) {
if (path == null) { if (path == null) {
throw new NullPointerException("Path may not be null"); throw new NullPointerException("Path may not be null");
} }
if (defaults == null) { if (this.defaults == null) {
defaults = new MemoryConfiguration(); this.defaults = new MemoryConfiguration();
} }
defaults.set(path, value); this.defaults.set(path, value);
} }
@Override @Override
public void addDefaults(final Map<String, Object> defaults) { public void addDefaults(Map<String, Object> defaults) {
if (defaults == null) { if (defaults == null) {
throw new NullPointerException("Defaults may not be null"); throw new NullPointerException("Defaults may not be null");
} }
for (final Map.Entry<String, Object> entry : defaults.entrySet()) { for (Map.Entry<String, Object> entry : defaults.entrySet()) {
addDefault(entry.getKey(), entry.getValue()); addDefault(entry.getKey(), entry.getValue());
} }
} }
@Override @Override
public void addDefaults(final Configuration defaults) { public void addDefaults(Configuration defaults) {
if (defaults == null) { if (defaults == null) {
throw new NullPointerException("Defaults may not be null"); throw new NullPointerException("Defaults may not be null");
} }
@ -60,7 +60,12 @@ public class MemoryConfiguration extends MemorySection implements Configuration
} }
@Override @Override
public void setDefaults(final Configuration defaults) { public Configuration getDefaults() {
return this.defaults;
}
@Override
public void setDefaults(Configuration defaults) {
if (defaults == null) { if (defaults == null) {
throw new NullPointerException("Defaults may not be null"); throw new NullPointerException("Defaults may not be null");
} }
@ -68,11 +73,6 @@ public class MemoryConfiguration extends MemorySection implements Configuration
this.defaults = defaults; this.defaults = defaults;
} }
@Override
public Configuration getDefaults() {
return defaults;
}
@Override @Override
public ConfigurationSection getParent() { public ConfigurationSection getParent() {
return null; return null;
@ -80,10 +80,10 @@ public class MemoryConfiguration extends MemorySection implements Configuration
@Override @Override
public MemoryConfigurationOptions options() { public MemoryConfigurationOptions options() {
if (options == null) { if (this.options == null) {
options = new MemoryConfigurationOptions(this); this.options = new MemoryConfigurationOptions(this);
} }
return options; return this.options;
} }
} }

View File

@ -74,8 +74,7 @@ public class MemorySection implements ConfigurationSection {
if (obj instanceof String) { if (obj instanceof String) {
try { try {
return Double.parseDouble((String) obj); return Double.parseDouble((String) obj);
} catch (NumberFormatException ignored) { } catch (NumberFormatException ignored) {}
}
} else if (obj instanceof List) { } else if (obj instanceof List) {
List<?> val = (List<?>) obj; List<?> val = (List<?>) obj;
if (!val.isEmpty()) { if (!val.isEmpty()) {
@ -92,8 +91,7 @@ public class MemorySection implements ConfigurationSection {
if (obj instanceof String) { if (obj instanceof String) {
try { try {
return Integer.parseInt((String) obj); return Integer.parseInt((String) obj);
} catch (NumberFormatException ignored) { } catch (NumberFormatException ignored) {}
}
} else if (obj instanceof List) { } else if (obj instanceof List) {
List<?> val = (List<?>) obj; List<?> val = (List<?>) obj;
if (!val.isEmpty()) { if (!val.isEmpty()) {
@ -110,8 +108,7 @@ public class MemorySection implements ConfigurationSection {
if (obj instanceof String) { if (obj instanceof String) {
try { try {
return Long.parseLong((String) obj); return Long.parseLong((String) obj);
} catch (NumberFormatException ignored) { } catch (NumberFormatException ignored) {}
}
} else if (obj instanceof List) { } else if (obj instanceof List) {
List<?> val = (List<?>) obj; List<?> val = (List<?>) obj;
if (!val.isEmpty()) { if (!val.isEmpty()) {
@ -325,7 +322,7 @@ public class MemorySection implements ConfigurationSection {
} }
@Override @Override
public Object get(String path, Object def) { public Object get(String path, Object defaultValue) {
if (path == null) { if (path == null) {
throw new NullPointerException("Path cannot be null"); throw new NullPointerException("Path cannot be null");
} }
@ -348,7 +345,7 @@ public class MemorySection implements ConfigurationSection {
while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1) { while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1) {
section = section.getConfigurationSection(path.substring(i2, i1)); section = section.getConfigurationSection(path.substring(i2, i1));
if (section == null) { if (section == null) {
return def; return defaultValue;
} }
} }
@ -356,12 +353,12 @@ public class MemorySection implements ConfigurationSection {
if (section == this) { if (section == this) {
Object result = this.map.get(key); Object result = this.map.get(key);
if (result == null) { if (result == null) {
return def; return defaultValue;
} else { } else {
return result; return result;
} }
} }
return section.get(key, def); return section.get(key, defaultValue);
} }
@Override @Override
@ -465,12 +462,12 @@ public class MemorySection implements ConfigurationSection {
} }
@Override @Override
public boolean getBoolean(String path, boolean def) { public boolean getBoolean(String path, boolean defaultValue) {
Object val = get(path, def); Object val = get(path, defaultValue);
if (val instanceof Boolean) { if (val instanceof Boolean) {
return (Boolean) val; return (Boolean) val;
} else { } else {
return def; return defaultValue;
} }
} }
@ -487,9 +484,9 @@ public class MemorySection implements ConfigurationSection {
} }
@Override @Override
public double getDouble(String path, double def) { public double getDouble(String path, double defaultValue) {
Object val = get(path, def); Object val = get(path, defaultValue);
return toDouble(val, def); return toDouble(val, defaultValue);
} }
@Override @Override
@ -558,10 +555,6 @@ public class MemorySection implements ConfigurationSection {
public List<Integer> getIntegerList(String path) { public List<Integer> getIntegerList(String path) {
List<?> list = getList(path); List<?> list = getList(path);
if (list == null) {
return new ArrayList<>(0);
}
List<Integer> result = new ArrayList<>(); List<Integer> result = new ArrayList<>();
for (Object object : list) { for (Object object : list) {
@ -570,8 +563,7 @@ public class MemorySection implements ConfigurationSection {
} else if (object instanceof String) { } else if (object instanceof String) {
try { try {
result.add(Integer.valueOf((String) object)); result.add(Integer.valueOf((String) object));
} catch (NumberFormatException ignored) { } catch (NumberFormatException ignored) {}
}
} else if (object instanceof Character) { } else if (object instanceof Character) {
result.add((int) (Character) object); result.add((int) (Character) object);
} else if (object instanceof Number) { } else if (object instanceof Number) {
@ -586,10 +578,6 @@ public class MemorySection implements ConfigurationSection {
public List<Boolean> getBooleanList(String path) { public List<Boolean> getBooleanList(String path) {
List<?> list = getList(path); List<?> list = getList(path);
if (list == null) {
return new ArrayList<>(0);
}
List<Boolean> result = new ArrayList<>(); List<Boolean> result = new ArrayList<>();
for (Object object : list) { for (Object object : list) {
@ -611,10 +599,6 @@ public class MemorySection implements ConfigurationSection {
public List<Double> getDoubleList(String path) { public List<Double> getDoubleList(String path) {
List<?> list = getList(path); List<?> list = getList(path);
if (list == null) {
return new ArrayList<>(0);
}
List<Double> result = new ArrayList<>(); List<Double> result = new ArrayList<>();
for (Object object : list) { for (Object object : list) {
@ -623,8 +607,7 @@ public class MemorySection implements ConfigurationSection {
} else if (object instanceof String) { } else if (object instanceof String) {
try { try {
result.add(Double.valueOf((String) object)); result.add(Double.valueOf((String) object));
} catch (NumberFormatException ignored) { } catch (NumberFormatException ignored) {}
}
} else if (object instanceof Character) { } else if (object instanceof Character) {
result.add((double) (Character) object); result.add((double) (Character) object);
} else if (object instanceof Number) { } else if (object instanceof Number) {
@ -639,10 +622,6 @@ public class MemorySection implements ConfigurationSection {
public List<Float> getFloatList(String path) { public List<Float> getFloatList(String path) {
List<?> list = getList(path); List<?> list = getList(path);
if (list == null) {
return new ArrayList<>(0);
}
List<Float> result = new ArrayList<>(); List<Float> result = new ArrayList<>();
for (Object object : list) { for (Object object : list) {
@ -651,8 +630,7 @@ public class MemorySection implements ConfigurationSection {
} else if (object instanceof String) { } else if (object instanceof String) {
try { try {
result.add(Float.valueOf((String) object)); result.add(Float.valueOf((String) object));
} catch (NumberFormatException ignored) { } catch (NumberFormatException ignored) {}
}
} else if (object instanceof Character) { } else if (object instanceof Character) {
result.add((float) (Character) object); result.add((float) (Character) object);
} else if (object instanceof Number) { } else if (object instanceof Number) {
@ -667,10 +645,6 @@ public class MemorySection implements ConfigurationSection {
public List<Long> getLongList(String path) { public List<Long> getLongList(String path) {
List<?> list = getList(path); List<?> list = getList(path);
if (list == null) {
return new ArrayList<>(0);
}
List<Long> result = new ArrayList<>(); List<Long> result = new ArrayList<>();
for (Object object : list) { for (Object object : list) {
@ -679,8 +653,7 @@ public class MemorySection implements ConfigurationSection {
} else if (object instanceof String) { } else if (object instanceof String) {
try { try {
result.add(Long.valueOf((String) object)); result.add(Long.valueOf((String) object));
} catch (NumberFormatException ignored) { } catch (NumberFormatException ignored) {}
}
} else if (object instanceof Character) { } else if (object instanceof Character) {
result.add((long) (Character) object); result.add((long) (Character) object);
} else if (object instanceof Number) { } else if (object instanceof Number) {
@ -695,10 +668,6 @@ public class MemorySection implements ConfigurationSection {
public List<Byte> getByteList(String path) { public List<Byte> getByteList(String path) {
List<?> list = getList(path); List<?> list = getList(path);
if (list == null) {
return new ArrayList<>(0);
}
List<Byte> result = new ArrayList<>(); List<Byte> result = new ArrayList<>();
for (Object object : list) { for (Object object : list) {
@ -707,8 +676,7 @@ public class MemorySection implements ConfigurationSection {
} else if (object instanceof String) { } else if (object instanceof String) {
try { try {
result.add(Byte.valueOf((String) object)); result.add(Byte.valueOf((String) object));
} catch (NumberFormatException ignored) { } catch (NumberFormatException ignored) {}
}
} else if (object instanceof Character) { } else if (object instanceof Character) {
result.add((byte) ((Character) object).charValue()); result.add((byte) ((Character) object).charValue());
} else if (object instanceof Number) { } else if (object instanceof Number) {
@ -723,10 +691,6 @@ public class MemorySection implements ConfigurationSection {
public List<Character> getCharacterList(String path) { public List<Character> getCharacterList(String path) {
List<?> list = getList(path); List<?> list = getList(path);
if (list == null) {
return new ArrayList<>(0);
}
List<Character> result = new ArrayList<>(); List<Character> result = new ArrayList<>();
for (Object object : list) { for (Object object : list) {
@ -750,10 +714,6 @@ public class MemorySection implements ConfigurationSection {
public List<Short> getShortList(String path) { public List<Short> getShortList(String path) {
List<?> list = getList(path); List<?> list = getList(path);
if (list == null) {
return new ArrayList<>(0);
}
List<Short> result = new ArrayList<>(); List<Short> result = new ArrayList<>();
for (Object object : list) { for (Object object : list) {
@ -762,8 +722,7 @@ public class MemorySection implements ConfigurationSection {
} else if (object instanceof String) { } else if (object instanceof String) {
try { try {
result.add(Short.valueOf((String) object)); result.add(Short.valueOf((String) object));
} catch (NumberFormatException ignored) { } catch (NumberFormatException ignored) {}
}
} else if (object instanceof Character) { } else if (object instanceof Character) {
result.add((short) ((Character) object).charValue()); result.add((short) ((Character) object).charValue());
} else if (object instanceof Number) { } else if (object instanceof Number) {
@ -779,10 +738,6 @@ public class MemorySection implements ConfigurationSection {
List<?> list = getList(path); List<?> list = getList(path);
List<Map<?, ?>> result = new ArrayList<>(); List<Map<?, ?>> result = new ArrayList<>();
if (list == null) {
return result;
}
for (Object object : list) { for (Object object : list) {
if (object instanceof Map) { if (object instanceof Map) {
result.add((Map<?, ?>) object); result.add((Map<?, ?>) object);

View File

@ -25,9 +25,7 @@ public abstract class FileConfiguration extends MemoryConfiguration {
/** /**
* Creates an empty {@link FileConfiguration} with no default values. * Creates an empty {@link FileConfiguration} with no default values.
*/ */
public FileConfiguration() { FileConfiguration() {}
super();
}
/** /**
* Creates an empty {@link FileConfiguration} using the specified {@link * Creates an empty {@link FileConfiguration} using the specified {@link
@ -35,7 +33,7 @@ public abstract class FileConfiguration extends MemoryConfiguration {
* *
* @param defaults Default value provider * @param defaults Default value provider
*/ */
public FileConfiguration(final Configuration defaults) { public FileConfiguration(Configuration defaults) {
super(defaults); super(defaults);
} }
@ -54,42 +52,16 @@ public abstract class FileConfiguration extends MemoryConfiguration {
* any reason. * any reason.
* @throws IllegalArgumentException Thrown when file is null. * @throws IllegalArgumentException Thrown when file is null.
*/ */
public void save(final File file) throws IOException { public void save(File file) throws IOException {
if (file == null) {
throw new NullPointerException("File cannot be null");
}
file.getParentFile().mkdirs(); file.getParentFile().mkdirs();
final String data = saveToString(); String data = saveToString();
try (Writer writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)) { try (Writer writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)) {
writer.write(data); writer.write(data);
} }
} }
/**
* Saves this {@link FileConfiguration} to the specified location.
* <p>
* If the file does not exist, it will be created. If already exists, it
* will be overwritten. If it cannot be overwritten or created, an
* exception will be thrown.
* <p>
* This method will save using the system default encoding, or possibly
* using UTF8.
*
* @param file File to save to.
* @throws IOException Thrown when the given file cannot be written to for
* any reason.
* @throws IllegalArgumentException Thrown when file is null.
*/
public void save(final String file) throws IOException {
if (file == null) {
throw new NullPointerException("File cannot be null");
}
save(new File(file));
}
/** /**
* Saves this {@link FileConfiguration} to a string, and returns it. * Saves this {@link FileConfiguration} to a string, and returns it.
* *
@ -116,12 +88,12 @@ public abstract class FileConfiguration extends MemoryConfiguration {
* a valid Configuration. * a valid Configuration.
* @throws IllegalArgumentException Thrown when file is null. * @throws IllegalArgumentException Thrown when file is null.
*/ */
public void load(final File file) throws IOException, InvalidConfigurationException { public void load(File file) throws IOException, InvalidConfigurationException {
if (file == null) { if (file == null) {
throw new NullPointerException("File cannot be null"); throw new NullPointerException("File cannot be null");
} }
final FileInputStream stream = new FileInputStream(file); FileInputStream stream = new FileInputStream(file);
load(new InputStreamReader(stream, StandardCharsets.UTF_8)); load(new InputStreamReader(stream, StandardCharsets.UTF_8));
} }
@ -139,9 +111,9 @@ public abstract class FileConfiguration extends MemoryConfiguration {
* represent a valid Configuration * represent a valid Configuration
* @throws IllegalArgumentException thrown when reader is null * @throws IllegalArgumentException thrown when reader is null
*/ */
public void load(final Reader reader) throws IOException, InvalidConfigurationException { public void load(Reader reader) throws IOException, InvalidConfigurationException {
final StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
try (BufferedReader input = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader)) { try (BufferedReader input = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader)) {
String line; String line;
@ -173,7 +145,7 @@ public abstract class FileConfiguration extends MemoryConfiguration {
* a valid Configuration. * a valid Configuration.
* @throws IllegalArgumentException Thrown when file is null. * @throws IllegalArgumentException Thrown when file is null.
*/ */
public void load(final String file) throws IOException, InvalidConfigurationException { public void load(String file) throws IOException, InvalidConfigurationException {
if (file == null) { if (file == null) {
throw new NullPointerException("File cannot be null"); throw new NullPointerException("File cannot be null");
} }
@ -196,7 +168,7 @@ public abstract class FileConfiguration extends MemoryConfiguration {
* invalid. * invalid.
* @throws IllegalArgumentException Thrown if contents is null. * @throws IllegalArgumentException Thrown if contents is null.
*/ */
public abstract void loadFromString(final String contents) throws InvalidConfigurationException; public abstract void loadFromString(String contents) throws InvalidConfigurationException;
/** /**
* Compiles the header for this {@link FileConfiguration} and returns the * Compiles the header for this {@link FileConfiguration} and returns the
@ -212,10 +184,10 @@ public abstract class FileConfiguration extends MemoryConfiguration {
@Override @Override
public FileConfigurationOptions options() { public FileConfigurationOptions options() {
if (options == null) { if (this.options == null) {
options = new FileConfigurationOptions(this); this.options = new FileConfigurationOptions(this);
} }
return (FileConfigurationOptions) options; return (FileConfigurationOptions) this.options;
} }
} }

View File

@ -1,5 +1,6 @@
package com.intellectualcrafters.configuration.file; package com.intellectualcrafters.configuration.file;
import com.intellectualcrafters.configuration.Configuration;
import com.intellectualcrafters.configuration.MemoryConfiguration; import com.intellectualcrafters.configuration.MemoryConfiguration;
import com.intellectualcrafters.configuration.MemoryConfigurationOptions; import com.intellectualcrafters.configuration.MemoryConfigurationOptions;
@ -75,7 +76,7 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions {
* <p> * <p>
* If this is true, if a default {@link FileConfiguration} is passed to * If this is true, if a default {@link FileConfiguration} is passed to
* {@link * {@link
* FileConfiguration#setDefaults(com.intellectualcrafters.configuration.Configuration)} * FileConfiguration#setDefaults(Configuration)}
* then upon saving it will use the header from that config, instead of * then upon saving it will use the header from that config, instead of
* the one provided here. * the one provided here.
* <p> * <p>
@ -97,7 +98,7 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions {
* <p> * <p>
* If this is true, if a default {@link FileConfiguration} is passed to * If this is true, if a default {@link FileConfiguration} is passed to
* {@link * {@link
* FileConfiguration#setDefaults(com.intellectualcrafters.configuration.Configuration)} * FileConfiguration#setDefaults(Configuration)}
* then upon saving it will use the header from that config, instead of * then upon saving it will use the header from that config, instead of
* the one provided here. * the one provided here.
* <p> * <p>

View File

@ -21,8 +21,8 @@ import java.util.Map;
* Note that this implementation is not synchronized. * Note that this implementation is not synchronized.
*/ */
public class YamlConfiguration extends FileConfiguration { public class YamlConfiguration extends FileConfiguration {
protected static final String COMMENT_PREFIX = "# "; private static final String COMMENT_PREFIX = "# ";
protected static final String BLANK_CONFIG = "{}\n"; private static final String BLANK_CONFIG = "{}\n";
private final DumperOptions yamlOptions = new DumperOptions(); private final DumperOptions yamlOptions = new DumperOptions();
private final Representer yamlRepresenter = new YamlRepresenter(); private final Representer yamlRepresenter = new YamlRepresenter();
private final Yaml yaml = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions); private final Yaml yaml = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions);
@ -40,7 +40,7 @@ public class YamlConfiguration extends FileConfiguration {
* @return Resulting configuration * @return Resulting configuration
* @throws IllegalArgumentException Thrown if file is null * @throws IllegalArgumentException Thrown if file is null
*/ */
public static YamlConfiguration loadConfiguration(final File file) { public static YamlConfiguration loadConfiguration(File file) {
if (file == null) { if (file == null) {
throw new NullPointerException("File cannot be null"); throw new NullPointerException("File cannot be null");
} }
@ -51,7 +51,6 @@ public class YamlConfiguration extends FileConfiguration {
config.load(file); config.load(file);
} catch (InvalidConfigurationException | IOException ex) { } catch (InvalidConfigurationException | IOException ex) {
try { try {
file.getAbsolutePath();
File dest = new File(file.getAbsolutePath() + "_broken"); File dest = new File(file.getAbsolutePath() + "_broken");
int i = 0; int i = 0;
while (dest.exists()) { while (dest.exists()) {
@ -126,7 +125,7 @@ public class YamlConfiguration extends FileConfiguration {
input = (Map<?, ?>) yaml.load(contents); input = (Map<?, ?>) yaml.load(contents);
} catch (final YAMLException e) { } catch (final YAMLException e) {
throw new InvalidConfigurationException(e); throw new InvalidConfigurationException(e);
} catch (final ClassCastException e) { } catch (final ClassCastException ignored) {
throw new InvalidConfigurationException("Top level is not a Map."); throw new InvalidConfigurationException("Top level is not a Map.");
} }
@ -164,7 +163,7 @@ public class YamlConfiguration extends FileConfiguration {
if (line.startsWith(COMMENT_PREFIX)) { if (line.startsWith(COMMENT_PREFIX)) {
if (i > 0) { if (i > 0) {
result.append("\n"); result.append('\n');
} }
if (line.length() > COMMENT_PREFIX.length()) { if (line.length() > COMMENT_PREFIX.length()) {
@ -173,7 +172,7 @@ public class YamlConfiguration extends FileConfiguration {
foundHeader = true; foundHeader = true;
} else if (foundHeader && line.isEmpty()) { } else if (foundHeader && line.isEmpty()) {
result.append("\n"); result.append('\n');
} else if (foundHeader) { } else if (foundHeader) {
readingHeader = false; readingHeader = false;
} }
@ -189,9 +188,9 @@ public class YamlConfiguration extends FileConfiguration {
if (options().copyHeader()) { if (options().copyHeader()) {
final Configuration def = getDefaults(); final Configuration def = getDefaults();
if (def != null && def instanceof FileConfiguration) { if (def instanceof FileConfiguration) {
final FileConfiguration filedefaults = (FileConfiguration) def; final FileConfiguration fileDefaults = (FileConfiguration) def;
final String defaultsHeader = filedefaults.buildHeader(); final String defaultsHeader = fileDefaults.buildHeader();
if ((defaultsHeader != null) && !defaultsHeader.isEmpty()) { if ((defaultsHeader != null) && !defaultsHeader.isEmpty()) {
return defaultsHeader; return defaultsHeader;
@ -208,7 +207,7 @@ public class YamlConfiguration extends FileConfiguration {
boolean startedHeader = false; boolean startedHeader = false;
for (int i = lines.length - 1; i >= 0; i--) { for (int i = lines.length - 1; i >= 0; i--) {
builder.insert(0, "\n"); builder.insert(0, '\n');
if (startedHeader || !lines[i].isEmpty()) { if (startedHeader || !lines[i].isEmpty()) {
builder.insert(0, lines[i]); builder.insert(0, lines[i]);

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