Compare commits

...

234 Commits

Author SHA1 Message Date
eabb5f3180 Fix remaining compile errors
Note: Sponge version needs a number of things implemented before it will
actually run
2016-02-20 06:55:49 +11:00
92b3ddb0ac Finish debugpaste for sponge 2016-02-20 06:13:41 +11:00
6caa7ee757 Merge remote-tracking branch 'origin/master' 2016-02-20 06:05:47 +11:00
de1328e78c Update some sponge classes
Update world generator
Replace some broken code with TODO
FIxed a few errors
Started on block placement
Other sponge stuff
2016-02-20 05:52:26 +11:00
60629db042 Feature / Fix
Add trim regen argument @manuelgu /plot trim <world> true
Add grant check other + console usage
Finish abstracting world generation to prepare for sponge port
Fix economy hook
Add ban as alias for deny
Remove some redundant code
2016-02-20 05:42:06 +11:00
a055a90979 Add target folder 2016-02-20 05:16:20 +11:00
302fe0c2c8 Fix SpongeEventUtil 2016-02-19 12:50:38 -05:00
660cd1b870 Fix more Sponge Classes 2016-02-19 12:45:43 -05:00
63cd7c8b97 Fix SpongeEconHandler 2016-02-19 12:18:15 -05:00
c719d548d0 Fix SpongePlayer 2016-02-19 12:07:09 -05:00
536b011ea0 Fix SpongePlayer 2016-02-19 12:01:24 -05:00
2a2c85a642 Fix Typos and Various little things. 2016-02-19 11:55:00 -05:00
c592790f68 Merge pull request #881 from manuelgu/patch-3
Update Issue Template
2016-02-18 16:35:13 -05:00
81f57b5675 Update Issue Template
More proper description
2016-02-18 22:19:50 +01:00
3fadbf3358 Lol okay this is better 2016-02-18 22:05:09 +01:00
26e73af35c Rename CONTRIBUTING.md to .github/CONTRIBUTING.md 2016-02-18 21:59:55 +01:00
4a9d063576 Create ISSUE_TEMPLATE.md 2016-02-18 21:58:48 +01:00
411a74eefa Fix compatibility with old type 2 plotworld cluster data 2016-02-17 23:38:36 +11:00
11064ec814 Fixes #878 2016-02-17 14:49:10 +11:00
af9f5b5f44 Fixes
Fix #879 stackoverflow in PlotHandler (from
fde845e1d8)
Fix getCorners returning last value twice
Fix getConnectedPlots only returning adjacent connections (from
c83378a91b)
other tweaks
2016-02-17 14:46:25 +11:00
3b58e19b25 Merge pull request #869 from manuelgu/patch-2
Fix mismatch of brackets
2016-02-15 20:11:51 +11:00
eda4575dd6 Tweaks / Fixes
Fixed id being renamed to type in
fde845e1d8
Fixes #870
2016-02-15 16:25:37 +11:00
87d4ecb1f1 Fix TextualCompontent Class that broke in last commit 2016-02-13 20:05:30 -05:00
fde845e1d8 Refractoring and Cleanup
Optimized some of the code where possible and removed some magic numbers as well.
2016-02-13 20:01:18 -05:00
0a4e42e1a7 Fix mismatch of brackets
This could potentially cause problems because the permission check is not correct
2016-02-13 18:45:35 +01:00
a1eec4eb0c Fixes #853 2016-02-13 22:19:07 +11:00
e2ba9fb8e9 Fixes / Additions / Tweaks
Fixed #867
Fixes some issues with partial plot areas
Added /plot area regen
2016-02-13 22:01:22 +11:00
03aec43f5d Merge remote-tracking branch 'origin/master'
# Conflicts:
#	src/main/java/com/intellectualcrafters/plot/commands/Condense.java
#	src/main/java/com/intellectualcrafters/plot/commands/Deny.java
#	src/main/java/com/intellectualcrafters/plot/commands/Save.java
#	src/main/java/com/intellectualcrafters/plot/commands/list.java
#	src/main/java/com/intellectualcrafters/plot/database/SQLManager.java
2016-02-13 04:32:43 +11:00
b87a886345 Additions / Fixes
Added `/plot area` command for area info and management
Fixed typo for player meta table preventing the plugin from starting /
cleanup
Moved pagination from list to subcommand
Removed default PlotArea values
Added pair and tuple RunnableVal classes
Tweak pom so that it actually compiles
More command categories
Removed unclaim and limit command
Fixed a few issues with the 2d mapping of plot areas
2016-02-13 03:25:04 +11:00
ccbd4f60c2 Refractoring and Cleanup 2016-02-10 20:37:21 -05:00
ca73addc88 Updated this via browser, sorry if something broke xD 2016-02-10 22:23:49 +01:00
893c2b3088 Remove bukkit classes from core 2016-02-11 06:43:47 +11:00
50f891a974 this 2016-02-11 06:02:54 +11:00
c83378a91b Refactor / Cleanup / Optimizations 2016-02-11 05:59:51 +11:00
085f621f0f Merge pull request #856 from MattBDev/spelling
Spelling Corrections
2016-02-07 16:37:40 +01:00
8d6b412dc8 Spelling Corrections 2016-02-04 18:45:50 -05:00
692ad5db81 Update README.md 2016-01-24 10:50:53 +01:00
a69f7162f1 Merge pull request #839 from manuelgu/patch-1
Update README.md
2016-01-23 23:19:54 +01:00
ee6d9d2d5c Merge pull request #840 from aaomidi/master
Make plugin compatible with DeluxeChat
2016-01-23 23:13:48 +01:00
7cc8e8bfb5 Merge pull request #1 from aaomidi/aaomidi-patch-1
Update PlayerEvents.java
2016-01-24 00:33:50 +03:30
5f74aa8ab8 Update PlayerEvents.java
Allow other plugins to manage chat.

Makes plugin work with DeluxeChat plugin.
2016-01-24 00:32:43 +03:30
df27b1ddd8 Update README.md 2016-01-23 20:18:48 +01:00
d8998ac715 Yeah, no. This needs fixing. 2016-01-23 19:21:17 +01:00
948b5c5789 Merge pull request #837 from manuelgu/patch-2
Push target folder as it is needed for /p update
2016-01-21 12:07:47 +01:00
8a34276eb5 Push target folder as it is needed for /p update 2016-01-21 11:23:48 +01:00
e8d2e9fd12 Merge pull request #830 from sgdc3/master
Clean the project [WIP]
2016-01-20 20:11:27 +01:00
e3b5ca14be Disable spongeapi dependency 2016-01-20 13:34:33 +01:00
a872bd0f61 Shade libs 2016-01-20 13:30:03 +01:00
efeecd423e Merge pull request #1 from IntellectualSites/master
Up
2016-01-20 12:44:33 +01:00
51d2e37853 Clean the project 2016-01-20 12:40:04 +01:00
ddfa4fe6af Merge pull request #831 from manuelgu/patch-1
Fix notify-enter message being sent to wrong person
2016-01-19 15:53:32 +01:00
165d9b6258 Fix #829 2016-01-19 14:12:42 +01:00
0f3d6b63f5 I was tired, okay. 2016-01-18 23:07:10 +01:00
adfd0e6674 Should fix #824 2016-01-17 13:19:14 +01:00
faa9c10364 Add fixes to shizzle 2016-01-16 18:32:00 +01:00
830a5111f4 Add plot grants for /plot auto 2016-01-16 17:48:49 +01:00
cf6ca67ce7 Add persistent meta, and added plot grants 2016-01-16 17:07:42 +01:00
dc22514809 Implements #752 and gives credits to manuelgu :) 2016-01-16 13:14:18 +01:00
c6f087fd50 Fixes #774 and allows for similar features in the future 2016-01-16 13:03:51 +01:00
ad1272b0e5 Minor fixes
Fixes #797
Fixes #794
2016-01-12 23:13:47 +11:00
af79100f7d Update README / pom / merge with 8629c4a6f5
closes #809
2016-01-11 07:00:56 +11:00
00b6158181 Use plot metadata to track tasks 2015-12-20 06:40:42 +11:00
f70e2248e7 Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared 2015-12-20 06:30:16 +11:00
cf517d5be0 Cleanup 2015-12-20 06:30:06 +11:00
9b990faa47 Merge pull request #792 from manuelgu/master
fix typo
2015-12-20 06:15:46 +11:00
2aab349c4b Merge pull request #796 from MattBDev/spongeFix
Fix Sponge Generator
2015-12-20 06:15:33 +11:00
dc799ecc26 Merge pull request #795 from MattBDev/cleanup
Fixes javadoc errors
2015-12-20 06:15:28 +11:00
d65bd7a704 Fixes javadoc errors
It does not improve upon the existing documentation but instead removes all broken documentation and has minor changes to some existing. More work will need to be done later to documentation.
2015-12-19 12:23:32 -05:00
8ddecce75b Fix Sponge Generator 2015-12-19 12:05:00 -05:00
5e33c175ab Typo in "ice-melt" flag
The flag doesnt seem to be used anyways, so not much of a deal.
2015-12-17 18:11:50 +01:00
abc2681f97 fix typo 2015-12-17 18:07:57 +01:00
ce387333d2 Plot deny / kick bypass
Fixes #777
2015-12-17 17:51:12 +11:00
c32cfc62fa Various
Fix sethome/home for mega plots
Minor tweaks
2015-12-16 16:38:53 +11:00
dd4a1faede Fixes #772 2015-12-15 03:32:59 +11:00
163ccc9eae Fixes
Fixes #783
Fixes #780
2015-12-15 03:15:30 +11:00
35589dcc5f Fixe
Fixes #753
2015-12-04 20:00:30 +11:00
c72edc40f0 Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared 2015-12-03 02:43:05 +11:00
f102b2b448 Fixes
Fixes #768 (Plot clearing with given plot id)
2015-12-03 02:42:50 +11:00
2cdb279528 Merge pull request #769 from XxCoolGamesxX/patch-1
Added Spanish Translation
2015-12-03 02:42:21 +11:00
08e3876b01 Added Spanish Translation
We translation in Spanish so the people can read it.

Thank to my team of Mega Planet (www.megaplanet.net).
2015-12-02 00:09:22 +01:00
1b7a58b720 Merge pull request #766 from swan201/master
Update Korean Translation File
2015-11-30 13:55:33 +11:00
b71b0aa46e Update Korean Translation 2015-11-30 05:59:14 +09:00
dcefa95278 Merge pull request #1 from IntellectualSites/master
Merge
2015-11-30 05:56:40 +09:00
60406812ee Merge pull request #764 from manuelgu/patch-3
remove website link
2015-11-29 21:42:20 +01:00
82ccca8f63 . 2015-11-30 02:24:01 +11:00
1fcb4ea705 remove website link 2015-11-29 12:49:20 +01:00
9118f111e4 Fixes
fixes #763
2015-11-29 19:21:32 +11:00
c2b781da98 Deny negative ratings 2015-11-28 23:27:36 +11:00
1ee13ff96c Fix commands being case sensitive. 2015-11-28 22:56:12 +11:00
d1ac355e58 Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared
# Conflicts:
#	src/main/java/com/intellectualcrafters/plot/config/C.java
2015-11-28 22:49:42 +11:00
94b0fbb266 Stuff
Fixes #748
Fixes #759
2015-11-28 22:46:10 +11:00
ef327434cd Merge pull request #751 from Aaron1011/update-spongeapi
git@github.com:Aaron1011/PlotSquared.gitUpdate for SpongeAPI changes
2015-11-26 14:45:39 +11:00
e0e2756b95 Update for SpongeAPI changes 2015-11-25 22:40:22 -05:00
7d494fef16 Merge pull request #749 from manuelgu/patch-1
fixed importing
2015-11-25 23:12:00 +01:00
7bbf549221 fixed importing
related to #733
2015-11-25 23:05:08 +01:00
a0c93bb3e7 Merge pull request #747 from manuelgu/patch-2
formatting in german file
2015-11-25 22:51:18 +01:00
46989faee6 Merge pull request #746 from manuelgu/patch-1
formatting
2015-11-25 22:51:06 +01:00
f80a833689 formatting in german file 2015-11-25 22:30:35 +01:00
eba75363c8 formatting 2015-11-25 22:29:20 +01:00
cc10c52230 Update README.md 2015-11-25 22:04:16 +01:00
8a1dfe46c9 Merge pull request #733 from manuelgu/patch-1
fix color formatting
2015-11-22 22:01:28 +01:00
d56b4da7c2 fix color formatting 2015-11-22 12:04:24 +01:00
7db30590c6 Fixes
Fixes #701
Fixes set components for other plots
Add setowner uuid.
Probably some other stuff
2015-11-20 17:28:33 +11:00
7ed693dfc8 Fix populator random seed / algorithm differing from chunk generator 2015-11-18 16:42:19 +11:00
1e1259b81d Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared 2015-11-18 10:39:52 +11:00
452efc4b08 Fix
Fixes #724
Fixes flag remove for non list based flags when player lacks permission.
2015-11-18 10:39:44 +11:00
9adb256ff6 Merge pull request #719 from manuelgu/patch-2
remove not needed message
2015-11-16 12:31:36 +11:00
c34f41b150 remove not needed message
Since calculating the TPS Values has been removed, the message is no longer in use
2015-11-15 18:58:12 +01:00
a8140f8cb0 Check if no metadata is set. 2015-11-15 20:52:32 +11:00
27d1ba810b Default, default flags 2015-11-15 19:56:32 +11:00
9218147aa0 Whoops. 2015-11-15 13:51:28 +11:00
ab5e826fe8 Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared 2015-11-15 13:31:01 +11:00
93a7b2cace Potential fixes
Fixes #712
Fixes #711
Fixes #707
Fixes #705
Fixes #702
Fixes #698
Fixes #697
Fixes #694
Fixes #717
2015-11-15 13:30:52 +11:00
8a9f4d2598 Merge pull request #706 from swan201/master
Add Korean Translate File
2015-11-07 12:48:40 +11:00
ebf0fee3ac Add Korean Translate File
First Korean Translate
2015-11-07 10:44:31 +09:00
c32edfe0ee . 2015-11-04 04:52:44 +11:00
008e35d307 Fixes #700 2015-11-04 02:39:42 +11:00
215ed04754 Minor tweaks 2015-10-29 23:13:10 +11:00
95feaed870 Changes
ratings api
misc-cap
other tweakes
2015-10-27 10:57:34 +11:00
2e79f3d0f8 Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared 2015-10-26 18:21:35 +11:00
2afc16de7a Schematics / tweak message 2015-10-26 18:18:31 +11:00
bc836201d5 Merge pull request #687 from manuelgu/patch-1
Update german.yml
2015-10-26 18:05:49 +11:00
24406a250b Update german.yml
tweaked some german translations and also added untranslated things
2015-10-24 22:52:50 +02:00
e20e4a8650 Fixes
Closes #683
Potential fix for sign issue
Potential fix for templates not working
Incremented version number.
2015-10-24 21:55:34 +11:00
6650ea2a4c Fixes #681 2015-10-21 18:31:14 +11:00
a6dad4fb7b Fixes #682 2015-10-21 16:34:15 +11:00
fa442f5903 Fixes
closes #679
closes #676
2015-10-19 17:27:51 +11:00
f509252646 Fix plot cluster command from console. 2015-10-18 23:31:35 +11:00
f75822f56c Fixed no argument feedback for move/copy/swap 2015-10-18 23:18:45 +11:00
26c0e3fa85 Fixes
- Fix sign lines on claim not updating
- Fix plot tier removing for merged plots
- Fix stair rotation for id=24
- Fix interaction to have a lower priority than chestshop (why doesn't
chestshop use monitor priority?)
2015-10-18 22:20:12 +11:00
c595b69c3a fixed world loading. 2015-10-18 01:25:17 +11:00
54655c1a72 Fixes
closes #673
closes #668
closes #672
closes #664 (hopefully)
2015-10-17 22:50:52 +11:00
50c6753bf4 Fixes
close #659
close #662
close #665
close #638
2015-10-10 18:07:26 +11:00
8e874ddeb0 Fix PlotMe conversion 2015-10-07 18:42:50 +11:00
0c4b703510 Fix for sponge 2015-10-07 17:33:33 +11:00
74a967b535 Fixes container contents spillage on plot clear
TODO: fix component setting for ^
2015-10-05 01:40:46 +11:00
f2431c869f fixes
Fixes #657
Fixes #656
Fixes #653
Fixes #652
Fixes #585
2015-10-05 00:59:43 +11:00
9d77b422df Fixes #651 #618 2015-09-30 16:11:44 +10:00
3bd4895676 Fix structure growth on roads (from big trees on plot edges)
Possible unresolved issue (TODO)
- big tree growth on plot edges with 0 road width
2015-09-29 19:50:05 +10:00
b9bb9f5674 Fixes #646 2015-09-29 16:29:28 +10:00
c3eb44f51c un-cache base plot on merge 2015-09-27 19:42:22 +10:00
0273a4614b Load plots with no settings. 2015-09-27 18:37:33 +10:00
bb32507841 Fix plot unclaiming for non hybrid classic generators. 2015-09-27 17:20:59 +10:00
3336d302ac Potential fixes 2015-09-27 16:43:11 +10:00
a93e8fac38 Some fixes
Fixes #641
Closes #640 (need to also update Plot2Dynmap)
Fixes #637 (duplicate)
Fixes #636
Fixes #634
2015-09-26 18:05:27 +10:00
d42ef3cf63 restructure a couple things. 2015-09-22 23:23:28 +10:00
c948b18239 Forward plot home to plot visit 2015-09-15 14:56:23 +10:00
9682e2914c Recover from world gen error. 2015-09-15 00:35:28 +10:00
b524d5fcfe minor conversion tweaks + fix plot sorting with empty worlds. 2015-09-15 00:24:25 +10:00
4002ed4de1 Fixes #613 2015-09-14 20:43:51 +10:00
064a555ba1 Fix cluster create with non ascending coords 2015-09-14 18:39:07 +10:00
91bfcd0deb Fixes #620 2015-09-14 18:20:25 +10:00
5137b23357 Hows this? 2015-09-13 14:04:31 +10:00
1cccdd9d4d Merge branch 'master' of https://github.com/IntellectualSites/PlotSquared
Conflicts:
	src/main/java/com/intellectualcrafters/plot/IPlotMain.java
	src/main/java/com/intellectualcrafters/plot/commands/Trim.java
	src/main/java/com/intellectualcrafters/plot/util/ChunkManager.java
	src/main/java/com/plotsquared/bukkit/BukkitMain.java
	src/main/java/com/plotsquared/bukkit/util/BukkitChunkManager.java
	src/main/java/com/plotsquared/sponge/SpongeMain.java
	src/main/java/com/plotsquared/sponge/util/SpongeChunkManager.java
2015-09-13 13:46:45 +10:00
c163446f7e Fix plot clear event not being called. 2015-09-13 13:33:18 +10:00
052019bb35 default to offline-mode uuid if owner isn't valid. 2015-09-13 13:30:28 +10:00
a6535d3b7b Forward plot set flag to the flag command. 2015-09-13 01:26:35 +10:00
1c28a72f9c WE unregistration + home/visit sorting + format
- WorldEdit listener unregistration for external masking/extent/async
worldedit management. (wink)
- Use the same listing for home and visit as previous behavior was
confusing.
2015-09-13 01:19:39 +10:00
c386f33df8 cleanup 2015-09-11 20:09:22 +10:00
063a369d8d Merge pull request #615 from MinelinkNetwork/fix-trimming
Fix trimming for worlds in non-standard directories
2015-09-11 08:52:30 +10:00
629ff443f3 Fix trimming for worlds in non-standard directories 2015-09-09 22:34:41 -07:00
37a8861fa0 Temporary fix for sponge toggles. 2015-09-07 22:31:48 +10:00
66730794d6 Fixes for sponge + minor tweaks for spigot
- Updated to sponge 591
- Added optional WorldEdit restriction
- several fixes (including greeting/farewell flag)
2015-09-07 22:17:48 +10:00
2b3b947143 Fix plot entry/leave for sponge. 2015-09-06 11:53:56 +10:00
ea146dcf91 Fix plot chat, chatspy + add comment spying 2015-09-06 10:33:11 +10:00
e704784570 Try this version, otherwise maybe downgrade? 2015-09-05 20:45:31 +10:00
1e386d274e add jars 2015-09-05 20:21:29 +10:00
a71d5a134b Fix rating when no categories are configured 2015-09-05 20:17:39 +10:00
e3cb59f362 Lazy UUID conversion 2015-09-05 20:07:59 +10:00
8606319340 Fix world caching + block interaction
Fixes #608
2015-09-05 11:35:43 +10:00
4cc4196487 jars 2015-09-03 23:37:19 +10:00
c707a7baa2 Remove spectator from flag pack 2015-09-03 23:34:52 +10:00
4e321d2b27 Here you go. 2015-09-03 22:40:36 +10:00
dfc32741fa Export negative coord blocks with BO3 if not part of normal plot component 2015-09-03 15:57:12 +10:00
574ca7a180 Call plot leave on quit 2015-09-03 15:48:36 +10:00
afef79ea66 Some changes
Fixes #605
Possibly #604
Other minor tweaks
2015-09-03 15:45:25 +10:00
3a29022d19 Add command queue option + fix nearest target 2015-09-01 21:33:45 +10:00
fcb7c23380 Latest jars 2015-09-01 15:46:56 +10:00
ea6d5778c8 Added chat spy toggle 2015-09-01 15:09:46 +10:00
6006b0e011 Add world parameter to EconHandler permission checks
Fixes #595
2015-09-01 14:02:37 +10:00
f22874970f Fix side location + fix brushtool mask 2015-09-01 10:23:46 +10:00
6671fd7e6d Fixes #582 2015-09-01 09:55:14 +10:00
29da0da8bb Fixes #577 2015-09-01 08:51:51 +10:00
9accbd5ea7 Decrease intensity of fastmode clearing 2015-09-01 07:31:53 +10:00
80b2c6b792 Merge pull request #589 from Maescool/master
Fixing plotme converter for some installations
2015-08-31 07:05:25 +10:00
a63110f303 Fixing plotme converter for some installations
-Making sure the uuid is checked when it's ownerId
-Checking if there are uuid's for denied/allowed, then use them if those are not in the cache
2015-08-30 16:23:05 +02:00
4027e84a0a Fixed boat interaction 2015-08-30 16:24:53 +10:00
0ba838b16b Minor tweaks
- SBQ unsanitized input
- plotme conversion tweaks
- schematic default output directory
- increment version number
2015-08-30 16:19:35 +10:00
3662b05da8 Fixes #584 2015-08-29 18:47:56 +10:00
fb0b50218d Ignore invalid tool 2015-08-29 12:25:13 +10:00
75fbf67dca Fix async worldedit masks 2015-08-29 06:56:02 +10:00
0dbb1887d5 Prevent teleporting to invalid coordinates 2015-08-28 16:36:26 +10:00
1e8bdb17f8 Per player plot cluster limits 2015-08-28 16:28:55 +10:00
22997ac089 Some work on plot clusters 2015-08-28 12:37:01 +10:00
ad94637c2a Fix inbox deletion perm 2015-08-28 09:53:35 +10:00
552ace359a Feedback for failed uploads + fix plot list done 2015-08-28 09:51:59 +10:00
ac27a7f37a Fix automerge.js 2015-08-28 09:51:05 +10:00
fcf2400798 Fix lighting updates for chunks not sent to players 2015-08-28 09:50:57 +10:00
5acd9c5143 Download requires done 2015-08-28 09:50:44 +10:00
56d50bd9e1 Fix masking extent + process non plot worlds 2015-08-28 08:33:32 +10:00
5b44e39bec documentation + fix toggles for admins 2015-08-26 16:44:50 +10:00
3229705012 Offline uuid from flat file. 2015-08-26 14:21:48 +10:00
1872e147cb WE delayed command execution + fix SBQ notify 2015-08-26 12:02:00 +10:00
dc37465c8a Forgot to push this 2015-08-26 08:35:32 +10:00
b2f8238f5d fix undo 2015-08-25 12:23:10 +10:00
2b187f2066 3.1.6 2015-08-25 10:51:33 +10:00
ee17457403 v3.1.5 2015-08-25 09:13:13 +10:00
6ca6880917 New features + fixes
Fixed a very specific case of IC world not loading with multiverse every
second startup
Fixed chunks not being sent for plot clearing (although it was being
sent for other thing) Fixes #554
Added fast experimental sudo-async worldedit processor
2015-08-25 09:01:45 +10:00
0e8ae9e6e4 WE tweak / Fix teleport event 2015-08-25 05:56:22 +10:00
3164838e05 Experimental allow plot clearing on mega plots 2015-08-25 03:07:09 +10:00
c7f5e3061d Retain trusted / helpers / denied when merging
fixes #533
2015-08-25 02:52:02 +10:00
8c245b4f21 Optional bo3 tags 2015-08-25 02:33:28 +10:00
68df5b1930 Fixed interactive chat colors + added interactive pages to sponge. 2015-08-25 02:28:32 +10:00
83d0b8cebb Revert some plot chat changes.
- Having chat for that plotworld will force it on all players without
the bypass permission
- Not having it will require the player to opt into plot chat
2015-08-25 00:35:37 +10:00
3bc3b51a27 Fix plot automerging 2015-08-25 00:19:50 +10:00
f2d56ec231 Plot merge limits 2015-08-25 00:00:29 +10:00
66f73374ac Tweak block interaction flags 2015-08-24 04:31:33 +10:00
d427ba3152 Fix auto-trim 2015-08-24 04:09:57 +10:00
79b16b8040 ChunkProcessor auto trim and chunk unloading
- The auto trim drastically reduces the cost of players exploring on
speed 10, as it prevents chunks of unowned plots from saving to disk
when the chunk is unloaded
- It is recommended to disable world auto saving, or also enable the
chunk processor GC, as otherwise minecraft will also save chunks as they
are loaded.
2015-08-24 03:29:59 +10:00
e228c00d87 Increment version 2015-08-24 00:18:31 +10:00
bd86caa818 Fixed fallback plotme conversion 2015-08-24 00:17:17 +10:00
d52e9b4c8c Minor fixes 2015-08-23 22:04:52 +10:00
dbdd207390 Merge pull request #576 from confuser/master
Fixed bukkit plot chat
2015-08-23 22:01:35 +10:00
316a4e0484 Fixed plot chat using meta instead of attributes
Pass message into setFormat and setMessage correctly
this avoids % symbols in player messages causing exceptions

Fixed #571
2015-08-23 12:00:52 +01:00
b5fbc6629f Fixed compiliation issue 2015-08-23 11:36:41 +01:00
a1be218580 Merge pull request #568 from LaxWasHere/patch-1
cannot into spelling
2015-08-22 17:47:08 +10:00
Lax
373044c928 cannot into spelling 2015-08-21 21:12:16 -07:00
83b1be8944 revert this 2015-08-21 19:24:20 +10:00
2185384746 . 2015-08-21 14:53:53 +10:00
b063494955 Redstone, chunk sending, reload fix, chunk unloader,
- Added redstone disabler when no players are in the plot
- Fixed chunk sending leaving ghost blocks
- Fixed reloading not populating new values
- Added chunk unloader to chunk processor (decreases memory usage)
2015-08-21 04:54:42 +10:00
ae7eed8a5b . 2015-08-20 21:54:04 +10:00
5f8505e698 Fix permission checking 2015-08-20 21:51:26 +10:00
75f189aae8 Fix auto updating. 2015-08-20 20:48:48 +10:00
d0605b9b55 Fixes
Fixes #556
Fixes #540
Fixed plot analysis being slow
Fixed auto updating
2015-08-20 14:56:25 +10:00
423 changed files with 42553 additions and 37387 deletions

2
.github/CONTRIBUTING.md vendored Normal file
View File

@ -0,0 +1,2 @@
### Bugs
Please provide a `/plot debugpaste` if you are reporting a bug.

12
.github/ISSUE_TEMPLATE.md vendored Normal file
View File

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

68
.gitignore vendored
View File

@ -1,9 +1,14 @@
### Ignore script files
*.sh
### Others ###
*.bat
*.cmd
*.sh
*.prefs
### Maven template
target/
### Maven ###
/target/lib
/target/maven-archiver
/target/classes
/target/maven-status
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
@ -14,8 +19,23 @@ buildNumber.properties
.mvn/timing.properties
### JetBrains template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion
### Java ###
*.class
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.ear
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
### Intellij ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
*.iml
@ -27,6 +47,7 @@ buildNumber.properties
# .idea/workspace.xml
# .idea/tasks.xml
# .idea/dictionaries
# .idea/shelf
# Sensitive or high-churn files:
# .idea/dataSources.ids
@ -61,23 +82,12 @@ atlassian-ide-plugin.xml
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
### NetBeans template
nbproject/private/
build/
nbbuild/
dist/
nbdist/
nbactions.xml
nb-configuration.xml
.nb-gradle/
### Eclipse template
### Eclipse ###
*.pydevproject
.metadata
.gradle
bin/
tmp/
*.tmp
@ -115,20 +125,6 @@ local.properties
# TeXlipse plugin
.texlipse
### Java template
*.class
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.ear
*.zip
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
# STS (Spring Tool Suite)
.springBeans
/target/

View File

@ -17,23 +17,23 @@ is to provide a lag-free and smooth experience.
### Developer Resources
* *Outdated* [JavaDocs](http://empcraft.com/plotsquared/doc/)
* [Build Server](http://ci.intellectualsites.com/job/PlotSquared/)
* [Maven Repo](http://mvn.intellectualsites.com/content/repositories/intellectualsites/)
* [Build Server](http://ci.xephi.fr/job/PlotSquared/)
* [Maven Repo](http://ci.xephi.fr/plugin/repository/everything/)
# Maven
We're now on maven!
We're now on maven! (Unofficial Maven Repo)
```xml
<!-- Repository -->
<repository>
<id>intellectualsites</id>
<url>http://mvn.intellectualsites.com/content/repositories/intellectualsites/</url>
<id>xephi-repo</id>
<url>http://ci.xephi.fr/plugin/repository/everything/</url>
</repository>
<!-- Dependency -->
<dependency>
<groupId>com.intellectualcrafters</groupId>
<artifactId>PlotSquared</artifactId>
<version>2.12.9</version>
<artifactId>plotsquared</artifactId>
<version>3.2.27-SNAPSHOT</version>
</dependency>
```

263
pom.xml
View File

@ -1,44 +1,87 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.intellectualcrafters</groupId>
<artifactId>plotsquared</artifactId>
<version>3.2.27</version>
<packaging>jar</packaging>
<name>PlotSquared</name>
<description>Reinventing the plotworld!</description>
<url>http://www.spigotmc.org/resources/plotsquared.1177/</url>
<organization>
<name>IntellectualSites</name>
<url>https://github.com/IntellectualSites</url>
</organization>
<scm>
<connection>scm:git:https://github.com/IntellectualSites/PlotSquared.git</connection>
<developerConnection>scm:git:git@github.com:IntellectualSites/PlotSquared.git</developerConnection>
<url>https://github.com/IntellectualSites/PlotSquared</url>
</scm>
<!-- Not Official -->
<ciManagement>
<system>jenkins</system>
<url>http://ci.xephi.fr/job/PlotSquared/</url>
</ciManagement>
<licenses>
<license>
<name>The GNU General Public Licence version 3 (GPLv3)</name>
<url>http://www.gnu.org/licenses/gpl-3.0.html</url>
</license>
</licenses>
<prerequisites>
<maven>3.3.3</maven>
</prerequisites>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Change Compiler Version (JDK) HERE! -->
<javaVersion>1.7</javaVersion>
<!-- Change Bukkit Version HERE! -->
<bukkitVersion>1.8.8-R0.1-SNAPSHOT</bukkitVersion>
<spongeVersion>3.1.0-SNAPSHOT</spongeVersion>
</properties>
<artifactId>PlotSquared</artifactId>
<version>3.1.0</version>
<name>PlotSquared</name>
<packaging>jar</packaging>
<build>
<finalName>PlotSquared-Uber</finalName>
<finalName>${project.name}-Uber-${project.version}</finalName>
<sourceDirectory>src/main/java</sourceDirectory>
<resources>
<resource>
<filtering>true</filtering>
<excludes>
<exclude>skyblock.template</exclude>
<exclude>town.template</exclude>
</excludes>
<includes>
<include>plugin.yml</include>
</includes>
<directory>${basedir}/src/main/resources/</directory>
</resource>
<resource>
<filtering>false</filtering>
<includes>
<include>skyblock.template</include>
<include>town.template</include>
<include>s_chinese.yml</include>
<include>s_chinese_unescaped.yml</include>
<include>german.yml</include>
<include>italian.yml</include>
</includes>
<excludes>
<exclude>plugin.yml</exclude>
</excludes>
<directory>${basedir}/src/main/resources/</directory>
</resource>
</resources>
<plugins>
<!--
TODO: split the project into more modules
TODO: fix sponge compilation
-->
<!-- Invalid -->
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<id>bukkit</id>
@ -47,12 +90,13 @@
</goals>
<phase>package</phase>
<configuration>
<finalName>PlotSquared-Bukkit</finalName>
<finalName>${project.name}-Bukkit-${project.version}</finalName>
<excludes>
<exclude>**/com/plotsquared/sponge/**</exclude>
</excludes>
</configuration>
</execution>
<execution>
<id>sponge</id>
<goals>
@ -60,13 +104,14 @@
</goals>
<phase>package</phase>
<configuration>
<finalName>PlotSquared-Sponge</finalName>
<finalName>${project.name}-Sponge-${project.version}</finalName>
<excludes>
<exclude>**/com/plotsquared/bukkit/**</exclude>
<exclude>**/com/intellectualcrafters/plot/api/*</exclude>
</excludes>
</configuration>
</execution>
<execution>
<id>api</id>
<goals>
@ -74,7 +119,7 @@
</goals>
<phase>package</phase>
<configuration>
<finalName>PlotSquared-Null</finalName>
<finalName>${project.name}-API-${project.version}</finalName>
<excludes>
<exclude>**/com/plotsquared/bukkit/**</exclude>
<exclude>**/com/plotsquared/sponge/**</exclude>
@ -84,14 +129,52 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<version>3.3</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<target>${javaVersion}</target>
</configuration>
</plugin>
<!-- None of these are needed -->
<!-- <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.3</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
<minimizeJar>false</minimizeJar>
<relocations>
<relocation>
<pattern>com.google.gson</pattern>
<shadedPattern>com.plotsquared.libs.gson</shadedPattern>
</relocation>
<relocation>
<pattern>javax.websocket</pattern>
<shadedPattern>com.plotsquared.libs.websocket</shadedPattern>
</relocation>
<relocation>
<pattern>org.apache.commons.math3</pattern>
<shadedPattern>com.plotsquared.libs.math3</shadedPattern>
</relocation>
</relocations>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin> -->
<!-- Useless ATM
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
@ -100,37 +183,21 @@
<additionalparam>-Xdoclint:none</additionalparam>
</configuration>
</plugin>
-->
</plugins>
</build>
<repositories>
<repository>
<id>techcable-repo</id>
<!-- Just leave the repositories section alone or bukkit won't work -->
<url>http://repo.techcable.net/content/groups/public/</url>
</repository>
<repository>
<id>empcraft-repo</id>
<url>http://empcraft.com/maven2</url>
</repository>
<repository>
<id>spigot-repo</id>
<url>http://hub.spigotmc.org/nexus/content/groups/public/</url>
</repository>
<repository>
<id>confuser-repo</id>
<url>http://ci.frostcast.net/plugin/repository/everything</url>
</repository>
<repository>
<id>sk80q</id>
<url>http://maven.sk89q.com/artifactory/repo/</url>
</repository>
<repository>
<id>vault-repo</id>
<url>http://nexus.theyeticave.net/content/repositories/pub_releases</url>
<url>https://hub.spigotmc.org/nexus/content/groups/public/</url>
</repository>
<repository>
<id>sponge-maven-repo</id>
<name>Sponge maven repo</name>
<url>http://repo.spongepowered.org/maven</url>
<releases>
<enabled>true</enabled>
@ -139,55 +206,125 @@
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>sk89q</id>
<url>http://maven.sk89q.com/repo/</url>
</repository>
<repository>
<id>vault-repo</id>
<url>http://nexus.theyeticave.net/content/repositories/pub_releases</url>
</repository>
</repositories>
<dependencies>
<!-- Bukkit API, http://www.spigotmc.org/ or http://bukkit.org/ -->
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>${bukkitVersion}</version>
<scope>provided</scope>
<optional>true</optional>
<exclusions>
<exclusion>
<artifactId>junit</artifactId>
<groupId>junit</groupId>
</exclusion>
<!-- <exclusion>
<artifactId>gson</artifactId>
<groupId>com.google.code.gson</groupId>
</exclusion> -->
<exclusion>
<artifactId>persistence-api</artifactId>
<groupId>javax.persistence</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- Sponge API -->
<dependency>
<groupId>org.spongepowered</groupId>
<artifactId>spongeapi</artifactId>
<version>2.1-SNAPSHOT</version>
<version>${spongeVersion}</version>
<scope>provided</scope>
<optional>true</optional>
<exclusions>
<exclusion>
<artifactId>jsr305</artifactId>
<groupId>com.google.code.findbugs</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.8.3-R0.1-SNAPSHOT</version>
<version>1.8.8-R0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.sk89q</groupId>
<artifactId>worldedit</artifactId>
<version>6.0.0-SNAPSHOT</version>
<type>jar</type>
<scope>compile</scope>
<scope>provided</scope>
<optional>true</optional>
<exclusions>
<exclusion>
<artifactId>truezip</artifactId>
<groupId>de.schlichtherle</groupId>
</exclusion>
<exclusion>
<artifactId>js</artifactId>
<groupId>rhino</groupId>
</exclusion>
<exclusion>
<artifactId>jsr305</artifactId>
<groupId>com.google.code.findbugs</groupId>
</exclusion>
<exclusion>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>me.confuser</groupId>
<artifactId>BarAPI</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<!-- <dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>3.2</version>
</dependency>
<dependency>
<version>3.6</version>
<scope>compile</scope>
<optional>true</optional>
</dependency> -->
<!-- <dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<version>4.12</version>
<scope>test</scope>
<optional>true</optional>
</dependency>
-->
<dependency>
<groupId>net.milkbowl.vault</groupId>
<artifactId>VaultAPI</artifactId>
<version>1.5</version>
<scope>provided</scope>
<optional>true</optional>
<exclusions>
<exclusion>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<!-- GSON (required to provide 1.7.10 and below compatibility) -->
<!-- GSON (except it's only needed in 1.8+) -->
<!-- <dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3.1</version>
</dependency>
<version>2.5</version>
<scope>compile</scope>
<optional>true</optional>
</dependency> -->
</dependencies>
</project>

View File

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

View File

@ -9,7 +9,7 @@ public class ConfigurationOptions {
private boolean copyDefaults = false;
private final Configuration configuration;
protected ConfigurationOptions(Configuration configuration) {
protected ConfigurationOptions(final Configuration configuration) {
this.configuration = configuration;
}
@ -45,8 +45,8 @@ public class ConfigurationOptions {
* @param value Path separator
* @return This object, for chaining
*/
public ConfigurationOptions pathSeparator(char value) {
this.pathSeparator = value;
public ConfigurationOptions pathSeparator(final char value) {
pathSeparator = value;
return this;
}
@ -83,8 +83,8 @@ public class ConfigurationOptions {
* @param value Whether or not defaults are directly copied
* @return This object, for chaining
*/
public ConfigurationOptions copyDefaults(boolean value) {
this.copyDefaults = value;
public ConfigurationOptions copyDefaults(final boolean value) {
copyDefaults = value;
return this;
}
}

View File

@ -22,7 +22,7 @@ public interface ConfigurationSection {
* list.
* @return Set of keys contained within this ConfigurationSection.
*/
public Set<String> getKeys(boolean deep);
public Set<String> getKeys(final boolean deep);
/**
* Gets a Map containing all keys and their values for this section.
@ -38,7 +38,7 @@ public interface ConfigurationSection {
* list.
* @return Map of keys and values of this section.
*/
public Map<String, Object> getValues(boolean deep);
public Map<String, Object> getValues(final boolean deep);
/**
* Checks if this {@link ConfigurationSection} contains the given path.
@ -51,7 +51,7 @@ public interface ConfigurationSection {
* default or being set.
* @throws IllegalArgumentException Thrown when path is null.
*/
public boolean contains(String path);
public boolean contains(final String path);
/**
* Checks if this {@link ConfigurationSection} has a value set for the
@ -65,7 +65,7 @@ public interface ConfigurationSection {
* having a default.
* @throws IllegalArgumentException Thrown when path is null.
*/
public boolean isSet(String path);
public boolean isSet(final String path);
/**
* Gets the path of this {@link ConfigurationSection} from its root {@link
@ -132,7 +132,7 @@ public interface ConfigurationSection {
* @param path Path of the Object to get.
* @return Requested Object.
*/
public Object get(String path);
public Object get(final String path);
/**
* Gets the requested Object by path, returning a default value if not
@ -146,7 +146,7 @@ public interface ConfigurationSection {
* @param def The default value to return if the path is not found.
* @return Requested Object.
*/
public Object get(String path, Object def);
public Object get(final String path, final Object def);
/**
* Sets the specified path to the given value.
@ -155,14 +155,14 @@ public interface ConfigurationSection {
* replaced, regardless of what the new value is.
* <p>
* Some implementations may have limitations on what you may store. See
* their individual javadocs for details. No implementations should allow
* their individual javadoc for details. No implementations should allow
* you to store {@link Configuration}s or {@link ConfigurationSection}s,
* please use {@link #createSection(java.lang.String)} for that.
* please use {@link #createSection(String)} for that.
*
* @param path Path of the object to set.
* @param value New value to set the path to.
*/
public void set(String path, Object value);
public void set(final String path, final Object value);
/**
* Creates an empty {@link ConfigurationSection} at the specified path.
@ -174,7 +174,7 @@ public interface ConfigurationSection {
* @param path Path to create the section at.
* @return Newly created section
*/
public ConfigurationSection createSection(String path);
public ConfigurationSection createSection(final String path);
/**
* Creates a {@link ConfigurationSection} at the specified path, with
@ -188,7 +188,7 @@ public interface ConfigurationSection {
* @param map The values to used.
* @return Newly created section
*/
public ConfigurationSection createSection(String path, Map<?, ?> map);
public ConfigurationSection createSection(final String path, final Map<?, ?> map);
// Primitives
/**
@ -201,7 +201,7 @@ public interface ConfigurationSection {
* @param path Path of the String to get.
* @return Requested String.
*/
public String getString(String path);
public String getString(final String path);
/**
* Gets the requested String by path, returning a default value if not
@ -216,7 +216,7 @@ public interface ConfigurationSection {
* not a String.
* @return Requested String.
*/
public String getString(String path, String def);
public String getString(final String path, final String def);
/**
* Checks if the specified path is a String.
@ -229,7 +229,7 @@ public interface ConfigurationSection {
* @param path Path of the String to check.
* @return Whether or not the specified path is a String.
*/
public boolean isString(String path);
public boolean isString(final String path);
/**
* Gets the requested int by path.
@ -241,7 +241,7 @@ public interface ConfigurationSection {
* @param path Path of the int to get.
* @return Requested int.
*/
public int getInt(String path);
public int getInt(final String path);
/**
* Gets the requested int by path, returning a default value if not found.
@ -255,7 +255,7 @@ public interface ConfigurationSection {
* not an int.
* @return Requested int.
*/
public int getInt(String path, int def);
public int getInt(final String path, final int def);
/**
* Checks if the specified path is an int.
@ -268,7 +268,7 @@ public interface ConfigurationSection {
* @param path Path of the int to check.
* @return Whether or not the specified path is an int.
*/
public boolean isInt(String path);
public boolean isInt(final String path);
/**
* Gets the requested boolean by path.
@ -280,7 +280,7 @@ public interface ConfigurationSection {
* @param path Path of the boolean to get.
* @return Requested boolean.
*/
public boolean getBoolean(String path);
public boolean getBoolean(final String path);
/**
* Gets the requested boolean by path, returning a default value if not
@ -295,7 +295,7 @@ public interface ConfigurationSection {
* not a boolean.
* @return Requested boolean.
*/
public boolean getBoolean(String path, boolean def);
public boolean getBoolean(final String path, final boolean def);
/**
* Checks if the specified path is a boolean.
@ -308,7 +308,7 @@ public interface ConfigurationSection {
* @param path Path of the boolean to check.
* @return Whether or not the specified path is a boolean.
*/
public boolean isBoolean(String path);
public boolean isBoolean(final String path);
/**
* Gets the requested double by path.
@ -320,7 +320,7 @@ public interface ConfigurationSection {
* @param path Path of the double to get.
* @return Requested double.
*/
public double getDouble(String path);
public double getDouble(final String path);
/**
* Gets the requested double by path, returning a default value if not
@ -335,7 +335,7 @@ public interface ConfigurationSection {
* not a double.
* @return Requested double.
*/
public double getDouble(String path, double def);
public double getDouble(final String path, final double def);
/**
* Checks if the specified path is a double.
@ -348,7 +348,7 @@ public interface ConfigurationSection {
* @param path Path of the double to check.
* @return Whether or not the specified path is a double.
*/
public boolean isDouble(String path);
public boolean isDouble(final String path);
/**
* Gets the requested long by path.
@ -360,7 +360,7 @@ public interface ConfigurationSection {
* @param path Path of the long to get.
* @return Requested long.
*/
public long getLong(String path);
public long getLong(final String path);
/**
* Gets the requested long by path, returning a default value if not
@ -375,7 +375,7 @@ public interface ConfigurationSection {
* not a long.
* @return Requested long.
*/
public long getLong(String path, long def);
public long getLong(final String path, final long def);
/**
* Checks if the specified path is a long.
@ -388,7 +388,7 @@ public interface ConfigurationSection {
* @param path Path of the long to check.
* @return Whether or not the specified path is a long.
*/
public boolean isLong(String path);
public boolean isLong(final String path);
// Java
/**
@ -401,7 +401,7 @@ public interface ConfigurationSection {
* @param path Path of the List to get.
* @return Requested List.
*/
public List<?> getList(String path);
public List<?> getList(final String path);
/**
* Gets the requested List by path, returning a default value if not
@ -416,7 +416,7 @@ public interface ConfigurationSection {
* not a List.
* @return Requested List.
*/
public List<?> getList(String path, List<?> def);
public List<?> getList(final String path, final List<?> def);
/**
* Checks if the specified path is a List.
@ -429,7 +429,7 @@ public interface ConfigurationSection {
* @param path Path of the List to check.
* @return Whether or not the specified path is a List.
*/
public boolean isList(String path);
public boolean isList(final String path);
/**
* Gets the requested List of String by path.
@ -444,7 +444,7 @@ public interface ConfigurationSection {
* @param path Path of the List to get.
* @return Requested List of String.
*/
public List<String> getStringList(String path);
public List<String> getStringList(final String path);
/**
* Gets the requested List of Integer by path.
@ -459,7 +459,7 @@ public interface ConfigurationSection {
* @param path Path of the List to get.
* @return Requested List of Integer.
*/
public List<Integer> getIntegerList(String path);
public List<Integer> getIntegerList(final String path);
/**
* Gets the requested List of Boolean by path.
@ -474,7 +474,7 @@ public interface ConfigurationSection {
* @param path Path of the List to get.
* @return Requested List of Boolean.
*/
public List<Boolean> getBooleanList(String path);
public List<Boolean> getBooleanList(final String path);
/**
* Gets the requested List of Double by path.
@ -489,7 +489,7 @@ public interface ConfigurationSection {
* @param path Path of the List to get.
* @return Requested List of Double.
*/
public List<Double> getDoubleList(String path);
public List<Double> getDoubleList(final String path);
/**
* Gets the requested List of Float by path.
@ -504,7 +504,7 @@ public interface ConfigurationSection {
* @param path Path of the List to get.
* @return Requested List of Float.
*/
public List<Float> getFloatList(String path);
public List<Float> getFloatList(final String path);
/**
* Gets the requested List of Long by path.
@ -519,7 +519,7 @@ public interface ConfigurationSection {
* @param path Path of the List to get.
* @return Requested List of Long.
*/
public List<Long> getLongList(String path);
public List<Long> getLongList(final String path);
/**
* Gets the requested List of Byte by path.
@ -534,7 +534,7 @@ public interface ConfigurationSection {
* @param path Path of the List to get.
* @return Requested List of Byte.
*/
public List<Byte> getByteList(String path);
public List<Byte> getByteList(final String path);
/**
* Gets the requested List of Character by path.
@ -549,7 +549,7 @@ public interface ConfigurationSection {
* @param path Path of the List to get.
* @return Requested List of Character.
*/
public List<Character> getCharacterList(String path);
public List<Character> getCharacterList(final String path);
/**
* Gets the requested List of Short by path.
@ -564,7 +564,7 @@ public interface ConfigurationSection {
* @param path Path of the List to get.
* @return Requested List of Short.
*/
public List<Short> getShortList(String path);
public List<Short> getShortList(final String path);
/**
* Gets the requested List of Maps by path.
@ -579,7 +579,7 @@ public interface ConfigurationSection {
* @param path Path of the List to get.
* @return Requested List of Maps.
*/
public List<Map<?, ?>> getMapList(String path);
public List<Map<?, ?>> getMapList(final String path);
/**
* Gets the requested ConfigurationSection by path.
@ -592,7 +592,7 @@ public interface ConfigurationSection {
* @param path Path of the ConfigurationSection to get.
* @return Requested ConfigurationSection.
*/
public ConfigurationSection getConfigurationSection(String path);
public ConfigurationSection getConfigurationSection(final String path);
/**
* Checks if the specified path is a ConfigurationSection.
@ -606,7 +606,7 @@ public interface ConfigurationSection {
* @param path Path of the ConfigurationSection to check.
* @return Whether or not the specified path is a ConfigurationSection.
*/
public boolean isConfigurationSection(String path);
public boolean isConfigurationSection(final String path);
/**
* Gets the equivalent {@link ConfigurationSection} from the default
@ -638,5 +638,5 @@ public interface ConfigurationSection {
* @param value Value to set the default to.
* @throws IllegalArgumentException Thrown if path is null.
*/
public void addDefault(String path, Object value);
public void addDefault(final String path, final Object value);
}

View File

@ -18,7 +18,7 @@ public class InvalidConfigurationException extends Exception {
*
* @param msg The details of the exception.
*/
public InvalidConfigurationException(String msg) {
public InvalidConfigurationException(final String msg) {
super(msg);
}
@ -28,7 +28,7 @@ public class InvalidConfigurationException extends Exception {
*
* @param cause The cause of the exception.
*/
public InvalidConfigurationException(Throwable cause) {
public InvalidConfigurationException(final Throwable cause) {
super(cause);
}
@ -39,7 +39,7 @@ public class InvalidConfigurationException extends Exception {
* @param cause The cause of the exception.
* @param msg The details of the exception.
*/
public InvalidConfigurationException(String msg, Throwable cause) {
public InvalidConfigurationException(final String msg, final Throwable cause) {
super(msg, cause);
}
}

View File

@ -23,13 +23,15 @@ public class MemoryConfiguration extends MemorySection implements Configuration
* @param defaults Default value provider
* @throws IllegalArgumentException Thrown if defaults is null
*/
public MemoryConfiguration(Configuration defaults) {
public MemoryConfiguration(final Configuration defaults) {
this.defaults = defaults;
}
@Override
public void addDefault(String path, Object value) {
if (path == null) throw new NullPointerException("Path may not be null");
public void addDefault(final String path, final Object value) {
if (path == null) {
throw new NullPointerException("Path may not be null");
}
if (defaults == null) {
defaults = new MemoryConfiguration();
}
@ -37,26 +39,36 @@ public class MemoryConfiguration extends MemorySection implements Configuration
defaults.set(path, value);
}
public void addDefaults(Map<String, Object> defaults) {
if (defaults == null) throw new NullPointerException("Defaults may not be null");
@Override
public void addDefaults(final Map<String, Object> defaults) {
if (defaults == null) {
throw new NullPointerException("Defaults may not be null");
}
for (Map.Entry<String, Object> entry : defaults.entrySet()) {
for (final Map.Entry<String, Object> entry : defaults.entrySet()) {
addDefault(entry.getKey(), entry.getValue());
}
}
public void addDefaults(Configuration defaults) {
if (defaults == null) throw new NullPointerException("Defaults may not be null");
@Override
public void addDefaults(final Configuration defaults) {
if (defaults == null) {
throw new NullPointerException("Defaults may not be null");
}
addDefaults(defaults.getValues(true));
}
public void setDefaults(Configuration defaults) {
if (defaults == null) throw new NullPointerException("Defaults may not be null");
@Override
public void setDefaults(final Configuration defaults) {
if (defaults == null) {
throw new NullPointerException("Defaults may not be null");
}
this.defaults = defaults;
}
@Override
public Configuration getDefaults() {
return defaults;
}
@ -66,6 +78,7 @@ public class MemoryConfiguration extends MemorySection implements Configuration
return null;
}
@Override
public MemoryConfigurationOptions options() {
if (options == null) {
options = new MemoryConfigurationOptions(this);

View File

@ -5,7 +5,7 @@ package com.intellectualcrafters.configuration;
* MemoryConfiguration}
*/
public class MemoryConfigurationOptions extends ConfigurationOptions {
protected MemoryConfigurationOptions(MemoryConfiguration configuration) {
protected MemoryConfigurationOptions(final MemoryConfiguration configuration) {
super(configuration);
}
@ -15,13 +15,13 @@ public class MemoryConfigurationOptions extends ConfigurationOptions {
}
@Override
public MemoryConfigurationOptions copyDefaults(boolean value) {
public MemoryConfigurationOptions copyDefaults(final boolean value) {
super.copyDefaults(value);
return this;
}
@Override
public MemoryConfigurationOptions pathSeparator(char value) {
public MemoryConfigurationOptions pathSeparator(final char value) {
super.pathSeparator(value);
return this;
}

View File

@ -73,7 +73,7 @@ public abstract class FileConfiguration extends MemoryConfiguration {
*
* @param defaults Default value provider
*/
public FileConfiguration(Configuration defaults) {
public FileConfiguration(final Configuration defaults) {
super(defaults);
}
@ -92,18 +92,17 @@ public abstract class FileConfiguration extends MemoryConfiguration {
* any reason.
* @throws IllegalArgumentException Thrown when file is null.
*/
public void save(File file) throws IOException {
if (file == null) throw new NullPointerException("File cannot be null");
public void save(final File file) throws IOException {
if (file == null) {
throw new NullPointerException("File cannot be null");
}
file.getParentFile().mkdirs();
String data = saveToString();
final String data = saveToString();
Writer writer = new OutputStreamWriter(new FileOutputStream(file), UTF8_OVERRIDE && !UTF_BIG ? StandardCharsets.UTF_8 : Charset.defaultCharset());
try {
try (Writer writer = new OutputStreamWriter(new FileOutputStream(file),
UTF8_OVERRIDE && !UTF_BIG ? StandardCharsets.UTF_8 : Charset.defaultCharset())) {
writer.write(data);
} finally {
writer.close();
}
}
@ -122,8 +121,10 @@ public abstract class FileConfiguration extends MemoryConfiguration {
* any reason.
* @throws IllegalArgumentException Thrown when file is null.
*/
public void save(String file) throws IOException {
if (file == null) throw new NullPointerException("File cannot be null");
public void save(final String file) throws IOException {
if (file == null) {
throw new NullPointerException("File cannot be null");
}
save(new File(file));
}
@ -157,8 +158,10 @@ public abstract class FileConfiguration extends MemoryConfiguration {
* a valid Configuration.
* @throws IllegalArgumentException Thrown when file is null.
*/
public void load(File file) throws IOException, InvalidConfigurationException {
if (file == null) throw new NullPointerException("File cannot be null");
public void load(final File file) throws IOException, InvalidConfigurationException {
if (file == null) {
throw new NullPointerException("File cannot be null");
}
final FileInputStream stream = new FileInputStream(file);
@ -184,8 +187,10 @@ public abstract class FileConfiguration extends MemoryConfiguration {
* @see #load(Reader)
*/
@Deprecated
public void load(InputStream stream) throws IOException, InvalidConfigurationException {
if (stream == null) throw new NullPointerException("Stream cannot be null");
public void load(final InputStream stream) throws IOException, InvalidConfigurationException {
if (stream == null) {
throw new NullPointerException("Stream cannot be null");
}
load(new InputStreamReader(stream, UTF8_OVERRIDE ? StandardCharsets.UTF_8 : Charset.defaultCharset()));
}
@ -203,20 +208,17 @@ public abstract class FileConfiguration extends MemoryConfiguration {
* represent a valid Configuration
* @throws IllegalArgumentException thrown when reader is null
*/
public void load(Reader reader) throws IOException, InvalidConfigurationException {
BufferedReader input = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader);
public void load(final Reader reader) throws IOException, InvalidConfigurationException {
StringBuilder builder = new StringBuilder();
final StringBuilder builder = new StringBuilder();
try {
try (BufferedReader input = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader)) {
String line;
while ((line = input.readLine()) != null) {
builder.append(line);
builder.append('\n');
}
} finally {
input.close();
}
loadFromString(builder.toString());
@ -240,8 +242,10 @@ public abstract class FileConfiguration extends MemoryConfiguration {
* a valid Configuration.
* @throws IllegalArgumentException Thrown when file is null.
*/
public void load(String file) throws IOException, InvalidConfigurationException {
if (file == null) throw new NullPointerException("File cannot be null");
public void load(final String file) throws IOException, InvalidConfigurationException {
if (file == null) {
throw new NullPointerException("File cannot be null");
}
load(new File(file));
}
@ -261,7 +265,7 @@ public abstract class FileConfiguration extends MemoryConfiguration {
* invalid.
* @throws IllegalArgumentException Thrown if contents is null.
*/
public abstract void loadFromString(String contents) throws InvalidConfigurationException;
public abstract void loadFromString(final String contents) throws InvalidConfigurationException;
/**
* Compiles the header for this {@link FileConfiguration} and returns the

View File

@ -11,7 +11,7 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions {
private String header = null;
private boolean copyHeader = true;
protected FileConfigurationOptions(MemoryConfiguration configuration) {
protected FileConfigurationOptions(final MemoryConfiguration configuration) {
super(configuration);
}
@ -21,13 +21,13 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions {
}
@Override
public FileConfigurationOptions copyDefaults(boolean value) {
public FileConfigurationOptions copyDefaults(final boolean value) {
super.copyDefaults(value);
return this;
}
@Override
public FileConfigurationOptions pathSeparator(char value) {
public FileConfigurationOptions pathSeparator(final char value) {
super.pathSeparator(value);
return this;
}
@ -65,8 +65,8 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions {
* @param value New header
* @return This object, for chaining
*/
public FileConfigurationOptions header(String value) {
this.header = value;
public FileConfigurationOptions header(final String value) {
header = value;
return this;
}
@ -111,7 +111,7 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions {
* @param value Whether or not to copy the header
* @return This object, for chaining
*/
public FileConfigurationOptions copyHeader(boolean value) {
public FileConfigurationOptions copyHeader(final boolean value) {
copyHeader = value;
return this;

View File

@ -1,22 +1,20 @@
package com.intellectualcrafters.configuration.file;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.Map;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.error.YAMLException;
import org.yaml.snakeyaml.representer.Representer;
import com.intellectualcrafters.configuration.Configuration;
import com.intellectualcrafters.configuration.ConfigurationSection;
import com.intellectualcrafters.configuration.InvalidConfigurationException;
import com.intellectualcrafters.plot.PS;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.error.YAMLException;
import org.yaml.snakeyaml.representer.Representer;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.Map;
/**
* An implementation of {@link Configuration} which saves all files in Yaml.
@ -29,14 +27,87 @@ public class YamlConfiguration extends FileConfiguration {
private final Representer yamlRepresenter = new YamlRepresenter();
private final Yaml yaml = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions);
/**
* Creates a new {@link YamlConfiguration}, loading from the given file.
* <p>
* Any errors loading the Configuration will be logged and then ignored.
* If the specified input is not a valid config, a blank config will be
* returned.
* <p>
* The encoding used may follow the system dependent default.
*
* @param file Input file
* @return Resulting configuration
* @throws IllegalArgumentException Thrown if file is null
*/
public static YamlConfiguration loadConfiguration(final File file) {
if (file == null) {
throw new NullPointerException("File cannot be null");
}
final YamlConfiguration config = new YamlConfiguration();
try {
config.load(file);
} catch (InvalidConfigurationException | IOException ex) {
try {
file.getAbsolutePath();
File dest = new File(file.getAbsolutePath() + "_broken");
int i = 0;
while (dest.exists()) {
dest = new File(file.getAbsolutePath() + "_broken_" + i++);
}
Files.copy(file.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
PS.debug("&dCould not read: &7" + file);
PS.debug("&dRenamed to: &7" + dest.getName());
PS.debug("&c============ Full stacktrace ============");
ex.printStackTrace();
PS.debug("&c=========================================");
} catch (final IOException e) {
e.printStackTrace();
}
}
return config;
}
/**
* Creates a new {@link YamlConfiguration}, loading from the given reader.
* <p>
* Any errors loading the Configuration will be logged and then ignored.
* If the specified input is not a valid config, a blank config will be
* returned.
*
* @param reader input
* @return resulting configuration
* @throws IllegalArgumentException Thrown if stream is null
*/
public static YamlConfiguration loadConfiguration(final Reader reader) {
if (reader == null) {
throw new NullPointerException("Reader cannot be null");
}
final YamlConfiguration config = new YamlConfiguration();
try {
config.load(reader);
} catch (final IOException | InvalidConfigurationException ex) {
PS.debug("Cannot load configuration from stream");
ex.printStackTrace();
}
return config;
}
@Override
@SuppressWarnings("deprecation")
public String saveToString() {
yamlOptions.setIndent(options().indent());
yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
yamlOptions.setAllowUnicode(SYSTEM_UTF);
yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
String header = buildHeader();
final String header = buildHeader();
String dump = yaml.dump(getValues(false));
if (dump.equals(BLANK_CONFIG)) {
@ -47,20 +118,22 @@ public class YamlConfiguration extends FileConfiguration {
}
@Override
public void loadFromString(String contents) throws InvalidConfigurationException {
if (contents == null) throw new NullPointerException("Contents cannot be null");
public void loadFromString(final String contents) throws InvalidConfigurationException {
if (contents == null) {
throw new NullPointerException("Contents cannot be null");
}
Map<?, ?> input;
try {
input = (Map<?, ?>) yaml.load(contents);
} catch (YAMLException e) {
} catch (final YAMLException e) {
throw new InvalidConfigurationException(e);
} catch (ClassCastException e) {
} catch (final ClassCastException e) {
throw new InvalidConfigurationException("Top level is not a Map.");
}
String header = parseHeader(contents);
if (header.length() > 0) {
final String header = parseHeader(contents);
if (!header.isEmpty()) {
options().header(header);
}
@ -69,10 +142,10 @@ public class YamlConfiguration extends FileConfiguration {
}
}
protected void convertMapsToSections(Map<?, ?> input, ConfigurationSection section) {
for (Map.Entry<?, ?> entry : input.entrySet()) {
String key = entry.getKey().toString();
Object value = entry.getValue();
protected void convertMapsToSections(final Map<?, ?> input, final ConfigurationSection section) {
for (final Map.Entry<?, ?> entry : input.entrySet()) {
final String key = entry.getKey().toString();
final Object value = entry.getValue();
if (value instanceof Map) {
convertMapsToSections((Map<?, ?>) value, section.createSection(key));
@ -82,14 +155,14 @@ public class YamlConfiguration extends FileConfiguration {
}
}
protected String parseHeader(String input) {
String[] lines = input.split("\r?\n", -1);
StringBuilder result = new StringBuilder();
protected String parseHeader(final String input) {
final String[] lines = input.split("\r?\n", -1);
final StringBuilder result = new StringBuilder();
boolean readingHeader = true;
boolean foundHeader = false;
for (int i = 0; (i < lines.length) && (readingHeader); i++) {
String line = lines[i];
final String line = lines[i];
if (line.startsWith(COMMENT_PREFIX)) {
if (i > 0) {
@ -101,7 +174,7 @@ public class YamlConfiguration extends FileConfiguration {
}
foundHeader = true;
} else if ((foundHeader) && (line.length() == 0)) {
} else if ((foundHeader) && (line.isEmpty())) {
result.append("\n");
} else if (foundHeader) {
readingHeader = false;
@ -113,16 +186,16 @@ public class YamlConfiguration extends FileConfiguration {
@Override
protected String buildHeader() {
String header = options().header();
final String header = options().header();
if (options().copyHeader()) {
Configuration def = getDefaults();
final Configuration def = getDefaults();
if ((def != null) && (def instanceof FileConfiguration)) {
FileConfiguration filedefaults = (FileConfiguration) def;
String defaultsHeader = filedefaults.buildHeader();
final FileConfiguration filedefaults = (FileConfiguration) def;
final String defaultsHeader = filedefaults.buildHeader();
if ((defaultsHeader != null) && (defaultsHeader.length() > 0)) {
if ((defaultsHeader != null) && (!defaultsHeader.isEmpty())) {
return defaultsHeader;
}
}
@ -132,14 +205,14 @@ public class YamlConfiguration extends FileConfiguration {
return "";
}
StringBuilder builder = new StringBuilder();
String[] lines = header.split("\r?\n", -1);
final StringBuilder builder = new StringBuilder();
final String[] lines = header.split("\r?\n", -1);
boolean startedHeader = false;
for (int i = lines.length - 1; i >= 0; i--) {
builder.insert(0, "\n");
if ((startedHeader) || (lines[i].length() != 0)) {
if ((startedHeader) || (!lines[i].isEmpty())) {
builder.insert(0, lines[i]);
builder.insert(0, COMMENT_PREFIX);
startedHeader = true;
@ -157,109 +230,4 @@ public class YamlConfiguration extends FileConfiguration {
return (YamlConfigurationOptions) options;
}
/**
* Creates a new {@link YamlConfiguration}, loading from the given file.
* <p>
* Any errors loading the Configuration will be logged and then ignored.
* If the specified input is not a valid config, a blank config will be
* returned.
* <p>
* The encoding used may follow the system dependent default.
*
* @param file Input file
* @return Resulting configuration
* @throws IllegalArgumentException Thrown if file is null
*/
public static YamlConfiguration loadConfiguration(File file) {
if (file == null) throw new NullPointerException("File cannot be null");
YamlConfiguration config = new YamlConfiguration();
try {
config.load(file);
} catch (Exception ex) {
try {
String path = file.getAbsolutePath() + "_broken";
File dest = new File(file.getAbsolutePath() + "_broken");
int i = 0;
while (dest.exists()) {
dest = new File(file.getAbsolutePath() + "_broken_" + i++);
}
Files.copy( file.toPath(), dest.toPath() , StandardCopyOption.REPLACE_EXISTING);
PS.debug("&dCould not read: &7" + file);
PS.debug("&drenamed to: &7" + dest.getName());
PS.debug("&c============ Full stacktrace ============");
ex.printStackTrace();
PS.debug("&c=========================================");
} catch (IOException e) {
e.printStackTrace();
}
}
return config;
}
/**
* Creates a new {@link YamlConfiguration}, loading from the given stream.
* <p>
* Any errors loading the Configuration will be logged and then ignored.
* If the specified input is not a valid config, a blank config will be
* returned.
*
* @param stream Input stream
* @return Resulting configuration
* @throws IllegalArgumentException Thrown if stream is null
* @deprecated does not properly consider encoding
* @see #load(InputStream)
* @see #loadConfiguration(Reader)
*/
@Deprecated
public static YamlConfiguration loadConfiguration(InputStream stream) {
if (stream == null) throw new NullPointerException("Stream cannot be null");
YamlConfiguration config = new YamlConfiguration();
try {
config.load(stream);
} catch (IOException ex) {
PS.debug("Cannot load configuration from stream");
ex.printStackTrace();
} catch (InvalidConfigurationException ex) {
ex.printStackTrace();
PS.debug("Cannot load configuration from stream");
}
return config;
}
/**
* Creates a new {@link YamlConfiguration}, loading from the given reader.
* <p>
* Any errors loading the Configuration will be logged and then ignored.
* If the specified input is not a valid config, a blank config will be
* returned.
*
* @param reader input
* @return resulting configuration
* @throws IllegalArgumentException Thrown if stream is null
*/
public static YamlConfiguration loadConfiguration(Reader reader) {
if (reader == null) throw new NullPointerException("Reader cannot be null");
YamlConfiguration config = new YamlConfiguration();
try {
config.load(reader);
} catch (IOException ex) {
PS.debug("Cannot load configuration from stream");
ex.printStackTrace();
} catch (InvalidConfigurationException ex) {
PS.debug("Cannot load configuration from stream");
ex.printStackTrace();
}
return config;
}
}

View File

@ -7,7 +7,7 @@ package com.intellectualcrafters.configuration.file;
public class YamlConfigurationOptions extends FileConfigurationOptions {
private int indent = 2;
protected YamlConfigurationOptions(YamlConfiguration configuration) {
protected YamlConfigurationOptions(final YamlConfiguration configuration) {
super(configuration);
}
@ -17,25 +17,25 @@ public class YamlConfigurationOptions extends FileConfigurationOptions {
}
@Override
public YamlConfigurationOptions copyDefaults(boolean value) {
public YamlConfigurationOptions copyDefaults(final boolean value) {
super.copyDefaults(value);
return this;
}
@Override
public YamlConfigurationOptions pathSeparator(char value) {
public YamlConfigurationOptions pathSeparator(final char value) {
super.pathSeparator(value);
return this;
}
@Override
public YamlConfigurationOptions header(String value) {
public YamlConfigurationOptions header(final String value) {
super.header(value);
return this;
}
@Override
public YamlConfigurationOptions copyHeader(boolean value) {
public YamlConfigurationOptions copyHeader(final boolean value) {
super.copyHeader(value);
return this;
}
@ -59,11 +59,15 @@ public class YamlConfigurationOptions extends FileConfigurationOptions {
* @param value New indent
* @return This object, for chaining
*/
public YamlConfigurationOptions indent(int value) {
if (value < 2) throw new IllegalArgumentException("Indent must be at least 2 characters");
if (value > 9) throw new IllegalArgumentException("Indent cannot be greater than 9 characters");
public YamlConfigurationOptions indent(final int value) {
if (value < 2) {
throw new IllegalArgumentException("Indent must be at least 2 characters");
}
if (value > 9) {
throw new IllegalArgumentException("Indent cannot be greater than 9 characters");
}
this.indent = value;
indent = value;
return this;
}
}

View File

@ -13,27 +13,27 @@ import com.intellectualcrafters.configuration.serialization.ConfigurationSeriali
public class YamlConstructor extends SafeConstructor {
public YamlConstructor() {
this.yamlConstructors.put(Tag.MAP, new ConstructCustomObject());
yamlConstructors.put(Tag.MAP, new ConstructCustomObject());
}
private class ConstructCustomObject extends ConstructYamlMap {
@Override
public Object construct(Node node) {
public Object construct(final Node node) {
if (node.isTwoStepsConstruction()) {
throw new YAMLException("Unexpected referential mapping structure. Node: " + node);
}
Map<?, ?> raw = (Map<?, ?>) super.construct(node);
final Map<?, ?> raw = (Map<?, ?>) super.construct(node);
if (raw.containsKey(ConfigurationSerialization.SERIALIZED_TYPE_KEY)) {
Map<String, Object> typed = new LinkedHashMap<String, Object>(raw.size());
for (Map.Entry<?, ?> entry : raw.entrySet()) {
final Map<String, Object> typed = new LinkedHashMap<String, Object>(raw.size());
for (final Map.Entry<?, ?> entry : raw.entrySet()) {
typed.put(entry.getKey().toString(), entry.getValue());
}
try {
return ConfigurationSerialization.deserializeObject(typed);
} catch (IllegalArgumentException ex) {
} catch (final IllegalArgumentException ex) {
throw new YAMLException("Could not deserialize object", ex);
}
}
@ -42,7 +42,7 @@ public class YamlConstructor extends SafeConstructor {
}
@Override
public void construct2ndStep(Node node, Object object) {
public void construct2ndStep(final Node node, final Object object) {
throw new YAMLException("Unexpected referential mapping structure. Node: " + node);
}
}

View File

@ -13,22 +13,22 @@ import com.intellectualcrafters.configuration.serialization.ConfigurationSeriali
public class YamlRepresenter extends Representer {
public YamlRepresenter() {
this.multiRepresenters.put(ConfigurationSection.class, new RepresentConfigurationSection());
this.multiRepresenters.put(ConfigurationSerializable.class, new RepresentConfigurationSerializable());
multiRepresenters.put(ConfigurationSection.class, new RepresentConfigurationSection());
multiRepresenters.put(ConfigurationSerializable.class, new RepresentConfigurationSerializable());
}
private class RepresentConfigurationSection extends RepresentMap {
@Override
public Node representData(Object data) {
public Node representData(final Object data) {
return super.representData(((ConfigurationSection) data).getValues(false));
}
}
private class RepresentConfigurationSerializable extends RepresentMap {
@Override
public Node representData(Object data) {
ConfigurationSerializable serializable = (ConfigurationSerializable) data;
Map<String, Object> values = new LinkedHashMap<String, Object>();
public Node representData(final Object data) {
final ConfigurationSerializable serializable = (ConfigurationSerializable) data;
final Map<String, Object> values = new LinkedHashMap<>();
values.put(ConfigurationSerialization.SERIALIZED_TYPE_KEY, ConfigurationSerialization.getAlias(serializable.getClass()));
values.putAll(serializable.serialize());

View File

@ -27,7 +27,7 @@ public interface ConfigurationSerializable {
* Creates a Map representation of this class.
* <p>
* This class must provide a method to restore this class, as defined in
* the {@link ConfigurationSerializable} interface javadocs.
* the {@link ConfigurationSerializable} interface javadoc.
*
* @return Map containing the current state of this class
*/

View File

@ -1,5 +1,7 @@
package com.intellectualcrafters.configuration.serialization;
import com.intellectualcrafters.configuration.Configuration;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@ -9,8 +11,6 @@ import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.intellectualcrafters.configuration.Configuration;
/**
* Utility class for storing and retrieving classes for {@link Configuration}.
*/
@ -19,13 +19,13 @@ public class ConfigurationSerialization {
private final Class<? extends ConfigurationSerializable> clazz;
private static Map<String, Class<? extends ConfigurationSerializable>> aliases = new HashMap<String, Class<? extends ConfigurationSerializable>>();
protected ConfigurationSerialization(Class<? extends ConfigurationSerializable> clazz) {
protected ConfigurationSerialization(final Class<? extends ConfigurationSerializable> clazz) {
this.clazz = clazz;
}
protected Method getMethod(String name, boolean isStatic) {
protected Method getMethod(final String name, final boolean isStatic) {
try {
Method method = clazz.getDeclaredMethod(name, Map.class);
final Method method = clazz.getDeclaredMethod(name, Map.class);
if (!ConfigurationSerializable.class.isAssignableFrom(method.getReturnType())) {
return null;
@ -35,9 +35,9 @@ public class ConfigurationSerialization {
}
return method;
} catch (NoSuchMethodException ex) {
} catch (final NoSuchMethodException ex) {
return null;
} catch (SecurityException ex) {
} catch (final SecurityException ex) {
return null;
}
}
@ -45,59 +45,52 @@ public class ConfigurationSerialization {
protected Constructor<? extends ConfigurationSerializable> getConstructor() {
try {
return clazz.getConstructor(Map.class);
} catch (NoSuchMethodException ex) {
} catch (final NoSuchMethodException ex) {
return null;
} catch (SecurityException ex) {
} catch (final SecurityException ex) {
return null;
}
}
protected ConfigurationSerializable deserializeViaMethod(Method method, Map<String, ?> args) {
protected ConfigurationSerializable deserializeViaMethod(final Method method, final Map<String, ?> args) {
try {
ConfigurationSerializable result = (ConfigurationSerializable) method.invoke(null, args);
final ConfigurationSerializable result = (ConfigurationSerializable) method.invoke(null, args);
if (result == null) {
Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE, "Could not call method '" + method.toString() + "' of " + clazz + " for deserialization: method returned null");
Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE,
"Could not call method '" + method.toString() + "' of " + clazz + " for deserialization: method returned null");
} else {
return result;
}
} catch (Throwable ex) {
Logger.getLogger(ConfigurationSerialization.class.getName()).log(
Level.SEVERE,
"Could not call method '" + method.toString() + "' of " + clazz + " for deserialization",
} catch (final Throwable ex) {
Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE, "Could not call method '" + method.toString() + "' of " + clazz + " for deserialization",
ex instanceof InvocationTargetException ? ex.getCause() : ex);
}
return null;
}
protected ConfigurationSerializable deserializeViaCtor(Constructor<? extends ConfigurationSerializable> ctor, Map<String, ?> args) {
protected ConfigurationSerializable deserializeViaCtor(final Constructor<? extends ConfigurationSerializable> ctor, final Map<String, ?> args) {
try {
return ctor.newInstance(args);
} catch (Throwable ex) {
Logger.getLogger(ConfigurationSerialization.class.getName()).log(
Level.SEVERE,
"Could not call constructor '" + ctor.toString() + "' of " + clazz + " for deserialization",
} catch (final Throwable ex) {
Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE, "Could not call constructor '" + ctor.toString() + "' of " + clazz + " for deserialization",
ex instanceof InvocationTargetException ? ex.getCause() : ex);
}
return null;
}
public ConfigurationSerializable deserialize(Map<String, ?> args) {
public ConfigurationSerializable deserialize(final Map<String, ?> args) {
if (args == null) {
throw new NullPointerException("Args must not be null");
}
ConfigurationSerializable result = null;
Method method = null;
if (result == null) {
method = getMethod("deserialize", true);
Method method = getMethod("deserialize", true);
if (method != null) {
result = deserializeViaMethod(method, args);
}
}
if (result == null) {
method = getMethod("valueOf", true);
@ -108,7 +101,7 @@ public class ConfigurationSerialization {
}
if (result == null) {
Constructor<? extends ConfigurationSerializable> constructor = getConstructor();
final Constructor<? extends ConfigurationSerializable> constructor = getConstructor();
if (constructor != null) {
result = deserializeViaCtor(constructor, args);
@ -133,7 +126,7 @@ public class ConfigurationSerialization {
* @param clazz Class to deserialize into
* @return New instance of the specified class
*/
public static ConfigurationSerializable deserializeObject(Map<String, ?> args, Class<? extends ConfigurationSerializable> clazz) {
public static ConfigurationSerializable deserializeObject(final Map<String, ?> args, final Class<? extends ConfigurationSerializable> clazz) {
return new ConfigurationSerialization(clazz).deserialize(args);
}
@ -151,12 +144,12 @@ public class ConfigurationSerialization {
* @param args Arguments for deserialization
* @return New instance of the specified class
*/
public static ConfigurationSerializable deserializeObject(Map<String, ?> args) {
public static ConfigurationSerializable deserializeObject(final Map<String, ?> args) {
Class<? extends ConfigurationSerializable> clazz = null;
if (args.containsKey(SERIALIZED_TYPE_KEY)) {
try {
String alias = (String) args.get(SERIALIZED_TYPE_KEY);
final String alias = (String) args.get(SERIALIZED_TYPE_KEY);
if (alias == null) {
throw new IllegalArgumentException("Cannot have null alias");
@ -165,7 +158,7 @@ public class ConfigurationSerialization {
if (clazz == null) {
throw new IllegalArgumentException("Specified class does not exist ('" + alias + "')");
}
} catch (ClassCastException ex) {
} catch (final ClassCastException ex) {
ex.fillInStackTrace();
throw ex;
}
@ -182,8 +175,8 @@ public class ConfigurationSerialization {
*
* @param clazz Class to register
*/
public static void registerClass(Class<? extends ConfigurationSerializable> clazz) {
DelegateDeserialization delegate = clazz.getAnnotation(DelegateDeserialization.class);
public static void registerClass(final Class<? extends ConfigurationSerializable> clazz) {
final DelegateDeserialization delegate = clazz.getAnnotation(DelegateDeserialization.class);
if (delegate == null) {
registerClass(clazz, getAlias(clazz));
@ -199,7 +192,7 @@ public class ConfigurationSerialization {
* @param alias Alias to register as
* @see SerializableAs
*/
public static void registerClass(Class<? extends ConfigurationSerializable> clazz, String alias) {
public static void registerClass(final Class<? extends ConfigurationSerializable> clazz, final String alias) {
aliases.put(alias, clazz);
}
@ -208,7 +201,7 @@ public class ConfigurationSerialization {
*
* @param alias Alias to unregister
*/
public static void unregisterClass(String alias) {
public static void unregisterClass(final String alias) {
aliases.remove(alias);
}
@ -218,9 +211,8 @@ public class ConfigurationSerialization {
*
* @param clazz Class to unregister
*/
public static void unregisterClass(Class<? extends ConfigurationSerializable> clazz) {
while (aliases.values().remove(clazz)) {
}
public static void unregisterClass(final Class<? extends ConfigurationSerializable> clazz) {
while (aliases.values().remove(clazz)) {}
}
/**
@ -230,7 +222,7 @@ public class ConfigurationSerialization {
* @param alias Alias of the serializable
* @return Registered class, or null if not found
*/
public static Class<? extends ConfigurationSerializable> getClassByAlias(String alias) {
public static Class<? extends ConfigurationSerializable> getClassByAlias(final String alias) {
return aliases.get(alias);
}
@ -241,7 +233,7 @@ public class ConfigurationSerialization {
* @param clazz Class to get alias for
* @return Alias to use for the class
*/
public static String getAlias(Class<? extends ConfigurationSerializable> clazz) {
public static String getAlias(final Class<? extends ConfigurationSerializable> clazz) {
DelegateDeserialization delegate = clazz.getAnnotation(DelegateDeserialization.class);
if (delegate != null) {
@ -252,13 +244,11 @@ public class ConfigurationSerialization {
}
}
if (delegate == null) {
SerializableAs alias = clazz.getAnnotation(SerializableAs.class);
final SerializableAs alias = clazz.getAnnotation(SerializableAs.class);
if ((alias != null) && (alias.value() != null)) {
return alias.value();
}
}
return clazz.getName();
}

View File

@ -29,13 +29,13 @@ public final class ByteArrayTag extends Tag {
@Override
public byte[] getValue() {
return this.value;
return value;
}
@Override
public String toString() {
final StringBuilder hex = new StringBuilder();
for (final byte b : this.value) {
for (final byte b : value) {
final String hexDigits = Integer.toHexString(b).toUpperCase();
if (hexDigits.length() == 1) {
hex.append("0");
@ -45,7 +45,7 @@ public final class ByteArrayTag extends Tag {
final String name = getName();
String append = "";
if ((name != null) && !name.equals("")) {
append = "(\"" + this.getName() + "\")";
append = "(\"" + getName() + "\")";
}
return "TAG_Byte_Array" + append + ": " + hex;
}

View File

@ -29,7 +29,7 @@ public final class ByteTag extends Tag {
@Override
public Byte getValue() {
return this.value;
return value;
}
@Override
@ -37,8 +37,8 @@ public final class ByteTag extends Tag {
final String name = getName();
String append = "";
if ((name != null) && !name.equals("")) {
append = "(\"" + this.getName() + "\")";
append = "(\"" + getName() + "\")";
}
return "TAG_Byte" + append + ": " + this.value;
return "TAG_Byte" + append + ": " + value;
}
}

View File

@ -40,12 +40,12 @@ public final class CompoundTag extends Tag {
* @return true if the tag contains the given key
*/
public boolean containsKey(final String key) {
return this.value.containsKey(key);
return value.containsKey(key);
}
@Override
public Map<String, Tag> getValue() {
return this.value;
return value;
}
/**
@ -65,7 +65,7 @@ public final class CompoundTag extends Tag {
* @return the builder
*/
public CompoundTagBuilder createBuilder() {
return new CompoundTagBuilder(new HashMap<String, Tag>(this.value));
return new CompoundTagBuilder(new HashMap<String, Tag>(value));
}
/**
@ -77,7 +77,7 @@ public final class CompoundTag extends Tag {
* @return a byte array
*/
public byte[] getByteArray(final String key) {
final Tag tag = this.value.get(key);
final Tag tag = value.get(key);
if (tag instanceof ByteArrayTag) {
return ((ByteArrayTag) tag).getValue();
} else {
@ -94,7 +94,7 @@ public final class CompoundTag extends Tag {
* @return a byte
*/
public byte getByte(final String key) {
final Tag tag = this.value.get(key);
final Tag tag = value.get(key);
if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue();
} else {
@ -111,7 +111,7 @@ public final class CompoundTag extends Tag {
* @return a double
*/
public double getDouble(final String key) {
final Tag tag = this.value.get(key);
final Tag tag = value.get(key);
if (tag instanceof DoubleTag) {
return ((DoubleTag) tag).getValue();
} else {
@ -128,7 +128,7 @@ public final class CompoundTag extends Tag {
* @return a double
*/
public double asDouble(final String key) {
final Tag tag = this.value.get(key);
final Tag tag = value.get(key);
if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue();
} else if (tag instanceof ShortTag) {
@ -155,7 +155,7 @@ public final class CompoundTag extends Tag {
* @return a float
*/
public float getFloat(final String key) {
final Tag tag = this.value.get(key);
final Tag tag = value.get(key);
if (tag instanceof FloatTag) {
return ((FloatTag) tag).getValue();
} else {
@ -172,7 +172,7 @@ public final class CompoundTag extends Tag {
* @return an int array
*/
public int[] getIntArray(final String key) {
final Tag tag = this.value.get(key);
final Tag tag = value.get(key);
if (tag instanceof IntArrayTag) {
return ((IntArrayTag) tag).getValue();
} else {
@ -189,7 +189,7 @@ public final class CompoundTag extends Tag {
* @return an int
*/
public int getInt(final String key) {
final Tag tag = this.value.get(key);
final Tag tag = value.get(key);
if (tag instanceof IntTag) {
return ((IntTag) tag).getValue();
} else {
@ -206,7 +206,7 @@ public final class CompoundTag extends Tag {
* @return an int
*/
public int asInt(final String key) {
final Tag tag = this.value.get(key);
final Tag tag = value.get(key);
if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue();
} else if (tag instanceof ShortTag) {
@ -233,7 +233,7 @@ public final class CompoundTag extends Tag {
* @return a list of tags
*/
public List<Tag> getList(final String key) {
final Tag tag = this.value.get(key);
final Tag tag = value.get(key);
if (tag instanceof ListTag) {
return ((ListTag) tag).getValue();
} else {
@ -250,7 +250,7 @@ public final class CompoundTag extends Tag {
* @return a tag list instance
*/
public ListTag getListTag(final String key) {
final Tag tag = this.value.get(key);
final Tag tag = value.get(key);
if (tag instanceof ListTag) {
return (ListTag) tag;
} else {
@ -271,7 +271,7 @@ public final class CompoundTag extends Tag {
*/
@SuppressWarnings("unchecked")
public <T extends Tag> List<T> getList(final String key, final Class<T> listType) {
final Tag tag = this.value.get(key);
final Tag tag = value.get(key);
if (tag instanceof ListTag) {
final ListTag listTag = (ListTag) tag;
if (listTag.getType().equals(listType)) {
@ -293,7 +293,7 @@ public final class CompoundTag extends Tag {
* @return a long
*/
public long getLong(final String key) {
final Tag tag = this.value.get(key);
final Tag tag = value.get(key);
if (tag instanceof LongTag) {
return ((LongTag) tag).getValue();
} else {
@ -310,7 +310,7 @@ public final class CompoundTag extends Tag {
* @return a long
*/
public long asLong(final String key) {
final Tag tag = this.value.get(key);
final Tag tag = value.get(key);
if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue();
} else if (tag instanceof ShortTag) {
@ -337,7 +337,7 @@ public final class CompoundTag extends Tag {
* @return a short
*/
public short getShort(final String key) {
final Tag tag = this.value.get(key);
final Tag tag = value.get(key);
if (tag instanceof ShortTag) {
return ((ShortTag) tag).getValue();
} else {
@ -354,7 +354,7 @@ public final class CompoundTag extends Tag {
* @return a string
*/
public String getString(final String key) {
final Tag tag = this.value.get(key);
final Tag tag = value.get(key);
if (tag instanceof StringTag) {
return ((StringTag) tag).getValue();
} else {
@ -367,11 +367,11 @@ public final class CompoundTag extends Tag {
final String name = getName();
String append = "";
if ((name != null) && !name.equals("")) {
append = "(\"" + this.getName() + "\")";
append = "(\"" + getName() + "\")";
}
final StringBuilder bldr = new StringBuilder();
bldr.append("TAG_Compound").append(append).append(": ").append(this.value.size()).append(" entries\r\n{\r\n");
for (final Map.Entry<String, Tag> entry : this.value.entrySet()) {
bldr.append("TAG_Compound").append(append).append(": ").append(value.size()).append(" entries\r\n{\r\n");
for (final Map.Entry<String, Tag> entry : value.entrySet()) {
bldr.append(" ").append(entry.getValue().toString().replaceAll("\r\n", "\r\n ")).append("\r\n");
}
bldr.append("}");

View File

@ -15,7 +15,7 @@ public class CompoundTagBuilder {
* Create a new instance.
*/
CompoundTagBuilder() {
this.entries = new HashMap<String, Tag>();
entries = new HashMap<String, Tag>();
}
/**
@ -25,7 +25,7 @@ public class CompoundTagBuilder {
*/
CompoundTagBuilder(final Map<String, Tag> value) {
checkNotNull(value);
this.entries = value;
entries = value;
}
/**
@ -48,7 +48,7 @@ public class CompoundTagBuilder {
public CompoundTagBuilder put(final String key, final Tag value) {
checkNotNull(key);
checkNotNull(value);
this.entries.put(key, value);
entries.put(key, value);
return this;
}
@ -181,7 +181,7 @@ public class CompoundTagBuilder {
* @return the new compound tag
*/
public CompoundTag build() {
return new CompoundTag(new HashMap<String, Tag>(this.entries));
return new CompoundTag(new HashMap<String, Tag>(entries));
}
/**
@ -192,6 +192,6 @@ public class CompoundTagBuilder {
* @return the created compound tag
*/
public CompoundTag build(final String name) {
return new CompoundTag(name, new HashMap<String, Tag>(this.entries));
return new CompoundTag(name, new HashMap<String, Tag>(entries));
}
}

View File

@ -29,7 +29,7 @@ public final class DoubleTag extends Tag {
@Override
public Double getValue() {
return this.value;
return value;
}
@Override
@ -37,8 +37,8 @@ public final class DoubleTag extends Tag {
final String name = getName();
String append = "";
if ((name != null) && !name.equals("")) {
append = "(\"" + this.getName() + "\")";
append = "(\"" + getName() + "\")";
}
return "TAG_Double" + append + ": " + this.value;
return "TAG_Double" + append + ": " + value;
}
}

View File

@ -29,7 +29,7 @@ public final class FloatTag extends Tag {
@Override
public Float getValue() {
return this.value;
return value;
}
@Override
@ -37,8 +37,8 @@ public final class FloatTag extends Tag {
final String name = getName();
String append = "";
if ((name != null) && !name.equals("")) {
append = "(\"" + this.getName() + "\")";
append = "(\"" + getName() + "\")";
}
return "TAG_Float" + append + ": " + this.value;
return "TAG_Float" + append + ": " + value;
}
}

View File

@ -33,13 +33,13 @@ public final class IntArrayTag extends Tag {
@Override
public int[] getValue() {
return this.value;
return value;
}
@Override
public String toString() {
final StringBuilder hex = new StringBuilder();
for (final int b : this.value) {
for (final int b : value) {
final String hexDigits = Integer.toHexString(b).toUpperCase();
if (hexDigits.length() == 1) {
hex.append("0");
@ -49,7 +49,7 @@ public final class IntArrayTag extends Tag {
final String name = getName();
String append = "";
if ((name != null) && !name.equals("")) {
append = "(\"" + this.getName() + "\")";
append = "(\"" + getName() + "\")";
}
return "TAG_Int_Array" + append + ": " + hex;
}

View File

@ -29,7 +29,7 @@ public final class IntTag extends Tag {
@Override
public Integer getValue() {
return this.value;
return value;
}
@Override
@ -37,8 +37,8 @@ public final class IntTag extends Tag {
final String name = getName();
String append = "";
if ((name != null) && !name.equals("")) {
append = "(\"" + this.getName() + "\")";
append = "(\"" + getName() + "\")";
}
return "TAG_Int" + append + ": " + this.value;
return "TAG_Int" + append + ": " + value;
}
}

View File

@ -6,7 +6,6 @@ import java.util.Collections;
import java.util.List;
import java.util.NoSuchElementException;
/**
* The {@code TAG_List} tag.
*/
@ -47,12 +46,12 @@ public final class ListTag extends Tag {
* @return The type of item in this list.
*/
public Class<? extends Tag> getType() {
return this.type;
return type;
}
@Override
public List<Tag> getValue() {
return this.value;
return value;
}
/**
@ -75,7 +74,7 @@ public final class ListTag extends Tag {
*/
public Tag getIfExists(final int index) {
try {
return this.value.get(index);
return value.get(index);
} catch (final NoSuchElementException e) {
return null;
}
@ -380,11 +379,11 @@ public final class ListTag extends Tag {
final String name = getName();
String append = "";
if ((name != null) && !name.equals("")) {
append = "(\"" + this.getName() + "\")";
append = "(\"" + getName() + "\")";
}
final StringBuilder bldr = new StringBuilder();
bldr.append("TAG_List").append(append).append(": ").append(this.value.size()).append(" entries of type ").append(NBTUtils.getTypeName(this.type)).append("\r\n{\r\n");
for (final Tag t : this.value) {
bldr.append("TAG_List").append(append).append(": ").append(value.size()).append(" entries of type ").append(NBTUtils.getTypeName(type)).append("\r\n{\r\n");
for (final Tag t : value) {
bldr.append(" ").append(t.toString().replaceAll("\r\n", "\r\n ")).append("\r\n");
}
bldr.append("}");

View File

@ -22,7 +22,7 @@ public class ListTagBuilder {
ListTagBuilder(final Class<? extends Tag> type) {
checkNotNull(type);
this.type = type;
this.entries = new ArrayList<Tag>();
entries = new ArrayList<Tag>();
}
/**
@ -70,10 +70,10 @@ public class ListTagBuilder {
*/
public ListTagBuilder add(final Tag value) {
checkNotNull(value);
if (!this.type.isInstance(value)) {
throw new IllegalArgumentException(value.getClass().getCanonicalName() + " is not of expected type " + this.type.getCanonicalName());
if (!type.isInstance(value)) {
throw new IllegalArgumentException(value.getClass().getCanonicalName() + " is not of expected type " + type.getCanonicalName());
}
this.entries.add(value);
entries.add(value);
return this;
}
@ -98,7 +98,7 @@ public class ListTagBuilder {
* @return the new list tag
*/
public ListTag build() {
return new ListTag(this.type, new ArrayList<Tag>(this.entries));
return new ListTag(type, new ArrayList<Tag>(entries));
}
/**
@ -109,6 +109,6 @@ public class ListTagBuilder {
* @return the created list tag
*/
public ListTag build(final String name) {
return new ListTag(name, this.type, new ArrayList<Tag>(this.entries));
return new ListTag(name, type, new ArrayList<Tag>(entries));
}
}

View File

@ -29,7 +29,7 @@ public final class LongTag extends Tag {
@Override
public Long getValue() {
return this.value;
return value;
}
@Override
@ -37,8 +37,8 @@ public final class LongTag extends Tag {
final String name = getName();
String append = "";
if ((name != null) && !name.equals("")) {
append = "(\"" + this.getName() + "\")";
append = "(\"" + getName() + "\")";
}
return "TAG_Long" + append + ": " + this.value;
return "TAG_Long" + append + ": " + value;
}
}

View File

@ -21,19 +21,21 @@
package com.intellectualcrafters.jnbt;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
/**
* A class which holds constant values.
*/
public final class NBTConstants {
public static final Charset CHARSET = Charset.forName("UTF-8");
public static final int TYPE_END = 0, TYPE_BYTE = 1, TYPE_SHORT = 2, TYPE_INT = 3, TYPE_LONG = 4, TYPE_FLOAT = 5, TYPE_DOUBLE = 6, TYPE_BYTE_ARRAY = 7, TYPE_STRING = 8, TYPE_LIST = 9, TYPE_COMPOUND = 10, TYPE_INT_ARRAY = 11;
public static final Charset CHARSET = StandardCharsets.UTF_8;
public static final int TYPE_END = 0, TYPE_BYTE = 1, TYPE_SHORT = 2, TYPE_INT = 3, TYPE_LONG = 4, TYPE_FLOAT = 5, TYPE_DOUBLE = 6, TYPE_BYTE_ARRAY = 7, TYPE_STRING = 8, TYPE_LIST = 9,
TYPE_COMPOUND = 10, TYPE_INT_ARRAY = 11;
/**
* Default private constructor.
*/
private NBTConstants() {
}
private NBTConstants() {}
/**
* Convert a type ID to its corresponding {@link Tag} class.

View File

@ -26,7 +26,7 @@ public final class NBTInputStream implements Closeable {
*
* @throws IOException if an I/O error occurs
*/
public NBTInputStream(final InputStream is) throws IOException {
public NBTInputStream(final InputStream is) {
this.is = new DataInputStream(is);
}
@ -48,7 +48,7 @@ public final class NBTInputStream implements Closeable {
*
* @throws IOException if an I/O error occurs.
*/
public Tag readTag(int maxDepth) throws IOException {
public Tag readTag(final int maxDepth) throws IOException {
return readTag(0, maxDepth);
}
@ -61,14 +61,16 @@ public final class NBTInputStream implements Closeable {
*
* @throws IOException if an I/O error occurs.
*/
private Tag readTag(final int depth, int maxDepth) throws IOException {
if ((count++) > maxDepth) throw new IOException("Exceeds max depth: " + count);
final int type = this.is.readByte() & 0xFF;
private Tag readTag(final int depth, final int maxDepth) throws IOException {
if ((count++) > maxDepth) {
throw new IOException("Exceeds max depth: " + count);
}
final int type = is.readByte() & 0xFF;
String name;
if (type != NBTConstants.TYPE_END) {
final int nameLength = this.is.readShort() & 0xFFFF;
final int nameLength = is.readShort() & 0xFFFF;
final byte[] nameBytes = new byte[nameLength];
this.is.readFully(nameBytes);
is.readFully(nameBytes);
name = new String(nameBytes, NBTConstants.CHARSET);
} else {
name = "";
@ -87,8 +89,10 @@ public final class NBTInputStream implements Closeable {
*
* @throws IOException if an I/O error occurs.
*/
private Tag readTagPayload(final int type, final String name, final int depth, int maxDepth) throws IOException {
if ((count++) > maxDepth) throw new IOException("Exceeds max depth: " + count);
private Tag readTagPayload(final int type, final String name, final int depth, final int maxDepth) throws IOException {
if ((count++) > maxDepth) {
throw new IOException("Exceeds max depth: " + count);
}
count++;
switch (type) {
case NBTConstants.TYPE_END:
@ -98,44 +102,50 @@ public final class NBTInputStream implements Closeable {
return new EndTag();
}
case NBTConstants.TYPE_BYTE:
return new ByteTag(name, this.is.readByte());
return new ByteTag(name, is.readByte());
case NBTConstants.TYPE_SHORT:
return new ShortTag(name, this.is.readShort());
return new ShortTag(name, is.readShort());
case NBTConstants.TYPE_INT:
return new IntTag(name, this.is.readInt());
return new IntTag(name, is.readInt());
case NBTConstants.TYPE_LONG:
return new LongTag(name, this.is.readLong());
return new LongTag(name, is.readLong());
case NBTConstants.TYPE_FLOAT:
return new FloatTag(name, this.is.readFloat());
return new FloatTag(name, is.readFloat());
case NBTConstants.TYPE_DOUBLE:
return new DoubleTag(name, this.is.readDouble());
return new DoubleTag(name, is.readDouble());
case NBTConstants.TYPE_BYTE_ARRAY:
int length = this.is.readInt();
int length = is.readInt();
// Max depth
if ((count += length) > maxDepth) throw new IOException("Exceeds max depth: " + count);
if ((count += length) > maxDepth) {
throw new IOException("Exceeds max depth: " + count);
//
}
byte[] bytes = new byte[length];
this.is.readFully(bytes);
is.readFully(bytes);
return new ByteArrayTag(name, bytes);
case NBTConstants.TYPE_STRING:
length = this.is.readShort();
length = is.readShort();
// Max depth
if ((count += length) > maxDepth) throw new IOException("Exceeds max depth: " + count);
if ((count += length) > maxDepth) {
throw new IOException("Exceeds max depth: " + count);
//
}
bytes = new byte[length];
this.is.readFully(bytes);
is.readFully(bytes);
return new StringTag(name, new String(bytes, NBTConstants.CHARSET));
case NBTConstants.TYPE_LIST:
final int childType = this.is.readByte();
length = this.is.readInt();
final int childType = is.readByte();
length = is.readInt();
// Max depth
if ((count += length) > maxDepth) throw new IOException("Exceeds max depth: " + count);
if ((count += length) > maxDepth) {
throw new IOException("Exceeds max depth: " + count);
//
}
final List<Tag> tagList = new ArrayList<Tag>();
for (int i = 0; i < length; ++i) {
@ -158,13 +168,15 @@ public final class NBTInputStream implements Closeable {
}
return new CompoundTag(name, tagMap);
case NBTConstants.TYPE_INT_ARRAY:
length = this.is.readInt();
length = is.readInt();
// Max depth
if ((count += length) > maxDepth) throw new IOException("Exceeds max depth: " + count);
if ((count += length) > maxDepth) {
throw new IOException("Exceeds max depth: " + count);
}
//
final int[] data = new int[length];
for (int i = 0; i < length; i++) {
data[i] = this.is.readInt();
data[i] = is.readInt();
}
return new IntArrayTag(name, data);
default:
@ -174,6 +186,6 @@ public final class NBTInputStream implements Closeable {
@Override
public void close() throws IOException {
this.is.close();
is.close();
}
}

View File

@ -48,7 +48,7 @@ public final class NBTOutputStream implements Closeable {
*
* @throws IOException if an I/O error occurs.
*/
public NBTOutputStream(final OutputStream os) throws IOException {
public NBTOutputStream(final OutputStream os) {
this.os = new DataOutputStream(os);
}
@ -63,9 +63,9 @@ public final class NBTOutputStream implements Closeable {
final int type = NBTUtils.getTypeCode(tag.getClass());
final String name = tag.getName();
final byte[] nameBytes = name.getBytes(NBTConstants.CHARSET);
this.os.writeByte(type);
this.os.writeShort(nameBytes.length);
this.os.write(nameBytes);
os.writeByte(type);
os.writeShort(nameBytes.length);
os.write(nameBytes);
if (type == NBTConstants.TYPE_END) {
throw new IOException("Named TAG_End not permitted.");
}
@ -131,7 +131,7 @@ public final class NBTOutputStream implements Closeable {
* @throws IOException if an I/O error occurs.
*/
private void writeByteTagPayload(final ByteTag tag) throws IOException {
this.os.writeByte(tag.getValue());
os.writeByte(tag.getValue());
}
/**
@ -143,8 +143,8 @@ public final class NBTOutputStream implements Closeable {
*/
private void writeByteArrayTagPayload(final ByteArrayTag tag) throws IOException {
final byte[] bytes = tag.getValue();
this.os.writeInt(bytes.length);
this.os.write(bytes);
os.writeInt(bytes.length);
os.write(bytes);
}
/**
@ -158,7 +158,7 @@ public final class NBTOutputStream implements Closeable {
for (final Tag childTag : tag.getValue().values()) {
writeTag(childTag);
}
this.os.writeByte((byte) 0); // end tag - better way?
os.writeByte((byte) 0); // end tag - better way?
}
/**
@ -172,8 +172,8 @@ public final class NBTOutputStream implements Closeable {
final Class<? extends Tag> clazz = tag.getType();
final List<Tag> tags = tag.getValue();
final int size = tags.size();
this.os.writeByte(NBTUtils.getTypeCode(clazz));
this.os.writeInt(size);
os.writeByte(NBTUtils.getTypeCode(clazz));
os.writeInt(size);
for (final Tag tag1 : tags) {
writeTagPayload(tag1);
}
@ -188,8 +188,8 @@ public final class NBTOutputStream implements Closeable {
*/
private void writeStringTagPayload(final StringTag tag) throws IOException {
final byte[] bytes = tag.getValue().getBytes(NBTConstants.CHARSET);
this.os.writeShort(bytes.length);
this.os.write(bytes);
os.writeShort(bytes.length);
os.write(bytes);
}
/**
@ -200,7 +200,7 @@ public final class NBTOutputStream implements Closeable {
* @throws IOException if an I/O error occurs.
*/
private void writeDoubleTagPayload(final DoubleTag tag) throws IOException {
this.os.writeDouble(tag.getValue());
os.writeDouble(tag.getValue());
}
/**
@ -211,7 +211,7 @@ public final class NBTOutputStream implements Closeable {
* @throws IOException if an I/O error occurs.
*/
private void writeFloatTagPayload(final FloatTag tag) throws IOException {
this.os.writeFloat(tag.getValue());
os.writeFloat(tag.getValue());
}
/**
@ -222,7 +222,7 @@ public final class NBTOutputStream implements Closeable {
* @throws IOException if an I/O error occurs.
*/
private void writeLongTagPayload(final LongTag tag) throws IOException {
this.os.writeLong(tag.getValue());
os.writeLong(tag.getValue());
}
/**
@ -233,7 +233,7 @@ public final class NBTOutputStream implements Closeable {
* @throws IOException if an I/O error occurs.
*/
private void writeIntTagPayload(final IntTag tag) throws IOException {
this.os.writeInt(tag.getValue());
os.writeInt(tag.getValue());
}
/**
@ -244,7 +244,7 @@ public final class NBTOutputStream implements Closeable {
* @throws IOException if an I/O error occurs.
*/
private void writeShortTagPayload(final ShortTag tag) throws IOException {
this.os.writeShort(tag.getValue());
os.writeShort(tag.getValue());
}
/**
@ -260,15 +260,15 @@ public final class NBTOutputStream implements Closeable {
private void writeIntArrayTagPayload(final IntArrayTag tag) throws IOException {
final int[] data = tag.getValue();
this.os.writeInt(data.length);
os.writeInt(data.length);
for (final int element : data) {
this.os.writeInt(element);
os.writeInt(element);
}
}
@Override
public void close() throws IOException {
this.os.close();
os.close();
}
/**
@ -276,6 +276,6 @@ public final class NBTOutputStream implements Closeable {
* @throws IOException
*/
public void flush() throws IOException {
this.os.flush();
os.flush();
}
}

View File

@ -9,8 +9,7 @@ public final class NBTUtils {
/**
* Default private constructor.
*/
private NBTUtils() {
}
private NBTUtils() {}
/**
* Gets the type name of a tag.
@ -45,7 +44,7 @@ public final class NBTUtils {
} else if (clazz.equals(IntArrayTag.class)) {
return "TAG_Int_Array";
} else {
throw new IllegalArgumentException("Invalid tag classs (" + clazz.getName() + ").");
throw new IllegalArgumentException("Invalid tag class (" + clazz.getName() + ").");
}
}
@ -84,7 +83,7 @@ public final class NBTUtils {
} else if (clazz.equals(IntArrayTag.class)) {
return NBTConstants.TYPE_INT_ARRAY;
} else {
throw new IllegalArgumentException("Invalid tag classs (" + clazz.getName() + ").");
throw new IllegalArgumentException("Invalid tag class (" + clazz.getName() + ").");
}
}

View File

@ -49,7 +49,7 @@ public final class ShortTag extends Tag {
@Override
public Short getValue() {
return this.value;
return value;
}
@Override
@ -57,8 +57,8 @@ public final class ShortTag extends Tag {
final String name = getName();
String append = "";
if ((name != null) && !name.equals("")) {
append = "(\"" + this.getName() + "\")";
append = "(\"" + getName() + "\")";
}
return "TAG_Short" + append + ": " + this.value;
return "TAG_Short" + append + ": " + value;
}
}

View File

@ -33,7 +33,7 @@ public final class StringTag extends Tag {
@Override
public String getValue() {
return this.value;
return value;
}
@Override
@ -41,8 +41,8 @@ public final class StringTag extends Tag {
final String name = getName();
String append = "";
if ((name != null) && !name.equals("")) {
append = "(\"" + this.getName() + "\")";
append = "(\"" + getName() + "\")";
}
return "TAG_String" + append + ": " + this.value;
return "TAG_String" + append + ": " + value;
}
}

View File

@ -51,7 +51,7 @@ public abstract class Tag {
* @return the name of this tag
*/
public final String getName() {
return this.name;
return name;
}
/**

View File

@ -75,7 +75,7 @@ public class CDL {
for (;;) {
final String value = getValue(x);
char c = x.next();
if ((value == null) || ((ja.length() == 0) && (value.length() == 0) && (c != ','))) {
if ((value == null) || ((ja.length() == 0) && (value.isEmpty()) && (c != ','))) {
return null;
}
ja.put(value);
@ -128,7 +128,8 @@ public class CDL {
final Object object = ja.opt(i);
if (object != null) {
final String string = object.toString();
if ((string.length() > 0) && ((string.indexOf(',') >= 0) || (string.indexOf('\n') >= 0) || (string.indexOf('\r') >= 0) || (string.indexOf(0) >= 0) || (string.charAt(0) == '"'))) {
if ((!string.isEmpty()) && ((string.indexOf(',') >= 0) || (string.indexOf('\n') >= 0) || (string.indexOf('\r') >= 0) || (
string.indexOf(0) >= 0) || (string.charAt(0) == '"'))) {
sb.append('"');
final int length = string.length();
for (int j = 0; j < length; j += 1) {

View File

@ -66,7 +66,7 @@ public class JSONArray {
* Construct an empty JSONArray.
*/
public JSONArray() {
this.myArrayList = new ArrayList<Object>();
myArrayList = new ArrayList<Object>();
}
/**
@ -86,10 +86,10 @@ public class JSONArray {
for (;;) {
if (x.nextClean() == ',') {
x.back();
this.myArrayList.add(JSONObject.NULL);
myArrayList.add(JSONObject.NULL);
} else {
x.back();
this.myArrayList.add(x.nextValue());
myArrayList.add(x.nextValue());
}
switch (x.nextClean()) {
case ',':
@ -125,10 +125,10 @@ public class JSONArray {
* @param collection A Collection.
*/
public JSONArray(final Collection<Object> collection) {
this.myArrayList = new ArrayList<Object>();
myArrayList = new ArrayList<Object>();
if (collection != null) {
for (final Object aCollection : collection) {
this.myArrayList.add(JSONObject.wrap(aCollection));
myArrayList.add(JSONObject.wrap(aCollection));
}
}
}
@ -160,7 +160,7 @@ public class JSONArray {
* @throws JSONException If there is no value for the index.
*/
public Object get(final int index) throws JSONException {
final Object object = this.opt(index);
final Object object = opt(index);
if (object == null) {
throw new JSONException("JSONArray[" + index + "] not found.");
}
@ -177,7 +177,7 @@ public class JSONArray {
* @throws JSONException If there is no value for the index or if the value is not convertible to boolean.
*/
public boolean getBoolean(final int index) throws JSONException {
final Object object = this.get(index);
final Object object = get(index);
if (object.equals(Boolean.FALSE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("false"))) {
return false;
} else if (object.equals(Boolean.TRUE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("true"))) {
@ -196,10 +196,10 @@ public class JSONArray {
* @throws JSONException If the key is not found or if the value cannot be converted to a number.
*/
public double getDouble(final int index) throws JSONException {
final Object object = this.get(index);
final Object object = get(index);
try {
return object instanceof Number ? ((Number) object).doubleValue() : Double.parseDouble((String) object);
} catch (final Exception e) {
} catch (NumberFormatException e) {
throw new JSONException("JSONArray[" + index + "] is not a number.");
}
}
@ -214,10 +214,10 @@ public class JSONArray {
* @throws JSONException If the key is not found or if the value is not a number.
*/
public int getInt(final int index) throws JSONException {
final Object object = this.get(index);
final Object object = get(index);
try {
return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object);
} catch (final Exception e) {
} catch (NumberFormatException e) {
throw new JSONException("JSONArray[" + index + "] is not a number.");
}
}
@ -232,7 +232,7 @@ public class JSONArray {
* @throws JSONException If there is no value for the index. or if the value is not a JSONArray
*/
public JSONArray getJSONArray(final int index) throws JSONException {
final Object object = this.get(index);
final Object object = get(index);
if (object instanceof JSONArray) {
return (JSONArray) object;
}
@ -249,7 +249,7 @@ public class JSONArray {
* @throws JSONException If there is no value for the index or if the value is not a JSONObject
*/
public JSONObject getJSONObject(final int index) throws JSONException {
final Object object = this.get(index);
final Object object = get(index);
if (object instanceof JSONObject) {
return (JSONObject) object;
}
@ -266,10 +266,10 @@ public class JSONArray {
* @throws JSONException If the key is not found or if the value cannot be converted to a number.
*/
public long getLong(final int index) throws JSONException {
final Object object = this.get(index);
final Object object = get(index);
try {
return object instanceof Number ? ((Number) object).longValue() : Long.parseLong((String) object);
} catch (final Exception e) {
} catch (NumberFormatException e) {
throw new JSONException("JSONArray[" + index + "] is not a number.");
}
}
@ -284,7 +284,7 @@ public class JSONArray {
* @throws JSONException If there is no string value for the index.
*/
public String getString(final int index) throws JSONException {
final Object object = this.get(index);
final Object object = get(index);
if (object instanceof String) {
return (String) object;
}
@ -299,7 +299,7 @@ public class JSONArray {
* @return true if the value at the index is null, or if there is no value.
*/
public boolean isNull(final int index) {
return JSONObject.NULL.equals(this.opt(index));
return JSONObject.NULL.equals(opt(index));
}
/**
@ -313,13 +313,13 @@ public class JSONArray {
* @throws JSONException If the array contains an invalid number.
*/
public String join(final String separator) throws JSONException {
final int len = this.length();
final int len = length();
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i += 1) {
if (i > 0) {
sb.append(separator);
}
sb.append(JSONObject.valueToString(this.myArrayList.get(i)));
sb.append(JSONObject.valueToString(myArrayList.get(i)));
}
return sb.toString();
}
@ -330,7 +330,7 @@ public class JSONArray {
* @return The length (or size).
*/
public int length() {
return this.myArrayList.size();
return myArrayList.size();
}
/**
@ -341,7 +341,7 @@ public class JSONArray {
* @return An object value, or null if there is no object at that index.
*/
public Object opt(final int index) {
return ((index < 0) || (index >= this.length())) ? null : this.myArrayList.get(index);
return ((index < 0) || (index >= length())) ? null : myArrayList.get(index);
}
/**
@ -367,8 +367,8 @@ public class JSONArray {
*/
public boolean optBoolean(final int index, final boolean defaultValue) {
try {
return this.getBoolean(index);
} catch (final Exception e) {
return getBoolean(index);
} catch (JSONException e) {
return defaultValue;
}
}
@ -396,8 +396,8 @@ public class JSONArray {
*/
public double optDouble(final int index, final double defaultValue) {
try {
return this.getDouble(index);
} catch (final Exception e) {
return getDouble(index);
} catch (JSONException e) {
return defaultValue;
}
}
@ -425,8 +425,8 @@ public class JSONArray {
*/
public int optInt(final int index, final int defaultValue) {
try {
return this.getInt(index);
} catch (final Exception e) {
return getInt(index);
} catch (JSONException e) {
return defaultValue;
}
}
@ -439,7 +439,7 @@ public class JSONArray {
* @return A JSONArray value, or null if the index has no value, or if the value is not a JSONArray.
*/
public JSONArray optJSONArray(final int index) {
final Object o = this.opt(index);
final Object o = opt(index);
return o instanceof JSONArray ? (JSONArray) o : null;
}
@ -452,7 +452,7 @@ public class JSONArray {
* @return A JSONObject value.
*/
public JSONObject optJSONObject(final int index) {
final Object o = this.opt(index);
final Object o = opt(index);
return o instanceof JSONObject ? (JSONObject) o : null;
}
@ -479,8 +479,8 @@ public class JSONArray {
*/
public long optLong(final int index, final long defaultValue) {
try {
return this.getLong(index);
} catch (final Exception e) {
return getLong(index);
} catch (JSONException e) {
return defaultValue;
}
}
@ -506,7 +506,7 @@ public class JSONArray {
* @return A String value.
*/
public String optString(final int index, final String defaultValue) {
final Object object = this.opt(index);
final Object object = opt(index);
return JSONObject.NULL.equals(object) ? defaultValue : object.toString();
}
@ -595,7 +595,7 @@ public class JSONArray {
* @return this.
*/
public JSONArray put(final Object value) {
this.myArrayList.add(value);
myArrayList.add(value);
return this;
}
@ -710,10 +710,10 @@ public class JSONArray {
if (index < 0) {
throw new JSONException("JSONArray[" + index + "] not found.");
}
if (index < this.length()) {
this.myArrayList.set(index, value);
if (index < length()) {
myArrayList.set(index, value);
} else {
while (index != this.length()) {
while (index != length()) {
this.put(JSONObject.NULL);
}
this.put(value);
@ -729,7 +729,7 @@ public class JSONArray {
* @return The value that was associated with the index, or null if there was no value.
*/
public Object remove(final int index) {
return (index >= 0) && (index < this.length()) ? this.myArrayList.remove(index) : null;
return (index >= 0) && (index < length()) ? myArrayList.remove(index) : null;
}
/**
@ -743,12 +743,12 @@ public class JSONArray {
if (!(other instanceof JSONArray)) {
return false;
}
final int len = this.length();
final int len = length();
if (len != ((JSONArray) other).length()) {
return false;
}
for (int i = 0; i < len; i += 1) {
final Object valueThis = this.get(i);
final Object valueThis = get(i);
final Object valueOther = ((JSONArray) other).get(i);
if (valueThis instanceof JSONObject) {
if (!((JSONObject) valueThis).similar(valueOther)) {
@ -775,12 +775,12 @@ public class JSONArray {
* @throws JSONException If any of the names are null.
*/
public JSONObject toJSONObject(final JSONArray names) throws JSONException {
if ((names == null) || (names.length() == 0) || (this.length() == 0)) {
if ((names == null) || (names.length() == 0) || (length() == 0)) {
return null;
}
final JSONObject jo = new JSONObject();
for (int i = 0; i < names.length(); i += 1) {
jo.put(names.getString(i), this.opt(i));
jo.put(names.getString(i), opt(i));
}
return jo;
}
@ -798,7 +798,7 @@ public class JSONArray {
public String toString() {
try {
return this.toString(0);
} catch (final Exception e) {
} catch (JSONException e) {
return null;
}
}
@ -850,10 +850,10 @@ public class JSONArray {
Writer write(final Writer writer, final int indentFactor, final int indent) throws JSONException {
try {
boolean commanate = false;
final int length = this.length();
final int length = length();
writer.write('[');
if (length == 1) {
JSONObject.writeValue(writer, this.myArrayList.get(0), indentFactor, indent);
JSONObject.writeValue(writer, myArrayList.get(0), indentFactor, indent);
} else if (length != 0) {
final int newindent = indent + indentFactor;
for (int i = 0; i < length; i += 1) {
@ -864,7 +864,7 @@ public class JSONArray {
writer.write('\n');
}
JSONObject.indent(writer, newindent);
JSONObject.writeValue(writer, this.myArrayList.get(i), indentFactor, newindent);
JSONObject.writeValue(writer, myArrayList.get(i), indentFactor, newindent);
commanate = true;
}
if (indentFactor > 0) {

View File

@ -36,6 +36,6 @@ public class JSONException extends RuntimeException {
*/
@Override
public Throwable getCause() {
return this.cause;
return cause;
}
}

View File

@ -4,6 +4,7 @@ import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collection;
@ -69,7 +70,7 @@ public class JSONObject {
* Construct an empty JSONObject.
*/
public JSONObject() {
this.map = new HashMap<String, Object>();
map = new HashMap<String, Object>();
}
/**
@ -86,8 +87,8 @@ public class JSONObject {
this();
for (final String name : names) {
try {
this.putOnce(name, jo.opt(name));
} catch (final Exception ignore) {
putOnce(name, jo.opt(name));
} catch (JSONException ignore) {
}
}
}
@ -122,7 +123,7 @@ public class JSONObject {
if (c != ':') {
throw x.syntaxError("Expected a ':' after a key");
}
this.putOnce(key, x.nextValue());
putOnce(key, x.nextValue());
// Pairs are separated by ','.
switch (x.nextClean()) {
case ';':
@ -176,7 +177,7 @@ public class JSONObject {
*/
public JSONObject(final Object bean) {
this();
this.populateMap(bean);
populateMap(bean);
}
/**
@ -192,8 +193,8 @@ public class JSONObject {
final Class c = object.getClass();
for (final String name : names) {
try {
this.putOpt(name, c.getField(name).get(object));
} catch (final Exception ignore) {
putOpt(name, c.getField(name).get(object));
} catch (JSONException | SecurityException | NoSuchFieldException | IllegalArgumentException | IllegalAccessException ignore) {
}
}
}
@ -362,7 +363,7 @@ public class JSONObject {
}
public static Writer quote(final String string, final Writer w) throws IOException {
if ((string == null) || (string.length() == 0)) {
if ((string == null) || (string.isEmpty())) {
w.write("\"\"");
return w;
}
@ -460,7 +461,7 @@ public class JSONObject {
}
}
}
} catch (final Exception ignore) {
} catch (NumberFormatException ignore) {
}
}
return string;
@ -517,7 +518,7 @@ public class JSONObject {
} catch (final Exception e) {
throw new JSONException(e);
}
if (object instanceof String) {
if (object != null) {
return (String) object;
}
throw new JSONException("Bad value from toJSONString: " + object);
@ -555,7 +556,19 @@ public class JSONObject {
if (object == null) {
return NULL;
}
if ((object instanceof JSONObject) || (object instanceof JSONArray) || NULL.equals(object) || (object instanceof JSONString) || (object instanceof Byte) || (object instanceof Character) || (object instanceof Short) || (object instanceof Integer) || (object instanceof Long) || (object instanceof Boolean) || (object instanceof Float) || (object instanceof Double) || (object instanceof String)) {
if ((object instanceof JSONObject)
|| (object instanceof JSONArray)
|| NULL.equals(object)
|| (object instanceof JSONString)
|| (object instanceof Byte)
|| (object instanceof Character)
|| (object instanceof Short)
|| (object instanceof Integer)
|| (object instanceof Long)
|| (object instanceof Boolean)
|| (object instanceof Float)
|| (object instanceof Double)
|| (object instanceof String)) {
return object;
}
if (object instanceof Collection) {
@ -573,7 +586,7 @@ public class JSONObject {
return object.toString();
}
return new JSONObject(object);
} catch (final Exception exception) {
} catch (JSONException exception) {
return null;
}
}
@ -632,7 +645,7 @@ public class JSONObject {
*/
public JSONObject accumulate(final String key, final Object value) throws JSONException {
testValidity(value);
final Object object = this.opt(key);
final Object object = opt(key);
if (object == null) {
this.put(key, value instanceof JSONArray ? new JSONArray().put(value) : value);
} else if (object instanceof JSONArray) {
@ -657,7 +670,7 @@ public class JSONObject {
*/
public JSONObject append(final String key, final Object value) throws JSONException {
testValidity(value);
final Object object = this.opt(key);
final Object object = opt(key);
if (object == null) {
this.put(key, new JSONArray().put(value));
} else if (object instanceof JSONArray) {
@ -681,7 +694,7 @@ public class JSONObject {
if (key == null) {
throw new JSONException("Null key.");
}
final Object object = this.opt(key);
final Object object = opt(key);
if (object == null) {
throw new JSONException("JSONObject[" + quote(key) + "] not found.");
}
@ -698,7 +711,7 @@ public class JSONObject {
* @throws JSONException if the value is not a Boolean or the String "true" or "false".
*/
public boolean getBoolean(final String key) throws JSONException {
final Object object = this.get(key);
final Object object = get(key);
if (object.equals(Boolean.FALSE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("false"))) {
return false;
} else if (object.equals(Boolean.TRUE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("true"))) {
@ -718,10 +731,10 @@ public class JSONObject {
* number.
*/
public double getDouble(final String key) throws JSONException {
final Object object = this.get(key);
final Object object = get(key);
try {
return object instanceof Number ? ((Number) object).doubleValue() : Double.parseDouble((String) object);
} catch (final Exception e) {
} catch (NumberFormatException e) {
throw new JSONException("JSONObject[" + quote(key) + "] is not a number.");
}
}
@ -736,10 +749,10 @@ public class JSONObject {
* @throws JSONException if the key is not found or if the value cannot be converted to an integer.
*/
public int getInt(final String key) throws JSONException {
final Object object = this.get(key);
final Object object = get(key);
try {
return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object);
} catch (final Exception e) {
} catch (NumberFormatException e) {
throw new JSONException("JSONObject[" + quote(key) + "] is not an int.");
}
}
@ -754,7 +767,7 @@ public class JSONObject {
* @throws JSONException if the key is not found or if the value is not a JSONArray.
*/
public JSONArray getJSONArray(final String key) throws JSONException {
final Object object = this.get(key);
final Object object = get(key);
if (object instanceof JSONArray) {
return (JSONArray) object;
}
@ -771,7 +784,7 @@ public class JSONObject {
* @throws JSONException if the key is not found or if the value is not a JSONObject.
*/
public JSONObject getJSONObject(final String key) throws JSONException {
final Object object = this.get(key);
final Object object = get(key);
if (object instanceof JSONObject) {
return (JSONObject) object;
}
@ -788,10 +801,10 @@ public class JSONObject {
* @throws JSONException if the key is not found or if the value cannot be converted to a long.
*/
public long getLong(final String key) throws JSONException {
final Object object = this.get(key);
final Object object = get(key);
try {
return object instanceof Number ? ((Number) object).longValue() : Long.parseLong((String) object);
} catch (final Exception e) {
} catch (NumberFormatException e) {
throw new JSONException("JSONObject[" + quote(key) + "] is not a long.");
}
}
@ -806,7 +819,7 @@ public class JSONObject {
* @throws JSONException if there is no string value for the key.
*/
public String getString(final String key) throws JSONException {
final Object object = this.get(key);
final Object object = get(key);
if (object instanceof String) {
return (String) object;
}
@ -821,7 +834,7 @@ public class JSONObject {
* @return true if the key exists in the JSONObject.
*/
public boolean has(final String key) {
return this.map.containsKey(key);
return map.containsKey(key);
}
/**
@ -836,7 +849,7 @@ public class JSONObject {
* Float.
*/
public JSONObject increment(final String key) throws JSONException {
final Object value = this.opt(key);
final Object value = opt(key);
if (value == null) {
this.put(key, 1);
} else if (value instanceof Integer) {
@ -861,7 +874,7 @@ public class JSONObject {
* @return true if there is no value associated with the key or if the value is the JSONObject.NULL object.
*/
public boolean isNull(final String key) {
return JSONObject.NULL.equals(this.opt(key));
return JSONObject.NULL.equals(opt(key));
}
/**
@ -870,7 +883,7 @@ public class JSONObject {
* @return An iterator of the keys.
*/
public Iterator<String> keys() {
return this.keySet().iterator();
return keySet().iterator();
}
/**
@ -879,7 +892,7 @@ public class JSONObject {
* @return A keySet.
*/
public Set<String> keySet() {
return this.map.keySet();
return map.keySet();
}
/**
@ -888,7 +901,7 @@ public class JSONObject {
* @return The number of keys in the JSONObject.
*/
public int length() {
return this.map.size();
return map.size();
}
/**
@ -898,7 +911,7 @@ public class JSONObject {
*/
public JSONArray names() {
final JSONArray ja = new JSONArray();
final Iterator<String> keys = this.keys();
final Iterator<String> keys = keys();
while (keys.hasNext()) {
ja.put(keys.next());
}
@ -913,7 +926,7 @@ public class JSONObject {
* @return An object which is the value, or null if there is no value.
*/
public Object opt(final String key) {
return key == null ? null : this.map.get(key);
return key == null ? null : map.get(key);
}
/**
@ -939,8 +952,8 @@ public class JSONObject {
*/
public boolean optBoolean(final String key, final boolean defaultValue) {
try {
return this.getBoolean(key);
} catch (final Exception e) {
return getBoolean(key);
} catch (JSONException e) {
return defaultValue;
}
}
@ -968,8 +981,8 @@ public class JSONObject {
*/
public double optDouble(final String key, final double defaultValue) {
try {
return this.getDouble(key);
} catch (final Exception e) {
return getDouble(key);
} catch (JSONException e) {
return defaultValue;
}
}
@ -997,8 +1010,8 @@ public class JSONObject {
*/
public int optInt(final String key, final int defaultValue) {
try {
return this.getInt(key);
} catch (final Exception e) {
return getInt(key);
} catch (JSONException e) {
return defaultValue;
}
}
@ -1012,7 +1025,7 @@ public class JSONObject {
* @return A JSONArray which is the value.
*/
public JSONArray optJSONArray(final String key) {
final Object o = this.opt(key);
final Object o = opt(key);
return o instanceof JSONArray ? (JSONArray) o : null;
}
@ -1025,7 +1038,7 @@ public class JSONObject {
* @return A JSONObject which is the value.
*/
public JSONObject optJSONObject(final String key) {
final Object object = this.opt(key);
final Object object = opt(key);
return object instanceof JSONObject ? (JSONObject) object : null;
}
@ -1052,8 +1065,8 @@ public class JSONObject {
*/
public long optLong(final String key, final long defaultValue) {
try {
return this.getLong(key);
} catch (final Exception e) {
return getLong(key);
} catch (JSONException e) {
return defaultValue;
}
}
@ -1079,7 +1092,7 @@ public class JSONObject {
* @return A string which is the value.
*/
public String optString(final String key, final String defaultValue) {
final Object object = this.opt(key);
final Object object = opt(key);
return NULL.equals(object) ? defaultValue : object.toString();
}
@ -1102,7 +1115,7 @@ public class JSONObject {
} else if (name.startsWith("is")) {
key = name.substring(2);
}
if ((key.length() > 0) && Character.isUpperCase(key.charAt(0)) && (method.getParameterTypes().length == 0)) {
if ((!key.isEmpty()) && Character.isUpperCase(key.charAt(0)) && (method.getParameterTypes().length == 0)) {
if (key.length() == 1) {
key = key.toLowerCase();
} else if (!Character.isUpperCase(key.charAt(1))) {
@ -1110,11 +1123,11 @@ public class JSONObject {
}
final Object result = method.invoke(bean, (Object[]) null);
if (result != null) {
this.map.put(key, wrap(result));
map.put(key, wrap(result));
}
}
}
} catch (final Exception ignore) {
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ignore) {
}
}
}
@ -1227,9 +1240,9 @@ public class JSONObject {
}
if (value != null) {
testValidity(value);
this.map.put(key, value);
map.put(key, value);
} else {
this.remove(key);
remove(key);
}
return this;
}
@ -1247,7 +1260,7 @@ public class JSONObject {
*/
public JSONObject putOnce(final String key, final Object value) throws JSONException {
if ((key != null) && (value != null)) {
if (this.opt(key) != null) {
if (opt(key) != null) {
throw new JSONException("Duplicate key \"" + key + "\"");
}
this.put(key, value);
@ -1281,7 +1294,7 @@ public class JSONObject {
* @return The value that was associated with the name, or null if there was no value.
*/
public Object remove(final String key) {
return this.map.remove(key);
return map.remove(key);
}
/**
@ -1297,12 +1310,12 @@ public class JSONObject {
if (!(other instanceof JSONObject)) {
return false;
}
final Set<String> set = this.keySet();
final Set<String> set = keySet();
if (!set.equals(((JSONObject) other).keySet())) {
return false;
}
for (final String name : set) {
final Object valueThis = this.get(name);
final Object valueThis = get(name);
final Object valueOther = ((JSONObject) other).get(name);
if (valueThis instanceof JSONObject) {
if (!((JSONObject) valueThis).similar(valueOther)) {
@ -1338,7 +1351,7 @@ public class JSONObject {
}
final JSONArray ja = new JSONArray();
for (int i = 0; i < names.length(); i += 1) {
ja.put(this.opt(names.getString(i)));
ja.put(opt(names.getString(i)));
}
return ja;
}
@ -1357,7 +1370,7 @@ public class JSONObject {
public String toString() {
try {
return this.toString(0);
} catch (final Exception e) {
} catch (JSONException e) {
return null;
}
}
@ -1407,8 +1420,8 @@ public class JSONObject {
Writer write(final Writer writer, final int indentFactor, final int indent) throws JSONException {
try {
boolean commanate = false;
final int length = this.length();
final Iterator<String> keys = this.keys();
final int length = length();
final Iterator<String> keys = keys();
writer.write('{');
if (length == 1) {
final Object key = keys.next();
@ -1417,7 +1430,7 @@ public class JSONObject {
if (indentFactor > 0) {
writer.write(' ');
}
writeValue(writer, this.map.get(key), indentFactor, indent);
writeValue(writer, map.get(key), indentFactor, indent);
} else if (length != 0) {
final int newindent = indent + indentFactor;
while (keys.hasNext()) {
@ -1434,7 +1447,7 @@ public class JSONObject {
if (indentFactor > 0) {
writer.write(' ');
}
writeValue(writer, this.map.get(key), indentFactor, newindent);
writeValue(writer, map.get(key), indentFactor, newindent);
commanate = true;
}
if (indentFactor > 0) {
@ -1463,7 +1476,7 @@ public class JSONObject {
protected final Object clone() {
try {
return super.clone();
} catch (final Exception e) {
} catch (CloneNotSupportedException e) {
return this;
}
}

View File

@ -50,6 +50,6 @@ public class JSONStringer extends JSONWriter {
*/
@Override
public String toString() {
return this.mode == 'd' ? this.writer.toString() : null;
return mode == 'd' ? writer.toString() : null;
}
}

View File

@ -30,12 +30,12 @@ public class JSONTokener {
*/
public JSONTokener(final Reader reader) {
this.reader = reader.markSupported() ? reader : new BufferedReader(reader);
this.eof = false;
this.usePrevious = false;
this.previous = 0;
this.index = 0;
this.character = 1;
this.line = 1;
eof = false;
usePrevious = false;
previous = 0;
index = 0;
character = 1;
line = 1;
}
/**
@ -81,17 +81,17 @@ public class JSONTokener {
* before attempting to parse the next number or identifier.
*/
public void back() throws JSONException {
if (this.usePrevious || (this.index <= 0)) {
if (usePrevious || (index <= 0)) {
throw new JSONException("Stepping back two steps is not supported");
}
this.index -= 1;
this.character -= 1;
this.usePrevious = true;
this.eof = false;
index -= 1;
character -= 1;
usePrevious = true;
eof = false;
}
public boolean end() {
return this.eof && !this.usePrevious;
return eof && !usePrevious;
}
/**
@ -101,10 +101,10 @@ public class JSONTokener {
*/
public boolean more() throws JSONException {
this.next();
if (this.end()) {
if (end()) {
return false;
}
this.back();
back();
return true;
}
@ -115,32 +115,32 @@ public class JSONTokener {
*/
public char next() throws JSONException {
int c;
if (this.usePrevious) {
this.usePrevious = false;
c = this.previous;
if (usePrevious) {
usePrevious = false;
c = previous;
} else {
try {
c = this.reader.read();
c = reader.read();
} catch (final IOException exception) {
throw new JSONException(exception);
}
if (c <= 0) { // End of stream
this.eof = true;
eof = true;
c = 0;
}
}
this.index += 1;
if (this.previous == '\r') {
this.line += 1;
this.character = c == '\n' ? 0 : 1;
index += 1;
if (previous == '\r') {
line += 1;
character = c == '\n' ? 0 : 1;
} else if (c == '\n') {
this.line += 1;
this.character = 0;
line += 1;
character = 0;
} else {
this.character += 1;
character += 1;
}
this.previous = (char) c;
return this.previous;
previous = (char) c;
return previous;
}
/**
@ -155,7 +155,7 @@ public class JSONTokener {
public char next(final char c) throws JSONException {
final char n = this.next();
if (n != c) {
throw this.syntaxError("Expected '" + c + "' and instead saw '" + n + "'");
throw syntaxError("Expected '" + c + "' and instead saw '" + n + "'");
}
return n;
}
@ -177,8 +177,8 @@ public class JSONTokener {
int pos = 0;
while (pos < n) {
chars[pos] = this.next();
if (this.end()) {
throw this.syntaxError("Substring bounds error");
if (end()) {
throw syntaxError("Substring bounds error");
}
pos += 1;
}
@ -221,7 +221,7 @@ public class JSONTokener {
case 0:
case '\n':
case '\r':
throw this.syntaxError("Unterminated string");
throw syntaxError("Unterminated string");
case '\\':
c = this.next();
switch (c) {
@ -250,7 +250,7 @@ public class JSONTokener {
sb.append(c);
break;
default:
throw this.syntaxError("Illegal escape.");
throw syntaxError("Illegal escape.");
}
break;
default:
@ -275,7 +275,7 @@ public class JSONTokener {
final char c = this.next();
if ((c == delimiter) || (c == 0) || (c == '\n') || (c == '\r')) {
if (c != 0) {
this.back();
back();
}
return sb.toString().trim();
}
@ -298,7 +298,7 @@ public class JSONTokener {
c = this.next();
if ((delimiters.indexOf(c) >= 0) || (c == 0) || (c == '\n') || (c == '\r')) {
if (c != 0) {
this.back();
back();
}
return sb.toString().trim();
}
@ -315,17 +315,17 @@ public class JSONTokener {
* @throws JSONException If syntax error.
*/
public Object nextValue() throws JSONException {
char c = this.nextClean();
char c = nextClean();
String string;
switch (c) {
case '"':
case '\'':
return this.nextString(c);
return nextString(c);
case '{':
this.back();
back();
return new JSONObject(this);
case '[':
this.back();
back();
return new JSONArray(this);
}
/*
@ -340,10 +340,10 @@ public class JSONTokener {
sb.append(c);
c = this.next();
}
this.back();
back();
string = sb.toString().trim();
if ("".equals(string)) {
throw this.syntaxError("Missing value");
throw syntaxError("Missing value");
}
return JSONObject.stringToValue(string);
}
@ -359,24 +359,24 @@ public class JSONTokener {
public char skipTo(final char to) throws JSONException {
char c;
try {
final long startIndex = this.index;
final long startCharacter = this.character;
final long startLine = this.line;
this.reader.mark(1000000);
final long startIndex = index;
final long startCharacter = character;
final long startLine = line;
reader.mark(1000000);
do {
c = this.next();
if (c == 0) {
this.reader.reset();
this.index = startIndex;
this.character = startCharacter;
this.line = startLine;
reader.reset();
index = startIndex;
character = startCharacter;
line = startLine;
return c;
}
} while (c != to);
} catch (final IOException exception) {
throw new JSONException(exception);
}
this.back();
back();
return c;
}
@ -388,7 +388,7 @@ public class JSONTokener {
* @return A JSONException object, suitable for throwing
*/
public JSONException syntaxError(final String message) {
return new JSONException(message + this.toString());
return new JSONException(message + toString());
}
/**
@ -398,6 +398,6 @@ public class JSONTokener {
*/
@Override
public String toString() {
return " at " + this.index + " [character " + this.character + " line " + this.line + "]";
return " at " + index + " [character " + character + " line " + line + "]";
}
}

View File

@ -60,11 +60,11 @@ public class JSONWriter {
* Make a fresh JSONWriter. It can be used to build one JSON text.
*/
public JSONWriter(final Writer w) {
this.comma = false;
this.mode = 'i';
this.stack = new JSONObject[maxdepth];
this.top = 0;
this.writer = w;
comma = false;
mode = 'i';
stack = new JSONObject[maxdepth];
top = 0;
writer = w;
}
/**
@ -80,19 +80,19 @@ public class JSONWriter {
if (string == null) {
throw new JSONException("Null pointer");
}
if ((this.mode == 'o') || (this.mode == 'a')) {
if ((mode == 'o') || (mode == 'a')) {
try {
if (this.comma && (this.mode == 'a')) {
this.writer.write(',');
if (comma && (mode == 'a')) {
writer.write(',');
}
this.writer.write(string);
writer.write(string);
} catch (final IOException e) {
throw new JSONException(e);
}
if (this.mode == 'o') {
this.mode = 'k';
if (mode == 'o') {
mode = 'k';
}
this.comma = true;
comma = true;
return this;
}
throw new JSONException("Value out of sequence.");
@ -108,10 +108,10 @@ public class JSONWriter {
* a key or after the end of the outermost array or object).
*/
public JSONWriter array() throws JSONException {
if ((this.mode == 'i') || (this.mode == 'o') || (this.mode == 'a')) {
this.push(null);
this.append("[");
this.comma = false;
if ((mode == 'i') || (mode == 'o') || (mode == 'a')) {
push(null);
append("[");
comma = false;
return this;
}
throw new JSONException("Misplaced array.");
@ -131,13 +131,13 @@ public class JSONWriter {
if (this.mode != mode) {
throw new JSONException(mode == 'a' ? "Misplaced endArray." : "Misplaced endObject.");
}
this.pop(mode);
pop(mode);
try {
this.writer.write(c);
writer.write(c);
} catch (final IOException e) {
throw new JSONException(e);
}
this.comma = true;
comma = true;
return this;
}
@ -149,7 +149,7 @@ public class JSONWriter {
* @throws JSONException If incorrectly nested.
*/
public JSONWriter endArray() throws JSONException {
return this.end('a', ']');
return end('a', ']');
}
/**
@ -160,7 +160,7 @@ public class JSONWriter {
* @throws JSONException If incorrectly nested.
*/
public JSONWriter endObject() throws JSONException {
return this.end('k', '}');
return end('k', '}');
}
/**
@ -178,16 +178,16 @@ public class JSONWriter {
if (string == null) {
throw new JSONException("Null key.");
}
if (this.mode == 'k') {
if (mode == 'k') {
try {
this.stack[this.top - 1].putOnce(string, Boolean.TRUE);
if (this.comma) {
this.writer.write(',');
stack[top - 1].putOnce(string, Boolean.TRUE);
if (comma) {
writer.write(',');
}
this.writer.write(JSONObject.quote(string));
this.writer.write(':');
this.comma = false;
this.mode = 'o';
writer.write(JSONObject.quote(string));
writer.write(':');
comma = false;
mode = 'o';
return this;
} catch (final IOException e) {
throw new JSONException(e);
@ -206,13 +206,13 @@ public class JSONWriter {
* a key or after the end of the outermost array or object).
*/
public JSONWriter object() throws JSONException {
if (this.mode == 'i') {
this.mode = 'o';
if (mode == 'i') {
mode = 'o';
}
if ((this.mode == 'o') || (this.mode == 'a')) {
this.append("{");
this.push(new JSONObject());
this.comma = false;
if ((mode == 'o') || (mode == 'a')) {
append("{");
push(new JSONObject());
comma = false;
return this;
}
throw new JSONException("Misplaced object.");
@ -226,15 +226,15 @@ public class JSONWriter {
* @throws JSONException If nesting is wrong.
*/
private void pop(final char c) throws JSONException {
if (this.top <= 0) {
if (top <= 0) {
throw new JSONException("Nesting error.");
}
final char m = this.stack[this.top - 1] == null ? 'a' : 'k';
final char m = stack[top - 1] == null ? 'a' : 'k';
if (m != c) {
throw new JSONException("Nesting error.");
}
this.top -= 1;
this.mode = this.top == 0 ? 'd' : this.stack[this.top - 1] == null ? 'a' : 'k';
top -= 1;
mode = top == 0 ? 'd' : stack[top - 1] == null ? 'a' : 'k';
}
/**
@ -245,12 +245,12 @@ public class JSONWriter {
* @throws JSONException If nesting is too deep.
*/
private void push(final JSONObject jo) throws JSONException {
if (this.top >= maxdepth) {
if (top >= maxdepth) {
throw new JSONException("Nesting too deep.");
}
this.stack[this.top] = jo;
this.mode = jo == null ? 'a' : 'k';
this.top += 1;
stack[top] = jo;
mode = jo == null ? 'a' : 'k';
top += 1;
}
/**
@ -263,7 +263,7 @@ public class JSONWriter {
* @throws JSONException
*/
public JSONWriter value(final boolean b) throws JSONException {
return this.append(b ? "true" : "false");
return append(b ? "true" : "false");
}
/**
@ -289,7 +289,7 @@ public class JSONWriter {
* @throws JSONException
*/
public JSONWriter value(final long l) throws JSONException {
return this.append(Long.toString(l));
return append(Long.toString(l));
}
/**
@ -303,6 +303,6 @@ public class JSONWriter {
* @throws JSONException If the value is out of sequence.
*/
public JSONWriter value(final Object object) throws JSONException {
return this.append(JSONObject.valueToString(object));
return append(JSONObject.valueToString(object));
}
}

View File

@ -57,17 +57,17 @@ public class Kim {
// modified Fletcher code.
int sum = 1;
int value;
this.hashcode = 0;
this.length = thru - from;
if (this.length > 0) {
this.bytes = new byte[this.length];
for (int at = 0; at < this.length; at += 1) {
hashcode = 0;
length = thru - from;
if (length > 0) {
this.bytes = new byte[length];
for (int at = 0; at < length; at += 1) {
value = bytes[at + from] & 0xFF;
sum += value;
this.hashcode += sum;
hashcode += sum;
this.bytes[at] = (byte) value;
}
this.hashcode += sum << 16;
hashcode += sum << 16;
}
}
@ -101,17 +101,17 @@ public class Kim {
*/
public Kim(final String string) throws JSONException {
final int stringLength = string.length();
this.hashcode = 0;
this.length = 0;
hashcode = 0;
length = 0;
// First pass: Determine the length of the kim, allowing for the UTF-16
// to UTF-32 conversion, and then the UTF-32 to Kim conversion.
if (stringLength > 0) {
for (int i = 0; i < stringLength; i += 1) {
final int c = string.charAt(i);
if (c <= 0x7F) {
this.length += 1;
length += 1;
} else if (c <= 0x3FFF) {
this.length += 2;
length += 2;
} else {
if ((c >= 0xD800) && (c <= 0xDFFF)) {
i += 1;
@ -120,33 +120,33 @@ public class Kim {
throw new JSONException("Bad UTF16");
}
}
this.length += 3;
length += 3;
}
}
// Second pass: Allocate a byte array and fill that array with the
// conversion
// while computing the hashcode.
this.bytes = new byte[this.length];
bytes = new byte[length];
int at = 0;
int b;
int sum = 1;
for (int i = 0; i < stringLength; i += 1) {
int character = string.charAt(i);
if (character <= 0x7F) {
this.bytes[at] = (byte) character;
bytes[at] = (byte) character;
sum += character;
this.hashcode += sum;
hashcode += sum;
at += 1;
} else if (character <= 0x3FFF) {
b = 0x80 | (character >>> 7);
this.bytes[at] = (byte) b;
bytes[at] = (byte) b;
sum += b;
this.hashcode += sum;
hashcode += sum;
at += 1;
b = character & 0x7F;
this.bytes[at] = (byte) b;
bytes[at] = (byte) b;
sum += b;
this.hashcode += sum;
hashcode += sum;
at += 1;
} else {
if ((character >= 0xD800) && (character <= 0xDBFF)) {
@ -154,23 +154,23 @@ public class Kim {
character = (((character & 0x3FF) << 10) | (string.charAt(i) & 0x3FF)) + 65536;
}
b = 0x80 | (character >>> 14);
this.bytes[at] = (byte) b;
bytes[at] = (byte) b;
sum += b;
this.hashcode += sum;
hashcode += sum;
at += 1;
b = 0x80 | ((character >>> 7) & 0xFF);
this.bytes[at] = (byte) b;
bytes[at] = (byte) b;
sum += b;
this.hashcode += sum;
hashcode += sum;
at += 1;
b = character & 0x7F;
this.bytes[at] = (byte) b;
bytes[at] = (byte) b;
sum += b;
this.hashcode += sum;
hashcode += sum;
at += 1;
}
}
this.hashcode += sum << 16;
hashcode += sum << 16;
}
}
@ -230,8 +230,8 @@ public class Kim {
* @return The position immediately after the copy.
*/
public int copy(final byte[] bytes, final int at) {
System.arraycopy(this.bytes, 0, bytes, at, this.length);
return at + this.length;
System.arraycopy(this.bytes, 0, bytes, at, length);
return at + length;
}
/**
@ -250,10 +250,10 @@ public class Kim {
if (this == that) {
return true;
}
if (this.hashcode != that.hashcode) {
if (hashcode != that.hashcode) {
return false;
}
return java.util.Arrays.equals(this.bytes, that.bytes);
return java.util.Arrays.equals(bytes, that.bytes);
}
/**
@ -266,10 +266,10 @@ public class Kim {
* @throws JSONException if there is no byte at that position.
*/
public int get(final int at) throws JSONException {
if ((at < 0) || (at > this.length)) {
if ((at < 0) || (at > length)) {
throw new JSONException("Bad character at " + at);
}
return (this.bytes[at]) & 0xFF;
return (bytes[at]) & 0xFF;
}
/**
@ -277,7 +277,7 @@ public class Kim {
*/
@Override
public int hashCode() {
return this.hashcode;
return hashcode;
}
/**
@ -290,12 +290,12 @@ public class Kim {
*/
@Override
public String toString() throws JSONException {
if (this.string == null) {
if (string == null) {
int c;
int length = 0;
final char chars[] = new char[this.length];
for (int at = 0; at < this.length; at += characterSize(c)) {
c = this.characterAt(at);
c = characterAt(at);
if (c < 0x10000) {
chars[length] = (char) c;
length += 1;
@ -306,8 +306,8 @@ public class Kim {
length += 1;
}
}
this.string = new String(chars, 0, length);
string = new String(chars, 0, length);
}
return this.string;
return string;
}
}

View File

@ -108,7 +108,7 @@ public class XML {
if ("CDATA".equals(token)) {
if (x.next() == '[') {
string = x.nextCDATA();
if (string.length() > 0) {
if (!string.isEmpty()) {
context.accumulate("content", string);
}
return false;
@ -192,7 +192,7 @@ public class XML {
return false;
} else if (token instanceof String) {
string = (String) token;
if (string.length() > 0) {
if (!string.isEmpty()) {
jsonobject.accumulate("content", XML.stringToValue(string));
}
// Nested element
@ -235,9 +235,7 @@ public class XML {
if ("null".equalsIgnoreCase(string)) {
return JSONObject.NULL;
}
// If it might be a number, try converting it, first as a Long, and then
// as a
// Double. If that doesn't work, return the string.
//If it might be a number, try converting it, first as a Long, and then as a Double. If that doesn't work, return the string.
try {
final char initial = string.charAt(0);
if ((initial == '-') || ((initial >= '0') && (initial <= '9'))) {
@ -246,13 +244,13 @@ public class XML {
return value;
}
}
} catch (final Exception ignore) {
} catch (NumberFormatException ignore) {
try {
final Double value = new Double(string);
if (value.toString().equals(string)) {
return value;
}
} catch (final Exception ignoreAlso) {
} catch (NumberFormatException ignoreAlso) {
}
}
return string;
@ -381,7 +379,8 @@ public class XML {
return sb.toString();
} else {
string = (object == null) ? "null" : escape(object.toString());
return (tagName == null) ? "\"" + string + "\"" : (string.length() == 0) ? "<" + tagName + "/>" : "<" + tagName + ">" + string + "</" + tagName + ">";
return (tagName == null) ? "\"" + string + "\"" :
(string.isEmpty()) ? "<" + tagName + "/>" : "<" + tagName + ">" + string + "</" + tagName + ">";
}
}
}

View File

@ -1,20 +1,24 @@
package com.intellectualcrafters.plot;
import java.io.File;
import java.util.List;
import com.intellectualcrafters.plot.generator.GeneratorWrapper;
import com.intellectualcrafters.plot.generator.HybridUtils;
import com.intellectualcrafters.plot.generator.PlotGenerator;
import com.intellectualcrafters.plot.generator.IndependentPlotGenerator;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.AbstractTitle;
import com.intellectualcrafters.plot.util.BlockManager;
import com.intellectualcrafters.plot.util.ChatManager;
import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.EconHandler;
import com.intellectualcrafters.plot.util.EventUtil;
import com.intellectualcrafters.plot.util.InventoryUtil;
import com.intellectualcrafters.plot.util.PlotQueue;
import com.intellectualcrafters.plot.util.SchematicHandler;
import com.intellectualcrafters.plot.util.SetupUtils;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandlerImplementation;
import com.intellectualcrafters.plot.util.WorldUtil;
public interface IPlotMain {
@ -22,7 +26,7 @@ public interface IPlotMain {
* Log a message to console
* @param message
*/
void log(String message);
void log(final String message);
/**
* Get the `PlotSquared` directory (e.g. /plugins/PlotSquared or /mods/PlotSquared)
@ -30,12 +34,18 @@ public interface IPlotMain {
*/
File getDirectory();
/**
* Get the directory containing all the worlds
* @return
*/
File getWorldContainer();
/**
* Wrap a player into a PlotPlayer object
* @param obj
* @return
*/
PlotPlayer wrapPlayer(Object obj);
PlotPlayer wrapPlayer(final Object obj);
/**
* Disable the implementation
@ -68,6 +78,12 @@ public interface IPlotMain {
*/
SchematicHandler initSchematicHandler();
/**
* Get the schematic handler
* @return
*/
ChatManager initChatManager();
/**
* The task manager will run and manage minecraft tasks
* @return
@ -107,12 +123,7 @@ public interface IPlotMain {
/**
* Register the WorldEdit hook
*/
void registerWorldEditEvents();
/**
* Register TNT related events (if TNT protection is enabled)
*/
void registerTNTListener();
boolean initWorldEdit();
/**
* Get the economy provider
@ -121,10 +132,16 @@ public interface IPlotMain {
EconHandler getEconomyHandler();
/**
* Get the block manager
* Get the Plot Queue class
* @return
*/
BlockManager initBlockManager();
PlotQueue initPlotQueue();
/**
* Get the World Util class
* @return
*/
WorldUtil initWorldUtil();
/**
* Get the EventUtil class
@ -159,7 +176,7 @@ public interface IPlotMain {
* If a world is already loaded, set the generator (use NMS if required)
* @param world
*/
void setGenerator(String world);
void setGenerator(final String world);
/**
* Get the UUIDHandlerImplementation which will cache and provide UUIDs
@ -183,7 +200,7 @@ public interface IPlotMain {
* Unregister a PlotPlayer from cache e.g. if they have logged off
* @param player
*/
void unregister(PlotPlayer player);
void unregister(final PlotPlayer player);
/**
* Get the generator wrapper for a world (world) and generator (name)
@ -191,7 +208,12 @@ public interface IPlotMain {
* @param name
* @return
*/
PlotGenerator<?> getGenerator(String world, String name);
GeneratorWrapper<?> getGenerator(final String world, final String name);
/**
*
*/
GeneratorWrapper<?> wrapPlotGenerator(IndependentPlotGenerator generator);
/**
* Register the chunk processor which will clean out chunks that have too many blockstates or entities
@ -214,4 +236,6 @@ public interface IPlotMain {
* @return
*/
AbstractTitle initTitleManager();
List<String> getPluginIds();
}

File diff suppressed because it is too large Load Diff

View File

@ -21,17 +21,6 @@
package com.intellectualcrafters.plot.api;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;
import java.util.UUID;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import com.intellectualcrafters.configuration.file.YamlConfiguration;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.commands.MainCommand;
@ -40,26 +29,34 @@ import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.flag.AbstractFlag;
import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotManager;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.PlotWorld;
import com.intellectualcrafters.plot.util.BlockManager;
import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.ClusterManager;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.SchematicHandler;
import com.intellectualcrafters.plot.util.SetQueue;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.uuid.UUIDWrapper;
import com.plotsquared.bukkit.util.BukkitSetBlockManager;
import com.plotsquared.bukkit.util.BukkitUtil;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
/**
* PlotSquared API
*
* @author Citymonstret
* @author Empire92
* @version API 2.0
*
*/
@ -78,27 +75,27 @@ public class PlotAPI {
* @deprecated Use new PlotAPI() instead
*/
@Deprecated
public PlotAPI(final JavaPlugin plugin) {
}
public PlotAPI(final JavaPlugin plugin) {}
/**
* @param plugin Plugin used to access this method
* @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
*
* @throws com.intellectualcrafters.plot.util.PlotSquaredException if the program fails to fetch the PlotSquared
* instance
* @see com.intellectualcrafters.plot.PS
*
* @deprecated Use new PlotAPI() instead
*/
public PlotAPI() {
}
@Deprecated
public PlotAPI() {}
/**
* Get all plots
*
* @return all plots
*
* @see com.intellectualcrafters.plot.PS#getPlots()
* @see PS#getPlots()
*/
public Set<Plot> getAllPlots() {
return PS.get().getPlots();
@ -118,21 +115,17 @@ public class PlotAPI {
/**
* Add a plot world
*
* @param world World Name
* @param plotWorld Plot World Object
* @param manager World Manager
*
* @see com.intellectualcrafters.plot.PS#addPlotWorld(String, com.intellectualcrafters.plot.object.PlotWorld,
* com.intellectualcrafters.plot.object.PlotManager)
* @param plotArea Plot World Object
* @see PS#addPlotArea(PlotArea)
*/
public void addPlotWorld(final String world, final PlotWorld plotWorld, final PlotManager manager) {
PS.get().addPlotWorld(world, plotWorld, manager);
public void addPlotArea(final PlotArea plotArea) {
PS.get().addPlotArea(plotArea);
}
/**
* @return main configuration
*
* @see com.intellectualcrafters.plot.PS#config
* @see PS#config
*/
public YamlConfiguration getConfig() {
return PS.get().config;
@ -141,7 +134,7 @@ public class PlotAPI {
/**
* @return storage configuration
*
* @see com.intellectualcrafters.plot.PS#storage
* @see PS#storage
*/
public YamlConfiguration getStorage() {
return PS.get().storage;
@ -153,7 +146,7 @@ public class PlotAPI {
*
* @return PlotSquared PlotSquared Main Class
*
* @see com.intellectualcrafters.plot.PS
* @see PS
*/
public PS getMain() {
return PS.get();
@ -176,25 +169,11 @@ public class PlotAPI {
}
/**
* BlockManager class contains useful methods relating to blocks.
*
* @return BlockManager
*
* @see com.intellectualcrafters.plot.util.BlockManager
* Get the block/biome set queue
* @return SetQueue.IMP
*/
public BlockManager getBlockManager() {
return BlockManager.manager;
}
/**
* BukkitSetBlockManager class contains useful methods relating to bukkit blocks.
*
* @return BukkitSetBlockManager
*
* @see com.plotsquared.bukkit.util.BukkitSetBlockManager
*/
public BukkitSetBlockManager getBukkitBlockManager() {
return BukkitSetBlockManager.setBlockManager;
public SetQueue getSetQueue() {
return SetQueue.IMP;
}
/**
@ -221,26 +200,13 @@ public class PlotAPI {
return new FlagManager();
}
/**
* Do not use this. Instead use ClusterManager.[method] in your code.
* - Plot cluster related stuff
*
* @return ClusterManager
*
* @see com.intellectualcrafters.plot.util.ClusterManager
*/
@Deprecated
public ClusterManager getClusterManager() {
return new ClusterManager();
}
/**
* Do not use this. Instead use MainUtil.[method] in your code.
* - Basic plot management stuff
*
* @return MainUtil
*
* @see com.intellectualcrafters.plot.util.MainUtil
* @see MainUtil
*/
@Deprecated
public MainUtil getMainUtil() {
@ -257,13 +223,13 @@ public class PlotAPI {
*/
@Deprecated
public String[] getPermissions() {
ArrayList<String> perms = new ArrayList<>();
for (C c : C.values()) {
if (c.getCat().equals("static.permissions")) {
final ArrayList<String> perms = new ArrayList<>();
for (final C c : C.values()) {
if ("static.permissions".equals(c.getCat())) {
perms.add(c.s());
}
}
return perms.toArray(new String[0]);
return perms.toArray(new String[perms.size()]);
}
/**
@ -297,10 +263,21 @@ public class PlotAPI {
* @return PlotManager
*
* @see com.intellectualcrafters.plot.object.PlotManager
* @see PS#getPlotManager(String)
* @see PS#getPlotManager(Plot)
*/
@Deprecated
public PlotManager getPlotManager(final World world) {
return PS.get().getPlotManager(world.getName());
if (world == null) {
return null;
}
return getPlotManager(world.getName());
}
public Set<PlotArea> getPlotAreas(World world) {
if (world == null) {
return new HashSet<>();
}
return PS.get().getPlotAreas(world.getName());
}
/**
@ -311,40 +288,67 @@ public class PlotAPI {
*
* @return PlotManager
*
* @see PS#getPlotManager(String)
* @see PS#getPlotManager(Plot)
* @see com.intellectualcrafters.plot.object.PlotManager
*/
@Deprecated
public PlotManager getPlotManager(final String world) {
return PS.get().getPlotManager(world);
Set<PlotArea> areas = PS.get().getPlotAreas(world);
switch (areas.size()) {
case 0:
return null;
case 1:
return areas.iterator().next().manager;
default:
PS.debug("PlotAPI#getPlotManager(org.bukkit.World) is deprecated and doesn't support multi plot area worlds.");
return null;
}
}
/**
* Get the settings for a world (settings bundled in PlotWorld class) - You will need to downcast for the specific
* settings a Generator has. e.g. DefaultPlotWorld class implements PlotWorld
* Get the settings for a world (settings bundled in PlotArea class) - You will need to downcast for the specific
* settings a Generator has. e.g. DefaultPlotWorld class implements PlotArea
*
* @param world (to get settings of)
*
* @return PlotWorld class for that world ! will return null if not a plot world world
* @return PlotArea class for that world ! will return null if not a plot world world
*
* @see PS#getPlotWorld(String)
* @see com.intellectualcrafters.plot.object.PlotWorld
* @see #getPlotAreas(World)
* @see com.intellectualcrafters.plot.object.PlotArea
*/
public PlotWorld getWorldSettings(final World world) {
return PS.get().getPlotWorld(world.getName());
@Deprecated
public PlotArea getWorldSettings(final World world) {
if (world == null) {
return null;
}
return getWorldSettings(world.getName());
}
/**
* Get the settings for a world (settings bundled in PlotWorld class)
* Get the settings for a world (settings bundled in PlotArea class)
*
* @param world (to get settings of)
*
* @return PlotWorld class for that world ! will return null if not a plot world world
* @return PlotArea class for that world ! will return null if not a plot world world
*
* @see PS#getPlotWorld(String)
* @see com.intellectualcrafters.plot.object.PlotWorld
* @see PS#getPlotArea(String, String)
* @see com.intellectualcrafters.plot.object.PlotArea
*/
public PlotWorld getWorldSettings(final String world) {
return PS.get().getPlotWorld(world);
@Deprecated
public PlotArea getWorldSettings(final String world) {
if (world == null) {
return null;
}
Set<PlotArea> areas = PS.get().getPlotAreas(world);
switch (areas.size()) {
case 0:
return null;
case 1:
return areas.iterator().next();
default:
PS.debug("PlotAPI#getWorldSettings(org.bukkit.World) is deprecated and doesn't support multi plot area worlds.");
return null;
}
}
/**
@ -353,7 +357,7 @@ public class PlotAPI {
* @param player Player that will receive the message
* @param c (Caption)
*
* @see com.intellectualcrafters.plot.util.MainUtil#sendMessage(PlotPlayer, C, String...)
* @see MainUtil#sendMessage(PlotPlayer, C, String...)
* com.intellectualcrafters.plot.config.C, String...)
*/
public void sendMessage(final Player player, final C c) {
@ -366,7 +370,7 @@ public class PlotAPI {
* @param player Player that will receive the message
* @param string The message
*
* @see com.intellectualcrafters.plot.util.MainUtil#sendMessage(PlotPlayer, String)
* @see MainUtil#sendMessage(PlotPlayer, String)
*/
public void sendMessage(final Player player, final String string) {
MainUtil.sendMessage(BukkitUtil.getPlayer(player), string);
@ -377,10 +381,10 @@ public class PlotAPI {
*
* @param msg Message that should be sent to the console
*
* @see MainUtil#sendConsoleMessage(String)
* @see MainUtil#sendConsoleMessage(C, String...)
*/
public void sendConsoleMessage(final String msg) {
MainUtil.sendConsoleMessage(msg);
PS.log(msg);
}
/**
@ -428,11 +432,18 @@ public class PlotAPI {
*
* @return plot, null if ID is wrong
*
* @see MainUtil#getPlot(String, com.intellectualcrafters.plot.object.PlotId)
* @see com.intellectualcrafters.plot.object.Plot
* @see PlotArea#getPlot(PlotId)
*/
@Deprecated
public Plot getPlot(final World world, final int x, final int z) {
return MainUtil.getPlot(world.getName(), new PlotId(x, z));
if (world == null) {
return null;
}
PlotArea area = getWorldSettings(world);
if (area == null) {
return null;
}
return area.getPlot(new PlotId(x, z));
}
/**
@ -442,11 +453,13 @@ public class PlotAPI {
*
* @return plot if found, otherwise it creates a temporary plot-
*
* @see MainUtil#getPlot(com.intellectualcrafters.plot.object.Location)
* @see com.intellectualcrafters.plot.object.Plot
* @see Plot
*/
public Plot getPlot(final Location l) {
return MainUtil.getPlot(BukkitUtil.getLocation(l));
if (l == null) {
return null;
}
return BukkitUtil.getLocation(l).getPlot();
}
/**
@ -457,7 +470,7 @@ public class PlotAPI {
* @return plot if found, otherwise it creates a temporary plot
*
* @see #getPlot(org.bukkit.Location)
* @see com.intellectualcrafters.plot.object.Plot
* @see Plot
*/
public Plot getPlot(final Player player) {
return this.getPlot(player.getLocation());
@ -472,8 +485,9 @@ public class PlotAPI {
*
* @see #getPlots(World, Player, boolean)
*/
@Deprecated
public boolean hasPlot(final World world, final Player player) {
return (getPlots(world, player, true) != null) && (getPlots(world, player, true).length > 0);
return getPlots(world, player, true) != null && getPlots(world, player, true).length > 0;
}
/**
@ -481,18 +495,18 @@ public class PlotAPI {
*
* @param plr to search for
* @param just_owner should we just search for owner? Or with rights?
*
* @see com.intellectualcrafters.plot.object.Plot
*/
@Deprecated
public Plot[] getPlots(final World world, final Player plr, final boolean just_owner) {
final ArrayList<Plot> pPlots = new ArrayList<>();
for (final Plot plot : PS.get().getPlotsInWorld(world.getName())) {
UUID uuid = BukkitUtil.getPlayer(plr).getUUID();
for (final Plot plot : PS.get().getPlots(world.getName())) {
if (just_owner) {
if ((plot.owner != null) && (plot.owner.equals(UUIDHandler.getUUID(BukkitUtil.getPlayer(plr))))) {
if (plot.hasOwner() && plot.isOwner(uuid)) {
pPlots.add(plot);
}
} else {
if (plot.isAdded(UUIDHandler.getUUID(BukkitUtil.getPlayer(plr)))) {
if (plot.isAdded(uuid)) {
pPlots.add(plot);
}
}
@ -508,10 +522,14 @@ public class PlotAPI {
* @return Plot[] - array of plot objects in world
*
* @see PS#getPlots(String)
* @see com.intellectualcrafters.plot.object.Plot
* @see Plot
*/
@Deprecated
public Plot[] getPlots(final World world) {
Collection<Plot> plots = PS.get().getPlotsInWorld(world.getName());
if (world == null) {
return new Plot[0];
}
Collection<Plot> plots = PS.get().getPlots(world.getName());
return plots.toArray(new Plot[plots.size()]);
}
@ -520,11 +538,11 @@ public class PlotAPI {
*
* @return World[] - array of plot worlds
*
* @see com.intellectualcrafters.plot.PS#getPlotWorlds()
*/
@Deprecated
public String[] getPlotWorlds() {
Set<String> worlds = PS.get().getPlotWorlds();
return worlds.toArray(new String[worlds.size()]);
Set<String> plotWorldStrings = PS.get().getPlotWorldStrings();
return plotWorldStrings.toArray(new String[plotWorldStrings.size()]);
}
/**
@ -534,10 +552,11 @@ public class PlotAPI {
*
* @return boolean (if plot world or not)
*
* @see com.intellectualcrafters.plot.PS#isPlotWorld(String)
* @see PS#hasPlotArea(String)
*/
@Deprecated
public boolean isPlotWorld(final World world) {
return PS.get().isPlotWorld(world.getName());
return PS.get().hasPlotArea(world.getName());
}
/**
@ -547,16 +566,13 @@ public class PlotAPI {
*
* @return [0] = bottomLc, [1] = topLoc, [2] = home
*
* @see com.intellectualcrafters.plot.util.MainUtil#getPlotBottomLoc(String,
* com.intellectualcrafters.plot.object.PlotId)
* @see com.intellectualcrafters.plot.util.MainUtil#getPlotTopLoc(String,
* com.intellectualcrafters.plot.object.PlotId)
* @see com.intellectualcrafters.plot.util.MainUtil#getPlotHome(String,
* com.intellectualcrafters.plot.object.Plot)
* @see com.intellectualcrafters.plot.object.Plot
* @deprecated As merged plots may not have a rectangular shape
*
* @see Plot
*/
@Deprecated
public Location[] getLocations(final Plot p) {
return new Location[]{BukkitUtil.getLocation(MainUtil.getPlotBottomLoc(p.world, p.id)), BukkitUtil.getLocation(MainUtil.getPlotTopLoc(p.world, p.id)), BukkitUtil.getLocation(MainUtil.getPlotHome(p.world, p.id))};
return new Location[] { BukkitUtil.getLocation(p.getBottom()), BukkitUtil.getLocation(p.getTop()), BukkitUtil.getLocation(p.getHome()) };
}
/**
@ -566,12 +582,10 @@ public class PlotAPI {
*
* @return plot bottom location
*
* @see com.intellectualcrafters.plot.util.MainUtil#getPlotHome(String,
* com.intellectualcrafters.plot.object.Plot)
* @see com.intellectualcrafters.plot.object.Plot
* @see Plot
*/
public Location getHomeLocation(final Plot p) {
return BukkitUtil.getLocation(MainUtil.getPlotHome(p.world, p.id));
return BukkitUtil.getLocation(p.getHome());
}
/**
@ -581,12 +595,13 @@ public class PlotAPI {
*
* @return plot bottom location
*
* @see com.intellectualcrafters.plot.util.MainUtil#getPlotBottomLoc(String,
* com.intellectualcrafters.plot.object.PlotId)
* @see com.intellectualcrafters.plot.object.Plot
* @deprecated As merged plots may not have a rectangular shape
*
* @see Plot
*/
@Deprecated
public Location getBottomLocation(final Plot p) {
return BukkitUtil.getLocation(MainUtil.getPlotBottomLoc(p.world, p.id));
return BukkitUtil.getLocation(p.getBottom());
}
/**
@ -596,11 +611,13 @@ public class PlotAPI {
*
* @return plot top location
*
* @see MainUtil#getPlotTopLoc(String, com.intellectualcrafters.plot.object.PlotId)
* @see com.intellectualcrafters.plot.object.Plot
* @deprecated As merged plots may not have a rectangular shape
*
* @see Plot
*/
@Deprecated
public Location getTopLocation(final Plot p) {
return BukkitUtil.getLocation(MainUtil.getPlotTopLoc(p.world, p.id));
return BukkitUtil.getLocation(p.getTop());
}
/**
@ -610,10 +627,9 @@ public class PlotAPI {
*
* @return true if the player is in a plot, false if not-
*
* @see com.intellectualcrafters.plot.util.MainUtil#getPlot(com.intellectualcrafters.plot.object.Location)
*/
public boolean isInPlot(final Player player) {
return MainUtil.getPlot(BukkitUtil.getLocation(player)) != null;
return getPlot(player) != null;
}
/**
@ -636,7 +652,7 @@ public class PlotAPI {
*
* @return PlotSquared Class
*
* @see com.intellectualcrafters.plot.PS
* @see PS
*/
public PS getPlotSquared() {
return PS.get();
@ -650,10 +666,12 @@ public class PlotAPI {
*
* @return the number of plots the player has
*
* @see com.intellectualcrafters.plot.util.MainUtil#getPlayerPlotCount(String, PlotPlayer)
*/
public int getPlayerPlotCount(final World world, final Player player) {
return MainUtil.getPlayerPlotCount(world.getName(), BukkitUtil.getPlayer(player));
if (world == null) {
return 0;
}
return BukkitUtil.getPlayer(player).getPlotCount(world.getName());
}
/**
@ -664,12 +682,15 @@ public class PlotAPI {
*
* @return a set containing the players plots
*
* @see com.intellectualcrafters.plot.PS#getPlots(String, PlotPlayer)
* org.bukkit.entity.Player)
* @see com.intellectualcrafters.plot.object.Plot
* @see PS#getPlots(String, PlotPlayer)
*
* @see Plot
*/
public Set<Plot> getPlayerPlots(final World world, final Player player) {
return PS.get().getPlots(world.getName(), BukkitUtil.getPlayer(player));
if (world == null) {
return new HashSet<>();
}
return BukkitUtil.getPlayer(player).getPlots(world.getName());
}
/**
@ -681,44 +702,44 @@ public class PlotAPI {
*
*/
public int getAllowedPlots(final Player player) {
PlotPlayer pp = BukkitUtil.getPlayer(player);
return MainUtil.getAllowedPlots(pp);
final PlotPlayer pp = BukkitUtil.getPlayer(player);
return pp.getAllowedPlots();
}
/**
* Get the PlotPlayer for a player<br>
* - The PlotPlayer is usually cached and will provide useful functions relating to players
*
* @see PlotPlayer.wrap(Player|OfflinePlayer|String|UUID)
* @see PlotPlayer#wrap(Object)
*
* @param player
* @return
*/
public PlotPlayer wrapPlayer(Player player) {
public PlotPlayer wrapPlayer(final Player player) {
return PlotPlayer.wrap(player);
}
/**
* Get the PlotPlayer for a UUID (Please note that PlotSquared can be configured to provide different UUIDs than bukkit)
*
* @see PlotPlayer.wrap(UUID uuid)
* @see PlotPlayer#wrap(Object)
*
* @param player
* @param uuid
* @return
*/
public PlotPlayer wrapPlayer(UUID uuid) {
public PlotPlayer wrapPlayer(final UUID uuid) {
return PlotPlayer.wrap(uuid);
}
/**
* Get the PlotPlayer for a username
*
* @see PlotPlayer.wrap(String name)
* @see PlotPlayer#wrap(Object)
*
* @param player
* @return
*/
public PlotPlayer wrapPlayer(String player) {
public PlotPlayer wrapPlayer(final String player) {
return PlotPlayer.wrap(player);
}
@ -726,12 +747,12 @@ public class PlotAPI {
* Get the PlotPlayer for an offline player<br>
* Note that this will work if the player is offline, however not all functionality will work
*
* @see PlotPlayer.wrap(OfflinePlayer op)
* @see PlotPlayer#wrap(Object)
*
* @param player
* @return
*/
public PlotPlayer wrapPlayer(OfflinePlayer player) {
public PlotPlayer wrapPlayer(final OfflinePlayer player) {
return PlotPlayer.wrap(player);
}
}

View File

@ -22,7 +22,6 @@ package com.intellectualcrafters.plot.commands;
import java.util.UUID;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.object.Location;
@ -32,7 +31,6 @@ import com.intellectualcrafters.plot.util.EventUtil;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.bukkit.uuid.SQLUUIDHandler;
import com.plotsquared.general.commands.Argument;
import com.plotsquared.general.commands.CommandDeclaration;
@ -41,22 +39,19 @@ import com.plotsquared.general.commands.CommandDeclaration;
aliases = { "a" },
description = "Allow a user to build while you are online",
usage = "/plot add <player>",
category = CommandCategory.ACTIONS,
category = CommandCategory.SETTINGS,
permission = "plots.add",
requiredType = RequiredType.NONE
)
requiredType = RequiredType.NONE)
public class Add extends SubCommand {
public Add() {
requiredArguments = new Argument[] {
Argument.PlayerName
};
requiredArguments = new Argument[] { Argument.PlayerName };
}
@Override
public boolean onCommand(PlotPlayer plr, String[] args) {
public boolean onCommand(final PlotPlayer plr, final String[] args) {
final Location loc = plr.getLocation();
final Plot plot = MainUtil.getPlot(loc);
final Plot plot = loc.getPlotAbs();
if (plot == null) {
return !sendMessage(plr, C.NOT_IN_PLOT);
}
@ -90,9 +85,8 @@ public class Add extends SubCommand {
}
if (plot.removeTrusted(uuid)) {
plot.addMember(uuid);
}
else {
if (plot.getMembers().size() + plot.getTrusted().size() >= PS.get().getPlotWorld(plot.world).MAX_PLOT_MEMBERS) {
} else {
if ((plot.getMembers().size() + plot.getTrusted().size()) >= plot.getArea().MAX_PLOT_MEMBERS) {
MainUtil.sendMessage(plr, C.PLOT_MAX_MEMBERS);
return false;
}

View File

@ -22,51 +22,50 @@ package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.PlotWorld;
import com.intellectualcrafters.plot.util.EconHandler;
import com.intellectualcrafters.plot.object.StringWrapper;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(
command = "unclaim",
usage = "/plot unclaim",
requiredType = RequiredType.NONE,
description = "Unclaim a plot",
category = CommandCategory.ACTIONS
)
public class Unclaim extends SubCommand {
command = "setalias",
permission = "plots.set.alias",
description = "Set the plot name",
usage = "/plot alias <alias>",
aliases = { "alias", "sa", "name", "rename", "setname", "seta" },
category = CommandCategory.SETTINGS,
requiredType = RequiredType.NONE)
public class Alias extends SetCommand {
@Override
public boolean onCommand(final PlotPlayer plr, final String[] args) {
final Location loc = plr.getLocation();
final Plot plot = MainUtil.getPlot(loc);
if (plot == null) {
return !sendMessage(plr, C.NOT_IN_PLOT);
public boolean set(final PlotPlayer plr, final Plot plot, final String alias) {
if (alias.isEmpty()) {
C.COMMAND_SYNTAX.send(plr, getUsage());
return false;
}
if (!MainUtil.getTopPlot(plot).equals(MainUtil.getBottomPlot(plot))) {
return !sendMessage(plr, C.UNLINK_REQUIRED);
if (alias.length() >= 50) {
MainUtil.sendMessage(plr, C.ALIAS_TOO_LONG);
return false;
}
if (((!plot.hasOwner() || !plot.isOwner(plr.getUUID()))) && !Permissions.hasPermission(plr, "plots.admin.command.unclaim")) {
return !sendMessage(plr, C.NO_PLOT_PERMS);
if (alias.contains(" ") || !StringMan.isAsciiPrintable(alias)) {
C.NOT_VALID_VALUE.send(plr);
return false;
}
final PlotWorld pWorld = PS.get().getPlotWorld(plot.world);
if ((EconHandler.manager != null) && pWorld.USE_ECONOMY) {
final double c = pWorld.SELL_PRICE;
if (c > 0d) {
EconHandler.manager.depositMoney(plr, c);
sendMessage(plr, C.ADDED_BALANCE, c + "");
for (final Plot p : PS.get().getPlots(plot.getArea())) {
if (p.getAlias().equalsIgnoreCase(alias)) {
MainUtil.sendMessage(plr, C.ALIAS_IS_TAKEN);
return false;
}
}
if (plot.unclaim()) {
MainUtil.sendMessage(plr, C.UNCLAIM_SUCCESS);
}
else {
MainUtil.sendMessage(plr, C.UNCLAIM_FAILED);
if (UUIDHandler.nameExists(new StringWrapper(alias)) || PS.get().hasPlotArea(alias)) {
MainUtil.sendMessage(plr, C.ALIAS_IS_TAKEN);
return false;
}
plot.setAlias(alias);
MainUtil.sendMessage(plr, C.ALIAS_SET_TO.s().replaceAll("%alias%", alias));
return true;
}
}

View File

@ -0,0 +1,461 @@
package com.intellectualcrafters.plot.commands;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Set;
import com.intellectualcrafters.configuration.ConfigurationSection;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Configuration;
import com.intellectualcrafters.plot.generator.AugmentedUtils;
import com.intellectualcrafters.plot.generator.HybridGen;
import com.intellectualcrafters.plot.generator.HybridPlotWorld;
import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotMessage;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.RegionWrapper;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.object.RunnableVal3;
import com.intellectualcrafters.plot.object.SetupObject;
import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.CmdConfirm;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.MathMan;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.SetupUtils;
import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.WorldUtil;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(
command = "area",
permission = "plots.area",
category = CommandCategory.ADMINISTRATION,
requiredType = RequiredType.NONE,
description = "Create a new PlotArea",
aliases = { "world" },
usage = "/plot area <create|info|list|tp|regen>")
public class Area extends SubCommand {
@Override
public boolean onCommand(final PlotPlayer plr, String[] args) {
if (args.length == 0) {
C.COMMAND_SYNTAX.send(plr, getUsage());
return false;
}
switch (args[0].toLowerCase()) {
case "c":
case "setup":
case "create": {
if (!Permissions.hasPermission(plr, "plots.area.create")) {
C.NO_PERMISSION.send(plr, "plots.area.create");
return false;
}
switch (args.length) {
case 1: {
C.COMMAND_SYNTAX.send(plr, "/plot area create [world[:id]] [<modifier>=<value>]...");
return false;
}
case 2: {
switch (args[1].toLowerCase()) {
case "pos1": { // Set position 1
HybridPlotWorld area = plr.<HybridPlotWorld> getMeta("area_create_area");
if (area == null) {
C.COMMAND_SYNTAX.send(plr, "/plot area create [world[:id]] [<modifier>=<value>]...");
return false;
}
Location loc = plr.getLocation();
plr.setMeta("area_pos1", loc);
C.SET_ATTRIBUTE.send(plr, "area_pos1", loc.getX() + "," + loc.getZ());
MainUtil.sendMessage(plr, "You will now set pos2: /plot area create pos2"
+ "\nNote: The chosen plot size may result in the created area not exactly matching your second position.");
return true;
}
case "pos2": { // Set position 2 and finish creation for type=2 (partial)
final HybridPlotWorld area = plr.<HybridPlotWorld> getMeta("area_create_area");
if (area == null) {
C.COMMAND_SYNTAX.send(plr, "/plot area create [world[:id]] [<modifier>=<value>]...");
return false;
}
Location pos1 = plr.getLocation();
Location pos2 = plr.<Location> getMeta("area_pos1");
int dx = Math.abs(pos1.getX() - pos2.getX());
int dz = Math.abs(pos1.getZ() - pos2.getZ());
int numx = Math.max(1, (dx + 1 + area.ROAD_WIDTH + (area.SIZE / 2)) / area.SIZE);
int numz = Math.max(1, (dz + 1 + area.ROAD_WIDTH + (area.SIZE / 2)) / area.SIZE);
final int ddx = dx - (numx * area.SIZE - area.ROAD_WIDTH);
final int ddz = dz - (numz * area.SIZE - area.ROAD_WIDTH);
int bx = Math.min(pos1.getX(), pos2.getX()) + ddx;
int bz = Math.min(pos1.getZ(), pos2.getZ()) + ddz;
int tx = Math.max(pos1.getX(), pos2.getX()) - ddx;
int tz = Math.max(pos1.getZ(), pos2.getZ()) - ddz;
int lower = (area.ROAD_WIDTH & 1) == 0 ? area.ROAD_WIDTH / 2 - 1 : area.ROAD_WIDTH / 2;
final int offsetx = bx - (area.ROAD_WIDTH == 0 ? 0 : lower);
final int offsetz = bz - (area.ROAD_WIDTH == 0 ? 0 : lower);
final RegionWrapper region = new RegionWrapper(bx, tx, bz, tz);
Set<PlotArea> areas = PS.get().getPlotAreas(area.worldname, region);
if (!areas.isEmpty()) {
C.CLUSTER_INTERSECTION.send(plr, areas.iterator().next().toString());
return false;
}
final SetupObject object = new SetupObject();
object.world = area.worldname;
object.id = area.id;
object.terrain = area.TERRAIN;
object.type = area.TYPE;
object.min = new PlotId(1, 1);
object.max = new PlotId(numx, numz);
object.plotManager = "PlotSquared";
object.setupGenerator = "PlotSquared";
object.step = area.getSettingNodes();
final String path = "worlds." + area.worldname + ".areas." + area.id + "-" + object.min + "-" + object.max;
CmdConfirm.addPending(plr, "/plot area create pos2 (Creates world)", new Runnable() {
@Override
public void run() {
if (offsetx != 0) {
PS.get().config.set(path + ".road.offset.x", offsetx);
}
if (offsetz != 0) {
PS.get().config.set(path + ".road.offset.z", offsetz);
}
final String world = SetupUtils.manager.setupWorld(object);
if (WorldUtil.IMP.isWorld(world)) {
PS.get().loadWorld(world, null);
C.SETUP_FINISHED.send(plr);
plr.teleport(WorldUtil.IMP.getSpawn(world));
if (area.TERRAIN != 3) {
ChunkManager.largeRegionTask(world, region, new RunnableVal<ChunkLoc>() {
@Override
public void run(final ChunkLoc value) {
AugmentedUtils.generate(world, value.x, value.z, null);
}
}, null);
}
} else {
MainUtil.sendMessage(plr, "An error occured while creating the world: " + area.worldname);
}
}
});
return true;
}
}
}
default: // Start creation
final SetupObject object = new SetupObject();
String[] split = args[1].split(":");
String id;
if (split.length == 2) {
id = split[1];
} else {
id = null;
}
object.world = split[0];
final HybridPlotWorld pa = new HybridPlotWorld(object.world, id, new HybridGen(), null, null);
PlotArea other = PS.get().getPlotArea(pa.worldname, id);
if (other != null && Objects.equals(pa.id, other.id)) {
C.SETUP_WORLD_TAKEN.send(plr, pa.toString());
return false;
}
Set<PlotArea> areas = PS.get().getPlotAreas(pa.worldname);
if (!areas.isEmpty()) {
PlotArea area = areas.iterator().next();
pa.TYPE = area.TYPE;
}
for (int i = 2; i < args.length; i++) {
String[] pair = args[i].split("=");
if (pair.length != 2) {
C.COMMAND_SYNTAX.send(plr, "/plot area create [world[:id]] [<modifier>=<value>]...");
return false;
}
switch (pair[0].toLowerCase()) {
case "s":
case "size": {
pa.PLOT_WIDTH = Integer.parseInt(pair[1]);
pa.SIZE = (short) (pa.PLOT_WIDTH + pa.ROAD_WIDTH);
break;
}
case "g":
case "gap": {
pa.ROAD_WIDTH = Integer.parseInt(pair[1]);
pa.SIZE = (short) (pa.PLOT_WIDTH + pa.ROAD_WIDTH);
break;
}
case "h":
case "height": {
int value = Integer.parseInt(pair[1]);
pa.PLOT_HEIGHT = value;
pa.ROAD_HEIGHT = value;
pa.WALL_HEIGHT = value;
break;
}
case "f":
case "floor": {
pa.TOP_BLOCK = Configuration.BLOCKLIST.parseString(pair[1]);
break;
}
case "m":
case "main": {
pa.MAIN_BLOCK = Configuration.BLOCKLIST.parseString(pair[1]);
break;
}
case "w":
case "wall": {
pa.WALL_FILLING = Configuration.BLOCK.parseString(pair[1]);
break;
}
case "b":
case "border": {
pa.WALL_BLOCK = Configuration.BLOCK.parseString(pair[1]);
break;
}
case "terrain": {
pa.TERRAIN = Integer.parseInt(pair[1]);
object.terrain = pa.TERRAIN;
break;
}
case "type": {
pa.TYPE = Integer.parseInt(pair[1]);
object.type = pa.TYPE;
break;
}
default: {
C.COMMAND_SYNTAX.send(plr, "/plot area create [world[:id]] [<modifier>=<value>]...");
return false;
}
}
}
if (pa.TYPE != 2) {
if (WorldUtil.IMP.isWorld(pa.worldname)) {
C.SETUP_WORLD_TAKEN.send(plr, pa.worldname);
return false;
}
CmdConfirm.addPending(plr, "/plot area " + StringMan.join(args, " "), new Runnable() {
@Override
public void run() {
String path = "worlds." + pa.worldname;
if (!PS.get().config.contains(path)) {
PS.get().config.createSection(path);
}
ConfigurationSection section = PS.get().config.getConfigurationSection(path);
pa.saveConfiguration(section);
pa.loadConfiguration(section);
object.plotManager = "PlotSquared";
object.setupGenerator = "PlotSquared";
String world = SetupUtils.manager.setupWorld(object);
if (WorldUtil.IMP.isWorld(world)) {
C.SETUP_FINISHED.send(plr);
plr.teleport(WorldUtil.IMP.getSpawn(world));
} else {
MainUtil.sendMessage(plr, "An error occured while creating the world: " + pa.worldname);
}
try {
PS.get().config.save(PS.get().configFile);
} catch (IOException e) {
e.printStackTrace();
}
}
});
return true;
}
if (pa.id == null) {
C.COMMAND_SYNTAX.send(plr, "/plot area create [world[:id]] [<modifier>=<value>]...");
return false;
}
if (WorldUtil.IMP.isWorld(pa.worldname)) {
if (!plr.getLocation().getWorld().equals(pa.worldname)) {
plr.teleport(WorldUtil.IMP.getSpawn(pa.worldname));
}
} else {
object.terrain = 0;
object.type = 0;
SetupUtils.manager.setupWorld(object);
plr.teleport(WorldUtil.IMP.getSpawn(pa.worldname));
}
plr.setMeta("area_create_area", pa);
MainUtil.sendMessage(plr, "$1Go to the first corner and use: $2/plot area create pos1");
break;
}
return true;
}
case "i":
case "info": {
if (!Permissions.hasPermission(plr, "plots.area.info")) {
C.NO_PERMISSION.send(plr, "plots.area.info");
return false;
}
PlotArea area;
switch (args.length) {
case 1:
area = plr.getApplicablePlotArea();
break;
case 2:
area = PS.get().getPlotAreaByString(args[1]);
break;
default:
C.COMMAND_SYNTAX.send(plr, "/plot area info [area]");
return false;
}
if (area == null) {
if (args.length == 2) {
C.NOT_VALID_PLOT_WORLD.send(plr, args[1]);
} else {
C.NOT_IN_PLOT_WORLD.send(plr);
}
return false;
}
String name;
double percent;
int claimed = area.getPlotCount();
int clusters = area.getClusters().size();
String region;
String generator = area.getGenerator() + "";
if (area.TYPE == 2) {
PlotId min = area.getMin();
PlotId max = area.getMax();
name = area.worldname + ";" + area.id + ";" + min + ";" + max;
int size = (max.x - min.x + 1) * (max.y - min.y + 1);
percent = claimed == 0 ? 0 : size / (double) claimed;
region = area.getRegion().toString();
} else {
name = area.worldname;
percent = claimed == 0 ? 0 : (100d * claimed) / (Integer.MAX_VALUE);
region = "N/A";
}
String value = "&r$1NAME: " + name
+ "\n$1Type: $2" + area.TYPE
+ "\n$1Terrain: $2" + area.TERRAIN
+ "\n$1Usage: $2" + String.format("%.2f", percent) + "%"
+ "\n$1Claimed: $2" + claimed
+ "\n$1Clusters: $2" + clusters
+ "\n$1Region: $2" + region
+ "\n$1Generator: $2" + generator;
MainUtil.sendMessage(plr, C.PLOT_INFO_HEADER.s() + '\n' + value + '\n' + C.PLOT_INFO_FOOTER.s(), false);
return true;
}
case "l":
case "list": {
if (!Permissions.hasPermission(plr, "plots.area.list")) {
C.NO_PERMISSION.send(plr, "plots.area.list");
return false;
}
int page;
switch (args.length) {
case 1:
page = 0;
break;
case 2:
if (MathMan.isInteger(args[1])) {
page = Integer.parseInt(args[1]);
break;
}
default:
C.COMMAND_SYNTAX.send(plr, "/plot area list [#]");
return false;
}
ArrayList<PlotArea> areas = new ArrayList<>(PS.get().getPlotAreas());
paginate(plr, areas, 8, page, new RunnableVal3<Integer, PlotArea, PlotMessage>() {
@Override
public void run(Integer i, PlotArea area, PlotMessage message) {
String name;
double percent;
int claimed = area.getPlotCount();
int clusters = area.getClusters().size();
String region;
String generator = area.getGenerator() + "";
if (area.TYPE == 2) {
PlotId min = area.getMin();
PlotId max = area.getMax();
name = area.worldname + ";" + area.id + ";" + min + ";" + max;
int size = (max.x - min.x + 1) * (max.y - min.y + 1);
percent = claimed == 0 ? 0 : size / (double) claimed;
region = area.getRegion().toString();
} else {
name = area.worldname;
percent = claimed == 0 ? 0 : Short.MAX_VALUE * Short.MAX_VALUE / (double) claimed;
region = "N/A";
}
PlotMessage tooltip = new PlotMessage()
.text("Claimed=").color("$1").text("" + claimed).color("$2")
.text("\nUsage=").color("$1").text(String.format("%.2f", percent) + "%").color("$2")
.text("\nClusters=").color("$1").text("" + clusters).color("$2")
.text("\nRegion=").color("$1").text(region).color("$2")
.text("\nGenerator=").color("$1").text(generator).color("$2");
// type / terrain
String visit = "/plot area tp " + area.toString();
message.text("[").color("$3")
.text(i + "").command(visit).tooltip(visit).color("$1")
.text("]").color("$3")
.text(" " + name).tooltip(tooltip).command("/plot area info " + area).color("$1").text(" - ").color("$2")
.text(area.TYPE + ":" + area.TERRAIN).color("$3");
}
}, "/plot area list", C.AREA_LIST_HEADER_PAGED.s());
return true;
}
case "regen":
case "regenerate": {
if (!Permissions.hasPermission(plr, "plots.area.regen")) {
C.NO_PERMISSION.send(plr, "plots.area.regen");
return false;
}
final PlotArea area = plr.getApplicablePlotArea();
if (area == null) {
C.NOT_IN_PLOT_WORLD.send(plr);
return false;
}
if (area.TYPE != 2) {
MainUtil.sendMessage(plr, "$4Stop the server and delete: " + area.worldname + "/region");
return false;
}
ChunkManager.largeRegionTask(area.worldname, area.getRegion(), new RunnableVal<ChunkLoc>() {
@Override
public void run(ChunkLoc value) {
AugmentedUtils.generate(area.worldname, value.x, value.z, null);
}
}, null);
return true;
}
case "goto":
case "v":
case "teleport":
case "visit":
case "tp": {
if (!Permissions.hasPermission(plr, "plots.area.tp")) {
C.NO_PERMISSION.send(plr, "plots.area.tp");
return false;
}
if (args.length != 2) {
C.COMMAND_SYNTAX.send(plr, "/plot visit [area]");
return false;
}
PlotArea area = PS.get().getPlotAreaByString(args[1]);
if (area == null) {
C.NOT_VALID_PLOT_WORLD.send(plr, args[1]);
return false;
}
RegionWrapper region = area.getRegion();
Location center = new Location(area.worldname, region.minX + (region.maxX - region.minX) / 2, 0, region.minZ + (region.maxZ - region.minZ) / 2);
center.setY(WorldUtil.IMP.getHighestBlock(area.worldname, center.getX(), center.getZ()));
plr.teleport(center);
return true;
}
case "delete":
case "remove": {
MainUtil.sendMessage(plr, "$1World creation settings may be stored in multiple locations:"
+ "\n$3 - $2Bukkit bukkit.yml"
+ "\n$3 - $2PlotSquared settings.yml"
+ "\n$3 - $2Multiverse worlds.yml (or any world management plugin)"
+ "\n$1Stop the server and delete it from these locations.");
return true;
}
}
C.COMMAND_SYNTAX.send(plr, getUsage());
return false;
}
}

View File

@ -20,16 +20,13 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotCluster;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.PlotWorld;
import com.intellectualcrafters.plot.util.ClusterManager;
import com.intellectualcrafters.plot.util.ByteArrayUtilities;
import com.intellectualcrafters.plot.util.EconHandler;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions;
@ -42,11 +39,10 @@ import com.plotsquared.general.commands.CommandDeclaration;
requiredType = RequiredType.NONE,
description = "Claim the nearest plot",
aliases = { "a" },
usage = "/plot auto"
)
usage = "/plot auto [length,width]")
public class Auto extends SubCommand {
public static PlotId getNextPlot(final PlotId id, final int step) {
public static PlotId getNextPlotId(final PlotId id, final int step) {
final int absX = Math.abs(id.x);
final int absY = Math.abs(id.y);
if (absX > absY) {
@ -76,37 +72,28 @@ public class Auto extends SubCommand {
}
@Override
public boolean onCommand(PlotPlayer plr, String[] args) {
String world;
int size_x = 1;
int size_z = 1;
String schematic = "";
if (PS.get().getPlotWorlds().size() == 1) {
world = PS.get().getPlotWorlds().iterator().next();
} else {
world = plr.getLocation().getWorld();
if (!PS.get().isPlotWorld(world)) {
public boolean onCommand(final PlotPlayer plr, final String[] args) {
PlotArea plotarea = plr.getApplicablePlotArea();
if (plotarea == null) {
MainUtil.sendMessage(plr, C.NOT_IN_PLOT_WORLD);
return false;
}
}
int size_x = 1;
int size_z = 1;
String schematic = null;
if (args.length > 0) {
if (Permissions.hasPermission(plr, "plots.auto.mega")) {
try {
final String[] split = args[0].split(",");
final String[] split = args[0].split(",|;");
size_x = Integer.parseInt(split[0]);
size_z = Integer.parseInt(split[1]);
if ((size_x < 1) || (size_z < 1)) {
MainUtil.sendMessage(plr, "&cError: size<=0");
}
if ((size_x > 4) || (size_z > 4)) {
MainUtil.sendMessage(plr, "&cError: size>4");
}
if (args.length > 1) {
schematic = args[1];
}
} catch (final Exception e) {
} catch (NumberFormatException e) {
size_x = 1;
size_z = 1;
schematic = args[0];
@ -124,19 +111,31 @@ public class Auto extends SubCommand {
MainUtil.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS_NUM, Settings.MAX_AUTO_SIZE + "");
return false;
}
final int currentPlots = Settings.GLOBAL_LIMIT ? MainUtil.getPlayerPlotCount(plr) : MainUtil.getPlayerPlotCount(world, plr);
final int diff = currentPlots - MainUtil.getAllowedPlots(plr);
int removeGrants = 0;
final int currentPlots = Settings.GLOBAL_LIMIT ? plr.getPlotCount() : plr.getPlotCount(plotarea.worldname);
final int diff = currentPlots - plr.getAllowedPlots();
if ((diff + (size_x * size_z)) > 0) {
if (diff < 0) {
MainUtil.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS_NUM, (-diff) + "");
} else {
if (plr.hasPersistentMeta("grantedPlots")) {
int grantedPlots = ByteArrayUtilities.bytesToInteger(plr.getPersistentMeta("grantedPlots"));
if (grantedPlots < size_x * size_z) {
plr.removePersistentMeta("grantedPlots");
return sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS);
} else {
removeGrants = size_x * size_z;
}
} else {
MainUtil.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS);
}
}
if (removeGrants == 0) {
return false;
}
final PlotWorld pWorld = PS.get().getPlotWorld(world);
if ((EconHandler.manager != null) && pWorld.USE_ECONOMY) {
double cost = pWorld.PLOT_PRICE;
}
if ((EconHandler.manager != null) && plotarea.USE_ECONOMY) {
double cost = plotarea.PLOT_PRICE;
cost = (size_x * size_z) * cost;
if (cost > 0d) {
if (EconHandler.manager.getMoney(plr) < cost) {
@ -147,9 +146,13 @@ public class Auto extends SubCommand {
sendMessage(plr, C.REMOVED_BALANCE, cost + "");
}
}
if (!schematic.equals("")) {
// if (pWorld.SCHEMATIC_CLAIM_SPECIFY) {
if (!pWorld.SCHEMATICS.contains(schematic.toLowerCase())) {
if (removeGrants > 0) {
int grantedPlots = ByteArrayUtilities.bytesToInteger(plr.getPersistentMeta("grantedPlots"));
plr.setPersistentMeta("grantedPlots", ByteArrayUtilities.integerToBytes(grantedPlots - removeGrants));
sendMessage(plr, C.REMOVED_GRANTED_PLOT, "" + removeGrants, "" + (grantedPlots - removeGrants));
}
if (schematic != null && !schematic.equals("")) {
if (!plotarea.SCHEMATICS.contains(schematic.toLowerCase())) {
sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent: " + schematic);
return true;
}
@ -157,24 +160,10 @@ public class Auto extends SubCommand {
MainUtil.sendMessage(plr, C.NO_SCHEMATIC_PERMISSION, schematic);
return true;
}
// }
}
final String worldname = world;
final PlotWorld plotworld = PS.get().getPlotWorld(worldname);
if (plotworld.TYPE == 2) {
final Location loc = plr.getLocation();
final Plot plot = MainUtil.getPlot(new Location(worldname, loc.getX(), loc.getY(), loc.getZ()));
if (plot == null) {
return sendMessage(plr, C.NOT_IN_PLOT);
}
final PlotCluster cluster = ClusterManager.getCluster(loc);
// Must be standing in a cluster
if (cluster == null) {
MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER);
return false;
}
final PlotId bot = cluster.getP1();
final PlotId top = cluster.getP2();
if (plotarea.TYPE == 2) {
final PlotId bot = plotarea.getMin();
final PlotId top = plotarea.getMax();
final PlotId origin = new PlotId((bot.x + top.x) / 2, (bot.y + top.y) / 2);
PlotId id = new PlotId(0, 0);
final int width = Math.max((top.x - bot.x) + 1, (top.y - bot.y) + 1);
@ -182,12 +171,12 @@ public class Auto extends SubCommand {
//
for (int i = 0; i <= max; i++) {
final PlotId currentId = new PlotId(origin.x + id.x, origin.y + id.y);
final Plot current = MainUtil.getPlot(worldname, currentId);
if (MainUtil.canClaim(plr, current) && (current.getSettings().isMerged() == false) && cluster.equals(ClusterManager.getCluster(current))) {
Plot current = plotarea.getPlotAbs(currentId);
if (current.canClaim(plr)) {
Claim.claimPlot(plr, current, true, true);
return true;
}
id = getNextPlot(id, 1);
id = getNextPlotId(id, 1);
}
// no free plots
MainUtil.sendMessage(plr, C.NO_FREE_PLOTS);
@ -196,50 +185,44 @@ public class Auto extends SubCommand {
boolean br = false;
if ((size_x == 1) && (size_z == 1)) {
while (!br) {
final Plot plot = MainUtil.getPlot(worldname, getLastPlot(worldname));
if (MainUtil.canClaim(plr, plot)) {
Plot plot = plotarea.getPlotAbs(getLastPlotId(plotarea));
if (plot.canClaim(plr)) {
Claim.claimPlot(plr, plot, true, true);
br = true;
}
MainUtil.lastPlot.put(worldname, getNextPlot(getLastPlot(worldname), 1));
plotarea.setMeta("lastPlot", getNextPlotId(plot.getId(), 1));
}
} else {
boolean lastPlot = true;
while (!br) {
final PlotId start = getNextPlot(getLastPlot(worldname), 1);
// Checking if the current set of plots is a viable option.
MainUtil.lastPlot.put(worldname, start);
if (lastPlot) {
}
if ((PS.get().getPlot(worldname, start) != null) && (PS.get().getPlot(worldname, start).owner != null)) {
continue;
} else {
lastPlot = false;
}
final PlotId start = getNextPlotId(getLastPlotId(plotarea), 1);
final PlotId end = new PlotId((start.x + size_x) - 1, (start.y + size_z) - 1);
if (MainUtil.canClaim(plr, worldname, start, end)) {
plotarea.setMeta("lastPlot", start);
if (plotarea.canClaim(plr, start, end)) {
for (int i = start.x; i <= end.x; i++) {
for (int j = start.y; j <= end.y; j++) {
final Plot plot = MainUtil.getPlot(worldname, new PlotId(i, j));
Plot plot = plotarea.getPlotAbs(new PlotId(i, j));
final boolean teleport = ((i == end.x) && (j == end.y));
Claim.claimPlot(plr, plot, teleport, true);
}
}
if (!MainUtil.mergePlots(worldname, MainUtil.getPlotSelectionIds(start, end), true, true)) {
if (!plotarea.mergePlots(MainUtil.getPlotSelectionIds(start, end), Settings.MERGE_REMOVES_ROADS, true)) {
return false;
}
br = true;
}
}
}
MainUtil.lastPlot.put(worldname, new PlotId(0, 0));
plotarea.setMeta("lastPlot", new PlotId(0, 0));
return true;
}
public PlotId getLastPlot(final String world) {
if ((MainUtil.lastPlot == null) || !MainUtil.lastPlot.containsKey(world)) {
MainUtil.lastPlot.put(world, new PlotId(0, 0));
public PlotId getLastPlotId(final PlotArea area) {
PlotId value = (PlotId) area.getMeta("lastPlot");
if (value == null) {
value = new PlotId(0, 0);
area.setMeta("lastPlot", value);
return value;
}
return MainUtil.lastPlot.get(world);
return value;
}
}

View File

@ -21,33 +21,18 @@
package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.generator.HybridUtils;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotAnalysis;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.util.BO3Handler;
import com.intellectualcrafters.plot.util.BlockManager;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(
command = "bo3",
aliases = {"bo2"},
description = "Mark a plot as done",
permission = "plots.done",
category = CommandCategory.ACTIONS,
requiredType = RequiredType.NONE
)
@CommandDeclaration(command = "bo3", aliases = { "bo2" }, description = "Mark a plot as done", permission = "plots.bo3", category = CommandCategory.SCHEMATIC, requiredType = RequiredType.NONE)
public class BO3 extends SubCommand {
public void noArgs(PlotPlayer plr) {
public void noArgs(final PlotPlayer plr) {
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot bo3 export [category] [alias] [-r]");
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot bo3 import <file>");
}
@ -55,8 +40,8 @@ public class BO3 extends SubCommand {
@Override
public boolean onCommand(final PlotPlayer plr, final String[] args) {
final Location loc = plr.getLocation();
final Plot plot = MainUtil.getPlot(loc);
if (plot == null || !plot.hasOwner()) {
final Plot plot = loc.getPlotAbs();
if ((plot == null) || !plot.hasOwner()) {
return !sendMessage(plr, C.NOT_IN_PLOT);
}
if ((!plot.isOwner(plr.getUUID())) && !Permissions.hasPermission(plr, "plots.admin.command.bo3")) {

View File

@ -20,51 +20,43 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.generator.SquarePlotWorld;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.WorldUtil;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(
command = "debugclear",
aliases = {"fastclear"},
description = "Clear a plot using a fast experiment algorithm",
category = CommandCategory.DEBUG
)
public class DebugClear extends SubCommand {
command = "setbiome",
permission = "plots.set.biome",
description = "Set the plot biome",
usage = "/plot biome [biome]",
aliases = { "biome", "sb", "setb", "b" },
category = CommandCategory.APPEARANCE,
requiredType = RequiredType.NONE)
public class Biome extends SetCommand {
@Override
public boolean onCommand(final PlotPlayer plr, String[] args) {
final Location loc = plr.getLocation();
final Plot plot = MainUtil.getPlot(loc);
if ((plot == null) || !(PS.get().getPlotWorld(loc.getWorld()) instanceof SquarePlotWorld)) {
return sendMessage(plr, C.NOT_IN_PLOT);
public boolean set(final PlotPlayer plr, final Plot plot, final String value) {
final int biome = WorldUtil.IMP.getBiomeFromString(value);
if (biome == -1) {
String biomes = StringMan.join(WorldUtil.IMP.getBiomeList(), C.BLOCK_LIST_SEPARATER.s());
C.NEED_BIOME.send(plr);
MainUtil.sendMessage(plr, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + biomes);
return false;
}
if (!MainUtil.getTopPlot(plot).equals(MainUtil.getBottomPlot(plot))) {
return sendMessage(plr, C.UNLINK_REQUIRED);
}
if ((!plot.hasOwner() || !plot.isOwner(UUIDHandler.getUUID(plr))) && !Permissions.hasPermission(plr, "plots.admin.command.debugclear")) {
return sendMessage(plr, C.NO_PLOT_PERMS);
}
final Location pos1 = MainUtil.getPlotBottomLoc(loc.getWorld(), plot.id).add(1, 0, 1);
final Location pos2 = MainUtil.getPlotTopLoc(loc.getWorld(), plot.id);
if (MainUtil.runners.containsKey(plot)) {
if (plot.getRunning() > 0) {
MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER);
return false;
}
MainUtil.runners.put(plot, 1);
ChunkManager.manager.regenerateRegion(pos1, pos2, new Runnable() {
plot.addRunning();
plot.setBiome(value.toUpperCase(), new Runnable() {
@Override
public void run() {
MainUtil.runners.remove(plot);
MainUtil.sendMessage(plr, "&aDone!");
plot.removeRunning();
MainUtil.sendMessage(plr, C.BIOME_SET_TO.s() + value.toLowerCase());
}
});
return true;

View File

@ -20,18 +20,15 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import java.util.Set;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotHandler;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.PlotWorld;
import com.intellectualcrafters.plot.util.EconHandler;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.UUIDHandler;
@ -44,79 +41,68 @@ import com.plotsquared.general.commands.CommandDeclaration;
usage = "/plot buy",
permission = "plots.buy",
category = CommandCategory.CLAIMING,
requiredType = RequiredType.NONE
)
requiredType = RequiredType.NONE)
public class Buy extends SubCommand {
@Override
public boolean onCommand(final PlotPlayer plr, final String... args) {
if (EconHandler.manager == null) {
return sendMessage(plr, C.ECON_DISABLED);
}
final Location loc = plr.getLocation();
final String world = loc.getWorld();
if (!PS.get().isPlotWorld(world)) {
if (!PS.get().hasPlotArea(world)) {
return sendMessage(plr, C.NOT_IN_PLOT_WORLD);
}
Set<Plot> plots;
Plot plot;
if (args.length > 0) {
try {
final String[] split = args[0].split(";");
final PlotId id = new PlotId(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
plot = MainUtil.getPlot(world, id);
plot = MainUtil.getPlotFromString(plr, world, true);
if (plot == null) {
return false;
}
plots = plot.getConnectedPlots();
} catch (final Exception e) {
return sendMessage(plr, C.NOT_VALID_PLOT_ID);
}
} else {
plot = MainUtil.getPlot(loc);
plot = loc.getPlotAbs();
plots = plot.getConnectedPlots();
}
if (plot == null) {
if (plots == null) {
return sendMessage(plr, C.NOT_IN_PLOT);
}
final int currentPlots = Settings.GLOBAL_LIMIT ? MainUtil.getPlayerPlotCount(plr) : MainUtil.getPlayerPlotCount(world, plr);
if (currentPlots >= MainUtil.getAllowedPlots(plr)) {
return sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS);
}
if (!plot.hasOwner()) {
return sendMessage(plr, C.PLOT_UNOWNED);
}
if (PlotHandler.isOwner(plot, plr.getUUID())) {
return sendMessage(plr, C.CANNOT_BUY_OWN);
final int currentPlots = plr.getPlotCount() + plots.size();
if (currentPlots > plr.getAllowedPlots()) {
return sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS);
}
final Flag flag = FlagManager.getPlotFlag(plot, "price");
final Flag flag = FlagManager.getPlotFlagRaw(plot, "price");
if (flag == null) {
return sendMessage(plr, C.NOT_FOR_SALE);
}
double initPrice = (double) flag.getValue();
double price = initPrice;
final PlotId id = plot.id;
final PlotId id2 = MainUtil.getTopPlot(plot).id;
final int size = MainUtil.getPlotSelectionIds(id, id2).size();
final PlotWorld plotworld = PS.get().getPlotWorld(world);
if (plotworld.USE_ECONOMY) {
price += plotworld.PLOT_PRICE * size;
initPrice += plotworld.SELL_PRICE * size;
if (plot.isOwner(plr.getUUID())) {
return sendMessage(plr, C.CANNOT_BUY_OWN);
}
double price = (double) flag.getValue();
if ((EconHandler.manager != null) && (price > 0d)) {
if (EconHandler.manager.getMoney(plr) < price) {
return sendMessage(plr, C.CANNOT_AFFORD_PLOT, "" + price);
}
EconHandler.manager.withdrawMoney(plr, price);
sendMessage(plr, C.REMOVED_BALANCE, price + "");
EconHandler.manager.depositMoney(UUIDHandler.getUUIDWrapper().getOfflinePlayer(plot.owner), initPrice);
EconHandler.manager.depositMoney(UUIDHandler.getUUIDWrapper().getOfflinePlayer(plot.owner), price);
final PlotPlayer owner = UUIDHandler.getPlayer(plot.owner);
if (owner != null) {
sendMessage(plr, C.PLOT_SOLD, plot.id + "", plr.getName(), initPrice + "");
sendMessage(plr, C.PLOT_SOLD, plot.getId() + "", plr.getName(), price + "");
}
FlagManager.removePlotFlag(plot, "price");
}
Plot top = MainUtil.getTopPlot(plot);
for (PlotId myId : MainUtil.getPlotSelectionIds(plot.id, top.id)) {
Plot myPlot = MainUtil.getPlot(plot.world, myId);
myPlot.owner = plr.getUUID();
DBFunc.setOwner(plot, myPlot.owner);
for (final Plot current : plots) {
plot.setOwner(plr.getUUID());
}
MainUtil.sendMessage(plr, C.CLAIMED);
return true;

View File

@ -1,19 +1,15 @@
package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.PlotWorld;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(
command = "chat",
description = "Toggle plto chant on or off",
description = "Toggle plot chat on or off",
usage = "/plot chat [on|off]",
permission = "plots.chat",
category = CommandCategory.ACTIONS,
requiredType = RequiredType.NONE
)
category = CommandCategory.CHAT,
requiredType = RequiredType.NONE)
public class Chat extends SubCommand {
@Override

View File

@ -20,14 +20,14 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.PlotWorld;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.util.ByteArrayUtilities;
import com.intellectualcrafters.plot.util.EconHandler;
import com.intellectualcrafters.plot.util.EventUtil;
import com.intellectualcrafters.plot.util.MainUtil;
@ -43,8 +43,7 @@ import com.plotsquared.general.commands.CommandDeclaration;
category = CommandCategory.CLAIMING,
requiredType = RequiredType.NONE,
permission = "plots.claim",
usage = "/plot claim"
)
usage = "/plot claim")
public class Claim extends SubCommand {
public static boolean claimPlot(final PlotPlayer player, final Plot plot, final boolean teleport, final boolean auto) {
@ -52,24 +51,21 @@ public class Claim extends SubCommand {
}
public static boolean claimPlot(final PlotPlayer player, final Plot plot, final boolean teleport, final String schematic, final boolean auto) {
if (plot.hasOwner() || plot.getSettings().isMerged()) {
if (plot.hasOwner() || plot.isMerged()) {
return false;
}
final boolean result = EventUtil.manager.callClaim(player, plot, false);
if (result) {
MainUtil.createPlot(player.getUUID(), plot);
MainUtil.setSign(player.getName(), plot);
plot.create(player.getUUID(), true);
plot.setSign(player.getName());
MainUtil.sendMessage(player, C.CLAIMED);
final Location loc = player.getLocation();
if (teleport) {
MainUtil.teleportPlayer(player, loc, plot);
plot.teleportPlayer(player);
}
final String world = plot.world;
final PlotWorld plotworld = PS.get().getPlotWorld(world);
final Plot plot2 = PS.get().getPlot(world, plot.id);
final PlotArea plotworld = plot.getArea();
if (plotworld.SCHEMATIC_ON_CLAIM) {
Schematic sch;
if (schematic.equals("")) {
if (schematic.isEmpty()) {
sch = SchematicHandler.manager.getSchematic(plotworld.SCHEMATIC_FILE);
} else {
sch = SchematicHandler.manager.getSchematic(schematic);
@ -77,43 +73,52 @@ public class Claim extends SubCommand {
sch = SchematicHandler.manager.getSchematic(plotworld.SCHEMATIC_FILE);
}
}
SchematicHandler.manager.paste(sch, plot2, 0, 0, new RunnableVal<Boolean>() {
SchematicHandler.manager.paste(sch, plot, 0, 0, new RunnableVal<Boolean>() {
@Override
public void run() {
public void run(Boolean value) {
if (value) {
MainUtil.sendMessage(player, C.SCHEMATIC_PASTE_SUCCESS);
}
else {
} else {
MainUtil.sendMessage(player, C.SCHEMATIC_PASTE_FAILED);
}
}
});
}
PS.get().getPlotManager(world).claimPlot(plotworld, plot);
plotworld.getPlotManager().claimPlot(plotworld, plot);
}
return result;
}
@Override
public boolean onCommand(final PlotPlayer plr, final String... args) {
String schematic = "";
if (args.length >= 1) {
schematic = args[0];
}
final Location loc = plr.getLocation();
final Plot plot = MainUtil.getPlot(loc);
final Plot plot = loc.getPlotAbs();
if (plot == null) {
return sendMessage(plr, C.NOT_IN_PLOT);
}
final int currentPlots = Settings.GLOBAL_LIMIT ? MainUtil.getPlayerPlotCount(plr) : MainUtil.getPlayerPlotCount(loc.getWorld(), plr);
if (currentPlots >= MainUtil.getAllowedPlots(plr)) {
final int currentPlots = Settings.GLOBAL_LIMIT ? plr.getPlotCount() : plr.getPlotCount(loc.getWorld());
boolean removeGrantedPlot = false;
if (currentPlots >= plr.getAllowedPlots()) {
if (plr.hasPersistentMeta("grantedPlots")) {
int grantedPlots = ByteArrayUtilities.bytesToInteger(plr.getPersistentMeta("grantedPlots"));
if (grantedPlots < 1) {
plr.removePersistentMeta("grantedPlots");
return sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS);
} else {
removeGrantedPlot = true;
}
} else {
return sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS);
}
if (!MainUtil.canClaim(plr, plot)) {
}
if (!plot.canClaim(plr)) {
return sendMessage(plr, C.PLOT_IS_CLAIMED);
}
final PlotWorld world = PS.get().getPlotWorld(plot.world);
final PlotArea world = plot.getArea();
if ((EconHandler.manager != null) && world.USE_ECONOMY) {
final double cost = world.PLOT_PRICE;
if (cost > 0d) {
@ -124,6 +129,11 @@ public class Claim extends SubCommand {
sendMessage(plr, C.REMOVED_BALANCE, cost + "");
}
}
if (removeGrantedPlot) {
int grantedPlots = ByteArrayUtilities.bytesToInteger(plr.getPersistentMeta("grantedPlots"));
plr.setPersistentMeta("grantedPlots", ByteArrayUtilities.integerToBytes(grantedPlots - 1));
sendMessage(plr, C.REMOVED_GRANTED_PLOT, "1", "" + (grantedPlots - 1));
}
if (!schematic.equals("")) {
if (world.SCHEMATIC_CLAIM_SPECIFY) {
if (!world.SCHEMATICS.contains(schematic.toLowerCase())) {

View File

@ -22,102 +22,101 @@ package com.intellectualcrafters.plot.commands;
import java.util.Set;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.CmdConfirm;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.SetQueue;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(
command = "clear",
description = "Clear a plot",
permission = "plots.clear",
category = CommandCategory.ACTIONS,
usage = "/plot clear [id]"
)
@CommandDeclaration(command = "clear", description = "Clear a plot", permission = "plots.clear", category = CommandCategory.APPEARANCE,
usage = "/plot clear [id]", aliases = "reset")
public class Clear extends SubCommand {
@Override
public boolean onCommand(final PlotPlayer plr, final String... args) {
final Location loc = plr.getLocation();
final Plot plot;
if (args.length == 2) {
PlotId id = PlotId.fromString(args[0]);
if (id == null) {
if (args[1].equalsIgnoreCase("mine")) {
Set<Plot> plots = PS.get().getPlots(plr);
if (plots.size() == 0) {
if (args.length == 1) {
if (args[0].equalsIgnoreCase("mine")) {
Set<Plot> plots = plr.getPlots();
if (!plots.isEmpty()) {
plot = plots.iterator().next();
} else {
MainUtil.sendMessage(plr, C.NO_PLOTS);
return false;
}
plot = plots.iterator().next();
}
else {
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot clear [X;Z|mine]");
return false;
}
}
else {
plot = MainUtil.getPlot(loc.getWorld(), id);
}
}
else {
plot = MainUtil.getPlot(loc);
} else {
plot = MainUtil.getPlotFromString(plr, args[0], true);
}
if (plot == null) {
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot clear [X;Z|mine]");
return sendMessage(plr, C.NOT_IN_PLOT);
return false;
}
if (!MainUtil.getTopPlot(plot).equals(MainUtil.getBottomPlot(plot))) {
return sendMessage(plr, C.UNLINK_REQUIRED);
} else if (args.length == 0) {
plot = loc.getPlotAbs();
if (plot == null) {
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot clear [X;Z|mine]");
C.NOT_IN_PLOT.send(plr);
return false;
}
if (((plot == null) || !plot.hasOwner() || !plot.isOwner(UUIDHandler.getUUID(plr))) && !Permissions.hasPermission(plr, "plots.admin.command.clear")) {
} else {
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot clear [X;Z|mine]");
return false;
}
if ((!plot.hasOwner() || !plot.isOwner(plr.getUUID())) && !Permissions.hasPermission(plr, "plots.admin.command.clear")) {
return sendMessage(plr, C.NO_PLOT_PERMS);
}
assert plot != null;
if (MainUtil.runners.containsKey(plot)) {
if (plot.getRunning() != 0) {
MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER);
return false;
}
if (Settings.DONE_RESTRICTS_BUILDING && FlagManager.isPlotFlagTrue(plot, "done" ) && (!Permissions.hasPermission(plr, "plots.continue") || (Settings.DONE_COUNTS_TOWARDS_LIMIT && MainUtil.getAllowedPlots(plr) >= MainUtil.getPlayerPlotCount(plr)))) {
if ((FlagManager.getPlotFlagRaw(plot, "done") != null)
&& (!Permissions.hasPermission(plr, "plots.continue") || (Settings.DONE_COUNTS_TOWARDS_LIMIT && (plr.getAllowedPlots() >= plr.getPlotCount())))) {
MainUtil.sendMessage(plr, C.DONE_ALREADY_DONE);
return false;
}
Runnable runnable = new Runnable() {
final Runnable runnable = new Runnable() {
@Override
public void run() {
final long start = System.currentTimeMillis();
final boolean result = MainUtil.clearAsPlayer(plot, plot.owner == null, new Runnable() {
final boolean result = plot.clear(true, false, new Runnable() {
@Override
public void run() {
plot.unlink();
SetQueue.IMP.addTask(new Runnable() {
@Override
public void run() {
plot.removeRunning();
// If the state changes, then mark it as no longer done
if (FlagManager.getPlotFlag(plot, "done" ) != null) {
if (FlagManager.getPlotFlagRaw(plot, "done") != null) {
FlagManager.removePlotFlag(plot, "done");
}
if (FlagManager.getPlotFlag(plot, "analysis") != null) {
if (FlagManager.getPlotFlagRaw(plot, "analysis") != null) {
FlagManager.removePlotFlag(plot, "analysis");
}
MainUtil.sendMessage(plr, C.CLEARING_DONE, "" + (System.currentTimeMillis() - start));
}
});
}
});
if (!result) {
MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER);
}
else {
plot.addRunning();
}
}
};
if (Settings.CONFIRM_CLEAR && !(Permissions.hasPermission(plr, "plots.confirm.bypass"))) {
CmdConfirm.addPending(plr, "/plot clear " + plot.id, runnable);
}
else {
CmdConfirm.addPending(plr, "/plot clear " + plot.getId(), runnable);
} else {
TaskManager.runTask(runnable);
}
return true;

View File

@ -22,40 +22,34 @@ package com.intellectualcrafters.plot.commands;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.generator.PlotGenerator;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.object.BlockLoc;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotCluster;
import com.intellectualcrafters.plot.object.PlotClusterId;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.PlotWorld;
import com.intellectualcrafters.plot.util.ClusterManager;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.SetupUtils;
import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.UUIDHandler;
//import com.plotsquared.bukkit.generator.AugmentedPopulator;
//import com.plotsquared.bukkit.generator.AugmentedPopulator;
//import com.plotsquared.bukkit.generator.BukkitPlotGenerator;
//import com.plotsquared.bukkit.generator.HybridGen;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(
command = "cluster",
aliases = { "clusters" },
category = CommandCategory.ACTIONS,
category = CommandCategory.ADMINISTRATION,
requiredType = RequiredType.NONE,
permission = "plots.cluster",
description = "Manage a plot cluster"
)
description = "Manage a plot cluster")
public class Cluster extends SubCommand {
@Override
@ -79,16 +73,17 @@ public class Cluster extends SubCommand {
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster list");
return false;
}
final HashSet<PlotCluster> clusters = ClusterManager.getClusters(plr.getLocation().getWorld());
PlotArea area = plr.getApplicablePlotArea();
final Set<PlotCluster> clusters = area.getClusters();
MainUtil.sendMessage(plr, C.CLUSTER_LIST_HEADING, clusters.size() + "");
for (final PlotCluster cluster : clusters) {
// Ignore unmanaged clusters
final String name = "'" + cluster.getName() + "' : " + cluster.toString();
if (UUIDHandler.getUUID(plr).equals(cluster.owner)) {
if (plr.getUUID().equals(cluster.owner)) {
MainUtil.sendMessage(plr, C.CLUSTER_LIST_ELEMENT, "&a" + name);
} else if (cluster.helpers.contains(UUIDHandler.getUUID(plr))) {
} else if (cluster.helpers.contains(plr.getUUID())) {
MainUtil.sendMessage(plr, C.CLUSTER_LIST_ELEMENT, "&3" + name);
} else if (cluster.invited.contains(UUIDHandler.getUUID(plr))) {
} else if (cluster.invited.contains(plr.getUUID())) {
MainUtil.sendMessage(plr, C.CLUSTER_LIST_ELEMENT, "&9" + name);
} else {
MainUtil.sendMessage(plr, C.CLUSTER_LIST_ELEMENT, cluster.toString());
@ -102,87 +97,79 @@ public class Cluster extends SubCommand {
MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.create");
return false;
}
PlotArea area = plr.getApplicablePlotArea();
if (area == null) {
C.NOT_IN_PLOT_WORLD.send(plr);
return false;
}
if (args.length != 4) {
final PlotId id = ClusterManager.estimatePlotId(plr.getLocation());
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster create <name> <id-bot> <id-top>");
MainUtil.sendMessage(plr, C.CLUSTER_CURRENT_PLOTID, "" + id);
return false;
}
// check pos1 / pos2
PlotId pos1 = MainUtil.parseId(args[2]);
PlotId pos2 = MainUtil.parseId(args[3]);
PlotId pos1 = PlotId.fromString(args[2]);
PlotId pos2 = PlotId.fromString(args[3]);
if ((pos1 == null) || (pos2 == null)) {
MainUtil.sendMessage(plr, C.NOT_VALID_PLOT_ID);
return false;
}
// check if name is taken
final String name = args[1];
for (final PlotCluster cluster : ClusterManager.getClusters(plr.getLocation().getWorld())) {
if (name.equals(cluster.getName())) {
if (area.getCluster(name) != null) {
MainUtil.sendMessage(plr, C.ALIAS_IS_TAKEN);
return false;
}
if ((pos2.x < pos1.x) || (pos2.y < pos1.y)) {
PlotId tmp = new PlotId(Math.min(pos1.x, pos2.x), Math.min(pos1.y, pos2.y));
pos2 = new PlotId(Math.max(pos1.x, pos2.x), Math.max(pos1.y, pos2.y));
pos1 = tmp;
}
//check if overlap
final PlotClusterId id = new PlotClusterId(pos1, pos2);
final HashSet<PlotCluster> intersects = ClusterManager.getIntersects(plr.getLocation().getWorld(), id);
if ((intersects.size() > 0)) {
MainUtil.sendMessage(plr, C.CLUSTER_INTERSECTION, intersects.size() + "");
PlotCluster cluster = area.getFirstIntersectingCluster(pos1, pos2);
if (cluster != null) {
MainUtil.sendMessage(plr, C.CLUSTER_INTERSECTION, cluster.getName());
return false;
}
if ((pos2.x < pos1.x) || (pos2.y < pos1.y) ) {
pos1 = new PlotId(Math.min(pos1.x, pos2.x), Math.min(pos1.y, pos2.y));
pos2 = new PlotId(Math.max(pos1.x, pos2.x), Math.max(pos1.y, pos2.y));
// Check if it occupies existing plots
final Set<Plot> plots = area.getPlotSelectionOwned(pos1, pos2);
if (!plots.isEmpty()) {
if (!Permissions.hasPermission(plr, "plots.cluster.create.other")) {
final UUID uuid = plr.getUUID();
for (final Plot plot : plots) {
if (!plot.isOwner(uuid)) {
MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.create.other");
return false;
}
}
}
}
// Check allowed cluster size
cluster = new PlotCluster(area, pos1, pos2, plr.getUUID());
int current;
if (Settings.GLOBAL_LIMIT) {
current = plr.getPlayerClusterCount();
} else {
current = plr.getPlayerClusterCount(plr.getLocation().getWorld());
}
final int allowed = Permissions.hasPermissionRange(plr, "plots.cluster", Settings.MAX_PLOTS);
if ((current + cluster.getArea()) > allowed) {
MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster." + (current + cluster.getArea()));
return false;
}
// create cluster
final String world = plr.getLocation().getWorld();
final PlotCluster cluster = new PlotCluster(world, pos1, pos2, UUIDHandler.getUUID(plr));
cluster.settings.setAlias(name);
DBFunc.createCluster(world, cluster);
if (!ClusterManager.clusters.containsKey(world)) {
ClusterManager.clusters.put(world, new HashSet<PlotCluster>());
}
ClusterManager.clusters.get(world).add(cluster);
area.addCluster(cluster);
DBFunc.createCluster(cluster);
// Add any existing plots to the current cluster
for (final Plot plot : PS.get().getPlotsInWorld(plr.getLocation().getWorld())) {
final PlotCluster current = ClusterManager.getCluster(plot);
if (cluster.equals(current) && !cluster.isAdded(plot.owner)) {
for (final Plot plot : plots) {
if (plot.hasOwner()) {
final Flag flag = new Flag(FlagManager.getFlag("cluster"), cluster);
FlagManager.addPlotFlag(plot, flag);
if (!cluster.isAdded(plot.owner)) {
cluster.invited.add(plot.owner);
DBFunc.setInvited(world, cluster, plot.owner);
DBFunc.setInvited(cluster, plot.owner);
}
}
PlotWorld plotworld = PS.get().getPlotWorld(world);
if (plotworld == null) {
PS.get().config.createSection("worlds." + world);
PS.get().loadWorld(world, PS.get().IMP.getGenerator(world, null));
}
else {
String gen_string = PS.get().config.getString("worlds." + world + "." + "generator.plugin");
if (gen_string == null) {
gen_string = "PlotSquared";
}
PlotGenerator<?> wrapper = PS.get().IMP.getGenerator(world, gen_string);
if (wrapper.isFull()) {
wrapper.augment(cluster, plotworld);
}
else {
MainUtil.sendMessage(plr, C.SETUP_INVALID_GENERATOR, StringMan.join(SetupUtils.generators.keySet(), ","));
return false;
}
// BukkitPlotGenerator generator;
// if (gen_string == null) {
// generator = new HybridGen(world);
// } else {
// ChunkGenerator chunkgen = (ChunkGenerator) PS.get().IMP.getGenerator(world, gen_string).generator;
// if (chunkgen instanceof BukkitPlotGenerator) {
// generator = (BukkitPlotGenerator) chunkgen;
// }
// else {
// MainUtil.sendMessage(plr, C.SETUP_INVALID_GENERATOR, StringMan.join(SetupUtils.generators.keySet(), ","));
// return false;
// }
// }
// new AugmentedPopulator(world, generator, cluster, plotworld.TERRAIN == 2, plotworld.TERRAIN != 2);
}
MainUtil.sendMessage(plr, C.CLUSTER_ADDED);
return true;
@ -198,46 +185,32 @@ public class Cluster extends SubCommand {
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster delete [name]");
return false;
}
PlotArea area = plr.getApplicablePlotArea();
if (area == null) {
C.NOT_IN_PLOT_WORLD.send(plr);
return false;
}
PlotCluster cluster;
if (args.length == 2) {
cluster = ClusterManager.getCluster(plr.getLocation().getWorld(), args[1]);
cluster = area.getCluster(args[1]);
if (cluster == null) {
MainUtil.sendMessage(plr, C.INVALID_CLUSTER, args[1]);
return false;
}
} else {
cluster = ClusterManager.getCluster(plr.getLocation());
cluster = area.getCluster(plr.getLocation());
if (cluster == null) {
MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER);
return false;
}
}
if (!cluster.owner.equals(UUIDHandler.getUUID(plr))) {
if (!cluster.owner.equals(plr.getUUID())) {
if (!Permissions.hasPermission(plr, "plots.cluster.delete.other")) {
MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.delete.other");
return false;
}
}
final PlotWorld plotworld = PS.get().getPlotWorld(plr.getLocation().getWorld());
if (plotworld.TYPE == 2) {
final ArrayList<Plot> toRemove = new ArrayList<>();
for (final Plot plot : PS.get().getPlotsInWorld(plr.getLocation().getWorld())) {
final PlotCluster other = ClusterManager.getCluster(plot);
if (cluster.equals(other)) {
toRemove.add(plot);
}
}
for (final Plot plot : toRemove) {
plot.unclaim();
}
}
DBFunc.delete(cluster);
if (plotworld.TYPE == 2) {
SetupUtils.manager.removePopulator(plr.getLocation().getWorld(), cluster);
}
ClusterManager.last = null;
ClusterManager.clusters.get(cluster.world).remove(cluster);
ClusterManager.regenCluster(cluster);
MainUtil.sendMessage(plr, C.CLUSTER_DELETED);
return true;
}
@ -252,72 +225,81 @@ public class Cluster extends SubCommand {
return false;
}
// check pos1 / pos2
final PlotId pos1 = MainUtil.parseId(args[1]);
final PlotId pos2 = MainUtil.parseId(args[2]);
PlotId pos1 = PlotId.fromString(args[1]);
PlotId pos2 = PlotId.fromString(args[2]);
if ((pos1 == null) || (pos2 == null)) {
MainUtil.sendMessage(plr, C.NOT_VALID_PLOT_ID);
return false;
}
if ((pos2.x < pos1.x) || (pos2.y < pos1.y)) {
pos1 = new PlotId(Math.min(pos1.x, pos2.x), Math.min(pos1.y, pos2.y));
pos2 = new PlotId(Math.max(pos1.x, pos2.x), Math.max(pos1.y, pos2.y));
}
// check if in cluster
final PlotCluster cluster = ClusterManager.getCluster(plr.getLocation());
PlotArea area = plr.getApplicablePlotArea();
if (area == null) {
C.NOT_IN_PLOT_WORLD.send(plr);
return false;
}
final PlotCluster cluster = area.getCluster(plr.getLocation());
if (cluster == null) {
MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER);
return false;
}
if (!cluster.hasHelperRights(UUIDHandler.getUUID(plr))) {
if (!cluster.hasHelperRights(plr.getUUID())) {
if (!Permissions.hasPermission(plr, "plots.cluster.resize.other")) {
MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.resize.other");
return false;
}
}
//check if overlap
final PlotClusterId id = new PlotClusterId(pos1, pos2);
final HashSet<PlotCluster> intersects = ClusterManager.getIntersects(plr.getLocation().getWorld(), id);
if (intersects.size() > 1) {
MainUtil.sendMessage(plr, C.CLUSTER_INTERSECTION, (intersects.size() - 1) + "");
PlotCluster intersect = area.getFirstIntersectingCluster(pos1, pos2);
if (intersect != null) {
MainUtil.sendMessage(plr, C.CLUSTER_INTERSECTION, intersect.getName());
return false;
}
final HashSet<Plot> existing = area.getPlotSelectionOwned(cluster.getP1(), cluster.getP2());
final HashSet<Plot> newplots = area.getPlotSelectionOwned(pos1, pos2);
final HashSet<Plot> removed = ((HashSet<Plot>) existing.clone());
removed.removeAll(newplots);
// Check expand / shrink
if (!removed.isEmpty()) {
if (!Permissions.hasPermission(plr, "plots.cluster.resize.shrink")) {
MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.resize.shrink");
return false;
}
}
newplots.removeAll(existing);
if (!newplots.isEmpty()) {
if (!Permissions.hasPermission(plr, "plots.cluster.resize.expand")) {
MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.resize.expand");
return false;
}
}
// Check allowed cluster size
int current;
if (Settings.GLOBAL_LIMIT) {
current = plr.getPlayerClusterCount();
} else {
current = plr.getPlayerClusterCount(plr.getLocation().getWorld());
}
current -= cluster.getArea() + (((1 + pos2.x) - pos1.x) * ((1 + pos2.y) - pos1.y));
final int allowed = Permissions.hasPermissionRange(plr, "plots.cluster", Settings.MAX_PLOTS);
if ((current + cluster.getArea()) > allowed) {
MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster." + (current + cluster.getArea()));
return false;
}
for (final Plot plot : removed) {
FlagManager.removePlotFlag(plot, "cluster");
}
for (final Plot plot : newplots) {
FlagManager.addPlotFlag(plot, new Flag(FlagManager.getFlag("cluster"), cluster));
}
// resize cluster
DBFunc.resizeCluster(cluster, id);
DBFunc.resizeCluster(cluster, pos1, pos2);
MainUtil.sendMessage(plr, C.CLUSTER_RESIZED);
return true;
}
case "reg":
case "regenerate":
case "regen": {
if (!Permissions.hasPermission(plr, "plots.cluster.delete")) {
MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.regen");
return false;
}
if ((args.length != 1) && (args.length != 2)) {
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster regen [name]");
return false;
}
PlotCluster cluster;
if (args.length == 2) {
cluster = ClusterManager.getCluster(plr.getLocation().getWorld(), args[1]);
if (cluster == null) {
MainUtil.sendMessage(plr, C.INVALID_CLUSTER, args[1]);
return false;
}
} else {
cluster = ClusterManager.getCluster(plr.getLocation());
if (cluster == null) {
MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER);
return false;
}
}
if (!cluster.owner.equals(UUIDHandler.getUUID(plr))) {
if (!Permissions.hasPermission(plr, "plots.cluster.regen.other")) {
MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.regen.other");
return false;
}
}
long start = System.currentTimeMillis();
ClusterManager.regenCluster(cluster);
MainUtil.sendMessage(plr, C.CLUSTER_REGENERATED, (System.currentTimeMillis() - start) + "");
return true;
}
case "add":
case "inv":
case "invite": {
@ -330,12 +312,16 @@ public class Cluster extends SubCommand {
return false;
}
// check if in cluster
final PlotCluster cluster = ClusterManager.getCluster(plr.getLocation());
PlotArea area = plr.getApplicablePlotArea();
if (area == null) {
C.NOT_IN_PLOT_WORLD.send(plr);
}
final PlotCluster cluster = area.getCluster(plr.getLocation());
if (cluster == null) {
MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER);
return false;
}
if (!cluster.hasHelperRights(UUIDHandler.getUUID(plr))) {
if (!cluster.hasHelperRights(plr.getUUID())) {
if (!Permissions.hasPermission(plr, "plots.cluster.invite.other")) {
MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.invite.other");
return false;
@ -350,8 +336,7 @@ public class Cluster extends SubCommand {
if (!cluster.isAdded(uuid)) {
// add the user if not added
cluster.invited.add(uuid);
final String world = plr.getLocation().getWorld();
DBFunc.setInvited(world, cluster, uuid);
DBFunc.setInvited(cluster, uuid);
final PlotPlayer player = UUIDHandler.getPlayer(uuid);
if (player != null) {
MainUtil.sendMessage(player, C.CLUSTER_INVITED, cluster.getName());
@ -371,12 +356,16 @@ public class Cluster extends SubCommand {
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster kick <player>");
return false;
}
final PlotCluster cluster = ClusterManager.getCluster(plr.getLocation());
PlotArea area = plr.getApplicablePlotArea();
if (area == null) {
C.NOT_IN_PLOT_WORLD.send(plr);
}
final PlotCluster cluster = area.getCluster(plr.getLocation());
if (cluster == null) {
MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER);
return false;
}
if (!cluster.hasHelperRights(UUIDHandler.getUUID(plr))) {
if (!cluster.hasHelperRights(plr.getUUID())) {
if (!Permissions.hasPermission(plr, "plots.cluster.kick.other")) {
MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.kick.other");
return false;
@ -389,7 +378,7 @@ public class Cluster extends SubCommand {
return false;
}
// Can't kick if the player is yourself, the owner, or not added to the cluster
if (uuid.equals(UUIDHandler.getUUID(plr)) || uuid.equals(cluster.owner) || !cluster.isAdded(uuid)) {
if (uuid.equals(plr.getUUID()) || uuid.equals(cluster.owner) || !cluster.isAdded(uuid)) {
MainUtil.sendMessage(plr, C.CANNOT_KICK_PLAYER, cluster.getName());
return false;
}
@ -404,9 +393,9 @@ public class Cluster extends SubCommand {
MainUtil.sendMessage(player, C.CLUSTER_REMOVED, cluster.getName());
}
for (final Plot plot : new ArrayList<>(PS.get().getPlots(plr.getLocation().getWorld(), uuid))) {
final PlotCluster current = ClusterManager.getCluster(plot);
final PlotCluster current = plot.getCluster();
if ((current != null) && current.equals(cluster)) {
final String world = plr.getLocation().getWorld();
plr.getLocation().getWorld();
plot.unclaim();
}
}
@ -423,21 +412,25 @@ public class Cluster extends SubCommand {
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster leave [name]");
return false;
}
PlotArea area = plr.getApplicablePlotArea();
if (area == null) {
C.NOT_IN_PLOT_WORLD.send(plr);
}
PlotCluster cluster;
if (args.length == 2) {
cluster = ClusterManager.getCluster(plr.getLocation().getWorld(), args[1]);
cluster = area.getCluster(args[1]);
if (cluster == null) {
MainUtil.sendMessage(plr, C.INVALID_CLUSTER, args[1]);
return false;
}
} else {
cluster = ClusterManager.getCluster(plr.getLocation());
cluster = area.getCluster(plr.getLocation());
if (cluster == null) {
MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER);
return false;
}
}
final UUID uuid = UUIDHandler.getUUID(plr);
final UUID uuid = plr.getUUID();
if (!cluster.isAdded(uuid)) {
MainUtil.sendMessage(plr, C.CLUSTER_NOT_ADDED);
return false;
@ -454,9 +447,9 @@ public class Cluster extends SubCommand {
DBFunc.removeInvited(cluster, uuid);
MainUtil.sendMessage(plr, C.CLUSTER_REMOVED, cluster.getName());
for (final Plot plot : new ArrayList<>(PS.get().getPlots(plr.getLocation().getWorld(), uuid))) {
final PlotCluster current = ClusterManager.getCluster(plot);
final PlotCluster current = plot.getCluster();
if ((current != null) && current.equals(cluster)) {
final String world = plr.getLocation().getWorld();
plr.getLocation().getWorld();
plot.unclaim();
}
}
@ -473,7 +466,11 @@ public class Cluster extends SubCommand {
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster helpers <add|remove> <player>");
return false;
}
final PlotCluster cluster = ClusterManager.getCluster(plr.getLocation());
PlotArea area = plr.getApplicablePlotArea();
if (area == null) {
C.NOT_IN_PLOT_WORLD.send(plr);
}
final PlotCluster cluster = area.getCluster(plr.getLocation());
if (cluster == null) {
MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER);
return false;
@ -507,19 +504,23 @@ public class Cluster extends SubCommand {
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster tp <name>");
return false;
}
final PlotCluster cluster = ClusterManager.getCluster(plr.getLocation().getWorld(), args[1]);
PlotArea area = plr.getApplicablePlotArea();
if (area == null) {
C.NOT_IN_PLOT_WORLD.send(plr);
}
final PlotCluster cluster = area.getCluster(args[1]);
if (cluster == null) {
MainUtil.sendMessage(plr, C.INVALID_CLUSTER, args[1]);
return false;
}
final UUID uuid = UUIDHandler.getUUID(plr);
final UUID uuid = plr.getUUID();
if (!cluster.isAdded(uuid)) {
if (!Permissions.hasPermission(plr, "plots.cluster.tp.other")) {
MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.tp.other");
return false;
}
}
plr.teleport(ClusterManager.getHome(cluster));
plr.teleport(cluster.getHome());
return MainUtil.sendMessage(plr, C.CLUSTER_TELEPORTING);
}
case "i":
@ -534,15 +535,19 @@ public class Cluster extends SubCommand {
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster info [name]");
return false;
}
PlotArea area = plr.getApplicablePlotArea();
if (area == null) {
C.NOT_IN_PLOT_WORLD.send(plr);
}
PlotCluster cluster;
if (args.length == 2) {
cluster = ClusterManager.getCluster(plr.getLocation().getWorld(), args[1]);
cluster = area.getCluster(args[1]);
if (cluster == null) {
MainUtil.sendMessage(plr, C.INVALID_CLUSTER, args[1]);
return false;
}
} else {
cluster = ClusterManager.getCluster(plr.getLocation());
cluster = area.getCluster(plr.getLocation());
if (cluster == null) {
MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER);
return false;
@ -555,7 +560,7 @@ public class Cluster extends SubCommand {
}
final String name = cluster.getName();
final String size = ((cluster.getP2().x - cluster.getP1().x) + 1) + "x" + ((cluster.getP2().y - cluster.getP1().y) + 1);
final String rights = cluster.isAdded(UUIDHandler.getUUID(plr)) + "";
final String rights = cluster.isAdded(plr.getUUID()) + "";
String message = C.CLUSTER_INFO.s();
message = message.replaceAll("%id%", id);
message = message.replaceAll("%owner%", owner);
@ -576,18 +581,22 @@ public class Cluster extends SubCommand {
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster sethome");
return false;
}
final PlotCluster cluster = ClusterManager.getCluster(plr.getLocation());
PlotArea area = plr.getApplicablePlotArea();
if (area == null) {
C.NOT_IN_PLOT_WORLD.send(plr);
}
final PlotCluster cluster = area.getCluster(plr.getLocation());
if (cluster == null) {
MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER);
return false;
}
if (!cluster.hasHelperRights(UUIDHandler.getUUID(plr))) {
if (!cluster.hasHelperRights(plr.getUUID())) {
if (!Permissions.hasPermission(plr, "plots.cluster.sethome.other")) {
MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.sethome.other");
return false;
}
}
final Location base = ClusterManager.getClusterBottom(cluster);
final Location base = cluster.getClusterBottom();
final Location relative = plr.getLocation().subtract(base.getX(), 0, base.getZ());
final BlockLoc blockloc = new BlockLoc(relative.getX(), relative.getY(), relative.getZ());
cluster.settings.setPosition(blockloc);

View File

@ -3,8 +3,6 @@ package com.intellectualcrafters.plot.commands;
/**
* CommandCategory
*
* @author Citymonstret
* @author Empire92
*/
@ -18,25 +16,40 @@ public enum CommandCategory {
/**
* Teleportation Commands
*
TELEPORT("Teleportation"),
* Such as: /plot visit
*/
* Action Commands
*
* Such as: /plot clear
TELEPORT("Teleport"),
/**
ACTIONS("Actions"),
* Protection
*/
SETTINGS("Protection"),
/**
* Chat
*/
CHAT("Chat"),
/**
* Web
*/
SCHEMATIC("Web"),
/**
* Cosmetic
*/
APPEARANCE("Cosmetic"),
/**
* Information Commands
*
INFO("Information"),
* Such as: /plot info
*/
INFO("Info"),
/**
* Debug Commands
*
DEBUG("Debug");
* Such as: /plot debug
*/
DEBUG("Debug"),
/**
* Administration commands
*/
ADMINISTRATION("Admin");
/**
@ -53,6 +66,6 @@ public enum CommandCategory {
this.name = name;
}
return this.name;
@Override
public String toString() {
return name;

View File

@ -26,7 +26,6 @@ import com.intellectualcrafters.plot.util.Permissions;
/**
* Created by Citymonstret on 2014-08-03.
*
* @author Citymonstret
*/
public class CommandPermission {
@ -47,6 +46,6 @@ public class CommandPermission {
*
* @return true of player has the required permission node
*/
return Permissions.hasPermission(player, this.permission);
public boolean hasPermission(final PlotPlayer player) {
return Permissions.hasPermission(player, permission);
}

View File

@ -21,6 +21,7 @@
package com.intellectualcrafters.plot.commands;
import java.util.Arrays;
import java.util.Map.Entry;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.Location;
@ -32,57 +33,55 @@ import com.intellectualcrafters.plot.object.comment.PlotComment;
import com.intellectualcrafters.plot.util.CommentManager;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(
command = "comment",
aliases = {"msg"},
description = "Comment on a plot",
category = CommandCategory.ACTIONS,
requiredType = RequiredType.NONE,
permission = "plots.comment"
)
@CommandDeclaration(command = "comment", aliases = { "msg" }, description = "Comment on a plot", category = CommandCategory.CHAT, requiredType = RequiredType.NONE, permission = "plots.comment")
public class Comment extends SubCommand {
@Override
public boolean onCommand(PlotPlayer player, String[] args) {
public boolean onCommand(final PlotPlayer player, final String[] args) {
if (args.length < 2) {
sendMessage(player, C.COMMENT_SYNTAX, StringMan.join(CommentManager.inboxes.keySet(), "|"));
return false;
}
CommentInbox inbox = CommentManager.inboxes.get(args[0].toLowerCase());
final CommentInbox inbox = CommentManager.inboxes.get(args[0].toLowerCase());
if (inbox == null) {
sendMessage(player, C.COMMENT_SYNTAX, StringMan.join(CommentManager.inboxes.keySet(), "|"));
return false;
}
Plot plot;
Location loc = player.getLocation();
PlotId id = PlotId.fromString(args[1]);
final Location loc = player.getLocation();
final PlotId id = PlotId.fromString(args[1]);
Plot plot = MainUtil.getPlotFromString(player, args[1], false);
int index;
if (id != null) {
if (plot == null) {
index = 1;
plot = loc.getPlotAbs();
} else {
if (args.length < 4) {
sendMessage(player, C.COMMENT_SYNTAX, StringMan.join(CommentManager.inboxes.keySet(), "|"));
return false;
}
index = 2;
plot = MainUtil.getPlot(loc.getWorld(), id);
}
else {
index = 1;
plot = MainUtil.getPlot(loc);
}
if (!inbox.canWrite(plot, player)) {
sendMessage(player, C.NO_PERM_INBOX, "");
return false;
}
String message = StringMan.join(Arrays.copyOfRange(args,index, args.length), " ");
PlotComment comment = new PlotComment(loc.getWorld(), id, message, player.getName(), inbox.toString(), System.currentTimeMillis());
boolean result = inbox.addComment(plot, comment);
final String message = StringMan.join(Arrays.copyOfRange(args, index, args.length), " ");
final PlotComment comment = new PlotComment(loc.getWorld(), id, message, player.getName(), inbox.toString(), System.currentTimeMillis());
final boolean result = inbox.addComment(plot, comment);
if (!result) {
sendMessage(player, C.NO_PLOT_INBOX, "");
sendMessage(player, C.COMMENT_SYNTAX, StringMan.join(CommentManager.inboxes.keySet(), "|"));
return false;
}
for (Entry<String, PlotPlayer> entry : UUIDHandler.getPlayers().entrySet()) {
PlotPlayer pp = entry.getValue();
if (pp.getAttribute("chatspy")) {
MainUtil.sendMessage(pp, "/plot comment " + StringMan.join(args, " "));
}
}
sendMessage(player, C.COMMENT_ADDED);
return true;
}

View File

@ -20,47 +20,45 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.MathMan;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.WorldUtil;
import com.plotsquared.general.commands.CommandDeclaration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.BlockManager;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.MathMan;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(
command = "condense",
permission = "plots.admin",
description = "Condense a plotworld",
category = CommandCategory.DEBUG,
requiredType = RequiredType.CONSOLE
)
@CommandDeclaration(command = "condense", permission = "plots.admin", description = "Condense a plotworld", category = CommandCategory.ADMINISTRATION, requiredType = RequiredType.CONSOLE)
public class Condense extends SubCommand {
public static boolean TASK = false;
@Override
public boolean onCommand(final PlotPlayer plr, String ... args) {
public boolean onCommand(final PlotPlayer plr, final String... args) {
if ((args.length != 2) && (args.length != 3)) {
MainUtil.sendMessage(plr, "/plot condense <world> <start|stop|info> [radius]");
MainUtil.sendMessage(plr, "/plot condense <area> <start|stop|info> [radius]");
return false;
}
final String worldname = args[0];
if (!BlockManager.manager.isWorld(worldname) || !PS.get().isPlotWorld(worldname)) {
MainUtil.sendMessage(plr, "INVALID WORLD");
PlotArea area = PS.get().getPlotAreaByString(args[0]);
if (area == null || !WorldUtil.IMP.isWorld(area.worldname)) {
MainUtil.sendMessage(plr, "INVALID AREA");
return false;
}
switch (args[1].toLowerCase()) {
case "start": {
if (args.length == 2) {
MainUtil.sendMessage(plr, "/plot condense " + worldname + " start <radius>");
MainUtil.sendMessage(plr, "/plot condense " + area.toString() + " start <radius>");
return false;
}
if (TASK) {
@ -68,7 +66,7 @@ public class Condense extends SubCommand {
return false;
}
if (args.length == 2) {
MainUtil.sendMessage(plr, "/plot condense " + worldname + " start <radius>");
MainUtil.sendMessage(plr, "/plot condense " + area.toString() + " start <radius>");
return false;
}
if (!MathMan.isInteger(args[2])) {
@ -76,74 +74,110 @@ public class Condense extends SubCommand {
return false;
}
final int radius = Integer.parseInt(args[2]);
final Collection<Plot> plots = PS.get().getPlotsInWorld(worldname);
final int size = plots.size();
ArrayList<Plot> plots = new ArrayList<>(PS.get().getPlots(area));
// remove non base plots
Iterator<Plot> iter = plots.iterator();
int maxSize = 0;
ArrayList<Integer> sizes = new ArrayList<>();
while (iter.hasNext()) {
Plot plot = iter.next();
if (!plot.isBasePlot()) {
iter.remove();
continue;
}
int size = plot.getConnectedPlots().size();
if (size > maxSize) {
maxSize = size;
}
sizes.add(size - 1);
}
// Sort plots by size (buckets?)]
ArrayList<Plot>[] buckets = new ArrayList[maxSize];
for (int i = 0; i < plots.size(); i++) {
Plot plot = plots.get(i);
int size = sizes.get(i);
ArrayList<Plot> array = buckets[size];
if (array == null) {
array = new ArrayList<Plot>();
buckets[size] = array;
}
array.add(plot);
}
final ArrayList<Plot> allPlots = new ArrayList<Plot>(plots.size());
for (int i = buckets.length - 1; i >= 0; i--) {
ArrayList<Plot> array = buckets[i];
if (array != null) {
allPlots.addAll(array);
}
}
final int size = allPlots.size();
final int minimum_radius = (int) Math.ceil((Math.sqrt(size) / 2) + 1);
if (radius < minimum_radius) {
MainUtil.sendMessage(plr, "RADIUS TOO SMALL");
return false;
}
final List<PlotId> to_move = new ArrayList<>(getPlots(plots, radius));
final List<PlotId> to_move = new ArrayList<>(getPlots(allPlots, radius));
final List<PlotId> free = new ArrayList<>();
PlotId start = new PlotId(0, 0);
while ((start.x <= minimum_radius) && (start.y <= minimum_radius)) {
final Plot plot = MainUtil.getPlot(worldname, start);
if (!plot.hasOwner()) {
free.add(plot.id);
Plot plot = area.getPlotAbs(start);
if (plot != null && !plot.hasOwner()) {
free.add(plot.getId());
}
start = Auto.getNextPlot(start, 1);
start = Auto.getNextPlotId(start, 1);
}
if (free.size() == 0 || to_move.size() == 0) {
if ((free.isEmpty()) || (to_move.isEmpty())) {
MainUtil.sendMessage(plr, "NO FREE PLOTS FOUND");
return false;
}
MainUtil.move(MainUtil.getPlot(worldname, to_move.get(0)), MainUtil.getPlot(worldname, free.get(0)), new Runnable() {
MainUtil.sendMessage(plr, "TASK STARTED...");
Runnable run = new Runnable() {
@Override
public void run() {
if (!TASK) {
MainUtil.sendMessage(plr, "CONDENSE TASK CANCELLED");
return;
MainUtil.sendMessage(plr, "TASK CANCELLED.");
}
to_move.remove(0);
free.remove(0);
int index = 0;
for (final PlotId id : to_move) {
final Plot plot = MainUtil.getPlot(worldname, id);
if (plot.hasOwner()) {
break;
}
index++;
}
for (int i = 0; i < index; i++) {
to_move.remove(0);
}
index = 0;
for (final PlotId id : free) {
final Plot plot = MainUtil.getPlot(worldname, id);
if (!plot.hasOwner()) {
break;
}
index++;
}
for (int i = 0; i < index; i++) {
free.remove(0);
}
if (to_move.size() == 0) {
if (allPlots.isEmpty()) {
TASK = false;
MainUtil.sendMessage(plr, "TASK COMPLETE. PLEASE VERIFY THAT NO NEW PLOTS HAVE BEEN CLAIMED DURING TASK.");
TASK = false;
return;
}
if (free.size() == 0) {
final Runnable task = this;
final Plot origin = allPlots.remove(0);
int i = 0;
while (free.size() > i) {
final Plot possible = origin.getArea().getPlotAbs(free.get(i));
if (possible.hasOwner()) {
free.remove(i);
continue;
}
i++;
final AtomicBoolean result = new AtomicBoolean(false);
result.set(origin.move(possible, new Runnable() {
@Override
public void run() {
if (result.get()) {
MainUtil.sendMessage(plr, "Moving: " + origin + " -> " + possible);
TaskManager.runTaskLater(task, 1);
}
}
}, false));
if (result.get()) {
break;
}
}
if (free.isEmpty()) {
TASK = false;
MainUtil.sendMessage(plr, "TASK FAILED. NO FREE PLOTS FOUND!");
TASK = false;
return;
}
MainUtil.sendMessage(plr, "MOVING " + to_move.get(0) + " to " + free.get(0));
MainUtil.move(MainUtil.getPlot(worldname, to_move.get(0)), MainUtil.getPlot(worldname, free.get(0)), this);
if (i >= free.size()) {
MainUtil.sendMessage(plr, "SKIPPING COMPLEX PLOT: " + origin);
}
});
}
};
TASK = true;
MainUtil.sendMessage(plr, "TASK STARTED...");
TaskManager.runTaskAsync(run);
return true;
}
case "stop": {
@ -157,7 +191,7 @@ public class Condense extends SubCommand {
}
case "info": {
if (args.length == 2) {
MainUtil.sendMessage(plr, "/plot condense " + worldname + " info <radius>");
MainUtil.sendMessage(plr, "/plot condense " + area.toString() + " info <radius>");
return false;
}
if (!MathMan.isInteger(args[2])) {
@ -165,7 +199,7 @@ public class Condense extends SubCommand {
return false;
}
final int radius = Integer.parseInt(args[2]);
final Collection<Plot> plots = PS.get().getPlotsInWorld(worldname);
final Collection<Plot> plots = area.getPlots();
final int size = plots.size();
final int minimum_radius = (int) Math.ceil((Math.sqrt(size) / 2) + 1);
if (radius < minimum_radius) {
@ -185,15 +219,15 @@ public class Condense extends SubCommand {
return true;
}
}
MainUtil.sendMessage(plr, "/plot condense " + worldname + " <start|stop|info> [radius]");
MainUtil.sendMessage(plr, "/plot condense " + area.worldname + " <start|stop|info> [radius]");
return false;
}
public Set<PlotId> getPlots(final Collection<Plot> plots, final int radius) {
final HashSet<PlotId> outside = new HashSet<>();
for (final Plot plot : plots) {
if ((plot.id.x > radius) || (plot.id.x < -radius) || (plot.id.y > radius) || (plot.id.y < -radius)) {
outside.add(plot.id);
if ((plot.getId().x > radius) || (plot.getId().x < -radius) || (plot.getId().y > radius) || (plot.getId().y < -radius)) {
outside.add(plot.getId());
}
}
return outside;

View File

@ -20,7 +20,6 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.CmdInstance;
import com.intellectualcrafters.plot.object.PlotPlayer;
@ -29,23 +28,18 @@ import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(
command = "confirm",
permission = "plots.use",
description = "Confirm an action",
category = CommandCategory.ACTIONS
)
@CommandDeclaration(command = "confirm", permission = "plots.use", description = "Confirm an action", category = CommandCategory.INFO)
public class Confirm extends SubCommand {
@Override
public boolean onCommand(final PlotPlayer plr, final String... args) {
CmdInstance command = CmdConfirm.getPending(plr);
final CmdInstance command = CmdConfirm.getPending(plr);
if (command == null) {
MainUtil.sendMessage(plr, C.FAILED_CONFIRM);
return false;
}
CmdConfirm.removePending(plr);
if (System.currentTimeMillis() - command.timestamp > 20000) {
if ((System.currentTimeMillis() - command.timestamp) > 20000) {
MainUtil.sendMessage(plr, C.FAILED_CONFIRM);
return false;
}

View File

@ -22,45 +22,42 @@ package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.generator.HybridUtils;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotAnalysis;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.util.BlockManager;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(
command = "continue",
description = "Continue a plot that was previously marked as done",
permission = "plots.continue",
category = CommandCategory.ACTIONS,
requiredType = RequiredType.NONE
)
category = CommandCategory.SETTINGS,
requiredType = RequiredType.NONE)
public class Continue extends SubCommand {
@Override
public boolean onCommand(final PlotPlayer plr, final String[] args) {
final Location loc = plr.getLocation();
final Plot plot = MainUtil.getPlot(loc);
if (plot == null || !plot.hasOwner()) {
final Plot plot = loc.getPlotAbs();
if ((plot == null) || !plot.hasOwner()) {
return !sendMessage(plr, C.NOT_IN_PLOT);
}
if ((!plot.isOwner(plr.getUUID())) && !Permissions.hasPermission(plr, "plots.admin.command.continue")) {
if (!plot.isOwner(plr.getUUID()) && !Permissions.hasPermission(plr, "plots.admin.command.continue")) {
MainUtil.sendMessage(plr, C.NO_PLOT_PERMS);
return false;
}
if (!plot.getSettings().flags.containsKey("done")) {
if (!plot.getFlags().containsKey("done")) {
MainUtil.sendMessage(plr, C.DONE_NOT_DONE);
return false;
}
if (MainUtil.runners.containsKey(plot)) {
if (Settings.DONE_COUNTS_TOWARDS_LIMIT && (plr.getAllowedPlots() >= plr.getPlotCount())) {
MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.admin.command.continue");
return false;
}
if (plot.getRunning() > 0) {
MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER);
return false;
}

View File

@ -23,54 +23,50 @@ package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions;
import com.plotsquared.general.commands.Argument;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(
command = "copy",
permission = "plots.copy",
aliases = { "copypaste" },
category = CommandCategory.ACTIONS,
category = CommandCategory.CLAIMING,
description = "Copy a plot",
usage = "/plot copy <X;Z>",
requiredType = RequiredType.NONE
)
requiredType = RequiredType.NONE)
public class Copy extends SubCommand {
public Copy() {
requiredArguments = new Argument[] {
Argument.PlotID
};
}
@Override
public boolean onCommand(final PlotPlayer plr, final String ... args) {
public boolean onCommand(final PlotPlayer plr, final String[] args) {
final Location loc = plr.getLocation();
final Plot plot1 = MainUtil.getPlot(loc);
final Plot plot1 = loc.getPlotAbs();
if (plot1 == null) {
return !MainUtil.sendMessage(plr, C.NOT_IN_PLOT);
}
if (!plot1.isAdded(plr.getUUID()) && !Permissions.hasPermission(plr, C.PERMISSION_ADMIN.s())) {
if (!plot1.isOwner(plr.getUUID()) && !Permissions.hasPermission(plr, C.PERMISSION_ADMIN.s())) {
MainUtil.sendMessage(plr, C.NO_PLOT_PERMS);
return false;
}
final String world = loc.getWorld();
final PlotId plot2 = MainUtil.parseId(args[0]);
if (args.length != 1) {
C.COMMAND_SYNTAX.send(plr, getUsage());
return false;
}
final Plot plot2 = MainUtil.getPlotFromString(plr, args[0], true);
if ((plot2 == null)) {
MainUtil.sendMessage(plr, C.NOT_VALID_PLOT_ID);
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot copy <X;Z>");
return false;
}
if (plot1.id.equals(plot2)) {
if (plot1.equals(plot2)) {
MainUtil.sendMessage(plr, C.NOT_VALID_PLOT_ID);
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot copy <X;Z>");
C.COMMAND_SYNTAX.send(plr, getUsage());
return false;
}
if (MainUtil.copy(world, plot1.id, plot2, new Runnable() {
if (!plot1.getArea().isCompatible(plot2.getArea())) {
C.PLOTWORLD_INCOMPATIBLE.send(plr);
return false;
}
if (plot1.copy(plot2, new Runnable() {
@Override
public void run() {
MainUtil.sendMessage(plr, C.COPY_SUCCESS);

View File

@ -20,7 +20,6 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.generator.HybridPlotWorld;
import com.intellectualcrafters.plot.generator.HybridUtils;
@ -33,26 +32,25 @@ import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(
command = "createroadschematic",
aliases = { "crs" },
category = CommandCategory.DEBUG,
category = CommandCategory.ADMINISTRATION,
requiredType = RequiredType.NONE,
permission = "plots.createroadschematic",
description = "Add a road schematic to your world using the roads around your current plot",
usage = "/plot createroadschematic"
)
usage = "/plot createroadschematic")
public class CreateRoadSchematic extends SubCommand {
@Override
public boolean onCommand(final PlotPlayer player, final String... args) {
final Location loc = player.getLocation();
final Plot plot = MainUtil.getPlot(loc);
final Plot plot = loc.getPlotAbs();
if (plot == null) {
return sendMessage(player, C.NOT_IN_PLOT);
}
if (!(PS.get().getPlotWorld(loc.getWorld()) instanceof HybridPlotWorld)) {
if (!(loc.getPlotArea() instanceof HybridPlotWorld)) {
return sendMessage(player, C.NOT_IN_PLOT_WORLD);
}
HybridUtils.manager.setupRoadSchematic(plot);
MainUtil.sendMessage(player, "&6Saved new road schematic (see console for more information)");
MainUtil.sendMessage(player, "&6Saved new road schematic. To test the road, fly to a few other plots and use /plot debugroadregen");
return true;
}
}

View File

@ -3,17 +3,16 @@ package com.intellectualcrafters.plot.commands;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.database.MySQL;
import com.intellectualcrafters.plot.database.SQLManager;
import com.intellectualcrafters.plot.database.SQLite;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.MainUtil;
@ -23,11 +22,11 @@ import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(
command = "database",
aliases = { "convert" },
category = CommandCategory.DEBUG,
category = CommandCategory.ADMINISTRATION,
permission = "plots.database",
description = "Convert/Backup Storage",
requiredType = RequiredType.CONSOLE,
usage = "/plots database [world] <sqlite|mysql|import>"
usage = "/plots database [area] <sqlite|mysql|import>"
)
public class Database extends SubCommand {
@ -60,16 +59,16 @@ public class Database extends SubCommand {
@Override
public boolean onCommand(final PlotPlayer player, String[] args) {
if (args.length < 1) {
MainUtil.sendMessage(player, "/plot database [world] <sqlite|mysql>");
MainUtil.sendMessage(player, "/plot database [area] <sqlite|mysql|import>");
return false;
}
ArrayList<Plot> plots;
if (PS.get().isPlotWorld(args[0])) {
plots = PS.get().sortPlotsByTemp(PS.get().getPlotsInWorld(args[0]));
PlotArea area = PS.get().getPlotAreaByString(args[0]);
if (area != null) {
plots = PS.get().sortPlotsByTemp(area.getPlots());
args = Arrays.copyOfRange(args, 1, args.length);
}
else {
plots = PS.get().sortPlotsByTemp(PS.get().getPlotsRaw());
} else {
plots = PS.get().sortPlotsByTemp(PS.get().getPlots());
}
if (args.length < 1) {
MainUtil.sendMessage(player, "/plot database [world] <sqlite|mysql|import>");
@ -85,15 +84,23 @@ public class Database extends SubCommand {
MainUtil.sendMessage(player, "/plot database import [sqlite file] [prefix]");
return false;
}
File file = new File(PS.get().IMP.getDirectory() + File.separator + args[1] + ".db");
if (!file.exists()) {
MainUtil.sendMessage(player, "&6Database does not exist: " + file);
return false;
}
MainUtil.sendMessage(player, "&6Starting...");
implementation = new SQLite(PS.get().IMP.getDirectory() + File.separator + args[1] + ".db");
SQLManager manager = new SQLManager(implementation, (args.length == 3) ? args[2] : "", true);
ConcurrentHashMap<String, ConcurrentHashMap<PlotId, Plot>> map = manager.getPlots();
implementation = new SQLite(file.getPath());
final SQLManager manager = new SQLManager(implementation, (args.length == 3) ? args[2] : "", true);
final HashMap<String, HashMap<PlotId, Plot>> map = manager.getPlots();
plots = new ArrayList<Plot>();
for (Entry<String, ConcurrentHashMap<PlotId, Plot>> entry : map.entrySet()) {
for (Entry<PlotId, Plot> entry2 : entry.getValue().entrySet()) {
Plot plot = entry2.getValue();
if (PS.get().getPlot(plot.world, plot.id) != null) {
for (final Entry<String, HashMap<PlotId, Plot>> entry : map.entrySet()) {
String areaname = entry.getKey();
PlotArea pa = PS.get().getPlotAreaByString(areaname);
if (pa != null) {
for (final Entry<PlotId, Plot> entry2 : entry.getValue().entrySet()) {
final Plot plot = entry2.getValue();
if (pa.getOwnedPlotAbs(plot.getId()) != null) {
MainUtil.sendMessage(player, "Skipping duplicate plot: " + plot + " | id=" + plot.temp);
continue;
}
@ -101,6 +108,15 @@ public class Database extends SubCommand {
plots.add(entry2.getValue());
}
}
else {
HashMap<PlotId, Plot> plotmap = PS.get().plots_tmp.get(areaname);
if (plotmap == null) {
plotmap = new HashMap<>();
PS.get().plots_tmp.put(areaname, plotmap);
}
plotmap.putAll(entry.getValue());
}
}
DBFunc.createPlotsAndData(plots, new Runnable() {
@Override
public void run() {
@ -136,8 +152,7 @@ public class Database extends SubCommand {
final SQLManager manager = new SQLManager(implementation, prefix, true);
insertPlots(manager, plots, player);
return true;
}
catch (Exception e) {
} catch (final Exception e) {
MainUtil.sendMessage(player, "$1Failed to save plots, read stacktrace for info");
MainUtil.sendMessage(player, "&d==== Here is an ugly stacktrace, if you are interested in those things ===");
e.printStackTrace();
@ -145,8 +160,7 @@ public class Database extends SubCommand {
MainUtil.sendMessage(player, "$1Please make sure you are using the correct arguments!");
return false;
}
}
catch (Exception e) {
} catch (final Exception e) {
MainUtil.sendMessage(player, "$1Failed to open connection, read stacktrace for info");
MainUtil.sendMessage(player, "&d==== Here is an ugly stacktrace, if you are interested in those things ===");
e.printStackTrace();

View File

@ -22,22 +22,17 @@ package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.Lag;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.util.MainUtil;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(
command = "debug",
category = CommandCategory.DEBUG,
description = "Show debug information",
usage = "/plot debug [msg]",
permission = "plots.admin"
)
@CommandDeclaration(command = "debug", category = CommandCategory.DEBUG, description = "Show debug information", usage = "/plot debug [msg]", permission = "plots.admin")
public class Debug extends SubCommand {
@Override
public boolean onCommand(PlotPlayer plr, String[] args) {
public boolean onCommand(final PlotPlayer plr, final String[] args) {
if ((args.length > 0) && args[0].equalsIgnoreCase("msg")) {
final StringBuilder msg = new StringBuilder();
for (final C c : C.values()) {
@ -56,15 +51,14 @@ public class Debug extends SubCommand {
}
{
final StringBuilder worlds = new StringBuilder("");
for (final String world : PS.get().getPlotWorlds()) {
worlds.append(world).append(" ");
PS.get().foreachPlotArea(new RunnableVal<PlotArea>() {
@Override
public void run(PlotArea value) {
worlds.append(value.toString()).append(" ");
}
});
information.append(header);
information.append(getSection(section, "Lag / TPS"));
information.append(getLine(line, "Ticks Per Second", Lag.getTPS()));
information.append(getLine(line, "Lag Percentage", (int) Lag.getPercentage() + "%"));
information.append(getLine(line, "TPS Percentage", (int) Lag.getFullPercentage() + "%"));
information.append(getSection(section, "PlotWorld"));
information.append(getSection(section, "PlotArea"));
information.append(getLine(line, "Plot Worlds", worlds));
information.append(getLine(line, "Owned Plots", PS.get().getPlots().size()));
information.append(getSection(section, "Messages"));

View File

@ -14,8 +14,7 @@ import com.plotsquared.general.commands.CommandDeclaration;
usage = "/plot debugallowunsafe",
category = CommandCategory.DEBUG,
requiredType = RequiredType.NONE,
permission = "plots.debugallowunsafe"
)
permission = "plots.debugallowunsafe")
public class DebugAllowUnsafe extends SubCommand {
public static final List<UUID> unsafeAllowed = new ArrayList<>();

View File

@ -20,9 +20,6 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import java.util.ArrayList;
import java.util.UUID;
import com.google.common.collect.BiMap;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
@ -30,25 +27,28 @@ import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotManager;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.PlotWorld;
import com.intellectualcrafters.plot.object.StringWrapper;
import com.intellectualcrafters.plot.util.BlockManager;
import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.EventUtil;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.util.WorldUtil;
import com.plotsquared.general.commands.CommandDeclaration;
import java.util.ArrayList;
import java.util.Map;
import java.util.UUID;
@CommandDeclaration(
command = "debugclaimtest",
description = "If you accidentally delete your database, this command will attempt to restore all plots based on the data from plot sighs. Execution time may vary",
description = "If you accidentally delete your database, this command will attempt to restore all plots based on the data from plot signs. Execution time may vary",
category = CommandCategory.DEBUG,
requiredType = RequiredType.CONSOLE,
permission = "plots.debugclaimtest"
)
permission = "plots.debugclaimtest")
public class DebugClaimTest extends SubCommand {
public static boolean claimPlot(final PlotPlayer player, final Plot plot, final boolean teleport) {
@ -58,62 +58,66 @@ public class DebugClaimTest extends SubCommand {
public static boolean claimPlot(final PlotPlayer player, final Plot plot, final boolean teleport, final String schematic) {
final boolean result = EventUtil.manager.callClaim(player, plot, false);
if (result) {
MainUtil.createPlot(player.getUUID(), plot);
MainUtil.setSign(player.getName(), plot);
plot.create(player.getUUID(), true);
plot.setSign(player.getName());
MainUtil.sendMessage(player, C.CLAIMED);
if (teleport) {
MainUtil.teleportPlayer(player, player.getLocation(), plot);
plot.teleportPlayer(player);
}
}
return !result;
}
@Override
public boolean onCommand(PlotPlayer plr, String[] args) {
public boolean onCommand(final PlotPlayer plr, final String[] args) {
if (args.length < 3) {
return !MainUtil.sendMessage(null, "If you accidentally delete your database, this command will attempt to restore all plots based on the data from the plot signs. \n\n&cMissing world arg /plot debugclaimtest {world} {PlotId min} {PlotId max}");
return !MainUtil
.sendMessage(
null,
"If you accidentally delete your database, this command will attempt to restore all plots based on the data from the plot signs. \n\n&cMissing world arg /plot debugclaimtest {world} {PlotId min} {PlotId max}");
}
final String world = args[0];
if (!BlockManager.manager.isWorld(world) || !PS.get().isPlotWorld(world)) {
return !MainUtil.sendMessage(null, "&cInvalid plot world!");
PlotArea area = PS.get().getPlotAreaByString(args[0]);
if (area == null || !WorldUtil.IMP.isWorld(area.worldname)) {
C.NOT_VALID_PLOT_WORLD.send(plr, args[0]);
return false;
}
PlotId min, max;
try {
final String[] split1 = args[1].split(";");
final String[] split2 = args[2].split(";");
min = new PlotId(Integer.parseInt(split1[0]), Integer.parseInt(split1[1]));
max = new PlotId(Integer.parseInt(split2[0]), Integer.parseInt(split2[1]));
args[1].split(";");
args[2].split(";");
min = PlotId.fromString(args[1]);
max = PlotId.fromString(args[2]);
} catch (final Exception e) {
return !MainUtil.sendMessage(null, "&cInvalid min/max values. &7The values are to Plot IDs in the format &cX;Y &7where X,Y are the plot coords\nThe conversion will only check the plots in the selected area.");
return !MainUtil.sendMessage(plr,
"&cInvalid min/max values. &7The values are to Plot IDs in the format &cX;Y &7where X;Y are the plot coords\nThe conversion will only check the plots in the selected area.");
}
MainUtil.sendMessage(null, "&3Sign Block&8->&3PlotSquared&8: &7Beginning sign to plot conversion. This may take a while...");
MainUtil.sendMessage(null, "&3Sign Block&8->&3PlotSquared&8: Found an excess of 250,000 chunks. Limiting search radius... (~3.8 min)");
final PlotManager manager = PS.get().getPlotManager(world);
final PlotWorld plotworld = PS.get().getPlotWorld(world);
MainUtil.sendMessage(plr, "&3Sign Block&8->&3PlotSquared&8: &7Beginning sign to plot conversion. This may take a while...");
MainUtil.sendMessage(plr, "&3Sign Block&8->&3PlotSquared&8: Found an excess of 250,000 chunks. Limiting search radius... (~3.8 min)");
final PlotManager manager = area.getPlotManager();
final ArrayList<Plot> plots = new ArrayList<>();
for (final PlotId id : MainUtil.getPlotSelectionIds(min, max)) {
final Plot plot = MainUtil.getPlot(world, id);
if (PS.get().getPlot(world, plot.id) != null) {
MainUtil.sendMessage(null, " - &cDB Already contains: " + plot.id);
final Plot plot = area.getPlotAbs(id);
if (plot.hasOwner()) {
MainUtil.sendMessage(plr, " - &cDB Already contains: " + plot.getId());
continue;
}
final Location loc = manager.getSignLoc(plotworld, plot);
final Location loc = manager.getSignLoc(area, plot);
final ChunkLoc chunk = new ChunkLoc(loc.getX() >> 4, loc.getZ() >> 4);
final boolean result = ChunkManager.manager.loadChunk(world, chunk, false);
final boolean result = ChunkManager.manager.loadChunk(area.worldname, chunk, false);
if (!result) {
continue;
}
final String[] lines = BlockManager.manager.getSign(loc);
final String[] lines = WorldUtil.IMP.getSign(loc);
if (lines != null) {
String line = lines[2];
if ((line != null) && (line.length() > 2)) {
if (line != null && line.length() > 2) {
line = line.substring(2);
final BiMap<StringWrapper, UUID> map = UUIDHandler.getUuidMap();
UUID uuid = (map.get(new StringWrapper(line)));
UUID uuid = map.get(new StringWrapper(line));
if (uuid == null) {
for (final StringWrapper string : map.keySet()) {
if (string.value.toLowerCase().startsWith(line.toLowerCase())) {
uuid = map.get(string);
for (final Map.Entry<StringWrapper, UUID> stringWrapperUUIDEntry : map.entrySet()) {
if (stringWrapperUUIDEntry.getKey().value.toLowerCase().startsWith(line.toLowerCase())) {
uuid = stringWrapperUUIDEntry.getValue();
break;
}
}
@ -122,29 +126,29 @@ public class DebugClaimTest extends SubCommand {
uuid = UUIDHandler.getUUID(line, null);
}
if (uuid != null) {
MainUtil.sendMessage(null, " - &aFound plot: " + plot.id + " : " + line);
MainUtil.sendMessage(plr, " - &aFound plot: " + plot.getId() + " : " + line);
plot.owner = uuid;
plots.add(plot);
} else {
MainUtil.sendMessage(null, " - &cInvalid playername: " + plot.id + " : " + line);
MainUtil.sendMessage(plr, " - &cInvalid playername: " + plot.getId() + " : " + line);
}
}
}
}
if (plots.size() > 0) {
MainUtil.sendMessage(null, "&3Sign Block&8->&3PlotSquared&8: &7Updating '" + plots.size() + "' plots!");
if (!plots.isEmpty()) {
MainUtil.sendMessage(plr, "&3Sign Block&8->&3PlotSquared&8: &7Updating '" + plots.size() + "' plots!");
DBFunc.createPlotsAndData(plots, new Runnable() {
@Override
public void run() {
MainUtil.sendMessage(null, "&6Database update finished!");
MainUtil.sendMessage(plr, "&6Database update finished!");
}
});
for (final Plot plot : plots) {
PS.get().updatePlot(plot);
}
MainUtil.sendMessage(null, "&3Sign Block&8->&3PlotSquared&8: &7Complete!");
MainUtil.sendMessage(plr, "&3Sign Block&8->&3PlotSquared&8: &7Complete!");
} else {
MainUtil.sendMessage(null, "No plots were found for the given search.");
MainUtil.sendMessage(plr, "No plots were found for the given search.");
}
return true;
}

View File

@ -21,12 +21,9 @@
package com.intellectualcrafters.plot.commands;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
@ -47,60 +44,55 @@ import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.generator.HybridUtils;
import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.object.ConsolePlayer;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.OfflinePlotPlayer;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotAnalysis;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.util.AbstractTitle;
import com.intellectualcrafters.plot.util.BlockManager;
import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.EconHandler;
import com.intellectualcrafters.plot.util.EventUtil;
import com.intellectualcrafters.plot.util.ExpireManager;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.MathMan;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.SchematicHandler;
import com.intellectualcrafters.plot.util.SetupUtils;
import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.bukkit.util.BukkitHybridUtils;
import com.intellectualcrafters.plot.util.WorldUtil;
import com.plotsquared.general.commands.Command;
import com.plotsquared.general.commands.CommandCaller;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(
command = "debugexec",
permission = "plots.admin",
description = "Mutli-purpose debug command",
aliases = {"exec"},
category = CommandCategory.DEBUG
)
@CommandDeclaration(command = "debugexec", permission = "plots.admin", description = "Mutli-purpose debug command", aliases = "exec",
category = CommandCategory.DEBUG)
public class DebugExec extends SubCommand {
private ScriptEngine engine;
private Bindings scope;
public DebugExec() {
File file = new File(PS.get().IMP.getDirectory(), "scripts" + File.separator + "start.js");
try {
if (PS.get() != null) {
final File file = new File(PS.get().IMP.getDirectory(), "scripts" + File.separator + "start.js");
if (file.exists()) {
init();
try {
String script = StringMan.join(Files.readLines(new File(new File(PS.get().IMP.getDirectory() + File.separator + "scripts"), "start.js"), StandardCharsets.UTF_8), System.getProperty("line.separator"));
final String script = StringMan.join(Files
.readLines(new File(new File(PS.get().IMP.getDirectory() + File.separator + "scripts"), "start.js"),
StandardCharsets.UTF_8),
System.getProperty("line.separator"));
scope.put("THIS", this);
scope.put("PlotPlayer", ConsolePlayer.getConsole());
engine.eval(script, scope);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (IOException | ScriptException e) {}
}
public ScriptEngine getEngine() {
@ -115,11 +107,11 @@ public class DebugExec extends SubCommand {
if (engine != null) {
return;
}
engine = (new ScriptEngineManager(null)).getEngineByName("nashorn");
engine = new ScriptEngineManager(null).getEngineByName("nashorn");
if (engine == null) {
engine = (new ScriptEngineManager(null)).getEngineByName("JavaScript");
engine = new ScriptEngineManager(null).getEngineByName("JavaScript");
}
ScriptContext context = new SimpleScriptContext();
final ScriptContext context = new SimpleScriptContext();
scope = context.getBindings(ScriptContext.ENGINE_SCOPE);
// stuff
@ -127,6 +119,7 @@ public class DebugExec extends SubCommand {
scope.put("Settings", new Settings());
scope.put("StringMan", new StringMan());
scope.put("MathMan", new MathMan());
scope.put("FlagManager", new FlagManager());
// Classes
scope.put("Location", Location.class);
@ -143,7 +136,7 @@ public class DebugExec extends SubCommand {
scope.put("ConsolePlayer", ConsolePlayer.getConsole());
scope.put("SchematicHandler", SchematicHandler.manager);
scope.put("ChunkManager", ChunkManager.manager);
scope.put("BlockManager", BlockManager.manager);
scope.put("BlockManager", WorldUtil.IMP);
scope.put("SetupUtils", SetupUtils.manager);
scope.put("EventUtil", EventUtil.manager);
scope.put("EconHandler", EconHandler.manager);
@ -154,42 +147,42 @@ public class DebugExec extends SubCommand {
scope.put("MainCommand", MainCommand.getInstance());
// enums
for (Enum<?> value : C.values()) {
for (final Enum<?> value : C.values()) {
scope.put("C_" + value.name(), value);
}
}
@Override
public boolean onCommand(final PlotPlayer player, String... args) {
final List<String> allowed_params = Arrays.asList("calibrate-analysis", "remove-flag", "stop-expire", "start-expire", "show-expired", "update-expired", "seen", "trim-check");
public boolean onCommand(final PlotPlayer player, final String... args) {
final List<String> allowed_params = Arrays.asList("calibrate-analysis", "remove-flag", "stop-expire", "start-expire", "show-expired", "update-expired", "seen");
if (args.length > 0) {
final String arg = args[0].toLowerCase();
String script;
boolean async = false;
switch (arg) {
case "analyze": {
Plot plot = MainUtil.getPlot(player.getLocation());
final Plot plot = player.getCurrentPlot();
if (plot == null) {
MainUtil.sendMessage(player, C.NOT_IN_PLOT);
return false;
}
PlotAnalysis analysis = plot.getComplexity();
final PlotAnalysis analysis = plot.getComplexity();
if (analysis != null) {
int complexity = analysis.getComplexity();
MainUtil.sendMessage(player, "Changes: " + analysis.changes);
final int complexity = analysis.getComplexity();
MainUtil.sendMessage(player, "Changes/column: " + analysis.changes / 1.0);
MainUtil.sendMessage(player, "Complexity: " + complexity);
return true;
}
MainUtil.sendMessage(player, "$1Starting task...");
HybridUtils.manager.analyzePlot(plot, new RunnableVal<PlotAnalysis>() {
@Override
public void run() {
public void run(PlotAnalysis value) {
MainUtil.sendMessage(player, "$1Done: $2use $3/plot debugexec analyze$2 for more information");
}
});
return true;
}
case "calibrate-analysis": {
case "calibrate-analysis":
if (args.length != 2) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec analyze <threshold>");
MainUtil.sendMessage(player, "$1<threshold> $2= $1The percentage of plots you want to clear (100 clears 100% of plots so no point calibrating it)");
@ -198,8 +191,7 @@ public class DebugExec extends SubCommand {
double threshold;
try {
threshold = Integer.parseInt(args[1]) / 100d;
}
catch (NumberFormatException e) {
} catch (final NumberFormatException e) {
MainUtil.sendMessage(player, "$2Invalid threshold: " + args[1]);
MainUtil.sendMessage(player, "$1<threshold> $2= $1The percentage of plots you want to clear as a number between 0 - 100");
return false;
@ -211,8 +203,7 @@ public class DebugExec extends SubCommand {
}
}, threshold);
return true;
}
case "stop-expire": {
case "stop-expire":
if (ExpireManager.task != -1) {
PS.get().TASK.cancelTask(ExpireManager.task);
} else {
@ -220,35 +211,33 @@ public class DebugExec extends SubCommand {
}
ExpireManager.task = -1;
return MainUtil.sendMessage(player, "Cancelled task.");
}
case "remove-flag": {
case "remove-flag":
if (args.length != 2) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec remove-flag <flag>");
return false;
}
String flag = args[1];
for (Plot plot : PS.get().getPlots()) {
if (FlagManager.getPlotFlag(plot, flag) != null) {
final String flag = args[1];
for (final Plot plot : PS.get().getBasePlots()) {
if (FlagManager.getPlotFlagRaw(plot, flag) != null) {
FlagManager.removePlotFlag(plot, flag);
}
}
return MainUtil.sendMessage(player, "Cleared flag: " + flag);
}
case "start-rgar": {
if (args.length != 2) {
MainUtil.sendMessage(player, "&cInvalid syntax: /plot debugexec start-rgar <world>");
return false;
}
boolean result;
if (!PS.get().isPlotWorld(args[1])) {
PlotArea area = PS.get().getPlotAreaByString(args[1]);
if (area == null) {
MainUtil.sendMessage(player, C.NOT_VALID_PLOT_WORLD, args[1]);
return false;
}
if (BukkitHybridUtils.regions != null) {
result = ((BukkitHybridUtils)(HybridUtils.manager)).scheduleRoadUpdate(args[1], BukkitHybridUtils.regions, 0);
}
else {
result = HybridUtils.manager.scheduleRoadUpdate(args[1], 0);
boolean result;
if (HybridUtils.regions != null) {
result = HybridUtils.manager.scheduleRoadUpdate(area, HybridUtils.regions, 0);
} else {
result = HybridUtils.manager.scheduleRoadUpdate(area, 0);
}
if (!result) {
MainUtil.sendMessage(player, "&cCannot schedule mass schematic update! (Is one already in progress?)");
@ -256,7 +245,7 @@ public class DebugExec extends SubCommand {
}
return true;
}
case "stop-rgar": {
case "stop-rgar":
if (!HybridUtils.UPDATE) {
MainUtil.sendMessage(player, "&cTASK NOT RUNNING!");
return false;
@ -264,31 +253,29 @@ public class DebugExec extends SubCommand {
HybridUtils.UPDATE = false;
MainUtil.sendMessage(player, "&cCancelling task... (please wait)");
return true;
}
case "start-expire": {
case "start-expire":
if (ExpireManager.task == -1) {
ExpireManager.runTask();
} else {
return MainUtil.sendMessage(player, "Plot expiry task already started");
}
return MainUtil.sendMessage(player, "Started plot expiry task");
}
case "update-expired": {
case "update-expired":
if (args.length > 1) {
final String world = args[1];
if (!BlockManager.manager.isWorld(world)) {
return MainUtil.sendMessage(player, "Invalid world: " + args[1]);
PlotArea area = PS.get().getPlotAreaByString(args[1]);
if (area == null || !WorldUtil.IMP.isWorld(area.worldname)) {
C.NOT_VALID_PLOT_WORLD.send(player, args[1]);
return false;
}
MainUtil.sendMessage(player, "Updating expired plot list");
ExpireManager.updateExpired(args[1]);
ExpireManager.updateExpired(area);
return true;
}
return MainUtil.sendMessage(player, "Use /plot debugexec update-expired <world>");
}
case "show-expired": {
case "show-expired":
if (args.length > 1) {
final String world = args[1];
if (!BlockManager.manager.isWorld(world)) {
if (!WorldUtil.IMP.isWorld(world)) {
return MainUtil.sendMessage(player, "Invalid world: " + args[1]);
}
if (!ExpireManager.expiredPlots.containsKey(args[1])) {
@ -296,13 +283,13 @@ public class DebugExec extends SubCommand {
}
MainUtil.sendMessage(player, "Expired plots (" + ExpireManager.expiredPlots.get(args[1]).size() + "):");
for (final Plot plot : ExpireManager.expiredPlots.get(args[1])) {
MainUtil.sendMessage(player, " - " + plot.world + ";" + plot.id.x + ";" + plot.id.y + ";" + UUIDHandler.getName(plot.owner) + " : " + ExpireManager.dates.get(plot.owner));
MainUtil.sendMessage(player,
" - " + plot.getArea() + ";" + plot.getId().x + ";" + plot.getId().y + ";" + UUIDHandler.getName(plot.owner) + " : " + ExpireManager.dates.get(plot.owner));
}
return true;
}
return MainUtil.sendMessage(player, "Use /plot debugexec show-expired <world>");
}
case "seen": {
case "seen":
if (args.length != 2) {
return MainUtil.sendMessage(player, "Use /plot debugexec seen <player>");
}
@ -311,7 +298,7 @@ public class DebugExec extends SubCommand {
return MainUtil.sendMessage(player, "player not found: " + args[1]);
}
final OfflinePlotPlayer op = UUIDHandler.getUUIDWrapper().getOfflinePlayer(uuid);
if ((op == null) || (op.getLastPlayed() == 0)) {
if (op == null || op.getLastPlayed() == 0) {
return MainUtil.sendMessage(player, "player hasn't connected before: " + args[1]);
}
final Timestamp stamp = new Timestamp(op.getLastPlayed());
@ -322,68 +309,27 @@ public class DebugExec extends SubCommand {
MainUtil.sendMessage(player, "GMT: " + date.toGMTString());
MainUtil.sendMessage(player, "Local: " + date.toLocaleString());
return true;
}
case "trim-check": {
if (args.length != 2) {
MainUtil.sendMessage(player, "Use /plot debugexec trim-check <world>");
MainUtil.sendMessage(player, "&7 - Generates a list of regions to trim");
return MainUtil.sendMessage(player, "&7 - Run after plot expiry has run");
}
final String world = args[1];
if (!BlockManager.manager.isWorld(world) || !PS.get().isPlotWorld(args[1])) {
return MainUtil.sendMessage(player, "Invalid world: " + args[1]);
}
final ArrayList<ChunkLoc> empty = new ArrayList<>();
final boolean result = Trim.getTrimRegions(empty, world, new Runnable() {
@Override
public void run() {
Trim.sendMessage("Processing is complete! Here's how many chunks would be deleted:");
Trim.sendMessage(" - MCA #: " + empty.size());
Trim.sendMessage(" - CHUNKS: " + (empty.size() * 1024) + " (max)");
Trim.sendMessage("Exporting log for manual approval...");
final File file = new File(PS.get().IMP.getDirectory() + File.separator + "trim.txt");
PrintWriter writer;
try {
writer = new PrintWriter(file);
for (final ChunkLoc loc : empty) {
writer.println(world + "/region/r." + loc.x + "." + loc.z + ".mca");
}
writer.close();
Trim.sendMessage("File saved to 'plugins/PlotSquared/trim.txt'");
} catch (final FileNotFoundException e) {
e.printStackTrace();
Trim.sendMessage("File failed to save! :(");
}
Trim.sendMessage("How to get the chunk coords from a region file:");
Trim.sendMessage(" - Locate the x,z values for the region file (the two numbers which are separated by a dot)");
Trim.sendMessage(" - Multiply each number by 32; this gives you the starting position");
Trim.sendMessage(" - Add 31 to each number to get the end position");
}
});
if (!result) {
MainUtil.sendMessage(player, "Trim task already started!");
}
return result;
}
case "h":
case "he":
case "?":
case "help": {
case "help":
MainUtil.sendMessage(player, "Possible sub commands: /plot debugexec <" + StringMan.join(allowed_params, "|") + ">");
return false;
}
case "addcmd": {
case "addcmd":
try {
final String cmd = StringMan.join(Files.readLines(new File(new File(PS.get().IMP.getDirectory() + File.separator + "scripts"), args[1]), StandardCharsets.UTF_8), System.getProperty("line.separator"));
Command<PlotPlayer> subcommand = new Command<PlotPlayer>(args[1].split("\\.")[0]) {
final String cmd = StringMan.join(Files
.readLines(new File(new File(PS.get().IMP.getDirectory() + File.separator + "scripts"), args[1]),
StandardCharsets.UTF_8),
System.getProperty("line.separator"));
final Command<PlotPlayer> subcommand = new Command<PlotPlayer>(args[1].split("\\.")[0]) {
@Override
public boolean onCommand(PlotPlayer plr, String[] args) {
public boolean onCommand(final PlotPlayer plr, final String[] args) {
try {
scope.put("PlotPlayer", plr);
scope.put("args", args);
engine.eval(cmd, scope);
return true;
} catch (ScriptException e) {
} catch (final ScriptException e) {
e.printStackTrace();
MainUtil.sendMessage(player, C.COMMAND_WENT_WRONG);
return false;
@ -392,36 +338,77 @@ public class DebugExec extends SubCommand {
};
MainCommand.getInstance().addCommand(subcommand);
return true;
}
catch (Exception e) {
} catch (IOException e) {
e.printStackTrace();
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec addcmd <file>");
return false;
}
}
case "runasync": {
case "runasync":
async = true;
}
case "run": {
case "run":
try {
script = StringMan.join(Files.readLines(new File(new File(PS.get().IMP.getDirectory() + File.separator + "scripts"), args[1]), StandardCharsets.UTF_8), System.getProperty("line.separator"));
script = StringMan.join(Files.readLines(new File(new File(PS.get().IMP.getDirectory() + File.separator + "scripts"), args[1]), StandardCharsets.UTF_8),
System.getProperty("line.separator"));
if (args.length > 2) {
HashMap<String, String> replacements = new HashMap<>();
final HashMap<String, String> replacements = new HashMap<>();
for (int i = 2; i < args.length; i++) {
replacements.put("%s" + (i - 2), args[i]);
}
script = StringMan.replaceFromMap(script, replacements);
}
} catch (IOException e) {
} catch (final IOException e) {
e.printStackTrace();
return false;
}
break;
case "allcmd":
if (args.length < 3) {
C.COMMAND_SYNTAX.send(player, "/plot debugexec allcmd <condition> <command>");
return false;
}
default: {
long start = System.currentTimeMillis();
Command<PlotPlayer> cmd = MainCommand.getInstance().getCommand(args[3]);
String[] params = Arrays.copyOfRange(args, 4, args.length);
if ("true".equals(args[1])) {
Location loc = player.getMeta("location");
Plot plot = player.getMeta("lastplot");
for (Plot current : PS.get().getBasePlots()) {
player.setMeta("location", current.getBottomAbs());
player.setMeta("lastplot", current);
cmd.onCommand(player, params);
}
if (loc == null) {
player.deleteMeta("location");
} else {
player.setMeta("location", loc);
}
if (plot == null) {
player.deleteMeta("lastplot");
} else {
player.setMeta("lastplot", plot);
}
player.sendMessage("&c> " + (System.currentTimeMillis() - start));
return true;
}
init();
scope.put("_2", params);
scope.put("_3", cmd);
script = "_1=PS.getBasePlots().iterator();while(_1.hasNext()){plot=_1.next();if(" + args[1] + "){PlotPlayer.setMeta(\"location\",plot.getBottomAbs());PlotPlayer.setMeta(\"lastplot\",plot);_3.onCommand(PlotPlayer,_2)}}";
break;
case "all":
if (args.length < 3) {
C.COMMAND_SYNTAX.send(player, "/plot debugexec all <condition> <code>");
return false;
}
script = "_1=PS.getBasePlots().iterator();while(_1.hasNext()){plot=_1.next();if(" + args[1] + "){" + StringMan
.join(Arrays.copyOfRange(args, 2, args.length), " ")
+ "}}";
break;
default:
script = StringMan.join(args, " ");
}
}
if (!ConsolePlayer.isConsole(player)) {
MainUtil.sendMessage(player, C.NOT_CONSOLE);
return false;
@ -435,23 +422,23 @@ public class DebugExec extends SubCommand {
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
long start = System.currentTimeMillis();
final long start = System.currentTimeMillis();
Object result = null;
try {
engine.eval(toExec, scope);
} catch (ScriptException e) {
result = engine.eval(toExec, scope);
} catch (final ScriptException e) {
e.printStackTrace();
}
PS.log("> " + (System.currentTimeMillis() - start) + "ms");
ConsolePlayer.getConsole().sendMessage("> " + (System.currentTimeMillis() - start) + "ms -> " + result);
}
});
}
else {
long start = System.currentTimeMillis();
engine.eval(script, scope);
PS.log("> " + (System.currentTimeMillis() - start) + "ms");
} else {
final long start = System.currentTimeMillis();
Object result = engine.eval(script, scope);
ConsolePlayer.getConsole().sendMessage("> " + (System.currentTimeMillis() - start) + "ms -> " + result);
}
return true;
} catch (ScriptException e) {
} catch (final ScriptException e) {
e.printStackTrace();
return false;
}

View File

@ -1,169 +0,0 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// 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.commands;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.SetBlockQueue;
import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(
command = "fill",
permission = "plots.fill",
description = "Fill or surround a plot in bedrock",
usage = "/plot fill",
aliases = {"debugfill"},
category = CommandCategory.DEBUG,
requiredType = RequiredType.NONE
)
public class DebugFill extends SubCommand {
@Override
public boolean onCommand(final PlotPlayer player, final String ... args) {
if (args.length != 1 || (!args[0].equalsIgnoreCase("outline") && !args[0].equalsIgnoreCase("all"))) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot fill <outline|all>");
return true;
}
final Location loc = player.getLocation();
final Plot plot = MainUtil.getPlot(loc);
if (plot == null) {
return !sendMessage(player, C.NOT_IN_PLOT);
}
if (!plot.hasOwner()) {
MainUtil.sendMessage(player, C.PLOT_UNOWNED);
return false;
}
if (!plot.isOwner(player.getUUID()) && !Permissions.hasPermission(player, "plots.admin.command.fill")) {
MainUtil.sendMessage(player, C.NO_PLOT_PERMS);
return true;
}
if (MainUtil.runners.containsKey(plot)) {
MainUtil.sendMessage(player, C.WAIT_FOR_TIMER);
return false;
}
final Location bottom = MainUtil.getPlotBottomLoc(plot.world, plot.id).add(1, 0, 1);
final Location top = MainUtil.getPlotTopLoc(plot.world, plot.id);
MainUtil.sendMessage(player, "&cPreparing task");
MainUtil.runners.put(plot, 1);
SetBlockQueue.addNotify(new Runnable() {
@Override
public void run() {
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
MainUtil.sendMessage(player, "&7 - Starting");
if (args[0].equalsIgnoreCase("all")) {
int height = 255;
PlotBlock block = new PlotBlock((short) 7, (byte) 0);
PlotBlock air = new PlotBlock((short) 0, (byte) 0);
if (args.length > 2) {
try {
block = new PlotBlock(Short.parseShort(args[1]), (byte) 0);
if (args.length == 3) {
height = Integer.parseInt(args[2]);
}
}
catch (Exception e) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot fill all <id> <height>");
MainUtil.runners.remove(plot);
return;
}
}
for (int y = 0; y <= height; y++) {
for (int x = bottom.getX(); x <= top.getX(); x++) {
for (int z = bottom.getZ(); z <= top.getZ(); z++) {
SetBlockQueue.setBlock(plot.world, x, y, z, block);
}
}
}
for (int y = height + 1; y <= 255; y++) {
for (int x = bottom.getX(); x <= top.getX(); x++) {
for (int z = bottom.getZ(); z <= top.getZ(); z++) {
SetBlockQueue.setBlock(plot.world, x, y, z, air);
}
}
}
SetBlockQueue.addNotify(new Runnable() {
@Override
public void run() {
MainUtil.runners.remove(plot);
MainUtil.sendMessage(player, "&aFill task complete!");
}
});
}
else if (args[0].equals("outline")) {
int x, z;
z = bottom.getZ();
for (x = bottom.getX(); x <= (top.getX() - 1); x++) {
for (int y = 1; y <= 255; y++) {
SetBlockQueue.setBlock(plot.world, x, y, z, 7);
}
}
x = top.getX();
for (z = bottom.getZ(); z <= (top.getZ() - 1); z++) {
for (int y = 1; y <= 255; y++) {
SetBlockQueue.setBlock(plot.world, x, y, z, 7);
}
}
z = top.getZ();
for (x = top.getX(); x >= (bottom.getX() + 1); x--) {
for (int y = 1; y <= 255; y++) {
SetBlockQueue.setBlock(plot.world, x, y, z, 7);
}
}
x = bottom.getX();
for (z = top.getZ(); z >= (bottom.getZ() + 1); z--) {
for (int y = 1; y <= 255; y++) {
SetBlockQueue.setBlock(plot.world, x, y, z, 7);
}
}
SetBlockQueue.addNotify(new Runnable() {
@Override
public void run() {
MainUtil.sendMessage(player, "&aWalls complete! The ceiling will take a while :(");
bottom.setY(255);
top.add(1,0,1);
SetBlockQueue.setSlow(true);
MainUtil.setSimpleCuboidAsync(plot.world, bottom, top, new PlotBlock((short) 7, (byte) 0));
SetBlockQueue.addNotify(new Runnable() {
@Override
public void run() {
MainUtil.runners.remove(plot);
MainUtil.sendMessage(player, "&aFill task complete!");
SetBlockQueue.setSlow(false);
}
});
}
});
}
}
});
}
});
return true;
}
}

View File

@ -30,9 +30,10 @@ import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.BlockManager;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.WorldUtil;
import com.plotsquared.general.commands.Argument;
import com.plotsquared.general.commands.CommandDeclaration;
@ -42,27 +43,24 @@ import com.plotsquared.general.commands.CommandDeclaration;
permission = "plots.debugfixflags",
description = "Attempt to fix all flags for a world",
requiredType = RequiredType.CONSOLE,
category = CommandCategory.DEBUG
)
category = CommandCategory.DEBUG)
public class DebugFixFlags extends SubCommand {
public DebugFixFlags() {
requiredArguments = new Argument[] {
Argument.String
};
requiredArguments = new Argument[] { Argument.String };
}
@Override
public boolean onCommand(PlotPlayer plr, String[] args) {
final String world = args[0];
if (!BlockManager.manager.isWorld(world) || !PS.get().isPlotWorld(world)) {
public boolean onCommand(final PlotPlayer plr, final String[] args) {
PlotArea area = PS.get().getPlotAreaByString(args[0]);
if (area == null || !WorldUtil.IMP.isWorld(area.worldname)) {
MainUtil.sendMessage(plr, C.NOT_VALID_PLOT_WORLD, args[0]);
return false;
}
MainUtil.sendMessage(plr, "&8--- &6Starting task &8 ---");
for (final Plot plot : PS.get().getPlotsInWorld(world)) {
final HashMap<String, Flag> flags = plot.getSettings().flags;
Iterator<Entry<String, Flag>> i = flags.entrySet().iterator();
for (final Plot plot : area.getPlots()) {
final HashMap<String, Flag> flags = plot.getFlags();
final Iterator<Entry<String, Flag>> i = flags.entrySet().iterator();
boolean changed = false;
while (i.hasNext()) {
if (FlagManager.getFlag(i.next().getKey()) == null) {
@ -71,7 +69,7 @@ public class DebugFixFlags extends SubCommand {
}
}
if (changed) {
DBFunc.setFlags(plot, plot.getSettings().flags.values());
DBFunc.setFlags(plot, plot.getFlags().values());
}
}
MainUtil.sendMessage(plr, "&aDone!");

View File

@ -33,12 +33,11 @@ import com.plotsquared.general.commands.CommandDeclaration;
description = "This debug command will force the reload of all plots in the DB",
usage = "/plot debugloadtest",
category = CommandCategory.DEBUG,
requiredType = RequiredType.CONSOLE
)
requiredType = RequiredType.CONSOLE)
public class DebugLoadTest extends SubCommand {
@Override
public boolean onCommand(PlotPlayer plr, String[] args) {
public boolean onCommand(final PlotPlayer plr, final String[] args) {
try {
final Field fPlots = PS.class.getDeclaredField("plots");
fPlots.setAccessible(true);

View File

@ -3,55 +3,57 @@ package com.intellectualcrafters.plot.commands;
import java.io.File;
import java.io.IOException;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.HastebinUtility;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.bukkit.BukkitMain;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(
command = "debugpaste",
aliases = { "dp" },
usage = "/plot debugpaste",
description = "Upload settings.yml & latest.log to hastebin",
description = "Upload settings.yml & latest.log to HasteBin",
permission = "plots.debugpaste",
category = CommandCategory.DEBUG
)
category = CommandCategory.DEBUG)
public class DebugPaste extends SubCommand {
@Override
public boolean onCommand(final PlotPlayer plr, String[] args) {
public boolean onCommand(final PlotPlayer plr, final String[] args) {
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
try {
String settingsYML = HastebinUtility.upload(PS.get().configFile);
final String settingsYML = HastebinUtility.upload(PS.get().configFile);
String latestLOG;
try {
latestLOG = HastebinUtility.upload(new File(BukkitMain.THIS.getDirectory(), "../../logs/latest.log"));
latestLOG = HastebinUtility.upload(new File(PS.get().IMP.getDirectory(), "../../logs/latest.log"));
} catch (final Exception e) {
plr.sendMessage("&clatest.log is too big to be pasted, will ignore");
MainUtil.sendMessage(plr, "&clatest.log is too big to be pasted, will ignore");
latestLOG = "too big :(";
}
StringBuilder b = new StringBuilder();
final StringBuilder b = new StringBuilder();
b.append("# Welcome to this paste\n# It is meant to provide us at IntellectualSites with better information about your problem\n\n# We will start with some informational files\n");
b.append("links.settings_yml: '").append(settingsYML).append("'\n");
b.append("links.latest_log: '").append(latestLOG).append("'\n");
b.append("\n# YAAAS! Now let us move on to the server info\n");
b.append("version.server: '").append(Bukkit.getServer().getVersion()).append("'\n");
b.append("version.bukkit: '").append(Bukkit.getBukkitVersion()).append("'\n");
b.append("online_mode: ").append(Bukkit.getServer().getOnlineMode()).append("\n");
b.append("version.server: '").append(PS.get().IMP.getServerVersion()).append("'\n");
b.append("online_mode: ").append(UUIDHandler.getUUIDWrapper() + ";" + !Settings.OFFLINE_MODE).append("\n");
b.append("plugins:");
for (final Plugin p : Bukkit.getPluginManager().getPlugins()) {
b.append("\n ").append(p.getName()).append(":\n ").append("version: '").append(p.getDescription().getVersion()).append("'").append("\n enabled: ").append(p.isEnabled());
for (String id : PS.get().IMP.getPluginIds()) {
String[] split = id.split(":");
String[] split2 = split[0].split(";");
String enabled = split.length == 2 ? split[1] : "unknown";
String name = split2[0];
String version = split2.length == 2 ? split2[1] : "unknown";
b.append("\n ").append(name).append(":\n ").append("version: '").append(version).append("'").append("\n enabled: ").append(enabled);
}
b.append("\n\n# YAY! Now, let's see what we can find in your JVM\n");
Runtime runtime = Runtime.getRuntime();
final Runtime runtime = Runtime.getRuntime();
b.append("memory.free: ").append(runtime.freeMemory()).append("\n");
b.append("memory.max: ").append(runtime.maxMemory()).append("\n");
b.append("java.specification.version: '").append(System.getProperty("java.specification.version")).append("'\n");
@ -63,9 +65,9 @@ public class DebugPaste extends SubCommand {
b.append("# Okay :D Great. You are now ready to create your bug report!");
b.append("\n# You can do so at https://github.com/IntellectualSites/PlotSquared/issues");
String link = HastebinUtility.upload(b.toString());
final String link = HastebinUtility.upload(b.toString());
plr.sendMessage(C.DEBUG_REPORT_CREATED.s().replace("%url%", link));
} catch (IOException e) {
} catch (final IOException e) {
e.printStackTrace();
}
}

View File

@ -20,7 +20,6 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.generator.HybridPlotManager;
import com.intellectualcrafters.plot.generator.HybridPlotWorld;
@ -28,8 +27,8 @@ import com.intellectualcrafters.plot.generator.HybridUtils;
import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.PlotWorld;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.MathMan;
import com.plotsquared.general.commands.CommandDeclaration;
@ -40,19 +39,17 @@ import com.plotsquared.general.commands.CommandDeclaration;
requiredType = RequiredType.NONE,
description = "Regenerate all roads based on the road schematic",
category = CommandCategory.DEBUG,
permission = "plots.debugroadregen"
)
permission = "plots.debugroadregen")
public class DebugRoadRegen extends SubCommand {
@Override
public boolean onCommand(final PlotPlayer player, final String... args) {
final Location loc = player.getLocation();
final String world = loc.getWorld();
PlotWorld plotworld = PS.get().getPlotWorld(world);
final PlotArea plotworld = loc.getPlotArea();
if (!(plotworld instanceof HybridPlotWorld)) {
return sendMessage(player, C.NOT_IN_PLOT_WORLD);
}
Plot plot = player.getCurrentPlot();
final Plot plot = player.getCurrentPlot();
if (plot == null) {
final ChunkLoc chunk = new ChunkLoc(loc.getX() >> 4, loc.getZ() >> 4);
int extend = 0;
@ -60,22 +57,22 @@ public class DebugRoadRegen extends SubCommand {
if (MathMan.isInteger(args[0])) {
try {
extend = Integer.parseInt(args[0]);
}
catch (Exception e) {
} catch (final Exception e) {
C.NOT_VALID_NUMBER.send(player, "(0, <EXTEND HEIGHT>)");
return false;
}
}
}
boolean result = HybridUtils.manager.regenerateRoad(world, chunk, extend);
MainUtil.sendMessage(player, "&6Regenerating chunk: " + chunk.x + "," + chunk.z + "\n&6 - Result: " + (result == true ? "&aSuccess" : "&cFailed"));
}
else {
HybridPlotManager manager = (HybridPlotManager) PS.get().getPlotManager(world);
final boolean result = HybridUtils.manager.regenerateRoad(plotworld, chunk, extend);
MainUtil.sendMessage(player, "&6Regenerating chunk: " + chunk.x + "," + chunk.z + "\n&6 - Result: " + (result ? "&aSuccess" : "&cFailed"));
MainUtil.sendMessage(player, "&cTo regenerate all roads: /plot regenallroads");
} else {
final HybridPlotManager manager = (HybridPlotManager) plotworld.getPlotManager();
manager.createRoadEast(plotworld, plot);
manager.createRoadSouth(plotworld, plot);
manager.createRoadSouthEast(plotworld, plot);
MainUtil.sendMessage(player, "&6Regenerating plot south/east roads: " + plot.id + "\n&6 - Result: &aSuccess");
MainUtil.sendMessage(player, "&6Regenerating plot south/east roads: " + plot.getId() + "\n&6 - Result: &aSuccess");
MainUtil.sendMessage(player, "&cTo regenerate all roads: /plot regenallroads");
}
return true;
}

View File

@ -35,19 +35,18 @@ import com.plotsquared.general.commands.CommandDeclaration;
category = CommandCategory.DEBUG,
requiredType = RequiredType.CONSOLE,
usage = "/plot debugsavetest",
description = "This command will force the recreation of all plots in the DB"
)
description = "This command will force the recreation of all plots in the DB")
public class DebugSaveTest extends SubCommand {
@Override
public boolean onCommand(PlotPlayer plr, String[] args) {
public boolean onCommand(final PlotPlayer plr, final String[] args) {
final ArrayList<Plot> plots = new ArrayList<Plot>();
plots.addAll(PS.get().getPlots());
MainUtil.sendMessage(null, "&6Starting `DEBUGSAVETEST`");
MainUtil.sendMessage(plr, "&6Starting `DEBUGSAVETEST`");
DBFunc.createPlotsAndData(plots, new Runnable() {
@Override
public void run() {
MainUtil.sendMessage(null, "&6Database sync finished!");
MainUtil.sendMessage(plr, "&6Database sync finished!");
}
});
return true;

View File

@ -1,303 +0,0 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
// 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.commands;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.UUID;
import org.bukkit.Bukkit;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.database.AbstractDB;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.object.OfflinePlotPlayer;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.StringWrapper;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.uuid.UUIDWrapper;
import com.plotsquared.bukkit.uuid.DefaultUUIDWrapper;
import com.plotsquared.bukkit.uuid.LowerOfflineUUIDWrapper;
import com.plotsquared.bukkit.uuid.OfflineUUIDWrapper;
import com.plotsquared.general.commands.Argument;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(
command = "uuidconvert",
permission = "plots.admin",
description = "Debug UUID conversion",
usage = "/plot uuidconvert <lower|offline|online>",
requiredType = RequiredType.CONSOLE,
category = CommandCategory.DEBUG
)
public class DebugUUID extends SubCommand {
public DebugUUID() {
requiredArguments = new Argument[] {
Argument.String
};
}
@Override
public boolean onCommand(final PlotPlayer plr, final String[] args) {
PlotPlayer player = null;
UUIDWrapper currentUUIDWrapper = UUIDHandler.getUUIDWrapper();
UUIDWrapper newWrapper = null;
switch (args[0].toLowerCase()) {
case "lower": {
newWrapper = new LowerOfflineUUIDWrapper();
break;
}
case "offline": {
newWrapper = new OfflineUUIDWrapper();
break;
}
case "online": {
newWrapper = new DefaultUUIDWrapper();
break;
}
default: {
try {
Class<?> clazz = Class.forName(args[0]);
newWrapper = (UUIDWrapper) clazz.newInstance();
}
catch (Exception e) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot uuidconvert <lower|offline|online>");
return false;
}
}
}
if (args.length != 2 || !args[1].equals("-o")) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot uuidconvert " + args[0] + " - o");
MainUtil.sendMessage(player, "&cBe aware of the following!");
MainUtil.sendMessage(player, "&8 - &cUse the database command or another method to backup your plots beforehand");
MainUtil.sendMessage(player, "&8 - &cIf the process is interrupted, all plots could be deleted");
MainUtil.sendMessage(player, "&8 - &cIf an error occurs, all plots could be deleted");
MainUtil.sendMessage(player, "&8 - &cPlot settings WILL be lost upon conversion");
MainUtil.sendMessage(player, "&cTO REITERATE: BACK UP YOUR DATABASE BEFORE USING THIS!!!");
MainUtil.sendMessage(player, "&7Retype the command with the override parameter when ready :)");
return false;
}
if (currentUUIDWrapper.getClass().getCanonicalName().equals(newWrapper.getClass().getCanonicalName())) {
MainUtil.sendMessage(player, "&cUUID mode already in use!");
return false;
}
MainUtil.sendConsoleMessage("&6Beginning UUID mode conversion");
MainUtil.sendConsoleMessage("&7 - Disconnecting players");
for (PlotPlayer pp : UUIDHandler.getPlayers().values()) {
pp.kick("PlotSquared UUID conversion has been initiated. You may reconnect when finished.");
}
MainUtil.sendConsoleMessage("&7 - Initializing map");
HashMap<UUID, UUID> uCMap = new HashMap<UUID, UUID>();
HashMap<UUID, UUID> uCReverse = new HashMap<UUID, UUID>();
MainUtil.sendConsoleMessage("&7 - Collecting playerdata");
final HashSet<String> worlds = new HashSet<>();
worlds.add(Bukkit.getWorlds().get(0).getName());
worlds.add("world");
final HashSet<UUID> uuids = new HashSet<>();
final HashSet<String> names = new HashSet<>();
for (final String worldname : worlds) {
final File playerdataFolder = new File(worldname + File.separator + "playerdata");
String[] dat = playerdataFolder.list(new FilenameFilter() {
@Override
public boolean accept(final File f, final String s) {
return s.endsWith(".dat");
}
});
if (dat != null) {
for (final String current : dat) {
final String s = current.replaceAll(".dat$", "");
try {
final UUID uuid = UUID.fromString(s);
uuids.add(uuid);
} catch (final Exception e) {
MainUtil.sendMessage(plr, C.PREFIX.s() + "Invalid playerdata: " + current);
}
}
}
final File playersFolder = new File(worldname + File.separator + "players");
dat = playersFolder.list(new FilenameFilter() {
@Override
public boolean accept(final File f, final String s) {
return s.endsWith(".dat");
}
});
if (dat != null) {
for (final String current : dat) {
names.add(current.replaceAll(".dat$", ""));
}
}
}
MainUtil.sendConsoleMessage("&7 - Populating map");
UUID uuid2;
final UUIDWrapper wrapper = new DefaultUUIDWrapper();
for (UUID uuid : uuids) {
try {
final OfflinePlotPlayer op = wrapper.getOfflinePlayer(uuid);
uuid = currentUUIDWrapper.getUUID(op);
uuid2 = newWrapper.getUUID(op);
if (!uuid.equals(uuid2)) {
uCMap.put(uuid, uuid2);
uCReverse.put(uuid2, uuid);
}
} catch (final Throwable e) {
MainUtil.sendMessage(plr, C.PREFIX.s() + "&6Invalid playerdata: " + uuid.toString() + ".dat");
}
}
for (final String name : names) {
final UUID uuid = currentUUIDWrapper.getUUID(name);
uuid2 = newWrapper.getUUID(name);
if (!uuid.equals(uuid2)) {
uCMap.put(uuid, uuid2);
uCReverse.put(uuid2, uuid);
}
}
if (uCMap.size() == 0) {
MainUtil.sendConsoleMessage("&c - Error! Attempting to repopulate");
for (OfflinePlotPlayer op : currentUUIDWrapper.getOfflinePlayers()) {
if (op.getLastPlayed() != 0) {
String name = op.getName();
StringWrapper wrap = new StringWrapper(name);
UUID uuid = currentUUIDWrapper.getUUID(op);
uuid2 = newWrapper.getUUID(op);
if (!uuid.equals(uuid2)) {
uCMap.put(uuid, uuid2);
uCReverse.put(uuid2, uuid);
}
}
}
if (uCMap.size() == 0) {
MainUtil.sendConsoleMessage("&cError. Failed to collect UUIDs!");
return false;
}
else {
MainUtil.sendConsoleMessage("&a - Successfully repopulated");
}
}
MainUtil.sendConsoleMessage("&7 - Replacing cache");
for (Entry<UUID, UUID> entry : uCMap.entrySet()) {
String name = UUIDHandler.getName(entry.getKey());
UUIDHandler.add(new StringWrapper(name), entry.getValue());
}
MainUtil.sendConsoleMessage("&7 - Replacing wrapper");
UUIDHandler.setUUIDWrapper(newWrapper);
MainUtil.sendConsoleMessage("&7 - Updating plot objects");
for (Plot plot : PS.get().getPlotsRaw()) {
UUID value = uCMap.get(plot.owner);
if (value != null) {
plot.owner = value;
}
plot.getTrusted().clear();
plot.getMembers().clear();
plot.getDenied().clear();
}
MainUtil.sendConsoleMessage("&7 - Deleting database");
final AbstractDB database = DBFunc.dbManager;
boolean result = database.deleteTables();
MainUtil.sendConsoleMessage("&7 - Creating tables");
try {
database.createTables();
if (!result) {
MainUtil.sendConsoleMessage("&cConversion failed! Attempting recovery");
for (Plot plot : PS.get().getPlots()) {
UUID value = uCReverse.get(plot.owner);
if (value != null) {
plot.owner = value;
}
}
database.createPlotsAndData(new ArrayList<>(PS.get().getPlots()), new Runnable() {
@Override
public void run() {
MainUtil.sendMessage(null, "&6Recovery was successful!");
}
});
return false;
}
}
catch (Exception e) {
e.printStackTrace();
return false;
}
if (newWrapper instanceof OfflineUUIDWrapper) {
PS.get().config.set("UUID.force-lowercase", false);
PS.get().config.set("UUID.offline", true);
}
else if (newWrapper instanceof LowerOfflineUUIDWrapper) {
PS.get().config.set("UUID.force-lowercase", true);
PS.get().config.set("UUID.offline", true);
}
else if (newWrapper instanceof DefaultUUIDWrapper) {
PS.get().config.set("UUID.force-lowercase", false);
PS.get().config.set("UUID.offline", false);
}
try {
PS.get().config.save(PS.get().configFile);
}
catch (Exception e) {
MainUtil.sendConsoleMessage("Could not save configuration. It will need to be manuall set!");
}
MainUtil.sendConsoleMessage("&7 - Populating tables");
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
ArrayList<Plot> plots = new ArrayList<>(PS.get().getPlots());
database.createPlotsAndData(plots, new Runnable() {
@Override
public void run() {
MainUtil.sendConsoleMessage("&aConversion complete!");
}
});
}
});
MainUtil.sendConsoleMessage("&aIt is now safe for players to join");
MainUtil.sendConsoleMessage("&cConversion is still in progress, you will be notified when it is complete");
return true;
}
}

View File

@ -20,19 +20,19 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.PS;
import java.util.HashSet;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.PlotWorld;
import com.intellectualcrafters.plot.util.CmdConfirm;
import com.intellectualcrafters.plot.util.EconHandler;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(
@ -41,62 +41,60 @@ import com.plotsquared.general.commands.CommandDeclaration;
description = "Delete a plot",
usage = "/plot delete",
aliases = { "dispose", "del" },
category = CommandCategory.ACTIONS,
requiredType = RequiredType.NONE
)
category = CommandCategory.CLAIMING,
requiredType = RequiredType.NONE)
public class Delete extends SubCommand {
@Override
public boolean onCommand(final PlotPlayer plr, final String[] args) {
final Location loc = plr.getLocation();
final Plot plot = MainUtil.getPlot(loc);
final Plot plot = loc.getPlotAbs();
if (plot == null) {
return !sendMessage(plr, C.NOT_IN_PLOT);
}
if (!MainUtil.getTopPlot(plot).equals(MainUtil.getBottomPlot(plot))) {
return !sendMessage(plr, C.UNLINK_REQUIRED);
if (!plot.hasOwner()) {
return !sendMessage(plr, C.PLOT_UNOWNED);
}
if (((!plot.hasOwner() || !plot.isOwner(plr.getUUID()))) && !Permissions.hasPermission(plr, "plots.admin.command.delete")) {
if (!plot.isOwner(plr.getUUID()) && !Permissions.hasPermission(plr, "plots.admin.command.delete")) {
return !sendMessage(plr, C.NO_PLOT_PERMS);
}
final PlotWorld pWorld = PS.get().getPlotWorld(plot.world);
if (MainUtil.runners.containsKey(plot)) {
final PlotArea plotworld = plot.getArea();
final HashSet<Plot> plots = plot.getConnectedPlots();
final Runnable run = new Runnable() {
@Override
public void run() {
if (plot.getRunning() > 0) {
MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER);
return false;
return;
}
Runnable runnable = new Runnable() {
@Override
public void run() {
if ((EconHandler.manager != null) && pWorld.USE_ECONOMY && plot.hasOwner() && plot.isOwner(UUIDHandler.getUUID(plr))) {
final double c = pWorld.SELL_PRICE;
if (c > 0d) {
EconHandler.manager.depositMoney(plr, c);
sendMessage(plr, C.ADDED_BALANCE, c + "");
}
}
if (plot.unclaim()) {
final long start = System.currentTimeMillis();
final boolean result = MainUtil.clearAsPlayer(plot, true, new Runnable() {
boolean result = plot.deletePlot(new Runnable() {
@Override
public void run() {
plot.removeRunning();
if ((EconHandler.manager != null) && plotworld.USE_ECONOMY) {
final double value = plotworld.SELL_PRICE * plots.size();
if (value > 0d) {
EconHandler.manager.depositMoney(plr, value);
sendMessage(plr, C.ADDED_BALANCE, value + "");
}
}
MainUtil.sendMessage(plr, C.CLEARING_DONE, "" + (System.currentTimeMillis() - start));
}
});
if (!result) {
MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER);
}
if (result) {
plot.addRunning();
}
else {
MainUtil.sendMessage(plr, C.UNCLAIM_FAILED);
MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER);
}
}
};
if (Settings.CONFIRM_DELETE && !(Permissions.hasPermission(plr, "plots.confirm.bypass"))) {
CmdConfirm.addPending(plr, "/plot delete " + plot.id, runnable);
}
else {
TaskManager.runTask(runnable);
CmdConfirm.addPending(plr, "/plot delete " + plot.getId(), run);
} else {
TaskManager.runTask(run);
}
return true;
}

View File

@ -27,40 +27,30 @@ import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.BlockManager;
import com.intellectualcrafters.plot.util.EventUtil;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.bukkit.uuid.SQLUUIDHandler;
import com.intellectualcrafters.plot.util.WorldUtil;
import com.plotsquared.general.commands.Argument;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(
command = "deny",
aliases = {"d"},
description = "Deny a user from a plot",
usage = "/plot deny <player>",
category = CommandCategory.ACTIONS,
requiredType = RequiredType.NONE
)
@CommandDeclaration(command = "deny", aliases = { "d", "ban" }, description = "Deny a user from a plot", usage = "/plot deny <player>", category = CommandCategory.SETTINGS, requiredType = RequiredType.NONE)
public class Deny extends SubCommand {
public Deny() {
requiredArguments = new Argument[] {
Argument.PlayerName
};
requiredArguments = new Argument[] { Argument.PlayerName };
}
@Override
public boolean onCommand(final PlotPlayer plr, final String[] args) {
final Location loc = plr.getLocation();
final Plot plot = MainUtil.getPlot(loc);
final Plot plot = loc.getPlotAbs();
if (plot == null) {
return !sendMessage(plr, C.NOT_IN_PLOT);
}
if ((plot == null) || !plot.hasOwner()) {
if (!plot.hasOwner()) {
MainUtil.sendMessage(plr, C.PLOT_UNOWNED);
return false;
}
@ -75,11 +65,7 @@ public class Deny extends SubCommand {
uuid = UUIDHandler.getUUID(args[0], null);
}
if (uuid == null) {
if (UUIDHandler.implementation instanceof SQLUUIDHandler) {
MainUtil.sendMessage(plr, C.INVALID_PLAYER_WAIT, args[0]);
} else {
MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[0]);
}
return false;
}
if (plot.isOwner(uuid)) {
@ -97,16 +83,26 @@ public class Deny extends SubCommand {
EventUtil.manager.callDenied(plr, plot, uuid, true);
MainUtil.sendMessage(plr, C.DENIED_ADDED);
if (!uuid.equals(DBFunc.everyone)) {
handleKick(uuid, plot);
handleKick(UUIDHandler.getPlayer(uuid), plot);
} else {
for (PlotPlayer pp : plot.getPlayersInPlot()) {
handleKick(pp, plot);
}
}
return true;
}
private void handleKick(final UUID uuid, final Plot plot) {
PlotPlayer pp = UUIDHandler.getPlayer(uuid);
if (pp != null && plot.equals(MainUtil.getPlot(pp.getLocation()))) {
pp.teleport(BlockManager.manager.getSpawn(pp.getLocation().getWorld()));
private void handleKick(final PlotPlayer pp, final Plot plot) {
if (pp == null) {
return;
}
if (!plot.equals(pp.getCurrentPlot())) {
return;
}
if (pp.hasPermission("plots.admin.entry.denied")) {
return;
}
pp.teleport(WorldUtil.IMP.getSpawn(pp.getLocation().getWorld()));
MainUtil.sendMessage(pp, C.YOU_GOT_DENIED);
}
}
}

View File

@ -20,49 +20,38 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import java.util.UUID;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.OfflinePlotPlayer;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.general.commands.Argument;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(
command = "limit",
permission = "plots.limit",
description = "Set or increment player plot claim limits",
aliases = {"setlimit"},
usage = "/plot limit <player> <expression>",
category = CommandCategory.DEBUG
)
public class Limit extends SubCommand {
public Limit() {
requiredArguments = new Argument[] {
Argument.String,
Argument.String
};
}
command = "setdescription",
permission = "plots.set.desc",
description = "Set the plot description",
usage = "/plot desc <description>",
aliases = { "desc", "setdesc", "setd", "description" },
category = CommandCategory.SETTINGS,
requiredType = RequiredType.NONE)
public class Desc extends SetCommand {
@Override
public boolean onCommand(final PlotPlayer plr, final String[] args) {
UUID uuid = UUIDHandler.getUUID(args[0], null);
if (uuid == null) {
MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[0]);
public boolean set(PlotPlayer plr, Plot plot, String desc) {
if (desc.isEmpty()) {
plot.removeFlag("description");
MainUtil.sendMessage(plr, C.DESC_UNSET);
return true;
}
final Flag flag = new Flag(FlagManager.getFlag("description"), desc);
final boolean result = FlagManager.addPlotFlag(plot, flag);
if (!result) {
MainUtil.sendMessage(plr, C.FLAG_NOT_ADDED);
return false;
}
OfflinePlotPlayer op = UUIDHandler.getUUIDWrapper().getOfflinePlayer(uuid);
// get current plot limit
// increase
// EconHandler.manager.setPermission(op, perm, value);
plr.sendMessage("TODO");
MainUtil.sendMessage(plr, C.DESC_SET);
return true;
}
}

View File

@ -30,52 +30,43 @@ import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotAnalysis;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.util.BlockManager;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(
command = "done",
aliases = {"submit"},
description = "Mark a plot as done",
permission = "plots.done",
category = CommandCategory.ACTIONS,
requiredType = RequiredType.NONE
)
@CommandDeclaration(command = "done", aliases = { "submit" }, description = "Mark a plot as done", permission = "plots.done", category = CommandCategory.SETTINGS, requiredType = RequiredType.NONE)
public class Done extends SubCommand {
@Override
public boolean onCommand(final PlotPlayer plr, final String[] args) {
final Location loc = plr.getLocation();
final Plot plot = MainUtil.getPlot(loc);
if (plot == null || !plot.hasOwner()) {
final Plot plot = loc.getPlotAbs();
if ((plot == null) || !plot.hasOwner()) {
return !sendMessage(plr, C.NOT_IN_PLOT);
}
if ((!plot.isOwner(plr.getUUID())) && !Permissions.hasPermission(plr, "plots.admin.command.done")) {
MainUtil.sendMessage(plr, C.NO_PLOT_PERMS);
return false;
}
if (plot.getSettings().flags.containsKey("done")) {
if (plot.getFlags().containsKey("done")) {
MainUtil.sendMessage(plr, C.DONE_ALREADY_DONE);
return false;
}
if (MainUtil.runners.containsKey(plot)) {
if (plot.getRunning() > 0) {
MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER);
return false;
}
MainUtil.runners.put(plot, 1);
plot.addRunning();
MainUtil.sendMessage(plr, C.GENERATING_LINK);
HybridUtils.manager.analyzePlot(plot, new RunnableVal<PlotAnalysis>() {
@Override
public void run() {
MainUtil.runners.remove(plot);
if (value == null || value.getComplexity() >= Settings.CLEAR_THRESHOLD) {
Flag flag = new Flag(FlagManager.getFlag("done"), (System.currentTimeMillis() / 1000));
public void run(PlotAnalysis value) {
plot.removeRunning();
if ((value == null) || (value.getComplexity() >= Settings.CLEAR_THRESHOLD)) {
final Flag flag = new Flag(FlagManager.getFlag("done"), (System.currentTimeMillis() / 1000));
FlagManager.addPlotFlag(plot, flag);
MainUtil.sendMessage(plr, C.DONE_SUCCESS);
}
else {
} else {
MainUtil.sendMessage(plr, C.DONE_INSUFFICIENT_COMPLEXITY);
}
}

View File

@ -6,6 +6,7 @@ import com.intellectualcrafters.jnbt.CompoundTag;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.RunnableVal;
@ -15,14 +16,7 @@ import com.intellectualcrafters.plot.util.SchematicHandler;
import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(
command = "download",
aliases = {"dl"},
category = CommandCategory.ACTIONS,
requiredType = RequiredType.NONE,
description = "Download your plot",
permission = "plots.download"
)
@CommandDeclaration(command = "download", aliases = { "dl" }, category = CommandCategory.SCHEMATIC, requiredType = RequiredType.NONE, description = "Download your plot", permission = "plots.download")
public class Download extends SubCommand {
@Override
@ -33,10 +27,10 @@ public class Download extends SubCommand {
return false;
}
final String world = plr.getLocation().getWorld();
if (!PS.get().isPlotWorld(world)) {
if (!PS.get().hasPlotArea(world)) {
return !sendMessage(plr, C.NOT_IN_PLOT_WORLD);
}
final Plot plot = MainUtil.getPlot(plr.getLocation());
final Plot plot = plr.getCurrentPlot();
if (plot == null) {
return !sendMessage(plr, C.NOT_IN_PLOT);
}
@ -44,30 +38,30 @@ public class Download extends SubCommand {
MainUtil.sendMessage(plr, C.PLOT_UNOWNED);
return false;
}
if (!plot.isOwner(plr.getUUID()) && !Permissions.hasPermission(plr, "plots.admin.command.download")) {
if ((!plot.isOwner(plr.getUUID()) || (Settings.DOWNLOAD_REQUIRES_DONE && (FlagManager.getPlotFlagRaw(plot, "done") != null))) && !Permissions.hasPermission(plr, "plots.admin.command.download")) {
MainUtil.sendMessage(plr, C.NO_PLOT_PERMS);
return false;
}
if (MainUtil.runners.containsKey(plot)) {
if (plot.getRunning() > 0) {
MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER);
return false;
}
MainUtil.runners.put(plot, 1);
plot.addRunning();
MainUtil.sendMessage(plr, C.GENERATING_LINK);
SchematicHandler.manager.getCompoundTag(plot.world, plot.id, new RunnableVal<CompoundTag>() {
SchematicHandler.manager.getCompoundTag(plot, new RunnableVal<CompoundTag>() {
@Override
public void run() {
public void run(final CompoundTag value) {
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
URL url = SchematicHandler.manager.upload(value, null, null);
final URL url = SchematicHandler.manager.upload(value, null, null);
if (url == null) {
MainUtil.sendMessage(plr, C.GENERATING_LINK_FAILED);
MainUtil.runners.remove(plot);
plot.removeRunning();
return;
}
MainUtil.sendMessage(plr, url.toString());
MainUtil.runners.remove(plot);
plot.removeRunning();
}
});
}

View File

@ -20,10 +20,6 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.flag.AbstractFlag;
@ -38,15 +34,19 @@ import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.StringMan;
import com.plotsquared.general.commands.CommandDeclaration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@CommandDeclaration(
command = "flag",
aliases = {"f"},
command = "setflag",
aliases = { "f", "flag", "setf", "setflag" },
usage = "/plot flag <set|remove|add|list|info> <flag> <value>",
description = "Manage plot flags",
category = CommandCategory.ACTIONS,
description = "Set plot flags",
category = CommandCategory.SETTINGS,
requiredType = RequiredType.NONE,
permission = "plots.flag"
)
permission = "plots.flag")
public class FlagCmd extends SubCommand {
@Override
@ -69,7 +69,7 @@ public class FlagCmd extends SubCommand {
return false;
}
final Location loc = player.getLocation();
final Plot plot = MainUtil.getPlot(loc);
final Plot plot = loc.getPlotAbs();
if (plot == null) {
MainUtil.sendMessage(player, C.NOT_IN_PLOT);
return false;
@ -124,11 +124,11 @@ public class FlagCmd extends SubCommand {
MainUtil.sendMessage(player, C.NOT_VALID_FLAG);
return false;
}
if (!Permissions.hasPermission(player, "plots.set.flag." + args[1].toLowerCase())) {
MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.set.flag." + args[1].toLowerCase());
final String value = StringMan.join(Arrays.copyOfRange(args, 2, args.length), " ");
if (!Permissions.hasPermission(player, "plots.set.flag." + args[1].toLowerCase() + "." + value.toLowerCase())) {
MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.set.flag." + args[1].toLowerCase() + "." + value.toLowerCase());
return false;
}
final String value = StringMan.join(Arrays.copyOfRange(args, 2, args.length), " ");
final Object parsed = af.parseValueRaw(value);
if (parsed == null) {
MainUtil.sendMessage(player, "&c" + af.getValueDesc());
@ -148,7 +148,7 @@ public class FlagCmd extends SubCommand {
MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.flag.remove");
return false;
}
if ((args.length != 2) && (args.length != 3)) {
if (args.length != 2 && args.length != 3) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag remove <flag> [values]");
return false;
}
@ -157,19 +157,27 @@ public class FlagCmd extends SubCommand {
MainUtil.sendMessage(player, C.NOT_VALID_FLAG);
return false;
}
final Flag flag = FlagManager.getPlotFlagAbs(plot, args[1].toLowerCase());
if (!Permissions.hasPermission(player, "plots.set.flag." + args[1].toLowerCase())) {
if (args.length != 2) {
MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.set.flag." + args[1].toLowerCase());
return false;
}
final Flag flag = FlagManager.getPlotFlagAbs(plot, args[1].toLowerCase());
for (final String entry : args[2].split(",")) {
if (!Permissions.hasPermission(player, "plots.set.flag." + args[1].toLowerCase() + "." + entry)) {
MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.set.flag." + args[1].toLowerCase() + "." + entry);
return false;
}
}
}
if (flag == null) {
MainUtil.sendMessage(player, C.FLAG_NOT_IN_PLOT);
return false;
}
if ((args.length == 3) && flag.getAbstractFlag().isList()) {
if (args.length == 3 && flag.getAbstractFlag().isList()) {
final String value = StringMan.join(Arrays.copyOfRange(args, 2, args.length), " ");
((FlagValue.ListValue) flag.getAbstractFlag().value).remove(flag.getValue(), value);
DBFunc.setFlags(plot, plot.getSettings().flags.values());
DBFunc.setFlags(plot, plot.getFlags().values());
} else {
final boolean result = FlagManager.removePlotFlag(plot, flag.getKey());
if (!result) {
@ -194,10 +202,12 @@ public class FlagCmd extends SubCommand {
MainUtil.sendMessage(player, C.NOT_VALID_FLAG);
return false;
}
if (!Permissions.hasPermission(player, "plots.set.flag." + args[1].toLowerCase())) {
MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.set.flag." + args[1].toLowerCase());
for (final String entry : args[2].split(",")) {
if (!Permissions.hasPermission(player, "plots.set.flag." + args[1].toLowerCase() + "." + entry)) {
MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.set.flag." + args[1].toLowerCase() + "." + entry);
return false;
}
}
final String value = StringMan.join(Arrays.copyOfRange(args, 2, args.length), " ");
final Object parsed = af.parseValueRaw(value);
if (parsed == null) {
@ -205,7 +215,7 @@ public class FlagCmd extends SubCommand {
return false;
}
Flag flag = FlagManager.getPlotFlag(plot, args[1].toLowerCase());
if ((flag == null) || !flag.getAbstractFlag().isList()) {
if (flag == null || !flag.getAbstractFlag().isList()) {
flag = new Flag(FlagManager.getFlag(args[1].toLowerCase(), true), parsed);
} else {
((FlagValue.ListValue) flag.getAbstractFlag().value).add(flag.getValue(), value);
@ -215,11 +225,11 @@ public class FlagCmd extends SubCommand {
MainUtil.sendMessage(player, C.FLAG_NOT_ADDED);
return false;
}
DBFunc.setFlags(plot, plot.getSettings().flags.values());
DBFunc.setFlags(plot, plot.getFlags().values());
MainUtil.sendMessage(player, C.FLAG_ADDED);
return true;
}
case "list": {
case "list":
if (!Permissions.hasPermission(player, "plots.flag.list")) {
MainUtil.sendMessage(player, C.NO_PERMISSION, "plots.flag.list");
return false;
@ -238,14 +248,13 @@ public class FlagCmd extends SubCommand {
}
String message = "";
String prefix = "";
for (final String flag : flags.keySet()) {
message += prefix + "&6" + flag + ": &7" + StringMan.join(flags.get(flag), ", ");
for (final Map.Entry<String, ArrayList<String>> stringArrayListEntry : flags.entrySet()) {
message += prefix + "&6" + stringArrayListEntry.getKey() + ": &7" + StringMan.join(stringArrayListEntry.getValue(), ", ");
prefix = "\n";
}
MainUtil.sendMessage(player, message);
return true;
}
}
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot flag <set|remove|add|list|info>");
return false;
}

View File

@ -0,0 +1,221 @@
package com.intellectualcrafters.plot.commands;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.StringMan;
import com.plotsquared.general.commands.Command;
public class GenerateDocs {
public static void main(final String[] args) {
MainCommand.getInstance().addCommand(new WE_Anywhere());
MainCommand.getInstance().addCommand(new Cluster());
final ArrayList<Command<PlotPlayer>> commands = MainCommand.getInstance().getCommands();
log("### Want to document some commands?");
log(" - This page is automatically generated");
log(" - Fork the project and add a javadoc comment to one of the command classes");
log(" - Then do a pull request and it will be added to this page");
log("");
log("# Contents");
for (final CommandCategory category : CommandCategory.values()) {
log("###### " + category.name());
for (final Command<PlotPlayer> command : MainCommand.getCommands(category, null)) {
log(" - [/plot " + command.getCommand() + "](https://github.com/IntellectualSites/PlotSquared/wiki/Commands#" + command.getCommand() + ") ");
}
log("");
}
log("# Commands");
for (final Command<PlotPlayer> command : commands) {
printCommand(command);
}
}
public static void printCommand(final Command<PlotPlayer> command) {
try {
final String clazz = command.getClass().getSimpleName();
final String name = command.getCommand();
// Header
final String source = "https://github.com/IntellectualSites/PlotSquared/tree/master/src/main/java/com/intellectualcrafters/plot/commands/" + clazz + ".java";
log("## [" + name.toUpperCase() + "](" + source + ") ");
final File file = new File("src/main/java/com/intellectualcrafters/plot/commands/" + clazz + ".java");
final List<String> lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
final List<String> perms = getPerms(name, lines);
final List<String> usages = getUsage(name, lines);
final String comment = getComments(lines);
log("#### Description");
log("`" + command.getDescription() + "`");
if (!comment.isEmpty()) {
log("##### Comments");
log("``` java");
log(comment);
log("```");
}
log("#### Usage ");
{
String mainUsage = command.getUsage().replaceAll("\\{label\\}", "plot");
if (!usages.isEmpty() && !usages.get(0).equalsIgnoreCase(mainUsage)) {
log("##### Primary ");
log(" - `" + mainUsage + "` ");
log("");
log("##### Other ");
log(" - `" + StringMan.join(usages, "`\n - `") + "` ");
log("");
} else {
log("`" + mainUsage + "` ");
}
}
if (command.getRequiredType() != RequiredType.NONE) {
log("#### Required callers");
log("`" + command.getRequiredType().name() + "`");
}
final Set<String> aliases = command.getAliases();
if (!aliases.isEmpty()) {
log("#### Aliases");
log("`" + StringMan.getString(command.getAliases()) + "`");
}
log("#### Permissions");
if (!perms.isEmpty()) {
log("##### Primary");
log(" - `" + command.getPermission() + "` ");
log("");
log("##### Other");
log(" - `" + StringMan.join(perms, "`\n - `") + "`");
log("");
} else {
log("`" + command.getPermission() + "` ");
}
log("***");
log("");
} catch (final Exception e) {
e.printStackTrace();
}
}
public static List<String> getUsage(String cmd, List<String> lines) {
final Pattern p = Pattern.compile("\"([^\"]*)\"");
HashSet<String> usages = new HashSet<String>();
for (final String line : lines) {
if (line.contains("COMMAND_SYNTAX") && !line.contains("getUsage()")) {
final Matcher m = p.matcher(line);
String prefix = "";
StringBuilder usage = new StringBuilder();
while (m.find()) {
String match = m.group(1);
usage.append(prefix).append(match);
prefix = " <arg> ";
}
if (usage.length() != 0) {
usages.add(usage.toString().trim().replaceAll(" ", " ").replaceAll("\\{label\\}", "plot"));
}
}
}
return new ArrayList<>(usages);
}
public static List<String> getPerms(final String cmd, final List<String> lines) {
final HashSet<String> perms = new HashSet<String>();
final Pattern p = Pattern.compile("\"([^\"]*)\"");
final Pattern p2 = Pattern.compile("C.PERMISSION_\\s*(\\w+)");
String last = null;
for (final String line : lines) {
Matcher m2 = p2.matcher(line);
while (m2.find()) {
perms.add(C.valueOf("PERMISSION_" + m2.group(1)).s());
}
if (line.contains("Permissions.hasPermission(")) {
String[] split = line.split("Permissions.hasPermission");
split = Arrays.copyOfRange(split, 1, split.length);
for (String method : split) {
String perm = method.split("[,|)]")[1].trim();
if (!perm.toLowerCase().equals(perm)) {
if (perm.startsWith("C.")) {
perm = C.valueOf(perm.split("\\.")[1]).s();
}
else {
continue;
}
}
else {
perm = perm.substring(1, perm.length() - 1);
}
perms.add(perm);
}
final Matcher m = p.matcher(line);
while (m.find()) {
String perm = m.group(1);
if (perm.endsWith(".")) {
perm += "<arg>";
}
if (perm.startsWith(".")) {
perms.remove(last);
perms.add(last + perm);
} else if (perm.contains(".")) {
last = perm;
perms.add(perm);
}
}
}
else if (line.contains("Permissions.hasPermissionRange")) {
String[] split = line.split("Permissions.hasPermissionRange");
split = Arrays.copyOfRange(split, 1, split.length);
for (String method : split) {
String perm = method.split("[,|)]")[1].trim();
if (!perm.toLowerCase().equals(perm)) {
if (perm.startsWith("C.")) {
perm = C.valueOf(perm.split("\\.")[1]).s();
}
else {
continue;
}
}
else {
perm = perm.substring(1, perm.length() - 1);
}
perms.add(perm + ".<#>");
}
}
}
switch (cmd.toLowerCase()) {
case "auto":
case "claim": {
perms.add("plots.plot.<#>");
break;
}
}
return new ArrayList<>(perms);
}
public static String getComments(final List<String> lines) {
final StringBuilder result = new StringBuilder();
for (String line : lines) {
line = line.trim();
if (line.startsWith("/** ") || line.startsWith("*/ ") || line.startsWith("* ")) {
line = (line.replaceAll("/[*][*] ", "").replaceAll("[*]/ ", "").replaceAll("[*] ", "")).trim();
result.append(line + "\n");
}
}
return result.toString().trim();
}
public static void log(final String s) {
System.out.println(s);
}
}

View File

@ -0,0 +1,60 @@
package com.intellectualcrafters.plot.commands;
import java.util.UUID;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.util.ByteArrayUtilities;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(
command = "grant",
category = CommandCategory.CLAIMING,
usage = "/plot grant <check|add> [player]",
permission = "plots.grant",
requiredType = RequiredType.NONE
)
public class Grant extends SubCommand {
@Override
public boolean onCommand(final PlotPlayer plr, final String[] args) {
final String arg0 = args[0].toLowerCase();
switch (arg0) {
case "add":
case "check":
if (Permissions.hasPermission(plr, "plots.grant." + arg0)) {
C.NO_PERMISSION.send(plr, "plots.grant." + arg0);
return false;
}
if (args.length > 2) {
break;
}
final UUID uuid = args.length == 2 ? UUIDHandler.getUUIDFromString(args[1]) : plr.getUUID();
if (uuid == null) {
C.INVALID_PLAYER.send(plr, args[1]);
return false;
}
MainUtil.getPersistentMeta(uuid, "grantedPlots", new RunnableVal<byte[]>() {
@Override
public void run(byte[] array) {
if (arg0.equals("check")) { // check
int granted = array == null ? 0 : ByteArrayUtilities.bytesToInteger(array);
C.GRANTED_PLOTS.send(plr, granted);
} else { // add
int amount = 1 + (array == null ? 0 : ByteArrayUtilities.bytesToInteger(array));
boolean replace = array != null;
DBFunc.dbManager.addPersistentMeta(uuid, "grantedPlots", ByteArrayUtilities.integerToBytes(amount), replace);
}
}
});
return true;
}
C.COMMAND_SYNTAX.send(plr, getUsage());
return false;
}
}

View File

@ -1,21 +1,9 @@
/*
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
*
* >> File = Help.java >> Generated by: Citymonstret at 2014-08-11 17:32
*/
package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(
command = "help",
description = "Get this help menu",
aliases = {"he"},
category = CommandCategory.INFO
)
@CommandDeclaration(command = "help", description = "Get this help menu", aliases = { "he" }, category = CommandCategory.INFO)
public class Help extends SubCommand {
@Override

View File

@ -20,76 +20,15 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import java.util.ArrayList;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.PS.SortType;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.MainUtil;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(
command = "home",
aliases = {"h"},
description = "Go to your plot",
usage = "/plot home [id|alias]",
category = CommandCategory.TELEPORT,
requiredType = RequiredType.NONE
)
@CommandDeclaration(command = "home", aliases = { "h" }, description = "Go to your plot", usage = "/plot home [id|alias]",
category = CommandCategory.TELEPORT, requiredType = RequiredType.NONE)
public class Home extends SubCommand {
private Plot isAlias(final String a) {
for (final Plot p : PS.get().getPlots()) {
if ((p.getSettings().getAlias().length() > 0) && p.getSettings().getAlias().equalsIgnoreCase(a)) {
return p;
}
}
return null;
}
@Override
public boolean onCommand(final PlotPlayer plr, String[] args) {
final ArrayList<Plot> plots = PS.get().sortPlotsByTemp(PS.get().getPlots(plr));//PS.get().sortPlots(PS.get().getPlots(plr), SortType.CREATION_DATE, null);
if (plots.size() == 1) {
MainUtil.teleportPlayer(plr, plr.getLocation(), plots.get(0));
return true;
} else if (plots.size() > 1) {
if (args.length < 1) {
args = new String[] { "1" };
}
int id = 0;
try {
id = Integer.parseInt(args[0]);
} catch (final Exception e) {
Plot temp;
if ((temp = isAlias(args[0])) != null) {
if (temp.hasOwner()) {
if (temp.isOwner(plr.getUUID())) {
MainUtil.teleportPlayer(plr, plr.getLocation(), temp);
return true;
}
}
MainUtil.sendMessage(plr, C.NOT_YOUR_PLOT);
return false;
}
MainUtil.sendMessage(plr, C.NOT_VALID_NUMBER, "(1, " + plots.size() + ")");
return true;
}
if ((id > (plots.size())) || (id < 1)) {
MainUtil.sendMessage(plr, C.NOT_VALID_NUMBER, "(1, " + plots.size() + ")");
return false;
}
MainUtil.teleportPlayer(plr, plr.getLocation(), plots.get(id - 1));
return true;
} else {
MainUtil.sendMessage(plr, C.FOUND_NO_PLOTS);
return true;
}
}
public void teleportPlayer(final PlotPlayer player, final Plot plot) {
MainUtil.teleportPlayer(player, player.getLocation(), plot);
return MainCommand.getInstance().getCommand("visit").onCommand(plr, args);
}
}

View File

@ -20,9 +20,6 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import java.util.ArrayList;
import java.util.List;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
@ -34,22 +31,24 @@ import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.StringMan;
import com.plotsquared.general.commands.CommandDeclaration;
import java.util.ArrayList;
import java.util.List;
@CommandDeclaration(
command = "inbox",
description = "Review the comments for a plot",
usage = "/plot inbox [inbox] [delete <index>|clear|page]",
permission = "plots.inbox",
category = CommandCategory.ACTIONS,
requiredType = RequiredType.NONE
)
category = CommandCategory.CHAT,
requiredType = RequiredType.NONE)
public class Inbox extends SubCommand {
public void displayComments(PlotPlayer player, List<PlotComment> oldComments, int page) {
if (oldComments == null || oldComments.size() == 0) {
public void displayComments(final PlotPlayer player, final List<PlotComment> oldComments, int page) {
if ((oldComments == null) || (oldComments.isEmpty())) {
MainUtil.sendMessage(player, C.INBOX_EMPTY);
return;
}
PlotComment[] comments = oldComments.toArray(new PlotComment[oldComments.size()]);
final PlotComment[] comments = oldComments.toArray(new PlotComment[oldComments.size()]);
if (page < 0) {
page = 0;
}
@ -73,11 +72,10 @@ public class Inbox extends SubCommand {
String color;
if (player.getName().equals(c.senderName)) {
color = "&a";
}
else {
} else {
color = "&7";
}
string.append("&8[&7#" + x + "&8][&7" + c.world + ";" + c.id + "&8][&6" + c.senderName + "&8]" + color + c.comment + "\n");
string.append("&8[&7#" + (x + 1) + "&8][&7" + c.world + ";" + c.id + "&8][&6" + c.senderName + "&8]" + color + c.comment + "\n");
}
MainUtil.sendMessage(player, string.toString());
}
@ -85,19 +83,18 @@ public class Inbox extends SubCommand {
@Override
public boolean onCommand(final PlotPlayer player, final String[] args) {
final Plot plot = MainUtil.getPlot(player.getLocation());
final Plot plot = player.getCurrentPlot();
if (args.length == 0) {
sendMessage(player, C.COMMAND_SYNTAX, "/plot inbox [inbox] [delete <index>|clear|page]");
for (final CommentInbox inbox : CommentManager.inboxes.values()) {
if (inbox.canRead(plot, player)) {
if (!inbox.getComments(plot, new RunnableVal() {
if (!inbox.getComments(plot, new RunnableVal<List<PlotComment>>() {
@Override
public void run() {
public void run(List<PlotComment> value) {
if (value != null) {
int total = 0;
int unread = 0;
for (PlotComment comment : (ArrayList<PlotComment>) value) {
for (final PlotComment comment : value) {
total++;
if (comment.timestamp > CommentManager.getTimestamp(player, inbox.toString())) {
unread++;
@ -107,8 +104,7 @@ public class Inbox extends SubCommand {
String color;
if (unread > 0) {
color = "&c";
}
else {
} else {
color = "";
}
sendMessage(player, C.INBOX_ITEM, color + inbox.toString() + " (" + total + "/" + unread + ")");
@ -136,6 +132,7 @@ public class Inbox extends SubCommand {
case "delete": {
if (!inbox.canModify(plot, player)) {
sendMessage(player, C.NO_PERM_INBOX_MODIFY);
return false;
}
if (args.length != 3) {
sendMessage(player, C.COMMAND_SYNTAX, "/plot inbox " + inbox.toString() + " delete <index>");
@ -147,20 +144,20 @@ public class Inbox extends SubCommand {
sendMessage(player, C.NOT_VALID_INBOX_INDEX, index + "");
return false;
}
}
catch (NumberFormatException e) {
} catch (final NumberFormatException e) {
sendMessage(player, C.COMMAND_SYNTAX, "/plot inbox " + inbox.toString() + " delete <index>");
return false;
}
if (!inbox.getComments(plot, new RunnableVal() {
if (!inbox.getComments(plot, new RunnableVal<List<PlotComment>>() {
@Override
public void run() {
List<PlotComment> comments = (List<PlotComment>) value;
public void run(List<PlotComment> value) {
final List<PlotComment> comments = value;
if (index > comments.size()) {
sendMessage(player, C.NOT_VALID_INBOX_INDEX, index + "");
return;
}
PlotComment comment = comments.get(index - 1);
final PlotComment comment = comments.get(index - 1);
inbox.removeComment(plot, comment);
plot.getSettings().removeComment(comment);
MainUtil.sendMessage(player, C.COMMENT_REMOVED, comment.comment);
@ -176,7 +173,7 @@ public class Inbox extends SubCommand {
sendMessage(player, C.NO_PERM_INBOX_MODIFY);
}
inbox.clearInbox(plot);
ArrayList<PlotComment> comments = plot.getSettings().getComments(inbox.toString());
final ArrayList<PlotComment> comments = plot.getSettings().getComments(inbox.toString());
if (comments != null) {
plot.getSettings().removeComments(comments);
}
@ -186,32 +183,29 @@ public class Inbox extends SubCommand {
default: {
try {
page = Integer.parseInt(args[1]);
}
catch (NumberFormatException e) {
} catch (final NumberFormatException e) {
sendMessage(player, C.COMMAND_SYNTAX, "/plot inbox [inbox] [delete <index>|clear|page]");
return false;
}
}
}
}
else {
} else {
page = 1;
}
if (!inbox.canRead(plot, player)) {
sendMessage(player, C.NO_PERM_INBOX);
return false;
}
if (!inbox.getComments(plot, new RunnableVal() {
if (!inbox.getComments(plot, new RunnableVal<List<PlotComment>>() {
@Override
public void run() {
List<PlotComment> comments = (List<PlotComment>) value;
public void run(List<PlotComment> value) {
final List<PlotComment> comments = value;
displayComments(player, comments, page);
}
})) {
if (plot == null) {
sendMessage(player, C.NOT_IN_PLOT);
}
else {
} else {
sendMessage(player, C.PLOT_UNOWNED);
}
return false;

View File

@ -20,77 +20,28 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import java.util.ArrayList;
import java.util.Collection;
import java.util.UUID;
import java.util.regex.Matcher;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotInventory;
import com.intellectualcrafters.plot.object.PlotItemStack;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.PlotWorld;
import com.intellectualcrafters.plot.util.BlockManager;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(
command = "info",
aliases = {"i"},
description = "Display plot info",
usage = "/plot info <id>",
category = CommandCategory.INFO
)
@CommandDeclaration(command = "info", aliases = { "i" }, description = "Display plot info", usage = "/plot info <id>",
category = CommandCategory.INFO)
public class Info extends SubCommand {
public static String getPlayerList(final Collection<UUID> uuids) {
ArrayList<UUID> l = new ArrayList<>(uuids);
if ((l == null) || (l.size() < 1)) {
return C.NONE.s();
}
final String c = C.PLOT_USER_LIST.s();
final StringBuilder list = new StringBuilder();
for (int x = 0; x < l.size(); x++) {
if ((x + 1) == l.size()) {
list.append(c.replace("%user%", getPlayerName(l.get(x))).replace(",", ""));
} else {
list.append(c.replace("%user%", getPlayerName(l.get(x))));
}
}
return list.toString();
}
public static String getPlayerName(final UUID uuid) {
if (uuid == null) {
return C.UNKNOWN.s();
}
if (uuid.equals(DBFunc.everyone) || uuid.toString().equalsIgnoreCase(DBFunc.everyone.toString())) {
return "everyone";
}
final String name = UUIDHandler.getName(uuid);
if (name == null) {
return "unknown";
}
return name;
}
@Override
public boolean onCommand(final PlotPlayer player, String[] args) {
String arg = null;
Plot plot;
if (args.length > 0) arg = args[0] + "";
if (arg != null) {
String arg;
if (args.length > 0) {
arg = args[0];
switch (arg) {
case "trusted":
case "alias":
@ -109,18 +60,17 @@ public class Info extends SubCommand {
plot = MainUtil.getPlotFromString(player, arg, false);
if (args.length == 2) {
arg = args[1];
}
else {
} else {
arg = null;
}
break;
}
if (plot == null) {
plot = player.getCurrentPlot();
}
else {
plot = MainUtil.getPlotFromString(player, null, false);
}
if (plot == null && arg != null) {
plot = MainUtil.getPlotFromString(player, null, false);
} else {
arg = null;
plot = player.getCurrentPlot();
}
if (plot == null) {
MainUtil.sendMessage(player, C.NOT_IN_PLOT);
@ -129,27 +79,35 @@ public class Info extends SubCommand {
if (arg != null) {
if (args.length == 1) {
args = new String[0];
}
else {
} else {
args = new String[] { args[1] };
}
}
if ((args.length == 1) && args[0].equalsIgnoreCase("inv")) {
PlotInventory inv = new PlotInventory(player) {
final PlotInventory inv = new PlotInventory(player) {
@Override
public boolean onClick(int index) {
public boolean onClick(final int index) {
// TODO InfoInventory not implemented yet!!!!!!!!
// See plot rating or musicsubcommand on examples
return false;
}
};
UUID uuid = player.getUUID();
String name = MainUtil.getName(plot.owner);
inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cPlot Info", new String[] { "&cID: &6" + plot.getId().toString(), "&cOwner: &6" + name, "&cAlias: &6" + plot.getSettings().getAlias(), "&cBiome: &6" + plot.getBiome().toString().replaceAll("_", "").toLowerCase(), "&cCan Build: &6" + plot.isAdded(uuid), "&cIs Denied: &6" + plot.isDenied(uuid)}));
inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cTrusted", new String[] {"&cAmount: &6" + plot.getTrusted().size(), "&8Click to view a list of the trusted users"}));
inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cMembers", new String[] {"&cAmount: &6" + plot.getMembers().size(), "&8Click to view a list of plot members"}));
inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cDenied", new String[] {"&cDenied", "&cAmount: &6" + plot.getDenied().size(), "&8Click to view a list of denied players"}));
inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cFlags", new String[] {"&cFlags", "&cAmount: &6" + plot.getSettings().flags.size(), "&8Click to view a list of plot flags"}));
final UUID uuid = player.getUUID();
final String name = MainUtil.getName(plot.owner);
inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cPlot Info", "&cID: &6" + plot.getId().toString(),
"&cOwner: &6" + name,
"&cAlias: &6" + plot.getAlias(),
"&cBiome: &6" + plot.getBiome().replaceAll("_", "").toLowerCase(),
"&cCan Build: &6" + plot.isAdded(uuid),
"&cIs Denied: &6" + plot.isDenied(uuid)));
inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cTrusted", "&cAmount: &6" + plot.getTrusted().size(),
"&8Click to view a list of the trusted users"));
inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cMembers", "&cAmount: &6" + plot.getMembers().size(),
"&8Click to view a list of plot members"));
inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cDenied", "&cDenied", "&cAmount: &6" + plot.getDenied().size(),
"&8Click to view a list of denied players"));
inv.setItem(1, new PlotItemStack(388, (short) 0, 1, "&cFlags", "&cFlags", "&cAmount: &6" + plot.getFlags().size(),
"&8Click to view a list of plot flags"));
inv.openInventory();
return true;
}
@ -163,21 +121,27 @@ public class Info extends SubCommand {
}
// Unclaimed?
if (!hasOwner && !containsEveryone && !trustedEveryone) {
MainUtil.sendMessage(player, C.PLOT_INFO_UNCLAIMED, (plot.id.x + ";" + plot.id.y));
MainUtil.sendMessage(player, C.PLOT_INFO_UNCLAIMED, (plot.getId().x + ";" + plot.getId().y));
return true;
}
String info = C.PLOT_INFO.s();
boolean full;
if (arg != null) {
info = getCaption(arg);
if (info == null) {
MainUtil.sendMessage(player, "&6Categories&7: &amembers&7, &aalias&7, &abiome&7, &adenied&7, &aflags&7, &aid&7, &asize&7, &atrusted&7, &aowner&7, &arating");
return false;
}
formatAndSend(info, plot.world, plot, player, true);
full = true;
} else {
full = false;
}
else {
formatAndSend(info, plot.world, plot, player, false);
MainUtil.format(info, plot, player, full, new RunnableVal<String>() {
@Override
public void run(String value) {
MainUtil.sendMessage(player, C.PLOT_INFO_HEADER.s() + '\n' + value + '\n' + C.PLOT_INFO_FOOTER.s(), false);
}
});
return true;
}
@ -207,72 +171,4 @@ public class Info extends SubCommand {
return null;
}
}
private void formatAndSend(String info, final String world, final Plot plot, final PlotPlayer player, final boolean full) {
final PlotId id = plot.id;
final PlotId id2 = MainUtil.getTopPlot(plot).id;
final int num = MainUtil.getPlotSelectionIds(id, id2).size();
final String alias = plot.getSettings().getAlias().length() > 0 ? plot.getSettings().getAlias() : C.NONE.s();
Location top = MainUtil.getPlotTopLoc(world, plot.id);
Location bot = MainUtil.getPlotBottomLoc(world, plot.id).add(1, 0, 1);
final String biome = BlockManager.manager.getBiome(plot.world, bot.getX() + ((top.getX() - bot.getX()) / 2), bot.getZ() + ((top.getZ() - bot.getZ()) / 2));
final String trusted = getPlayerList(plot.getTrusted());
final String members = getPlayerList(plot.getMembers());
final String denied = getPlayerList(plot.getDenied());
Flag descriptionFlag = FlagManager.getPlotFlag(plot, "description");
final String description = descriptionFlag == null ? C.NONE.s() : descriptionFlag.getValueString();
final String flags = StringMan.replaceFromMap("$2" + (StringMan.join(FlagManager.getPlotFlags(plot.world, plot.getSettings(), true).values(), "").length() > 0 ? StringMan.join(FlagManager.getPlotFlags(plot.world, plot.getSettings(), true).values(), "$1, $2") : C.NONE.s()), C.replacements);
final boolean build = plot.isAdded(player.getUUID());
String owner = plot.owner == null ? "unowned" : getPlayerList(plot.getOwners());
info = info.replaceAll("%alias%", alias);
info = info.replaceAll("%id%", id.toString());
info = info.replaceAll("%id2%", id2.toString());
info = info.replaceAll("%num%", num + "");
info = info.replaceAll("%desc%", description);
info = info.replaceAll("%biome%", biome);
info = info.replaceAll("%owner%", owner);
info = info.replaceAll("%members%", members);
info = info.replaceAll("%trusted%", trusted);
info = info.replaceAll("%helpers%", members);
info = info.replaceAll("%denied%", denied);
info = info.replaceAll("%flags%", Matcher.quoteReplacement(flags));
info = info.replaceAll("%build%", build + "");
info = info.replaceAll("%desc%", "No description set.");
if (info.contains("%rating%")) {
final String newInfo = info;
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
int max = 10;
if (Settings.RATING_CATEGORIES != null && Settings.RATING_CATEGORIES.size() > 0) {
max = 8;
}
String info;
if (full && Settings.RATING_CATEGORIES != null && Settings.RATING_CATEGORIES.size() > 1) {
String rating = "";
String prefix = "";
double[] ratings = MainUtil.getAverageRatings(plot);
for (int i = 0; i < ratings.length; i++) {
rating += prefix + Settings.RATING_CATEGORIES.get(i) + "=" + String.format("%.1f", ratings[i]);
prefix = ",";
}
info = newInfo.replaceAll("%rating%", rating);
}
else {
info = newInfo.replaceAll("%rating%", String.format("%.1f", MainUtil.getAverageRating(plot)) + "/" + max);
}
MainUtil.sendMessage(player, C.PLOT_INFO_HEADER);
MainUtil.sendMessage(player, info, false);
MainUtil.sendMessage(player, C.PLOT_INFO_FOOTER);
}
});
return;
}
MainUtil.sendMessage(player, C.PLOT_INFO_HEADER);
MainUtil.sendMessage(player, info, false);
}
}

View File

@ -24,31 +24,23 @@ import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.BlockManager;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.util.WorldUtil;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(
command = "kick",
aliases = {"k"},
description = "Kick a player from your plot",
permission = "plots.kick",
category = CommandCategory.ACTIONS,
requiredType = RequiredType.NONE
)
@CommandDeclaration(command = "kick", aliases = { "k" }, description = "Kick a player from your plot", permission = "plots.kick", category = CommandCategory.TELEPORT, requiredType = RequiredType.NONE)
public class Kick extends SubCommand {
@Override
public boolean onCommand(final PlotPlayer plr, final String[] args) {
final Location loc = plr.getLocation();
final Plot plot = MainUtil.getPlot(loc);
final Plot plot = loc.getPlot();
if (plot == null) {
return !sendMessage(plr, C.NOT_IN_PLOT);
}
if (plot == null || ((!plot.hasOwner() || !plot.isOwner(plr.getUUID())) && !Permissions.hasPermission(plr, "plots.admin.command.kick"))) {
if (((!plot.hasOwner() || !plot.isOwner(plr.getUUID())) && !Permissions.hasPermission(plr, "plots.admin.command.kick"))) {
MainUtil.sendMessage(plr, C.NO_PLOT_PERMS);
return false;
}
@ -61,12 +53,16 @@ public class Kick extends SubCommand {
MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[0]);
return false;
}
Location otherLoc = player.getLocation();
if (!plr.getLocation().getWorld().equals(otherLoc.getWorld()) || !plot.equals(MainUtil.getPlot(otherLoc))) {
final Location otherLoc = player.getLocation();
if (!plr.getLocation().getWorld().equals(otherLoc.getWorld()) || !plot.equals(otherLoc.getPlot())) {
MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[0]);
return false;
}
player.teleport(BlockManager.manager.getSpawn(loc.getWorld()));
if (player.hasPermission("plots.admin.entry.denied")) {
C.CANNOT_KICK_PLAYER.send(plr, player.getName());
return false;
}
player.teleport(WorldUtil.IMP.getSpawn(loc.getWorld()));
return true;
}
}

View File

@ -1,9 +1,5 @@
package com.intellectualcrafters.plot.commands;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
@ -18,15 +14,18 @@ import com.intellectualcrafters.plot.util.SchematicHandler.Schematic;
import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.general.commands.CommandDeclaration;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
@CommandDeclaration(
command = "load",
aliases = { "restore" },
category = CommandCategory.ACTIONS,
category = CommandCategory.SCHEMATIC,
requiredType = RequiredType.NONE,
description = "Load your plot",
permission = "plots.load",
usage = "/plot restore"
)
usage = "/plot restore")
public class Load extends SubCommand {
@Override
@ -37,10 +36,10 @@ public class Load extends SubCommand {
return false;
}
final String world = plr.getLocation().getWorld();
if (!PS.get().isPlotWorld(world)) {
if (!PS.get().hasPlotArea(world)) {
return !sendMessage(plr, C.NOT_IN_PLOT_WORLD);
}
final Plot plot = MainUtil.getPlot(plr.getLocation());
final Plot plot = plr.getCurrentPlot();
if (plot == null) {
return !sendMessage(plr, C.NOT_IN_PLOT);
}
@ -52,15 +51,14 @@ public class Load extends SubCommand {
MainUtil.sendMessage(plr, C.NO_PLOT_PERMS);
return false;
}
if (MainUtil.runners.containsKey(plot)) {
if (plot.getRunning() > 0) {
MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER);
return false;
}
if (args.length != 0) {
if (args.length == 1) {
// TODO load save here
List<String> schematics = (List<String>) plr.getMeta("plot_schematics");
final List<String> schematics = (List<String>) plr.getMeta("plot_schematics");
if (schematics == null) {
// No schematics found:
MainUtil.sendMessage(plr, C.LOAD_NULL);
@ -69,8 +67,7 @@ public class Load extends SubCommand {
String schem;
try {
schem = schematics.get(Integer.parseInt(args[0]) - 1);
}
catch (Exception e) {
} catch (final Exception e) {
// use /plot load <index>
MainUtil.sendMessage(plr, C.NOT_VALID_NUMBER, "(1, " + schematics.size() + ")");
return false;
@ -78,31 +75,29 @@ public class Load extends SubCommand {
final URL url;
try {
url = new URL(Settings.WEB_URL + "saves/" + plr.getUUID() + "/" + schem + ".schematic");
} catch (MalformedURLException e) {
} catch (final MalformedURLException e) {
e.printStackTrace();
MainUtil.sendMessage(plr, C.LOAD_FAILED);
return false;
}
MainUtil.runners.put(plot, 1);
plot.addRunning();
MainUtil.sendMessage(plr, C.GENERATING_COMPONENT);
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
Schematic schematic = SchematicHandler.manager.getSchematic(url);
final Schematic schematic = SchematicHandler.manager.getSchematic(url);
if (schematic == null) {
MainUtil.runners.remove(plot);
plot.removeRunning();
sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent or not in gzip format");
return;
}
SchematicHandler.manager.paste(schematic, plot, 0, 0, new RunnableVal<Boolean>() {
@Override
public void run() {
MainUtil.runners.remove(plot);
if (this.value) {
public void run(Boolean value) {
plot.removeRunning();
if (value) {
sendMessage(plr, C.SCHEMATIC_PASTE_SUCCESS);
}
else {
} else {
sendMessage(plr, C.SCHEMATIC_PASTE_FAILED);
}
}
@ -111,22 +106,22 @@ public class Load extends SubCommand {
});
return true;
}
MainUtil.runners.remove(plot);
plot.removeRunning();
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot load <index>");
return false;
}
// list schematics
List<String> schematics = (List<String>) plr.getMeta("plot_schematics");
final List<String> schematics = (List<String>) plr.getMeta("plot_schematics");
if (schematics == null) {
MainUtil.runners.put(plot, 1);
plot.addRunning();
TaskManager.runTaskAsync(new Runnable() {
@Override
public void run() {
List<String> schematics = SchematicHandler.manager.getSaves(plr.getUUID());
MainUtil.runners.remove(plot);
if (schematics == null || schematics.size() == 0) {
final List<String> schematics = SchematicHandler.manager.getSaves(plr.getUUID());
plot.removeRunning();
if ((schematics == null) || (schematics.isEmpty())) {
MainUtil.sendMessage(plr, C.LOAD_FAILED);
return;
}
@ -134,37 +129,34 @@ public class Load extends SubCommand {
displaySaves(plr, 0);
}
});
}
else {
} else {
displaySaves(plr, 0);
}
return true;
}
public void displaySaves(PlotPlayer player, int page) {
List<String> schematics = (List<String>) player.getMeta("plot_schematics");
public void displaySaves(final PlotPlayer player, final int page) {
final List<String> schematics = (List<String>) player.getMeta("plot_schematics");
for (int i = 0; i < Math.min(schematics.size(), 32); i++) {
try {
String schem = schematics.get(i);
String[] split = schem.split("_");
final String schem = schematics.get(i);
final String[] split = schem.split("_");
if (split.length != 6) {
continue;
}
String time = secToTime((System.currentTimeMillis() / 1000) - (Long.parseLong(split[0])));
String world = split[1];
PlotId id = PlotId.fromString(split[2] + ";" + split[3]);
String size = split[4];
String server = split[5].replaceAll(".schematic", "");
final String time = secToTime((System.currentTimeMillis() / 1000) - (Long.parseLong(split[0])));
final String world = split[1];
final PlotId id = PlotId.fromString(split[2] + ";" + split[3]);
final String size = split[4];
final String server = split[5].replaceAll(".schematic", "");
String color;
if (PS.get().IMP.getServerName().replaceAll("[^A-Za-z0-9]", "").equals(server)) {
color = "$4";
}
else {
} else {
color = "$1";
}
MainUtil.sendMessage(player, "$3[$2" + (i + 1) + "$3] " + color + time + "$3 | " + color + world + ";" + id + "$3 | " + color + size + "x" + size);
}
catch (Exception e) {
} catch (final Exception e) {
e.printStackTrace();
}
}
@ -172,7 +164,7 @@ public class Load extends SubCommand {
}
public String secToTime(long time) {
StringBuilder toreturn = new StringBuilder();
final StringBuilder toreturn = new StringBuilder();
int years = 0;
int weeks = 0;
int days = 0;
@ -203,7 +195,7 @@ public class Load extends SubCommand {
time -= minutes * 60;
toreturn.append(minutes + "m ");
}
if (toreturn.equals("")||time>0){
if (toreturn.equals("") || (time > 0)) {
toreturn.append((time) + "s ");
}
return toreturn.toString().trim();

View File

@ -20,20 +20,13 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.object.ConsolePlayer;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.MathMan;
import com.intellectualcrafters.plot.util.Permissions;
@ -45,21 +38,22 @@ import com.plotsquared.general.commands.Command;
import com.plotsquared.general.commands.CommandHandlingOutput;
import com.plotsquared.general.commands.CommandManager;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
/**
* PlotSquared command class
*
* @author Citymonstret
*/
public class MainCommand extends CommandManager<PlotPlayer> {
private static MainCommand instance;
public static MainCommand getInstance() {
if (instance == null) {
instance = new MainCommand();
}
return instance;
}
private HashMap<String, Command<PlotPlayer>> setCommands;
private MainCommand() {
super(null, new ArrayList<Command<PlotPlayer>>());
@ -67,30 +61,26 @@ public class MainCommand extends CommandManager<PlotPlayer> {
createCommand(new Buy());
createCommand(new Save());
createCommand(new Load());
createCommand(new Unclaim());
createCommand(new Confirm());
createCommand(new Template());
createCommand(new Download());
createCommand(new Update());
createCommand(new Template());
createCommand(new Setup());
createCommand(new DebugFill());
createCommand(new Area());
createCommand(new DebugSaveTest());
createCommand(new DebugLoadTest());
createCommand(new CreateRoadSchematic());
createCommand(new DebugAllowUnsafe());
createCommand(new RegenAllRoads());
createCommand(new DebugClear());
createCommand(new Claim());
createCommand(new Auto());
createCommand(new Home());
createCommand(new Visit());
createCommand(new TP());
createCommand(new Home());
createCommand(new Set());
createCommand(new Toggle());
createCommand(new Clear());
createCommand(new Delete());
createCommand(new SetOwner());
createCommand(new Trust());
createCommand(new Add());
createCommand(new Deny());
@ -131,23 +121,38 @@ public class MainCommand extends CommandManager<PlotPlayer> {
createCommand(new Done());
createCommand(new Continue());
createCommand(new BO3());
createCommand(new Middle());
createCommand(new Grant());
// set commands
createCommand(new Owner());
createCommand(new Desc());
createCommand(new Biome());
createCommand(new Alias());
createCommand(new SetHome());
if (Settings.ENABLE_CLUSTERS) {
MainCommand.getInstance().addCommand(new Cluster());
}
}
public static MainCommand getInstance() {
if (instance == null) {
instance = new MainCommand();
}
return instance;
}
public static boolean no_permission(final PlotPlayer player, final String permission) {
MainUtil.sendMessage(player, C.NO_PERMISSION, permission);
return false;
}
public static List<Command<PlotPlayer>> getCommandAndAliases(final CommandCategory category, final PlotPlayer player) {
List<Command<PlotPlayer>> commands = new ArrayList<>();
for (Command<PlotPlayer> command : getInstance().getCommands()) {
if (category != null && !command.getCategory().equals(category)) {
final List<Command<PlotPlayer>> commands = new ArrayList<>();
for (final Command<PlotPlayer> command : getInstance().getCommands()) {
if ((category != null) && !command.getCategory().equals(category)) {
continue;
}
if (player != null && !Permissions.hasPermission(player, command.getPermission())) {
if ((player != null) && !Permissions.hasPermission(player, command.getPermission())) {
continue;
}
commands.add(command);
@ -156,12 +161,12 @@ public class MainCommand extends CommandManager<PlotPlayer> {
}
public static List<Command<PlotPlayer>> getCommands(final CommandCategory category, final PlotPlayer player) {
List<Command<PlotPlayer>> commands = new ArrayList<>();
for (Command<PlotPlayer> command : new HashSet<>(getInstance().getCommands())) {
if (category != null && !command.getCategory().equals(category)) {
final List<Command<PlotPlayer>> commands = new ArrayList<>();
for (final Command<PlotPlayer> command : new HashSet<>(getInstance().getCommands())) {
if ((category != null) && !command.getCategory().equals(category)) {
continue;
}
if (player != null && !Permissions.hasPermission(player, command.getPermission())) {
if ((player != null) && !Permissions.hasPermission(player, command.getPermission())) {
continue;
}
commands.add(command);
@ -169,55 +174,13 @@ public class MainCommand extends CommandManager<PlotPlayer> {
return commands;
}
//// public static List<String> helpMenu(final PlotPlayer player, final CommandCategory category, int page) {
// List<Command<PlotPlayer>> commands;
// // commands = getCommands(category, player);
// // final int totalPages = ((int) Math.ceil(12 * (commands.size()) /
// // 100));
// final int perPage = 5;
// // final int totalPages = (commands.size() / perPage) + (commands.size() % perPage == 0 ? 0 : 1);
// // if (page > totalPages) {
// // page = totalPages;
// // }
// int max = (page * perPage) + perPage;
// // if (max > commands.size()) {
// // max = commands.size();
// // }
// final List<String> help = new ArrayList<>();
// help.add(C.HELP_HEADER.s());
// // HELP_PAGE_HEADER("&cCategory: &6%category%&c, Page: %current%&c/&6%max%&c, Displaying: &6%dis%&c/&6%total%"),
// // help.add(C.HELP_PAGE_HEADER.s().replace("%category%", category == null ? "All" : category.toString()).replace("%current%", "" + (page + 1)).replace("%max%", "" + (totalPages)).replace("%dis%", "" + perPage).replace("%total%", "" + commands.size()));
// Command cmd;
// // HELP_CATEGORY("&cCategory: &6%category%&c, Page: %current%&c/&6%max%&c, Displaying: &6%dis%&c/&6%total%"),
// // help.add(C.HELP_CATEGORY.s().replace("%category%", category == null ? "All" : category.toString()).replace("%current%", "" + (page + 1)).replace("%max%", "" + (totalPages)).replace("%dis%", "" + perPage).replace("%total%", "" + commands.size()));
// // Command<PlotPlayer> cmd;
// final int start = page * perPage;
// for (int x = start; x < max; x++) {
// // cmd = commands.get(x);
// String s = C.HELP_ITEM.s();
// if (cmd.getAliases().size() > 0) {
// s = s.replace("%alias%", StringMan.join(cmd.getAliases(), "|"));
// }
// else {
// s = s.replace("%alias%", "");
// }
// s = s.replace("%usage%", cmd.getUsage().contains("plot") ? cmd.getUsage() : "/plot " + cmd.getUsage()).replace("%cmd%", cmd.getCommand()).replace("%desc%", cmd.getDescription()).replace("[]", "");
// help.add(s);
// }
// if (help.size() < 2) {
// help.add(C.NO_COMMANDS.s());
// }
// return help;
// }
//
public static void displayHelp(PlotPlayer player, String cat, int page, String label) {
public static void displayHelp(final PlotPlayer player, String cat, int page, final String label) {
CommandCategory catEnum = null;
if (cat != null) {
if (StringMan.isEqualIgnoreCase(cat, "all")) {
catEnum = null;
}
else {
for (CommandCategory c : CommandCategory.values()) {
} else {
for (final CommandCategory c : CommandCategory.values()) {
if (StringMan.isEqualIgnoreCaseToAny(cat, c.name(), c.toString())) {
catEnum = c;
cat = c.name();
@ -229,7 +192,7 @@ public class MainCommand extends CommandManager<PlotPlayer> {
}
}
}
if (cat == null && page == 0) {
if ((cat == null) && (page == 0)) {
final StringBuilder builder = new StringBuilder();
builder.append(C.HELP_HEADER.s());
for (final CommandCategory c : CommandCategory.values()) {
@ -241,33 +204,39 @@ public class MainCommand extends CommandManager<PlotPlayer> {
return;
}
page--;
new HelpMenu(player)
.setCategory(catEnum)
.getCommands()
.generateMaxPages()
.generatePage(page, label)
.render();
new HelpMenu(player).setCategory(catEnum).getCommands().generateMaxPages().generatePage(page, label).render();
}
public static boolean onCommand(final PlotPlayer player, final String cmd, String... args) {
// Clear perm caching //
player.deleteMeta("perm");
////////////////////////
int help_index = -1;
String category = null;
if (args.length == 0) {
help_index = 0;
}
else if (StringMan.isEqualIgnoreCaseToAny(args[0], "he", "help", "?")) {
help_index = 0;
Location loc = null;
Plot plot = null;
boolean tp = false;
switch (args.length) {
case 3: {
category = args[1];
if (MathMan.isInteger(args[2])) {
case 0: {
help_index = 0;
break;
}
case 1: {
if (MathMan.isInteger(args[0])) {
try {
help_index = Integer.parseInt(args[2]);
}
catch (NumberFormatException e) {
help_index = 1;
help_index = Integer.parseInt(args[args.length - 1]);
} catch (final NumberFormatException e) {}
break;
}
}
default: {
switch (args[0].toLowerCase()) {
case "he":
case "help":
case "?": {
switch (args.length) {
case 1: {
help_index = 0;
break;
}
case 2: {
@ -275,7 +244,7 @@ public class MainCommand extends CommandManager<PlotPlayer> {
category = null;
try {
help_index = Integer.parseInt(args[1]);
} catch(NumberFormatException e) {
} catch (final NumberFormatException e) {
help_index = 1;
}
} else {
@ -284,58 +253,115 @@ public class MainCommand extends CommandManager<PlotPlayer> {
}
break;
}
}
}
else if (args.length == 1 && MathMan.isInteger(args[args.length - 1])) {
case 3: {
category = args[1];
if (MathMan.isInteger(args[2])) {
try {
help_index = Integer.parseInt(args[args.length - 1]);
help_index = Integer.parseInt(args[2]);
} catch (final NumberFormatException e) {
help_index = 1;
}
catch (NumberFormatException e) {}
}
else if (ConsolePlayer.isConsole(player) && args.length >= 2) {
String[] split = args[0].split(";");
String world;
PlotId id;
if (split.length == 2) {
world = player.getLocation().getWorld();
id = PlotId.fromString(split[0] + ";" + split[1]);
break;
}
else if (split.length == 3) {
world = split[0];
id = PlotId.fromString(split[1] + ";" + split[2]);
default: {
C.COMMAND_SYNTAX.send(player, "/" + cmd + "? [#|<term>|category [#]]");
return true;
}
else {
id = null;
world = null;
}
if (id != null && PS.get().isPlotWorld(world)) {
Plot plot = MainUtil.getPlot(world, id);
if (plot != null) {
player.teleport(MainUtil.getPlotCenter(plot));
break;
}
default: {
if (args.length >= 2) {
PlotArea area = player.getApplicablePlotArea();
Plot newPlot = Plot.fromString(area, args[0]);
if (newPlot == null) {
break;
}
if (!ConsolePlayer.isConsole(player) && (!newPlot.getArea().equals(area) || newPlot.isDenied(player.getUUID())) && !Permissions.hasPermission(player, C.PERMISSION_ADMIN)) {
break;
}
// Save meta
loc = (Location) player.getMeta("location");
plot = (Plot) player.getMeta("lastplot");
tp = true;
// Set loc
player.setMeta("location", newPlot.getBottomAbs());
player.setMeta("lastplot", newPlot);
// Trim command
args = Arrays.copyOfRange(args, 1, args.length);
}
}
}
}
}
if (help_index != -1) {
displayHelp(player, category, help_index, cmd);
return true;
}
StringBuilder builder = new StringBuilder(cmd).append(" ");
Iterator<String> iterator = Arrays.asList(args).iterator();
while (iterator.hasNext()) {
builder.append(iterator.next());
if (iterator.hasNext()) {
builder.append(" ");
if (args[0].contains(":")) {
args[0] = args[0].replaceFirst(":", " ");
}
String fullCmd = StringMan.join(args, " ");
getInstance().handle(player, cmd + " " + fullCmd);
// Restore location
if (tp) {
if (loc == null) {
player.deleteMeta("location");
} else {
player.setMeta("location", loc);
}
if (plot == null) {
player.deleteMeta("lastplot");
} else {
player.setMeta("lastplot", plot);
}
}
getInstance().handle(player, builder.toString());
return true;
}
public int getMatch(String[] args, Command<PlotPlayer> cmd) {
int count = 0;
String perm = cmd.getPermission();
HashSet<String> desc = new HashSet<String>();
for (String alias : cmd.getAliases()) {
if (alias.startsWith(args[0])) {
count += 5;
}
}
Collections.addAll(desc, cmd.getDescription().split(" "));
for (String arg : args) {
if (perm.startsWith(arg)) {
count++;
}
if (desc.contains(arg)) {
count++;
}
}
String[] usage = cmd.getUsage().split(" ");
for (int i = 0; i < Math.min(4 , usage.length); i++) {
int require;
if (usage[i].startsWith("<")) {
require = 1;
} else {
require = 0;
}
String[] split = usage[i].split("\\|| |\\>|\\<|\\[|\\]|\\{|\\}|\\_|\\/");
for (String aSplit : split) {
for (String arg : args) {
if (StringMan.isEqualIgnoreCase(arg, aSplit)) {
count += 5 - i + require;
}
}
}
}
count += StringMan.intersection(desc, args);
return count;
}
@Override
public int handle(PlotPlayer plr, String input) {
String[] parts = input.split(" ");
public int handle(final PlotPlayer plr, final String input) {
final String[] parts = input.split(" ");
String[] args;
String label;
if (parts.length == 1) {
@ -348,63 +374,43 @@ public class MainCommand extends CommandManager<PlotPlayer> {
}
Command<PlotPlayer> cmd;
if (label != null) {
cmd = getInstance().commands.get(label);
if (label.contains(":")) {
// Ref: c:v, this will push value to the last spot in the array
// ex. /p h:2 SomeUsername
// > /p h SomeUsername 2
String[] temp = label.split(":");
label = temp[0];
String[] tempArgs = new String[args.length + 1];
System.arraycopy(args, 0, tempArgs, 0, args.length);
tempArgs[tempArgs.length - 1] = temp[1];
args = tempArgs;
}
else {
cmd = getInstance().commands.get(label.toLowerCase());
} else {
cmd = null;
}
if (cmd == null) {
MainUtil.sendMessage(plr, C.NOT_VALID_SUBCOMMAND);
{
List<Command<PlotPlayer>> cmds = getCommands(null, plr);
if (label == null || cmds.size() == 0) {
final List<Command<PlotPlayer>> cmds = getCommands(null, plr);
if ((label == null) || (cmds.isEmpty())) {
MainUtil.sendMessage(plr, C.DID_YOU_MEAN, "/plot help");
}
else {
HashSet<String> setargs = new HashSet<>(args.length + 1);
for (String arg : args) {
} else {
final HashSet<String> setargs = new HashSet<>(args.length + 1);
for (final String arg : args) {
setargs.add(arg.toLowerCase());
}
setargs.add(label.toLowerCase());
String[] allargs = setargs.toArray(new String[setargs.size()]);
setargs.add(label);
final String[] allargs = setargs.toArray(new String[setargs.size()]);
int best = 0;
for (Command<PlotPlayer> current : cmds) {
if (current.getUsage() != null) {
int count = 0;
for (String word : new HashSet<String>(Arrays.asList((current.getUsage() + " " + current.getPermission() + " " + current.getCategory().name()).toLowerCase().replaceAll("\\||\\>|\\<|\\[|\\]|\\{|\\}|\\_|\\/", " ").trim().replaceAll("\\s+", " ").split(" ")))) {
for (int i = 0; i < allargs.length; i++) {
String arg = allargs[i];
if (best - count - (allargs.length - i) * 3 >= 0) {
continue;
}
if (StringMan.isEqual(arg, word)) {
count+=3;
}
else if (word.length() > arg.length() && word.contains(arg)) {
count+=2;
}
}
}
for (String word : new HashSet<String>(Arrays.asList((current.getDescription()).toLowerCase().replaceAll("\\||\\>|\\<|\\[|\\]|\\{|\\}|\\_|\\/", " ").trim().replaceAll("\\s+", " ").split(" ")))) {
for (int i = 0; i < allargs.length; i++) {
String arg = allargs[i];
if (best - count - (allargs.length - i) * 2 >= 0) {
continue;
}
if (StringMan.isEqual(arg, word)) {
count+=2;
}
else if (word.length() > arg.length() && word.contains(arg)) {
count++;
}
}
}
if (count > best) {
best = count;
for (final Command<PlotPlayer> current : cmds) {
int match = getMatch(allargs, current);
if (match > best) {
cmd = current;
}
}
}
if (cmd == null) {
cmd = new StringComparison<>(label, getCommandAndAliases(null, plr)).getMatchObject();
}
@ -425,8 +431,8 @@ public class MainCommand extends CommandManager<PlotPlayer> {
MainUtil.sendMessage(plr, C.NO_PERMISSION, cmd.getPermission());
return CommandHandlingOutput.NOT_PERMITTED;
}
Argument<?>[] requiredArguments = cmd.getRequiredArguments();
if (requiredArguments != null && requiredArguments.length > 0) {
final Argument<?>[] requiredArguments = cmd.getRequiredArguments();
if ((requiredArguments != null) && (requiredArguments.length > 0)) {
boolean success = true;
if (args.length < requiredArguments.length) {
success = false;
@ -444,9 +450,9 @@ public class MainCommand extends CommandManager<PlotPlayer> {
}
}
try {
boolean result = cmd.onCommand(plr, args);
final boolean result = cmd.onCommand(plr, args);
if (!result) {
String usage = cmd.getUsage();
cmd.getUsage();
// Unecessary!
// if (usage != null && !usage.isEmpty()) {
// MainUtil.sendMessage(plr, usage);

View File

@ -20,38 +20,29 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.UUID;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.PlotWorld;
import com.intellectualcrafters.plot.util.CmdConfirm;
import com.intellectualcrafters.plot.util.EconHandler;
import com.intellectualcrafters.plot.util.EventUtil;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(
command = "merge",
aliases = {"m"},
description = "Merge the plot you are standing on, with another plot",
permission = "plots.merge",
usage = "/plot merge [direction]",
category = CommandCategory.ACTIONS,
requiredType = RequiredType.NONE
)
import java.util.HashSet;
import java.util.UUID;
@CommandDeclaration(command = "merge", aliases = "m", description = "Merge the plot you are standing on, with another plot",
permission = "plots.merge", usage = "/plot merge <all|n|e|s|w> [removeroads]", category = CommandCategory.SETTINGS,
requiredType = RequiredType.NONE)
public class Merge extends SubCommand {
public final static String[] values = new String[] { "north", "east", "south", "west" };
public final static String[] aliases = new String[] { "n", "e", "s", "w" };
public final static String[] values = new String[] { "north", "east", "south", "west", "auto" };
public final static String[] aliases = new String[] { "n", "e", "s", "w", "all" };
public static String direction(float yaw) {
yaw = yaw / 90;
@ -77,39 +68,71 @@ public class Merge extends SubCommand {
@Override
public boolean onCommand(final PlotPlayer plr, final String[] args) {
final Location loc = plr.getLocationFull();
final Plot plot = MainUtil.getPlot(loc);
final Plot plot = loc.getPlotAbs();
if (plot == null) {
return !sendMessage(plr, C.NOT_IN_PLOT);
}
if ((plot == null) || !plot.hasOwner()) {
if (!plot.hasOwner()) {
MainUtil.sendMessage(plr, C.PLOT_UNOWNED);
return false;
}
final boolean admin = Permissions.hasPermission(plr, "plots.admin.command.merge");
if (!plot.isOwner(plr.getUUID()) && !admin) {
UUID uuid = plr.getUUID();
if (!plot.isOwner(uuid)) {
if (!Permissions.hasPermission(plr, "plots.admin.command.merge")) {
MainUtil.sendMessage(plr, C.NO_PLOT_PERMS);
return false;
}
else {
uuid = plot.owner;
}
}
final PlotArea plotworld = plot.getArea();
if (EconHandler.manager != null && plotworld.USE_ECONOMY && plotworld.MERGE_PRICE > 0d
&& EconHandler.manager.getMoney(plr) < plotworld.MERGE_PRICE) {
sendMessage(plr, C.CANNOT_AFFORD_MERGE, plotworld.MERGE_PRICE + "");
return false;
}
final int size = plot.getConnectedPlots().size();
final int maxSize = Permissions.hasPermissionRange(plr, "plots.merge", Settings.MAX_PLOTS);
if (size - 1> maxSize) {
MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.merge." + (size + 1));
return false;
}
int direction = -1;
if (args.length == 0) {
switch (direction(plr.getLocationFull().getYaw())) {
case "NORTH":
direction = 0;
break;
case "EAST":
direction = 1;
break;
case "SOUTH":
direction = 2;
break;
case "WEST":
direction = 3;
break;
// switch (direction(plr.getLocationFull().getYaw())) {
// case "NORTH":
// direction = 0;
// break;
// case "EAST":
// direction = 1;
// break;
// case "SOUTH":
// direction = 2;
// break;
// case "WEST":
// direction = 3;
// break;
// }
} else {
if ("all".equalsIgnoreCase(args[0]) || "auto".equalsIgnoreCase(args[0])) {
boolean terrain = Settings.MERGE_REMOVES_ROADS;
if (args.length == 2) {
terrain = "true".equalsIgnoreCase(args[1]);
}
if (plot.autoMerge(-1, maxSize, uuid, terrain)) {
if (EconHandler.manager != null && plotworld.USE_ECONOMY && plotworld.MERGE_PRICE > 0d) {
EconHandler.manager.withdrawMoney(plr, plotworld.MERGE_PRICE);
sendMessage(plr, C.REMOVED_BALANCE, plotworld.MERGE_PRICE + "");
}
MainUtil.sendMessage(plr, C.SUCCESS_MERGE);
return true;
}
MainUtil.sendMessage(plr, C.NO_AVAILABLE_AUTOMERGE);
return false;
}
else {
for (int i = 0; i < values.length; i++) {
if (args[0].equalsIgnoreCase(values[i]) || args[0].equalsIgnoreCase(aliases[i])) {
direction = i;
@ -118,130 +141,69 @@ public class Merge extends SubCommand {
}
}
if (direction == -1) {
MainUtil.sendMessage(plr, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + StringMan.join(values, C.BLOCK_LIST_SEPARATER.s()));
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot merge <" + StringMan.join(values, "|") + "> [removeroads]");
MainUtil.sendMessage(plr, C.DIRECTION.s().replaceAll("%dir%", direction(loc.getYaw())));
return false;
}
PlotId bot = MainUtil.getBottomPlot(plot).id;
PlotId top = MainUtil.getTopPlot(plot).id;
ArrayList<PlotId> selPlots;
final String world = loc.getWorld();
switch (direction) {
case 0: // north = -y
selPlots = MainUtil.getMaxPlotSelectionIds(world, new PlotId(bot.x, bot.y - 1), new PlotId(top.x, top.y));
break;
case 1: // east = +x
selPlots = MainUtil.getMaxPlotSelectionIds(world, new PlotId(bot.x, bot.y), new PlotId(top.x + 1, top.y));
break;
case 2: // south = +y
selPlots = MainUtil.getMaxPlotSelectionIds(world, new PlotId(bot.x, bot.y), new PlotId(top.x, top.y + 1));
break;
case 3: // west = -x
selPlots = MainUtil.getMaxPlotSelectionIds(world, new PlotId(bot.x - 1, bot.y), new PlotId(top.x, top.y));
break;
default:
final boolean terrain;
if (args.length == 2) {
terrain = "true".equalsIgnoreCase(args[1]);
} else {
terrain = Settings.MERGE_REMOVES_ROADS;
}
if (plot.autoMerge(direction, maxSize - size, uuid, terrain)) {
if (EconHandler.manager != null && plotworld.USE_ECONOMY && plotworld.MERGE_PRICE > 0d) {
EconHandler.manager.withdrawMoney(plr, plotworld.MERGE_PRICE);
sendMessage(plr, C.REMOVED_BALANCE, plotworld.MERGE_PRICE + "");
}
MainUtil.sendMessage(plr, C.SUCCESS_MERGE);
return true;
}
Plot adjacent = plot.getRelative(direction);
if (adjacent == null || !adjacent.hasOwner() || adjacent.getMerged((direction + 2) % 4) || adjacent.isOwner(uuid)) {
MainUtil.sendMessage(plr, C.NO_AVAILABLE_AUTOMERGE);
return false;
}
final PlotId botId = selPlots.get(0);
final PlotId topId = selPlots.get(selPlots.size() - 1);
final PlotId bot1 = MainUtil.getBottomPlot(MainUtil.getPlot(world, botId)).id;
final PlotId bot2 = MainUtil.getBottomPlot(MainUtil.getPlot(world, topId)).id;
final PlotId top1 = MainUtil.getTopPlot(MainUtil.getPlot(world, topId)).id;
final PlotId top2 = MainUtil.getTopPlot(MainUtil.getPlot(world, botId)).id;
bot = new PlotId(Math.min(bot1.x, bot2.x), Math.min(bot1.y, bot2.y));
top = new PlotId(Math.max(top1.x, top2.x), Math.max(top1.y, top2.y));
final ArrayList<PlotId> plots = MainUtil.getMaxPlotSelectionIds(world, bot, top);
boolean multiMerge = false;
final HashSet<UUID> multiUUID = new HashSet<UUID>();
HashSet<PlotId> multiPlots = new HashSet<>();
final UUID u1 = plot.owner;
for (final PlotId myid : plots) {
final Plot myplot = PS.get().getPlot(world, myid);
if (myplot == null || myplot.owner == null) {
MainUtil.sendMessage(plr, C.NO_PERM_MERGE.s().replaceAll("%plot%", myid.toString()));
return false;
}
UUID u2 = myplot.owner;
if (u2.equals(u1)) {
continue;
}
PlotPlayer p2 = UUIDHandler.getPlayer(u2);
if (p2 == null) {
MainUtil.sendMessage(plr, C.NO_PERM_MERGE.s().replaceAll("%plot%", myid.toString()));
return false;
}
multiMerge = true;
multiPlots.add(myid);
multiUUID.add(u2);
}
if (multiMerge) {
if (!Permissions.hasPermission(plr, C.PERMISSION_MERGE_OTHER)) {
MainUtil.sendMessage(plr, C.NO_PERMISSION, C.PERMISSION_MERGE_OTHER.s());
return false;
}
for (final UUID uuid : multiUUID) {
PlotPlayer accepter = UUIDHandler.getPlayer(uuid);
HashSet<UUID> uuids = adjacent.getOwners();
boolean isOnline = false;
for (final UUID owner : uuids) {
final PlotPlayer accepter = UUIDHandler.getPlayer(owner);
if (accepter == null) {
continue;
}
isOnline = true;
final int dir = direction;
CmdConfirm.addPending(accepter, C.MERGE_REQUEST_CONFIRM.s().replaceAll("%s", plr.getName()), new Runnable() {
@Override
public void run() {
PlotPlayer accepter = UUIDHandler.getPlayer(uuid);
multiUUID.remove(uuid);
if (multiUUID.size() == 0) {
PlotPlayer pp = UUIDHandler.getPlayer(u1);
MainUtil.sendMessage(accepter, C.MERGE_ACCEPTED);
plot.autoMerge(dir, maxSize - size, owner, terrain);
final PlotPlayer pp = UUIDHandler.getPlayer(plr.getUUID());
if (pp == null) {
sendMessage(accepter, C.MERGE_NOT_VALID);
return;
}
final PlotWorld plotWorld = PS.get().getPlotWorld(world);
if ((EconHandler.manager != null) && plotWorld.USE_ECONOMY) {
double cost = plotWorld.MERGE_PRICE;
cost = plots.size() * cost;
if (cost > 0d) {
if (EconHandler.manager.getMoney(plr) < cost) {
sendMessage(plr, C.CANNOT_AFFORD_MERGE, cost + "");
if (EconHandler.manager != null && plotworld.USE_ECONOMY && plotworld.MERGE_PRICE > 0d) {
if (EconHandler.manager.getMoney(plr) < plotworld.MERGE_PRICE) {
sendMessage(plr, C.CANNOT_AFFORD_MERGE, plotworld.MERGE_PRICE + "");
return;
}
EconHandler.manager.withdrawMoney(plr, cost);
sendMessage(plr, C.REMOVED_BALANCE, cost + "");
}
}
final boolean result = EventUtil.manager.callMerge(world, plot, plots);
if (!result) {
MainUtil.sendMessage(plr, "&cMerge has been cancelled");
return;
EconHandler.manager.withdrawMoney(plr, plotworld.MERGE_PRICE);
sendMessage(plr, C.REMOVED_BALANCE, plotworld.MERGE_PRICE + "");
}
MainUtil.sendMessage(plr, C.SUCCESS_MERGE);
MainUtil.mergePlots(world, plots, true, true);
MainUtil.setSign(UUIDHandler.getName(plot.owner), plot);
}
MainUtil.sendMessage(accepter, C.MERGE_ACCEPTED);
}
});
}
if (!isOnline) {
MainUtil.sendMessage(plr, C.NO_AVAILABLE_AUTOMERGE);
return false;
}
MainUtil.sendMessage(plr, C.MERGE_REQUESTED);
return true;
}
final PlotWorld plotWorld = PS.get().getPlotWorld(world);
if ((EconHandler.manager != null) && plotWorld.USE_ECONOMY) {
double cost = plotWorld.MERGE_PRICE;
cost = plots.size() * cost;
if (cost > 0d) {
if (EconHandler.manager.getMoney(plr) < cost) {
sendMessage(plr, C.CANNOT_AFFORD_MERGE, cost + "");
return false;
}
EconHandler.manager.withdrawMoney(plr, cost);
sendMessage(plr, C.REMOVED_BALANCE, cost + "");
}
}
final boolean result = EventUtil.manager.callMerge(world, plot, plots);
if (!result) {
MainUtil.sendMessage(plr, "&cMerge has been cancelled");
return false;
}
MainUtil.sendMessage(plr, C.SUCCESS_MERGE);
MainUtil.mergePlots(world, plots, true, true);
MainUtil.setSign(UUIDHandler.getName(plot.owner), plot);
return true;
}
}

View File

@ -0,0 +1,40 @@
package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.plotsquared.general.commands.CommandDeclaration;
/**
* Legally stolen from https://github.com/manuelgu/PlotSquaredMiddle
*
* @author manuelgu, altered by Citymonstret
*/
@CommandDeclaration(
command = "middle",
aliases = { "center" },
description = "Teleports you to the center of the current plot",
usage = "/plot middle",
category = CommandCategory.TELEPORT,
requiredType = RequiredType.PLAYER
)
public class Middle extends SubCommand {
@Override
public boolean onCommand(PlotPlayer player, String[] arguments) {
final Location location = player.getLocation();
final Plot plot = location.getPlot();
if (plot == null) {
return sendMessage(player, C.NOT_IN_PLOT);
}
if (!plot.hasOwner()) {
return sendMessage(player, C.PLOT_UNOWNED);
}
if (!player.hasPermission("plots.middle")) {
return sendMessage(player, C.NO_PERMISSION, "plots.middle");
}
player.teleport(plot.getCenter());
return true;
}
}

View File

@ -20,83 +20,63 @@
////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.PlotWorld;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions;
import com.plotsquared.general.commands.Argument;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(
usage = "/plot move <X;Z>",
command = "move",
description = "Move a plot",
aliases = { "debugmove" },
permission = "plots.move",
category = CommandCategory.ACTIONS,
requiredType = RequiredType.NONE
)
category = CommandCategory.CLAIMING,
requiredType = RequiredType.NONE)
public class Move extends SubCommand {
public Move() {
requiredArguments = new Argument[] {
Argument.PlotID
};
}
@Override
public boolean onCommand(final PlotPlayer plr, final String[] args) {
final Location loc = plr.getLocation();
final Plot plot1 = MainUtil.getPlot(loc);
final Plot plot1 = loc.getPlotAbs();
if (plot1 == null) {
return !sendMessage(plr, C.NOT_IN_PLOT);
return !MainUtil.sendMessage(plr, C.NOT_IN_PLOT);
}
if (!plot1.isAdded(plr.getUUID()) && !Permissions.hasPermission(plr, C.PERMISSION_ADMIN.s())) {
if (!plot1.isOwner(plr.getUUID()) && !Permissions.hasPermission(plr, C.PERMISSION_ADMIN.s())) {
MainUtil.sendMessage(plr, C.NO_PLOT_PERMS);
return false;
}
final String world = loc.getWorld();
final PlotId plot2id = MainUtil.parseId(args[0]);
if ((plot2id == null)) {
MainUtil.sendMessage(plr, C.NOT_VALID_PLOT_ID);
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot move <X;Z>");
if (args.length != 1) {
C.COMMAND_SYNTAX.send(plr, getUsage());
return false;
}
String world2;
if (args.length == 2) {
PlotWorld other = PS.get().getPlotWorld(args[1]);
PlotWorld current = PS.get().getPlotWorld(loc.getWorld());
if (other == null || current == null || !other.equals(current)) {
MainUtil.sendMessage(plr, C.PLOTWORLD_INCOMPATIBLE);
final Plot plot2 = MainUtil.getPlotFromString(plr, args[0], true);
if ((plot2 == null)) {
return false;
}
world2 = other.worldname;
}
else {
world2 = world;
}
Plot plot2 = MainUtil.getPlot(world2, plot2id);
if (plot1.equals(plot2)) {
MainUtil.sendMessage(plr, C.NOT_VALID_PLOT_ID);
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot move <X;Z>");
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot copy <X;Z>");
return false;
}
if (MainUtil.move(plot1, plot2, new Runnable() {
if (!plot1.getArea().isCompatible(plot2.getArea())) {
C.PLOTWORLD_INCOMPATIBLE.send(plr);
return false;
}
if (plot1.move(plot2, new Runnable() {
@Override
public void run() {
MainUtil.sendMessage(plr, C.MOVE_SUCCESS);
}
})) {
}, false)) {
return true;
} else {
MainUtil.sendMessage(plr, C.REQUIRES_UNOWNED);
return false;
}
}
}

View File

@ -29,8 +29,7 @@ import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.object.PlotInventory;
import com.intellectualcrafters.plot.object.PlotItemStack;
import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.BlockManager;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.WorldUtil;
import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration(
@ -38,15 +37,14 @@ import com.plotsquared.general.commands.CommandDeclaration;
permission = "plots.music",
description = "Player music in a plot",
usage = "/plot music",
category = CommandCategory.ACTIONS,
requiredType = RequiredType.NONE
)
category = CommandCategory.APPEARANCE,
requiredType = RequiredType.NONE)
public class MusicSubcommand extends SubCommand {
@Override
public boolean onCommand(final PlotPlayer player, final String[] args) {
final Location loc = player.getLocation();
final Plot plot = MainUtil.getPlot(loc);
final Plot plot = loc.getPlotAbs();
if (plot == null) {
return !sendMessage(player, C.NOT_IN_PLOT);
}
@ -54,17 +52,17 @@ public class MusicSubcommand extends SubCommand {
sendMessage(player, C.NO_PLOT_PERMS);
return true;
}
PlotInventory inv = new PlotInventory(player, 2, "Plot Jukebox") {
public boolean onClick(int index) {
PlotItemStack item = getItem(index);
final PlotInventory inv = new PlotInventory(player, 2, "Plot Jukebox") {
@Override
public boolean onClick(final int index) {
final PlotItemStack item = getItem(index);
if (item == null) {
return true;
}
int id = item.id == 7 ? 0 : item.id;
final int id = item.id == 7 ? 0 : item.id;
if (id == 0) {
FlagManager.removePlotFlag(plot, "music");
}
else {
} else {
FlagManager.addPlotFlag(plot, new Flag(FlagManager.getFlag("music"), id));
}
return false;
@ -72,15 +70,15 @@ public class MusicSubcommand extends SubCommand {
};
int index = 0;
for (int i = 2256; i < 2268; i++) {
String name = "&r&6" + BlockManager.manager.getClosestMatchingName(new PlotBlock((short) i, (byte) 0));
String[] lore = {"&r&aClick to play!"};
PlotItemStack item = new PlotItemStack(i, (byte) 0, 1, name, lore);
final String name = "&r&6" + WorldUtil.IMP.getClosestMatchingName(new PlotBlock((short) i, (byte) 0));
final String[] lore = { "&r&aClick to play!" };
final PlotItemStack item = new PlotItemStack(i, (byte) 0, 1, name, lore);
inv.setItem(index, item);
index++;
}
if (player.getMeta("music") != null) {
String name = "&r&6Cancel music";
String[] lore = {"&r&cClick to cancel!"};
final String name = "&r&6Cancel music";
final String[] lore = { "&r&cClick to cancel!" };
inv.setItem(index, new PlotItemStack(7, (short) 0, 1, name, lore));
}
inv.openInventory();

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