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 ### Others ###
*.sh
*.bat *.bat
*.cmd
*.sh
*.prefs
### Maven template ### Maven ###
target/ /target/lib
/target/maven-archiver
/target/classes
/target/maven-status
pom.xml.tag pom.xml.tag
pom.xml.releaseBackup pom.xml.releaseBackup
pom.xml.versionsBackup pom.xml.versionsBackup
@ -14,8 +19,23 @@ buildNumber.properties
.mvn/timing.properties .mvn/timing.properties
### JetBrains template ### Java ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion *.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 *.iml
@ -27,6 +47,7 @@ buildNumber.properties
# .idea/workspace.xml # .idea/workspace.xml
# .idea/tasks.xml # .idea/tasks.xml
# .idea/dictionaries # .idea/dictionaries
# .idea/shelf
# Sensitive or high-churn files: # Sensitive or high-churn files:
# .idea/dataSources.ids # .idea/dataSources.ids
@ -61,23 +82,12 @@ atlassian-ide-plugin.xml
com_crashlytics_export_strings.xml com_crashlytics_export_strings.xml
crashlytics.properties crashlytics.properties
crashlytics-build.properties crashlytics-build.properties
fabric.properties
### NetBeans template ### Eclipse ###
nbproject/private/
build/
nbbuild/
dist/
nbdist/
nbactions.xml
nb-configuration.xml
.nb-gradle/
### Eclipse template
*.pydevproject *.pydevproject
.metadata .metadata
.gradle
bin/ bin/
tmp/ tmp/
*.tmp *.tmp
@ -115,20 +125,6 @@ local.properties
# TeXlipse plugin # TeXlipse plugin
.texlipse .texlipse
# STS (Spring Tool Suite)
### Java template .springBeans
*.class /target/
# 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*

View File

@ -17,23 +17,23 @@ is to provide a lag-free and smooth experience.
### Developer Resources ### Developer Resources
* *Outdated* [JavaDocs](http://empcraft.com/plotsquared/doc/) * *Outdated* [JavaDocs](http://empcraft.com/plotsquared/doc/)
* [Build Server](http://ci.intellectualsites.com/job/PlotSquared/) * [Build Server](http://ci.xephi.fr/job/PlotSquared/)
* [Maven Repo](http://mvn.intellectualsites.com/content/repositories/intellectualsites/) * [Maven Repo](http://ci.xephi.fr/plugin/repository/everything/)
# Maven # Maven
We're now on maven! We're now on maven! (Unofficial Maven Repo)
```xml ```xml
<!-- Repository --> <!-- Repository -->
<repository> <repository>
<id>intellectualsites</id> <id>xephi-repo</id>
<url>http://mvn.intellectualsites.com/content/repositories/intellectualsites/</url> <url>http://ci.xephi.fr/plugin/repository/everything/</url>
</repository> </repository>
<!-- Dependency --> <!-- Dependency -->
<dependency> <dependency>
<groupId>com.intellectualcrafters</groupId> <groupId>com.intellectualcrafters</groupId>
<artifactId>PlotSquared</artifactId> <artifactId>plotsquared</artifactId>
<version>2.12.9</version> <version>3.2.27-SNAPSHOT</version>
</dependency> </dependency>
``` ```
@ -52,4 +52,4 @@ Feel free to contribute, if you feel like you can improve the plugin in any way.
* [BiomeGenerator](https://www.spigotmc.org/resources/biomegenerator.1663/) * [BiomeGenerator](https://www.spigotmc.org/resources/biomegenerator.1663/)
* [PlotSquaredMG](https://www.spigotmc.org/resources/plotsquaredmg.8025/) * [PlotSquaredMG](https://www.spigotmc.org/resources/plotsquaredmg.8025/)
* [BasicPlots](https://www.spigotmc.org/resources/basicplots.6901/) * [BasicPlots](https://www.spigotmc.org/resources/basicplots.6901/)
* [HoloPlots](https://www.spigotmc.org/resources/holoplots.4880/) * [HoloPlots](https://www.spigotmc.org/resources/holoplots.4880/)

267
pom.xml
View File

@ -1,58 +1,102 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
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"> 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> <modelVersion>4.0.0</modelVersion>
<groupId>com.intellectualcrafters</groupId> <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> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <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> </properties>
<artifactId>PlotSquared</artifactId>
<version>3.1.0</version>
<name>PlotSquared</name>
<packaging>jar</packaging>
<build> <build>
<finalName>PlotSquared-Uber</finalName> <finalName>${project.name}-Uber-${project.version}</finalName>
<sourceDirectory>src/main/java</sourceDirectory> <sourceDirectory>src/main/java</sourceDirectory>
<resources> <resources>
<resource> <resource>
<filtering>true</filtering> <filtering>true</filtering>
<excludes> <includes>
<exclude>skyblock.template</exclude> <include>plugin.yml</include>
<exclude>town.template</exclude> </includes>
</excludes>
<directory>${basedir}/src/main/resources/</directory> <directory>${basedir}/src/main/resources/</directory>
</resource> </resource>
<resource> <resource>
<filtering>false</filtering> <filtering>false</filtering>
<includes> <excludes>
<include>skyblock.template</include> <exclude>plugin.yml</exclude>
<include>town.template</include> </excludes>
<include>s_chinese.yml</include>
<include>s_chinese_unescaped.yml</include>
<include>german.yml</include>
<include>italian.yml</include>
</includes>
<directory>${basedir}/src/main/resources/</directory> <directory>${basedir}/src/main/resources/</directory>
</resource> </resource>
</resources> </resources>
<plugins> <plugins>
<!--
TODO: split the project into more modules
TODO: fix sponge compilation
-->
<!-- Invalid -->
<plugin> <plugin>
<artifactId>maven-jar-plugin</artifactId> <artifactId>maven-jar-plugin</artifactId>
<version>2.6</version>
<executions> <executions>
<execution> <execution>
<id>bukkit</id> <id>bukkit</id>
<goals> <goals>
<goal>jar</goal> <goal>jar</goal>
</goals> </goals>
<phase>package</phase> <phase>package</phase>
<configuration> <configuration>
<finalName>PlotSquared-Bukkit</finalName> <finalName>${project.name}-Bukkit-${project.version}</finalName>
<excludes> <excludes>
<exclude>**/com/plotsquared/sponge/**</exclude> <exclude>**/com/plotsquared/sponge/**</exclude>
</excludes> </excludes>
</configuration> </configuration>
</execution> </execution>
<execution> <execution>
<id>sponge</id> <id>sponge</id>
<goals> <goals>
@ -60,13 +104,14 @@
</goals> </goals>
<phase>package</phase> <phase>package</phase>
<configuration> <configuration>
<finalName>PlotSquared-Sponge</finalName> <finalName>${project.name}-Sponge-${project.version}</finalName>
<excludes> <excludes>
<exclude>**/com/plotsquared/bukkit/**</exclude> <exclude>**/com/plotsquared/bukkit/**</exclude>
<exclude>**/com/intellectualcrafters/plot/api/*</exclude> <exclude>**/com/intellectualcrafters/plot/api/*</exclude>
</excludes> </excludes>
</configuration> </configuration>
</execution> </execution>
<execution> <execution>
<id>api</id> <id>api</id>
<goals> <goals>
@ -74,7 +119,7 @@
</goals> </goals>
<phase>package</phase> <phase>package</phase>
<configuration> <configuration>
<finalName>PlotSquared-Null</finalName> <finalName>${project.name}-API-${project.version}</finalName>
<excludes> <excludes>
<exclude>**/com/plotsquared/bukkit/**</exclude> <exclude>**/com/plotsquared/bukkit/**</exclude>
<exclude>**/com/plotsquared/sponge/**</exclude> <exclude>**/com/plotsquared/sponge/**</exclude>
@ -84,14 +129,52 @@
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version> <version>3.3</version>
<configuration> <configuration>
<source>1.7</source> <source>1.7</source>
<target>1.7</target> <target>${javaVersion}</target>
</configuration> </configuration>
</plugin> </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> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId> <artifactId>maven-javadoc-plugin</artifactId>
@ -100,37 +183,21 @@
<additionalparam>-Xdoclint:none</additionalparam> <additionalparam>-Xdoclint:none</additionalparam>
</configuration> </configuration>
</plugin> </plugin>
-->
</plugins> </plugins>
</build> </build>
<repositories> <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> <repository>
<id>empcraft-repo</id> <id>empcraft-repo</id>
<url>http://empcraft.com/maven2</url> <url>http://empcraft.com/maven2</url>
</repository> </repository>
<repository> <repository>
<id>spigot-repo</id> <id>spigot-repo</id>
<url>http://hub.spigotmc.org/nexus/content/groups/public/</url> <url>https://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>
</repository> </repository>
<repository> <repository>
<id>sponge-maven-repo</id> <id>sponge-maven-repo</id>
<name>Sponge maven repo</name>
<url>http://repo.spongepowered.org/maven</url> <url>http://repo.spongepowered.org/maven</url>
<releases> <releases>
<enabled>true</enabled> <enabled>true</enabled>
@ -139,55 +206,125 @@
<enabled>true</enabled> <enabled>true</enabled>
</snapshots> </snapshots>
</repository> </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> </repositories>
<dependencies> <dependencies>
<!-- Bukkit API, http://www.spigotmc.org/ or http://bukkit.org/ -->
<dependency> <dependency>
<groupId>javax.websocket</groupId> <groupId>org.bukkit</groupId>
<artifactId>javax.websocket-api</artifactId> <artifactId>bukkit</artifactId>
<version>1.1</version> <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> </dependency>
<!-- Sponge API -->
<dependency> <dependency>
<groupId>org.spongepowered</groupId> <groupId>org.spongepowered</groupId>
<artifactId>spongeapi</artifactId> <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>
<dependency> <dependency>
<groupId>org.bukkit</groupId> <groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId> <artifactId>bukkit</artifactId>
<version>1.8.3-R0.1-SNAPSHOT</version> <version>1.8.8-R0.1-SNAPSHOT</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.sk89q</groupId> <groupId>com.sk89q</groupId>
<artifactId>worldedit</artifactId> <artifactId>worldedit</artifactId>
<version>6.0.0-SNAPSHOT</version> <version>6.0.0-SNAPSHOT</version>
<type>jar</type> <scope>provided</scope>
<scope>compile</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>
<dependency>
<groupId>me.confuser</groupId> <!-- <dependency>
<artifactId>BarAPI</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId> <artifactId>commons-math3</artifactId>
<version>3.2</version> <version>3.6</version>
</dependency> <scope>compile</scope>
<dependency> <optional>true</optional>
</dependency> -->
<!-- <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<version>4.11</version> <version>4.12</version>
<scope>test</scope>
<optional>true</optional>
</dependency> </dependency>
-->
<dependency> <dependency>
<groupId>net.milkbowl.vault</groupId> <groupId>net.milkbowl.vault</groupId>
<artifactId>VaultAPI</artifactId> <artifactId>VaultAPI</artifactId>
<version>1.5</version> <version>1.5</version>
<scope>provided</scope> <scope>provided</scope>
<optional>true</optional>
<exclusions>
<exclusion>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
</exclusion>
</exclusions>
</dependency> </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> <groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId> <artifactId>gson</artifactId>
<version>2.3.1</version> <version>2.5</version>
</dependency> <scope>compile</scope>
<optional>true</optional>
</dependency> -->
</dependencies> </dependencies>
</project> </project>

View File

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

View File

@ -8,11 +8,11 @@ public class ConfigurationOptions {
private char pathSeparator = '.'; private char pathSeparator = '.';
private boolean copyDefaults = false; private boolean copyDefaults = false;
private final Configuration configuration; private final Configuration configuration;
protected ConfigurationOptions(Configuration configuration) { protected ConfigurationOptions(final Configuration configuration) {
this.configuration = configuration; this.configuration = configuration;
} }
/** /**
* Returns the {@link Configuration} that this object is responsible for. * Returns the {@link Configuration} that this object is responsible for.
* *
@ -21,7 +21,7 @@ public class ConfigurationOptions {
public Configuration configuration() { public Configuration configuration() {
return configuration; return configuration;
} }
/** /**
* Gets the char that will be used to separate {@link * Gets the char that will be used to separate {@link
* ConfigurationSection}s * ConfigurationSection}s
@ -34,7 +34,7 @@ public class ConfigurationOptions {
public char pathSeparator() { public char pathSeparator() {
return pathSeparator; return pathSeparator;
} }
/** /**
* Sets the char that will be used to separate {@link * Sets the char that will be used to separate {@link
* ConfigurationSection}s * ConfigurationSection}s
@ -45,11 +45,11 @@ public class ConfigurationOptions {
* @param value Path separator * @param value Path separator
* @return This object, for chaining * @return This object, for chaining
*/ */
public ConfigurationOptions pathSeparator(char value) { public ConfigurationOptions pathSeparator(final char value) {
this.pathSeparator = value; pathSeparator = value;
return this; return this;
} }
/** /**
* Checks if the {@link Configuration} should copy values from its default * Checks if the {@link Configuration} should copy values from its default
* {@link Configuration} directly. * {@link Configuration} directly.
@ -67,7 +67,7 @@ public class ConfigurationOptions {
public boolean copyDefaults() { public boolean copyDefaults() {
return copyDefaults; return copyDefaults;
} }
/** /**
* Sets if the {@link Configuration} should copy values from its default * Sets if the {@link Configuration} should copy values from its default
* {@link Configuration} directly. * {@link Configuration} directly.
@ -83,8 +83,8 @@ public class ConfigurationOptions {
* @param value Whether or not defaults are directly copied * @param value Whether or not defaults are directly copied
* @return This object, for chaining * @return This object, for chaining
*/ */
public ConfigurationOptions copyDefaults(boolean value) { public ConfigurationOptions copyDefaults(final boolean value) {
this.copyDefaults = value; copyDefaults = value;
return this; return this;
} }
} }

View File

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

View File

@ -5,33 +5,33 @@ package com.intellectualcrafters.configuration;
*/ */
@SuppressWarnings("serial") @SuppressWarnings("serial")
public class InvalidConfigurationException extends Exception { public class InvalidConfigurationException extends Exception {
/** /**
* Creates a new instance of InvalidConfigurationException without a * Creates a new instance of InvalidConfigurationException without a
* message or cause. * message or cause.
*/ */
public InvalidConfigurationException() {} public InvalidConfigurationException() {}
/** /**
* Constructs an instance of InvalidConfigurationException with the * Constructs an instance of InvalidConfigurationException with the
* specified message. * specified message.
* *
* @param msg The details of the exception. * @param msg The details of the exception.
*/ */
public InvalidConfigurationException(String msg) { public InvalidConfigurationException(final String msg) {
super(msg); super(msg);
} }
/** /**
* Constructs an instance of InvalidConfigurationException with the * Constructs an instance of InvalidConfigurationException with the
* specified cause. * specified cause.
* *
* @param cause The cause of the exception. * @param cause The cause of the exception.
*/ */
public InvalidConfigurationException(Throwable cause) { public InvalidConfigurationException(final Throwable cause) {
super(cause); super(cause);
} }
/** /**
* Constructs an instance of InvalidConfigurationException with the * Constructs an instance of InvalidConfigurationException with the
* specified message and cause. * specified message and cause.
@ -39,7 +39,7 @@ public class InvalidConfigurationException extends Exception {
* @param cause The cause of the exception. * @param cause The cause of the exception.
* @param msg The details 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); super(msg, cause);
} }
} }

View File

@ -10,12 +10,12 @@ import java.util.Map;
public class MemoryConfiguration extends MemorySection implements Configuration { public class MemoryConfiguration extends MemorySection implements Configuration {
protected Configuration defaults; protected Configuration defaults;
protected MemoryConfigurationOptions options; protected MemoryConfigurationOptions options;
/** /**
* Creates an empty {@link MemoryConfiguration} with no default values. * Creates an empty {@link MemoryConfiguration} with no default values.
*/ */
public MemoryConfiguration() {} public MemoryConfiguration() {}
/** /**
* Creates an empty {@link MemoryConfiguration} using the specified {@link * Creates an empty {@link MemoryConfiguration} using the specified {@link
* Configuration} as a source for all default values. * Configuration} as a source for all default values.
@ -23,54 +23,67 @@ public class MemoryConfiguration extends MemorySection implements Configuration
* @param defaults Default value provider * @param defaults Default value provider
* @throws IllegalArgumentException Thrown if defaults is null * @throws IllegalArgumentException Thrown if defaults is null
*/ */
public MemoryConfiguration(Configuration defaults) { public MemoryConfiguration(final Configuration defaults) {
this.defaults = defaults; this.defaults = defaults;
} }
@Override @Override
public void addDefault(String path, Object value) { public void addDefault(final String path, final Object value) {
if (path == null) throw new NullPointerException("Path may not be null"); if (path == null) {
throw new NullPointerException("Path may not be null");
}
if (defaults == null) { if (defaults == null) {
defaults = new MemoryConfiguration(); defaults = new MemoryConfiguration();
} }
defaults.set(path, value); defaults.set(path, value);
} }
public void addDefaults(Map<String, Object> defaults) { @Override
if (defaults == null) throw new NullPointerException("Defaults may not be null"); public void addDefaults(final Map<String, Object> defaults) {
if (defaults == null) {
for (Map.Entry<String, Object> entry : defaults.entrySet()) { throw new NullPointerException("Defaults may not be null");
}
for (final Map.Entry<String, Object> entry : defaults.entrySet()) {
addDefault(entry.getKey(), entry.getValue()); addDefault(entry.getKey(), entry.getValue());
} }
} }
public void addDefaults(Configuration defaults) { @Override
if (defaults == null) throw new NullPointerException("Defaults may not be null"); public void addDefaults(final Configuration defaults) {
if (defaults == null) {
throw new NullPointerException("Defaults may not be null");
}
addDefaults(defaults.getValues(true)); addDefaults(defaults.getValues(true));
} }
public void setDefaults(Configuration defaults) { @Override
if (defaults == null) throw new NullPointerException("Defaults may not be null"); public void setDefaults(final Configuration defaults) {
if (defaults == null) {
throw new NullPointerException("Defaults may not be null");
}
this.defaults = defaults; this.defaults = defaults;
} }
@Override
public Configuration getDefaults() { public Configuration getDefaults() {
return defaults; return defaults;
} }
@Override @Override
public ConfigurationSection getParent() { public ConfigurationSection getParent() {
return null; return null;
} }
@Override
public MemoryConfigurationOptions options() { public MemoryConfigurationOptions options() {
if (options == null) { if (options == null) {
options = new MemoryConfigurationOptions(this); options = new MemoryConfigurationOptions(this);
} }
return options; return options;
} }
} }

View File

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

View File

@ -59,24 +59,24 @@ public abstract class FileConfiguration extends MemoryConfiguration {
SYSTEM_UTF = trueUTF || UTF8_OVERRIDE; SYSTEM_UTF = trueUTF || UTF8_OVERRIDE;
UTF_BIG = trueUTF && UTF8_OVERRIDE; UTF_BIG = trueUTF && UTF8_OVERRIDE;
} }
/** /**
* Creates an empty {@link FileConfiguration} with no default values. * Creates an empty {@link FileConfiguration} with no default values.
*/ */
public FileConfiguration() { public FileConfiguration() {
super(); super();
} }
/** /**
* Creates an empty {@link FileConfiguration} using the specified {@link * Creates an empty {@link FileConfiguration} using the specified {@link
* Configuration} as a source for all default values. * Configuration} as a source for all default values.
* *
* @param defaults Default value provider * @param defaults Default value provider
*/ */
public FileConfiguration(Configuration defaults) { public FileConfiguration(final Configuration defaults) {
super(defaults); super(defaults);
} }
/** /**
* Saves this {@link FileConfiguration} to the specified location. * Saves this {@link FileConfiguration} to the specified location.
* <p> * <p>
@ -92,21 +92,20 @@ public abstract class FileConfiguration extends MemoryConfiguration {
* any reason. * any reason.
* @throws IllegalArgumentException Thrown when file is null. * @throws IllegalArgumentException Thrown when file is null.
*/ */
public void save(File file) throws IOException { public void save(final File file) throws IOException {
if (file == null) throw new NullPointerException("File cannot be null"); if (file == null) {
throw new NullPointerException("File cannot be null");
}
file.getParentFile().mkdirs(); file.getParentFile().mkdirs();
final String data = saveToString();
String data = saveToString(); try (Writer writer = new OutputStreamWriter(new FileOutputStream(file),
UTF8_OVERRIDE && !UTF_BIG ? StandardCharsets.UTF_8 : Charset.defaultCharset())) {
Writer writer = new OutputStreamWriter(new FileOutputStream(file), UTF8_OVERRIDE && !UTF_BIG ? StandardCharsets.UTF_8 : Charset.defaultCharset());
try {
writer.write(data); writer.write(data);
} finally {
writer.close();
} }
} }
/** /**
* Saves this {@link FileConfiguration} to the specified location. * Saves this {@link FileConfiguration} to the specified location.
* <p> * <p>
@ -122,19 +121,21 @@ public abstract class FileConfiguration extends MemoryConfiguration {
* any reason. * any reason.
* @throws IllegalArgumentException Thrown when file is null. * @throws IllegalArgumentException Thrown when file is null.
*/ */
public void save(String file) throws IOException { public void save(final String file) throws IOException {
if (file == null) throw new NullPointerException("File cannot be null"); if (file == null) {
throw new NullPointerException("File cannot be null");
}
save(new File(file)); save(new File(file));
} }
/** /**
* Saves this {@link FileConfiguration} to a string, and returns it. * Saves this {@link FileConfiguration} to a string, and returns it.
* *
* @return String containing this configuration. * @return String containing this configuration.
*/ */
public abstract String saveToString(); public abstract String saveToString();
/** /**
* Loads this {@link FileConfiguration} from the specified location. * Loads this {@link FileConfiguration} from the specified location.
* <p> * <p>
@ -157,14 +158,16 @@ public abstract class FileConfiguration extends MemoryConfiguration {
* a valid Configuration. * a valid Configuration.
* @throws IllegalArgumentException Thrown when file is null. * @throws IllegalArgumentException Thrown when file is null.
*/ */
public void load(File file) throws IOException, InvalidConfigurationException { public void load(final File file) throws IOException, InvalidConfigurationException {
if (file == null) throw new NullPointerException("File cannot be null"); if (file == null) {
throw new NullPointerException("File cannot be null");
}
final FileInputStream stream = new FileInputStream(file); final FileInputStream stream = new FileInputStream(file);
load(new InputStreamReader(stream, UTF8_OVERRIDE && !UTF_BIG ? StandardCharsets.UTF_8 : Charset.defaultCharset())); load(new InputStreamReader(stream, UTF8_OVERRIDE && !UTF_BIG ? StandardCharsets.UTF_8 : Charset.defaultCharset()));
} }
/** /**
* Loads this {@link FileConfiguration} from the specified stream. * Loads this {@link FileConfiguration} from the specified stream.
* <p> * <p>
@ -184,12 +187,14 @@ public abstract class FileConfiguration extends MemoryConfiguration {
* @see #load(Reader) * @see #load(Reader)
*/ */
@Deprecated @Deprecated
public void load(InputStream stream) throws IOException, InvalidConfigurationException { public void load(final InputStream stream) throws IOException, InvalidConfigurationException {
if (stream == null) throw new NullPointerException("Stream cannot be null"); if (stream == null) {
throw new NullPointerException("Stream cannot be null");
}
load(new InputStreamReader(stream, UTF8_OVERRIDE ? StandardCharsets.UTF_8 : Charset.defaultCharset())); load(new InputStreamReader(stream, UTF8_OVERRIDE ? StandardCharsets.UTF_8 : Charset.defaultCharset()));
} }
/** /**
* Loads this {@link FileConfiguration} from the specified reader. * Loads this {@link FileConfiguration} from the specified reader.
* <p> * <p>
@ -203,25 +208,22 @@ public abstract class FileConfiguration extends MemoryConfiguration {
* represent a valid Configuration * represent a valid Configuration
* @throws IllegalArgumentException thrown when reader is null * @throws IllegalArgumentException thrown when reader is null
*/ */
public void load(Reader reader) throws IOException, InvalidConfigurationException { public void load(final Reader reader) throws IOException, InvalidConfigurationException {
BufferedReader input = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader);
StringBuilder builder = new StringBuilder(); final StringBuilder builder = new StringBuilder();
try { try (BufferedReader input = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader)) {
String line; String line;
while ((line = input.readLine()) != null) { while ((line = input.readLine()) != null) {
builder.append(line); builder.append(line);
builder.append('\n'); builder.append('\n');
} }
} finally {
input.close();
} }
loadFromString(builder.toString()); loadFromString(builder.toString());
} }
/** /**
* Loads this {@link FileConfiguration} from the specified location. * Loads this {@link FileConfiguration} from the specified location.
* <p> * <p>
@ -240,12 +242,14 @@ public abstract class FileConfiguration extends MemoryConfiguration {
* a valid Configuration. * a valid Configuration.
* @throws IllegalArgumentException Thrown when file is null. * @throws IllegalArgumentException Thrown when file is null.
*/ */
public void load(String file) throws IOException, InvalidConfigurationException { public void load(final String file) throws IOException, InvalidConfigurationException {
if (file == null) throw new NullPointerException("File cannot be null"); if (file == null) {
throw new NullPointerException("File cannot be null");
}
load(new File(file)); load(new File(file));
} }
/** /**
* Loads this {@link FileConfiguration} from the specified string, as * Loads this {@link FileConfiguration} from the specified string, as
* opposed to from file. * opposed to from file.
@ -261,8 +265,8 @@ public abstract class FileConfiguration extends MemoryConfiguration {
* invalid. * invalid.
* @throws IllegalArgumentException Thrown if contents is null. * @throws IllegalArgumentException Thrown if contents is null.
*/ */
public abstract void loadFromString(String contents) throws InvalidConfigurationException; public abstract void loadFromString(final String contents) throws InvalidConfigurationException;
/** /**
* Compiles the header for this {@link FileConfiguration} and returns the * Compiles the header for this {@link FileConfiguration} and returns the
* result. * result.
@ -274,13 +278,13 @@ public abstract class FileConfiguration extends MemoryConfiguration {
* @return Compiled header * @return Compiled header
*/ */
protected abstract String buildHeader(); protected abstract String buildHeader();
@Override @Override
public FileConfigurationOptions options() { public FileConfigurationOptions options() {
if (options == null) { if (options == null) {
options = new FileConfigurationOptions(this); options = new FileConfigurationOptions(this);
} }
return (FileConfigurationOptions) options; return (FileConfigurationOptions) options;
} }
} }

View File

@ -10,28 +10,28 @@ import com.intellectualcrafters.configuration.MemoryConfigurationOptions;
public class FileConfigurationOptions extends MemoryConfigurationOptions { public class FileConfigurationOptions extends MemoryConfigurationOptions {
private String header = null; private String header = null;
private boolean copyHeader = true; private boolean copyHeader = true;
protected FileConfigurationOptions(MemoryConfiguration configuration) { protected FileConfigurationOptions(final MemoryConfiguration configuration) {
super(configuration); super(configuration);
} }
@Override @Override
public FileConfiguration configuration() { public FileConfiguration configuration() {
return (FileConfiguration) super.configuration(); return (FileConfiguration) super.configuration();
} }
@Override @Override
public FileConfigurationOptions copyDefaults(boolean value) { public FileConfigurationOptions copyDefaults(final boolean value) {
super.copyDefaults(value); super.copyDefaults(value);
return this; return this;
} }
@Override @Override
public FileConfigurationOptions pathSeparator(char value) { public FileConfigurationOptions pathSeparator(final char value) {
super.pathSeparator(value); super.pathSeparator(value);
return this; return this;
} }
/** /**
* Gets the header that will be applied to the top of the saved output. * Gets the header that will be applied to the top of the saved output.
* <p> * <p>
@ -49,7 +49,7 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions {
public String header() { public String header() {
return header; return header;
} }
/** /**
* Sets the header that will be applied to the top of the saved output. * Sets the header that will be applied to the top of the saved output.
* <p> * <p>
@ -65,11 +65,11 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions {
* @param value New header * @param value New header
* @return This object, for chaining * @return This object, for chaining
*/ */
public FileConfigurationOptions header(String value) { public FileConfigurationOptions header(final String value) {
this.header = value; header = value;
return this; return this;
} }
/** /**
* Gets whether or not the header should be copied from a default source. * Gets whether or not the header should be copied from a default source.
* <p> * <p>
@ -91,7 +91,7 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions {
public boolean copyHeader() { public boolean copyHeader() {
return copyHeader; return copyHeader;
} }
/** /**
* Sets whether or not the header should be copied from a default source. * Sets whether or not the header should be copied from a default source.
* <p> * <p>
@ -111,9 +111,9 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions {
* @param value Whether or not to copy the header * @param value Whether or not to copy the header
* @return This object, for chaining * @return This object, for chaining
*/ */
public FileConfigurationOptions copyHeader(boolean value) { public FileConfigurationOptions copyHeader(final boolean value) {
copyHeader = value; copyHeader = value;
return this; return this;
} }
} }

View File

@ -1,22 +1,20 @@
package com.intellectualcrafters.configuration.file; 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.Configuration;
import com.intellectualcrafters.configuration.ConfigurationSection; import com.intellectualcrafters.configuration.ConfigurationSection;
import com.intellectualcrafters.configuration.InvalidConfigurationException; import com.intellectualcrafters.configuration.InvalidConfigurationException;
import com.intellectualcrafters.plot.PS; 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. * 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 Representer yamlRepresenter = new YamlRepresenter();
private final Yaml yaml = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions); 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 @Override
@SuppressWarnings("deprecation")
public String saveToString() { public String saveToString() {
yamlOptions.setIndent(options().indent()); yamlOptions.setIndent(options().indent());
yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
yamlOptions.setAllowUnicode(SYSTEM_UTF); yamlOptions.setAllowUnicode(SYSTEM_UTF);
yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
String header = buildHeader(); final String header = buildHeader();
String dump = yaml.dump(getValues(false)); String dump = yaml.dump(getValues(false));
if (dump.equals(BLANK_CONFIG)) { if (dump.equals(BLANK_CONFIG)) {
@ -45,22 +116,24 @@ public class YamlConfiguration extends FileConfiguration {
return header + dump; return header + dump;
} }
@Override @Override
public void loadFromString(String contents) throws InvalidConfigurationException { public void loadFromString(final String contents) throws InvalidConfigurationException {
if (contents == null) throw new NullPointerException("Contents cannot be null"); if (contents == null) {
throw new NullPointerException("Contents cannot be null");
}
Map<?, ?> input; Map<?, ?> input;
try { try {
input = (Map<?, ?>) yaml.load(contents); input = (Map<?, ?>) yaml.load(contents);
} catch (YAMLException e) { } catch (final YAMLException e) {
throw new InvalidConfigurationException(e); throw new InvalidConfigurationException(e);
} catch (ClassCastException e) { } catch (final ClassCastException e) {
throw new InvalidConfigurationException("Top level is not a Map."); throw new InvalidConfigurationException("Top level is not a Map.");
} }
String header = parseHeader(contents); final String header = parseHeader(contents);
if (header.length() > 0) { if (!header.isEmpty()) {
options().header(header); options().header(header);
} }
@ -68,11 +141,11 @@ public class YamlConfiguration extends FileConfiguration {
convertMapsToSections(input, this); convertMapsToSections(input, this);
} }
} }
protected void convertMapsToSections(Map<?, ?> input, ConfigurationSection section) { protected void convertMapsToSections(final Map<?, ?> input, final ConfigurationSection section) {
for (Map.Entry<?, ?> entry : input.entrySet()) { for (final Map.Entry<?, ?> entry : input.entrySet()) {
String key = entry.getKey().toString(); final String key = entry.getKey().toString();
Object value = entry.getValue(); final Object value = entry.getValue();
if (value instanceof Map) { if (value instanceof Map) {
convertMapsToSections((Map<?, ?>) value, section.createSection(key)); convertMapsToSections((Map<?, ?>) value, section.createSection(key));
@ -81,15 +154,15 @@ public class YamlConfiguration extends FileConfiguration {
} }
} }
} }
protected String parseHeader(String input) { protected String parseHeader(final String input) {
String[] lines = input.split("\r?\n", -1); final String[] lines = input.split("\r?\n", -1);
StringBuilder result = new StringBuilder(); final StringBuilder result = new StringBuilder();
boolean readingHeader = true; boolean readingHeader = true;
boolean foundHeader = false; boolean foundHeader = false;
for (int i = 0; (i < lines.length) && (readingHeader); i++) { for (int i = 0; (i < lines.length) && (readingHeader); i++) {
String line = lines[i]; final String line = lines[i];
if (line.startsWith(COMMENT_PREFIX)) { if (line.startsWith(COMMENT_PREFIX)) {
if (i > 0) { if (i > 0) {
@ -101,7 +174,7 @@ public class YamlConfiguration extends FileConfiguration {
} }
foundHeader = true; foundHeader = true;
} else if ((foundHeader) && (line.length() == 0)) { } else if ((foundHeader) && (line.isEmpty())) {
result.append("\n"); result.append("\n");
} else if (foundHeader) { } else if (foundHeader) {
readingHeader = false; readingHeader = false;
@ -110,19 +183,19 @@ public class YamlConfiguration extends FileConfiguration {
return result.toString(); return result.toString();
} }
@Override @Override
protected String buildHeader() { protected String buildHeader() {
String header = options().header(); final String header = options().header();
if (options().copyHeader()) { if (options().copyHeader()) {
Configuration def = getDefaults(); final Configuration def = getDefaults();
if ((def != null) && (def instanceof FileConfiguration)) { if ((def != null) && (def instanceof FileConfiguration)) {
FileConfiguration filedefaults = (FileConfiguration) def; final FileConfiguration filedefaults = (FileConfiguration) def;
String defaultsHeader = filedefaults.buildHeader(); final String defaultsHeader = filedefaults.buildHeader();
if ((defaultsHeader != null) && (defaultsHeader.length() > 0)) { if ((defaultsHeader != null) && (!defaultsHeader.isEmpty())) {
return defaultsHeader; return defaultsHeader;
} }
} }
@ -132,14 +205,14 @@ public class YamlConfiguration extends FileConfiguration {
return ""; return "";
} }
StringBuilder builder = new StringBuilder(); final StringBuilder builder = new StringBuilder();
String[] lines = header.split("\r?\n", -1); final String[] lines = header.split("\r?\n", -1);
boolean startedHeader = false; boolean startedHeader = false;
for (int i = lines.length - 1; i >= 0; i--) { for (int i = lines.length - 1; i >= 0; i--) {
builder.insert(0, "\n"); builder.insert(0, "\n");
if ((startedHeader) || (lines[i].length() != 0)) { if ((startedHeader) || (!lines[i].isEmpty())) {
builder.insert(0, lines[i]); builder.insert(0, lines[i]);
builder.insert(0, COMMENT_PREFIX); builder.insert(0, COMMENT_PREFIX);
startedHeader = true; startedHeader = true;
@ -157,109 +230,4 @@ public class YamlConfiguration extends FileConfiguration {
return (YamlConfigurationOptions) options; 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

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

View File

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

View File

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

View File

@ -22,12 +22,12 @@ import java.util.Map;
* @see SerializableAs * @see SerializableAs
*/ */
public interface ConfigurationSerializable { public interface ConfigurationSerializable {
/** /**
* Creates a Map representation of this class. * Creates a Map representation of this class.
* <p> * <p>
* This class must provide a method to restore this class, as defined in * 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 * @return Map containing the current state of this class
*/ */

View File

@ -1,5 +1,7 @@
package com.intellectualcrafters.configuration.serialization; package com.intellectualcrafters.configuration.serialization;
import com.intellectualcrafters.configuration.Configuration;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
@ -9,8 +11,6 @@ import java.util.Map;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import com.intellectualcrafters.configuration.Configuration;
/** /**
* Utility class for storing and retrieving classes for {@link Configuration}. * Utility class for storing and retrieving classes for {@link Configuration}.
*/ */
@ -18,106 +18,99 @@ public class ConfigurationSerialization {
public static final String SERIALIZED_TYPE_KEY = "=="; public static final String SERIALIZED_TYPE_KEY = "==";
private final Class<? extends ConfigurationSerializable> clazz; private final Class<? extends ConfigurationSerializable> clazz;
private static Map<String, Class<? extends ConfigurationSerializable>> aliases = new HashMap<String, Class<? extends ConfigurationSerializable>>(); 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; this.clazz = clazz;
} }
protected Method getMethod(String name, boolean isStatic) { protected Method getMethod(final String name, final boolean isStatic) {
try { try {
Method method = clazz.getDeclaredMethod(name, Map.class); final Method method = clazz.getDeclaredMethod(name, Map.class);
if (!ConfigurationSerializable.class.isAssignableFrom(method.getReturnType())) { if (!ConfigurationSerializable.class.isAssignableFrom(method.getReturnType())) {
return null; return null;
} }
if (Modifier.isStatic(method.getModifiers()) != isStatic) { if (Modifier.isStatic(method.getModifiers()) != isStatic) {
return null; return null;
} }
return method; return method;
} catch (NoSuchMethodException ex) { } catch (final NoSuchMethodException ex) {
return null; return null;
} catch (SecurityException ex) { } catch (final SecurityException ex) {
return null; return null;
} }
} }
protected Constructor<? extends ConfigurationSerializable> getConstructor() { protected Constructor<? extends ConfigurationSerializable> getConstructor() {
try { try {
return clazz.getConstructor(Map.class); return clazz.getConstructor(Map.class);
} catch (NoSuchMethodException ex) { } catch (final NoSuchMethodException ex) {
return null; return null;
} catch (SecurityException ex) { } catch (final SecurityException ex) {
return null; return null;
} }
} }
protected ConfigurationSerializable deserializeViaMethod(Method method, Map<String, ?> args) { protected ConfigurationSerializable deserializeViaMethod(final Method method, final Map<String, ?> args) {
try { try {
ConfigurationSerializable result = (ConfigurationSerializable) method.invoke(null, args); final ConfigurationSerializable result = (ConfigurationSerializable) method.invoke(null, args);
if (result == null) { 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 { } else {
return result; return result;
} }
} catch (Throwable ex) { } catch (final Throwable ex) {
Logger.getLogger(ConfigurationSerialization.class.getName()).log( Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE, "Could not call method '" + method.toString() + "' of " + clazz + " for deserialization",
Level.SEVERE, ex instanceof InvocationTargetException ? ex.getCause() : ex);
"Could not call method '" + method.toString() + "' of " + clazz + " for deserialization",
ex instanceof InvocationTargetException ? ex.getCause() : ex);
} }
return null; 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 { try {
return ctor.newInstance(args); return ctor.newInstance(args);
} catch (Throwable ex) { } catch (final Throwable ex) {
Logger.getLogger(ConfigurationSerialization.class.getName()).log( Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE, "Could not call constructor '" + ctor.toString() + "' of " + clazz + " for deserialization",
Level.SEVERE, ex instanceof InvocationTargetException ? ex.getCause() : ex);
"Could not call constructor '" + ctor.toString() + "' of " + clazz + " for deserialization",
ex instanceof InvocationTargetException ? ex.getCause() : ex);
} }
return null; return null;
} }
public ConfigurationSerializable deserialize(Map<String, ?> args) { public ConfigurationSerializable deserialize(final Map<String, ?> args) {
if (args == null) { if (args == null) {
throw new NullPointerException("Args must not be null"); throw new NullPointerException("Args must not be null");
} }
ConfigurationSerializable result = null; ConfigurationSerializable result = null;
Method method = null; Method method = getMethod("deserialize", true);
if (result == null) { if (method != null) {
method = getMethod("deserialize", true); result = deserializeViaMethod(method, args);
if (method != null) {
result = deserializeViaMethod(method, args);
}
} }
if (result == null) { if (result == null) {
method = getMethod("valueOf", true); method = getMethod("valueOf", true);
if (method != null) { if (method != null) {
result = deserializeViaMethod(method, args); result = deserializeViaMethod(method, args);
} }
} }
if (result == null) { if (result == null) {
Constructor<? extends ConfigurationSerializable> constructor = getConstructor(); final Constructor<? extends ConfigurationSerializable> constructor = getConstructor();
if (constructor != null) { if (constructor != null) {
result = deserializeViaCtor(constructor, args); result = deserializeViaCtor(constructor, args);
} }
} }
return result; return result;
} }
/** /**
* Attempts to deserialize the given arguments into a new instance of the * Attempts to deserialize the given arguments into a new instance of the
* given class. * given class.
@ -133,10 +126,10 @@ public class ConfigurationSerialization {
* @param clazz Class to deserialize into * @param clazz Class to deserialize into
* @return New instance of the specified class * @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); return new ConfigurationSerialization(clazz).deserialize(args);
} }
/** /**
* Attempts to deserialize the given arguments into a new instance of the * Attempts to deserialize the given arguments into a new instance of the
* given class. * given class.
@ -151,13 +144,13 @@ public class ConfigurationSerialization {
* @param args Arguments for deserialization * @param args Arguments for deserialization
* @return New instance of the specified class * @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; Class<? extends ConfigurationSerializable> clazz = null;
if (args.containsKey(SERIALIZED_TYPE_KEY)) { if (args.containsKey(SERIALIZED_TYPE_KEY)) {
try { try {
String alias = (String) args.get(SERIALIZED_TYPE_KEY); final String alias = (String) args.get(SERIALIZED_TYPE_KEY);
if (alias == null) { if (alias == null) {
throw new IllegalArgumentException("Cannot have null alias"); throw new IllegalArgumentException("Cannot have null alias");
} }
@ -165,32 +158,32 @@ public class ConfigurationSerialization {
if (clazz == null) { if (clazz == null) {
throw new IllegalArgumentException("Specified class does not exist ('" + alias + "')"); throw new IllegalArgumentException("Specified class does not exist ('" + alias + "')");
} }
} catch (ClassCastException ex) { } catch (final ClassCastException ex) {
ex.fillInStackTrace(); ex.fillInStackTrace();
throw ex; throw ex;
} }
} else { } else {
throw new IllegalArgumentException("Args doesn't contain type key ('" + SERIALIZED_TYPE_KEY + "')"); throw new IllegalArgumentException("Args doesn't contain type key ('" + SERIALIZED_TYPE_KEY + "')");
} }
return new ConfigurationSerialization(clazz).deserialize(args); return new ConfigurationSerialization(clazz).deserialize(args);
} }
/** /**
* Registers the given {@link ConfigurationSerializable} class by its * Registers the given {@link ConfigurationSerializable} class by its
* alias * alias
* *
* @param clazz Class to register * @param clazz Class to register
*/ */
public static void registerClass(Class<? extends ConfigurationSerializable> clazz) { public static void registerClass(final Class<? extends ConfigurationSerializable> clazz) {
DelegateDeserialization delegate = clazz.getAnnotation(DelegateDeserialization.class); final DelegateDeserialization delegate = clazz.getAnnotation(DelegateDeserialization.class);
if (delegate == null) { if (delegate == null) {
registerClass(clazz, getAlias(clazz)); registerClass(clazz, getAlias(clazz));
registerClass(clazz, clazz.getName()); registerClass(clazz, clazz.getName());
} }
} }
/** /**
* Registers the given alias to the specified {@link * Registers the given alias to the specified {@link
* ConfigurationSerializable} class * ConfigurationSerializable} class
@ -199,30 +192,29 @@ public class ConfigurationSerialization {
* @param alias Alias to register as * @param alias Alias to register as
* @see SerializableAs * @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); aliases.put(alias, clazz);
} }
/** /**
* Unregisters the specified alias to a {@link ConfigurationSerializable} * Unregisters the specified alias to a {@link ConfigurationSerializable}
* *
* @param alias Alias to unregister * @param alias Alias to unregister
*/ */
public static void unregisterClass(String alias) { public static void unregisterClass(final String alias) {
aliases.remove(alias); aliases.remove(alias);
} }
/** /**
* Unregisters any aliases for the specified {@link * Unregisters any aliases for the specified {@link
* ConfigurationSerializable} class * ConfigurationSerializable} class
* *
* @param clazz Class to unregister * @param clazz Class to unregister
*/ */
public static void unregisterClass(Class<? extends ConfigurationSerializable> clazz) { public static void unregisterClass(final Class<? extends ConfigurationSerializable> clazz) {
while (aliases.values().remove(clazz)) { while (aliases.values().remove(clazz)) {}
}
} }
/** /**
* Attempts to get a registered {@link ConfigurationSerializable} class by * Attempts to get a registered {@link ConfigurationSerializable} class by
* its alias * its alias
@ -230,10 +222,10 @@ public class ConfigurationSerialization {
* @param alias Alias of the serializable * @param alias Alias of the serializable
* @return Registered class, or null if not found * @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); return aliases.get(alias);
} }
/** /**
* Gets the correct alias for the given {@link ConfigurationSerializable} * Gets the correct alias for the given {@link ConfigurationSerializable}
* class * class
@ -241,9 +233,9 @@ public class ConfigurationSerialization {
* @param clazz Class to get alias for * @param clazz Class to get alias for
* @return Alias to use for the class * @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); DelegateDeserialization delegate = clazz.getAnnotation(DelegateDeserialization.class);
if (delegate != null) { if (delegate != null) {
if ((delegate.value() == null) || (delegate.value() == clazz)) { if ((delegate.value() == null) || (delegate.value() == clazz)) {
delegate = null; delegate = null;
@ -252,12 +244,10 @@ public class ConfigurationSerialization {
} }
} }
if (delegate == null) { final SerializableAs alias = clazz.getAnnotation(SerializableAs.class);
SerializableAs alias = clazz.getAnnotation(SerializableAs.class);
if ((alias != null) && (alias.value() != null)) { if ((alias != null) && (alias.value() != null)) {
return alias.value(); return alias.value();
}
} }
return clazz.getName(); return clazz.getName();

View File

@ -5,7 +5,7 @@ package com.intellectualcrafters.jnbt;
*/ */
public final class ByteArrayTag extends Tag { public final class ByteArrayTag extends Tag {
private final byte[] value; private final byte[] value;
/** /**
* Creates the tag with an empty name. * Creates the tag with an empty name.
* *
@ -15,7 +15,7 @@ public final class ByteArrayTag extends Tag {
super(); super();
this.value = value; this.value = value;
} }
/** /**
* Creates the tag. * Creates the tag.
* *
@ -26,16 +26,16 @@ public final class ByteArrayTag extends Tag {
super(name); super(name);
this.value = value; this.value = value;
} }
@Override @Override
public byte[] getValue() { public byte[] getValue() {
return this.value; return value;
} }
@Override @Override
public String toString() { public String toString() {
final StringBuilder hex = new StringBuilder(); final StringBuilder hex = new StringBuilder();
for (final byte b : this.value) { for (final byte b : value) {
final String hexDigits = Integer.toHexString(b).toUpperCase(); final String hexDigits = Integer.toHexString(b).toUpperCase();
if (hexDigits.length() == 1) { if (hexDigits.length() == 1) {
hex.append("0"); hex.append("0");
@ -45,7 +45,7 @@ public final class ByteArrayTag extends Tag {
final String name = getName(); final String name = getName();
String append = ""; String append = "";
if ((name != null) && !name.equals("")) { if ((name != null) && !name.equals("")) {
append = "(\"" + this.getName() + "\")"; append = "(\"" + getName() + "\")";
} }
return "TAG_Byte_Array" + append + ": " + hex; return "TAG_Byte_Array" + append + ": " + hex;
} }

View File

@ -5,7 +5,7 @@ package com.intellectualcrafters.jnbt;
*/ */
public final class ByteTag extends Tag { public final class ByteTag extends Tag {
private final byte value; private final byte value;
/** /**
* Creates the tag with an empty name. * Creates the tag with an empty name.
* *
@ -15,7 +15,7 @@ public final class ByteTag extends Tag {
super(); super();
this.value = value; this.value = value;
} }
/** /**
* Creates the tag. * Creates the tag.
* *
@ -26,19 +26,19 @@ public final class ByteTag extends Tag {
super(name); super(name);
this.value = value; this.value = value;
} }
@Override @Override
public Byte getValue() { public Byte getValue() {
return this.value; return value;
} }
@Override @Override
public String toString() { public String toString() {
final String name = getName(); final String name = getName();
String append = ""; String append = "";
if ((name != null) && !name.equals("")) { if ((name != null) && !name.equals("")) {
append = "(\"" + this.getName() + "\")"; append = "(\"" + getName() + "\")";
} }
return "TAG_Byte" + append + ": " + this.value; return "TAG_Byte" + append + ": " + value;
} }
} }

View File

@ -10,7 +10,7 @@ import java.util.Map;
*/ */
public final class CompoundTag extends Tag { public final class CompoundTag extends Tag {
private final Map<String, Tag> value; private final Map<String, Tag> value;
/** /**
* Creates the tag with an empty name. * Creates the tag with an empty name.
* *
@ -20,7 +20,7 @@ public final class CompoundTag extends Tag {
super(); super();
this.value = Collections.unmodifiableMap(value); this.value = Collections.unmodifiableMap(value);
} }
/** /**
* Creates the tag. * Creates the tag.
* *
@ -31,7 +31,7 @@ public final class CompoundTag extends Tag {
super(name); super(name);
this.value = Collections.unmodifiableMap(value); this.value = Collections.unmodifiableMap(value);
} }
/** /**
* Returns whether this compound tag contains the given key. * Returns whether this compound tag contains the given key.
* *
@ -40,14 +40,14 @@ public final class CompoundTag extends Tag {
* @return true if the tag contains the given key * @return true if the tag contains the given key
*/ */
public boolean containsKey(final String key) { public boolean containsKey(final String key) {
return this.value.containsKey(key); return value.containsKey(key);
} }
@Override @Override
public Map<String, Tag> getValue() { public Map<String, Tag> getValue() {
return this.value; return value;
} }
/** /**
* Return a new compound tag with the given values. * Return a new compound tag with the given values.
* *
@ -58,16 +58,16 @@ public final class CompoundTag extends Tag {
public CompoundTag setValue(final Map<String, Tag> value) { public CompoundTag setValue(final Map<String, Tag> value) {
return new CompoundTag(getName(), value); return new CompoundTag(getName(), value);
} }
/** /**
* Create a compound tag builder. * Create a compound tag builder.
* *
* @return the builder * @return the builder
*/ */
public CompoundTagBuilder createBuilder() { public CompoundTagBuilder createBuilder() {
return new CompoundTagBuilder(new HashMap<String, Tag>(this.value)); return new CompoundTagBuilder(new HashMap<String, Tag>(value));
} }
/** /**
* Get a byte array named with the given key. <p> If the key does not exist or its value is not a byte array * Get a byte array named with the given key. <p> If the key does not exist or its value is not a byte array
* tag, then an empty byte array will be returned. </p> * tag, then an empty byte array will be returned. </p>
@ -77,14 +77,14 @@ public final class CompoundTag extends Tag {
* @return a byte array * @return a byte array
*/ */
public byte[] getByteArray(final String key) { public byte[] getByteArray(final String key) {
final Tag tag = this.value.get(key); final Tag tag = value.get(key);
if (tag instanceof ByteArrayTag) { if (tag instanceof ByteArrayTag) {
return ((ByteArrayTag) tag).getValue(); return ((ByteArrayTag) tag).getValue();
} else { } else {
return new byte[0]; return new byte[0];
} }
} }
/** /**
* Get a byte named with the given key. <p> If the key does not exist or its value is not a byte tag, then * Get a byte named with the given key. <p> If the key does not exist or its value is not a byte tag, then
* {@code 0} will be returned. </p> * {@code 0} will be returned. </p>
@ -94,14 +94,14 @@ public final class CompoundTag extends Tag {
* @return a byte * @return a byte
*/ */
public byte getByte(final String key) { public byte getByte(final String key) {
final Tag tag = this.value.get(key); final Tag tag = value.get(key);
if (tag instanceof ByteTag) { if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue(); return ((ByteTag) tag).getValue();
} else { } else {
return (byte) 0; return (byte) 0;
} }
} }
/** /**
* Get a double named with the given key. <p> If the key does not exist or its value is not a double tag, then * Get a double named with the given key. <p> If the key does not exist or its value is not a double tag, then
* {@code 0} will be returned. </p> * {@code 0} will be returned. </p>
@ -111,14 +111,14 @@ public final class CompoundTag extends Tag {
* @return a double * @return a double
*/ */
public double getDouble(final String key) { public double getDouble(final String key) {
final Tag tag = this.value.get(key); final Tag tag = value.get(key);
if (tag instanceof DoubleTag) { if (tag instanceof DoubleTag) {
return ((DoubleTag) tag).getValue(); return ((DoubleTag) tag).getValue();
} else { } else {
return 0; return 0;
} }
} }
/** /**
* Get a double named with the given key, even if it's another type of number. <p> If the key does not exist or * Get a double named with the given key, even if it's another type of number. <p> If the key does not exist or
* its value is not a number, then {@code 0} will be returned. </p> * its value is not a number, then {@code 0} will be returned. </p>
@ -128,7 +128,7 @@ public final class CompoundTag extends Tag {
* @return a double * @return a double
*/ */
public double asDouble(final String key) { public double asDouble(final String key) {
final Tag tag = this.value.get(key); final Tag tag = value.get(key);
if (tag instanceof ByteTag) { if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue(); return ((ByteTag) tag).getValue();
} else if (tag instanceof ShortTag) { } else if (tag instanceof ShortTag) {
@ -145,7 +145,7 @@ public final class CompoundTag extends Tag {
return 0; return 0;
} }
} }
/** /**
* Get a float named with the given key. <p> If the key does not exist or its value is not a float tag, then * Get a float named with the given key. <p> If the key does not exist or its value is not a float tag, then
* {@code 0} will be returned. </p> * {@code 0} will be returned. </p>
@ -155,14 +155,14 @@ public final class CompoundTag extends Tag {
* @return a float * @return a float
*/ */
public float getFloat(final String key) { public float getFloat(final String key) {
final Tag tag = this.value.get(key); final Tag tag = value.get(key);
if (tag instanceof FloatTag) { if (tag instanceof FloatTag) {
return ((FloatTag) tag).getValue(); return ((FloatTag) tag).getValue();
} else { } else {
return 0; return 0;
} }
} }
/** /**
* Get a {@code int[]} named with the given key. <p> If the key does not exist or its value is not an int array * Get a {@code int[]} named with the given key. <p> If the key does not exist or its value is not an int array
* tag, then an empty array will be returned. </p> * tag, then an empty array will be returned. </p>
@ -172,14 +172,14 @@ public final class CompoundTag extends Tag {
* @return an int array * @return an int array
*/ */
public int[] getIntArray(final String key) { public int[] getIntArray(final String key) {
final Tag tag = this.value.get(key); final Tag tag = value.get(key);
if (tag instanceof IntArrayTag) { if (tag instanceof IntArrayTag) {
return ((IntArrayTag) tag).getValue(); return ((IntArrayTag) tag).getValue();
} else { } else {
return new int[0]; return new int[0];
} }
} }
/** /**
* Get an int named with the given key. <p> If the key does not exist or its value is not an int tag, then * Get an int named with the given key. <p> If the key does not exist or its value is not an int tag, then
* {@code 0} will be returned. </p> * {@code 0} will be returned. </p>
@ -189,14 +189,14 @@ public final class CompoundTag extends Tag {
* @return an int * @return an int
*/ */
public int getInt(final String key) { public int getInt(final String key) {
final Tag tag = this.value.get(key); final Tag tag = value.get(key);
if (tag instanceof IntTag) { if (tag instanceof IntTag) {
return ((IntTag) tag).getValue(); return ((IntTag) tag).getValue();
} else { } else {
return 0; return 0;
} }
} }
/** /**
* Get an int named with the given key, even if it's another type of number. <p> If the key does not exist or * Get an int named with the given key, even if it's another type of number. <p> If the key does not exist or
* its value is not a number, then {@code 0} will be returned. </p> * its value is not a number, then {@code 0} will be returned. </p>
@ -206,7 +206,7 @@ public final class CompoundTag extends Tag {
* @return an int * @return an int
*/ */
public int asInt(final String key) { public int asInt(final String key) {
final Tag tag = this.value.get(key); final Tag tag = value.get(key);
if (tag instanceof ByteTag) { if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue(); return ((ByteTag) tag).getValue();
} else if (tag instanceof ShortTag) { } else if (tag instanceof ShortTag) {
@ -223,7 +223,7 @@ public final class CompoundTag extends Tag {
return 0; return 0;
} }
} }
/** /**
* Get a list of tags named with the given key. <p> If the key does not exist or its value is not a list tag, * Get a list of tags named with the given key. <p> If the key does not exist or its value is not a list tag,
* then an empty list will be returned. </p> * then an empty list will be returned. </p>
@ -233,14 +233,14 @@ public final class CompoundTag extends Tag {
* @return a list of tags * @return a list of tags
*/ */
public List<Tag> getList(final String key) { public List<Tag> getList(final String key) {
final Tag tag = this.value.get(key); final Tag tag = value.get(key);
if (tag instanceof ListTag) { if (tag instanceof ListTag) {
return ((ListTag) tag).getValue(); return ((ListTag) tag).getValue();
} else { } else {
return Collections.emptyList(); return Collections.emptyList();
} }
} }
/** /**
* Get a {@code TagList} named with the given key. <p> If the key does not exist or its value is not a list * Get a {@code TagList} named with the given key. <p> If the key does not exist or its value is not a list
* tag, then an empty tag list will be returned. </p> * tag, then an empty tag list will be returned. </p>
@ -250,14 +250,14 @@ public final class CompoundTag extends Tag {
* @return a tag list instance * @return a tag list instance
*/ */
public ListTag getListTag(final String key) { public ListTag getListTag(final String key) {
final Tag tag = this.value.get(key); final Tag tag = value.get(key);
if (tag instanceof ListTag) { if (tag instanceof ListTag) {
return (ListTag) tag; return (ListTag) tag;
} else { } else {
return new ListTag(key, StringTag.class, Collections.<Tag> emptyList()); return new ListTag(key, StringTag.class, Collections.<Tag> emptyList());
} }
} }
/** /**
* Get a list of tags named with the given key. <p> If the key does not exist or its value is not a list tag, * Get a list of tags named with the given key. <p> If the key does not exist or its value is not a list tag,
* then an empty list will be returned. If the given key references a list but the list of of a different type, then * then an empty list will be returned. If the given key references a list but the list of of a different type, then
@ -271,7 +271,7 @@ public final class CompoundTag extends Tag {
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <T extends Tag> List<T> getList(final String key, final Class<T> listType) { 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) { if (tag instanceof ListTag) {
final ListTag listTag = (ListTag) tag; final ListTag listTag = (ListTag) tag;
if (listTag.getType().equals(listType)) { if (listTag.getType().equals(listType)) {
@ -283,7 +283,7 @@ public final class CompoundTag extends Tag {
return Collections.emptyList(); return Collections.emptyList();
} }
} }
/** /**
* Get a long named with the given key. <p> If the key does not exist or its value is not a long tag, then * Get a long named with the given key. <p> If the key does not exist or its value is not a long tag, then
* {@code 0} will be returned. </p> * {@code 0} will be returned. </p>
@ -293,14 +293,14 @@ public final class CompoundTag extends Tag {
* @return a long * @return a long
*/ */
public long getLong(final String key) { public long getLong(final String key) {
final Tag tag = this.value.get(key); final Tag tag = value.get(key);
if (tag instanceof LongTag) { if (tag instanceof LongTag) {
return ((LongTag) tag).getValue(); return ((LongTag) tag).getValue();
} else { } else {
return 0L; return 0L;
} }
} }
/** /**
* Get a long named with the given key, even if it's another type of number. <p> If the key does not exist or * Get a long named with the given key, even if it's another type of number. <p> If the key does not exist or
* its value is not a number, then {@code 0} will be returned. </p> * its value is not a number, then {@code 0} will be returned. </p>
@ -310,7 +310,7 @@ public final class CompoundTag extends Tag {
* @return a long * @return a long
*/ */
public long asLong(final String key) { public long asLong(final String key) {
final Tag tag = this.value.get(key); final Tag tag = value.get(key);
if (tag instanceof ByteTag) { if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue(); return ((ByteTag) tag).getValue();
} else if (tag instanceof ShortTag) { } else if (tag instanceof ShortTag) {
@ -327,7 +327,7 @@ public final class CompoundTag extends Tag {
return 0L; return 0L;
} }
} }
/** /**
* Get a short named with the given key. <p> If the key does not exist or its value is not a short tag, then * Get a short named with the given key. <p> If the key does not exist or its value is not a short tag, then
* {@code 0} will be returned. </p> * {@code 0} will be returned. </p>
@ -337,14 +337,14 @@ public final class CompoundTag extends Tag {
* @return a short * @return a short
*/ */
public short getShort(final String key) { public short getShort(final String key) {
final Tag tag = this.value.get(key); final Tag tag = value.get(key);
if (tag instanceof ShortTag) { if (tag instanceof ShortTag) {
return ((ShortTag) tag).getValue(); return ((ShortTag) tag).getValue();
} else { } else {
return 0; return 0;
} }
} }
/** /**
* Get a string named with the given key. <p> If the key does not exist or its value is not a string tag, then * Get a string named with the given key. <p> If the key does not exist or its value is not a string tag, then
* {@code ""} will be returned. </p> * {@code ""} will be returned. </p>
@ -354,24 +354,24 @@ public final class CompoundTag extends Tag {
* @return a string * @return a string
*/ */
public String getString(final String key) { public String getString(final String key) {
final Tag tag = this.value.get(key); final Tag tag = value.get(key);
if (tag instanceof StringTag) { if (tag instanceof StringTag) {
return ((StringTag) tag).getValue(); return ((StringTag) tag).getValue();
} else { } else {
return ""; return "";
} }
} }
@Override @Override
public String toString() { public String toString() {
final String name = getName(); final String name = getName();
String append = ""; String append = "";
if ((name != null) && !name.equals("")) { if ((name != null) && !name.equals("")) {
append = "(\"" + this.getName() + "\")"; append = "(\"" + getName() + "\")";
} }
final StringBuilder bldr = new StringBuilder(); final StringBuilder bldr = new StringBuilder();
bldr.append("TAG_Compound").append(append).append(": ").append(this.value.size()).append(" entries\r\n{\r\n"); bldr.append("TAG_Compound").append(append).append(": ").append(value.size()).append(" entries\r\n{\r\n");
for (final Map.Entry<String, Tag> entry : this.value.entrySet()) { 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(" ").append(entry.getValue().toString().replaceAll("\r\n", "\r\n ")).append("\r\n");
} }
bldr.append("}"); bldr.append("}");

View File

@ -10,14 +10,14 @@ import java.util.Map;
*/ */
public class CompoundTagBuilder { public class CompoundTagBuilder {
private final Map<String, Tag> entries; private final Map<String, Tag> entries;
/** /**
* Create a new instance. * Create a new instance.
*/ */
CompoundTagBuilder() { CompoundTagBuilder() {
this.entries = new HashMap<String, Tag>(); entries = new HashMap<String, Tag>();
} }
/** /**
* Create a new instance and use the given map (which will be modified). * Create a new instance and use the given map (which will be modified).
* *
@ -25,9 +25,9 @@ public class CompoundTagBuilder {
*/ */
CompoundTagBuilder(final Map<String, Tag> value) { CompoundTagBuilder(final Map<String, Tag> value) {
checkNotNull(value); checkNotNull(value);
this.entries = value; entries = value;
} }
/** /**
* Create a new builder instance. * Create a new builder instance.
* *
@ -36,7 +36,7 @@ public class CompoundTagBuilder {
public static CompoundTagBuilder create() { public static CompoundTagBuilder create() {
return new CompoundTagBuilder(); return new CompoundTagBuilder();
} }
/** /**
* Put the given key and tag into the compound tag. * Put the given key and tag into the compound tag.
* *
@ -48,10 +48,10 @@ public class CompoundTagBuilder {
public CompoundTagBuilder put(final String key, final Tag value) { public CompoundTagBuilder put(final String key, final Tag value) {
checkNotNull(key); checkNotNull(key);
checkNotNull(value); checkNotNull(value);
this.entries.put(key, value); entries.put(key, value);
return this; return this;
} }
/** /**
* Put the given key and value into the compound tag as a {@code ByteArrayTag}. * Put the given key and value into the compound tag as a {@code ByteArrayTag}.
* *
@ -63,7 +63,7 @@ public class CompoundTagBuilder {
public CompoundTagBuilder putByteArray(final String key, final byte[] value) { public CompoundTagBuilder putByteArray(final String key, final byte[] value) {
return put(key, new ByteArrayTag(key, value)); return put(key, new ByteArrayTag(key, value));
} }
/** /**
* Put the given key and value into the compound tag as a {@code ByteTag}. * Put the given key and value into the compound tag as a {@code ByteTag}.
* *
@ -75,7 +75,7 @@ public class CompoundTagBuilder {
public CompoundTagBuilder putByte(final String key, final byte value) { public CompoundTagBuilder putByte(final String key, final byte value) {
return put(key, new ByteTag(key, value)); return put(key, new ByteTag(key, value));
} }
/** /**
* Put the given key and value into the compound tag as a {@code DoubleTag}. * Put the given key and value into the compound tag as a {@code DoubleTag}.
* *
@ -87,7 +87,7 @@ public class CompoundTagBuilder {
public CompoundTagBuilder putDouble(final String key, final double value) { public CompoundTagBuilder putDouble(final String key, final double value) {
return put(key, new DoubleTag(key, value)); return put(key, new DoubleTag(key, value));
} }
/** /**
* Put the given key and value into the compound tag as a {@code FloatTag}. * Put the given key and value into the compound tag as a {@code FloatTag}.
* *
@ -99,7 +99,7 @@ public class CompoundTagBuilder {
public CompoundTagBuilder putFloat(final String key, final float value) { public CompoundTagBuilder putFloat(final String key, final float value) {
return put(key, new FloatTag(key, value)); return put(key, new FloatTag(key, value));
} }
/** /**
* Put the given key and value into the compound tag as a {@code IntArrayTag}. * Put the given key and value into the compound tag as a {@code IntArrayTag}.
* *
@ -111,7 +111,7 @@ public class CompoundTagBuilder {
public CompoundTagBuilder putIntArray(final String key, final int[] value) { public CompoundTagBuilder putIntArray(final String key, final int[] value) {
return put(key, new IntArrayTag(key, value)); return put(key, new IntArrayTag(key, value));
} }
/** /**
* Put the given key and value into the compound tag as an {@code IntTag}. * Put the given key and value into the compound tag as an {@code IntTag}.
* *
@ -123,7 +123,7 @@ public class CompoundTagBuilder {
public CompoundTagBuilder putInt(final String key, final int value) { public CompoundTagBuilder putInt(final String key, final int value) {
return put(key, new IntTag(key, value)); return put(key, new IntTag(key, value));
} }
/** /**
* Put the given key and value into the compound tag as a {@code LongTag}. * Put the given key and value into the compound tag as a {@code LongTag}.
* *
@ -135,7 +135,7 @@ public class CompoundTagBuilder {
public CompoundTagBuilder putLong(final String key, final long value) { public CompoundTagBuilder putLong(final String key, final long value) {
return put(key, new LongTag(key, value)); return put(key, new LongTag(key, value));
} }
/** /**
* Put the given key and value into the compound tag as a {@code ShortTag}. * Put the given key and value into the compound tag as a {@code ShortTag}.
* *
@ -147,7 +147,7 @@ public class CompoundTagBuilder {
public CompoundTagBuilder putShort(final String key, final short value) { public CompoundTagBuilder putShort(final String key, final short value) {
return put(key, new ShortTag(key, value)); return put(key, new ShortTag(key, value));
} }
/** /**
* Put the given key and value into the compound tag as a {@code StringTag}. * Put the given key and value into the compound tag as a {@code StringTag}.
* *
@ -159,7 +159,7 @@ public class CompoundTagBuilder {
public CompoundTagBuilder putString(final String key, final String value) { public CompoundTagBuilder putString(final String key, final String value) {
return put(key, new StringTag(key, value)); return put(key, new StringTag(key, value));
} }
/** /**
* Put all the entries from the given map into this map. * Put all the entries from the given map into this map.
* *
@ -174,16 +174,16 @@ public class CompoundTagBuilder {
} }
return this; return this;
} }
/** /**
* Build an unnamed compound tag with this builder's entries. * Build an unnamed compound tag with this builder's entries.
* *
* @return the new compound tag * @return the new compound tag
*/ */
public CompoundTag build() { public CompoundTag build() {
return new CompoundTag(new HashMap<String, Tag>(this.entries)); return new CompoundTag(new HashMap<String, Tag>(entries));
} }
/** /**
* Build a new compound tag with this builder's entries. * Build a new compound tag with this builder's entries.
* *
@ -192,6 +192,6 @@ public class CompoundTagBuilder {
* @return the created compound tag * @return the created compound tag
*/ */
public CompoundTag build(final String name) { 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

@ -5,7 +5,7 @@ package com.intellectualcrafters.jnbt;
*/ */
public final class DoubleTag extends Tag { public final class DoubleTag extends Tag {
private final double value; private final double value;
/** /**
* Creates the tag with an empty name. * Creates the tag with an empty name.
* *
@ -15,7 +15,7 @@ public final class DoubleTag extends Tag {
super(); super();
this.value = value; this.value = value;
} }
/** /**
* Creates the tag. * Creates the tag.
* *
@ -26,19 +26,19 @@ public final class DoubleTag extends Tag {
super(name); super(name);
this.value = value; this.value = value;
} }
@Override @Override
public Double getValue() { public Double getValue() {
return this.value; return value;
} }
@Override @Override
public String toString() { public String toString() {
final String name = getName(); final String name = getName();
String append = ""; String append = "";
if ((name != null) && !name.equals("")) { if ((name != null) && !name.equals("")) {
append = "(\"" + this.getName() + "\")"; append = "(\"" + getName() + "\")";
} }
return "TAG_Double" + append + ": " + this.value; return "TAG_Double" + append + ": " + value;
} }
} }

View File

@ -10,12 +10,12 @@ public final class EndTag extends Tag {
public EndTag() { public EndTag() {
super(); super();
} }
@Override @Override
public Object getValue() { public Object getValue() {
return null; return null;
} }
@Override @Override
public String toString() { public String toString() {
return "TAG_End"; return "TAG_End";

View File

@ -5,7 +5,7 @@ package com.intellectualcrafters.jnbt;
*/ */
public final class FloatTag extends Tag { public final class FloatTag extends Tag {
private final float value; private final float value;
/** /**
* Creates the tag with an empty name. * Creates the tag with an empty name.
* *
@ -15,7 +15,7 @@ public final class FloatTag extends Tag {
super(); super();
this.value = value; this.value = value;
} }
/** /**
* Creates the tag. * Creates the tag.
* *
@ -26,19 +26,19 @@ public final class FloatTag extends Tag {
super(name); super(name);
this.value = value; this.value = value;
} }
@Override @Override
public Float getValue() { public Float getValue() {
return this.value; return value;
} }
@Override @Override
public String toString() { public String toString() {
final String name = getName(); final String name = getName();
String append = ""; String append = "";
if ((name != null) && !name.equals("")) { if ((name != null) && !name.equals("")) {
append = "(\"" + this.getName() + "\")"; append = "(\"" + getName() + "\")";
} }
return "TAG_Float" + append + ": " + this.value; return "TAG_Float" + append + ": " + value;
} }
} }

View File

@ -7,7 +7,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
*/ */
public final class IntArrayTag extends Tag { public final class IntArrayTag extends Tag {
private final int[] value; private final int[] value;
/** /**
* Creates the tag with an empty name. * Creates the tag with an empty name.
* *
@ -18,7 +18,7 @@ public final class IntArrayTag extends Tag {
checkNotNull(value); checkNotNull(value);
this.value = value; this.value = value;
} }
/** /**
* Creates the tag. * Creates the tag.
* *
@ -30,16 +30,16 @@ public final class IntArrayTag extends Tag {
checkNotNull(value); checkNotNull(value);
this.value = value; this.value = value;
} }
@Override @Override
public int[] getValue() { public int[] getValue() {
return this.value; return value;
} }
@Override @Override
public String toString() { public String toString() {
final StringBuilder hex = new StringBuilder(); final StringBuilder hex = new StringBuilder();
for (final int b : this.value) { for (final int b : value) {
final String hexDigits = Integer.toHexString(b).toUpperCase(); final String hexDigits = Integer.toHexString(b).toUpperCase();
if (hexDigits.length() == 1) { if (hexDigits.length() == 1) {
hex.append("0"); hex.append("0");
@ -49,7 +49,7 @@ public final class IntArrayTag extends Tag {
final String name = getName(); final String name = getName();
String append = ""; String append = "";
if ((name != null) && !name.equals("")) { if ((name != null) && !name.equals("")) {
append = "(\"" + this.getName() + "\")"; append = "(\"" + getName() + "\")";
} }
return "TAG_Int_Array" + append + ": " + hex; return "TAG_Int_Array" + append + ": " + hex;
} }

View File

@ -5,7 +5,7 @@ package com.intellectualcrafters.jnbt;
*/ */
public final class IntTag extends Tag { public final class IntTag extends Tag {
private final int value; private final int value;
/** /**
* Creates the tag with an empty name. * Creates the tag with an empty name.
* *
@ -15,7 +15,7 @@ public final class IntTag extends Tag {
super(); super();
this.value = value; this.value = value;
} }
/** /**
* Creates the tag. * Creates the tag.
* *
@ -26,19 +26,19 @@ public final class IntTag extends Tag {
super(name); super(name);
this.value = value; this.value = value;
} }
@Override @Override
public Integer getValue() { public Integer getValue() {
return this.value; return value;
} }
@Override @Override
public String toString() { public String toString() {
final String name = getName(); final String name = getName();
String append = ""; String append = "";
if ((name != null) && !name.equals("")) { if ((name != null) && !name.equals("")) {
append = "(\"" + this.getName() + "\")"; append = "(\"" + getName() + "\")";
} }
return "TAG_Int" + append + ": " + this.value; return "TAG_Int" + append + ": " + value;
} }
} }

View File

@ -6,14 +6,13 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
/** /**
* The {@code TAG_List} tag. * The {@code TAG_List} tag.
*/ */
public final class ListTag extends Tag { public final class ListTag extends Tag {
private final Class<? extends Tag> type; private final Class<? extends Tag> type;
private final List<Tag> value; private final List<Tag> value;
/** /**
* Creates the tag with an empty name. * Creates the tag with an empty name.
* *
@ -26,7 +25,7 @@ public final class ListTag extends Tag {
this.type = type; this.type = type;
this.value = Collections.unmodifiableList(value); this.value = Collections.unmodifiableList(value);
} }
/** /**
* Creates the tag. * Creates the tag.
* *
@ -40,21 +39,21 @@ public final class ListTag extends Tag {
this.type = type; this.type = type;
this.value = Collections.unmodifiableList(value); this.value = Collections.unmodifiableList(value);
} }
/** /**
* Gets the type of item in this list. * Gets the type of item in this list.
* *
* @return The type of item in this list. * @return The type of item in this list.
*/ */
public Class<? extends Tag> getType() { public Class<? extends Tag> getType() {
return this.type; return type;
} }
@Override @Override
public List<Tag> getValue() { public List<Tag> getValue() {
return this.value; return value;
} }
/** /**
* Create a new list tag with this tag's name and type. * Create a new list tag with this tag's name and type.
* *
@ -65,7 +64,7 @@ public final class ListTag extends Tag {
public ListTag setValue(final List<Tag> list) { public ListTag setValue(final List<Tag> list) {
return new ListTag(getName(), getType(), list); return new ListTag(getName(), getType(), list);
} }
/** /**
* Get the tag if it exists at the given index. * Get the tag if it exists at the given index.
* *
@ -75,12 +74,12 @@ public final class ListTag extends Tag {
*/ */
public Tag getIfExists(final int index) { public Tag getIfExists(final int index) {
try { try {
return this.value.get(index); return value.get(index);
} catch (final NoSuchElementException e) { } catch (final NoSuchElementException e) {
return null; return null;
} }
} }
/** /**
* Get a byte array named with the given index. <p> If the index does not exist or its value is not a byte * Get a byte array named with the given index. <p> If the index does not exist or its value is not a byte
* array tag, then an empty byte array will be returned. </p> * array tag, then an empty byte array will be returned. </p>
@ -97,7 +96,7 @@ public final class ListTag extends Tag {
return new byte[0]; return new byte[0];
} }
} }
/** /**
* Get a byte named with the given index. <p> If the index does not exist or its value is not a byte tag, then * Get a byte named with the given index. <p> If the index does not exist or its value is not a byte tag, then
* {@code 0} will be returned. </p> * {@code 0} will be returned. </p>
@ -114,7 +113,7 @@ public final class ListTag extends Tag {
return (byte) 0; return (byte) 0;
} }
} }
/** /**
* Get a double named with the given index. <p> If the index does not exist or its value is not a double tag, * Get a double named with the given index. <p> If the index does not exist or its value is not a double tag,
* then {@code 0} will be returned. </p> * then {@code 0} will be returned. </p>
@ -131,7 +130,7 @@ public final class ListTag extends Tag {
return 0; return 0;
} }
} }
/** /**
* Get a double named with the given index, even if it's another type of number. <p> If the index does not * Get a double named with the given index, even if it's another type of number. <p> If the index does not
* exist or its value is not a number, then {@code 0} will be returned. </p> * exist or its value is not a number, then {@code 0} will be returned. </p>
@ -158,7 +157,7 @@ public final class ListTag extends Tag {
return 0; return 0;
} }
} }
/** /**
* Get a float named with the given index. <p> If the index does not exist or its value is not a float tag, * Get a float named with the given index. <p> If the index does not exist or its value is not a float tag,
* then {@code 0} will be returned. </p> * then {@code 0} will be returned. </p>
@ -175,7 +174,7 @@ public final class ListTag extends Tag {
return 0; return 0;
} }
} }
/** /**
* Get a {@code int[]} named with the given index. <p> If the index does not exist or its value is not an int * Get a {@code int[]} named with the given index. <p> If the index does not exist or its value is not an int
* array tag, then an empty array will be returned. </p> * array tag, then an empty array will be returned. </p>
@ -192,7 +191,7 @@ public final class ListTag extends Tag {
return new int[0]; return new int[0];
} }
} }
/** /**
* Get an int named with the given index. <p> If the index does not exist or its value is not an int tag, then * Get an int named with the given index. <p> If the index does not exist or its value is not an int tag, then
* {@code 0} will be returned. </p> * {@code 0} will be returned. </p>
@ -209,7 +208,7 @@ public final class ListTag extends Tag {
return 0; return 0;
} }
} }
/** /**
* Get an int named with the given index, even if it's another type of number. <p> If the index does not exist * Get an int named with the given index, even if it's another type of number. <p> If the index does not exist
* or its value is not a number, then {@code 0} will be returned. </p> * or its value is not a number, then {@code 0} will be returned. </p>
@ -236,7 +235,7 @@ public final class ListTag extends Tag {
return 0; return 0;
} }
} }
/** /**
* Get a list of tags named with the given index. <p> If the index does not exist or its value is not a list * Get a list of tags named with the given index. <p> If the index does not exist or its value is not a list
* tag, then an empty list will be returned. </p> * tag, then an empty list will be returned. </p>
@ -253,7 +252,7 @@ public final class ListTag extends Tag {
return Collections.emptyList(); return Collections.emptyList();
} }
} }
/** /**
* Get a {@code TagList} named with the given index. <p> If the index does not exist or its value is not a list * Get a {@code TagList} named with the given index. <p> If the index does not exist or its value is not a list
* tag, then an empty tag list will be returned. </p> * tag, then an empty tag list will be returned. </p>
@ -270,7 +269,7 @@ public final class ListTag extends Tag {
return new ListTag(StringTag.class, Collections.<Tag> emptyList()); return new ListTag(StringTag.class, Collections.<Tag> emptyList());
} }
} }
/** /**
* Get a list of tags named with the given index. <p> If the index does not exist or its value is not a list * Get a list of tags named with the given index. <p> If the index does not exist or its value is not a list
* tag, then an empty list will be returned. If the given index references a list but the list of of a different * tag, then an empty list will be returned. If the given index references a list but the list of of a different
@ -296,7 +295,7 @@ public final class ListTag extends Tag {
return Collections.emptyList(); return Collections.emptyList();
} }
} }
/** /**
* Get a long named with the given index. <p> If the index does not exist or its value is not a long tag, then * Get a long named with the given index. <p> If the index does not exist or its value is not a long tag, then
* {@code 0} will be returned. </p> * {@code 0} will be returned. </p>
@ -313,7 +312,7 @@ public final class ListTag extends Tag {
return 0L; return 0L;
} }
} }
/** /**
* Get a long named with the given index, even if it's another type of number. <p> If the index does not exist * Get a long named with the given index, even if it's another type of number. <p> If the index does not exist
* or its value is not a number, then {@code 0} will be returned. </p> * or its value is not a number, then {@code 0} will be returned. </p>
@ -340,7 +339,7 @@ public final class ListTag extends Tag {
return 0; return 0;
} }
} }
/** /**
* Get a short named with the given index. <p> If the index does not exist or its value is not a short tag, * Get a short named with the given index. <p> If the index does not exist or its value is not a short tag,
* then {@code 0} will be returned. </p> * then {@code 0} will be returned. </p>
@ -357,7 +356,7 @@ public final class ListTag extends Tag {
return 0; return 0;
} }
} }
/** /**
* Get a string named with the given index. <p> If the index does not exist or its value is not a string tag, * Get a string named with the given index. <p> If the index does not exist or its value is not a string tag,
* then {@code ""} will be returned. </p> * then {@code ""} will be returned. </p>
@ -374,17 +373,17 @@ public final class ListTag extends Tag {
return ""; return "";
} }
} }
@Override @Override
public String toString() { public String toString() {
final String name = getName(); final String name = getName();
String append = ""; String append = "";
if ((name != null) && !name.equals("")) { if ((name != null) && !name.equals("")) {
append = "(\"" + this.getName() + "\")"; append = "(\"" + getName() + "\")";
} }
final StringBuilder bldr = new StringBuilder(); 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"); 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 : this.value) { for (final Tag t : value) {
bldr.append(" ").append(t.toString().replaceAll("\r\n", "\r\n ")).append("\r\n"); bldr.append(" ").append(t.toString().replaceAll("\r\n", "\r\n ")).append("\r\n");
} }
bldr.append("}"); bldr.append("}");

View File

@ -13,7 +13,7 @@ import java.util.List;
public class ListTagBuilder { public class ListTagBuilder {
private final Class<? extends Tag> type; private final Class<? extends Tag> type;
private final List<Tag> entries; private final List<Tag> entries;
/** /**
* Create a new instance. * Create a new instance.
* *
@ -22,12 +22,12 @@ public class ListTagBuilder {
ListTagBuilder(final Class<? extends Tag> type) { ListTagBuilder(final Class<? extends Tag> type) {
checkNotNull(type); checkNotNull(type);
this.type = type; this.type = type;
this.entries = new ArrayList<Tag>(); entries = new ArrayList<Tag>();
} }
/** /**
* Create a new builder instance. * Create a new builder instance.
* *
* @param type * @param type
* *
* @return a new builder * @return a new builder
@ -35,10 +35,10 @@ public class ListTagBuilder {
public static ListTagBuilder create(final Class<? extends Tag> type) { public static ListTagBuilder create(final Class<? extends Tag> type) {
return new ListTagBuilder(type); return new ListTagBuilder(type);
} }
/** /**
* Create a new builder instance. * Create a new builder instance.
* *
* @param entries * @param entries
* @param <T> * @param <T>
* *
@ -60,7 +60,7 @@ public class ListTagBuilder {
builder.addAll(Arrays.asList(entries)); builder.addAll(Arrays.asList(entries));
return builder; return builder;
} }
/** /**
* Add the given tag. * Add the given tag.
* *
@ -70,13 +70,13 @@ public class ListTagBuilder {
*/ */
public ListTagBuilder add(final Tag value) { public ListTagBuilder add(final Tag value) {
checkNotNull(value); checkNotNull(value);
if (!this.type.isInstance(value)) { if (!type.isInstance(value)) {
throw new IllegalArgumentException(value.getClass().getCanonicalName() + " is not of expected type " + this.type.getCanonicalName()); throw new IllegalArgumentException(value.getClass().getCanonicalName() + " is not of expected type " + type.getCanonicalName());
} }
this.entries.add(value); entries.add(value);
return this; return this;
} }
/** /**
* Add all the tags in the given list. * Add all the tags in the given list.
* *
@ -91,16 +91,16 @@ public class ListTagBuilder {
} }
return this; return this;
} }
/** /**
* Build an unnamed list tag with this builder's entries. * Build an unnamed list tag with this builder's entries.
* *
* @return the new list tag * @return the new list tag
*/ */
public ListTag build() { public ListTag build() {
return new ListTag(this.type, new ArrayList<Tag>(this.entries)); return new ListTag(type, new ArrayList<Tag>(entries));
} }
/** /**
* Build a new list tag with this builder's entries. * Build a new list tag with this builder's entries.
* *
@ -109,6 +109,6 @@ public class ListTagBuilder {
* @return the created list tag * @return the created list tag
*/ */
public ListTag build(final String name) { 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

@ -5,7 +5,7 @@ package com.intellectualcrafters.jnbt;
*/ */
public final class LongTag extends Tag { public final class LongTag extends Tag {
private final long value; private final long value;
/** /**
* Creates the tag with an empty name. * Creates the tag with an empty name.
* *
@ -15,7 +15,7 @@ public final class LongTag extends Tag {
super(); super();
this.value = value; this.value = value;
} }
/** /**
* Creates the tag. * Creates the tag.
* *
@ -26,19 +26,19 @@ public final class LongTag extends Tag {
super(name); super(name);
this.value = value; this.value = value;
} }
@Override @Override
public Long getValue() { public Long getValue() {
return this.value; return value;
} }
@Override @Override
public String toString() { public String toString() {
final String name = getName(); final String name = getName();
String append = ""; String append = "";
if ((name != null) && !name.equals("")) { if ((name != null) && !name.equals("")) {
append = "(\"" + this.getName() + "\")"; append = "(\"" + getName() + "\")";
} }
return "TAG_Long" + append + ": " + this.value; return "TAG_Long" + append + ": " + value;
} }
} }

View File

@ -21,20 +21,22 @@
package com.intellectualcrafters.jnbt; package com.intellectualcrafters.jnbt;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
/** /**
* A class which holds constant values. * A class which holds constant values.
*/ */
public final class NBTConstants { 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. * Default private constructor.
*/ */
private NBTConstants() { private NBTConstants() {}
}
/** /**
* Convert a type ID to its corresponding {@link Tag} class. * Convert a type ID to its corresponding {@link Tag} class.
* *

View File

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

View File

@ -29,7 +29,7 @@ import java.util.List;
/** /**
* <p> This class writes <strong>NBT</strong>, or <strong>Named Binary Tag</strong> <code>Tag</code> objects to an * <p> This class writes <strong>NBT</strong>, or <strong>Named Binary Tag</strong> <code>Tag</code> objects to an
* underlying <code>OutputStream</code>. </p> <p> The NBT format was created by Markus Persson, and the * underlying <code>OutputStream</code>. </p> <p> The NBT format was created by Markus Persson, and the
* specification may be found at * specification may be found at
* @linktourl http://www.minecraft.net/docs/NBT.txt * @linktourl http://www.minecraft.net/docs/NBT.txt
* </p> * </p>
* *
@ -40,7 +40,7 @@ public final class NBTOutputStream implements Closeable {
* The output stream. * The output stream.
*/ */
private final DataOutputStream os; private final DataOutputStream os;
/** /**
* Creates a new <code>NBTOutputStream</code>, which will write data to the specified underlying output stream. * Creates a new <code>NBTOutputStream</code>, which will write data to the specified underlying output stream.
* *
@ -48,10 +48,10 @@ public final class NBTOutputStream implements Closeable {
* *
* @throws IOException if an I/O error occurs. * @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); this.os = new DataOutputStream(os);
} }
/** /**
* Writes a tag. * Writes a tag.
* *
@ -63,15 +63,15 @@ public final class NBTOutputStream implements Closeable {
final int type = NBTUtils.getTypeCode(tag.getClass()); final int type = NBTUtils.getTypeCode(tag.getClass());
final String name = tag.getName(); final String name = tag.getName();
final byte[] nameBytes = name.getBytes(NBTConstants.CHARSET); final byte[] nameBytes = name.getBytes(NBTConstants.CHARSET);
this.os.writeByte(type); os.writeByte(type);
this.os.writeShort(nameBytes.length); os.writeShort(nameBytes.length);
this.os.write(nameBytes); os.write(nameBytes);
if (type == NBTConstants.TYPE_END) { if (type == NBTConstants.TYPE_END) {
throw new IOException("Named TAG_End not permitted."); throw new IOException("Named TAG_End not permitted.");
} }
writeTagPayload(tag); writeTagPayload(tag);
} }
/** /**
* Writes tag payload. * Writes tag payload.
* *
@ -122,7 +122,7 @@ public final class NBTOutputStream implements Closeable {
throw new IOException("Invalid tag type: " + type + "."); throw new IOException("Invalid tag type: " + type + ".");
} }
} }
/** /**
* Writes a <code>TAG_Byte</code> tag. * Writes a <code>TAG_Byte</code> tag.
* *
@ -131,9 +131,9 @@ public final class NBTOutputStream implements Closeable {
* @throws IOException if an I/O error occurs. * @throws IOException if an I/O error occurs.
*/ */
private void writeByteTagPayload(final ByteTag tag) throws IOException { private void writeByteTagPayload(final ByteTag tag) throws IOException {
this.os.writeByte(tag.getValue()); os.writeByte(tag.getValue());
} }
/** /**
* Writes a <code>TAG_Byte_Array</code> tag. * Writes a <code>TAG_Byte_Array</code> tag.
* *
@ -143,10 +143,10 @@ public final class NBTOutputStream implements Closeable {
*/ */
private void writeByteArrayTagPayload(final ByteArrayTag tag) throws IOException { private void writeByteArrayTagPayload(final ByteArrayTag tag) throws IOException {
final byte[] bytes = tag.getValue(); final byte[] bytes = tag.getValue();
this.os.writeInt(bytes.length); os.writeInt(bytes.length);
this.os.write(bytes); os.write(bytes);
} }
/** /**
* Writes a <code>TAG_Compound</code> tag. * Writes a <code>TAG_Compound</code> tag.
* *
@ -158,9 +158,9 @@ public final class NBTOutputStream implements Closeable {
for (final Tag childTag : tag.getValue().values()) { for (final Tag childTag : tag.getValue().values()) {
writeTag(childTag); writeTag(childTag);
} }
this.os.writeByte((byte) 0); // end tag - better way? os.writeByte((byte) 0); // end tag - better way?
} }
/** /**
* Writes a <code>TAG_List</code> tag. * Writes a <code>TAG_List</code> tag.
* *
@ -172,13 +172,13 @@ public final class NBTOutputStream implements Closeable {
final Class<? extends Tag> clazz = tag.getType(); final Class<? extends Tag> clazz = tag.getType();
final List<Tag> tags = tag.getValue(); final List<Tag> tags = tag.getValue();
final int size = tags.size(); final int size = tags.size();
this.os.writeByte(NBTUtils.getTypeCode(clazz)); os.writeByte(NBTUtils.getTypeCode(clazz));
this.os.writeInt(size); os.writeInt(size);
for (final Tag tag1 : tags) { for (final Tag tag1 : tags) {
writeTagPayload(tag1); writeTagPayload(tag1);
} }
} }
/** /**
* Writes a <code>TAG_String</code> tag. * Writes a <code>TAG_String</code> tag.
* *
@ -188,10 +188,10 @@ public final class NBTOutputStream implements Closeable {
*/ */
private void writeStringTagPayload(final StringTag tag) throws IOException { private void writeStringTagPayload(final StringTag tag) throws IOException {
final byte[] bytes = tag.getValue().getBytes(NBTConstants.CHARSET); final byte[] bytes = tag.getValue().getBytes(NBTConstants.CHARSET);
this.os.writeShort(bytes.length); os.writeShort(bytes.length);
this.os.write(bytes); os.write(bytes);
} }
/** /**
* Writes a <code>TAG_Double</code> tag. * Writes a <code>TAG_Double</code> tag.
* *
@ -200,9 +200,9 @@ public final class NBTOutputStream implements Closeable {
* @throws IOException if an I/O error occurs. * @throws IOException if an I/O error occurs.
*/ */
private void writeDoubleTagPayload(final DoubleTag tag) throws IOException { private void writeDoubleTagPayload(final DoubleTag tag) throws IOException {
this.os.writeDouble(tag.getValue()); os.writeDouble(tag.getValue());
} }
/** /**
* Writes a <code>TAG_Float</code> tag. * Writes a <code>TAG_Float</code> tag.
* *
@ -211,9 +211,9 @@ public final class NBTOutputStream implements Closeable {
* @throws IOException if an I/O error occurs. * @throws IOException if an I/O error occurs.
*/ */
private void writeFloatTagPayload(final FloatTag tag) throws IOException { private void writeFloatTagPayload(final FloatTag tag) throws IOException {
this.os.writeFloat(tag.getValue()); os.writeFloat(tag.getValue());
} }
/** /**
* Writes a <code>TAG_Long</code> tag. * Writes a <code>TAG_Long</code> tag.
* *
@ -222,9 +222,9 @@ public final class NBTOutputStream implements Closeable {
* @throws IOException if an I/O error occurs. * @throws IOException if an I/O error occurs.
*/ */
private void writeLongTagPayload(final LongTag tag) throws IOException { private void writeLongTagPayload(final LongTag tag) throws IOException {
this.os.writeLong(tag.getValue()); os.writeLong(tag.getValue());
} }
/** /**
* Writes a <code>TAG_Int</code> tag. * Writes a <code>TAG_Int</code> tag.
* *
@ -233,9 +233,9 @@ public final class NBTOutputStream implements Closeable {
* @throws IOException if an I/O error occurs. * @throws IOException if an I/O error occurs.
*/ */
private void writeIntTagPayload(final IntTag tag) throws IOException { private void writeIntTagPayload(final IntTag tag) throws IOException {
this.os.writeInt(tag.getValue()); os.writeInt(tag.getValue());
} }
/** /**
* Writes a <code>TAG_Short</code> tag. * Writes a <code>TAG_Short</code> tag.
* *
@ -244,9 +244,9 @@ public final class NBTOutputStream implements Closeable {
* @throws IOException if an I/O error occurs. * @throws IOException if an I/O error occurs.
*/ */
private void writeShortTagPayload(final ShortTag tag) throws IOException { private void writeShortTagPayload(final ShortTag tag) throws IOException {
this.os.writeShort(tag.getValue()); os.writeShort(tag.getValue());
} }
/** /**
* Writes a <code>TAG_Empty</code> tag. * Writes a <code>TAG_Empty</code> tag.
* *
@ -257,25 +257,25 @@ public final class NBTOutputStream implements Closeable {
private void writeEndTagPayload(final EndTag tag) { private void writeEndTagPayload(final EndTag tag) {
/* empty */ /* empty */
} }
private void writeIntArrayTagPayload(final IntArrayTag tag) throws IOException { private void writeIntArrayTagPayload(final IntArrayTag tag) throws IOException {
final int[] data = tag.getValue(); final int[] data = tag.getValue();
this.os.writeInt(data.length); os.writeInt(data.length);
for (final int element : data) { for (final int element : data) {
this.os.writeInt(element); os.writeInt(element);
} }
} }
@Override @Override
public void close() throws IOException { public void close() throws IOException {
this.os.close(); os.close();
} }
/** /**
* Flush output * Flush output
* @throws IOException * @throws IOException
*/ */
public void flush() throws IOException { public void flush() throws IOException {
this.os.flush(); os.flush();
} }
} }

View File

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

View File

@ -25,7 +25,7 @@ package com.intellectualcrafters.jnbt;
*/ */
public final class ShortTag extends Tag { public final class ShortTag extends Tag {
private final short value; private final short value;
/** /**
* Creates the tag with an empty name. * Creates the tag with an empty name.
* *
@ -35,7 +35,7 @@ public final class ShortTag extends Tag {
super(); super();
this.value = value; this.value = value;
} }
/** /**
* Creates the tag. * Creates the tag.
* *
@ -46,19 +46,19 @@ public final class ShortTag extends Tag {
super(name); super(name);
this.value = value; this.value = value;
} }
@Override @Override
public Short getValue() { public Short getValue() {
return this.value; return value;
} }
@Override @Override
public String toString() { public String toString() {
final String name = getName(); final String name = getName();
String append = ""; String append = "";
if ((name != null) && !name.equals("")) { if ((name != null) && !name.equals("")) {
append = "(\"" + this.getName() + "\")"; append = "(\"" + getName() + "\")";
} }
return "TAG_Short" + append + ": " + this.value; return "TAG_Short" + append + ": " + value;
} }
} }

View File

@ -7,7 +7,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
*/ */
public final class StringTag extends Tag { public final class StringTag extends Tag {
private final String value; private final String value;
/** /**
* Creates the tag with an empty name. * Creates the tag with an empty name.
* *
@ -18,7 +18,7 @@ public final class StringTag extends Tag {
checkNotNull(value); checkNotNull(value);
this.value = value; this.value = value;
} }
/** /**
* Creates the tag. * Creates the tag.
* *
@ -30,19 +30,19 @@ public final class StringTag extends Tag {
checkNotNull(value); checkNotNull(value);
this.value = value; this.value = value;
} }
@Override @Override
public String getValue() { public String getValue() {
return this.value; return value;
} }
@Override @Override
public String toString() { public String toString() {
final String name = getName(); final String name = getName();
String append = ""; String append = "";
if ((name != null) && !name.equals("")) { if ((name != null) && !name.equals("")) {
append = "(\"" + this.getName() + "\")"; append = "(\"" + getName() + "\")";
} }
return "TAG_String" + append + ": " + this.value; return "TAG_String" + append + ": " + value;
} }
} }

View File

@ -25,14 +25,14 @@ package com.intellectualcrafters.jnbt;
*/ */
public abstract class Tag { public abstract class Tag {
private final String name; private final String name;
/** /**
* Create a new tag with an empty name. * Create a new tag with an empty name.
*/ */
Tag() { Tag() {
this(""); this("");
} }
/** /**
* Creates the tag with the specified name. * Creates the tag with the specified name.
* *
@ -44,16 +44,16 @@ public abstract class Tag {
} }
this.name = name; this.name = name;
} }
/** /**
* Gets the name of this tag. * Gets the name of this tag.
* *
* @return the name of this tag * @return the name of this tag
*/ */
public final String getName() { public final String getName() {
return this.name; return name;
} }
/** /**
* Gets the value of this tag. * Gets the value of this tag.
* *

View File

@ -4,13 +4,13 @@ package com.intellectualcrafters.json;
* This provides static methods to convert comma delimited text into a JSONArray, and to covert a JSONArray into comma * This provides static methods to convert comma delimited text into a JSONArray, and to covert a JSONArray into comma
* delimited text. Comma delimited text is a very popular format for data interchange. It is understood by most * delimited text. Comma delimited text is a very popular format for data interchange. It is understood by most
* database, spreadsheet, and organizer programs. * database, spreadsheet, and organizer programs.
* *
* Each row of text represents a row in a table or a data record. Each row ends with a NEWLINE character. Each row * Each row of text represents a row in a table or a data record. Each row ends with a NEWLINE character. Each row
* contains one or more values. Values are separated by commas. A value can contain any character except for comma, * contains one or more values. Values are separated by commas. A value can contain any character except for comma,
* unless is is wrapped in single quotes or double quotes. * unless is is wrapped in single quotes or double quotes.
* *
* The first row usually contains the names of the columns. * The first row usually contains the names of the columns.
* *
* A comma delimited list can be converted into a JSONArray of JSONObjects. The names for the elements in the * A comma delimited list can be converted into a JSONArray of JSONObjects. The names for the elements in the
* JSONObjects can be taken from the names in the first row. * JSONObjects can be taken from the names in the first row.
* *
@ -60,7 +60,7 @@ public class CDL {
return x.nextTo(','); return x.nextTo(',');
} }
} }
/** /**
* Produce a JSONArray of strings from a row of comma delimited values. * Produce a JSONArray of strings from a row of comma delimited values.
* *
@ -75,7 +75,7 @@ public class CDL {
for (;;) { for (;;) {
final String value = getValue(x); final String value = getValue(x);
char c = x.next(); 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; return null;
} }
ja.put(value); ja.put(value);
@ -93,7 +93,7 @@ public class CDL {
} }
} }
} }
/** /**
* Produce a JSONObject from a row of comma delimited text, using a parallel JSONArray of strings to provides the * Produce a JSONObject from a row of comma delimited text, using a parallel JSONArray of strings to provides the
* names of the elements. * names of the elements.
@ -110,7 +110,7 @@ public class CDL {
final JSONArray ja = rowToJSONArray(x); final JSONArray ja = rowToJSONArray(x);
return ja != null ? ja.toJSONObject(names) : null; return ja != null ? ja.toJSONObject(names) : null;
} }
/** /**
* Produce a comma delimited text row from a JSONArray. Values containing the comma character will be quoted. * Produce a comma delimited text row from a JSONArray. Values containing the comma character will be quoted.
* Troublesome characters may be removed. * Troublesome characters may be removed.
@ -128,7 +128,8 @@ public class CDL {
final Object object = ja.opt(i); final Object object = ja.opt(i);
if (object != null) { if (object != null) {
final String string = object.toString(); 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('"'); sb.append('"');
final int length = string.length(); final int length = string.length();
for (int j = 0; j < length; j += 1) { for (int j = 0; j < length; j += 1) {
@ -146,7 +147,7 @@ public class CDL {
sb.append('\n'); sb.append('\n');
return sb.toString(); return sb.toString();
} }
/** /**
* Produce a JSONArray of JSONObjects from a comma delimited text string, using the first row as a source of names. * Produce a JSONArray of JSONObjects from a comma delimited text string, using the first row as a source of names.
* *
@ -159,7 +160,7 @@ public class CDL {
public static JSONArray toJSONArray(final String string) throws JSONException { public static JSONArray toJSONArray(final String string) throws JSONException {
return toJSONArray(new JSONTokener(string)); return toJSONArray(new JSONTokener(string));
} }
/** /**
* Produce a JSONArray of JSONObjects from a comma delimited text string, using the first row as a source of names. * Produce a JSONArray of JSONObjects from a comma delimited text string, using the first row as a source of names.
* *
@ -172,7 +173,7 @@ public class CDL {
public static JSONArray toJSONArray(final JSONTokener x) throws JSONException { public static JSONArray toJSONArray(final JSONTokener x) throws JSONException {
return toJSONArray(rowToJSONArray(x), x); return toJSONArray(rowToJSONArray(x), x);
} }
/** /**
* Produce a JSONArray of JSONObjects from a comma delimited text string using a supplied JSONArray as the source of * Produce a JSONArray of JSONObjects from a comma delimited text string using a supplied JSONArray as the source of
* element names. * element names.
@ -187,7 +188,7 @@ public class CDL {
public static JSONArray toJSONArray(final JSONArray names, final String string) throws JSONException { public static JSONArray toJSONArray(final JSONArray names, final String string) throws JSONException {
return toJSONArray(names, new JSONTokener(string)); return toJSONArray(names, new JSONTokener(string));
} }
/** /**
* Produce a JSONArray of JSONObjects from a comma delimited text string using a supplied JSONArray as the source of * Produce a JSONArray of JSONObjects from a comma delimited text string using a supplied JSONArray as the source of
* element names. * element names.
@ -216,7 +217,7 @@ public class CDL {
} }
return ja; return ja;
} }
/** /**
* Produce a comma delimited text from a JSONArray of JSONObjects. The first row will be a list of names obtained by * Produce a comma delimited text from a JSONArray of JSONObjects. The first row will be a list of names obtained by
* inspecting the first JSONObject. * inspecting the first JSONObject.
@ -237,7 +238,7 @@ public class CDL {
} }
return null; return null;
} }
/** /**
* Produce a comma delimited text from a JSONArray of JSONObjects using a provided list of names. The list of names * Produce a comma delimited text from a JSONArray of JSONObjects using a provided list of names. The list of names
* is not included in the output. * is not included in the output.

View File

@ -56,7 +56,7 @@ public class Cookie {
} }
return sb.toString(); return sb.toString();
} }
/** /**
* Convert a cookie specification string into a JSONObject. The string will contain a name value pair separated by * Convert a cookie specification string into a JSONObject. The string will contain a name value pair separated by
* '='. The name and the value will be unescaped, possibly converting '+' and '%' sequences. The cookie properties * '='. The name and the value will be unescaped, possibly converting '+' and '%' sequences. The cookie properties
@ -96,7 +96,7 @@ public class Cookie {
} }
return jo; return jo;
} }
/** /**
* Convert a JSONObject into a cookie specification string. The JSONObject must contain "name" and "value" members. * Convert a JSONObject into a cookie specification string. The JSONObject must contain "name" and "value" members.
* If the JSONObject contains "expires", "domain", "path", or "secure" members, they will be appended to the cookie * If the JSONObject contains "expires", "domain", "path", or "secure" members, they will be appended to the cookie
@ -130,7 +130,7 @@ public class Cookie {
} }
return sb.toString(); return sb.toString();
} }
/** /**
* Convert <code>%</code><i>hh</i> sequences to single characters, and convert plus to space. * Convert <code>%</code><i>hh</i> sequences to single characters, and convert plus to space.
* *

View File

@ -13,7 +13,7 @@ public class CookieList {
* Convert a cookie list into a JSONObject. A cookie list is a sequence of name/value pairs. The names are separated * Convert a cookie list into a JSONObject. A cookie list is a sequence of name/value pairs. The names are separated
* from the values by '='. The pairs are separated by ';'. The names and the values will be unescaped, possibly * from the values by '='. The pairs are separated by ';'. The names and the values will be unescaped, possibly
* converting '+' and '%' sequences. * converting '+' and '%' sequences.
* *
* To add a cookie to a cooklist, cookielistJSONObject.put(cookieJSONObject.getString("name"), * To add a cookie to a cooklist, cookielistJSONObject.put(cookieJSONObject.getString("name"),
* cookieJSONObject.getString("value")); * cookieJSONObject.getString("value"));
* *
@ -34,7 +34,7 @@ public class CookieList {
} }
return jo; return jo;
} }
/** /**
* Convert a JSONObject into a cookie list. A cookie list is a sequence of name/value pairs. The names are separated * Convert a JSONObject into a cookie list. A cookie list is a sequence of name/value pairs. The names are separated
* from the values by '='. The pairs are separated by ';'. The characters '%', '+', '=', and ';' in the names and * from the values by '='. The pairs are separated by ';'. The characters '%', '+', '=', and ';' in the names and

View File

@ -33,7 +33,7 @@ public class HTTP {
* Carriage return/line feed. * Carriage return/line feed.
*/ */
public static final String CRLF = "\r\n"; public static final String CRLF = "\r\n";
public static JSONObject toJSONObject(final String string) throws JSONException { public static JSONObject toJSONObject(final String string) throws JSONException {
final JSONObject jo = new JSONObject(); final JSONObject jo = new JSONObject();
final HTTPTokener x = new HTTPTokener(string); final HTTPTokener x = new HTTPTokener(string);
@ -60,11 +60,11 @@ public class HTTP {
} }
return jo; return jo;
} }
/** /**
* Convert a JSONObject into an HTTP header. A request header must contain * Convert a JSONObject into an HTTP header. A request header must contain
* *
* *
* <pre> * <pre>
* { * {
* Method: "POST" (for example), * Method: "POST" (for example),
@ -72,10 +72,10 @@ public class HTTP {
* "HTTP-Version": "HTTP/1.1" (for example) * "HTTP-Version": "HTTP/1.1" (for example)
* } * }
* </pre> * </pre>
* *
* A response header must contain * A response header must contain
* *
* *
* <pre> * <pre>
* { * {
* "HTTP-Version": "HTTP/1.1" (for example), * "HTTP-Version": "HTTP/1.1" (for example),
@ -83,7 +83,7 @@ public class HTTP {
* "Reason-Phrase": "OK" (for example) * "Reason-Phrase": "OK" (for example)
* } * }
* </pre> * </pre>
* *
* Any other members of the JSONObject will be output as HTTP fields. The result will end with two CRLF pairs. * Any other members of the JSONObject will be output as HTTP fields. The result will end with two CRLF pairs.
* *
* @param jo A JSONObject * @param jo A JSONObject

View File

@ -15,7 +15,7 @@ public class HTTPTokener extends JSONTokener {
public HTTPTokener(final String string) { public HTTPTokener(final String string) {
super(string); super(string);
} }
/** /**
* Get the next token or string. This is used in parsing HTTP headers. * Get the next token or string. This is used in parsing HTTP headers.
* *

View File

@ -34,16 +34,16 @@ import java.util.Map;
* accessing the values by index, and <code>put</code> methods for adding or replacing values. The values can be any of * accessing the values by index, and <code>put</code> methods for adding or replacing values. The values can be any of
* these types: <code>Boolean</code>, <code>JSONArray</code>, <code>JSONObject</code>, <code>Number</code>, * these types: <code>Boolean</code>, <code>JSONArray</code>, <code>JSONObject</code>, <code>Number</code>,
* <code>String</code>, or the <code>JSONObject.NULL object</code>. * <code>String</code>, or the <code>JSONObject.NULL object</code>.
* *
* The constructor can convert a JSON text into a Java object. The <code>toString</code> method converts to JSON text. * The constructor can convert a JSON text into a Java object. The <code>toString</code> method converts to JSON text.
* *
* A <code>get</code> method returns a value if one can be found, and throws an exception if one cannot be found. An * A <code>get</code> method returns a value if one can be found, and throws an exception if one cannot be found. An
* <code>opt</code> method returns a default value instead of throwing an exception, and so is useful for obtaining * <code>opt</code> method returns a default value instead of throwing an exception, and so is useful for obtaining
* optional values. * optional values.
* *
* The generic <code>get()</code> and <code>opt()</code> methods return an object which you can cast or query for type. * The generic <code>get()</code> and <code>opt()</code> methods return an object which you can cast or query for type.
* There are also typed <code>get</code> and <code>opt</code> methods that do type checking and type coercion for you. * There are also typed <code>get</code> and <code>opt</code> methods that do type checking and type coercion for you.
* *
* The texts produced by the <code>toString</code> methods strictly conform to JSON syntax rules. The constructors are * The texts produced by the <code>toString</code> methods strictly conform to JSON syntax rules. The constructors are
* more forgiving in the texts they will accept: <ul> <li>An extra <code>,</code>&nbsp;<small>(comma)</small> may appear * more forgiving in the texts they will accept: <ul> <li>An extra <code>,</code>&nbsp;<small>(comma)</small> may appear
* just before the closing bracket.</li> <li>The <code>null</code> value will be inserted when there is <code>,</code> * just before the closing bracket.</li> <li>The <code>null</code> value will be inserted when there is <code>,</code>
@ -61,14 +61,14 @@ public class JSONArray {
* The arrayList where the JSONArray's properties are kept. * The arrayList where the JSONArray's properties are kept.
*/ */
private final ArrayList<Object> myArrayList; private final ArrayList<Object> myArrayList;
/** /**
* Construct an empty JSONArray. * Construct an empty JSONArray.
*/ */
public JSONArray() { public JSONArray() {
this.myArrayList = new ArrayList<Object>(); myArrayList = new ArrayList<Object>();
} }
/** /**
* Construct a JSONArray from a JSONTokener. * Construct a JSONArray from a JSONTokener.
* *
@ -86,10 +86,10 @@ public class JSONArray {
for (;;) { for (;;) {
if (x.nextClean() == ',') { if (x.nextClean() == ',') {
x.back(); x.back();
this.myArrayList.add(JSONObject.NULL); myArrayList.add(JSONObject.NULL);
} else { } else {
x.back(); x.back();
this.myArrayList.add(x.nextValue()); myArrayList.add(x.nextValue());
} }
switch (x.nextClean()) { switch (x.nextClean()) {
case ',': case ',':
@ -106,7 +106,7 @@ public class JSONArray {
} }
} }
} }
/** /**
* Construct a JSONArray from a source JSON text. * Construct a JSONArray from a source JSON text.
* *
@ -118,21 +118,21 @@ public class JSONArray {
public JSONArray(final String source) throws JSONException { public JSONArray(final String source) throws JSONException {
this(new JSONTokener(source)); this(new JSONTokener(source));
} }
/** /**
* Construct a JSONArray from a Collection. * Construct a JSONArray from a Collection.
* *
* @param collection A Collection. * @param collection A Collection.
*/ */
public JSONArray(final Collection<Object> collection) { public JSONArray(final Collection<Object> collection) {
this.myArrayList = new ArrayList<Object>(); myArrayList = new ArrayList<Object>();
if (collection != null) { if (collection != null) {
for (final Object aCollection : collection) { for (final Object aCollection : collection) {
this.myArrayList.add(JSONObject.wrap(aCollection)); myArrayList.add(JSONObject.wrap(aCollection));
} }
} }
} }
/** /**
* Construct a JSONArray from an array * Construct a JSONArray from an array
* *
@ -149,7 +149,7 @@ public class JSONArray {
throw new JSONException("JSONArray initial value should be a string or collection or array."); throw new JSONException("JSONArray initial value should be a string or collection or array.");
} }
} }
/** /**
* Get the object value associated with an index. * Get the object value associated with an index.
* *
@ -160,13 +160,13 @@ public class JSONArray {
* @throws JSONException If there is no value for the index. * @throws JSONException If there is no value for the index.
*/ */
public Object get(final int index) throws JSONException { public Object get(final int index) throws JSONException {
final Object object = this.opt(index); final Object object = opt(index);
if (object == null) { if (object == null) {
throw new JSONException("JSONArray[" + index + "] not found."); throw new JSONException("JSONArray[" + index + "] not found.");
} }
return object; return object;
} }
/** /**
* Get the boolean value associated with an index. The string values "true" and "false" are converted to boolean. * Get the boolean value associated with an index. The string values "true" and "false" are converted to boolean.
* *
@ -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. * @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 { 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"))) { if (object.equals(Boolean.FALSE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("false"))) {
return false; return false;
} else if (object.equals(Boolean.TRUE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("true"))) { } else if (object.equals(Boolean.TRUE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("true"))) {
@ -185,7 +185,7 @@ public class JSONArray {
} }
throw new JSONException("JSONArray[" + index + "] is not a boolean."); throw new JSONException("JSONArray[" + index + "] is not a boolean.");
} }
/** /**
* Get the double value associated with an index. * Get the double value associated with an index.
* *
@ -196,14 +196,14 @@ public class JSONArray {
* @throws JSONException If the key is not found or if the value cannot be converted to a number. * @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 { public double getDouble(final int index) throws JSONException {
final Object object = this.get(index); final Object object = get(index);
try { try {
return object instanceof Number ? ((Number) object).doubleValue() : Double.parseDouble((String) object); 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."); throw new JSONException("JSONArray[" + index + "] is not a number.");
} }
} }
/** /**
* Get the int value associated with an index. * Get the int value associated with an index.
* *
@ -214,14 +214,14 @@ public class JSONArray {
* @throws JSONException If the key is not found or if the value is not a number. * @throws JSONException If the key is not found or if the value is not a number.
*/ */
public int getInt(final int index) throws JSONException { public int getInt(final int index) throws JSONException {
final Object object = this.get(index); final Object object = get(index);
try { try {
return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object); 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."); throw new JSONException("JSONArray[" + index + "] is not a number.");
} }
} }
/** /**
* Get the JSONArray associated with an index. * Get the JSONArray associated with an index.
* *
@ -232,13 +232,13 @@ public class JSONArray {
* @throws JSONException If there is no value for the index. or if the value is not a 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 { public JSONArray getJSONArray(final int index) throws JSONException {
final Object object = this.get(index); final Object object = get(index);
if (object instanceof JSONArray) { if (object instanceof JSONArray) {
return (JSONArray) object; return (JSONArray) object;
} }
throw new JSONException("JSONArray[" + index + "] is not a JSONArray."); throw new JSONException("JSONArray[" + index + "] is not a JSONArray.");
} }
/** /**
* Get the JSONObject associated with an index. * Get the JSONObject associated with an index.
* *
@ -249,13 +249,13 @@ public class JSONArray {
* @throws JSONException If there is no value for the index or if the value is not a JSONObject * @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 { public JSONObject getJSONObject(final int index) throws JSONException {
final Object object = this.get(index); final Object object = get(index);
if (object instanceof JSONObject) { if (object instanceof JSONObject) {
return (JSONObject) object; return (JSONObject) object;
} }
throw new JSONException("JSONArray[" + index + "] is not a JSONObject."); throw new JSONException("JSONArray[" + index + "] is not a JSONObject.");
} }
/** /**
* Get the long value associated with an index. * Get the long value associated with an index.
* *
@ -266,14 +266,14 @@ public class JSONArray {
* @throws JSONException If the key is not found or if the value cannot be converted to a number. * @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 { public long getLong(final int index) throws JSONException {
final Object object = this.get(index); final Object object = get(index);
try { try {
return object instanceof Number ? ((Number) object).longValue() : Long.parseLong((String) object); 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."); throw new JSONException("JSONArray[" + index + "] is not a number.");
} }
} }
/** /**
* Get the string associated with an index. * Get the string associated with an index.
* *
@ -284,13 +284,13 @@ public class JSONArray {
* @throws JSONException If there is no string value for the index. * @throws JSONException If there is no string value for the index.
*/ */
public String getString(final int index) throws JSONException { public String getString(final int index) throws JSONException {
final Object object = this.get(index); final Object object = get(index);
if (object instanceof String) { if (object instanceof String) {
return (String) object; return (String) object;
} }
throw new JSONException("JSONArray[" + index + "] not a string."); throw new JSONException("JSONArray[" + index + "] not a string.");
} }
/** /**
* Determine if the value is null. * Determine if the value is null.
* *
@ -299,9 +299,9 @@ public class JSONArray {
* @return true if the value at the index is null, or if there is no value. * @return true if the value at the index is null, or if there is no value.
*/ */
public boolean isNull(final int index) { public boolean isNull(final int index) {
return JSONObject.NULL.equals(this.opt(index)); return JSONObject.NULL.equals(opt(index));
} }
/** /**
* Make a string from the contents of this JSONArray. The <code>separator</code> string is inserted between each * Make a string from the contents of this JSONArray. The <code>separator</code> string is inserted between each
* element. Warning: This method assumes that the data structure is acyclical. * element. Warning: This method assumes that the data structure is acyclical.
@ -313,26 +313,26 @@ public class JSONArray {
* @throws JSONException If the array contains an invalid number. * @throws JSONException If the array contains an invalid number.
*/ */
public String join(final String separator) throws JSONException { public String join(final String separator) throws JSONException {
final int len = this.length(); final int len = length();
final StringBuilder sb = new StringBuilder(); final StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i += 1) { for (int i = 0; i < len; i += 1) {
if (i > 0) { if (i > 0) {
sb.append(separator); sb.append(separator);
} }
sb.append(JSONObject.valueToString(this.myArrayList.get(i))); sb.append(JSONObject.valueToString(myArrayList.get(i)));
} }
return sb.toString(); return sb.toString();
} }
/** /**
* Get the number of elements in the JSONArray, included nulls. * Get the number of elements in the JSONArray, included nulls.
* *
* @return The length (or size). * @return The length (or size).
*/ */
public int length() { public int length() {
return this.myArrayList.size(); return myArrayList.size();
} }
/** /**
* Get the optional object value associated with an index. * Get the optional object value associated with an index.
* *
@ -341,9 +341,9 @@ public class JSONArray {
* @return An object value, or null if there is no object at that index. * @return An object value, or null if there is no object at that index.
*/ */
public Object opt(final int 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);
} }
/** /**
* Get the optional boolean value associated with an index. It returns false if there is no value at that index, or * Get the optional boolean value associated with an index. It returns false if there is no value at that index, or
* if the value is not Boolean.TRUE or the String "true". * if the value is not Boolean.TRUE or the String "true".
@ -355,7 +355,7 @@ public class JSONArray {
public boolean optBoolean(final int index) { public boolean optBoolean(final int index) {
return this.optBoolean(index, false); return this.optBoolean(index, false);
} }
/** /**
* Get the optional boolean value associated with an index. It returns the defaultValue if there is no value at that * Get the optional boolean value associated with an index. It returns the defaultValue if there is no value at that
* index or if it is not a Boolean or the String "true" or "false" (case insensitive). * index or if it is not a Boolean or the String "true" or "false" (case insensitive).
@ -367,12 +367,12 @@ public class JSONArray {
*/ */
public boolean optBoolean(final int index, final boolean defaultValue) { public boolean optBoolean(final int index, final boolean defaultValue) {
try { try {
return this.getBoolean(index); return getBoolean(index);
} catch (final Exception e) { } catch (JSONException e) {
return defaultValue; return defaultValue;
} }
} }
/** /**
* Get the optional double value associated with an index. NaN is returned if there is no value for the index, or if * Get the optional double value associated with an index. NaN is returned if there is no value for the index, or if
* the value is not a number and cannot be converted to a number. * the value is not a number and cannot be converted to a number.
@ -384,7 +384,7 @@ public class JSONArray {
public double optDouble(final int index) { public double optDouble(final int index) {
return this.optDouble(index, Double.NaN); return this.optDouble(index, Double.NaN);
} }
/** /**
* Get the optional double value associated with an index. The defaultValue is returned if there is no value for the * Get the optional double value associated with an index. The defaultValue is returned if there is no value for the
* index, or if the value is not a number and cannot be converted to a number. * index, or if the value is not a number and cannot be converted to a number.
@ -396,12 +396,12 @@ public class JSONArray {
*/ */
public double optDouble(final int index, final double defaultValue) { public double optDouble(final int index, final double defaultValue) {
try { try {
return this.getDouble(index); return getDouble(index);
} catch (final Exception e) { } catch (JSONException e) {
return defaultValue; return defaultValue;
} }
} }
/** /**
* Get the optional int value associated with an index. Zero is returned if there is no value for the index, or if * Get the optional int value associated with an index. Zero is returned if there is no value for the index, or if
* the value is not a number and cannot be converted to a number. * the value is not a number and cannot be converted to a number.
@ -413,7 +413,7 @@ public class JSONArray {
public int optInt(final int index) { public int optInt(final int index) {
return this.optInt(index, 0); return this.optInt(index, 0);
} }
/** /**
* Get the optional int value associated with an index. The defaultValue is returned if there is no value for the * Get the optional int value associated with an index. The defaultValue is returned if there is no value for the
* index, or if the value is not a number and cannot be converted to a number. * index, or if the value is not a number and cannot be converted to a number.
@ -425,12 +425,12 @@ public class JSONArray {
*/ */
public int optInt(final int index, final int defaultValue) { public int optInt(final int index, final int defaultValue) {
try { try {
return this.getInt(index); return getInt(index);
} catch (final Exception e) { } catch (JSONException e) {
return defaultValue; return defaultValue;
} }
} }
/** /**
* Get the optional JSONArray associated with an index. * Get the optional JSONArray associated with an index.
* *
@ -439,10 +439,10 @@ public class JSONArray {
* @return A JSONArray value, or null if the index has no value, or if the value is not a 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) { public JSONArray optJSONArray(final int index) {
final Object o = this.opt(index); final Object o = opt(index);
return o instanceof JSONArray ? (JSONArray) o : null; return o instanceof JSONArray ? (JSONArray) o : null;
} }
/** /**
* Get the optional JSONObject associated with an index. Null is returned if the key is not found, or null if the * Get the optional JSONObject associated with an index. Null is returned if the key is not found, or null if the
* index has no value, or if the value is not a JSONObject. * index has no value, or if the value is not a JSONObject.
@ -452,10 +452,10 @@ public class JSONArray {
* @return A JSONObject value. * @return A JSONObject value.
*/ */
public JSONObject optJSONObject(final int index) { public JSONObject optJSONObject(final int index) {
final Object o = this.opt(index); final Object o = opt(index);
return o instanceof JSONObject ? (JSONObject) o : null; return o instanceof JSONObject ? (JSONObject) o : null;
} }
/** /**
* Get the optional long value associated with an index. Zero is returned if there is no value for the index, or if * Get the optional long value associated with an index. Zero is returned if there is no value for the index, or if
* the value is not a number and cannot be converted to a number. * the value is not a number and cannot be converted to a number.
@ -467,7 +467,7 @@ public class JSONArray {
public long optLong(final int index) { public long optLong(final int index) {
return this.optLong(index, 0); return this.optLong(index, 0);
} }
/** /**
* Get the optional long value associated with an index. The defaultValue is returned if there is no value for the * Get the optional long value associated with an index. The defaultValue is returned if there is no value for the
* index, or if the value is not a number and cannot be converted to a number. * index, or if the value is not a number and cannot be converted to a number.
@ -479,12 +479,12 @@ public class JSONArray {
*/ */
public long optLong(final int index, final long defaultValue) { public long optLong(final int index, final long defaultValue) {
try { try {
return this.getLong(index); return getLong(index);
} catch (final Exception e) { } catch (JSONException e) {
return defaultValue; return defaultValue;
} }
} }
/** /**
* Get the optional string value associated with an index. It returns an empty string if there is no value at that * Get the optional string value associated with an index. It returns an empty string if there is no value at that
* index. If the value is not a string and is not null, then it is coverted to a string. * index. If the value is not a string and is not null, then it is coverted to a string.
@ -496,7 +496,7 @@ public class JSONArray {
public String optString(final int index) { public String optString(final int index) {
return this.optString(index, ""); return this.optString(index, "");
} }
/** /**
* Get the optional string associated with an index. The defaultValue is returned if the key is not found. * Get the optional string associated with an index. The defaultValue is returned if the key is not found.
* *
@ -506,10 +506,10 @@ public class JSONArray {
* @return A String value. * @return A String value.
*/ */
public String optString(final int index, final String defaultValue) { 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(); return JSONObject.NULL.equals(object) ? defaultValue : object.toString();
} }
/** /**
* Append a boolean value. This increases the array's length by one. * Append a boolean value. This increases the array's length by one.
* *
@ -521,7 +521,7 @@ public class JSONArray {
this.put(value ? Boolean.TRUE : Boolean.FALSE); this.put(value ? Boolean.TRUE : Boolean.FALSE);
return this; return this;
} }
/** /**
* Put a value in the JSONArray, where the value will be a JSONArray which is produced from a Collection. * Put a value in the JSONArray, where the value will be a JSONArray which is produced from a Collection.
* *
@ -533,7 +533,7 @@ public class JSONArray {
this.put(new JSONArray(value)); this.put(new JSONArray(value));
return this; return this;
} }
/** /**
* Append a double value. This increases the array's length by one. * Append a double value. This increases the array's length by one.
* *
@ -549,7 +549,7 @@ public class JSONArray {
this.put(d); this.put(d);
return this; return this;
} }
/** /**
* Append an int value. This increases the array's length by one. * Append an int value. This increases the array's length by one.
* *
@ -561,7 +561,7 @@ public class JSONArray {
this.put(new Integer(value)); this.put(new Integer(value));
return this; return this;
} }
/** /**
* Append an long value. This increases the array's length by one. * Append an long value. This increases the array's length by one.
* *
@ -573,7 +573,7 @@ public class JSONArray {
this.put(new Long(value)); this.put(new Long(value));
return this; return this;
} }
/** /**
* Put a value in the JSONArray, where the value will be a JSONObject which is produced from a Map. * Put a value in the JSONArray, where the value will be a JSONObject which is produced from a Map.
* *
@ -585,7 +585,7 @@ public class JSONArray {
this.put(new JSONObject(value)); this.put(new JSONObject(value));
return this; return this;
} }
/** /**
* Append an object value. This increases the array's length by one. * Append an object value. This increases the array's length by one.
* *
@ -595,10 +595,10 @@ public class JSONArray {
* @return this. * @return this.
*/ */
public JSONArray put(final Object value) { public JSONArray put(final Object value) {
this.myArrayList.add(value); myArrayList.add(value);
return this; return this;
} }
/** /**
* Put or replace a boolean value in the JSONArray. If the index is greater than the length of the JSONArray, then * Put or replace a boolean value in the JSONArray. If the index is greater than the length of the JSONArray, then
* null elements will be added as necessary to pad it out. * null elements will be added as necessary to pad it out.
@ -614,7 +614,7 @@ public class JSONArray {
this.put(index, value ? Boolean.TRUE : Boolean.FALSE); this.put(index, value ? Boolean.TRUE : Boolean.FALSE);
return this; return this;
} }
/** /**
* Put a value in the JSONArray, where the value will be a JSONArray which is produced from a Collection. * Put a value in the JSONArray, where the value will be a JSONArray which is produced from a Collection.
* *
@ -629,7 +629,7 @@ public class JSONArray {
this.put(index, new JSONArray(value)); this.put(index, new JSONArray(value));
return this; return this;
} }
/** /**
* Put or replace a double value. If the index is greater than the length of the JSONArray, then null elements will * Put or replace a double value. If the index is greater than the length of the JSONArray, then null elements will
* be added as necessary to pad it out. * be added as necessary to pad it out.
@ -645,7 +645,7 @@ public class JSONArray {
this.put(index, new Double(value)); this.put(index, new Double(value));
return this; return this;
} }
/** /**
* Put or replace an int value. If the index is greater than the length of the JSONArray, then null elements will be * Put or replace an int value. If the index is greater than the length of the JSONArray, then null elements will be
* added as necessary to pad it out. * added as necessary to pad it out.
@ -661,7 +661,7 @@ public class JSONArray {
this.put(index, new Integer(value)); this.put(index, new Integer(value));
return this; return this;
} }
/** /**
* Put or replace a long value. If the index is greater than the length of the JSONArray, then null elements will be * Put or replace a long value. If the index is greater than the length of the JSONArray, then null elements will be
* added as necessary to pad it out. * added as necessary to pad it out.
@ -677,7 +677,7 @@ public class JSONArray {
this.put(index, new Long(value)); this.put(index, new Long(value));
return this; return this;
} }
/** /**
* Put a value in the JSONArray, where the value will be a JSONObject that is produced from a Map. * Put a value in the JSONArray, where the value will be a JSONObject that is produced from a Map.
* *
@ -692,7 +692,7 @@ public class JSONArray {
this.put(index, new JSONObject(value)); this.put(index, new JSONObject(value));
return this; return this;
} }
/** /**
* Put or replace an object value in the JSONArray. If the index is greater than the length of the JSONArray, then * Put or replace an object value in the JSONArray. If the index is greater than the length of the JSONArray, then
* null elements will be added as necessary to pad it out. * null elements will be added as necessary to pad it out.
@ -710,17 +710,17 @@ public class JSONArray {
if (index < 0) { if (index < 0) {
throw new JSONException("JSONArray[" + index + "] not found."); throw new JSONException("JSONArray[" + index + "] not found.");
} }
if (index < this.length()) { if (index < length()) {
this.myArrayList.set(index, value); myArrayList.set(index, value);
} else { } else {
while (index != this.length()) { while (index != length()) {
this.put(JSONObject.NULL); this.put(JSONObject.NULL);
} }
this.put(value); this.put(value);
} }
return this; return this;
} }
/** /**
* Remove an index and close the hole. * Remove an index and close the hole.
* *
@ -729,9 +729,9 @@ public class JSONArray {
* @return The value that was associated with the index, or null if there was no value. * @return The value that was associated with the index, or null if there was no value.
*/ */
public Object remove(final int index) { 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;
} }
/** /**
* Determine if two JSONArrays are similar. They must contain similar sequences. * Determine if two JSONArrays are similar. They must contain similar sequences.
* *
@ -743,12 +743,12 @@ public class JSONArray {
if (!(other instanceof JSONArray)) { if (!(other instanceof JSONArray)) {
return false; return false;
} }
final int len = this.length(); final int len = length();
if (len != ((JSONArray) other).length()) { if (len != ((JSONArray) other).length()) {
return false; return false;
} }
for (int i = 0; i < len; i += 1) { 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); final Object valueOther = ((JSONArray) other).get(i);
if (valueThis instanceof JSONObject) { if (valueThis instanceof JSONObject) {
if (!((JSONObject) valueThis).similar(valueOther)) { if (!((JSONObject) valueThis).similar(valueOther)) {
@ -764,7 +764,7 @@ public class JSONArray {
} }
return true; return true;
} }
/** /**
* Produce a JSONObject by combining a JSONArray of names with the values of this JSONArray. * Produce a JSONObject by combining a JSONArray of names with the values of this JSONArray.
* *
@ -775,21 +775,21 @@ public class JSONArray {
* @throws JSONException If any of the names are null. * @throws JSONException If any of the names are null.
*/ */
public JSONObject toJSONObject(final JSONArray names) throws JSONException { 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; return null;
} }
final JSONObject jo = new JSONObject(); final JSONObject jo = new JSONObject();
for (int i = 0; i < names.length(); i += 1) { 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; return jo;
} }
/** /**
* Make a JSON text of this JSONArray. For compactness, no unnecessary whitespace is added. If it is not possible to * Make a JSON text of this JSONArray. For compactness, no unnecessary whitespace is added. If it is not possible to
* produce a syntactically correct JSON text then null will be returned instead. This could occur if the array * produce a syntactically correct JSON text then null will be returned instead. This could occur if the array
* contains an invalid number. * contains an invalid number.
* *
* Warning: This method assumes that the data structure is acyclical. * Warning: This method assumes that the data structure is acyclical.
* *
* @return a printable, displayable, transmittable representation of the array. * @return a printable, displayable, transmittable representation of the array.
@ -798,11 +798,11 @@ public class JSONArray {
public String toString() { public String toString() {
try { try {
return this.toString(0); return this.toString(0);
} catch (final Exception e) { } catch (JSONException e) {
return null; return null;
} }
} }
/** /**
* Make a prettyprinted JSON text of this JSONArray. Warning: This method assumes that the data structure is * Make a prettyprinted JSON text of this JSONArray. Warning: This method assumes that the data structure is
* acyclical. * acyclical.
@ -821,10 +821,10 @@ public class JSONArray {
return this.write(sw, indentFactor, 0).toString(); return this.write(sw, indentFactor, 0).toString();
} }
} }
/** /**
* Write the contents of the JSONArray as JSON text to a writer. For compactness, no whitespace is added. * Write the contents of the JSONArray as JSON text to a writer. For compactness, no whitespace is added.
* *
* Warning: This method assumes that the data structure is acyclical. * Warning: This method assumes that the data structure is acyclical.
* *
* @return The writer. * @return The writer.
@ -834,10 +834,10 @@ public class JSONArray {
public Writer write(final Writer writer) throws JSONException { public Writer write(final Writer writer) throws JSONException {
return this.write(writer, 0, 0); return this.write(writer, 0, 0);
} }
/** /**
* Write the contents of the JSONArray as JSON text to a writer. For compactness, no whitespace is added. * Write the contents of the JSONArray as JSON text to a writer. For compactness, no whitespace is added.
* *
* Warning: This method assumes that the data structure is acyclical. * Warning: This method assumes that the data structure is acyclical.
* *
* @param indentFactor The number of spaces to add to each level of indentation. * @param indentFactor The number of spaces to add to each level of indentation.
@ -850,10 +850,10 @@ public class JSONArray {
Writer write(final Writer writer, final int indentFactor, final int indent) throws JSONException { Writer write(final Writer writer, final int indentFactor, final int indent) throws JSONException {
try { try {
boolean commanate = false; boolean commanate = false;
final int length = this.length(); final int length = length();
writer.write('['); writer.write('[');
if (length == 1) { if (length == 1) {
JSONObject.writeValue(writer, this.myArrayList.get(0), indentFactor, indent); JSONObject.writeValue(writer, myArrayList.get(0), indentFactor, indent);
} else if (length != 0) { } else if (length != 0) {
final int newindent = indent + indentFactor; final int newindent = indent + indentFactor;
for (int i = 0; i < length; i += 1) { for (int i = 0; i < length; i += 1) {
@ -864,7 +864,7 @@ public class JSONArray {
writer.write('\n'); writer.write('\n');
} }
JSONObject.indent(writer, newindent); JSONObject.indent(writer, newindent);
JSONObject.writeValue(writer, this.myArrayList.get(i), indentFactor, newindent); JSONObject.writeValue(writer, myArrayList.get(i), indentFactor, newindent);
commanate = true; commanate = true;
} }
if (indentFactor > 0) { if (indentFactor > 0) {

View File

@ -9,7 +9,7 @@ package com.intellectualcrafters.json;
public class JSONException extends RuntimeException { public class JSONException extends RuntimeException {
private static final long serialVersionUID = 0; private static final long serialVersionUID = 0;
private Throwable cause; private Throwable cause;
/** /**
* Constructs a JSONException with an explanatory message. * Constructs a JSONException with an explanatory message.
* *
@ -18,7 +18,7 @@ public class JSONException extends RuntimeException {
public JSONException(final String message) { public JSONException(final String message) {
super(message); super(message);
} }
/** /**
* Constructs a new JSONException with the specified cause. * Constructs a new JSONException with the specified cause.
* *
@ -28,7 +28,7 @@ public class JSONException extends RuntimeException {
super(cause.getMessage()); super(cause.getMessage());
this.cause = cause; this.cause = cause;
} }
/** /**
* Returns the cause of this exception or null if the cause is nonexistent or unknown. * Returns the cause of this exception or null if the cause is nonexistent or unknown.
* *
@ -36,6 +36,6 @@ public class JSONException extends RuntimeException {
*/ */
@Override @Override
public Throwable getCause() { public Throwable getCause() {
return this.cause; return cause;
} }
} }

View File

@ -183,7 +183,7 @@ public class JSONML {
} }
} }
} }
/** /**
* Convert a well-formed (but not necessarily valid) XML string into a JSONArray using the JsonML transform. Each * Convert a well-formed (but not necessarily valid) XML string into a JSONArray using the JsonML transform. Each
* XML tag is represented as a JSONArray in which the first element is the tag name. If the tag has attributes, then * XML tag is represented as a JSONArray in which the first element is the tag name. If the tag has attributes, then
@ -198,7 +198,7 @@ public class JSONML {
public static JSONArray toJSONArray(final String string) throws JSONException { public static JSONArray toJSONArray(final String string) throws JSONException {
return toJSONArray(new XMLTokener(string)); return toJSONArray(new XMLTokener(string));
} }
/** /**
* Convert a well-formed (but not necessarily valid) XML string into a JSONArray using the JsonML transform. Each * Convert a well-formed (but not necessarily valid) XML string into a JSONArray using the JsonML transform. Each
* XML tag is represented as a JSONArray in which the first element is the tag name. If the tag has attributes, then * XML tag is represented as a JSONArray in which the first element is the tag name. If the tag has attributes, then
@ -215,13 +215,13 @@ public class JSONML {
public static JSONArray toJSONArray(final XMLTokener x) throws JSONException { public static JSONArray toJSONArray(final XMLTokener x) throws JSONException {
return (JSONArray) parse(x, true, null); return (JSONArray) parse(x, true, null);
} }
/** /**
* Convert a well-formed (but not necessarily valid) XML string into a JSONObject using the JsonML transform. Each * Convert a well-formed (but not necessarily valid) XML string into a JSONObject using the JsonML transform. Each
* XML tag is represented as a JSONObject with a "tagName" property. If the tag has attributes, then the attributes * XML tag is represented as a JSONObject with a "tagName" property. If the tag has attributes, then the attributes
* will be in the JSONObject as properties. If the tag contains children, the object will have a "childNodes" * will be in the JSONObject as properties. If the tag contains children, the object will have a "childNodes"
* property which will be an array of strings and JsonML JSONObjects. * property which will be an array of strings and JsonML JSONObjects.
* *
* Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored. * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
* *
* @param x An XMLTokener of the XML source text. * @param x An XMLTokener of the XML source text.
@ -233,13 +233,13 @@ public class JSONML {
public static JSONObject toJSONObject(final XMLTokener x) throws JSONException { public static JSONObject toJSONObject(final XMLTokener x) throws JSONException {
return (JSONObject) parse(x, false, null); return (JSONObject) parse(x, false, null);
} }
/** /**
* Convert a well-formed (but not necessarily valid) XML string into a JSONObject using the JsonML transform. Each * Convert a well-formed (but not necessarily valid) XML string into a JSONObject using the JsonML transform. Each
* XML tag is represented as a JSONObject with a "tagName" property. If the tag has attributes, then the attributes * XML tag is represented as a JSONObject with a "tagName" property. If the tag has attributes, then the attributes
* will be in the JSONObject as properties. If the tag contains children, the object will have a "childNodes" * will be in the JSONObject as properties. If the tag contains children, the object will have a "childNodes"
* property which will be an array of strings and JsonML JSONObjects. * property which will be an array of strings and JsonML JSONObjects.
* *
* Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored. * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
* *
* @param string The XML source text. * @param string The XML source text.
@ -251,7 +251,7 @@ public class JSONML {
public static JSONObject toJSONObject(final String string) throws JSONException { public static JSONObject toJSONObject(final String string) throws JSONException {
return toJSONObject(new XMLTokener(string)); return toJSONObject(new XMLTokener(string));
} }
/** /**
* Reverse the JSONML transformation, making an XML text from a JSONArray. * Reverse the JSONML transformation, making an XML text from a JSONArray.
* *
@ -326,7 +326,7 @@ public class JSONML {
} }
return sb.toString(); return sb.toString();
} }
/** /**
* Reverse the JSONML transformation, making an XML text from a JSONObject. The JSONObject must contain a "tagName" * Reverse the JSONML transformation, making an XML text from a JSONObject. The JSONObject must contain a "tagName"
* property. If it has children, then it must have a "childNodes" property containing an array of objects. The other * property. If it has children, then it must have a "childNodes" property containing an array of objects. The other

View File

@ -4,6 +4,7 @@ import java.io.IOException;
import java.io.StringWriter; import java.io.StringWriter;
import java.io.Writer; import java.io.Writer;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.util.Collection; import java.util.Collection;
@ -27,21 +28,21 @@ import java.util.Set;
* values into a JSON text using the <code>put</code> and <code>toString</code> methods. A <code>get</code> method * values into a JSON text using the <code>put</code> and <code>toString</code> methods. A <code>get</code> method
* returns a value if one can be found, and throws an exception if one cannot be found. An <code>opt</code> method * returns a value if one can be found, and throws an exception if one cannot be found. An <code>opt</code> method
* returns a default value instead of throwing an exception, and so is useful for obtaining optional values. * returns a default value instead of throwing an exception, and so is useful for obtaining optional values.
* *
* The generic <code>get()</code> and <code>opt()</code> methods return an object, which you can cast or query for type. * The generic <code>get()</code> and <code>opt()</code> methods return an object, which you can cast or query for type.
* There are also typed <code>get</code> and <code>opt</code> methods that do type checking and type coercion for you. * There are also typed <code>get</code> and <code>opt</code> methods that do type checking and type coercion for you.
* The opt methods differ from the get methods in that they do not throw. Instead, they return a specified value, such * The opt methods differ from the get methods in that they do not throw. Instead, they return a specified value, such
* as null. * as null.
* *
* The <code>put</code> methods add or replace values in an object. For example, * The <code>put</code> methods add or replace values in an object. For example,
* *
* *
* <pre> * <pre>
* myString = new JSONObject().put(&quot;JSON&quot;, &quot;Hello, World!&quot;).toString(); * myString = new JSONObject().put(&quot;JSON&quot;, &quot;Hello, World!&quot;).toString();
* </pre> * </pre>
* *
* produces the string <code>{"JSON": "Hello, World"}</code>. * produces the string <code>{"JSON": "Hello, World"}</code>.
* *
* The texts produced by the <code>toString</code> methods strictly conform to the JSON syntax rules. The constructors * The texts produced by the <code>toString</code> methods strictly conform to the JSON syntax rules. The constructors
* are more forgiving in the texts they will accept: <ul> <li>An extra <code>,</code>&nbsp;<small>(comma)</small> may * are more forgiving in the texts they will accept: <ul> <li>An extra <code>,</code>&nbsp;<small>(comma)</small> may
* appear just before the closing brace.</li> <li>Strings may be quoted with <code>'</code>&nbsp;<small>(single * appear just before the closing brace.</li> <li>Strings may be quoted with <code>'</code>&nbsp;<small>(single
@ -64,14 +65,14 @@ public class JSONObject {
* The map where the JSONObject's properties are kept. * The map where the JSONObject's properties are kept.
*/ */
private final Map<String, Object> map; private final Map<String, Object> map;
/** /**
* Construct an empty JSONObject. * Construct an empty JSONObject.
*/ */
public JSONObject() { public JSONObject() {
this.map = new HashMap<String, Object>(); map = new HashMap<String, Object>();
} }
/** /**
* Construct a JSONObject from a subset of another JSONObject. An array of strings is used to identify the keys that * Construct a JSONObject from a subset of another JSONObject. An array of strings is used to identify the keys that
* should be copied. Missing keys are ignored. * should be copied. Missing keys are ignored.
@ -86,12 +87,12 @@ public class JSONObject {
this(); this();
for (final String name : names) { for (final String name : names) {
try { try {
this.putOnce(name, jo.opt(name)); putOnce(name, jo.opt(name));
} catch (final Exception ignore) { } catch (JSONException ignore) {
} }
} }
} }
/** /**
* Construct a JSONObject from a JSONTokener. * Construct a JSONObject from a JSONTokener.
* *
@ -122,7 +123,7 @@ public class JSONObject {
if (c != ':') { if (c != ':') {
throw x.syntaxError("Expected a ':' after a key"); throw x.syntaxError("Expected a ':' after a key");
} }
this.putOnce(key, x.nextValue()); putOnce(key, x.nextValue());
// Pairs are separated by ','. // Pairs are separated by ','.
switch (x.nextClean()) { switch (x.nextClean()) {
case ';': case ';':
@ -139,7 +140,7 @@ public class JSONObject {
} }
} }
} }
/** /**
* Construct a JSONObject from a Map. * Construct a JSONObject from a Map.
* *
@ -158,16 +159,16 @@ public class JSONObject {
} }
} }
} }
/** /**
* Construct a JSONObject from an Object using bean getters. It reflects on all of the public methods of the object. * Construct a JSONObject from an Object using bean getters. It reflects on all of the public methods of the object.
* For each of the methods with no parameters and a name starting with <code>"get"</code> or <code>"is"</code> * For each of the methods with no parameters and a name starting with <code>"get"</code> or <code>"is"</code>
* followed by an uppercase letter, the method is invoked, and a key and the value returned from the getter method * followed by an uppercase letter, the method is invoked, and a key and the value returned from the getter method
* are put into the new JSONObject. * are put into the new JSONObject.
* *
* The key is formed by removing the <code>"get"</code> or <code>"is"</code> prefix. If the second remaining * The key is formed by removing the <code>"get"</code> or <code>"is"</code> prefix. If the second remaining
* character is not upper case, then the first character is converted to lower case. * character is not upper case, then the first character is converted to lower case.
* *
* For example, if an object has a method named <code>"getName"</code>, and if the result of calling * For example, if an object has a method named <code>"getName"</code>, and if the result of calling
* <code>object.getName()</code> is <code>"Larry Fine"</code>, then the JSONObject will contain <code>"name": "Larry * <code>object.getName()</code> is <code>"Larry Fine"</code>, then the JSONObject will contain <code>"name": "Larry
* Fine"</code>. * Fine"</code>.
@ -176,9 +177,9 @@ public class JSONObject {
*/ */
public JSONObject(final Object bean) { public JSONObject(final Object bean) {
this(); this();
this.populateMap(bean); populateMap(bean);
} }
/** /**
* Construct a JSONObject from an Object, using reflection to find the public members. The resulting JSONObject's * Construct a JSONObject from an Object, using reflection to find the public members. The resulting JSONObject's
* keys will be the strings from the names array, and the values will be the field values associated with those keys * keys will be the strings from the names array, and the values will be the field values associated with those keys
@ -192,12 +193,12 @@ public class JSONObject {
final Class c = object.getClass(); final Class c = object.getClass();
for (final String name : names) { for (final String name : names) {
try { try {
this.putOpt(name, c.getField(name).get(object)); putOpt(name, c.getField(name).get(object));
} catch (final Exception ignore) { } catch (JSONException | SecurityException | NoSuchFieldException | IllegalArgumentException | IllegalAccessException ignore) {
} }
} }
} }
/** /**
* Construct a JSONObject from a source JSON text string. This is the most commonly used JSONObject constructor. * Construct a JSONObject from a source JSON text string. This is the most commonly used JSONObject constructor.
* *
@ -209,7 +210,7 @@ public class JSONObject {
public JSONObject(final String source) throws JSONException { public JSONObject(final String source) throws JSONException {
this(new JSONTokener(source)); this(new JSONTokener(source));
} }
/** /**
* Construct a JSONObject from a ResourceBundle. * Construct a JSONObject from a ResourceBundle.
* *
@ -247,7 +248,7 @@ public class JSONObject {
} }
} }
} }
/** /**
* Produce a string from a double. The string "null" will be returned if the number is not finite. * Produce a string from a double. The string "null" will be returned if the number is not finite.
* *
@ -271,7 +272,7 @@ public class JSONObject {
} }
return string; return string;
} }
/** /**
* Get an array of field names from a JSONObject. * Get an array of field names from a JSONObject.
* *
@ -291,7 +292,7 @@ public class JSONObject {
} }
return names; return names;
} }
/** /**
* Get an array of field names from an Object. * Get an array of field names from an Object.
* *
@ -313,7 +314,7 @@ public class JSONObject {
} }
return names; return names;
} }
/** /**
* Produce a string from a Number. * Produce a string from a Number.
* *
@ -340,7 +341,7 @@ public class JSONObject {
} }
return string; return string;
} }
/** /**
* Produce a string in double quotes with backslash sequences in all the right places. A backslash will be inserted * Produce a string in double quotes with backslash sequences in all the right places. A backslash will be inserted
* control character or an unescaped quote or backslash. * control character or an unescaped quote or backslash.
@ -360,9 +361,9 @@ public class JSONObject {
} }
} }
} }
public static Writer quote(final String string, final Writer w) throws IOException { 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("\"\""); w.write("\"\"");
return w; return w;
} }
@ -416,7 +417,7 @@ public class JSONObject {
w.write('"'); w.write('"');
return w; return w;
} }
/** /**
* Try to convert a string into a number, boolean, or null. If the string can't be converted, return the string. * Try to convert a string into a number, boolean, or null. If the string can't be converted, return the string.
* *
@ -460,12 +461,12 @@ public class JSONObject {
} }
} }
} }
} catch (final Exception ignore) { } catch (NumberFormatException ignore) {
} }
} }
return string; return string;
} }
/** /**
* Throw an exception if the object is a NaN or infinite number. * Throw an exception if the object is a NaN or infinite number.
* *
@ -486,7 +487,7 @@ public class JSONObject {
} }
} }
} }
/** /**
* Make a JSON text of an Object value. If the object has an value.toJSONString() method, then that method will be * Make a JSON text of an Object value. If the object has an value.toJSONString() method, then that method will be
* used to produce the JSON text. The method is required to produce a strictly conforming text. If the object does * used to produce the JSON text. The method is required to produce a strictly conforming text. If the object does
@ -494,8 +495,8 @@ public class JSONObject {
* If the value is an array or Collection, then a JSONArray will be made from it and its toJSONString method will be * If the value is an array or Collection, then a JSONArray will be made from it and its toJSONString method will be
* called. If the value is a MAP, then a JSONObject will be made from it and its toJSONString method will be called. * called. If the value is a MAP, then a JSONObject will be made from it and its toJSONString method will be called.
* Otherwise, the value's toString method will be called, and the result will be quoted. * Otherwise, the value's toString method will be called, and the result will be quoted.
* *
* *
* Warning: This method assumes that the data structure is acyclical. * Warning: This method assumes that the data structure is acyclical.
* *
* @param value The value to be serialized. * @param value The value to be serialized.
@ -517,7 +518,7 @@ public class JSONObject {
} catch (final Exception e) { } catch (final Exception e) {
throw new JSONException(e); throw new JSONException(e);
} }
if (object instanceof String) { if (object != null) {
return (String) object; return (String) object;
} }
throw new JSONException("Bad value from toJSONString: " + object); throw new JSONException("Bad value from toJSONString: " + object);
@ -539,7 +540,7 @@ public class JSONObject {
} }
return quote(value.toString()); return quote(value.toString());
} }
/** /**
* Wrap an object, if necessary. If the object is null, return the NULL object. If it is an array or collection, * Wrap an object, if necessary. If the object is null, return the NULL object. If it is an array or collection,
* wrap it in a JSONArray. If it is a map, wrap it in a JSONObject. If it is a standard property (Double, String, et * wrap it in a JSONArray. If it is a map, wrap it in a JSONObject. If it is a standard property (Double, String, et
@ -555,7 +556,19 @@ public class JSONObject {
if (object == null) { if (object == null) {
return 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; return object;
} }
if (object instanceof Collection) { if (object instanceof Collection) {
@ -573,11 +586,11 @@ public class JSONObject {
return object.toString(); return object.toString();
} }
return new JSONObject(object); return new JSONObject(object);
} catch (final Exception exception) { } catch (JSONException exception) {
return null; return null;
} }
} }
static final Writer writeValue(final Writer writer, final Object value, final int indentFactor, final int indent) throws JSONException, IOException { static final Writer writeValue(final Writer writer, final Object value, final int indentFactor, final int indent) throws JSONException, IOException {
if ((value == null) || value.equals(null)) { if ((value == null) || value.equals(null)) {
writer.write("null"); writer.write("null");
@ -608,18 +621,18 @@ public class JSONObject {
} }
return writer; return writer;
} }
static final void indent(final Writer writer, final int indent) throws IOException { static final void indent(final Writer writer, final int indent) throws IOException {
for (int i = 0; i < indent; i += 1) { for (int i = 0; i < indent; i += 1) {
writer.write(' '); writer.write(' ');
} }
} }
/** /**
* Accumulate values under a key. It is similar to the put method except that if there is already an object stored * Accumulate values under a key. It is similar to the put method except that if there is already an object stored
* under the key then a JSONArray is stored under the key to hold all of the accumulated values. If there is already * under the key then a JSONArray is stored under the key to hold all of the accumulated values. If there is already
* a JSONArray, then the new value is appended to it. In contrast, the put method replaces the previous value. * a JSONArray, then the new value is appended to it. In contrast, the put method replaces the previous value.
* *
* If only one value is accumulated that is not a JSONArray, then the result will be the same as using put. But if * If only one value is accumulated that is not a JSONArray, then the result will be the same as using put. But if
* multiple values are accumulated, then the result will be like append. * multiple values are accumulated, then the result will be like append.
* *
@ -632,7 +645,7 @@ public class JSONObject {
*/ */
public JSONObject accumulate(final String key, final Object value) throws JSONException { public JSONObject accumulate(final String key, final Object value) throws JSONException {
testValidity(value); testValidity(value);
final Object object = this.opt(key); final Object object = opt(key);
if (object == null) { if (object == null) {
this.put(key, value instanceof JSONArray ? new JSONArray().put(value) : value); this.put(key, value instanceof JSONArray ? new JSONArray().put(value) : value);
} else if (object instanceof JSONArray) { } else if (object instanceof JSONArray) {
@ -642,7 +655,7 @@ public class JSONObject {
} }
return this; return this;
} }
/** /**
* Append values to the array under a key. If the key does not exist in the JSONObject, then the key is put in the * Append values to the array under a key. If the key does not exist in the JSONObject, then the key is put in the
* JSONObject with its value being a JSONArray containing the value parameter. If the key was already associated * JSONObject with its value being a JSONArray containing the value parameter. If the key was already associated
@ -657,7 +670,7 @@ public class JSONObject {
*/ */
public JSONObject append(final String key, final Object value) throws JSONException { public JSONObject append(final String key, final Object value) throws JSONException {
testValidity(value); testValidity(value);
final Object object = this.opt(key); final Object object = opt(key);
if (object == null) { if (object == null) {
this.put(key, new JSONArray().put(value)); this.put(key, new JSONArray().put(value));
} else if (object instanceof JSONArray) { } else if (object instanceof JSONArray) {
@ -667,7 +680,7 @@ public class JSONObject {
} }
return this; return this;
} }
/** /**
* Get the value object associated with a key. * Get the value object associated with a key.
* *
@ -681,13 +694,13 @@ public class JSONObject {
if (key == null) { if (key == null) {
throw new JSONException("Null key."); throw new JSONException("Null key.");
} }
final Object object = this.opt(key); final Object object = opt(key);
if (object == null) { if (object == null) {
throw new JSONException("JSONObject[" + quote(key) + "] not found."); throw new JSONException("JSONObject[" + quote(key) + "] not found.");
} }
return object; return object;
} }
/** /**
* Get the boolean value associated with a key. * Get the boolean value associated with a key.
* *
@ -698,7 +711,7 @@ public class JSONObject {
* @throws JSONException if the value is not a Boolean or the String "true" or "false". * @throws JSONException if the value is not a Boolean or the String "true" or "false".
*/ */
public boolean getBoolean(final String key) throws JSONException { 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"))) { if (object.equals(Boolean.FALSE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("false"))) {
return false; return false;
} else if (object.equals(Boolean.TRUE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("true"))) { } else if (object.equals(Boolean.TRUE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("true"))) {
@ -706,7 +719,7 @@ public class JSONObject {
} }
throw new JSONException("JSONObject[" + quote(key) + "] is not a Boolean."); throw new JSONException("JSONObject[" + quote(key) + "] is not a Boolean.");
} }
/** /**
* Get the double value associated with a key. * Get the double value associated with a key.
* *
@ -718,14 +731,14 @@ public class JSONObject {
* number. * number.
*/ */
public double getDouble(final String key) throws JSONException { public double getDouble(final String key) throws JSONException {
final Object object = this.get(key); final Object object = get(key);
try { try {
return object instanceof Number ? ((Number) object).doubleValue() : Double.parseDouble((String) object); 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."); throw new JSONException("JSONObject[" + quote(key) + "] is not a number.");
} }
} }
/** /**
* Get the int value associated with a key. * Get the int value associated with a key.
* *
@ -736,14 +749,14 @@ public class JSONObject {
* @throws JSONException if the key is not found or if the value cannot be converted to an integer. * @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 { public int getInt(final String key) throws JSONException {
final Object object = this.get(key); final Object object = get(key);
try { try {
return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object); 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."); throw new JSONException("JSONObject[" + quote(key) + "] is not an int.");
} }
} }
/** /**
* Get the JSONArray value associated with a key. * Get the JSONArray value associated with a key.
* *
@ -754,13 +767,13 @@ public class JSONObject {
* @throws JSONException if the key is not found or if the value is not a JSONArray. * @throws JSONException if the key is not found or if the value is not a JSONArray.
*/ */
public JSONArray getJSONArray(final String key) throws JSONException { public JSONArray getJSONArray(final String key) throws JSONException {
final Object object = this.get(key); final Object object = get(key);
if (object instanceof JSONArray) { if (object instanceof JSONArray) {
return (JSONArray) object; return (JSONArray) object;
} }
throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONArray."); throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONArray.");
} }
/** /**
* Get the JSONObject value associated with a key. * Get the JSONObject value associated with a key.
* *
@ -771,13 +784,13 @@ public class JSONObject {
* @throws JSONException if the key is not found or if the value is not a 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 { public JSONObject getJSONObject(final String key) throws JSONException {
final Object object = this.get(key); final Object object = get(key);
if (object instanceof JSONObject) { if (object instanceof JSONObject) {
return (JSONObject) object; return (JSONObject) object;
} }
throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONObject."); throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONObject.");
} }
/** /**
* Get the long value associated with a key. * Get the long value associated with a key.
* *
@ -788,14 +801,14 @@ public class JSONObject {
* @throws JSONException if the key is not found or if the value cannot be converted to a long. * @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 { public long getLong(final String key) throws JSONException {
final Object object = this.get(key); final Object object = get(key);
try { try {
return object instanceof Number ? ((Number) object).longValue() : Long.parseLong((String) object); 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."); throw new JSONException("JSONObject[" + quote(key) + "] is not a long.");
} }
} }
/** /**
* Get the string associated with a key. * Get the string associated with a key.
* *
@ -806,13 +819,13 @@ public class JSONObject {
* @throws JSONException if there is no string value for the key. * @throws JSONException if there is no string value for the key.
*/ */
public String getString(final String key) throws JSONException { public String getString(final String key) throws JSONException {
final Object object = this.get(key); final Object object = get(key);
if (object instanceof String) { if (object instanceof String) {
return (String) object; return (String) object;
} }
throw new JSONException("JSONObject[" + quote(key) + "] not a string."); throw new JSONException("JSONObject[" + quote(key) + "] not a string.");
} }
/** /**
* Determine if the JSONObject contains a specific key. * Determine if the JSONObject contains a specific key.
* *
@ -821,9 +834,9 @@ public class JSONObject {
* @return true if the key exists in the JSONObject. * @return true if the key exists in the JSONObject.
*/ */
public boolean has(final String key) { public boolean has(final String key) {
return this.map.containsKey(key); return map.containsKey(key);
} }
/** /**
* Increment a property of a JSONObject. If there is no such property, create one with a value of 1. If there is * Increment a property of a JSONObject. If there is no such property, create one with a value of 1. If there is
* such a property, and if it is an Integer, Long, Double, or Float, then add one to it. * such a property, and if it is an Integer, Long, Double, or Float, then add one to it.
@ -836,7 +849,7 @@ public class JSONObject {
* Float. * Float.
*/ */
public JSONObject increment(final String key) throws JSONException { public JSONObject increment(final String key) throws JSONException {
final Object value = this.opt(key); final Object value = opt(key);
if (value == null) { if (value == null) {
this.put(key, 1); this.put(key, 1);
} else if (value instanceof Integer) { } else if (value instanceof Integer) {
@ -852,7 +865,7 @@ public class JSONObject {
} }
return this; return this;
} }
/** /**
* Determine if the value associated with the key is null or if there is no value. * Determine if the value associated with the key is null or if there is no value.
* *
@ -861,36 +874,36 @@ public class JSONObject {
* @return true if there is no value associated with the key or if the value is the JSONObject.NULL object. * @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) { public boolean isNull(final String key) {
return JSONObject.NULL.equals(this.opt(key)); return JSONObject.NULL.equals(opt(key));
} }
/** /**
* Get an enumeration of the keys of the JSONObject. * Get an enumeration of the keys of the JSONObject.
* *
* @return An iterator of the keys. * @return An iterator of the keys.
*/ */
public Iterator<String> keys() { public Iterator<String> keys() {
return this.keySet().iterator(); return keySet().iterator();
} }
/** /**
* Get a set of keys of the JSONObject. * Get a set of keys of the JSONObject.
* *
* @return A keySet. * @return A keySet.
*/ */
public Set<String> keySet() { public Set<String> keySet() {
return this.map.keySet(); return map.keySet();
} }
/** /**
* Get the number of keys stored in the JSONObject. * Get the number of keys stored in the JSONObject.
* *
* @return The number of keys in the JSONObject. * @return The number of keys in the JSONObject.
*/ */
public int length() { public int length() {
return this.map.size(); return map.size();
} }
/** /**
* Produce a JSONArray containing the names of the elements of this JSONObject. * Produce a JSONArray containing the names of the elements of this JSONObject.
* *
@ -898,13 +911,13 @@ public class JSONObject {
*/ */
public JSONArray names() { public JSONArray names() {
final JSONArray ja = new JSONArray(); final JSONArray ja = new JSONArray();
final Iterator<String> keys = this.keys(); final Iterator<String> keys = keys();
while (keys.hasNext()) { while (keys.hasNext()) {
ja.put(keys.next()); ja.put(keys.next());
} }
return ja.length() == 0 ? null : ja; return ja.length() == 0 ? null : ja;
} }
/** /**
* Get an optional value associated with a key. * Get an optional value associated with a key.
* *
@ -913,9 +926,9 @@ public class JSONObject {
* @return An object which is the value, or null if there is no value. * @return An object which is the value, or null if there is no value.
*/ */
public Object opt(final String key) { public Object opt(final String key) {
return key == null ? null : this.map.get(key); return key == null ? null : map.get(key);
} }
/** /**
* Get an optional boolean associated with a key. It returns false if there is no such key, or if the value is not * Get an optional boolean associated with a key. It returns false if there is no such key, or if the value is not
* Boolean.TRUE or the String "true". * Boolean.TRUE or the String "true".
@ -927,7 +940,7 @@ public class JSONObject {
public boolean optBoolean(final String key) { public boolean optBoolean(final String key) {
return this.optBoolean(key, false); return this.optBoolean(key, false);
} }
/** /**
* Get an optional boolean associated with a key. It returns the defaultValue if there is no such key, or if it is * Get an optional boolean associated with a key. It returns the defaultValue if there is no such key, or if it is
* not a Boolean or the String "true" or "false" (case insensitive). * not a Boolean or the String "true" or "false" (case insensitive).
@ -939,12 +952,12 @@ public class JSONObject {
*/ */
public boolean optBoolean(final String key, final boolean defaultValue) { public boolean optBoolean(final String key, final boolean defaultValue) {
try { try {
return this.getBoolean(key); return getBoolean(key);
} catch (final Exception e) { } catch (JSONException e) {
return defaultValue; return defaultValue;
} }
} }
/** /**
* Get an optional double associated with a key, or NaN if there is no such key or if its value is not a number. If * Get an optional double associated with a key, or NaN if there is no such key or if its value is not a number. If
* the value is a string, an attempt will be made to evaluate it as a number. * the value is a string, an attempt will be made to evaluate it as a number.
@ -956,7 +969,7 @@ public class JSONObject {
public double optDouble(final String key) { public double optDouble(final String key) {
return this.optDouble(key, Double.NaN); return this.optDouble(key, Double.NaN);
} }
/** /**
* Get an optional double associated with a key, or the defaultValue if there is no such key or if its value is not * Get an optional double associated with a key, or the defaultValue if there is no such key or if its value is not
* a number. If the value is a string, an attempt will be made to evaluate it as a number. * a number. If the value is a string, an attempt will be made to evaluate it as a number.
@ -968,12 +981,12 @@ public class JSONObject {
*/ */
public double optDouble(final String key, final double defaultValue) { public double optDouble(final String key, final double defaultValue) {
try { try {
return this.getDouble(key); return getDouble(key);
} catch (final Exception e) { } catch (JSONException e) {
return defaultValue; return defaultValue;
} }
} }
/** /**
* Get an optional int value associated with a key, or zero if there is no such key or if the value is not a number. * Get an optional int value associated with a key, or zero if there is no such key or if the value is not a number.
* If the value is a string, an attempt will be made to evaluate it as a number. * If the value is a string, an attempt will be made to evaluate it as a number.
@ -985,7 +998,7 @@ public class JSONObject {
public int optInt(final String key) { public int optInt(final String key) {
return this.optInt(key, 0); return this.optInt(key, 0);
} }
/** /**
* Get an optional int value associated with a key, or the default if there is no such key or if the value is not a * Get an optional int value associated with a key, or the default if there is no such key or if the value is not a
* number. If the value is a string, an attempt will be made to evaluate it as a number. * number. If the value is a string, an attempt will be made to evaluate it as a number.
@ -997,12 +1010,12 @@ public class JSONObject {
*/ */
public int optInt(final String key, final int defaultValue) { public int optInt(final String key, final int defaultValue) {
try { try {
return this.getInt(key); return getInt(key);
} catch (final Exception e) { } catch (JSONException e) {
return defaultValue; return defaultValue;
} }
} }
/** /**
* Get an optional JSONArray associated with a key. It returns null if there is no such key, or if its value is not * Get an optional JSONArray associated with a key. It returns null if there is no such key, or if its value is not
* a JSONArray. * a JSONArray.
@ -1012,10 +1025,10 @@ public class JSONObject {
* @return A JSONArray which is the value. * @return A JSONArray which is the value.
*/ */
public JSONArray optJSONArray(final String key) { public JSONArray optJSONArray(final String key) {
final Object o = this.opt(key); final Object o = opt(key);
return o instanceof JSONArray ? (JSONArray) o : null; return o instanceof JSONArray ? (JSONArray) o : null;
} }
/** /**
* Get an optional JSONObject associated with a key. It returns null if there is no such key, or if its value is not * Get an optional JSONObject associated with a key. It returns null if there is no such key, or if its value is not
* a JSONObject. * a JSONObject.
@ -1025,10 +1038,10 @@ public class JSONObject {
* @return A JSONObject which is the value. * @return A JSONObject which is the value.
*/ */
public JSONObject optJSONObject(final String key) { public JSONObject optJSONObject(final String key) {
final Object object = this.opt(key); final Object object = opt(key);
return object instanceof JSONObject ? (JSONObject) object : null; return object instanceof JSONObject ? (JSONObject) object : null;
} }
/** /**
* Get an optional long value associated with a key, or zero if there is no such key or if the value is not a * Get an optional long value associated with a key, or zero if there is no such key or if the value is not a
* number. If the value is a string, an attempt will be made to evaluate it as a number. * number. If the value is a string, an attempt will be made to evaluate it as a number.
@ -1040,7 +1053,7 @@ public class JSONObject {
public long optLong(final String key) { public long optLong(final String key) {
return this.optLong(key, 0); return this.optLong(key, 0);
} }
/** /**
* Get an optional long value associated with a key, or the default if there is no such key or if the value is not a * Get an optional long value associated with a key, or the default if there is no such key or if the value is not a
* number. If the value is a string, an attempt will be made to evaluate it as a number. * number. If the value is a string, an attempt will be made to evaluate it as a number.
@ -1052,12 +1065,12 @@ public class JSONObject {
*/ */
public long optLong(final String key, final long defaultValue) { public long optLong(final String key, final long defaultValue) {
try { try {
return this.getLong(key); return getLong(key);
} catch (final Exception e) { } catch (JSONException e) {
return defaultValue; return defaultValue;
} }
} }
/** /**
* Get an optional string associated with a key. It returns an empty string if there is no such key. If the value is * Get an optional string associated with a key. It returns an empty string if there is no such key. If the value is
* not a string and is not null, then it is converted to a string. * not a string and is not null, then it is converted to a string.
@ -1069,7 +1082,7 @@ public class JSONObject {
public String optString(final String key) { public String optString(final String key) {
return this.optString(key, ""); return this.optString(key, "");
} }
/** /**
* Get an optional string associated with a key. It returns the defaultValue if there is no such key. * Get an optional string associated with a key. It returns the defaultValue if there is no such key.
* *
@ -1079,10 +1092,10 @@ public class JSONObject {
* @return A string which is the value. * @return A string which is the value.
*/ */
public String optString(final String key, final String defaultValue) { 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(); return NULL.equals(object) ? defaultValue : object.toString();
} }
private void populateMap(final Object bean) { private void populateMap(final Object bean) {
final Class klass = bean.getClass(); final Class klass = bean.getClass();
// If klass is a System class then set includeSuperClass to false. // If klass is a System class then set includeSuperClass to false.
@ -1102,7 +1115,7 @@ public class JSONObject {
} else if (name.startsWith("is")) { } else if (name.startsWith("is")) {
key = name.substring(2); 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) { if (key.length() == 1) {
key = key.toLowerCase(); key = key.toLowerCase();
} else if (!Character.isUpperCase(key.charAt(1))) { } else if (!Character.isUpperCase(key.charAt(1))) {
@ -1110,15 +1123,15 @@ public class JSONObject {
} }
final Object result = method.invoke(bean, (Object[]) null); final Object result = method.invoke(bean, (Object[]) null);
if (result != null) { if (result != null) {
this.map.put(key, wrap(result)); map.put(key, wrap(result));
} }
} }
} }
} catch (final Exception ignore) { } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ignore) {
} }
} }
} }
/** /**
* Put a key/boolean pair in the JSONObject. * Put a key/boolean pair in the JSONObject.
* *
@ -1133,7 +1146,7 @@ public class JSONObject {
this.put(key, value ? Boolean.TRUE : Boolean.FALSE); this.put(key, value ? Boolean.TRUE : Boolean.FALSE);
return this; return this;
} }
/** /**
* Put a key/value pair in the JSONObject, where the value will be a JSONArray which is produced from a Collection. * Put a key/value pair in the JSONObject, where the value will be a JSONArray which is produced from a Collection.
* *
@ -1148,7 +1161,7 @@ public class JSONObject {
this.put(key, new JSONArray(value)); this.put(key, new JSONArray(value));
return this; return this;
} }
/** /**
* Put a key/double pair in the JSONObject. * Put a key/double pair in the JSONObject.
* *
@ -1163,7 +1176,7 @@ public class JSONObject {
this.put(key, new Double(value)); this.put(key, new Double(value));
return this; return this;
} }
/** /**
* Put a key/int pair in the JSONObject. * Put a key/int pair in the JSONObject.
* *
@ -1178,7 +1191,7 @@ public class JSONObject {
this.put(key, new Integer(value)); this.put(key, new Integer(value));
return this; return this;
} }
/** /**
* Put a key/long pair in the JSONObject. * Put a key/long pair in the JSONObject.
* *
@ -1193,7 +1206,7 @@ public class JSONObject {
this.put(key, new Long(value)); this.put(key, new Long(value));
return this; return this;
} }
/** /**
* Put a key/value pair in the JSONObject, where the value will be a JSONObject which is produced from a Map. * Put a key/value pair in the JSONObject, where the value will be a JSONObject which is produced from a Map.
* *
@ -1208,7 +1221,7 @@ public class JSONObject {
this.put(key, new JSONObject(value)); this.put(key, new JSONObject(value));
return this; return this;
} }
/** /**
* Put a key/value pair in the JSONObject. If the value is null, then the key will be removed from the JSONObject if * Put a key/value pair in the JSONObject. If the value is null, then the key will be removed from the JSONObject if
* it is present. * it is present.
@ -1227,13 +1240,13 @@ public class JSONObject {
} }
if (value != null) { if (value != null) {
testValidity(value); testValidity(value);
this.map.put(key, value); map.put(key, value);
} else { } else {
this.remove(key); remove(key);
} }
return this; return this;
} }
/** /**
* Put a key/value pair in the JSONObject, but only if the key and the value are both non-null, and only if there is * Put a key/value pair in the JSONObject, but only if the key and the value are both non-null, and only if there is
* not already a member with that name. * not already a member with that name.
@ -1247,14 +1260,14 @@ public class JSONObject {
*/ */
public JSONObject putOnce(final String key, final Object value) throws JSONException { public JSONObject putOnce(final String key, final Object value) throws JSONException {
if ((key != null) && (value != null)) { if ((key != null) && (value != null)) {
if (this.opt(key) != null) { if (opt(key) != null) {
throw new JSONException("Duplicate key \"" + key + "\""); throw new JSONException("Duplicate key \"" + key + "\"");
} }
this.put(key, value); this.put(key, value);
} }
return this; return this;
} }
/** /**
* Put a key/value pair in the JSONObject, but only if the key and the value are both non-null. * Put a key/value pair in the JSONObject, but only if the key and the value are both non-null.
* *
@ -1272,7 +1285,7 @@ public class JSONObject {
} }
return this; return this;
} }
/** /**
* Remove a name and its value, if present. * Remove a name and its value, if present.
* *
@ -1281,9 +1294,9 @@ public class JSONObject {
* @return The value that was associated with the name, or null if there was no value. * @return The value that was associated with the name, or null if there was no value.
*/ */
public Object remove(final String key) { public Object remove(final String key) {
return this.map.remove(key); return map.remove(key);
} }
/** /**
* Determine if two JSONObjects are similar. They must contain the same set of names which must be associated with * Determine if two JSONObjects are similar. They must contain the same set of names which must be associated with
* similar values. * similar values.
@ -1297,12 +1310,12 @@ public class JSONObject {
if (!(other instanceof JSONObject)) { if (!(other instanceof JSONObject)) {
return false; return false;
} }
final Set<String> set = this.keySet(); final Set<String> set = keySet();
if (!set.equals(((JSONObject) other).keySet())) { if (!set.equals(((JSONObject) other).keySet())) {
return false; return false;
} }
for (final String name : set) { for (final String name : set) {
final Object valueThis = this.get(name); final Object valueThis = get(name);
final Object valueOther = ((JSONObject) other).get(name); final Object valueOther = ((JSONObject) other).get(name);
if (valueThis instanceof JSONObject) { if (valueThis instanceof JSONObject) {
if (!((JSONObject) valueThis).similar(valueOther)) { if (!((JSONObject) valueThis).similar(valueOther)) {
@ -1321,7 +1334,7 @@ public class JSONObject {
return false; return false;
} }
} }
/** /**
* Produce a JSONArray containing the values of the members of this JSONObject. * Produce a JSONArray containing the values of the members of this JSONObject.
* *
@ -1338,15 +1351,15 @@ public class JSONObject {
} }
final JSONArray ja = new JSONArray(); final JSONArray ja = new JSONArray();
for (int i = 0; i < names.length(); i += 1) { for (int i = 0; i < names.length(); i += 1) {
ja.put(this.opt(names.getString(i))); ja.put(opt(names.getString(i)));
} }
return ja; return ja;
} }
/** /**
* Make a JSON text of this JSONObject. For compactness, no whitespace is added. If this would not result in a * Make a JSON text of this JSONObject. For compactness, no whitespace is added. If this would not result in a
* syntactically correct JSON text, then null will be returned instead. * syntactically correct JSON text, then null will be returned instead.
* *
* Warning: This method assumes that the data structure is acyclical. * Warning: This method assumes that the data structure is acyclical.
* *
* @return a printable, displayable, portable, transmittable representation of the object, beginning with * @return a printable, displayable, portable, transmittable representation of the object, beginning with
@ -1357,14 +1370,14 @@ public class JSONObject {
public String toString() { public String toString() {
try { try {
return this.toString(0); return this.toString(0);
} catch (final Exception e) { } catch (JSONException e) {
return null; return null;
} }
} }
/** /**
* Make a prettyprinted JSON text of this JSONObject. * Make a prettyprinted JSON text of this JSONObject.
* *
* Warning: This method assumes that the data structure is acyclical. * Warning: This method assumes that the data structure is acyclical.
* *
* @param indentFactor The number of spaces to add to each level of indentation. * @param indentFactor The number of spaces to add to each level of indentation.
@ -1381,10 +1394,10 @@ public class JSONObject {
return this.write(w, indentFactor, 0).toString(); return this.write(w, indentFactor, 0).toString();
} }
} }
/** /**
* Write the contents of the JSONObject as JSON text to a writer. For compactness, no whitespace is added. * Write the contents of the JSONObject as JSON text to a writer. For compactness, no whitespace is added.
* *
* Warning: This method assumes that the data structure is acyclical. * Warning: This method assumes that the data structure is acyclical.
* *
* @return The writer. * @return The writer.
@ -1394,10 +1407,10 @@ public class JSONObject {
public Writer write(final Writer writer) throws JSONException { public Writer write(final Writer writer) throws JSONException {
return this.write(writer, 0, 0); return this.write(writer, 0, 0);
} }
/** /**
* Write the contents of the JSONObject as JSON text to a writer. For compactness, no whitespace is added. * Write the contents of the JSONObject as JSON text to a writer. For compactness, no whitespace is added.
* *
* Warning: This method assumes that the data structure is acyclical. * Warning: This method assumes that the data structure is acyclical.
* *
* @return The writer. * @return The writer.
@ -1407,8 +1420,8 @@ public class JSONObject {
Writer write(final Writer writer, final int indentFactor, final int indent) throws JSONException { Writer write(final Writer writer, final int indentFactor, final int indent) throws JSONException {
try { try {
boolean commanate = false; boolean commanate = false;
final int length = this.length(); final int length = length();
final Iterator<String> keys = this.keys(); final Iterator<String> keys = keys();
writer.write('{'); writer.write('{');
if (length == 1) { if (length == 1) {
final Object key = keys.next(); final Object key = keys.next();
@ -1417,7 +1430,7 @@ public class JSONObject {
if (indentFactor > 0) { if (indentFactor > 0) {
writer.write(' '); writer.write(' ');
} }
writeValue(writer, this.map.get(key), indentFactor, indent); writeValue(writer, map.get(key), indentFactor, indent);
} else if (length != 0) { } else if (length != 0) {
final int newindent = indent + indentFactor; final int newindent = indent + indentFactor;
while (keys.hasNext()) { while (keys.hasNext()) {
@ -1434,7 +1447,7 @@ public class JSONObject {
if (indentFactor > 0) { if (indentFactor > 0) {
writer.write(' '); writer.write(' ');
} }
writeValue(writer, this.map.get(key), indentFactor, newindent); writeValue(writer, map.get(key), indentFactor, newindent);
commanate = true; commanate = true;
} }
if (indentFactor > 0) { if (indentFactor > 0) {
@ -1448,7 +1461,7 @@ public class JSONObject {
throw new JSONException(exception); throw new JSONException(exception);
} }
} }
/** /**
* JSONObject.NULL is equivalent to the value that JavaScript calls null, whilst Java's null is equivalent to the * JSONObject.NULL is equivalent to the value that JavaScript calls null, whilst Java's null is equivalent to the
* value that JavaScript calls undefined. * value that JavaScript calls undefined.
@ -1463,11 +1476,11 @@ public class JSONObject {
protected final Object clone() { protected final Object clone() {
try { try {
return super.clone(); return super.clone();
} catch (final Exception e) { } catch (CloneNotSupportedException e) {
return this; return this;
} }
} }
/** /**
* A Null object is equal to the null value and to itself. * A Null object is equal to the null value and to itself.
* *
@ -1479,7 +1492,7 @@ public class JSONObject {
public boolean equals(final Object object) { public boolean equals(final Object object) {
return (object == null) || (object == this); return (object == null) || (object == this);
} }
/** /**
* Get the "null" string value. * Get the "null" string value.
* *

View File

@ -6,28 +6,28 @@ import java.io.StringWriter;
* JSONStringer provides a quick and convenient way of producing JSON text. The texts produced strictly conform to JSON * JSONStringer provides a quick and convenient way of producing JSON text. The texts produced strictly conform to JSON
* syntax rules. No whitespace is added, so the results are ready for transmission or storage. Each instance of * syntax rules. No whitespace is added, so the results are ready for transmission or storage. Each instance of
* JSONStringer can produce one JSON text. * JSONStringer can produce one JSON text.
* *
* A JSONStringer instance provides a <code>value</code> method for appending values to the text, and a <code>key</code> * A JSONStringer instance provides a <code>value</code> method for appending values to the text, and a <code>key</code>
* method for adding keys before values in objects. There are <code>array</code> and <code>endArray</code> methods that * method for adding keys before values in objects. There are <code>array</code> and <code>endArray</code> methods that
* make and bound array values, and <code>object</code> and <code>endObject</code> methods which make and bound object * make and bound array values, and <code>object</code> and <code>endObject</code> methods which make and bound object
* values. All of these methods return the JSONWriter instance, permitting cascade style. For example, * values. All of these methods return the JSONWriter instance, permitting cascade style. For example,
* *
* *
* <pre> * <pre>
* myString = new JSONStringer().object().key(&quot;JSON&quot;).value(&quot;Hello, * myString = new JSONStringer().object().key(&quot;JSON&quot;).value(&quot;Hello,
* World!&quot;).endObject().toString(); * World!&quot;).endObject().toString();
* </pre> * </pre>
* *
* which produces the string * which produces the string
* *
* *
* <pre> * <pre>
* {"JSON":"Hello, World!"} * {"JSON":"Hello, World!"}
* </pre> * </pre>
* *
* The first method called must be <code>array</code> or <code>object</code>. There are no methods for adding commas or * The first method called must be <code>array</code> or <code>object</code>. There are no methods for adding commas or
* colons. JSONStringer adds them for you. Objects and arrays can be nested up to 20 levels deep. * colons. JSONStringer adds them for you. Objects and arrays can be nested up to 20 levels deep.
* *
* This can sometimes be easier than using a JSONObject to build a string. * This can sometimes be easier than using a JSONObject to build a string.
* *
* @author JSON.org * @author JSON.org
@ -40,7 +40,7 @@ public class JSONStringer extends JSONWriter {
public JSONStringer() { public JSONStringer() {
super(new StringWriter()); super(new StringWriter());
} }
/** /**
* Return the JSON text. This method is used to obtain the product of the JSONStringer instance. It will return * Return the JSON text. This method is used to obtain the product of the JSONStringer instance. It will return
* <code>null</code> if there was a problem in the construction of the JSON text (such as the calls to * <code>null</code> if there was a problem in the construction of the JSON text (such as the calls to
@ -50,6 +50,6 @@ public class JSONStringer extends JSONWriter {
*/ */
@Override @Override
public String toString() { public String toString() {
return this.mode == 'd' ? this.writer.toString() : null; return mode == 'd' ? writer.toString() : null;
} }
} }

View File

@ -22,7 +22,7 @@ public class JSONTokener {
private long line; private long line;
private char previous; private char previous;
private boolean usePrevious; private boolean usePrevious;
/** /**
* Construct a JSONTokener from a Reader. * Construct a JSONTokener from a Reader.
* *
@ -30,14 +30,14 @@ public class JSONTokener {
*/ */
public JSONTokener(final Reader reader) { public JSONTokener(final Reader reader) {
this.reader = reader.markSupported() ? reader : new BufferedReader(reader); this.reader = reader.markSupported() ? reader : new BufferedReader(reader);
this.eof = false; eof = false;
this.usePrevious = false; usePrevious = false;
this.previous = 0; previous = 0;
this.index = 0; index = 0;
this.character = 1; character = 1;
this.line = 1; line = 1;
} }
/** /**
* Construct a JSONTokener from an InputStream. * Construct a JSONTokener from an InputStream.
* *
@ -46,7 +46,7 @@ public class JSONTokener {
public JSONTokener(final InputStream inputStream) throws JSONException { public JSONTokener(final InputStream inputStream) throws JSONException {
this(new InputStreamReader(inputStream)); this(new InputStreamReader(inputStream));
} }
/** /**
* Construct a JSONTokener from a string. * Construct a JSONTokener from a string.
* *
@ -55,7 +55,7 @@ public class JSONTokener {
public JSONTokener(final String s) { public JSONTokener(final String s) {
this(new StringReader(s)); this(new StringReader(s));
} }
/** /**
* Get the hex value of a character (base16). * Get the hex value of a character (base16).
* *
@ -75,25 +75,25 @@ public class JSONTokener {
} }
return -1; return -1;
} }
/** /**
* Back up one character. This provides a sort of lookahead capability, so that you can test for a digit or letter * Back up one character. This provides a sort of lookahead capability, so that you can test for a digit or letter
* before attempting to parse the next number or identifier. * before attempting to parse the next number or identifier.
*/ */
public void back() throws JSONException { 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"); throw new JSONException("Stepping back two steps is not supported");
} }
this.index -= 1; index -= 1;
this.character -= 1; character -= 1;
this.usePrevious = true; usePrevious = true;
this.eof = false; eof = false;
} }
public boolean end() { public boolean end() {
return this.eof && !this.usePrevious; return eof && !usePrevious;
} }
/** /**
* Determine if the source string still contains characters that next() can consume. * Determine if the source string still contains characters that next() can consume.
* *
@ -101,13 +101,13 @@ public class JSONTokener {
*/ */
public boolean more() throws JSONException { public boolean more() throws JSONException {
this.next(); this.next();
if (this.end()) { if (end()) {
return false; return false;
} }
this.back(); back();
return true; return true;
} }
/** /**
* Get the next character in the source string. * Get the next character in the source string.
* *
@ -115,34 +115,34 @@ public class JSONTokener {
*/ */
public char next() throws JSONException { public char next() throws JSONException {
int c; int c;
if (this.usePrevious) { if (usePrevious) {
this.usePrevious = false; usePrevious = false;
c = this.previous; c = previous;
} else { } else {
try { try {
c = this.reader.read(); c = reader.read();
} catch (final IOException exception) { } catch (final IOException exception) {
throw new JSONException(exception); throw new JSONException(exception);
} }
if (c <= 0) { // End of stream if (c <= 0) { // End of stream
this.eof = true; eof = true;
c = 0; c = 0;
} }
} }
this.index += 1; index += 1;
if (this.previous == '\r') { if (previous == '\r') {
this.line += 1; line += 1;
this.character = c == '\n' ? 0 : 1; character = c == '\n' ? 0 : 1;
} else if (c == '\n') { } else if (c == '\n') {
this.line += 1; line += 1;
this.character = 0; character = 0;
} else { } else {
this.character += 1; character += 1;
} }
this.previous = (char) c; previous = (char) c;
return this.previous; return previous;
} }
/** /**
* Consume the next character, and check that it matches a specified character. * Consume the next character, and check that it matches a specified character.
* *
@ -155,11 +155,11 @@ public class JSONTokener {
public char next(final char c) throws JSONException { public char next(final char c) throws JSONException {
final char n = this.next(); final char n = this.next();
if (n != c) { if (n != c) {
throw this.syntaxError("Expected '" + c + "' and instead saw '" + n + "'"); throw syntaxError("Expected '" + c + "' and instead saw '" + n + "'");
} }
return n; return n;
} }
/** /**
* Get the next n characters. * Get the next n characters.
* *
@ -177,14 +177,14 @@ public class JSONTokener {
int pos = 0; int pos = 0;
while (pos < n) { while (pos < n) {
chars[pos] = this.next(); chars[pos] = this.next();
if (this.end()) { if (end()) {
throw this.syntaxError("Substring bounds error"); throw syntaxError("Substring bounds error");
} }
pos += 1; pos += 1;
} }
return new String(chars); return new String(chars);
} }
/** /**
* Get the next char in the string, skipping whitespace. * Get the next char in the string, skipping whitespace.
* *
@ -200,7 +200,7 @@ public class JSONTokener {
} }
} }
} }
/** /**
* Return the characters up to the next close quote character. Backslash processing is done. The formal JSON format * Return the characters up to the next close quote character. Backslash processing is done. The formal JSON format
* does not allow strings in single quotes, but an implementation is allowed to accept them. * does not allow strings in single quotes, but an implementation is allowed to accept them.
@ -221,7 +221,7 @@ public class JSONTokener {
case 0: case 0:
case '\n': case '\n':
case '\r': case '\r':
throw this.syntaxError("Unterminated string"); throw syntaxError("Unterminated string");
case '\\': case '\\':
c = this.next(); c = this.next();
switch (c) { switch (c) {
@ -250,7 +250,7 @@ public class JSONTokener {
sb.append(c); sb.append(c);
break; break;
default: default:
throw this.syntaxError("Illegal escape."); throw syntaxError("Illegal escape.");
} }
break; break;
default: default:
@ -261,7 +261,7 @@ public class JSONTokener {
} }
} }
} }
/** /**
* Get the text up but not including the specified character or the end of line, whichever comes first. * Get the text up but not including the specified character or the end of line, whichever comes first.
* *
@ -275,14 +275,14 @@ public class JSONTokener {
final char c = this.next(); final char c = this.next();
if ((c == delimiter) || (c == 0) || (c == '\n') || (c == '\r')) { if ((c == delimiter) || (c == 0) || (c == '\n') || (c == '\r')) {
if (c != 0) { if (c != 0) {
this.back(); back();
} }
return sb.toString().trim(); return sb.toString().trim();
} }
sb.append(c); sb.append(c);
} }
} }
/** /**
* Get the text up but not including one of the specified delimiter characters or the end of line, whichever comes * Get the text up but not including one of the specified delimiter characters or the end of line, whichever comes
* first. * first.
@ -298,14 +298,14 @@ public class JSONTokener {
c = this.next(); c = this.next();
if ((delimiters.indexOf(c) >= 0) || (c == 0) || (c == '\n') || (c == '\r')) { if ((delimiters.indexOf(c) >= 0) || (c == 0) || (c == '\n') || (c == '\r')) {
if (c != 0) { if (c != 0) {
this.back(); back();
} }
return sb.toString().trim(); return sb.toString().trim();
} }
sb.append(c); sb.append(c);
} }
} }
/** /**
* Get the next value. The value can be a Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the * Get the next value. The value can be a Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the
* JSONObject.NULL object. * JSONObject.NULL object.
@ -315,17 +315,17 @@ public class JSONTokener {
* @throws JSONException If syntax error. * @throws JSONException If syntax error.
*/ */
public Object nextValue() throws JSONException { public Object nextValue() throws JSONException {
char c = this.nextClean(); char c = nextClean();
String string; String string;
switch (c) { switch (c) {
case '"': case '"':
case '\'': case '\'':
return this.nextString(c); return nextString(c);
case '{': case '{':
this.back(); back();
return new JSONObject(this); return new JSONObject(this);
case '[': case '[':
this.back(); back();
return new JSONArray(this); return new JSONArray(this);
} }
/* /*
@ -340,14 +340,14 @@ public class JSONTokener {
sb.append(c); sb.append(c);
c = this.next(); c = this.next();
} }
this.back(); back();
string = sb.toString().trim(); string = sb.toString().trim();
if ("".equals(string)) { if ("".equals(string)) {
throw this.syntaxError("Missing value"); throw syntaxError("Missing value");
} }
return JSONObject.stringToValue(string); return JSONObject.stringToValue(string);
} }
/** /**
* Skip characters until the next character is the requested character. If the requested character is not found, no * Skip characters until the next character is the requested character. If the requested character is not found, no
* characters are skipped. * characters are skipped.
@ -359,27 +359,27 @@ public class JSONTokener {
public char skipTo(final char to) throws JSONException { public char skipTo(final char to) throws JSONException {
char c; char c;
try { try {
final long startIndex = this.index; final long startIndex = index;
final long startCharacter = this.character; final long startCharacter = character;
final long startLine = this.line; final long startLine = line;
this.reader.mark(1000000); reader.mark(1000000);
do { do {
c = this.next(); c = this.next();
if (c == 0) { if (c == 0) {
this.reader.reset(); reader.reset();
this.index = startIndex; index = startIndex;
this.character = startCharacter; character = startCharacter;
this.line = startLine; line = startLine;
return c; return c;
} }
} while (c != to); } while (c != to);
} catch (final IOException exception) { } catch (final IOException exception) {
throw new JSONException(exception); throw new JSONException(exception);
} }
this.back(); back();
return c; return c;
} }
/** /**
* Make a JSONException to signal a syntax error. * Make a JSONException to signal a syntax error.
* *
@ -388,9 +388,9 @@ public class JSONTokener {
* @return A JSONException object, suitable for throwing * @return A JSONException object, suitable for throwing
*/ */
public JSONException syntaxError(final String message) { public JSONException syntaxError(final String message) {
return new JSONException(message + this.toString()); return new JSONException(message + toString());
} }
/** /**
* Make a printable string of this JSONTokener. * Make a printable string of this JSONTokener.
* *
@ -398,6 +398,6 @@ public class JSONTokener {
*/ */
@Override @Override
public String toString() { public String toString() {
return " at " + this.index + " [character " + this.character + " line " + this.line + "]"; return " at " + index + " [character " + character + " line " + line + "]";
} }
} }

View File

@ -7,27 +7,27 @@ import java.io.Writer;
* JSONWriter provides a quick and convenient way of producing JSON text. The texts produced strictly conform to JSON * JSONWriter provides a quick and convenient way of producing JSON text. The texts produced strictly conform to JSON
* syntax rules. No whitespace is added, so the results are ready for transmission or storage. Each instance of * syntax rules. No whitespace is added, so the results are ready for transmission or storage. Each instance of
* JSONWriter can produce one JSON text. * JSONWriter can produce one JSON text.
* *
* A JSONWriter instance provides a <code>value</code> method for appending values to the text, and a <code>key</code> * A JSONWriter instance provides a <code>value</code> method for appending values to the text, and a <code>key</code>
* method for adding keys before values in objects. There are <code>array</code> and <code>endArray</code> methods that * method for adding keys before values in objects. There are <code>array</code> and <code>endArray</code> methods that
* make and bound array values, and <code>object</code> and <code>endObject</code> methods which make and bound object * make and bound array values, and <code>object</code> and <code>endObject</code> methods which make and bound object
* values. All of these methods return the JSONWriter instance, permitting a cascade style. For example, * values. All of these methods return the JSONWriter instance, permitting a cascade style. For example,
* *
* *
* <pre> * <pre>
* new JSONWriter(myWriter).object().key(&quot;JSON&quot;).value(&quot;Hello, World!&quot;).endObject(); * new JSONWriter(myWriter).object().key(&quot;JSON&quot;).value(&quot;Hello, World!&quot;).endObject();
* </pre> * </pre>
* *
* which writes * which writes
* *
* *
* <pre> * <pre>
* {"JSON":"Hello, World!"} * {"JSON":"Hello, World!"}
* </pre> * </pre>
* *
* The first method called must be <code>array</code> or <code>object</code>. There are no methods for adding commas or * The first method called must be <code>array</code> or <code>object</code>. There are no methods for adding commas or
* colons. JSONWriter adds them for you. Objects and arrays can be nested up to 20 levels deep. * colons. JSONWriter adds them for you. Objects and arrays can be nested up to 20 levels deep.
* *
* This can sometimes be easier than using a JSONObject to build a string. * This can sometimes be easier than using a JSONObject to build a string.
* *
* @author JSON.org * @author JSON.org
@ -55,18 +55,18 @@ public class JSONWriter {
* The stack top index. A value of 0 indicates that the stack is empty. * The stack top index. A value of 0 indicates that the stack is empty.
*/ */
private int top; private int top;
/** /**
* Make a fresh JSONWriter. It can be used to build one JSON text. * Make a fresh JSONWriter. It can be used to build one JSON text.
*/ */
public JSONWriter(final Writer w) { public JSONWriter(final Writer w) {
this.comma = false; comma = false;
this.mode = 'i'; mode = 'i';
this.stack = new JSONObject[maxdepth]; stack = new JSONObject[maxdepth];
this.top = 0; top = 0;
this.writer = w; writer = w;
} }
/** /**
* Append a value. * Append a value.
* *
@ -80,24 +80,24 @@ public class JSONWriter {
if (string == null) { if (string == null) {
throw new JSONException("Null pointer"); throw new JSONException("Null pointer");
} }
if ((this.mode == 'o') || (this.mode == 'a')) { if ((mode == 'o') || (mode == 'a')) {
try { try {
if (this.comma && (this.mode == 'a')) { if (comma && (mode == 'a')) {
this.writer.write(','); writer.write(',');
} }
this.writer.write(string); writer.write(string);
} catch (final IOException e) { } catch (final IOException e) {
throw new JSONException(e); throw new JSONException(e);
} }
if (this.mode == 'o') { if (mode == 'o') {
this.mode = 'k'; mode = 'k';
} }
this.comma = true; comma = true;
return this; return this;
} }
throw new JSONException("Value out of sequence."); throw new JSONException("Value out of sequence.");
} }
/** /**
* Begin appending a new array. All values until the balancing <code>endArray</code> will be appended to this array. * Begin appending a new array. All values until the balancing <code>endArray</code> will be appended to this array.
* The <code>endArray</code> method must be called to mark the array's end. * The <code>endArray</code> method must be called to mark the array's end.
@ -108,15 +108,15 @@ public class JSONWriter {
* a key or after the end of the outermost array or object). * a key or after the end of the outermost array or object).
*/ */
public JSONWriter array() throws JSONException { public JSONWriter array() throws JSONException {
if ((this.mode == 'i') || (this.mode == 'o') || (this.mode == 'a')) { if ((mode == 'i') || (mode == 'o') || (mode == 'a')) {
this.push(null); push(null);
this.append("["); append("[");
this.comma = false; comma = false;
return this; return this;
} }
throw new JSONException("Misplaced array."); throw new JSONException("Misplaced array.");
} }
/** /**
* End something. * End something.
* *
@ -131,16 +131,16 @@ public class JSONWriter {
if (this.mode != mode) { if (this.mode != mode) {
throw new JSONException(mode == 'a' ? "Misplaced endArray." : "Misplaced endObject."); throw new JSONException(mode == 'a' ? "Misplaced endArray." : "Misplaced endObject.");
} }
this.pop(mode); pop(mode);
try { try {
this.writer.write(c); writer.write(c);
} catch (final IOException e) { } catch (final IOException e) {
throw new JSONException(e); throw new JSONException(e);
} }
this.comma = true; comma = true;
return this; return this;
} }
/** /**
* End an array. This method most be called to balance calls to <code>array</code>. * End an array. This method most be called to balance calls to <code>array</code>.
* *
@ -149,9 +149,9 @@ public class JSONWriter {
* @throws JSONException If incorrectly nested. * @throws JSONException If incorrectly nested.
*/ */
public JSONWriter endArray() throws JSONException { public JSONWriter endArray() throws JSONException {
return this.end('a', ']'); return end('a', ']');
} }
/** /**
* End an object. This method most be called to balance calls to <code>object</code>. * End an object. This method most be called to balance calls to <code>object</code>.
* *
@ -160,9 +160,9 @@ public class JSONWriter {
* @throws JSONException If incorrectly nested. * @throws JSONException If incorrectly nested.
*/ */
public JSONWriter endObject() throws JSONException { public JSONWriter endObject() throws JSONException {
return this.end('k', '}'); return end('k', '}');
} }
/** /**
* Append a key. The key will be associated with the next value. In an object, every value must be preceded by a * Append a key. The key will be associated with the next value. In an object, every value must be preceded by a
* key. * key.
@ -178,16 +178,16 @@ public class JSONWriter {
if (string == null) { if (string == null) {
throw new JSONException("Null key."); throw new JSONException("Null key.");
} }
if (this.mode == 'k') { if (mode == 'k') {
try { try {
this.stack[this.top - 1].putOnce(string, Boolean.TRUE); stack[top - 1].putOnce(string, Boolean.TRUE);
if (this.comma) { if (comma) {
this.writer.write(','); writer.write(',');
} }
this.writer.write(JSONObject.quote(string)); writer.write(JSONObject.quote(string));
this.writer.write(':'); writer.write(':');
this.comma = false; comma = false;
this.mode = 'o'; mode = 'o';
return this; return this;
} catch (final IOException e) { } catch (final IOException e) {
throw new JSONException(e); throw new JSONException(e);
@ -195,7 +195,7 @@ public class JSONWriter {
} }
throw new JSONException("Misplaced key."); throw new JSONException("Misplaced key.");
} }
/** /**
* Begin appending a new object. All keys and values until the balancing <code>endObject</code> will be appended to * Begin appending a new object. All keys and values until the balancing <code>endObject</code> will be appended to
* this object. The <code>endObject</code> method must be called to mark the object's end. * this object. The <code>endObject</code> method must be called to mark the object's end.
@ -206,18 +206,18 @@ public class JSONWriter {
* a key or after the end of the outermost array or object). * a key or after the end of the outermost array or object).
*/ */
public JSONWriter object() throws JSONException { public JSONWriter object() throws JSONException {
if (this.mode == 'i') { if (mode == 'i') {
this.mode = 'o'; mode = 'o';
} }
if ((this.mode == 'o') || (this.mode == 'a')) { if ((mode == 'o') || (mode == 'a')) {
this.append("{"); append("{");
this.push(new JSONObject()); push(new JSONObject());
this.comma = false; comma = false;
return this; return this;
} }
throw new JSONException("Misplaced object."); throw new JSONException("Misplaced object.");
} }
/** /**
* Pop an array or object scope. * Pop an array or object scope.
* *
@ -226,17 +226,17 @@ public class JSONWriter {
* @throws JSONException If nesting is wrong. * @throws JSONException If nesting is wrong.
*/ */
private void pop(final char c) throws JSONException { private void pop(final char c) throws JSONException {
if (this.top <= 0) { if (top <= 0) {
throw new JSONException("Nesting error."); 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) { if (m != c) {
throw new JSONException("Nesting error."); throw new JSONException("Nesting error.");
} }
this.top -= 1; top -= 1;
this.mode = this.top == 0 ? 'd' : this.stack[this.top - 1] == null ? 'a' : 'k'; mode = top == 0 ? 'd' : stack[top - 1] == null ? 'a' : 'k';
} }
/** /**
* Push an array or object scope. * Push an array or object scope.
* *
@ -245,14 +245,14 @@ public class JSONWriter {
* @throws JSONException If nesting is too deep. * @throws JSONException If nesting is too deep.
*/ */
private void push(final JSONObject jo) throws JSONException { private void push(final JSONObject jo) throws JSONException {
if (this.top >= maxdepth) { if (top >= maxdepth) {
throw new JSONException("Nesting too deep."); throw new JSONException("Nesting too deep.");
} }
this.stack[this.top] = jo; stack[top] = jo;
this.mode = jo == null ? 'a' : 'k'; mode = jo == null ? 'a' : 'k';
this.top += 1; top += 1;
} }
/** /**
* Append either the value <code>true</code> or the value <code>false</code> . * Append either the value <code>true</code> or the value <code>false</code> .
* *
@ -263,9 +263,9 @@ public class JSONWriter {
* @throws JSONException * @throws JSONException
*/ */
public JSONWriter value(final boolean b) throws JSONException { public JSONWriter value(final boolean b) throws JSONException {
return this.append(b ? "true" : "false"); return append(b ? "true" : "false");
} }
/** /**
* Append a double value. * Append a double value.
* *
@ -278,7 +278,7 @@ public class JSONWriter {
public JSONWriter value(final double d) throws JSONException { public JSONWriter value(final double d) throws JSONException {
return this.value(new Double(d)); return this.value(new Double(d));
} }
/** /**
* Append a long value. * Append a long value.
* *
@ -289,9 +289,9 @@ public class JSONWriter {
* @throws JSONException * @throws JSONException
*/ */
public JSONWriter value(final long l) throws JSONException { public JSONWriter value(final long l) throws JSONException {
return this.append(Long.toString(l)); return append(Long.toString(l));
} }
/** /**
* Append an object value. * Append an object value.
* *
@ -303,6 +303,6 @@ public class JSONWriter {
* @throws JSONException If the value is out of sequence. * @throws JSONException If the value is out of sequence.
*/ */
public JSONWriter value(final Object object) throws JSONException { public JSONWriter value(final Object object) throws JSONException {
return this.append(JSONObject.valueToString(object)); return append(JSONObject.valueToString(object));
} }
} }

View File

@ -5,22 +5,22 @@ package com.intellectualcrafters.json;
* byte. The last byte of a character never has the MSB reset. Every byte that is not the last byte has the MSB set. Kim * byte. The last byte of a character never has the MSB reset. Every byte that is not the last byte has the MSB set. Kim
* stands for "Keep it minimal". A Unicode character is never longer than 3 bytes. Every byte contributes 7 bits to the * stands for "Keep it minimal". A Unicode character is never longer than 3 bytes. Every byte contributes 7 bits to the
* character. ASCII is unmodified. * character. ASCII is unmodified.
* *
* Kim UTF-8 one byte U+007F U+007F two bytes U+3FFF U+07FF three bytes U+10FFF U+FFFF four bytes U+10FFFF * Kim UTF-8 one byte U+007F U+007F two bytes U+3FFF U+07FF three bytes U+10FFF U+FFFF four bytes U+10FFFF
* *
* Characters in the ranges U+0800..U+3FFF and U+10000..U+10FFFF will be one byte smaller when encoded in Kim compared * Characters in the ranges U+0800..U+3FFF and U+10000..U+10FFFF will be one byte smaller when encoded in Kim compared
* to UTF-8. * to UTF-8.
* *
* Kim is beneficial when using scripts such as Old South Arabian, Aramaic, Avestan, Balinese, Batak, Bopomofo, * Kim is beneficial when using scripts such as Old South Arabian, Aramaic, Avestan, Balinese, Batak, Bopomofo,
* Buginese, Buhid, Carian, Cherokee, Coptic, Cyrillic, Deseret, Egyptian Hieroglyphs, Ethiopic, Georgian, Glagolitic, * Buginese, Buhid, Carian, Cherokee, Coptic, Cyrillic, Deseret, Egyptian Hieroglyphs, Ethiopic, Georgian, Glagolitic,
* Gothic, Hangul Jamo, Hanunoo, Hiragana, Kanbun, Kaithi, Kannada, Katakana, Kharoshthi, Khmer, Lao, Lepcha, Limbu, * Gothic, Hangul Jamo, Hanunoo, Hiragana, Kanbun, Kaithi, Kannada, Katakana, Kharoshthi, Khmer, Lao, Lepcha, Limbu,
* Lycian, Lydian, Malayalam, Mandaic, Meroitic, Miao, Mongolian, Myanmar, New Tai Lue, Ol Chiki, Old Turkic, Oriya, * Lycian, Lydian, Malayalam, Mandaic, Meroitic, Miao, Mongolian, Myanmar, New Tai Lue, Ol Chiki, Old Turkic, Oriya,
* Osmanya, Pahlavi, Parthian, Phags-Pa, Phoenician, Samaritan, Sharada, Sinhala, Sora Sompeng, Tagalog, Tagbanwa, * Osmanya, Pahlavi, Parthian, Phags-Pa, Phoenician, Samaritan, Sharada, Sinhala, Sora Sompeng, Tagalog, Tagbanwa,
* Takri, Tai Le, Tai Tham, Tamil, Telugu, Thai, Tibetan, Tifinagh, UCAS. * Takri, Tai Le, Tai Tham, Tamil, Telugu, Thai, Tibetan, Tifinagh, UCAS.
* *
* A kim object can be constructed from an ordinary UTF-16 string, or from a byte array. A kim object can produce a * A kim object can be constructed from an ordinary UTF-16 string, or from a byte array. A kim object can produce a
* UTF-16 string. * UTF-16 string.
* *
* As with UTF-8, it is possible to detect character boundaries within a byte sequence. UTF-8 is one of the world's * As with UTF-8, it is possible to detect character boundaries within a byte sequence. UTF-8 is one of the world's
* great inventions. While Kim is more efficient, it is not clear that it is worth the expense of transition. * great inventions. While Kim is more efficient, it is not clear that it is worth the expense of transition.
* *
@ -43,7 +43,7 @@ public class Kim {
* The memoization of toString(). * The memoization of toString().
*/ */
private String string = null; private String string = null;
/** /**
* Make a kim from a portion of a byte array. * Make a kim from a portion of a byte array.
* *
@ -57,20 +57,20 @@ public class Kim {
// modified Fletcher code. // modified Fletcher code.
int sum = 1; int sum = 1;
int value; int value;
this.hashcode = 0; hashcode = 0;
this.length = thru - from; length = thru - from;
if (this.length > 0) { if (length > 0) {
this.bytes = new byte[this.length]; this.bytes = new byte[length];
for (int at = 0; at < this.length; at += 1) { for (int at = 0; at < length; at += 1) {
value = bytes[at + from] & 0xFF; value = bytes[at + from] & 0xFF;
sum += value; sum += value;
this.hashcode += sum; hashcode += sum;
this.bytes[at] = (byte) value; this.bytes[at] = (byte) value;
} }
this.hashcode += sum << 16; hashcode += sum << 16;
} }
} }
/** /**
* Make a kim from a byte array. * Make a kim from a byte array.
* *
@ -80,7 +80,7 @@ public class Kim {
public Kim(final byte[] bytes, final int length) { public Kim(final byte[] bytes, final int length) {
this(bytes, 0, length); this(bytes, 0, length);
} }
/** /**
* Make a new kim from a substring of an existing kim. The coordinates are in byte units, not character units. * Make a new kim from a substring of an existing kim. The coordinates are in byte units, not character units.
* *
@ -91,7 +91,7 @@ public class Kim {
public Kim(final Kim kim, final int from, final int thru) { public Kim(final Kim kim, final int from, final int thru) {
this(kim.bytes, from, thru); this(kim.bytes, from, thru);
} }
/** /**
* Make a kim from a string. * Make a kim from a string.
* *
@ -101,17 +101,17 @@ public class Kim {
*/ */
public Kim(final String string) throws JSONException { public Kim(final String string) throws JSONException {
final int stringLength = string.length(); final int stringLength = string.length();
this.hashcode = 0; hashcode = 0;
this.length = 0; length = 0;
// First pass: Determine the length of the kim, allowing for the UTF-16 // 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. // to UTF-32 conversion, and then the UTF-32 to Kim conversion.
if (stringLength > 0) { if (stringLength > 0) {
for (int i = 0; i < stringLength; i += 1) { for (int i = 0; i < stringLength; i += 1) {
final int c = string.charAt(i); final int c = string.charAt(i);
if (c <= 0x7F) { if (c <= 0x7F) {
this.length += 1; length += 1;
} else if (c <= 0x3FFF) { } else if (c <= 0x3FFF) {
this.length += 2; length += 2;
} else { } else {
if ((c >= 0xD800) && (c <= 0xDFFF)) { if ((c >= 0xD800) && (c <= 0xDFFF)) {
i += 1; i += 1;
@ -120,33 +120,33 @@ public class Kim {
throw new JSONException("Bad UTF16"); throw new JSONException("Bad UTF16");
} }
} }
this.length += 3; length += 3;
} }
} }
// Second pass: Allocate a byte array and fill that array with the // Second pass: Allocate a byte array and fill that array with the
// conversion // conversion
// while computing the hashcode. // while computing the hashcode.
this.bytes = new byte[this.length]; bytes = new byte[length];
int at = 0; int at = 0;
int b; int b;
int sum = 1; int sum = 1;
for (int i = 0; i < stringLength; i += 1) { for (int i = 0; i < stringLength; i += 1) {
int character = string.charAt(i); int character = string.charAt(i);
if (character <= 0x7F) { if (character <= 0x7F) {
this.bytes[at] = (byte) character; bytes[at] = (byte) character;
sum += character; sum += character;
this.hashcode += sum; hashcode += sum;
at += 1; at += 1;
} else if (character <= 0x3FFF) { } else if (character <= 0x3FFF) {
b = 0x80 | (character >>> 7); b = 0x80 | (character >>> 7);
this.bytes[at] = (byte) b; bytes[at] = (byte) b;
sum += b; sum += b;
this.hashcode += sum; hashcode += sum;
at += 1; at += 1;
b = character & 0x7F; b = character & 0x7F;
this.bytes[at] = (byte) b; bytes[at] = (byte) b;
sum += b; sum += b;
this.hashcode += sum; hashcode += sum;
at += 1; at += 1;
} else { } else {
if ((character >= 0xD800) && (character <= 0xDBFF)) { if ((character >= 0xD800) && (character <= 0xDBFF)) {
@ -154,26 +154,26 @@ public class Kim {
character = (((character & 0x3FF) << 10) | (string.charAt(i) & 0x3FF)) + 65536; character = (((character & 0x3FF) << 10) | (string.charAt(i) & 0x3FF)) + 65536;
} }
b = 0x80 | (character >>> 14); b = 0x80 | (character >>> 14);
this.bytes[at] = (byte) b; bytes[at] = (byte) b;
sum += b; sum += b;
this.hashcode += sum; hashcode += sum;
at += 1; at += 1;
b = 0x80 | ((character >>> 7) & 0xFF); b = 0x80 | ((character >>> 7) & 0xFF);
this.bytes[at] = (byte) b; bytes[at] = (byte) b;
sum += b; sum += b;
this.hashcode += sum; hashcode += sum;
at += 1; at += 1;
b = character & 0x7F; b = character & 0x7F;
this.bytes[at] = (byte) b; bytes[at] = (byte) b;
sum += b; sum += b;
this.hashcode += sum; hashcode += sum;
at += 1; at += 1;
} }
} }
this.hashcode += sum << 16; hashcode += sum << 16;
} }
} }
/** /**
* Returns the number of bytes needed to contain the character in Kim format. * Returns the number of bytes needed to contain the character in Kim format.
* *
@ -189,7 +189,7 @@ public class Kim {
} }
return character <= 0x7F ? 1 : character <= 0x3FFF ? 2 : 3; return character <= 0x7F ? 1 : character <= 0x3FFF ? 2 : 3;
} }
/** /**
* Returns the character at the specified index. The index refers to byte values and ranges from 0 to length - 1. * Returns the character at the specified index. The index refers to byte values and ranges from 0 to length - 1.
* The index of the next character is at index + Kim.characterSize(kim.characterAt(index)). * The index of the next character is at index + Kim.characterSize(kim.characterAt(index)).
@ -220,7 +220,7 @@ public class Kim {
} }
throw new JSONException("Bad character at " + at); throw new JSONException("Bad character at " + at);
} }
/** /**
* Copy the contents of this kim to a byte array. * Copy the contents of this kim to a byte array.
* *
@ -230,10 +230,10 @@ public class Kim {
* @return The position immediately after the copy. * @return The position immediately after the copy.
*/ */
public int copy(final byte[] bytes, final int at) { public int copy(final byte[] bytes, final int at) {
System.arraycopy(this.bytes, 0, bytes, at, this.length); System.arraycopy(this.bytes, 0, bytes, at, length);
return at + this.length; return at + length;
} }
/** /**
* Two kim objects containing exactly the same bytes in the same order are equal to each other. * Two kim objects containing exactly the same bytes in the same order are equal to each other.
* *
@ -250,12 +250,12 @@ public class Kim {
if (this == that) { if (this == that) {
return true; return true;
} }
if (this.hashcode != that.hashcode) { if (hashcode != that.hashcode) {
return false; return false;
} }
return java.util.Arrays.equals(this.bytes, that.bytes); return java.util.Arrays.equals(bytes, that.bytes);
} }
/** /**
* Get a byte from a kim. * Get a byte from a kim.
* *
@ -266,20 +266,20 @@ public class Kim {
* @throws JSONException if there is no byte at that position. * @throws JSONException if there is no byte at that position.
*/ */
public int get(final int at) throws JSONException { 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); throw new JSONException("Bad character at " + at);
} }
return (this.bytes[at]) & 0xFF; return (bytes[at]) & 0xFF;
} }
/** /**
* Returns a hash code value for the kim. * Returns a hash code value for the kim.
*/ */
@Override @Override
public int hashCode() { public int hashCode() {
return this.hashcode; return hashcode;
} }
/** /**
* Produce a UTF-16 String from this kim. The number of codepoints in the string will not be greater than the number * Produce a UTF-16 String from this kim. The number of codepoints in the string will not be greater than the number
* of bytes in the kim, although it could be less. * of bytes in the kim, although it could be less.
@ -290,12 +290,12 @@ public class Kim {
*/ */
@Override @Override
public String toString() throws JSONException { public String toString() throws JSONException {
if (this.string == null) { if (string == null) {
int c; int c;
int length = 0; int length = 0;
final char chars[] = new char[this.length]; final char chars[] = new char[this.length];
for (int at = 0; at < this.length; at += characterSize(c)) { for (int at = 0; at < this.length; at += characterSize(c)) {
c = this.characterAt(at); c = characterAt(at);
if (c < 0x10000) { if (c < 0x10000) {
chars[length] = (char) c; chars[length] = (char) c;
length += 1; length += 1;
@ -306,8 +306,8 @@ public class Kim {
length += 1; length += 1;
} }
} }
this.string = new String(chars, 0, length); string = new String(chars, 0, length);
} }
return this.string; return string;
} }
} }

View File

@ -51,7 +51,7 @@ public class Property {
} }
return jo; return jo;
} }
/** /**
* Converts the JSONObject into a property file object. * Converts the JSONObject into a property file object.
* *

View File

@ -18,7 +18,7 @@ public class XML {
public static final Character QUEST = '?'; public static final Character QUEST = '?';
public static final Character QUOT = '"'; public static final Character QUOT = '"';
public static final Character SLASH = '/'; public static final Character SLASH = '/';
public static String escape(final String string) { public static String escape(final String string) {
final StringBuilder sb = new StringBuilder(string.length()); final StringBuilder sb = new StringBuilder(string.length());
for (int i = 0, length = string.length(); i < length; i++) { for (int i = 0, length = string.length(); i < length; i++) {
@ -45,7 +45,7 @@ public class XML {
} }
return sb.toString(); return sb.toString();
} }
/** /**
* Throw an exception if the string contains whitespace. Whitespace is not allowed in tagNames and attributes. * Throw an exception if the string contains whitespace. Whitespace is not allowed in tagNames and attributes.
* *
@ -65,7 +65,7 @@ public class XML {
} }
} }
} }
/** /**
* Scan the content following the named tag, attaching it to the context. * Scan the content following the named tag, attaching it to the context.
* *
@ -108,7 +108,7 @@ public class XML {
if ("CDATA".equals(token)) { if ("CDATA".equals(token)) {
if (x.next() == '[') { if (x.next() == '[') {
string = x.nextCDATA(); string = x.nextCDATA();
if (string.length() > 0) { if (!string.isEmpty()) {
context.accumulate("content", string); context.accumulate("content", string);
} }
return false; return false;
@ -192,7 +192,7 @@ public class XML {
return false; return false;
} else if (token instanceof String) { } else if (token instanceof String) {
string = (String) token; string = (String) token;
if (string.length() > 0) { if (!string.isEmpty()) {
jsonobject.accumulate("content", XML.stringToValue(string)); jsonobject.accumulate("content", XML.stringToValue(string));
} }
// Nested element // Nested element
@ -215,7 +215,7 @@ public class XML {
} }
} }
} }
/** /**
* Try to convert a string into a number, boolean, or null. If the string can't be converted, return the string. * Try to convert a string into a number, boolean, or null. If the string can't be converted, return the string.
* This is much less ambitious than JSONObject.stringToValue, especially because it does not attempt to convert plus * This is much less ambitious than JSONObject.stringToValue, especially because it does not attempt to convert plus
@ -235,9 +235,7 @@ public class XML {
if ("null".equalsIgnoreCase(string)) { if ("null".equalsIgnoreCase(string)) {
return JSONObject.NULL; return JSONObject.NULL;
} }
// If it might be a number, try converting it, first as a Long, and then //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.
// as a
// Double. If that doesn't work, return the string.
try { try {
final char initial = string.charAt(0); final char initial = string.charAt(0);
if ((initial == '-') || ((initial >= '0') && (initial <= '9'))) { if ((initial == '-') || ((initial >= '0') && (initial <= '9'))) {
@ -246,18 +244,18 @@ public class XML {
return value; return value;
} }
} }
} catch (final Exception ignore) { } catch (NumberFormatException ignore) {
try { try {
final Double value = new Double(string); final Double value = new Double(string);
if (value.toString().equals(string)) { if (value.toString().equals(string)) {
return value; return value;
} }
} catch (final Exception ignoreAlso) { } catch (NumberFormatException ignoreAlso) {
} }
} }
return string; return string;
} }
public static JSONObject toJSONObject(final String string) throws JSONException { public static JSONObject toJSONObject(final String string) throws JSONException {
final JSONObject jo = new JSONObject(); final JSONObject jo = new JSONObject();
final XMLTokener x = new XMLTokener(string); final XMLTokener x = new XMLTokener(string);
@ -266,7 +264,7 @@ public class XML {
} }
return jo; return jo;
} }
/** /**
* Convert a JSONObject into a well-formed, element-normal XML string. * Convert a JSONObject into a well-formed, element-normal XML string.
* *
@ -279,7 +277,7 @@ public class XML {
public static String toString(final Object object) throws JSONException { public static String toString(final Object object) throws JSONException {
return toString(object, null); return toString(object, null);
} }
/** /**
* Convert a JSONObject into a well-formed, element-normal XML string. * Convert a JSONObject into a well-formed, element-normal XML string.
* *
@ -381,7 +379,8 @@ public class XML {
return sb.toString(); return sb.toString();
} else { } else {
string = (object == null) ? "null" : escape(object.toString()); 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

@ -19,7 +19,7 @@ public class XMLTokener extends JSONTokener {
entity.put("lt", XML.LT); entity.put("lt", XML.LT);
entity.put("quot", XML.QUOT); entity.put("quot", XML.QUOT);
} }
/** /**
* Construct an XMLTokener from a string. * Construct an XMLTokener from a string.
* *
@ -28,7 +28,7 @@ public class XMLTokener extends JSONTokener {
public XMLTokener(final String s) { public XMLTokener(final String s) {
super(s); super(s);
} }
/** /**
* Get the text in the CDATA block. * Get the text in the CDATA block.
* *
@ -53,7 +53,7 @@ public class XMLTokener extends JSONTokener {
} }
} }
} }
/** /**
* Get the next XML outer token, trimming whitespace. There are two kinds of tokens: the '&lt;' character which begins * Get the next XML outer token, trimming whitespace. There are two kinds of tokens: the '&lt;' character which begins
* a markup tag, and the content text between markup tags. * a markup tag, and the content text between markup tags.
@ -88,7 +88,7 @@ public class XMLTokener extends JSONTokener {
c = next(); c = next();
} }
} }
/** /**
* Return the next entity. These entities are translated to Characters: <code>&amp; &quot; &gt; &lt; * Return the next entity. These entities are translated to Characters: <code>&amp; &quot; &gt; &lt;
* &quot;</code>. * &quot;</code>.
@ -115,7 +115,7 @@ public class XMLTokener extends JSONTokener {
final Object object = entity.get(string); final Object object = entity.get(string);
return object != null ? object : ampersand + string + ";"; return object != null ? object : ampersand + string + ";";
} }
/** /**
* Returns the next XML meta token. This is used for skipping over <!...> and <?...?> structures. * Returns the next XML meta token. This is used for skipping over <!...> and <?...?> structures.
* *
@ -179,7 +179,7 @@ public class XMLTokener extends JSONTokener {
} }
} }
} }
/** /**
* Get the next XML Token. These tokens are found inside of angle brackets. It may be one of these characters: * Get the next XML Token. These tokens are found inside of angle brackets. It may be one of these characters:
* <code>/ &gt;= ! ?</code> or it may be a string wrapped in single quotes or double quotes, or it may be a name. * <code>/ &gt;= ! ?</code> or it may be a string wrapped in single quotes or double quotes, or it may be a name.
@ -258,7 +258,7 @@ public class XMLTokener extends JSONTokener {
} }
} }
} }
/** /**
* Skip characters until past the requested string. If it is not found, we are left at the end of the source with a * Skip characters until past the requested string. If it is not found, we are left at the end of the source with a
* result of false. * result of false.

View File

@ -1,20 +1,24 @@
package com.intellectualcrafters.plot; package com.intellectualcrafters.plot;
import java.io.File; 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.HybridUtils;
import com.intellectualcrafters.plot.generator.PlotGenerator; import com.intellectualcrafters.plot.generator.IndependentPlotGenerator;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.AbstractTitle; 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.ChunkManager;
import com.intellectualcrafters.plot.util.EconHandler; import com.intellectualcrafters.plot.util.EconHandler;
import com.intellectualcrafters.plot.util.EventUtil; import com.intellectualcrafters.plot.util.EventUtil;
import com.intellectualcrafters.plot.util.InventoryUtil; import com.intellectualcrafters.plot.util.InventoryUtil;
import com.intellectualcrafters.plot.util.PlotQueue;
import com.intellectualcrafters.plot.util.SchematicHandler; import com.intellectualcrafters.plot.util.SchematicHandler;
import com.intellectualcrafters.plot.util.SetupUtils; import com.intellectualcrafters.plot.util.SetupUtils;
import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandlerImplementation; import com.intellectualcrafters.plot.util.UUIDHandlerImplementation;
import com.intellectualcrafters.plot.util.WorldUtil;
public interface IPlotMain { public interface IPlotMain {
@ -22,27 +26,33 @@ public interface IPlotMain {
* Log a message to console * Log a message to console
* @param message * @param message
*/ */
void log(String message); void log(final String message);
/** /**
* Get the `PlotSquared` directory (e.g. /plugins/PlotSquared or /mods/PlotSquared) * Get the `PlotSquared` directory (e.g. /plugins/PlotSquared or /mods/PlotSquared)
* @return * @return
*/ */
File getDirectory(); File getDirectory();
/**
* Get the directory containing all the worlds
* @return
*/
File getWorldContainer();
/** /**
* Wrap a player into a PlotPlayer object * Wrap a player into a PlotPlayer object
* @param obj * @param obj
* @return * @return
*/ */
PlotPlayer wrapPlayer(Object obj); PlotPlayer wrapPlayer(final Object obj);
/** /**
* Disable the implementation * Disable the implementation
* - If a full disable isn't feasibly, just disable what it can * - If a full disable isn't feasibly, just disable what it can
*/ */
void disable(); void disable();
/** /**
* Get the version of the PlotSquared being used * Get the version of the PlotSquared being used
* @return * @return
@ -68,82 +78,89 @@ public interface IPlotMain {
*/ */
SchematicHandler initSchematicHandler(); SchematicHandler initSchematicHandler();
/**
* Get the schematic handler
* @return
*/
ChatManager initChatManager();
/** /**
* The task manager will run and manage minecraft tasks * The task manager will run and manage minecraft tasks
* @return * @return
*/ */
TaskManager getTaskManager(); TaskManager getTaskManager();
/** /**
* Run the task that will kill road mobs * Run the task that will kill road mobs
*/ */
void runEntityTask(); void runEntityTask();
/** /**
* Register the implementation specific commands * Register the implementation specific commands
*/ */
void registerCommands(); void registerCommands();
/** /**
* Register the protection system (used to protect blocks and such) * Register the protection system (used to protect blocks and such)
*/ */
void registerPlayerEvents(); void registerPlayerEvents();
/** /**
* Register inventory related events (used for inventory guis) * Register inventory related events (used for inventory guis)
*/ */
void registerInventoryEvents(); void registerInventoryEvents();
/** /**
* Register plot plus related events (whatever these are?) * Register plot plus related events (whatever these are?)
*/ */
void registerPlotPlusEvents(); void registerPlotPlusEvents();
/** /**
* Register force field events (why is this a thing?) * Register force field events (why is this a thing?)
*/ */
void registerForceFieldEvents(); void registerForceFieldEvents();
/** /**
* Register the WorldEdit hook * Register the WorldEdit hook
*/ */
void registerWorldEditEvents(); boolean initWorldEdit();
/**
* Register TNT related events (if TNT protection is enabled)
*/
void registerTNTListener();
/** /**
* Get the economy provider * Get the economy provider
* @return * @return
*/ */
EconHandler getEconomyHandler(); EconHandler getEconomyHandler();
/** /**
* Get the block manager * Get the Plot Queue class
* @return * @return
*/ */
BlockManager initBlockManager(); PlotQueue initPlotQueue();
/**
* Get the World Util class
* @return
*/
WorldUtil initWorldUtil();
/** /**
* Get the EventUtil class * Get the EventUtil class
* @return * @return
*/ */
EventUtil initEventUtil(); EventUtil initEventUtil();
/** /**
* Get the chunk manager * Get the chunk manager
* @return * @return
*/ */
ChunkManager initChunkManager(); ChunkManager initChunkManager();
/** /**
* Get the setuputils class (used for world creation) * Get the setuputils class (used for world creation)
* @return * @return
*/ */
SetupUtils initSetupUtils(); SetupUtils initSetupUtils();
/** /**
* Get HybridUtils class (common functions useful for hybrid world generation) * Get HybridUtils class (common functions useful for hybrid world generation)
* @return * @return
@ -159,8 +176,8 @@ public interface IPlotMain {
* If a world is already loaded, set the generator (use NMS if required) * If a world is already loaded, set the generator (use NMS if required)
* @param world * @param world
*/ */
void setGenerator(String world); void setGenerator(final String world);
/** /**
* Get the UUIDHandlerImplementation which will cache and provide UUIDs * Get the UUIDHandlerImplementation which will cache and provide UUIDs
* @return * @return
@ -172,7 +189,7 @@ public interface IPlotMain {
* @return * @return
*/ */
InventoryUtil initInventoryUtil(); InventoryUtil initInventoryUtil();
/** /**
* Run the converter for the implementation (not necessarily PlotMe, just any plugin that we can convert from) * Run the converter for the implementation (not necessarily PlotMe, just any plugin that we can convert from)
* @return * @return
@ -183,26 +200,31 @@ public interface IPlotMain {
* Unregister a PlotPlayer from cache e.g. if they have logged off * Unregister a PlotPlayer from cache e.g. if they have logged off
* @param player * @param player
*/ */
void unregister(PlotPlayer player); void unregister(final PlotPlayer player);
/** /**
* Get the generator wrapper for a world (world) and generator (name) * Get the generator wrapper for a world (world) and generator (name)
* @param world * @param world
* @param name * @param name
* @return * @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 * Register the chunk processor which will clean out chunks that have too many blockstates or entities
*/ */
void registerChunkProcessor(); void registerChunkProcessor();
/** /**
* Register the world initialization events (used to keep track of worlds being generated) * Register the world initialization events (used to keep track of worlds being generated)
*/ */
void registerWorldEvents(); void registerWorldEvents();
/** /**
* Get the name of the server * Get the name of the server
* @return * @return
@ -214,4 +236,6 @@ public interface IPlotMain {
* @return * @return
*/ */
AbstractTitle initTitleManager(); AbstractTitle initTitleManager();
List<String> getPluginIds();
} }

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

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

View File

@ -22,51 +22,50 @@ package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.PlotWorld; import com.intellectualcrafters.plot.object.StringWrapper;
import com.intellectualcrafters.plot.util.EconHandler;
import com.intellectualcrafters.plot.util.MainUtil; 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; import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration( @CommandDeclaration(
command = "unclaim", command = "setalias",
usage = "/plot unclaim", permission = "plots.set.alias",
requiredType = RequiredType.NONE, description = "Set the plot name",
description = "Unclaim a plot", usage = "/plot alias <alias>",
category = CommandCategory.ACTIONS aliases = { "alias", "sa", "name", "rename", "setname", "seta" },
) category = CommandCategory.SETTINGS,
public class Unclaim extends SubCommand { requiredType = RequiredType.NONE)
public class Alias extends SetCommand {
@Override @Override
public boolean onCommand(final PlotPlayer plr, final String[] args) { public boolean set(final PlotPlayer plr, final Plot plot, final String alias) {
final Location loc = plr.getLocation(); if (alias.isEmpty()) {
final Plot plot = MainUtil.getPlot(loc); C.COMMAND_SYNTAX.send(plr, getUsage());
if (plot == null) { return false;
return !sendMessage(plr, C.NOT_IN_PLOT);
} }
if (!MainUtil.getTopPlot(plot).equals(MainUtil.getBottomPlot(plot))) { if (alias.length() >= 50) {
return !sendMessage(plr, C.UNLINK_REQUIRED); MainUtil.sendMessage(plr, C.ALIAS_TOO_LONG);
return false;
} }
if (((!plot.hasOwner() || !plot.isOwner(plr.getUUID()))) && !Permissions.hasPermission(plr, "plots.admin.command.unclaim")) { if (alias.contains(" ") || !StringMan.isAsciiPrintable(alias)) {
return !sendMessage(plr, C.NO_PLOT_PERMS); C.NOT_VALID_VALUE.send(plr);
return false;
} }
final PlotWorld pWorld = PS.get().getPlotWorld(plot.world); for (final Plot p : PS.get().getPlots(plot.getArea())) {
if ((EconHandler.manager != null) && pWorld.USE_ECONOMY) { if (p.getAlias().equalsIgnoreCase(alias)) {
final double c = pWorld.SELL_PRICE; MainUtil.sendMessage(plr, C.ALIAS_IS_TAKEN);
if (c > 0d) { return false;
EconHandler.manager.depositMoney(plr, c);
sendMessage(plr, C.ADDED_BALANCE, c + "");
} }
} }
if (plot.unclaim()) { if (UUIDHandler.nameExists(new StringWrapper(alias)) || PS.get().hasPlotArea(alias)) {
MainUtil.sendMessage(plr, C.UNCLAIM_SUCCESS); MainUtil.sendMessage(plr, C.ALIAS_IS_TAKEN);
} return false;
else {
MainUtil.sendMessage(plr, C.UNCLAIM_FAILED);
} }
plot.setAlias(alias);
MainUtil.sendMessage(plr, C.ALIAS_SET_TO.s().replaceAll("%alias%", alias));
return true; 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,33 +20,29 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot; 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.PlotId;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.PlotWorld; import com.intellectualcrafters.plot.util.ByteArrayUtilities;
import com.intellectualcrafters.plot.util.ClusterManager;
import com.intellectualcrafters.plot.util.EconHandler; import com.intellectualcrafters.plot.util.EconHandler;
import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.Permissions;
import com.plotsquared.general.commands.CommandDeclaration; import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration( @CommandDeclaration(
command = "auto", command = "auto",
permission = "plots.auto", permission = "plots.auto",
category = CommandCategory.CLAIMING, category = CommandCategory.CLAIMING,
requiredType = RequiredType.NONE, requiredType = RequiredType.NONE,
description = "Claim the nearest plot", description = "Claim the nearest plot",
aliases = {"a"}, aliases = { "a" },
usage = "/plot auto" usage = "/plot auto [length,width]")
)
public class Auto extends SubCommand { 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 absX = Math.abs(id.x);
final int absY = Math.abs(id.y); final int absY = Math.abs(id.y);
if (absX > absY) { if (absX > absY) {
@ -74,39 +70,30 @@ public class Auto extends SubCommand {
return new PlotId(id.x + 1, id.y); return new PlotId(id.x + 1, id.y);
} }
} }
@Override @Override
public boolean onCommand(PlotPlayer plr, String[] args) { public boolean onCommand(final PlotPlayer plr, final String[] args) {
PlotArea plotarea = plr.getApplicablePlotArea();
String world; if (plotarea == null) {
MainUtil.sendMessage(plr, C.NOT_IN_PLOT_WORLD);
return false;
}
int size_x = 1; int size_x = 1;
int size_z = 1; int size_z = 1;
String schematic = ""; String schematic = null;
if (PS.get().getPlotWorlds().size() == 1) {
world = PS.get().getPlotWorlds().iterator().next();
} else {
world = plr.getLocation().getWorld();
if (!PS.get().isPlotWorld(world)) {
MainUtil.sendMessage(plr, C.NOT_IN_PLOT_WORLD);
return false;
}
}
if (args.length > 0) { if (args.length > 0) {
if (Permissions.hasPermission(plr, "plots.auto.mega")) { if (Permissions.hasPermission(plr, "plots.auto.mega")) {
try { try {
final String[] split = args[0].split(","); final String[] split = args[0].split(",|;");
size_x = Integer.parseInt(split[0]); size_x = Integer.parseInt(split[0]);
size_z = Integer.parseInt(split[1]); size_z = Integer.parseInt(split[1]);
if ((size_x < 1) || (size_z < 1)) { if ((size_x < 1) || (size_z < 1)) {
MainUtil.sendMessage(plr, "&cError: size<=0"); MainUtil.sendMessage(plr, "&cError: size<=0");
} }
if ((size_x > 4) || (size_z > 4)) {
MainUtil.sendMessage(plr, "&cError: size>4");
}
if (args.length > 1) { if (args.length > 1) {
schematic = args[1]; schematic = args[1];
} }
} catch (final Exception e) { } catch (NumberFormatException e) {
size_x = 1; size_x = 1;
size_z = 1; size_z = 1;
schematic = args[0]; 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 + ""); MainUtil.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS_NUM, Settings.MAX_AUTO_SIZE + "");
return false; return false;
} }
final int currentPlots = Settings.GLOBAL_LIMIT ? MainUtil.getPlayerPlotCount(plr) : MainUtil.getPlayerPlotCount(world, plr); int removeGrants = 0;
final int diff = currentPlots - MainUtil.getAllowedPlots(plr); 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 + (size_x * size_z)) > 0) {
if (diff < 0) { if (diff < 0) {
MainUtil.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS_NUM, (-diff) + ""); MainUtil.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS_NUM, (-diff) + "");
} else { } else {
MainUtil.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS); 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;
} }
return false;
} }
final PlotWorld pWorld = PS.get().getPlotWorld(world); if ((EconHandler.manager != null) && plotarea.USE_ECONOMY) {
if ((EconHandler.manager != null) && pWorld.USE_ECONOMY) { double cost = plotarea.PLOT_PRICE;
double cost = pWorld.PLOT_PRICE;
cost = (size_x * size_z) * cost; cost = (size_x * size_z) * cost;
if (cost > 0d) { if (cost > 0d) {
if (EconHandler.manager.getMoney(plr) < cost) { if (EconHandler.manager.getMoney(plr) < cost) {
@ -147,9 +146,13 @@ public class Auto extends SubCommand {
sendMessage(plr, C.REMOVED_BALANCE, cost + ""); sendMessage(plr, C.REMOVED_BALANCE, cost + "");
} }
} }
if (!schematic.equals("")) { if (removeGrants > 0) {
// if (pWorld.SCHEMATIC_CLAIM_SPECIFY) { int grantedPlots = ByteArrayUtilities.bytesToInteger(plr.getPersistentMeta("grantedPlots"));
if (!pWorld.SCHEMATICS.contains(schematic.toLowerCase())) { 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); sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent: " + schematic);
return true; return true;
} }
@ -157,24 +160,10 @@ public class Auto extends SubCommand {
MainUtil.sendMessage(plr, C.NO_SCHEMATIC_PERMISSION, schematic); MainUtil.sendMessage(plr, C.NO_SCHEMATIC_PERMISSION, schematic);
return true; return true;
} }
// }
} }
final String worldname = world; if (plotarea.TYPE == 2) {
final PlotWorld plotworld = PS.get().getPlotWorld(worldname); final PlotId bot = plotarea.getMin();
if (plotworld.TYPE == 2) { final PlotId top = plotarea.getMax();
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();
final PlotId origin = new PlotId((bot.x + top.x) / 2, (bot.y + top.y) / 2); final PlotId origin = new PlotId((bot.x + top.x) / 2, (bot.y + top.y) / 2);
PlotId id = new PlotId(0, 0); PlotId id = new PlotId(0, 0);
final int width = Math.max((top.x - bot.x) + 1, (top.y - bot.y) + 1); 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++) { for (int i = 0; i <= max; i++) {
final PlotId currentId = new PlotId(origin.x + id.x, origin.y + id.y); final PlotId currentId = new PlotId(origin.x + id.x, origin.y + id.y);
final Plot current = MainUtil.getPlot(worldname, currentId); Plot current = plotarea.getPlotAbs(currentId);
if (MainUtil.canClaim(plr, current) && (current.getSettings().isMerged() == false) && cluster.equals(ClusterManager.getCluster(current))) { if (current.canClaim(plr)) {
Claim.claimPlot(plr, current, true, true); Claim.claimPlot(plr, current, true, true);
return true; return true;
} }
id = getNextPlot(id, 1); id = getNextPlotId(id, 1);
} }
// no free plots // no free plots
MainUtil.sendMessage(plr, C.NO_FREE_PLOTS); MainUtil.sendMessage(plr, C.NO_FREE_PLOTS);
@ -196,50 +185,44 @@ public class Auto extends SubCommand {
boolean br = false; boolean br = false;
if ((size_x == 1) && (size_z == 1)) { if ((size_x == 1) && (size_z == 1)) {
while (!br) { while (!br) {
final Plot plot = MainUtil.getPlot(worldname, getLastPlot(worldname)); Plot plot = plotarea.getPlotAbs(getLastPlotId(plotarea));
if (MainUtil.canClaim(plr, plot)) { if (plot.canClaim(plr)) {
Claim.claimPlot(plr, plot, true, true); Claim.claimPlot(plr, plot, true, true);
br = true; br = true;
} }
MainUtil.lastPlot.put(worldname, getNextPlot(getLastPlot(worldname), 1)); plotarea.setMeta("lastPlot", getNextPlotId(plot.getId(), 1));
} }
} else { } else {
boolean lastPlot = true;
while (!br) { while (!br) {
final PlotId start = getNextPlot(getLastPlot(worldname), 1); final PlotId start = getNextPlotId(getLastPlotId(plotarea), 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 end = new PlotId((start.x + size_x) - 1, (start.y + size_z) - 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 i = start.x; i <= end.x; i++) {
for (int j = start.y; j <= end.y; j++) { 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)); final boolean teleport = ((i == end.x) && (j == end.y));
Claim.claimPlot(plr, plot, teleport, true); 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; return false;
} }
br = true; br = true;
} }
} }
} }
MainUtil.lastPlot.put(worldname, new PlotId(0, 0)); plotarea.setMeta("lastPlot", new PlotId(0, 0));
return true; return true;
} }
public PlotId getLastPlot(final String world) { public PlotId getLastPlotId(final PlotArea area) {
if ((MainUtil.lastPlot == null) || !MainUtil.lastPlot.containsKey(world)) { PlotId value = (PlotId) area.getMeta("lastPlot");
MainUtil.lastPlot.put(world, new PlotId(0, 0)); 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; package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.config.C; 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.Location;
import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotAnalysis;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.util.BO3Handler; import com.intellectualcrafters.plot.util.BO3Handler;
import com.intellectualcrafters.plot.util.BlockManager;
import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.general.commands.CommandDeclaration; import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration( @CommandDeclaration(command = "bo3", aliases = { "bo2" }, description = "Mark a plot as done", permission = "plots.bo3", category = CommandCategory.SCHEMATIC, requiredType = RequiredType.NONE)
command = "bo3",
aliases = {"bo2"},
description = "Mark a plot as done",
permission = "plots.done",
category = CommandCategory.ACTIONS,
requiredType = RequiredType.NONE
)
public class BO3 extends SubCommand { 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 export [category] [alias] [-r]");
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot bo3 import <file>"); MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot bo3 import <file>");
} }
@ -55,8 +40,8 @@ public class BO3 extends SubCommand {
@Override @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 Location loc = plr.getLocation();
final Plot plot = MainUtil.getPlot(loc); final Plot plot = loc.getPlotAbs();
if (plot == null || !plot.hasOwner()) { if ((plot == null) || !plot.hasOwner()) {
return !sendMessage(plr, C.NOT_IN_PLOT); return !sendMessage(plr, C.NOT_IN_PLOT);
} }
if ((!plot.isOwner(plr.getUUID())) && !Permissions.hasPermission(plr, "plots.admin.command.bo3")) { if ((!plot.isOwner(plr.getUUID())) && !Permissions.hasPermission(plr, "plots.admin.command.bo3")) {

View File

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

View File

@ -20,103 +20,89 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import java.util.Set;
import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.flag.Flag; import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.flag.FlagManager; import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotHandler;
import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.PlotWorld;
import com.intellectualcrafters.plot.util.EconHandler; import com.intellectualcrafters.plot.util.EconHandler;
import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.UUIDHandler; import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.general.commands.CommandDeclaration; import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration( @CommandDeclaration(
command = "buy", command = "buy",
aliases = {"b"}, aliases = { "b" },
description = "Buy the plot you are standing on", description = "Buy the plot you are standing on",
usage = "/plot buy", usage = "/plot buy",
permission = "plots.buy", permission = "plots.buy",
category = CommandCategory.CLAIMING, category = CommandCategory.CLAIMING,
requiredType = RequiredType.NONE requiredType = RequiredType.NONE)
)
public class Buy extends SubCommand { public class Buy extends SubCommand {
@Override @Override
public boolean onCommand(final PlotPlayer plr, final String ... args) { public boolean onCommand(final PlotPlayer plr, final String... args) {
if (EconHandler.manager == null) { if (EconHandler.manager == null) {
return sendMessage(plr, C.ECON_DISABLED); return sendMessage(plr, C.ECON_DISABLED);
} }
final Location loc = plr.getLocation(); final Location loc = plr.getLocation();
final String world = loc.getWorld(); final String world = loc.getWorld();
if (!PS.get().isPlotWorld(world)) { if (!PS.get().hasPlotArea(world)) {
return sendMessage(plr, C.NOT_IN_PLOT_WORLD); return sendMessage(plr, C.NOT_IN_PLOT_WORLD);
} }
Set<Plot> plots;
Plot plot; Plot plot;
if (args.length > 0) { if (args.length > 0) {
try { try {
final String[] split = args[0].split(";"); plot = MainUtil.getPlotFromString(plr, world, true);
final PlotId id = new PlotId(Integer.parseInt(split[0]), Integer.parseInt(split[1])); if (plot == null) {
plot = MainUtil.getPlot(world, id); return false;
}
plots = plot.getConnectedPlots();
} catch (final Exception e) { } catch (final Exception e) {
return sendMessage(plr, C.NOT_VALID_PLOT_ID); return sendMessage(plr, C.NOT_VALID_PLOT_ID);
} }
} else { } else {
plot = MainUtil.getPlot(loc); plot = loc.getPlotAbs();
plots = plot.getConnectedPlots();
} }
if (plot == null) { if (plots == null) {
return sendMessage(plr, C.NOT_IN_PLOT); 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()) { if (!plot.hasOwner()) {
return sendMessage(plr, C.PLOT_UNOWNED); return sendMessage(plr, C.PLOT_UNOWNED);
} }
if (PlotHandler.isOwner(plot, plr.getUUID())) { final int currentPlots = plr.getPlotCount() + plots.size();
return sendMessage(plr, C.CANNOT_BUY_OWN); 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) { if (flag == null) {
return sendMessage(plr, C.NOT_FOR_SALE); return sendMessage(plr, C.NOT_FOR_SALE);
} }
double initPrice = (double) flag.getValue(); if (plot.isOwner(plr.getUUID())) {
double price = initPrice; return sendMessage(plr, C.CANNOT_BUY_OWN);
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;
} }
double price = (double) flag.getValue();
if ((EconHandler.manager != null) && (price > 0d)) { if ((EconHandler.manager != null) && (price > 0d)) {
if (EconHandler.manager.getMoney(plr) < price) { if (EconHandler.manager.getMoney(plr) < price) {
return sendMessage(plr, C.CANNOT_AFFORD_PLOT, "" + price); return sendMessage(plr, C.CANNOT_AFFORD_PLOT, "" + price);
} }
EconHandler.manager.withdrawMoney(plr, price); EconHandler.manager.withdrawMoney(plr, price);
sendMessage(plr, C.REMOVED_BALANCE, 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); final PlotPlayer owner = UUIDHandler.getPlayer(plot.owner);
if (owner != null) { 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"); FlagManager.removePlotFlag(plot, "price");
} }
Plot top = MainUtil.getTopPlot(plot); for (final Plot current : plots) {
plot.setOwner(plr.getUUID());
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);
} }
MainUtil.sendMessage(plr, C.CLAIMED); MainUtil.sendMessage(plr, C.CLAIMED);
return true; return true;

View File

@ -1,23 +1,19 @@
package com.intellectualcrafters.plot.commands; 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.PlotPlayer;
import com.intellectualcrafters.plot.object.PlotWorld;
import com.plotsquared.general.commands.CommandDeclaration; import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration( @CommandDeclaration(
command = "chat", command = "chat",
description = "Toggle plto chant on or off", description = "Toggle plot chat on or off",
usage = "/plot chat [on|off]", usage = "/plot chat [on|off]",
permission = "plots.chat", permission = "plots.chat",
category = CommandCategory.ACTIONS, category = CommandCategory.CHAT,
requiredType = RequiredType.NONE requiredType = RequiredType.NONE)
)
public class Chat extends SubCommand { public class Chat extends SubCommand {
@Override @Override
public boolean onCommand(final PlotPlayer player, final String ... args) { public boolean onCommand(final PlotPlayer player, final String... args) {
return MainCommand.onCommand(player, "plot", new String[] {"toggle", "chat"}); return MainCommand.onCommand(player, "plot", new String[] { "toggle", "chat" });
} }
} }

View File

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

View File

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

View File

@ -22,44 +22,38 @@ package com.intellectualcrafters.plot.commands;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set;
import java.util.UUID; import java.util.UUID;
import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.database.DBFunc; 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.BlockLoc;
import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotCluster; import com.intellectualcrafters.plot.object.PlotCluster;
import com.intellectualcrafters.plot.object.PlotClusterId;
import com.intellectualcrafters.plot.object.PlotId; import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotPlayer; 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.MainUtil;
import com.intellectualcrafters.plot.util.Permissions; 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.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; import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration( @CommandDeclaration(
command = "cluster", command = "cluster",
aliases = {"clusters"}, aliases = { "clusters" },
category = CommandCategory.ACTIONS, category = CommandCategory.ADMINISTRATION,
requiredType = RequiredType.NONE, requiredType = RequiredType.NONE,
permission = "plots.cluster", permission = "plots.cluster",
description = "Manage a plot cluster" description = "Manage a plot cluster")
)
public class Cluster extends SubCommand { public class Cluster extends SubCommand {
@Override @Override
public boolean onCommand(final PlotPlayer plr, final String ... args) { public boolean onCommand(final PlotPlayer plr, final String... args) {
// list, create, delete, resize, invite, kick, leave, helpers, tp, sethome // list, create, delete, resize, invite, kick, leave, helpers, tp, sethome
if (args.length == 0) { if (args.length == 0) {
@ -79,16 +73,17 @@ public class Cluster extends SubCommand {
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster list"); MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster list");
return false; 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() + ""); MainUtil.sendMessage(plr, C.CLUSTER_LIST_HEADING, clusters.size() + "");
for (final PlotCluster cluster : clusters) { for (final PlotCluster cluster : clusters) {
// Ignore unmanaged clusters // Ignore unmanaged clusters
final String name = "'" + cluster.getName() + "' : " + cluster.toString(); 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); 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); 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); MainUtil.sendMessage(plr, C.CLUSTER_LIST_ELEMENT, "&9" + name);
} else { } else {
MainUtil.sendMessage(plr, C.CLUSTER_LIST_ELEMENT, cluster.toString()); MainUtil.sendMessage(plr, C.CLUSTER_LIST_ELEMENT, cluster.toString());
@ -102,88 +97,80 @@ public class Cluster extends SubCommand {
MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.create"); MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.create");
return false; return false;
} }
PlotArea area = plr.getApplicablePlotArea();
if (area == null) {
C.NOT_IN_PLOT_WORLD.send(plr);
return false;
}
if (args.length != 4) { 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.COMMAND_SYNTAX, "/plot cluster create <name> <id-bot> <id-top>");
MainUtil.sendMessage(plr, C.CLUSTER_CURRENT_PLOTID, "" + id);
return false; return false;
} }
// check pos1 / pos2 // check pos1 / pos2
PlotId pos1 = MainUtil.parseId(args[2]); PlotId pos1 = PlotId.fromString(args[2]);
PlotId pos2 = MainUtil.parseId(args[3]); PlotId pos2 = PlotId.fromString(args[3]);
if ((pos1 == null) || (pos2 == null)) { if ((pos1 == null) || (pos2 == null)) {
MainUtil.sendMessage(plr, C.NOT_VALID_PLOT_ID); MainUtil.sendMessage(plr, C.NOT_VALID_PLOT_ID);
return false; return false;
} }
// check if name is taken // check if name is taken
final String name = args[1]; final String name = args[1];
for (final PlotCluster cluster : ClusterManager.getClusters(plr.getLocation().getWorld())) { if (area.getCluster(name) != null) {
if (name.equals(cluster.getName())) { MainUtil.sendMessage(plr, C.ALIAS_IS_TAKEN);
MainUtil.sendMessage(plr, C.ALIAS_IS_TAKEN);
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() > 0)) {
MainUtil.sendMessage(plr, C.CLUSTER_INTERSECTION, intersects.size() + "");
return false; return false;
} }
if ((pos2.x < pos1.x) || (pos2.y < pos1.y) ) { if ((pos2.x < pos1.x) || (pos2.y < pos1.y)) {
pos1 = new PlotId(Math.min(pos1.x, pos2.x), Math.min(pos1.y, pos2.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)); pos2 = new PlotId(Math.max(pos1.x, pos2.x), Math.max(pos1.y, pos2.y));
pos1 = tmp;
}
//check if overlap
PlotCluster cluster = area.getFirstIntersectingCluster(pos1, pos2);
if (cluster != null) {
MainUtil.sendMessage(plr, C.CLUSTER_INTERSECTION, cluster.getName());
return false;
}
// 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 // create cluster
final String world = plr.getLocation().getWorld();
final PlotCluster cluster = new PlotCluster(world, pos1, pos2, UUIDHandler.getUUID(plr));
cluster.settings.setAlias(name); cluster.settings.setAlias(name);
DBFunc.createCluster(world, cluster); area.addCluster(cluster);
if (!ClusterManager.clusters.containsKey(world)) { DBFunc.createCluster(cluster);
ClusterManager.clusters.put(world, new HashSet<PlotCluster>());
}
ClusterManager.clusters.get(world).add(cluster);
// Add any existing plots to the current cluster // Add any existing plots to the current cluster
for (final Plot plot : PS.get().getPlotsInWorld(plr.getLocation().getWorld())) { for (final Plot plot : plots) {
final PlotCluster current = ClusterManager.getCluster(plot); if (plot.hasOwner()) {
if (cluster.equals(current) && !cluster.isAdded(plot.owner)) { final Flag flag = new Flag(FlagManager.getFlag("cluster"), cluster);
cluster.invited.add(plot.owner); FlagManager.addPlotFlag(plot, flag);
DBFunc.setInvited(world, cluster, plot.owner); if (!cluster.isAdded(plot.owner)) {
cluster.invited.add(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); MainUtil.sendMessage(plr, C.CLUSTER_ADDED);
return true; return true;
} }
@ -198,46 +185,32 @@ public class Cluster extends SubCommand {
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster delete [name]"); MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster delete [name]");
return false; return false;
} }
PlotArea area = plr.getApplicablePlotArea();
if (area == null) {
C.NOT_IN_PLOT_WORLD.send(plr);
return false;
}
PlotCluster cluster; PlotCluster cluster;
if (args.length == 2) { if (args.length == 2) {
cluster = ClusterManager.getCluster(plr.getLocation().getWorld(), args[1]); cluster = area.getCluster(args[1]);
if (cluster == null) { if (cluster == null) {
MainUtil.sendMessage(plr, C.INVALID_CLUSTER, args[1]); MainUtil.sendMessage(plr, C.INVALID_CLUSTER, args[1]);
return false; return false;
} }
} else { } else {
cluster = ClusterManager.getCluster(plr.getLocation()); cluster = area.getCluster(plr.getLocation());
if (cluster == null) { if (cluster == null) {
MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER); MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER);
return false; return false;
} }
} }
if (!cluster.owner.equals(UUIDHandler.getUUID(plr))) { if (!cluster.owner.equals(plr.getUUID())) {
if (!Permissions.hasPermission(plr, "plots.cluster.delete.other")) { if (!Permissions.hasPermission(plr, "plots.cluster.delete.other")) {
MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.delete.other"); MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.delete.other");
return false; 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); 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); MainUtil.sendMessage(plr, C.CLUSTER_DELETED);
return true; return true;
} }
@ -252,72 +225,81 @@ public class Cluster extends SubCommand {
return false; return false;
} }
// check pos1 / pos2 // check pos1 / pos2
final PlotId pos1 = MainUtil.parseId(args[1]); PlotId pos1 = PlotId.fromString(args[1]);
final PlotId pos2 = MainUtil.parseId(args[2]); PlotId pos2 = PlotId.fromString(args[2]);
if ((pos1 == null) || (pos2 == null)) { if ((pos1 == null) || (pos2 == null)) {
MainUtil.sendMessage(plr, C.NOT_VALID_PLOT_ID); MainUtil.sendMessage(plr, C.NOT_VALID_PLOT_ID);
return false; 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 // 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) { if (cluster == null) {
MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER); MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER);
return false; return false;
} }
if (!cluster.hasHelperRights(UUIDHandler.getUUID(plr))) { if (!cluster.hasHelperRights(plr.getUUID())) {
if (!Permissions.hasPermission(plr, "plots.cluster.resize.other")) { if (!Permissions.hasPermission(plr, "plots.cluster.resize.other")) {
MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.resize.other"); MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.resize.other");
return false; return false;
} }
} }
//check if overlap //check if overlap
final PlotClusterId id = new PlotClusterId(pos1, pos2); PlotCluster intersect = area.getFirstIntersectingCluster(pos1, pos2);
final HashSet<PlotCluster> intersects = ClusterManager.getIntersects(plr.getLocation().getWorld(), id); if (intersect != null) {
if (intersects.size() > 1) { MainUtil.sendMessage(plr, C.CLUSTER_INTERSECTION, intersect.getName());
MainUtil.sendMessage(plr, C.CLUSTER_INTERSECTION, (intersects.size() - 1) + "");
return false; 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 // resize cluster
DBFunc.resizeCluster(cluster, id); DBFunc.resizeCluster(cluster, pos1, pos2);
MainUtil.sendMessage(plr, C.CLUSTER_RESIZED); MainUtil.sendMessage(plr, C.CLUSTER_RESIZED);
return true; 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 "add":
case "inv": case "inv":
case "invite": { case "invite": {
@ -330,12 +312,16 @@ public class Cluster extends SubCommand {
return false; return false;
} }
// check if in cluster // 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) { if (cluster == null) {
MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER); MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER);
return false; return false;
} }
if (!cluster.hasHelperRights(UUIDHandler.getUUID(plr))) { if (!cluster.hasHelperRights(plr.getUUID())) {
if (!Permissions.hasPermission(plr, "plots.cluster.invite.other")) { if (!Permissions.hasPermission(plr, "plots.cluster.invite.other")) {
MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.invite.other"); MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.invite.other");
return false; return false;
@ -350,8 +336,7 @@ public class Cluster extends SubCommand {
if (!cluster.isAdded(uuid)) { if (!cluster.isAdded(uuid)) {
// add the user if not added // add the user if not added
cluster.invited.add(uuid); cluster.invited.add(uuid);
final String world = plr.getLocation().getWorld(); DBFunc.setInvited(cluster, uuid);
DBFunc.setInvited(world, cluster, uuid);
final PlotPlayer player = UUIDHandler.getPlayer(uuid); final PlotPlayer player = UUIDHandler.getPlayer(uuid);
if (player != null) { if (player != null) {
MainUtil.sendMessage(player, C.CLUSTER_INVITED, cluster.getName()); 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>"); MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster kick <player>");
return false; 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) { if (cluster == null) {
MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER); MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER);
return false; return false;
} }
if (!cluster.hasHelperRights(UUIDHandler.getUUID(plr))) { if (!cluster.hasHelperRights(plr.getUUID())) {
if (!Permissions.hasPermission(plr, "plots.cluster.kick.other")) { if (!Permissions.hasPermission(plr, "plots.cluster.kick.other")) {
MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.kick.other"); MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.kick.other");
return false; return false;
@ -389,7 +378,7 @@ public class Cluster extends SubCommand {
return false; return false;
} }
// Can't kick if the player is yourself, the owner, or not added to the cluster // 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()); MainUtil.sendMessage(plr, C.CANNOT_KICK_PLAYER, cluster.getName());
return false; return false;
} }
@ -404,9 +393,9 @@ public class Cluster extends SubCommand {
MainUtil.sendMessage(player, C.CLUSTER_REMOVED, cluster.getName()); MainUtil.sendMessage(player, C.CLUSTER_REMOVED, cluster.getName());
} }
for (final Plot plot : new ArrayList<>(PS.get().getPlots(plr.getLocation().getWorld(), uuid))) { 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)) { if ((current != null) && current.equals(cluster)) {
final String world = plr.getLocation().getWorld(); plr.getLocation().getWorld();
plot.unclaim(); plot.unclaim();
} }
} }
@ -423,21 +412,25 @@ public class Cluster extends SubCommand {
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster leave [name]"); MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster leave [name]");
return false; return false;
} }
PlotArea area = plr.getApplicablePlotArea();
if (area == null) {
C.NOT_IN_PLOT_WORLD.send(plr);
}
PlotCluster cluster; PlotCluster cluster;
if (args.length == 2) { if (args.length == 2) {
cluster = ClusterManager.getCluster(plr.getLocation().getWorld(), args[1]); cluster = area.getCluster(args[1]);
if (cluster == null) { if (cluster == null) {
MainUtil.sendMessage(plr, C.INVALID_CLUSTER, args[1]); MainUtil.sendMessage(plr, C.INVALID_CLUSTER, args[1]);
return false; return false;
} }
} else { } else {
cluster = ClusterManager.getCluster(plr.getLocation()); cluster = area.getCluster(plr.getLocation());
if (cluster == null) { if (cluster == null) {
MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER); MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER);
return false; return false;
} }
} }
final UUID uuid = UUIDHandler.getUUID(plr); final UUID uuid = plr.getUUID();
if (!cluster.isAdded(uuid)) { if (!cluster.isAdded(uuid)) {
MainUtil.sendMessage(plr, C.CLUSTER_NOT_ADDED); MainUtil.sendMessage(plr, C.CLUSTER_NOT_ADDED);
return false; return false;
@ -454,9 +447,9 @@ public class Cluster extends SubCommand {
DBFunc.removeInvited(cluster, uuid); DBFunc.removeInvited(cluster, uuid);
MainUtil.sendMessage(plr, C.CLUSTER_REMOVED, cluster.getName()); MainUtil.sendMessage(plr, C.CLUSTER_REMOVED, cluster.getName());
for (final Plot plot : new ArrayList<>(PS.get().getPlots(plr.getLocation().getWorld(), uuid))) { 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)) { if ((current != null) && current.equals(cluster)) {
final String world = plr.getLocation().getWorld(); plr.getLocation().getWorld();
plot.unclaim(); plot.unclaim();
} }
} }
@ -473,7 +466,11 @@ public class Cluster extends SubCommand {
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster helpers <add|remove> <player>"); MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster helpers <add|remove> <player>");
return false; 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) { if (cluster == null) {
MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER); MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER);
return false; return false;
@ -507,19 +504,23 @@ public class Cluster extends SubCommand {
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster tp <name>"); MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster tp <name>");
return false; 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) { if (cluster == null) {
MainUtil.sendMessage(plr, C.INVALID_CLUSTER, args[1]); MainUtil.sendMessage(plr, C.INVALID_CLUSTER, args[1]);
return false; return false;
} }
final UUID uuid = UUIDHandler.getUUID(plr); final UUID uuid = plr.getUUID();
if (!cluster.isAdded(uuid)) { if (!cluster.isAdded(uuid)) {
if (!Permissions.hasPermission(plr, "plots.cluster.tp.other")) { if (!Permissions.hasPermission(plr, "plots.cluster.tp.other")) {
MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.tp.other"); MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.tp.other");
return false; return false;
} }
} }
plr.teleport(ClusterManager.getHome(cluster)); plr.teleport(cluster.getHome());
return MainUtil.sendMessage(plr, C.CLUSTER_TELEPORTING); return MainUtil.sendMessage(plr, C.CLUSTER_TELEPORTING);
} }
case "i": case "i":
@ -534,15 +535,19 @@ public class Cluster extends SubCommand {
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster info [name]"); MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster info [name]");
return false; return false;
} }
PlotArea area = plr.getApplicablePlotArea();
if (area == null) {
C.NOT_IN_PLOT_WORLD.send(plr);
}
PlotCluster cluster; PlotCluster cluster;
if (args.length == 2) { if (args.length == 2) {
cluster = ClusterManager.getCluster(plr.getLocation().getWorld(), args[1]); cluster = area.getCluster(args[1]);
if (cluster == null) { if (cluster == null) {
MainUtil.sendMessage(plr, C.INVALID_CLUSTER, args[1]); MainUtil.sendMessage(plr, C.INVALID_CLUSTER, args[1]);
return false; return false;
} }
} else { } else {
cluster = ClusterManager.getCluster(plr.getLocation()); cluster = area.getCluster(plr.getLocation());
if (cluster == null) { if (cluster == null) {
MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER); MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER);
return false; return false;
@ -555,7 +560,7 @@ public class Cluster extends SubCommand {
} }
final String name = cluster.getName(); 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 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(); String message = C.CLUSTER_INFO.s();
message = message.replaceAll("%id%", id); message = message.replaceAll("%id%", id);
message = message.replaceAll("%owner%", owner); message = message.replaceAll("%owner%", owner);
@ -576,18 +581,22 @@ public class Cluster extends SubCommand {
MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster sethome"); MainUtil.sendMessage(plr, C.COMMAND_SYNTAX, "/plot cluster sethome");
return false; 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) { if (cluster == null) {
MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER); MainUtil.sendMessage(plr, C.NOT_IN_CLUSTER);
return false; return false;
} }
if (!cluster.hasHelperRights(UUIDHandler.getUUID(plr))) { if (!cluster.hasHelperRights(plr.getUUID())) {
if (!Permissions.hasPermission(plr, "plots.cluster.sethome.other")) { if (!Permissions.hasPermission(plr, "plots.cluster.sethome.other")) {
MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.sethome.other"); MainUtil.sendMessage(plr, C.NO_PERMISSION, "plots.cluster.sethome.other");
return false; 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 Location relative = plr.getLocation().subtract(base.getX(), 0, base.getZ());
final BlockLoc blockloc = new BlockLoc(relative.getX(), relative.getY(), relative.getZ()); final BlockLoc blockloc = new BlockLoc(relative.getX(), relative.getY(), relative.getZ());
cluster.settings.setPosition(blockloc); cluster.settings.setPosition(blockloc);

View File

@ -1,58 +1,71 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
/** /**
* CommandCategory * CommandCategory
* *
* @author Citymonstret
* @author Empire92
*/ */
public enum CommandCategory { public enum CommandCategory {
/** /**
* Claiming Commands * Claiming Commands
* *
* Such as: /plot claim * Such as: /plot claim
*/ */
CLAIMING("Claiming"), CLAIMING("Claiming"),
/** /**
* Teleportation Commands * Teleportation Commands
* *
* Such as: /plot visit * Such as: /plot visit
*/ */
TELEPORT("Teleportation"), TELEPORT("Teleport"),
/** /**
* Action Commands * Protection
* */
* Such as: /plot clear SETTINGS("Protection"),
*/ /**
ACTIONS("Actions"), * Chat
/** */
* Information Commands CHAT("Chat"),
* /**
* Such as: /plot info * Web
*/ */
INFO("Information"), SCHEMATIC("Web"),
/** /**
* Debug Commands * Cosmetic
* */
* Such as: /plot debug APPEARANCE("Cosmetic"),
*/ /**
DEBUG("Debug"); * Information Commands
/** *
* The category name (Readable) * Such as: /plot info
*/ */
private final String name; INFO("Info"),
/**
/** * Debug Commands
* Constructor *
* * Such as: /plot debug
* @param name readable name */
*/ DEBUG("Debug"),
CommandCategory(final String name) { /**
this.name = name; * Administration commands
} */
ADMINISTRATION("Admin");
@Override
public String toString() { /**
return this.name; * The category name (Readable)
} */
} private final String name;
/**
* Constructor
*
* @param name readable name
*/
CommandCategory(final String name) {
this.name = name;
}
@Override
public String toString() {
return name;

View File

@ -1,52 +1,51 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
// PlotSquared - A plot manager and world generator for the Bukkit API / // PlotSquared - A plot manager and world generator for the Bukkit API /
// Copyright (c) 2014 IntellectualSites/IntellectualCrafters / // Copyright (c) 2014 IntellectualSites/IntellectualCrafters /
// / // /
// This program is free software; you can redistribute it and/or modify / // 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 / // it under the terms of the GNU General Public License as published by /
// the Free Software Foundation; either version 3 of the License, or / // the Free Software Foundation; either version 3 of the License, or /
// (at your option) any later version. / // (at your option) any later version. /
// / // /
// This program is distributed in the hope that it will be useful, / // This program is distributed in the hope that it will be useful, /
// but WITHOUT ANY WARRANTY; without even the implied warranty of / // but WITHOUT ANY WARRANTY; without even the implied warranty of /
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /
// GNU General Public License for more details. / // GNU General Public License for more details. /
// / // /
// You should have received a copy of the GNU General Public License / // You should have received a copy of the GNU General Public License /
// along with this program; if not, write to the Free Software Foundation, / // along with this program; if not, write to the Free Software Foundation, /
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /
// / // /
// You can contact us via: support@intellectualsites.com / // You can contact us via: support@intellectualsites.com /
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.Permissions;
/** /**
* Created by Citymonstret on 2014-08-03. * Created by Citymonstret on 2014-08-03.
* *
* @author Citymonstret
*/ */
public class CommandPermission { public class CommandPermission {
/** /**
* Permission Node * Permission Node
*/ */
public final String permission; public final String permission;
/** /**
* @param permission Command Permission * @param permission Command Permission
*/ */
public CommandPermission(final String permission) { public CommandPermission(final String permission) {
this.permission = permission.toLowerCase(); this.permission = permission.toLowerCase();
} }
/** /**
* @param player Does the player have the permission? * @param player Does the player have the permission?
* *
* @return true of player has the required permission node * @return true of player has the required permission node
*/ */
public boolean hasPermission(final PlotPlayer player) { public boolean hasPermission(final PlotPlayer player) {
return Permissions.hasPermission(player, this.permission); return Permissions.hasPermission(player, permission);
} }
}

View File

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

View File

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

View File

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

View File

@ -22,45 +22,42 @@ package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.flag.FlagManager; import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.generator.HybridUtils;
import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotAnalysis;
import com.intellectualcrafters.plot.object.PlotPlayer; 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.MainUtil;
import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.general.commands.CommandDeclaration; import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration( @CommandDeclaration(
command = "continue", command = "continue",
description = "Continue a plot that was previously marked as done", description = "Continue a plot that was previously marked as done",
permission = "plots.continue", permission = "plots.continue",
category = CommandCategory.ACTIONS, category = CommandCategory.SETTINGS,
requiredType = RequiredType.NONE requiredType = RequiredType.NONE)
)
public class Continue extends SubCommand { public class Continue extends SubCommand {
@Override @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 Location loc = plr.getLocation();
final Plot plot = MainUtil.getPlot(loc); final Plot plot = loc.getPlotAbs();
if (plot == null || !plot.hasOwner()) { if ((plot == null) || !plot.hasOwner()) {
return !sendMessage(plr, C.NOT_IN_PLOT); 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); MainUtil.sendMessage(plr, C.NO_PLOT_PERMS);
return false; return false;
} }
if (!plot.getSettings().flags.containsKey("done")) { if (!plot.getFlags().containsKey("done")) {
MainUtil.sendMessage(plr, C.DONE_NOT_DONE); MainUtil.sendMessage(plr, C.DONE_NOT_DONE);
return false; 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); MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER);
return false; return false;
} }

View File

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

View File

@ -20,7 +20,6 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.generator.HybridPlotWorld; import com.intellectualcrafters.plot.generator.HybridPlotWorld;
import com.intellectualcrafters.plot.generator.HybridUtils; import com.intellectualcrafters.plot.generator.HybridUtils;
@ -31,28 +30,27 @@ import com.intellectualcrafters.plot.util.MainUtil;
import com.plotsquared.general.commands.CommandDeclaration; import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration( @CommandDeclaration(
command = "createroadschematic", command = "createroadschematic",
aliases = {"crs"}, aliases = { "crs" },
category = CommandCategory.DEBUG, category = CommandCategory.ADMINISTRATION,
requiredType = RequiredType.NONE, requiredType = RequiredType.NONE,
permission = "plots.createroadschematic", permission = "plots.createroadschematic",
description = "Add a road schematic to your world using the roads around your current plot", 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 { public class CreateRoadSchematic extends SubCommand {
@Override @Override
public boolean onCommand(final PlotPlayer player, final String ... args) { public boolean onCommand(final PlotPlayer player, final String... args) {
final Location loc = player.getLocation(); final Location loc = player.getLocation();
final Plot plot = MainUtil.getPlot(loc); final Plot plot = loc.getPlotAbs();
if (plot == null) { if (plot == null) {
return sendMessage(player, C.NOT_IN_PLOT); 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); return sendMessage(player, C.NOT_IN_PLOT_WORLD);
} }
HybridUtils.manager.setupRoadSchematic(plot); 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; return true;
} }
} }

View File

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

View File

@ -22,22 +22,17 @@ package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotPlayer; 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.intellectualcrafters.plot.util.MainUtil;
import com.plotsquared.general.commands.CommandDeclaration; import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration( @CommandDeclaration(command = "debug", category = CommandCategory.DEBUG, description = "Show debug information", usage = "/plot debug [msg]", permission = "plots.admin")
command = "debug",
category = CommandCategory.DEBUG,
description = "Show debug information",
usage = "/plot debug [msg]",
permission = "plots.admin"
)
public class Debug extends SubCommand { public class Debug extends SubCommand {
@Override @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")) { if ((args.length > 0) && args[0].equalsIgnoreCase("msg")) {
final StringBuilder msg = new StringBuilder(); final StringBuilder msg = new StringBuilder();
for (final C c : C.values()) { for (final C c : C.values()) {
@ -56,15 +51,14 @@ public class Debug extends SubCommand {
} }
{ {
final StringBuilder worlds = new StringBuilder(""); final StringBuilder worlds = new StringBuilder("");
for (final String world : PS.get().getPlotWorlds()) { PS.get().foreachPlotArea(new RunnableVal<PlotArea>() {
worlds.append(world).append(" "); @Override
} public void run(PlotArea value) {
worlds.append(value.toString()).append(" ");
}
});
information.append(header); information.append(header);
information.append(getSection(section, "Lag / TPS")); information.append(getSection(section, "PlotArea"));
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(getLine(line, "Plot Worlds", worlds)); information.append(getLine(line, "Plot Worlds", worlds));
information.append(getLine(line, "Owned Plots", PS.get().getPlots().size())); information.append(getLine(line, "Owned Plots", PS.get().getPlots().size()));
information.append(getSection(section, "Messages")); information.append(getSection(section, "Messages"));
@ -76,11 +70,11 @@ public class Debug extends SubCommand {
} }
return true; return true;
} }
private String getSection(final String line, final String val) { private String getSection(final String line, final String val) {
return line.replaceAll("%val%", val) + "\n"; return line.replaceAll("%val%", val) + "\n";
} }
private String getLine(final String line, final String var, final Object val) { private String getLine(final String line, final String var, final Object val) {
return line.replaceAll("%var%", var).replaceAll("%val%", "" + val) + "\n"; return line.replaceAll("%var%", var).replaceAll("%val%", "" + val) + "\n";
} }

View File

@ -9,19 +9,18 @@ import com.intellectualcrafters.plot.object.PlotPlayer;
import com.plotsquared.general.commands.CommandDeclaration; import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration( @CommandDeclaration(
command = "debugallowunsafe", command = "debugallowunsafe",
description = "Allow unsafe actions until toggled off", description = "Allow unsafe actions until toggled off",
usage = "/plot debugallowunsafe", usage = "/plot debugallowunsafe",
category = CommandCategory.DEBUG, category = CommandCategory.DEBUG,
requiredType = RequiredType.NONE, requiredType = RequiredType.NONE,
permission = "plots.debugallowunsafe" permission = "plots.debugallowunsafe")
)
public class DebugAllowUnsafe extends SubCommand { public class DebugAllowUnsafe extends SubCommand {
public static final List<UUID> unsafeAllowed = new ArrayList<>(); public static final List<UUID> unsafeAllowed = new ArrayList<>();
@Override @Override
public boolean onCommand(final PlotPlayer plr, final String ... args) { public boolean onCommand(final PlotPlayer plr, final String... args) {
if (unsafeAllowed.contains(plr.getUUID())) { if (unsafeAllowed.contains(plr.getUUID())) {
unsafeAllowed.remove(plr.getUUID()); unsafeAllowed.remove(plr.getUUID());
@ -32,5 +31,5 @@ public class DebugAllowUnsafe extends SubCommand {
} }
return true; return true;
} }
} }

View File

@ -20,9 +20,6 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import java.util.ArrayList;
import java.util.UUID;
import com.google.common.collect.BiMap; import com.google.common.collect.BiMap;
import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.C;
@ -30,90 +27,97 @@ import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.object.ChunkLoc; import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotId; import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotManager; import com.intellectualcrafters.plot.object.PlotManager;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.PlotWorld;
import com.intellectualcrafters.plot.object.StringWrapper; import com.intellectualcrafters.plot.object.StringWrapper;
import com.intellectualcrafters.plot.util.BlockManager;
import com.intellectualcrafters.plot.util.ChunkManager; import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.EventUtil; import com.intellectualcrafters.plot.util.EventUtil;
import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.UUIDHandler; import com.intellectualcrafters.plot.util.UUIDHandler;
import com.intellectualcrafters.plot.util.WorldUtil;
import com.plotsquared.general.commands.CommandDeclaration; import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration( import java.util.ArrayList;
command = "debugclaimtest", import java.util.Map;
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", import java.util.UUID;
category = CommandCategory.DEBUG,
requiredType = RequiredType.CONSOLE,
permission = "plots.debugclaimtest"
)
public class DebugClaimTest extends SubCommand {
@CommandDeclaration(
command = "debugclaimtest",
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")
public class DebugClaimTest extends SubCommand {
public static boolean claimPlot(final PlotPlayer player, final Plot plot, final boolean teleport) { public static boolean claimPlot(final PlotPlayer player, final Plot plot, final boolean teleport) {
return claimPlot(player, plot, teleport, ""); return claimPlot(player, plot, teleport, "");
} }
public static boolean claimPlot(final PlotPlayer player, final Plot plot, final boolean teleport, final String schematic) { 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); final boolean result = EventUtil.manager.callClaim(player, plot, false);
if (result) { if (result) {
MainUtil.createPlot(player.getUUID(), plot); plot.create(player.getUUID(), true);
MainUtil.setSign(player.getName(), plot); plot.setSign(player.getName());
MainUtil.sendMessage(player, C.CLAIMED); MainUtil.sendMessage(player, C.CLAIMED);
if (teleport) { if (teleport) {
MainUtil.teleportPlayer(player, player.getLocation(), plot); plot.teleportPlayer(player);
} }
} }
return !result; return !result;
} }
@Override @Override
public boolean onCommand(PlotPlayer plr, String[] args) { public boolean onCommand(final PlotPlayer plr, final String[] args) {
if (args.length < 3) { 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]; PlotArea area = PS.get().getPlotAreaByString(args[0]);
if (!BlockManager.manager.isWorld(world) || !PS.get().isPlotWorld(world)) { if (area == null || !WorldUtil.IMP.isWorld(area.worldname)) {
return !MainUtil.sendMessage(null, "&cInvalid plot world!"); C.NOT_VALID_PLOT_WORLD.send(plr, args[0]);
return false;
} }
PlotId min, max; PlotId min, max;
try { try {
final String[] split1 = args[1].split(";"); args[1].split(";");
final String[] split2 = args[2].split(";"); args[2].split(";");
min = new PlotId(Integer.parseInt(split1[0]), Integer.parseInt(split1[1])); min = PlotId.fromString(args[1]);
max = new PlotId(Integer.parseInt(split2[0]), Integer.parseInt(split2[1])); max = PlotId.fromString(args[2]);
} catch (final Exception e) { } 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(plr, "&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)"); MainUtil.sendMessage(plr, "&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 PlotManager manager = area.getPlotManager();
final PlotWorld plotworld = PS.get().getPlotWorld(world);
final ArrayList<Plot> plots = new ArrayList<>(); final ArrayList<Plot> plots = new ArrayList<>();
for (final PlotId id : MainUtil.getPlotSelectionIds(min, max)) { for (final PlotId id : MainUtil.getPlotSelectionIds(min, max)) {
final Plot plot = MainUtil.getPlot(world, id); final Plot plot = area.getPlotAbs(id);
if (PS.get().getPlot(world, plot.id) != null) { if (plot.hasOwner()) {
MainUtil.sendMessage(null, " - &cDB Already contains: " + plot.id); MainUtil.sendMessage(plr, " - &cDB Already contains: " + plot.getId());
continue; 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 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) { if (!result) {
continue; continue;
} }
final String[] lines = BlockManager.manager.getSign(loc); final String[] lines = WorldUtil.IMP.getSign(loc);
if (lines != null) { if (lines != null) {
String line = lines[2]; String line = lines[2];
if ((line != null) && (line.length() > 2)) { if (line != null && line.length() > 2) {
line = line.substring(2); line = line.substring(2);
final BiMap<StringWrapper, UUID> map = UUIDHandler.getUuidMap(); final BiMap<StringWrapper, UUID> map = UUIDHandler.getUuidMap();
UUID uuid = (map.get(new StringWrapper(line))); UUID uuid = map.get(new StringWrapper(line));
if (uuid == null) { if (uuid == null) {
for (final StringWrapper string : map.keySet()) { for (final Map.Entry<StringWrapper, UUID> stringWrapperUUIDEntry : map.entrySet()) {
if (string.value.toLowerCase().startsWith(line.toLowerCase())) { if (stringWrapperUUIDEntry.getKey().value.toLowerCase().startsWith(line.toLowerCase())) {
uuid = map.get(string); uuid = stringWrapperUUIDEntry.getValue();
break; break;
} }
} }
@ -122,29 +126,29 @@ public class DebugClaimTest extends SubCommand {
uuid = UUIDHandler.getUUID(line, null); uuid = UUIDHandler.getUUID(line, null);
} }
if (uuid != null) { if (uuid != null) {
MainUtil.sendMessage(null, " - &aFound plot: " + plot.id + " : " + line); MainUtil.sendMessage(plr, " - &aFound plot: " + plot.getId() + " : " + line);
plot.owner = uuid; plot.owner = uuid;
plots.add(plot); plots.add(plot);
} else { } else {
MainUtil.sendMessage(null, " - &cInvalid playername: " + plot.id + " : " + line); MainUtil.sendMessage(plr, " - &cInvalid playername: " + plot.getId() + " : " + line);
} }
} }
} }
} }
if (plots.size() > 0) { if (!plots.isEmpty()) {
MainUtil.sendMessage(null, "&3Sign Block&8->&3PlotSquared&8: &7Updating '" + plots.size() + "' plots!"); MainUtil.sendMessage(plr, "&3Sign Block&8->&3PlotSquared&8: &7Updating '" + plots.size() + "' plots!");
DBFunc.createPlotsAndData(plots, new Runnable() { DBFunc.createPlotsAndData(plots, new Runnable() {
@Override @Override
public void run() { public void run() {
MainUtil.sendMessage(null, "&6Database update finished!"); MainUtil.sendMessage(plr, "&6Database update finished!");
} }
}); });
for (final Plot plot : plots) { for (final Plot plot : plots) {
PS.get().updatePlot(plot); PS.get().updatePlot(plot);
} }
MainUtil.sendMessage(null, "&3Sign Block&8->&3PlotSquared&8: &7Complete!"); MainUtil.sendMessage(plr, "&3Sign Block&8->&3PlotSquared&8: &7Complete!");
} else { } 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; return true;
} }

View File

@ -21,12 +21,9 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
@ -47,60 +44,55 @@ import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.flag.FlagManager; import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.generator.HybridUtils; import com.intellectualcrafters.plot.generator.HybridUtils;
import com.intellectualcrafters.plot.object.ChunkLoc;
import com.intellectualcrafters.plot.object.ConsolePlayer; import com.intellectualcrafters.plot.object.ConsolePlayer;
import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.OfflinePlotPlayer; import com.intellectualcrafters.plot.object.OfflinePlotPlayer;
import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotAnalysis; import com.intellectualcrafters.plot.object.PlotAnalysis;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotBlock; import com.intellectualcrafters.plot.object.PlotBlock;
import com.intellectualcrafters.plot.object.PlotId; import com.intellectualcrafters.plot.object.PlotId;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.RunnableVal; import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.util.AbstractTitle; import com.intellectualcrafters.plot.util.AbstractTitle;
import com.intellectualcrafters.plot.util.BlockManager;
import com.intellectualcrafters.plot.util.ChunkManager; import com.intellectualcrafters.plot.util.ChunkManager;
import com.intellectualcrafters.plot.util.EconHandler; import com.intellectualcrafters.plot.util.EconHandler;
import com.intellectualcrafters.plot.util.EventUtil; import com.intellectualcrafters.plot.util.EventUtil;
import com.intellectualcrafters.plot.util.ExpireManager; import com.intellectualcrafters.plot.util.ExpireManager;
import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.MathMan; import com.intellectualcrafters.plot.util.MathMan;
import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.SchematicHandler; import com.intellectualcrafters.plot.util.SchematicHandler;
import com.intellectualcrafters.plot.util.SetupUtils; import com.intellectualcrafters.plot.util.SetupUtils;
import com.intellectualcrafters.plot.util.StringMan; import com.intellectualcrafters.plot.util.StringMan;
import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler; import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.bukkit.util.BukkitHybridUtils; import com.intellectualcrafters.plot.util.WorldUtil;
import com.plotsquared.general.commands.Command; import com.plotsquared.general.commands.Command;
import com.plotsquared.general.commands.CommandCaller;
import com.plotsquared.general.commands.CommandDeclaration; import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration( @CommandDeclaration(command = "debugexec", permission = "plots.admin", description = "Mutli-purpose debug command", aliases = "exec",
command = "debugexec", category = CommandCategory.DEBUG)
permission = "plots.admin",
description = "Mutli-purpose debug command",
aliases = {"exec"},
category = CommandCategory.DEBUG
)
public class DebugExec extends SubCommand { public class DebugExec extends SubCommand {
private ScriptEngine engine; private ScriptEngine engine;
private Bindings scope; private Bindings scope;
public DebugExec() { public DebugExec() {
File file = new File(PS.get().IMP.getDirectory(), "scripts" + File.separator + "start.js"); try {
if (file.exists()) { if (PS.get() != null) {
init(); final File file = new File(PS.get().IMP.getDirectory(), "scripts" + File.separator + "start.js");
try { if (file.exists()) {
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")); init();
scope.put("THIS", this); final String script = StringMan.join(Files
scope.put("PlotPlayer", ConsolePlayer.getConsole()); .readLines(new File(new File(PS.get().IMP.getDirectory() + File.separator + "scripts"), "start.js"),
engine.eval(script, scope); StandardCharsets.UTF_8),
} catch (Exception e) { System.getProperty("line.separator"));
e.printStackTrace(); scope.put("THIS", this);
scope.put("PlotPlayer", ConsolePlayer.getConsole());
engine.eval(script, scope);
}
} }
} } catch (IOException | ScriptException e) {}
} }
public ScriptEngine getEngine() { public ScriptEngine getEngine() {
@ -115,11 +107,11 @@ public class DebugExec extends SubCommand {
if (engine != null) { if (engine != null) {
return; return;
} }
engine = (new ScriptEngineManager(null)).getEngineByName("nashorn"); engine = new ScriptEngineManager(null).getEngineByName("nashorn");
if (engine == null) { 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); scope = context.getBindings(ScriptContext.ENGINE_SCOPE);
// stuff // stuff
@ -127,6 +119,7 @@ public class DebugExec extends SubCommand {
scope.put("Settings", new Settings()); scope.put("Settings", new Settings());
scope.put("StringMan", new StringMan()); scope.put("StringMan", new StringMan());
scope.put("MathMan", new MathMan()); scope.put("MathMan", new MathMan());
scope.put("FlagManager", new FlagManager());
// Classes // Classes
scope.put("Location", Location.class); scope.put("Location", Location.class);
@ -143,7 +136,7 @@ public class DebugExec extends SubCommand {
scope.put("ConsolePlayer", ConsolePlayer.getConsole()); scope.put("ConsolePlayer", ConsolePlayer.getConsole());
scope.put("SchematicHandler", SchematicHandler.manager); scope.put("SchematicHandler", SchematicHandler.manager);
scope.put("ChunkManager", ChunkManager.manager); scope.put("ChunkManager", ChunkManager.manager);
scope.put("BlockManager", BlockManager.manager); scope.put("BlockManager", WorldUtil.IMP);
scope.put("SetupUtils", SetupUtils.manager); scope.put("SetupUtils", SetupUtils.manager);
scope.put("EventUtil", EventUtil.manager); scope.put("EventUtil", EventUtil.manager);
scope.put("EconHandler", EconHandler.manager); scope.put("EconHandler", EconHandler.manager);
@ -154,42 +147,42 @@ public class DebugExec extends SubCommand {
scope.put("MainCommand", MainCommand.getInstance()); scope.put("MainCommand", MainCommand.getInstance());
// enums // enums
for (Enum<?> value : C.values()) { for (final Enum<?> value : C.values()) {
scope.put("C_" + value.name(), value); scope.put("C_" + value.name(), value);
} }
} }
@Override @Override
public boolean onCommand(final PlotPlayer player, String... args) { 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", "trim-check"); final List<String> allowed_params = Arrays.asList("calibrate-analysis", "remove-flag", "stop-expire", "start-expire", "show-expired", "update-expired", "seen");
if (args.length > 0) { if (args.length > 0) {
final String arg = args[0].toLowerCase(); final String arg = args[0].toLowerCase();
String script; String script;
boolean async = false; boolean async = false;
switch (arg) { switch (arg) {
case "analyze": { case "analyze": {
Plot plot = MainUtil.getPlot(player.getLocation()); final Plot plot = player.getCurrentPlot();
if (plot == null) { if (plot == null) {
MainUtil.sendMessage(player, C.NOT_IN_PLOT); MainUtil.sendMessage(player, C.NOT_IN_PLOT);
return false; return false;
} }
PlotAnalysis analysis = plot.getComplexity(); final PlotAnalysis analysis = plot.getComplexity();
if (analysis != null) { if (analysis != null) {
int complexity = analysis.getComplexity(); final int complexity = analysis.getComplexity();
MainUtil.sendMessage(player, "Changes: " + analysis.changes); MainUtil.sendMessage(player, "Changes/column: " + analysis.changes / 1.0);
MainUtil.sendMessage(player, "Complexity: " + complexity); MainUtil.sendMessage(player, "Complexity: " + complexity);
return true; return true;
} }
MainUtil.sendMessage(player, "$1Starting task..."); MainUtil.sendMessage(player, "$1Starting task...");
HybridUtils.manager.analyzePlot(plot, new RunnableVal<PlotAnalysis>() { HybridUtils.manager.analyzePlot(plot, new RunnableVal<PlotAnalysis>() {
@Override @Override
public void run() { public void run(PlotAnalysis value) {
MainUtil.sendMessage(player, "$1Done: $2use $3/plot debugexec analyze$2 for more information"); MainUtil.sendMessage(player, "$1Done: $2use $3/plot debugexec analyze$2 for more information");
} }
}); });
return true; return true;
} }
case "calibrate-analysis": { case "calibrate-analysis":
if (args.length != 2) { if (args.length != 2) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec analyze <threshold>"); 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)"); 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; double threshold;
try { try {
threshold = Integer.parseInt(args[1]) / 100d; threshold = Integer.parseInt(args[1]) / 100d;
} } catch (final NumberFormatException e) {
catch (NumberFormatException e) {
MainUtil.sendMessage(player, "$2Invalid threshold: " + args[1]); 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"); MainUtil.sendMessage(player, "$1<threshold> $2= $1The percentage of plots you want to clear as a number between 0 - 100");
return false; return false;
@ -211,8 +203,7 @@ public class DebugExec extends SubCommand {
} }
}, threshold); }, threshold);
return true; return true;
} case "stop-expire":
case "stop-expire": {
if (ExpireManager.task != -1) { if (ExpireManager.task != -1) {
PS.get().TASK.cancelTask(ExpireManager.task); PS.get().TASK.cancelTask(ExpireManager.task);
} else { } else {
@ -220,35 +211,33 @@ public class DebugExec extends SubCommand {
} }
ExpireManager.task = -1; ExpireManager.task = -1;
return MainUtil.sendMessage(player, "Cancelled task."); return MainUtil.sendMessage(player, "Cancelled task.");
} case "remove-flag":
case "remove-flag": {
if (args.length != 2) { if (args.length != 2) {
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec remove-flag <flag>"); MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec remove-flag <flag>");
return false; return false;
} }
String flag = args[1]; final String flag = args[1];
for (Plot plot : PS.get().getPlots()) { for (final Plot plot : PS.get().getBasePlots()) {
if (FlagManager.getPlotFlag(plot, flag) != null) { if (FlagManager.getPlotFlagRaw(plot, flag) != null) {
FlagManager.removePlotFlag(plot, flag); FlagManager.removePlotFlag(plot, flag);
} }
} }
return MainUtil.sendMessage(player, "Cleared flag: " + flag); return MainUtil.sendMessage(player, "Cleared flag: " + flag);
}
case "start-rgar": { case "start-rgar": {
if (args.length != 2) { if (args.length != 2) {
MainUtil.sendMessage(player, "&cInvalid syntax: /plot debugexec start-rgar <world>"); MainUtil.sendMessage(player, "&cInvalid syntax: /plot debugexec start-rgar <world>");
return false; return false;
} }
boolean result; PlotArea area = PS.get().getPlotAreaByString(args[1]);
if (!PS.get().isPlotWorld(args[1])) { if (area == null) {
MainUtil.sendMessage(player, C.NOT_VALID_PLOT_WORLD, args[1]); MainUtil.sendMessage(player, C.NOT_VALID_PLOT_WORLD, args[1]);
return false; return false;
} }
if (BukkitHybridUtils.regions != null) { boolean result;
result = ((BukkitHybridUtils)(HybridUtils.manager)).scheduleRoadUpdate(args[1], BukkitHybridUtils.regions, 0); if (HybridUtils.regions != null) {
} result = HybridUtils.manager.scheduleRoadUpdate(area, HybridUtils.regions, 0);
else { } else {
result = HybridUtils.manager.scheduleRoadUpdate(args[1], 0); result = HybridUtils.manager.scheduleRoadUpdate(area, 0);
} }
if (!result) { if (!result) {
MainUtil.sendMessage(player, "&cCannot schedule mass schematic update! (Is one already in progress?)"); MainUtil.sendMessage(player, "&cCannot schedule mass schematic update! (Is one already in progress?)");
@ -256,7 +245,7 @@ public class DebugExec extends SubCommand {
} }
return true; return true;
} }
case "stop-rgar": { case "stop-rgar":
if (!HybridUtils.UPDATE) { if (!HybridUtils.UPDATE) {
MainUtil.sendMessage(player, "&cTASK NOT RUNNING!"); MainUtil.sendMessage(player, "&cTASK NOT RUNNING!");
return false; return false;
@ -264,31 +253,29 @@ public class DebugExec extends SubCommand {
HybridUtils.UPDATE = false; HybridUtils.UPDATE = false;
MainUtil.sendMessage(player, "&cCancelling task... (please wait)"); MainUtil.sendMessage(player, "&cCancelling task... (please wait)");
return true; return true;
} case "start-expire":
case "start-expire": {
if (ExpireManager.task == -1) { if (ExpireManager.task == -1) {
ExpireManager.runTask(); ExpireManager.runTask();
} else { } else {
return MainUtil.sendMessage(player, "Plot expiry task already started"); return MainUtil.sendMessage(player, "Plot expiry task already started");
} }
return MainUtil.sendMessage(player, "Started plot expiry task"); return MainUtil.sendMessage(player, "Started plot expiry task");
} case "update-expired":
case "update-expired": {
if (args.length > 1) { if (args.length > 1) {
final String world = args[1]; PlotArea area = PS.get().getPlotAreaByString(args[1]);
if (!BlockManager.manager.isWorld(world)) { if (area == null || !WorldUtil.IMP.isWorld(area.worldname)) {
return MainUtil.sendMessage(player, "Invalid world: " + args[1]); C.NOT_VALID_PLOT_WORLD.send(player, args[1]);
return false;
} }
MainUtil.sendMessage(player, "Updating expired plot list"); MainUtil.sendMessage(player, "Updating expired plot list");
ExpireManager.updateExpired(args[1]); ExpireManager.updateExpired(area);
return true; return true;
} }
return MainUtil.sendMessage(player, "Use /plot debugexec update-expired <world>"); return MainUtil.sendMessage(player, "Use /plot debugexec update-expired <world>");
} case "show-expired":
case "show-expired": {
if (args.length > 1) { if (args.length > 1) {
final String world = args[1]; final String world = args[1];
if (!BlockManager.manager.isWorld(world)) { if (!WorldUtil.IMP.isWorld(world)) {
return MainUtil.sendMessage(player, "Invalid world: " + args[1]); return MainUtil.sendMessage(player, "Invalid world: " + args[1]);
} }
if (!ExpireManager.expiredPlots.containsKey(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() + "):"); MainUtil.sendMessage(player, "Expired plots (" + ExpireManager.expiredPlots.get(args[1]).size() + "):");
for (final Plot plot : ExpireManager.expiredPlots.get(args[1])) { 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 true;
} }
return MainUtil.sendMessage(player, "Use /plot debugexec show-expired <world>"); return MainUtil.sendMessage(player, "Use /plot debugexec show-expired <world>");
} case "seen":
case "seen": {
if (args.length != 2) { if (args.length != 2) {
return MainUtil.sendMessage(player, "Use /plot debugexec seen <player>"); 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]); return MainUtil.sendMessage(player, "player not found: " + args[1]);
} }
final OfflinePlotPlayer op = UUIDHandler.getUUIDWrapper().getOfflinePlayer(uuid); 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]); return MainUtil.sendMessage(player, "player hasn't connected before: " + args[1]);
} }
final Timestamp stamp = new Timestamp(op.getLastPlayed()); final Timestamp stamp = new Timestamp(op.getLastPlayed());
@ -322,105 +309,105 @@ public class DebugExec extends SubCommand {
MainUtil.sendMessage(player, "GMT: " + date.toGMTString()); MainUtil.sendMessage(player, "GMT: " + date.toGMTString());
MainUtil.sendMessage(player, "Local: " + date.toLocaleString()); MainUtil.sendMessage(player, "Local: " + date.toLocaleString());
return true; 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 "h":
case "he": case "he":
case "?": case "?":
case "help": { case "help":
MainUtil.sendMessage(player, "Possible sub commands: /plot debugexec <" + StringMan.join(allowed_params, "|") + ">"); MainUtil.sendMessage(player, "Possible sub commands: /plot debugexec <" + StringMan.join(allowed_params, "|") + ">");
return false; return false;
} case "addcmd":
case "addcmd": {
try { 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")); final String cmd = StringMan.join(Files
Command<PlotPlayer> subcommand = new Command<PlotPlayer>(args[1].split("\\.")[0]) { .readLines(new File(new File(PS.get().IMP.getDirectory() + File.separator + "scripts"), args[1]),
@Override StandardCharsets.UTF_8),
public boolean onCommand(PlotPlayer plr, String[] args) { System.getProperty("line.separator"));
try { final Command<PlotPlayer> subcommand = new Command<PlotPlayer>(args[1].split("\\.")[0]) {
scope.put("PlotPlayer", plr); @Override
scope.put("args", args); public boolean onCommand(final PlotPlayer plr, final String[] args) {
engine.eval(cmd, scope); try {
return true; scope.put("PlotPlayer", plr);
} catch (ScriptException e) { scope.put("args", args);
e.printStackTrace(); engine.eval(cmd, scope);
MainUtil.sendMessage(player, C.COMMAND_WENT_WRONG); return true;
return false; } catch (final ScriptException e) {
e.printStackTrace();
MainUtil.sendMessage(player, C.COMMAND_WENT_WRONG);
return false;
}
} }
} };
}; MainCommand.getInstance().addCommand(subcommand);
MainCommand.getInstance().addCommand(subcommand); return true;
return true; } catch (IOException e) {
}
catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec addcmd <file>"); MainUtil.sendMessage(player, C.COMMAND_SYNTAX, "/plot debugexec addcmd <file>");
return false; return false;
} }
} case "runasync":
case "runasync": {
async = true; async = true;
} case "run":
case "run": {
try { 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) { 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++) { for (int i = 2; i < args.length; i++) {
replacements.put("%s" + (i-2), args[i]); replacements.put("%s" + (i - 2), args[i]);
} }
script = StringMan.replaceFromMap(script, replacements); script = StringMan.replaceFromMap(script, replacements);
} }
} catch (IOException e) { } catch (final IOException e) {
e.printStackTrace(); e.printStackTrace();
return false; return false;
} }
break; break;
} case "allcmd":
default: { if (args.length < 3) {
C.COMMAND_SYNTAX.send(player, "/plot debugexec allcmd <condition> <command>");
return false;
}
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, " "); script = StringMan.join(args, " ");
}
} }
if (!ConsolePlayer.isConsole(player)) { if (!ConsolePlayer.isConsole(player)) {
MainUtil.sendMessage(player, C.NOT_CONSOLE); MainUtil.sendMessage(player, C.NOT_CONSOLE);
@ -435,23 +422,23 @@ public class DebugExec extends SubCommand {
TaskManager.runTaskAsync(new Runnable() { TaskManager.runTaskAsync(new Runnable() {
@Override @Override
public void run() { public void run() {
long start = System.currentTimeMillis(); final long start = System.currentTimeMillis();
Object result = null;
try { try {
engine.eval(toExec, scope); result = engine.eval(toExec, scope);
} catch (ScriptException e) { } catch (final ScriptException e) {
e.printStackTrace(); e.printStackTrace();
} }
PS.log("> " + (System.currentTimeMillis() - start) + "ms"); ConsolePlayer.getConsole().sendMessage("> " + (System.currentTimeMillis() - start) + "ms -> " + result);
} }
}); });
} } else {
else { final long start = System.currentTimeMillis();
long start = System.currentTimeMillis(); Object result = engine.eval(script, scope);
engine.eval(script, scope); ConsolePlayer.getConsole().sendMessage("> " + (System.currentTimeMillis() - start) + "ms -> " + result);
PS.log("> " + (System.currentTimeMillis() - start) + "ms");
} }
return true; return true;
} catch (ScriptException e) { } catch (final ScriptException e) {
e.printStackTrace(); e.printStackTrace();
return false; 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,39 +30,37 @@ import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.flag.Flag; import com.intellectualcrafters.plot.flag.Flag;
import com.intellectualcrafters.plot.flag.FlagManager; import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.BlockManager;
import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.WorldUtil;
import com.plotsquared.general.commands.Argument; import com.plotsquared.general.commands.Argument;
import com.plotsquared.general.commands.CommandDeclaration; import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration( @CommandDeclaration(
command = "debugfixflags", command = "debugfixflags",
usage = "/plot debugfixflags <world>", usage = "/plot debugfixflags <world>",
permission = "plots.debugfixflags", permission = "plots.debugfixflags",
description = "Attempt to fix all flags for a world", description = "Attempt to fix all flags for a world",
requiredType = RequiredType.CONSOLE, requiredType = RequiredType.CONSOLE,
category = CommandCategory.DEBUG category = CommandCategory.DEBUG)
)
public class DebugFixFlags extends SubCommand { public class DebugFixFlags extends SubCommand {
public DebugFixFlags() { public DebugFixFlags() {
requiredArguments = new Argument[] { requiredArguments = new Argument[] { Argument.String };
Argument.String
};
} }
@Override @Override
public boolean onCommand(PlotPlayer plr, String[] args) { public boolean onCommand(final PlotPlayer plr, final String[] args) {
final String world = args[0]; PlotArea area = PS.get().getPlotAreaByString(args[0]);
if (!BlockManager.manager.isWorld(world) || !PS.get().isPlotWorld(world)) { if (area == null || !WorldUtil.IMP.isWorld(area.worldname)) {
MainUtil.sendMessage(plr, C.NOT_VALID_PLOT_WORLD, args[0]); MainUtil.sendMessage(plr, C.NOT_VALID_PLOT_WORLD, args[0]);
return false; return false;
} }
MainUtil.sendMessage(plr, "&8--- &6Starting task &8 ---"); MainUtil.sendMessage(plr, "&8--- &6Starting task &8 ---");
for (final Plot plot : PS.get().getPlotsInWorld(world)) { for (final Plot plot : area.getPlots()) {
final HashMap<String, Flag> flags = plot.getSettings().flags; final HashMap<String, Flag> flags = plot.getFlags();
Iterator<Entry<String, Flag>> i = flags.entrySet().iterator(); final Iterator<Entry<String, Flag>> i = flags.entrySet().iterator();
boolean changed = false; boolean changed = false;
while (i.hasNext()) { while (i.hasNext()) {
if (FlagManager.getFlag(i.next().getKey()) == null) { if (FlagManager.getFlag(i.next().getKey()) == null) {
@ -71,7 +69,7 @@ public class DebugFixFlags extends SubCommand {
} }
} }
if (changed) { if (changed) {
DBFunc.setFlags(plot, plot.getSettings().flags.values()); DBFunc.setFlags(plot, plot.getFlags().values());
} }
} }
MainUtil.sendMessage(plr, "&aDone!"); MainUtil.sendMessage(plr, "&aDone!");

View File

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

View File

@ -3,55 +3,57 @@ package com.intellectualcrafters.plot.commands;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
import com.intellectualcrafters.plot.PS; import com.intellectualcrafters.plot.PS;
import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.HastebinUtility; import com.intellectualcrafters.plot.util.HastebinUtility;
import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.bukkit.BukkitMain; import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.general.commands.CommandDeclaration; import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration( @CommandDeclaration(
command = "debugpaste", command = "debugpaste",
aliases = {"dp"}, aliases = { "dp" },
usage = "/plot debugpaste", usage = "/plot debugpaste",
description = "Upload settings.yml & latest.log to hastebin", description = "Upload settings.yml & latest.log to HasteBin",
permission = "plots.debugpaste", permission = "plots.debugpaste",
category = CommandCategory.DEBUG category = CommandCategory.DEBUG)
)
public class DebugPaste extends SubCommand { public class DebugPaste extends SubCommand {
@Override @Override
public boolean onCommand(final PlotPlayer plr, String[] args) { public boolean onCommand(final PlotPlayer plr, final String[] args) {
TaskManager.runTaskAsync(new Runnable() { TaskManager.runTaskAsync(new Runnable() {
@Override @Override
public void run() { public void run() {
try { try {
String settingsYML = HastebinUtility.upload(PS.get().configFile); final String settingsYML = HastebinUtility.upload(PS.get().configFile);
String latestLOG; String latestLOG;
try { 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) { } 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 :("; 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("# 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.settings_yml: '").append(settingsYML).append("'\n");
b.append("links.latest_log: '").append(latestLOG).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("\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.server: '").append(PS.get().IMP.getServerVersion()).append("'\n");
b.append("version.bukkit: '").append(Bukkit.getBukkitVersion()).append("'\n"); b.append("online_mode: ").append(UUIDHandler.getUUIDWrapper() + ";" + !Settings.OFFLINE_MODE).append("\n");
b.append("online_mode: ").append(Bukkit.getServer().getOnlineMode()).append("\n");
b.append("plugins:"); b.append("plugins:");
for (final Plugin p : Bukkit.getPluginManager().getPlugins()) { for (String id : PS.get().IMP.getPluginIds()) {
b.append("\n ").append(p.getName()).append(":\n ").append("version: '").append(p.getDescription().getVersion()).append("'").append("\n enabled: ").append(p.isEnabled()); 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"); 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.free: ").append(runtime.freeMemory()).append("\n");
b.append("memory.max: ").append(runtime.maxMemory()).append("\n"); b.append("memory.max: ").append(runtime.maxMemory()).append("\n");
b.append("java.specification.version: '").append(System.getProperty("java.specification.version")).append("'\n"); b.append("java.specification.version: '").append(System.getProperty("java.specification.version")).append("'\n");
@ -62,10 +64,10 @@ public class DebugPaste extends SubCommand {
b.append("os.version: '").append(System.getProperty("os.version")).append("'\n\n"); b.append("os.version: '").append(System.getProperty("os.version")).append("'\n\n");
b.append("# Okay :D Great. You are now ready to create your bug report!"); 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"); 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)); plr.sendMessage(C.DEBUG_REPORT_CREATED.s().replace("%url%", link));
} catch (IOException e) { } catch (final IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }

View File

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

View File

@ -30,24 +30,23 @@ import com.intellectualcrafters.plot.util.MainUtil;
import com.plotsquared.general.commands.CommandDeclaration; import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration( @CommandDeclaration(
command = "debugsavetest", command = "debugsavetest",
permission = "plots.debugsavetest", permission = "plots.debugsavetest",
category = CommandCategory.DEBUG, category = CommandCategory.DEBUG,
requiredType = RequiredType.CONSOLE, requiredType = RequiredType.CONSOLE,
usage = "/plot debugsavetest", 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 { public class DebugSaveTest extends SubCommand {
@Override @Override
public boolean onCommand(PlotPlayer plr, String[] args) { public boolean onCommand(final PlotPlayer plr, final String[] args) {
final ArrayList<Plot> plots = new ArrayList<Plot>(); final ArrayList<Plot> plots = new ArrayList<Plot>();
plots.addAll(PS.get().getPlots()); plots.addAll(PS.get().getPlots());
MainUtil.sendMessage(null, "&6Starting `DEBUGSAVETEST`"); MainUtil.sendMessage(plr, "&6Starting `DEBUGSAVETEST`");
DBFunc.createPlotsAndData(plots, new Runnable() { DBFunc.createPlotsAndData(plots, new Runnable() {
@Override @Override
public void run() { public void run() {
MainUtil.sendMessage(null, "&6Database sync finished!"); MainUtil.sendMessage(plr, "&6Database sync finished!");
} }
}); });
return true; 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,83 +20,81 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.C;
import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.object.Location; import com.intellectualcrafters.plot.object.Location;
import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotArea;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.PlotWorld;
import com.intellectualcrafters.plot.util.CmdConfirm; import com.intellectualcrafters.plot.util.CmdConfirm;
import com.intellectualcrafters.plot.util.EconHandler; import com.intellectualcrafters.plot.util.EconHandler;
import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.general.commands.CommandDeclaration; import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration( @CommandDeclaration(
command = "delete", command = "delete",
permission = "plots.delete", permission = "plots.delete",
description = "Delete a plot", description = "Delete a plot",
usage = "/plot delete", usage = "/plot delete",
aliases = {"dispose", "del"}, aliases = { "dispose", "del" },
category = CommandCategory.ACTIONS, category = CommandCategory.CLAIMING,
requiredType = RequiredType.NONE requiredType = RequiredType.NONE)
)
public class Delete extends SubCommand { public class Delete extends SubCommand {
@Override @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 Location loc = plr.getLocation();
final Plot plot = MainUtil.getPlot(loc); final Plot plot = loc.getPlotAbs();
if (plot == null) { if (plot == null) {
return !sendMessage(plr, C.NOT_IN_PLOT); return !sendMessage(plr, C.NOT_IN_PLOT);
} }
if (!MainUtil.getTopPlot(plot).equals(MainUtil.getBottomPlot(plot))) { if (!plot.hasOwner()) {
return !sendMessage(plr, C.UNLINK_REQUIRED); 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); return !sendMessage(plr, C.NO_PLOT_PERMS);
} }
final PlotWorld pWorld = PS.get().getPlotWorld(plot.world); final PlotArea plotworld = plot.getArea();
if (MainUtil.runners.containsKey(plot)) { final HashSet<Plot> plots = plot.getConnectedPlots();
MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER); final Runnable run = new Runnable() {
return false;
}
Runnable runnable = new Runnable() {
@Override @Override
public void run() { public void run() {
if ((EconHandler.manager != null) && pWorld.USE_ECONOMY && plot.hasOwner() && plot.isOwner(UUIDHandler.getUUID(plr))) { if (plot.getRunning() > 0) {
final double c = pWorld.SELL_PRICE; MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER);
if (c > 0d) { return;
EconHandler.manager.depositMoney(plr, c);
sendMessage(plr, C.ADDED_BALANCE, c + "");
}
} }
if (plot.unclaim()) { final long start = System.currentTimeMillis();
final long start = System.currentTimeMillis(); boolean result = plot.deletePlot(new Runnable() {
final boolean result = MainUtil.clearAsPlayer(plot, true, new Runnable() { @Override
@Override public void run() {
public void run() { plot.removeRunning();
MainUtil.sendMessage(plr, C.CLEARING_DONE, "" + (System.currentTimeMillis() - start)); 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 { else {
MainUtil.sendMessage(plr, C.UNCLAIM_FAILED); MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER);
} }
} }
}; };
if (Settings.CONFIRM_DELETE && !(Permissions.hasPermission(plr, "plots.confirm.bypass"))) { if (Settings.CONFIRM_DELETE && !(Permissions.hasPermission(plr, "plots.confirm.bypass"))) {
CmdConfirm.addPending(plr, "/plot delete " + plot.id, runnable); CmdConfirm.addPending(plr, "/plot delete " + plot.getId(), run);
} } else {
else { TaskManager.runTask(run);
TaskManager.runTask(runnable);
} }
return true; 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.Location;
import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.util.BlockManager;
import com.intellectualcrafters.plot.util.EventUtil; import com.intellectualcrafters.plot.util.EventUtil;
import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.UUIDHandler; 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.Argument;
import com.plotsquared.general.commands.CommandDeclaration; import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration( @CommandDeclaration(command = "deny", aliases = { "d", "ban" }, description = "Deny a user from a plot", usage = "/plot deny <player>", category = CommandCategory.SETTINGS, requiredType = RequiredType.NONE)
command = "deny",
aliases = {"d"},
description = "Deny a user from a plot",
usage = "/plot deny <player>",
category = CommandCategory.ACTIONS,
requiredType = RequiredType.NONE
)
public class Deny extends SubCommand { public class Deny extends SubCommand {
public Deny() { public Deny() {
requiredArguments = new Argument[] { requiredArguments = new Argument[] { Argument.PlayerName };
Argument.PlayerName
};
} }
@Override @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 Location loc = plr.getLocation();
final Plot plot = MainUtil.getPlot(loc); final Plot plot = loc.getPlotAbs();
if (plot == null) { if (plot == null) {
return !sendMessage(plr, C.NOT_IN_PLOT); return !sendMessage(plr, C.NOT_IN_PLOT);
} }
if ((plot == null) || !plot.hasOwner()) { if (!plot.hasOwner()) {
MainUtil.sendMessage(plr, C.PLOT_UNOWNED); MainUtil.sendMessage(plr, C.PLOT_UNOWNED);
return false; return false;
} }
@ -75,11 +65,7 @@ public class Deny extends SubCommand {
uuid = UUIDHandler.getUUID(args[0], null); uuid = UUIDHandler.getUUID(args[0], null);
} }
if (uuid == null) { if (uuid == null) {
if (UUIDHandler.implementation instanceof SQLUUIDHandler) { MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[0]);
MainUtil.sendMessage(plr, C.INVALID_PLAYER_WAIT, args[0]);
} else {
MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[0]);
}
return false; return false;
} }
if (plot.isOwner(uuid)) { if (plot.isOwner(uuid)) {
@ -97,16 +83,26 @@ public class Deny extends SubCommand {
EventUtil.manager.callDenied(plr, plot, uuid, true); EventUtil.manager.callDenied(plr, plot, uuid, true);
MainUtil.sendMessage(plr, C.DENIED_ADDED); MainUtil.sendMessage(plr, C.DENIED_ADDED);
if (!uuid.equals(DBFunc.everyone)) { if (!uuid.equals(DBFunc.everyone)) {
handleKick(uuid, plot); handleKick(UUIDHandler.getPlayer(uuid), plot);
} else {
for (PlotPlayer pp : plot.getPlayersInPlot()) {
handleKick(pp, plot);
}
} }
return true; return true;
} }
private void handleKick(final UUID uuid, final Plot plot) { private void handleKick(final PlotPlayer pp, final Plot plot) {
PlotPlayer pp = UUIDHandler.getPlayer(uuid); if (pp == null) {
if (pp != null && plot.equals(MainUtil.getPlot(pp.getLocation()))) { return;
pp.teleport(BlockManager.manager.getSpawn(pp.getLocation().getWorld()));
MainUtil.sendMessage(pp, C.YOU_GOT_DENIED);
} }
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; package com.intellectualcrafters.plot.commands;
import java.util.UUID;
import com.intellectualcrafters.plot.config.C; 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.object.PlotPlayer;
import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.general.commands.Argument;
import com.plotsquared.general.commands.CommandDeclaration; import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration( @CommandDeclaration(
command = "limit", command = "setdescription",
permission = "plots.limit", permission = "plots.set.desc",
description = "Set or increment player plot claim limits", description = "Set the plot description",
aliases = {"setlimit"}, usage = "/plot desc <description>",
usage = "/plot limit <player> <expression>", aliases = { "desc", "setdesc", "setd", "description" },
category = CommandCategory.DEBUG category = CommandCategory.SETTINGS,
) requiredType = RequiredType.NONE)
public class Limit extends SubCommand { public class Desc extends SetCommand {
public Limit() {
requiredArguments = new Argument[] {
Argument.String,
Argument.String
};
}
@Override @Override
public boolean onCommand(final PlotPlayer plr, final String[] args) { public boolean set(PlotPlayer plr, Plot plot, String desc) {
UUID uuid = UUIDHandler.getUUID(args[0], null); if (desc.isEmpty()) {
if (uuid == null) { plot.removeFlag("description");
MainUtil.sendMessage(plr, C.INVALID_PLAYER, args[0]); 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; return false;
} }
OfflinePlotPlayer op = UUIDHandler.getUUIDWrapper().getOfflinePlayer(uuid); MainUtil.sendMessage(plr, C.DESC_SET);
// get current plot limit
// increase
// EconHandler.manager.setPermission(op, perm, value);
plr.sendMessage("TODO");
return true; 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.PlotAnalysis;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.RunnableVal; import com.intellectualcrafters.plot.object.RunnableVal;
import com.intellectualcrafters.plot.util.BlockManager;
import com.intellectualcrafters.plot.util.MainUtil; import com.intellectualcrafters.plot.util.MainUtil;
import com.intellectualcrafters.plot.util.Permissions; import com.intellectualcrafters.plot.util.Permissions;
import com.intellectualcrafters.plot.util.UUIDHandler;
import com.plotsquared.general.commands.CommandDeclaration; import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration( @CommandDeclaration(command = "done", aliases = { "submit" }, description = "Mark a plot as done", permission = "plots.done", category = CommandCategory.SETTINGS, requiredType = RequiredType.NONE)
command = "done",
aliases = {"submit"},
description = "Mark a plot as done",
permission = "plots.done",
category = CommandCategory.ACTIONS,
requiredType = RequiredType.NONE
)
public class Done extends SubCommand { public class Done extends SubCommand {
@Override @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 Location loc = plr.getLocation();
final Plot plot = MainUtil.getPlot(loc); final Plot plot = loc.getPlotAbs();
if (plot == null || !plot.hasOwner()) { if ((plot == null) || !plot.hasOwner()) {
return !sendMessage(plr, C.NOT_IN_PLOT); return !sendMessage(plr, C.NOT_IN_PLOT);
} }
if ((!plot.isOwner(plr.getUUID())) && !Permissions.hasPermission(plr, "plots.admin.command.done")) { if ((!plot.isOwner(plr.getUUID())) && !Permissions.hasPermission(plr, "plots.admin.command.done")) {
MainUtil.sendMessage(plr, C.NO_PLOT_PERMS); MainUtil.sendMessage(plr, C.NO_PLOT_PERMS);
return false; return false;
} }
if (plot.getSettings().flags.containsKey("done")) { if (plot.getFlags().containsKey("done")) {
MainUtil.sendMessage(plr, C.DONE_ALREADY_DONE); MainUtil.sendMessage(plr, C.DONE_ALREADY_DONE);
return false; return false;
} }
if (MainUtil.runners.containsKey(plot)) { if (plot.getRunning() > 0) {
MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER); MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER);
return false; return false;
} }
MainUtil.runners.put(plot, 1); plot.addRunning();
MainUtil.sendMessage(plr, C.GENERATING_LINK);
HybridUtils.manager.analyzePlot(plot, new RunnableVal<PlotAnalysis>() { HybridUtils.manager.analyzePlot(plot, new RunnableVal<PlotAnalysis>() {
@Override @Override
public void run() { public void run(PlotAnalysis value) {
MainUtil.runners.remove(plot); plot.removeRunning();
if (value == null || value.getComplexity() >= Settings.CLEAR_THRESHOLD) { if ((value == null) || (value.getComplexity() >= Settings.CLEAR_THRESHOLD)) {
Flag flag = new Flag(FlagManager.getFlag("done"), (System.currentTimeMillis() / 1000)); final Flag flag = new Flag(FlagManager.getFlag("done"), (System.currentTimeMillis() / 1000));
FlagManager.addPlotFlag(plot, flag); FlagManager.addPlotFlag(plot, flag);
MainUtil.sendMessage(plr, C.DONE_SUCCESS); MainUtil.sendMessage(plr, C.DONE_SUCCESS);
} } else {
else {
MainUtil.sendMessage(plr, C.DONE_INSUFFICIENT_COMPLEXITY); 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.PS;
import com.intellectualcrafters.plot.config.C; import com.intellectualcrafters.plot.config.C;
import com.intellectualcrafters.plot.config.Settings; import com.intellectualcrafters.plot.config.Settings;
import com.intellectualcrafters.plot.flag.FlagManager;
import com.intellectualcrafters.plot.object.Plot; import com.intellectualcrafters.plot.object.Plot;
import com.intellectualcrafters.plot.object.PlotPlayer; import com.intellectualcrafters.plot.object.PlotPlayer;
import com.intellectualcrafters.plot.object.RunnableVal; import com.intellectualcrafters.plot.object.RunnableVal;
@ -15,16 +16,9 @@ import com.intellectualcrafters.plot.util.SchematicHandler;
import com.intellectualcrafters.plot.util.TaskManager; import com.intellectualcrafters.plot.util.TaskManager;
import com.plotsquared.general.commands.CommandDeclaration; import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration( @CommandDeclaration(command = "download", aliases = { "dl" }, category = CommandCategory.SCHEMATIC, requiredType = RequiredType.NONE, description = "Download your plot", permission = "plots.download")
command = "download",
aliases = {"dl"},
category = CommandCategory.ACTIONS,
requiredType = RequiredType.NONE,
description = "Download your plot",
permission = "plots.download"
)
public class Download extends SubCommand { public class Download extends SubCommand {
@Override @Override
public boolean onCommand(final PlotPlayer plr, final String[] args) { public boolean onCommand(final PlotPlayer plr, final String[] args) {
@ -33,10 +27,10 @@ public class Download extends SubCommand {
return false; return false;
} }
final String world = plr.getLocation().getWorld(); final String world = plr.getLocation().getWorld();
if (!PS.get().isPlotWorld(world)) { if (!PS.get().hasPlotArea(world)) {
return !sendMessage(plr, C.NOT_IN_PLOT_WORLD); return !sendMessage(plr, C.NOT_IN_PLOT_WORLD);
} }
final Plot plot = MainUtil.getPlot(plr.getLocation()); final Plot plot = plr.getCurrentPlot();
if (plot == null) { if (plot == null) {
return !sendMessage(plr, C.NOT_IN_PLOT); return !sendMessage(plr, C.NOT_IN_PLOT);
} }
@ -44,30 +38,30 @@ public class Download extends SubCommand {
MainUtil.sendMessage(plr, C.PLOT_UNOWNED); MainUtil.sendMessage(plr, C.PLOT_UNOWNED);
return false; 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); MainUtil.sendMessage(plr, C.NO_PLOT_PERMS);
return false; return false;
} }
if (MainUtil.runners.containsKey(plot)) { if (plot.getRunning() > 0) {
MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER); MainUtil.sendMessage(plr, C.WAIT_FOR_TIMER);
return false; return false;
} }
MainUtil.runners.put(plot, 1); plot.addRunning();
MainUtil.sendMessage(plr, C.GENERATING_LINK); MainUtil.sendMessage(plr, C.GENERATING_LINK);
SchematicHandler.manager.getCompoundTag(plot.world, plot.id, new RunnableVal<CompoundTag>() { SchematicHandler.manager.getCompoundTag(plot, new RunnableVal<CompoundTag>() {
@Override @Override
public void run() { public void run(final CompoundTag value) {
TaskManager.runTaskAsync(new Runnable() { TaskManager.runTaskAsync(new Runnable() {
@Override @Override
public void run() { public void run() {
URL url = SchematicHandler.manager.upload(value, null, null); final URL url = SchematicHandler.manager.upload(value, null, null);
if (url == null) { if (url == null) {
MainUtil.sendMessage(plr, C.GENERATING_LINK_FAILED); MainUtil.sendMessage(plr, C.GENERATING_LINK_FAILED);
MainUtil.runners.remove(plot); plot.removeRunning();
return; return;
} }
MainUtil.sendMessage(plr, url.toString()); MainUtil.sendMessage(plr, url.toString());
MainUtil.runners.remove(plot); plot.removeRunning();
} }
}); });
} }

View File

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

View File

@ -20,76 +20,15 @@
//////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////
package com.intellectualcrafters.plot.commands; 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.object.PlotPlayer;
import com.intellectualcrafters.plot.util.MainUtil;
import com.plotsquared.general.commands.CommandDeclaration; import com.plotsquared.general.commands.CommandDeclaration;
@CommandDeclaration( @CommandDeclaration(command = "home", aliases = { "h" }, description = "Go to your plot", usage = "/plot home [id|alias]",
command = "home", category = CommandCategory.TELEPORT, requiredType = RequiredType.NONE)
aliases = {"h"},
description = "Go to your plot",
usage = "/plot home [id|alias]",
category = CommandCategory.TELEPORT,
requiredType = RequiredType.NONE
)
public class Home extends SubCommand { 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 @Override
public boolean onCommand(final PlotPlayer plr, String[] args) { 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); return MainCommand.getInstance().getCommand("visit").onCommand(plr, args);
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);
} }
} }

View File

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

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