From a6375796c0ac0ac5589b44f84d25db0121ef7adc Mon Sep 17 00:00:00 2001 From: Jesse Boyd Date: Sat, 11 Oct 2014 00:33:10 -0700 Subject: [PATCH] No red files anymore. Some stuff still unfinished. + weekly code cleanup --- .../plot/AbstractFlag.java | 59 +- .../src/com/intellectualcrafters/plot/C.java | 554 +++-- .../plot/Configuration.java | 360 +-- .../plot/ConfigurationNode.java | 93 +- .../plot/ConsoleColors.java | 178 +- .../com/intellectualcrafters/plot/Flag.java | 149 +- .../plot/FlagManager.java | 173 +- .../intellectualcrafters/plot/LSetCube.java | 202 +- .../com/intellectualcrafters/plot/Lag.java | 143 +- .../com/intellectualcrafters/plot/Logger.java | 85 +- .../intellectualcrafters/plot/Metrics.java | 1280 +++++----- .../com/intellectualcrafters/plot/PWE.java | 158 +- .../plot/PlayerFunctions.java | 436 ++-- .../com/intellectualcrafters/plot/Plot.java | 498 ++-- .../intellectualcrafters/plot/PlotBlock.java | 13 +- .../plot/PlotGenerator.java | 8 +- .../intellectualcrafters/plot/PlotHelper.java | 1517 ++++++------ .../plot/PlotHomePosition.java | 32 +- .../com/intellectualcrafters/plot/PlotId.java | 92 +- .../intellectualcrafters/plot/PlotMain.java | 2137 +++++++++-------- .../plot/PlotManager.java | 87 +- .../plot/PlotSettings.java | 356 +-- .../plot/PlotSquaredException.java | 37 +- .../intellectualcrafters/plot/PlotWorld.java | 316 ++- .../com/intellectualcrafters/plot/RUtils.java | 113 +- .../plot/ReflectionUtils.java | 1023 ++++---- .../plot/SchematicHandler.java | 264 +- .../plot/SetBlockFast.java | 67 +- .../intellectualcrafters/plot/Settings.java | 149 +- .../com/intellectualcrafters/plot/Title.java | 748 +++--- .../plot/UUIDHandler.java | 372 +-- .../plot/api/PlotAPI.java | 515 ++-- .../plot/commands/Auto.java | 302 +-- .../plot/commands/Camera.java | 124 +- .../plot/commands/Claim.java | 182 +- .../plot/commands/Clear.java | 36 +- .../plot/commands/Command.java | 304 +-- .../plot/commands/CommandPermission.java | 39 +- .../plot/commands/Copy.java | 36 +- .../plot/commands/Debug.java | 181 +- .../plot/commands/Delete.java | 90 +- .../plot/commands/Denied.java | 218 +- .../plot/commands/Help.java | 15 +- .../plot/commands/Helpers.java | 199 +- .../plot/commands/Home.java | 109 +- .../plot/commands/Info.java | 218 +- .../plot/commands/Inventory.java | 77 +- .../plot/commands/Kick.java | 68 +- .../plot/commands/MainCommand.java | 251 +- .../plot/commands/Merge.java | 269 ++- .../plot/commands/Rate.java | 113 +- .../plot/commands/Reload.java | 35 +- .../plot/commands/Schematic.java | 127 +- .../plot/commands/Set.java | 748 +++--- .../plot/commands/SetOwner.java | 68 +- .../plot/commands/Setup.java | 353 +-- .../plot/commands/SubCommand.java | 201 +- .../plot/commands/TP.java | 127 +- .../plot/commands/Trusted.java | 200 +- .../plot/commands/Unlink.java | 244 +- .../plot/commands/Visit.java | 92 +- .../plot/commands/list.java | 228 +- .../plot/commands/plugin.java | 119 +- .../plot/database/DBFunc.java | 1722 +++++++------ .../plot/database/Database.java | 151 +- .../plot/database/MySQL.java | 156 +- .../plot/database/PlotMeConverter.java | 298 ++- .../plot/database/SQLite.java | 144 +- .../plot/events/PlayerClaimPlotEvent.java | 72 +- .../plot/events/PlayerEnterPlotEvent.java | 48 +- .../plot/events/PlayerLeavePlotEvent.java | 48 +- .../plot/events/PlayerPlotDeniedEvent.java | 113 +- .../plot/events/PlayerPlotHelperEvent.java | 111 +- .../plot/events/PlayerPlotTrustedEvent.java | 111 +- .../events/PlayerTeleportToPlotEvent.java | 97 +- .../plot/events/PlotClearEvent.java | 90 +- .../plot/events/PlotDeleteEvent.java | 90 +- .../plot/events/PlotFlagAddEvent.java | 90 +- .../plot/events/PlotFlagRemoveEvent.java | 90 +- .../plot/events/PlotMergeEvent.java | 96 +- .../plot/events/PlotUnlinkEvent.java | 80 +- .../plot/generator/DefaultPlotManager.java | 1312 +++++----- .../plot/generator/DefaultPlotWorld.java | 336 +-- .../plot/generator/WorldGenerator.java | 1061 ++++---- .../plot/generator/XPopulator.java | 911 +++---- .../plot/listeners/PlayerEvents.java | 1364 ++++++----- .../plot/listeners/WorldEditListener.java | 247 +- .../plot/listeners/WorldGuardListener.java | 248 +- .../plot/uuid/NameFetcher.java | 63 +- .../plot/uuid/UUIDFetcher.java | 149 +- .../intellectualsites/web/IndexHandler.java | 127 +- .../com/intellectualsites/web/PlotWeb.java | 49 +- .../web/ResourceHandler.java | 70 +- .../src/com/intellectualsites/web/Test.java | 14 +- 94 files changed, 14237 insertions(+), 12908 deletions(-) diff --git a/PlotSquared/src/com/intellectualcrafters/plot/AbstractFlag.java b/PlotSquared/src/com/intellectualcrafters/plot/AbstractFlag.java index 246591f13..591c32f62 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/AbstractFlag.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/AbstractFlag.java @@ -7,37 +7,38 @@ import org.apache.commons.lang.StringUtils; */ public class AbstractFlag { - private final String key; + private final String key; - /** - * AbstractFlag is a parameter used in creating a new Flag - * - * @param key - * The key must be alphabetical characters and <= 16 characters - * in length - */ - public AbstractFlag(String key) { - if (!StringUtils.isAlpha(key)) { - throw new IllegalArgumentException("Flag must be alphabetic characters"); - } - if (key.length() > 16) { - throw new IllegalArgumentException("Key must be <= 16 characters"); - } - this.key = key.toLowerCase(); - } + /** + * AbstractFlag is a parameter used in creating a new Flag + * + * @param key + * The key must be alphabetical characters and <= 16 characters + * in length + */ + public AbstractFlag(String key) { + if (!StringUtils.isAlpha(key)) { + throw new IllegalArgumentException( + "Flag must be alphabetic characters"); + } + if (key.length() > 16) { + throw new IllegalArgumentException("Key must be <= 16 characters"); + } + this.key = key.toLowerCase(); + } - /** - * AbstractFlag key - * - * @return String - */ - public String getKey() { - return this.key; - } + /** + * AbstractFlag key + * + * @return String + */ + public String getKey() { + return this.key; + } - @Override - public String toString() { - return this.key; - } + @Override + public String toString() { + return this.key; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/C.java b/PlotSquared/src/com/intellectualcrafters/plot/C.java index 7c7609b37..f9c4d9a55 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/C.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/C.java @@ -13,246 +13,336 @@ import org.bukkit.ChatColor; /** * Captions class. - * + * * @author Citymonstret - * + * */ public enum C { - /* - * Ratings - */ - RATING_NOT_VALID("&cYou need to specify a number between 1 and 10"), RATING_ALREADY_EXISTS("&cYou have already rated plot &c%s"), RATING_APPLIED("&cYou successfully rated plot &6%s"), RATING_NOT_YOUR_OWN("&cYou cannot rate your own plot"), RATING_NOT_OWNED("&cYou cannot rate a plot that is not claimed by anyone"), - /* - * Economy Stuff - */ - CANNOT_AFFORD_PLOT("&cYou cannot afford to buy this plot. It costs &6%s"), CANNOT_AFFORD_MERGE("&cYou cannot afford to merge the plots. It costs &6%s"), ADDED_BALANCE("&6%s &chas been added to your balance"), REMOVED_BALANCE("&6%s &chas been taken from your balance"), - /* - * Setup Stuff - */ - SETUP_INIT("&6PlotSquared Setup -> Setup a new plotworld"), SETUP_STEP("&cStep &6%s&c: %s &c"), SETUP_INVALID_ARG("&c%s is not a valid argument for step %s. To cancel setup use: /plot setup cancel"), SETUP_VALID_ARG("&cValue &6%s &cset for step %s"), SETUP_FINISHED("&cFinished setup for world &c%s.\n&4If you are using MULTIVERSE or MULTIWORLD you will need to import this world. Otherwise you will need to add this world to the 'bukkit.yml' file (See installation tutorial for more info)"), SETUP_WORLD_TAKEN("&c%s is already a registered plotworld"), SETUP_MISSING_WORLD("&cYou need to specify a world name (&6/p setup {world}&c)\n&6Additional commands:\n&c - &6/p setup \n&c - &6/p setup back\n&c - &6/p setup cancel"), - /* - * Schematic Stuff - */ - SCHEMATIC_MISSING_ARG("&cYou need to specify an argument. Possible values: &6test {name}"), SCHEMATIC_INVALID("&cThat is not a valid schematic. Reason: &c%s"), SCHEMATIC_VALID("&cThat's a valid schematic"), SCHEMATIC_PASTE_FAILED("&cFailed to paste schematic"), SCHEMATIC_PASTE_SUCCESS("&cSchematic pasted successfully"), - /* - * Title Stuff - */ - TITLE_ENTERED_PLOT("You entered plot %s"), TITLE_ENTERED_PLOT_COLOR("GOLD"), TITLE_ENTERED_PLOT_SUB("Owned by %s"), TITLE_ENTERED_PLOT_SUB_COLOR("RED"), TITLE_LEFT_PLOT("You entered plot %s"), TITLE_LEFT_PLOT_COLOR("GOLD"), TITLE_LEFT_PLOT_SUB("Owned by %s"), TITLE_LEFT_PLOT_SUB_COLOR("RED"), - /* - * Core Stuff - */ - PREFIX("&c[&6&lPlot&c] "), ENABLED("&6Plots are now enabled"), EXAMPLE_MESSAGE("&cThis is an example message &k!!!"), - /* - * Reload - */ - RELOADED_CONFIGS("&6The translation files has been reloaded"), RELOAD_FAILED("&cFailed to reload the translations file"), - /* - * BarAPI - */ - BOSSBAR_CLEARING("&cClearing plot: &6%id%"), - /* - * Alias - */ - ALIAS_SET_TO("&cPlot alias set to &6%alias%"), MISSING_ALIAS("&cYou need to specify the alias"), ALIAS_IS_TAKEN("&cThat alias is already taken"), - /* - * Position - */ - MISSING_POSITION("&cYou need to specify a position. Possible values: &6default&c, &6center"), POSITION_SET("&cPlot home position set"), INVALID_POSITION("&cThat is not a valid position value"), - /* - * Time - */ - TIME_FORMAT("&6%hours%, %min%, %sec%"), - /* - * Permission - */ - NO_SCHEMATIC_PERMISSION("&cYou don't have the permission required to use schematic &6%s"), NO_PERMISSION("&cYou don't have the permissions required to use this command."), NO_PLOT_PERMS("&cYou don't have the permissions to do that in this plot"), CANT_CLAIM_MORE_PLOTS("&cYou can't claim more plots."), YOU_BE_DENIED("&cYou are not allowed to enter this plot"), + /* + * Ratings + */ + RATING_NOT_VALID("&cYou need to specify a number between 1 and 10"), RATING_ALREADY_EXISTS( + "&cYou have already rated plot &c%s"), RATING_APPLIED( + "&cYou successfully rated plot &6%s"), RATING_NOT_YOUR_OWN( + "&cYou cannot rate your own plot"), RATING_NOT_OWNED( + "&cYou cannot rate a plot that is not claimed by anyone"), + /* + * Economy Stuff + */ + CANNOT_AFFORD_PLOT("&cYou cannot afford to buy this plot. It costs &6%s"), CANNOT_AFFORD_MERGE( + "&cYou cannot afford to merge the plots. It costs &6%s"), ADDED_BALANCE( + "&6%s &chas been added to your balance"), REMOVED_BALANCE( + "&6%s &chas been taken from your balance"), + /* + * Setup Stuff + */ + SETUP_INIT("&6PlotSquared Setup -> Setup a new plotworld"), SETUP_STEP( + "&cStep &6%s&c: %s &c"), SETUP_INVALID_ARG( + "&c%s is not a valid argument for step %s. To cancel setup use: /plot setup cancel"), SETUP_VALID_ARG( + "&cValue &6%s &cset for step %s"), SETUP_FINISHED( + "&cFinished setup for world &c%s.\n&4If you are using MULTIVERSE or MULTIWORLD you will need to import this world. Otherwise you will need to add this world to the 'bukkit.yml' file (See installation tutorial for more info)"), SETUP_WORLD_TAKEN( + "&c%s is already a registered plotworld"), SETUP_MISSING_WORLD( + "&cYou need to specify a world name (&6/p setup {world}&c)\n&6Additional commands:\n&c - &6/p setup \n&c - &6/p setup back\n&c - &6/p setup cancel"), + /* + * Schematic Stuff + */ + SCHEMATIC_MISSING_ARG( + "&cYou need to specify an argument. Possible values: &6test {name}"), SCHEMATIC_INVALID( + "&cThat is not a valid schematic. Reason: &c%s"), SCHEMATIC_VALID( + "&cThat's a valid schematic"), SCHEMATIC_PASTE_FAILED( + "&cFailed to paste schematic"), SCHEMATIC_PASTE_SUCCESS( + "&cSchematic pasted successfully"), + /* + * Title Stuff + */ + TITLE_ENTERED_PLOT("You entered plot %s"), TITLE_ENTERED_PLOT_COLOR("GOLD"), TITLE_ENTERED_PLOT_SUB( + "Owned by %s"), TITLE_ENTERED_PLOT_SUB_COLOR("RED"), TITLE_LEFT_PLOT( + "You entered plot %s"), TITLE_LEFT_PLOT_COLOR("GOLD"), TITLE_LEFT_PLOT_SUB( + "Owned by %s"), TITLE_LEFT_PLOT_SUB_COLOR("RED"), + /* + * Core Stuff + */ + PREFIX("&c[&6&lPlot&c] "), ENABLED("&6Plots are now enabled"), EXAMPLE_MESSAGE( + "&cThis is an example message &k!!!"), + /* + * Reload + */ + RELOADED_CONFIGS("&6The translation files has been reloaded"), RELOAD_FAILED( + "&cFailed to reload the translations file"), + /* + * BarAPI + */ + BOSSBAR_CLEARING("&cClearing plot: &6%id%"), + /* + * Alias + */ + ALIAS_SET_TO("&cPlot alias set to &6%alias%"), MISSING_ALIAS( + "&cYou need to specify the alias"), ALIAS_IS_TAKEN( + "&cThat alias is already taken"), + /* + * Position + */ + MISSING_POSITION( + "&cYou need to specify a position. Possible values: &6default&c, &6center"), POSITION_SET( + "&cPlot home position set"), INVALID_POSITION( + "&cThat is not a valid position value"), + /* + * Time + */ + TIME_FORMAT("&6%hours%, %min%, %sec%"), + /* + * Permission + */ + NO_SCHEMATIC_PERMISSION( + "&cYou don't have the permission required to use schematic &6%s"), NO_PERMISSION( + "&cYou don't have the permissions required to use this command."), NO_PLOT_PERMS( + "&cYou don't have the permissions to do that in this plot"), CANT_CLAIM_MORE_PLOTS( + "&cYou can't claim more plots."), YOU_BE_DENIED( + "&cYou are not allowed to enter this plot"), - NO_PERM_MERGE("&cYou are not the owner of the plot: &6%plot%"), UNLINK_REQUIRED("&cAn unlink is required to do this."), UNLINK_IMPOSSIBLE("&cYou can only unlink a mega-plot"), NO_MERGE_TO_MEGA("&cMega plots cannot be merged into. Please merge from the desired mega plot."), - /* - * Commands - */ - NOT_VALID_SUBCOMMAND("&cThat is not a valid subcommand."), NO_COMMANDS("&cI'm sorry, but you're not permitted to use any subcommands."), SUBCOMMAND_SET_OPTIONS_HEADER("&cPossible Values: "), - /* - * Player not found - */ - INVALID_PLAYER("&cPlayer not found: &6%player%."), - /* - * - */ - COMMAND_WENT_WRONG("&cSomething went wrong when executing that command..."), - /* - * No {plot} - */ - NOT_IN_PLOT("&cYou're not in a plot"), NOT_IN_PLOT_WORLD("&cYou're not in a plot world"), NOT_VALID_WORLD("&cThat is not a valid world (case sensitive)"), NOT_VALID_PLOT_WORLD("&cThat is not a valid plot world (case sensitive)"), NO_PLOTS("&cYou don't have any plots"), - /* - * Block List - */ - NOT_VALID_BLOCK_LIST_HEADER("&cThat's not a valid block. Valid blocks are:\\n"), BLOCK_LIST_ITEM(" &6%mat%&c,"), BLOCK_LIST_SEPARATER("&6,&c "), - /* - * Biome - */ - NEED_BIOME("&cYou've got to specify a biome"), BIOME_SET_TO("&cPlot biome set to &c"), - /* - * Teleport / Entry - */ - TELEPORTED_TO_PLOT("&6You have been teleported"), - /* - * Set Block - */ - SET_BLOCK_ACTION_FINISHED("&6The last setblock action is now finished."), - /* - * Debug - */ - DEUBG_HEADER("&6Debug Information\\n"), DEBUG_SECTION("&c>> &6&l%val%"), DEBUG_LINE("&c>> &6%var%&c:&6 %val%\\n"), - /* - * Invalid - */ - NOT_VALID_DATA("&cThat's not a valid data id."), NOT_VALID_BLOCK("&cThat's not a valid block."), NOT_VALID_NUMBER("&cThat's not a valid number"), NOT_VALID_PLOT_ID("&cThat's not a valid plot id."), NOT_YOUR_PLOT("&cThat is not your plot."), NO_SUCH_PLOT("&cThere is no such plot"), PLAYER_HAS_NOT_BEEN_ON("&cThat player hasn't been in the plotworld"), FOUND_NO_PLOTS("&cFound no plots with your search query"), - /* - * Camera - */ - CAMERA_STARTED("&cYou have entered camera mode for plot &6%s"), CAMERA_STOPPED("&cYou are no longer in camera mode"), - /* - * Need - */ - NEED_PLOT_NUMBER("&cYou've got to specify a plot number or alias"), NEED_BLOCK("&cYou've got to specify a block"), NEED_PLOT_ID("&cYou've got to specify a plot id."), NEED_USER("&cYou need to specify a username"), - /* - * Info - */ - PLOT_INFO_UNCLAIMED("&cPlot &6%s&c is not yet claimed"), PLOT_INFO("plot ID: &6%id%&c, plot Alias: &6%alias%&c, plot Owner: &6%owner%&c, plot Biome: &6%biome%&c, plot Time: &6%time%&c, plot Weather: &6%weather%&c, plot Helpers:&6%helpers%&c, plot Trusted:&6%trusted%&c, plot Denied:&6%denied%&c, plot Rating: &6%rating%, &cplot flags: &6%flags%"), PLOT_USER_LIST(" &6%user%&c,"), - /* - * Generating - */ - GENERATING_FLOOR("&6Started generating floor from your settings. It will take %time%"), GENERATING_WALL("&6Started generating wall from your settings"), GENERATING_WALL_FILLING("&cStarted generating wall filling from your settings."), - /* - * Clearing - */ - CLEARING_PLOT("&cClearing plot."), CLEARING_DONE("&6Done, took &a%time%&6 ms!"), CLEARING_DONE_PACKETS("&6(&a%time% &6ms for packets)"), - /* - * Claiming - */ - PLOT_NOT_CLAIMED("&cCannot claim plot"), PLOT_IS_CLAIMED("&cThis plot is already claimed"), CLAIMED("&6You successfully claimed the plot"), - /* - * List - */ - PLOT_LIST_HEADER("&6List of %word% plots"), PLOT_LIST_ITEM("&c>> &6%id% &c- &6%owner%"), PLOT_LIST_FOOTER("&c>> &6%word% a total of &c%num% &6claimed %plot%."), - /* - * Left - */ - LEFT_PLOT("&cYou left a plot"), - /* - * Wait - */ - WAIT_FOR_TIMER("&cA setblock timer is bound to either the current plot or you. Please wait for it to finish"), - /* - * Chat - */ - PLOT_CHAT_FORMAT("&c[&6Plot Chat&c][&6%plot_id%&c] &6%sender%&c: &6%msg%"), - /* - * Denied - */ - DENIED_REMOVED("&cYou successfully undenied the player from this plot"), DENIED_ADDED("&cYou successfully denied the player from this plot"), DENIED_NEED_ARGUMENT("&cArguments are missing. &6/plot denied add {name} &cor &6/plot helpers remove {name}"), WAS_NOT_DENIED("&cThat player was not denied on this plot"), - /* - * Rain - */ - NEED_ON_OFF("&cYou need to specify a value. Possible values: &6on&c, &6off"), SETTING_UPDATED("&cYou successfully updated the setting"), - /* - * Flag - */ - NEED_KEY("&cPossible values: &6%values%"), NOT_VALID_FLAG("&cThat is not a valid flag"), NOT_VALID_VALUE("&cFlag values must be alphanumerical"), FLAG_NOT_IN_PLOT("&cThe plot does not have that flag"), FLAG_NOT_REMOVED("&cThe flag could not be removed"), FLAG_NOT_ADDED("&cThe flag could not be added"), FLAG_REMOVED("&6Successfully removed flag"), FLAG_ADDED("&6Successfully added flag"), - /* - * Helper - */ - HELPER_ADDED("&6You successfully added a helper to the plot"), HELPER_REMOVED("&6You successfully removed a helper from the plot"), HELPER_NEED_ARGUMENT("&cArguments are missing. &6/plot helpers add {name} &cor &6/plot helpers remove {name}"), WAS_NOT_ADDED("&cThat player was not added as a helper on this plot"), - /* - * Trusted - */ - TRUSTED_ADDED("&6You successfully added a trusted user to the plot"), TRUSTED_REMOVED("&6You successfully removed a trusted user from the plot"), TRUSTED_NEED_ARGUMENT("&cArguments are missing. &6/plot trusted add {name} &cor &6/plot trusted remove {name}"), T_WAS_NOT_ADDED("&cThat player was not added as a trusted user on this plot"), - /* - * Set Owner - */ - SET_OWNER("&6You successfully set the plot owner"), - /* - * Signs - */ - OWNER_SIGN_LINE_1("&cID: &6%id%"), OWNER_SIGN_LINE_2("&cOwner:"), OWNER_SIGN_LINE_3("&6%plr%"), OWNER_SIGN_LINE_4("&2Claimed"), - /* - * Help - */ - HELP_CATEGORY("&6Current Category&c: &l%category%"), HELP_INFO("&6You need to specify a help category"), HELP_INFO_ITEM("&6/plots help %category% &c- &6%category_desc%"), HELP_PAGE("&c>> &6%usage% &c[&6%alias%&c] &c- &6%desc%"), HELP_HEADER("&6Help for Plots"), - /* - * Direction - */ - DIRECTION("&6Current direction: %dir%"), - /* - * Custom - */ - CUSTOM_STRING("-"); - /** - * Default - */ - private String d; - /** - * Translated - */ - private String s; + NO_PERM_MERGE("&cYou are not the owner of the plot: &6%plot%"), UNLINK_REQUIRED( + "&cAn unlink is required to do this."), UNLINK_IMPOSSIBLE( + "&cYou can only unlink a mega-plot"), NO_MERGE_TO_MEGA( + "&cMega plots cannot be merged into. Please merge from the desired mega plot."), + /* + * Commands + */ + NOT_VALID_SUBCOMMAND("&cThat is not a valid subcommand."), NO_COMMANDS( + "&cI'm sorry, but you're not permitted to use any subcommands."), SUBCOMMAND_SET_OPTIONS_HEADER( + "&cPossible Values: "), + /* + * Player not found + */ + INVALID_PLAYER("&cPlayer not found: &6%player%."), + /* + * + */ + COMMAND_WENT_WRONG("&cSomething went wrong when executing that command..."), + /* + * No {plot} + */ + NOT_IN_PLOT("&cYou're not in a plot"), NOT_IN_PLOT_WORLD( + "&cYou're not in a plot world"), NOT_VALID_WORLD( + "&cThat is not a valid world (case sensitive)"), NOT_VALID_PLOT_WORLD( + "&cThat is not a valid plot world (case sensitive)"), NO_PLOTS( + "&cYou don't have any plots"), + /* + * Block List + */ + NOT_VALID_BLOCK_LIST_HEADER( + "&cThat's not a valid block. Valid blocks are:\\n"), BLOCK_LIST_ITEM( + " &6%mat%&c,"), BLOCK_LIST_SEPARATER("&6,&c "), + /* + * Biome + */ + NEED_BIOME("&cYou've got to specify a biome"), BIOME_SET_TO( + "&cPlot biome set to &c"), + /* + * Teleport / Entry + */ + TELEPORTED_TO_PLOT("&6You have been teleported"), + /* + * Set Block + */ + SET_BLOCK_ACTION_FINISHED("&6The last setblock action is now finished."), + /* + * Debug + */ + DEUBG_HEADER("&6Debug Information\\n"), DEBUG_SECTION("&c>> &6&l%val%"), DEBUG_LINE( + "&c>> &6%var%&c:&6 %val%\\n"), + /* + * Invalid + */ + NOT_VALID_DATA("&cThat's not a valid data id."), NOT_VALID_BLOCK( + "&cThat's not a valid block."), NOT_VALID_NUMBER( + "&cThat's not a valid number"), NOT_VALID_PLOT_ID( + "&cThat's not a valid plot id."), NOT_YOUR_PLOT( + "&cThat is not your plot."), NO_SUCH_PLOT("&cThere is no such plot"), PLAYER_HAS_NOT_BEEN_ON( + "&cThat player hasn't been in the plotworld"), FOUND_NO_PLOTS( + "&cFound no plots with your search query"), + /* + * Camera + */ + CAMERA_STARTED("&cYou have entered camera mode for plot &6%s"), CAMERA_STOPPED( + "&cYou are no longer in camera mode"), + /* + * Need + */ + NEED_PLOT_NUMBER("&cYou've got to specify a plot number or alias"), NEED_BLOCK( + "&cYou've got to specify a block"), NEED_PLOT_ID( + "&cYou've got to specify a plot id."), NEED_USER( + "&cYou need to specify a username"), + /* + * Info + */ + PLOT_INFO_UNCLAIMED("&cPlot &6%s&c is not yet claimed"), PLOT_INFO( + "plot ID: &6%id%&c, plot Alias: &6%alias%&c, plot Owner: &6%owner%&c, plot Biome: &6%biome%&c, plot Time: &6%time%&c, plot Weather: &6%weather%&c, plot Helpers:&6%helpers%&c, plot Trusted:&6%trusted%&c, plot Denied:&6%denied%&c, plot Rating: &6%rating%, &cplot flags: &6%flags%"), PLOT_USER_LIST( + " &6%user%&c,"), + /* + * Generating + */ + GENERATING_FLOOR( + "&6Started generating floor from your settings. It will take %time%"), GENERATING_WALL( + "&6Started generating wall from your settings"), GENERATING_WALL_FILLING( + "&cStarted generating wall filling from your settings."), + /* + * Clearing + */ + CLEARING_PLOT("&cClearing plot."), CLEARING_DONE( + "&6Done, took &a%time%&6 ms!"), CLEARING_DONE_PACKETS( + "&6(&a%time% &6ms for packets)"), + /* + * Claiming + */ + PLOT_NOT_CLAIMED("&cCannot claim plot"), PLOT_IS_CLAIMED( + "&cThis plot is already claimed"), CLAIMED( + "&6You successfully claimed the plot"), + /* + * List + */ + PLOT_LIST_HEADER("&6List of %word% plots"), PLOT_LIST_ITEM( + "&c>> &6%id% &c- &6%owner%"), PLOT_LIST_FOOTER( + "&c>> &6%word% a total of &c%num% &6claimed %plot%."), + /* + * Left + */ + LEFT_PLOT("&cYou left a plot"), + /* + * Wait + */ + WAIT_FOR_TIMER( + "&cA setblock timer is bound to either the current plot or you. Please wait for it to finish"), + /* + * Chat + */ + PLOT_CHAT_FORMAT("&c[&6Plot Chat&c][&6%plot_id%&c] &6%sender%&c: &6%msg%"), + /* + * Denied + */ + DENIED_REMOVED("&cYou successfully undenied the player from this plot"), DENIED_ADDED( + "&cYou successfully denied the player from this plot"), DENIED_NEED_ARGUMENT( + "&cArguments are missing. &6/plot denied add {name} &cor &6/plot helpers remove {name}"), WAS_NOT_DENIED( + "&cThat player was not denied on this plot"), + /* + * Rain + */ + NEED_ON_OFF("&cYou need to specify a value. Possible values: &6on&c, &6off"), SETTING_UPDATED( + "&cYou successfully updated the setting"), + /* + * Flag + */ + NEED_KEY("&cPossible values: &6%values%"), NOT_VALID_FLAG( + "&cThat is not a valid flag"), NOT_VALID_VALUE( + "&cFlag values must be alphanumerical"), FLAG_NOT_IN_PLOT( + "&cThe plot does not have that flag"), FLAG_NOT_REMOVED( + "&cThe flag could not be removed"), FLAG_NOT_ADDED( + "&cThe flag could not be added"), FLAG_REMOVED( + "&6Successfully removed flag"), FLAG_ADDED( + "&6Successfully added flag"), + /* + * Helper + */ + HELPER_ADDED("&6You successfully added a helper to the plot"), HELPER_REMOVED( + "&6You successfully removed a helper from the plot"), HELPER_NEED_ARGUMENT( + "&cArguments are missing. &6/plot helpers add {name} &cor &6/plot helpers remove {name}"), WAS_NOT_ADDED( + "&cThat player was not added as a helper on this plot"), + /* + * Trusted + */ + TRUSTED_ADDED("&6You successfully added a trusted user to the plot"), TRUSTED_REMOVED( + "&6You successfully removed a trusted user from the plot"), TRUSTED_NEED_ARGUMENT( + "&cArguments are missing. &6/plot trusted add {name} &cor &6/plot trusted remove {name}"), T_WAS_NOT_ADDED( + "&cThat player was not added as a trusted user on this plot"), + /* + * Set Owner + */ + SET_OWNER("&6You successfully set the plot owner"), + /* + * Signs + */ + OWNER_SIGN_LINE_1("&cID: &6%id%"), OWNER_SIGN_LINE_2("&cOwner:"), OWNER_SIGN_LINE_3( + "&6%plr%"), OWNER_SIGN_LINE_4("&2Claimed"), + /* + * Help + */ + HELP_CATEGORY("&6Current Category&c: &l%category%"), HELP_INFO( + "&6You need to specify a help category"), HELP_INFO_ITEM( + "&6/plots help %category% &c- &6%category_desc%"), HELP_PAGE( + "&c>> &6%usage% &c[&6%alias%&c] &c- &6%desc%"), HELP_HEADER( + "&6Help for Plots"), + /* + * Direction + */ + DIRECTION("&6Current direction: %dir%"), + /* + * Custom + */ + CUSTOM_STRING("-"); + /** + * Default + */ + private String d; + /** + * Translated + */ + private String s; - /** - * Constructor for custom strings. - */ - @SuppressWarnings("unused") - C() { - /* - * use setCustomString(); - */ - } + /** + * Constructor for custom strings. + */ + @SuppressWarnings("unused") + C() { + /* + * use setCustomString(); + */ + } - /** - * Constructor - * - * @param d - * default - */ - C(String d) { - this.d = d; - if (PlotMain.translations == null) { - this.s = d; - } else { - this.s = PlotMain.translations.getString(this.toString()); - } - if (this.s == null) { - this.s = ""; - } - } + /** + * Constructor + * + * @param d + * default + */ + C(String d) { + this.d = d; + if (PlotMain.translations == null) { + this.s = d; + } else { + this.s = PlotMain.translations.getString(this.toString()); + } + if (this.s == null) { + this.s = ""; + } + } - /** - * Get the default string - * - * @return default - */ - @SuppressWarnings("unused") - public String d() { - return this.d; - } + /** + * Get the default string + * + * @return default + */ + @SuppressWarnings("unused") + public String d() { + return this.d; + } - /** - * Get translated if exists - * - * @return translated if exists else default - */ - public String s() { - if (this.s.length() < 1) { - return this.d.replace("\\n", "\n"); - } - return this.s.replace("\\n", "\n"); - } + /** + * Get translated if exists + * + * @return translated if exists else default + */ + public String s() { + if (this.s.length() < 1) { + return this.d.replace("\\n", "\n"); + } + return this.s.replace("\\n", "\n"); + } - /** - * - * @return translated and color decoded - */ - public String translated() { - return ChatColor.translateAlternateColorCodes('&', this.s()); - } + /** + * + * @return translated and color decoded + */ + public String translated() { + return ChatColor.translateAlternateColorCodes('&', this.s()); + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/Configuration.java b/PlotSquared/src/com/intellectualcrafters/plot/Configuration.java index 24998e4ca..25d209ec6 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/Configuration.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/Configuration.java @@ -5,203 +5,207 @@ import java.util.List; import org.bukkit.block.Biome; - public class Configuration { - public static final SettingValue STRING = new SettingValue("STRING") { - @Override - public boolean validateValue(String string) { - return true; - } + public static final SettingValue STRING = new SettingValue("STRING") { + @Override + public boolean validateValue(String string) { + return true; + } - @Override - public Object parseString(String string) { - return string; - } - }; + @Override + public Object parseString(String string) { + return string; + } + }; - public static final SettingValue STRINGLIST = new SettingValue("STRINGLIST") { - @Override - public boolean validateValue(String string) { - return true; - } + public static final SettingValue STRINGLIST = new SettingValue("STRINGLIST") { + @Override + public boolean validateValue(String string) { + return true; + } - @Override - public Object parseString(String string) { - return string.split(","); - } - }; + @Override + public Object parseString(String string) { + return string.split(","); + } + }; - public static final SettingValue INTEGER = new SettingValue("INTEGER") { - @Override - public boolean validateValue(String string) { - try { - Integer.parseInt(string); - return true; - } catch (Exception e) { - return false; - } - } + public static final SettingValue INTEGER = new SettingValue("INTEGER") { + @Override + public boolean validateValue(String string) { + try { + Integer.parseInt(string); + return true; + } catch (Exception e) { + return false; + } + } - @Override - public Object parseString(String string) { - return Integer.parseInt(string); - } - }; + @Override + public Object parseString(String string) { + return Integer.parseInt(string); + } + }; - public static final SettingValue BOOLEAN = new SettingValue("BOOLEAN") { - @Override - public boolean validateValue(String string) { - try { - Boolean.parseBoolean(string); - return true; - } catch (Exception e) { - return false; - } - } + public static final SettingValue BOOLEAN = new SettingValue("BOOLEAN") { + @Override + public boolean validateValue(String string) { + try { + Boolean.parseBoolean(string); + return true; + } catch (Exception e) { + return false; + } + } - @Override - public Object parseString(String string) { - return Boolean.parseBoolean(string); - } - }; + @Override + public Object parseString(String string) { + return Boolean.parseBoolean(string); + } + }; - public static final SettingValue DOUBLE = new SettingValue("DOUBLE") { - @Override - public boolean validateValue(String string) { - try { - Double.parseDouble(string); - return true; - } catch (Exception e) { - return false; - } - } + public static final SettingValue DOUBLE = new SettingValue("DOUBLE") { + @Override + public boolean validateValue(String string) { + try { + Double.parseDouble(string); + return true; + } catch (Exception e) { + return false; + } + } - @Override - public Object parseString(String string) { - return Double.parseDouble(string); - } - }; + @Override + public Object parseString(String string) { + return Double.parseDouble(string); + } + }; - public static final SettingValue BIOME = new SettingValue("BIOME") { - @Override - public boolean validateValue(String string) { - try { - Biome.valueOf(string.toUpperCase()); - return true; - } catch (Exception e) { - return false; - } - } + public static final SettingValue BIOME = new SettingValue("BIOME") { + @Override + public boolean validateValue(String string) { + try { + Biome.valueOf(string.toUpperCase()); + return true; + } catch (Exception e) { + return false; + } + } - @Override - public Object parseString(String string) { - return Biome.valueOf(string.toUpperCase()); - } - - @Override - public Object parseObject(Object object) { - return ((Biome) object).toString(); - } - }; + @Override + public Object parseString(String string) { + return Biome.valueOf(string.toUpperCase()); + } - public static final SettingValue BLOCK = new SettingValue("BLOCK") { - @Override - public boolean validateValue(String string) { - try { - if (string.contains(":")) { - String[] split = string.split(":"); - Short.parseShort(split[0]); - Short.parseShort(split[1]); - } else { - Short.parseShort(string); - } - return true; - } catch (Exception e) { - return false; - } - } + @Override + public Object parseObject(Object object) { + return ((Biome) object).toString(); + } + }; - @Override - public Object parseString(String string) { - if (string.contains(":")) { - String[] split = string.split(":"); - return new PlotBlock(Short.parseShort(split[0]), Byte.parseByte(split[1])); - } else { - return new PlotBlock(Short.parseShort(string), (byte) 0); - } - } - - @Override - public Object parseObject(Object object) { - return ((PlotBlock) object).id+":"+((PlotBlock) object).data; - } - }; + public static final SettingValue BLOCK = new SettingValue("BLOCK") { + @Override + public boolean validateValue(String string) { + try { + if (string.contains(":")) { + String[] split = string.split(":"); + Short.parseShort(split[0]); + Short.parseShort(split[1]); + } else { + Short.parseShort(string); + } + return true; + } catch (Exception e) { + return false; + } + } - public static final SettingValue BLOCKLIST = new SettingValue("BLOCKLIST") { - @Override - public boolean validateValue(String string) { - try { - for (String block : string.split(",")) { - if (block.contains(":")) { - String[] split = block.split(":"); - Short.parseShort(split[0]); - Short.parseShort(split[1]); - } else { - Short.parseShort(block); - } - } - return true; - } catch (Exception e) { - return false; - } - } + @Override + public Object parseString(String string) { + if (string.contains(":")) { + String[] split = string.split(":"); + return new PlotBlock(Short.parseShort(split[0]), + Byte.parseByte(split[1])); + } else { + return new PlotBlock(Short.parseShort(string), (byte) 0); + } + } - @Override - public Object parseString(String string) { - String[] blocks = string.split(","); - PlotBlock[] values = new PlotBlock[blocks.length]; - for (int i = 0; i list = new ArrayList(); - for (PlotBlock block:(PlotBlock[]) object) { - list.add((block.id+":"+(block.data))); - } - return list; - } - }; + @Override + public Object parseObject(Object object) { + return ((PlotBlock) object).id + ":" + ((PlotBlock) object).data; + } + }; - /** - * - * Create your own SettingValue object to make the management of plotworld configuration easier - * - */ - public static abstract class SettingValue { - private String type; + public static final SettingValue BLOCKLIST = new SettingValue("BLOCKLIST") { + @Override + public boolean validateValue(String string) { + try { + for (String block : string.split(",")) { + if (block.contains(":")) { + String[] split = block.split(":"); + Short.parseShort(split[0]); + Short.parseShort(split[1]); + } else { + Short.parseShort(block); + } + } + return true; + } catch (Exception e) { + return false; + } + } - public SettingValue(String type) { - this.type = type; - } + @Override + public Object parseString(String string) { + String[] blocks = string.split(","); + PlotBlock[] values = new PlotBlock[blocks.length]; + for (int i = 0; i < blocks.length; i++) { + if (string.contains(":")) { + String[] split = string.split(":"); + values[i] = new PlotBlock(Short.parseShort(split[0]), + Byte.parseByte(split[1])); + } else { + values[i] = new PlotBlock(Short.parseShort(string), + (byte) 0); + } + } + return values; + } - public String getType() { - return this.type; - } - - public Object parseObject(Object object) { - return object; - } + @Override + public Object parseObject(Object object) { + List list = new ArrayList(); + for (PlotBlock block : (PlotBlock[]) object) { + list.add((block.id + ":" + (block.data))); + } + return list; + } + }; - public abstract Object parseString(String string); + /** + * + * Create your own SettingValue object to make the management of plotworld + * configuration easier + * + */ + public static abstract class SettingValue { + private String type; - public abstract boolean validateValue(String string); - } + public SettingValue(String type) { + this.type = type; + } + + public String getType() { + return this.type; + } + + public Object parseObject(Object object) { + return object; + } + + public abstract Object parseString(String string); + + public abstract boolean validateValue(String string); + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/ConfigurationNode.java b/PlotSquared/src/com/intellectualcrafters/plot/ConfigurationNode.java index 5e5ee54b5..e803d68ad 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/ConfigurationNode.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/ConfigurationNode.java @@ -7,51 +7,64 @@ import org.apache.commons.lang.StringUtils; import com.intellectualcrafters.plot.Configuration.SettingValue; public class ConfigurationNode { - private String constant; - private Object default_value; - private String description; - private Object value = 0; - private SettingValue type; + private String constant; + private Object default_value; + private String description; + private Object value = 0; + private SettingValue type; - public ConfigurationNode(String constant, Object default_value, String description, SettingValue type, boolean required) { - this.constant = constant; - this.default_value = default_value; - this.description = description; - this.value = default_value; - this.type = type; - } + public ConfigurationNode(String constant, Object default_value, + String description, SettingValue type, boolean required) { + this.constant = constant; + this.default_value = default_value; + this.description = description; + this.value = default_value; + this.type = type; + } - public String getType() { - return this.type.getType(); - } + public String getType() { + return this.type.getType(); + } - public boolean setValue(String string) { - if (!this.type.validateValue(string)) { - return false; - } - this.value = this.type.parseString(string); - return true; - } + public boolean isValid(String string) { + try { + Object result = this.type.parseString(string); + if (result == null) { + return false; + } + return true; + } catch (Exception e) { + return false; + } + } - public Object getValue() { - if (this.value instanceof String[]) { - return Arrays.asList((String[]) this.value); - } - return this.value; - } + public boolean setValue(String string) { + if (!this.type.validateValue(string)) { + return false; + } + this.value = this.type.parseString(string); + return true; + } - public String getConstant() { - return this.constant; - } + public Object getValue() { + if (this.value instanceof String[]) { + return Arrays.asList((String[]) this.value); + } + return this.value; + } - public Object getDefaultValue() { - if (this.default_value instanceof String[]) { - return StringUtils.join((String[]) this.default_value, ","); - } - return this.default_value; - } + public String getConstant() { + return this.constant; + } - public String getDescription() { - return this.description; - } + public Object getDefaultValue() { + if (this.default_value instanceof String[]) { + return StringUtils.join((String[]) this.default_value, ","); + } + return this.default_value; + } + + public String getDescription() { + return this.description; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/ConsoleColors.java b/PlotSquared/src/com/intellectualcrafters/plot/ConsoleColors.java index 33714f513..02cf3738a 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/ConsoleColors.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/ConsoleColors.java @@ -7,95 +7,107 @@ import org.bukkit.ChatColor; */ public class ConsoleColors { - static enum ConsoleColor { - RESET ("\u001B[0m"), - BLACK ("\u001B[30m"), - RED ("\u001B[31m"), - GREEN ("\u001B[32m"), - YELLOW ("\u001B[33m"), - BLUE ("\u001B[34m"), - PURPLE ("\u001B[35m"), - CYAN ("\u001B[36m"), - WHITE ("\u001B[37m"), - BOLD ("\033[1m"), - UNDERLINE ("\033[0m"), - ITALIC ("\033[3m"); + static enum ConsoleColor { + RESET("\u001B[0m"), BLACK("\u001B[30m"), RED("\u001B[31m"), GREEN( + "\u001B[32m"), YELLOW("\u001B[33m"), BLUE("\u001B[34m"), PURPLE( + "\u001B[35m"), CYAN("\u001B[36m"), WHITE("\u001B[37m"), BOLD( + "\033[1m"), UNDERLINE("\033[0m"), ITALIC("\033[3m"); - private String win; - private String lin; + private String win; + private String lin; - ConsoleColor(String lin) { - this.lin = lin; - this.win = win; - } + ConsoleColor(String lin) { + this.lin = lin; + this.win = this.win; + } - public String getWin() { - return win; - } + public String getWin() { + return this.win; + } - public String getLin(){ - return lin; - } - } + public String getLin() { + return this.lin; + } + } - /* public static final String ANSI_RESET = "\u001B[0m"; - public static final String ANSI_BLACK = "\u001B[30m"; - public static final String ANSI_RED = "\u001B[31m"; - public static final String ANSI_GREEN = "\u001B[32m"; - public static final String ANSI_YELLOW = "\u001B[33m"; - public static final String ANSI_BLUE = "\u001B[34m"; - public static final String ANSI_PURPLE = "\u001B[35m"; - public static final String ANSI_CYAN = "\u001B[36m"; - public static final String ANSI_WHITE = "\u001B[37m"; - public static final String ANSI_BOLD = "\033[1m"; - public static final String ANSI_UNDERLINE = "\033[0m"; - public static final String ANSI_ITALIC = "\033[3m]";*/ + /* + * public static final String ANSI_RESET = "\u001B[0m"; public static final + * String ANSI_BLACK = "\u001B[30m"; public static final String ANSI_RED = + * "\u001B[31m"; public static final String ANSI_GREEN = "\u001B[32m"; + * public static final String ANSI_YELLOW = "\u001B[33m"; public static + * final String ANSI_BLUE = "\u001B[34m"; public static final String + * ANSI_PURPLE = "\u001B[35m"; public static final String ANSI_CYAN = + * "\u001B[36m"; public static final String ANSI_WHITE = "\u001B[37m"; + * public static final String ANSI_BOLD = "\033[1m"; public static final + * String ANSI_UNDERLINE = "\033[0m"; public static final String ANSI_ITALIC + * = "\033[3m]"; + */ - public static String fromString(String input) { - input = input.replaceAll("&0", fromChatColor(ChatColor.BLACK)).replaceAll("&1", fromChatColor(ChatColor.DARK_BLUE)).replaceAll("&2", fromChatColor(ChatColor.DARK_GREEN)).replaceAll("&3", fromChatColor(ChatColor.DARK_AQUA)).replaceAll("&4", fromChatColor(ChatColor.DARK_RED)).replaceAll("&5", fromChatColor(ChatColor.DARK_PURPLE)).replaceAll("&6", fromChatColor(ChatColor.GOLD)).replaceAll("&7", fromChatColor(ChatColor.GRAY)).replaceAll("&8", fromChatColor(ChatColor.DARK_GRAY)).replaceAll("&9", fromChatColor(ChatColor.BLUE)).replaceAll("&a", fromChatColor(ChatColor.GREEN)).replaceAll("&b", fromChatColor(ChatColor.AQUA)).replaceAll("&c", fromChatColor(ChatColor.RED)).replaceAll("&d", fromChatColor(ChatColor.LIGHT_PURPLE)).replaceAll("&e", fromChatColor(ChatColor.YELLOW)).replaceAll("&f", fromChatColor(ChatColor.WHITE)).replaceAll("&k", fromChatColor(ChatColor.MAGIC)).replaceAll("&l", fromChatColor(ChatColor.BOLD)).replaceAll("&m", fromChatColor(ChatColor.STRIKETHROUGH)) - .replaceAll("&n", fromChatColor(ChatColor.UNDERLINE)).replaceAll("&o", fromChatColor(ChatColor.ITALIC)).replaceAll("&r", fromChatColor(ChatColor.RESET)); - return input + ConsoleColor.RESET.toString(); - } + public static String fromString(String input) { + input = input.replaceAll("&0", fromChatColor(ChatColor.BLACK)) + .replaceAll("&1", fromChatColor(ChatColor.DARK_BLUE)) + .replaceAll("&2", fromChatColor(ChatColor.DARK_GREEN)) + .replaceAll("&3", fromChatColor(ChatColor.DARK_AQUA)) + .replaceAll("&4", fromChatColor(ChatColor.DARK_RED)) + .replaceAll("&5", fromChatColor(ChatColor.DARK_PURPLE)) + .replaceAll("&6", fromChatColor(ChatColor.GOLD)) + .replaceAll("&7", fromChatColor(ChatColor.GRAY)) + .replaceAll("&8", fromChatColor(ChatColor.DARK_GRAY)) + .replaceAll("&9", fromChatColor(ChatColor.BLUE)) + .replaceAll("&a", fromChatColor(ChatColor.GREEN)) + .replaceAll("&b", fromChatColor(ChatColor.AQUA)) + .replaceAll("&c", fromChatColor(ChatColor.RED)) + .replaceAll("&d", fromChatColor(ChatColor.LIGHT_PURPLE)) + .replaceAll("&e", fromChatColor(ChatColor.YELLOW)) + .replaceAll("&f", fromChatColor(ChatColor.WHITE)) + .replaceAll("&k", fromChatColor(ChatColor.MAGIC)) + .replaceAll("&l", fromChatColor(ChatColor.BOLD)) + .replaceAll("&m", fromChatColor(ChatColor.STRIKETHROUGH)) + .replaceAll("&n", fromChatColor(ChatColor.UNDERLINE)) + .replaceAll("&o", fromChatColor(ChatColor.ITALIC)) + .replaceAll("&r", fromChatColor(ChatColor.RESET)); + return input + ConsoleColor.RESET.toString(); + } - public static String fromChatColor(ChatColor color) { - return chatColor(color).getLin(); - } + public static String fromChatColor(ChatColor color) { + return chatColor(color).getLin(); + } - public static ConsoleColor chatColor(ChatColor color) { - switch (color) { - case RESET: - return ConsoleColor.RESET; - case GRAY: - case DARK_GRAY: - return ConsoleColor.WHITE; - case BLACK: - return ConsoleColor.BLACK; - case DARK_RED: - case RED: - return ConsoleColor.RED; - case GOLD: - case YELLOW: - return ConsoleColor.YELLOW; - case DARK_GREEN: - case GREEN: - return ConsoleColor.GREEN; - case AQUA: - case DARK_AQUA: - return ConsoleColor.CYAN; - case LIGHT_PURPLE: - case DARK_PURPLE: - return ConsoleColor.PURPLE; - case BLUE: - case DARK_BLUE: - return ConsoleColor.BLUE; - case UNDERLINE: - return ConsoleColor.UNDERLINE; - case ITALIC: - return ConsoleColor.ITALIC; - case BOLD: - return ConsoleColor.BOLD; - default: - return ConsoleColor.RESET; - } - } + public static ConsoleColor chatColor(ChatColor color) { + switch (color) { + case RESET: + return ConsoleColor.RESET; + case GRAY: + case DARK_GRAY: + return ConsoleColor.WHITE; + case BLACK: + return ConsoleColor.BLACK; + case DARK_RED: + case RED: + return ConsoleColor.RED; + case GOLD: + case YELLOW: + return ConsoleColor.YELLOW; + case DARK_GREEN: + case GREEN: + return ConsoleColor.GREEN; + case AQUA: + case DARK_AQUA: + return ConsoleColor.CYAN; + case LIGHT_PURPLE: + case DARK_PURPLE: + return ConsoleColor.PURPLE; + case BLUE: + case DARK_BLUE: + return ConsoleColor.BLUE; + case UNDERLINE: + return ConsoleColor.UNDERLINE; + case ITALIC: + return ConsoleColor.ITALIC; + case BOLD: + return ConsoleColor.BOLD; + default: + return ConsoleColor.RESET; + } + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/Flag.java b/PlotSquared/src/com/intellectualcrafters/plot/Flag.java index 0cb83b667..3aaf23b84 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/Flag.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/Flag.java @@ -4,85 +4,86 @@ import org.apache.commons.lang.StringUtils; import org.bukkit.ChatColor; public class Flag { - private AbstractFlag key; - private String value; + private AbstractFlag key; + private String value; - /** - * Flag object used to store basic information for a Plot. Flags are a - * key/value pair. For a flag to be usable by a player, you need to register - * it with PlotSquared. - * - * @param key - * AbstractFlag - * @param value - * Value must be alphanumerical (can have spaces) and be <= 48 - * characters - * @throws IllegalArgumentException - * if you provide inadequate inputs - */ - public Flag(AbstractFlag key, String value) { - if (!StringUtils.isAlphanumericSpace(ChatColor.stripColor(value))) { - throw new IllegalArgumentException("Flag must be alphanumerical"); - } - if (value.length() > 48) { - throw new IllegalArgumentException("Value must be <= 48 characters"); - } - this.key = key; - this.value = value; - } + /** + * Flag object used to store basic information for a Plot. Flags are a + * key/value pair. For a flag to be usable by a player, you need to register + * it with PlotSquared. + * + * @param key + * AbstractFlag + * @param value + * Value must be alphanumerical (can have spaces) and be <= 48 + * characters + * @throws IllegalArgumentException + * if you provide inadequate inputs + */ + public Flag(AbstractFlag key, String value) { + if (!StringUtils.isAlphanumericSpace(ChatColor.stripColor(value))) { + throw new IllegalArgumentException("Flag must be alphanumerical"); + } + if (value.length() > 48) { + throw new IllegalArgumentException("Value must be <= 48 characters"); + } + this.key = key; + this.value = value; + } - /** - * Get the AbstractFlag used in creating the flag - * - * @return AbstractFlag - */ - public AbstractFlag getAbstractFlag() { - return this.key; - } + /** + * Get the AbstractFlag used in creating the flag + * + * @return AbstractFlag + */ + public AbstractFlag getAbstractFlag() { + return this.key; + } - /** - * Get the key for the AbstractFlag - * - * @return String - */ - public String getKey() { - return this.key.getKey(); - } + /** + * Get the key for the AbstractFlag + * + * @return String + */ + public String getKey() { + return this.key.getKey(); + } - /** - * Get the value - * - * @return String - */ - public String getValue() { - return this.value; - } + /** + * Get the value + * + * @return String + */ + public String getValue() { + return this.value; + } - @Override - public String toString() { - if (this.value.equals("")) { - return this.key.getKey(); - } - return this.key + ":" + this.value; - } + @Override + public String toString() { + if (this.value.equals("")) { + return this.key.getKey(); + } + return this.key + ":" + this.value; + } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - Flag other = (Flag) obj; - return (this.key.getKey().equals(other.key.getKey()) && this.value.equals(other.value)); - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + Flag other = (Flag) obj; + return (this.key.getKey().equals(other.key.getKey()) && this.value + .equals(other.value)); + } - @Override - public int hashCode() { - return this.key.getKey().hashCode(); - } + @Override + public int hashCode() { + return this.key.getKey().hashCode(); + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/FlagManager.java b/PlotSquared/src/com/intellectualcrafters/plot/FlagManager.java index e7681bf3c..f38715ca6 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/FlagManager.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/FlagManager.java @@ -6,91 +6,104 @@ import java.util.Set; public class FlagManager { - // TODO add some flags - // - Plot clear interval - // - Mob cap - // - customized plot composition - // - greeting / leaving message - // OR in the flag command, allow users to set worldguard flags. + // TODO add some flags + // - Plot clear interval + // - Mob cap + // - customized plot composition + // - greeting / leaving message + // OR in the flag command, allow users to set worldguard flags. - private static ArrayList flags = new ArrayList(); + private static ArrayList flags = new ArrayList(); - /** - * Register an AbstractFlag with PlotSquared - * - * @param flag - * @return - */ - public static boolean addFlag(AbstractFlag flag) { - if (getFlag(flag.getKey()) != null) { - return false; - } - return flags.add(flag); - } + /** + * Register an AbstractFlag with PlotSquared + * + * @param flag + * @return + */ + public static boolean addFlag(AbstractFlag flag) { + if (getFlag(flag.getKey()) != null) { + return false; + } + return flags.add(flag); + } - /** - * Get a list of registered AbstractFlag objects - * - * @return List (AbstractFlag) - */ - public static List getFlags() { - return flags; - } + /** + * Get a list of registered AbstractFlag objects + * + * @return List (AbstractFlag) + */ + public static List getFlags() { + return flags; + } - /** - * Get an AbstractFlag by a string Returns null if flag does not exist - * - * @param string - * @return AbstractFlag - */ - public static AbstractFlag getFlag(String string) { - for (AbstractFlag flag : flags) { - if (flag.getKey().equalsIgnoreCase(string)) { - return flag; - } - } - return null; - } + /** + * Get an AbstractFlag by a string Returns null if flag does not exist + * + * @param string + * @return AbstractFlag + */ + public static AbstractFlag getFlag(String string) { + for (AbstractFlag flag : flags) { + if (flag.getKey().equalsIgnoreCase(string)) { + return flag; + } + } + return null; + } - /** - * Get an AbstractFlag by a string - * - * @param string - * @param create - * If to create the flag if it does not exist - * @return AbstractFlag - */ - public static AbstractFlag getFlag(String string, boolean create) { - if ((getFlag(string) == null) && create) { - AbstractFlag flag = new AbstractFlag(string); - addFlag(flag); - return flag; - } - return getFlag(string); - } + /** + * Get an AbstractFlag by a string + * + * @param string + * @param create + * If to create the flag if it does not exist + * @return AbstractFlag + */ + public static AbstractFlag getFlag(String string, boolean create) { + if ((getFlag(string) == null) && create) { + AbstractFlag flag = new AbstractFlag(string); + addFlag(flag); + return flag; + } + return getFlag(string); + } - /** - * Remove a registered AbstractFlag - * - * @param flag - * @return boolean Result of operation - */ - public static boolean removeFlag(AbstractFlag flag) { - return flags.remove(flag); - } + /** + * Remove a registered AbstractFlag + * + * @param flag + * @return boolean Result of operation + */ + public static boolean removeFlag(AbstractFlag flag) { + return flags.remove(flag); + } - /** - * Get the flags for a plot - * - * @param plot - * @return List (AbstractFlag) - */ - public static List getPlotFlags(Plot plot) { - Set plotFlags = plot.settings.getFlags(); - List flags = new ArrayList<>(); - for (Flag flag : plotFlags) { - flags.add(flag.getAbstractFlag()); - } - return flags; - } + public static Flag[] parseFlags(List flagstrings) { + Flag[] flags = new Flag[flagstrings.size()]; + for (int i = 0; i < flagstrings.size(); i++) { + String[] split = flagstrings.get(i).split(";"); + if (split.length == 1) { + flags[i] = new Flag(getFlag(split[0], true), ""); + } else { + flags[i] = new Flag(getFlag(split[0], true), split[1]); + } + } + return flags; + } + + /** + * Get the flags for a plot + * + * @param plot + * @return List (AbstractFlag) + */ + public static List getPlotFlags(Plot plot) { + Set plotFlags = plot.settings.getFlags(); + List flags = new ArrayList<>(); + for (Flag flag : plotFlags) { + flags.add(flag.getAbstractFlag()); + } + return flags; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/LSetCube.java b/PlotSquared/src/com/intellectualcrafters/plot/LSetCube.java index 9008cbab0..9733792a6 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/LSetCube.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/LSetCube.java @@ -13,117 +13,119 @@ import org.bukkit.Location; /** * Cube utilities - * + * * @author Citymonstret - * + * */ public class LSetCube { - /** - * Base locations - */ - private Location l1, l2; + /** + * Base locations + */ + private Location l1, l2; - /** - * Constructor - * - * @param l1 - * @param l2 - */ - public LSetCube(Location l1, Location l2) { - this.l1 = l1; - this.l1 = l2; - } + /** + * Constructor + * + * @param l1 + * @param l2 + */ + public LSetCube(Location l1, Location l2) { + this.l1 = l1; + this.l1 = l2; + } - /** - * Secondary constructor - * - * @param l1 - * @param size - */ - public LSetCube(Location l1, int size) { - this.l1 = l1; - this.l2 = l1.clone().add(size, size, size); - } + /** + * Secondary constructor + * + * @param l1 + * @param size + */ + public LSetCube(Location l1, int size) { + this.l1 = l1; + this.l2 = l1.clone().add(size, size, size); + } - /** - * Returns the absolute min. of the cube - * - * @return abs. min - */ - public Location minLoc() { - int x = Math.min(this.l1.getBlockX(), this.l2.getBlockX()); - int y = Math.min(this.l1.getBlockY(), this.l2.getBlockY()); - int z = Math.min(this.l1.getBlockZ(), this.l2.getBlockZ()); - return new Location(this.l1.getWorld(), x, y, z); - } + /** + * Returns the absolute min. of the cube + * + * @return abs. min + */ + public Location minLoc() { + int x = Math.min(this.l1.getBlockX(), this.l2.getBlockX()); + int y = Math.min(this.l1.getBlockY(), this.l2.getBlockY()); + int z = Math.min(this.l1.getBlockZ(), this.l2.getBlockZ()); + return new Location(this.l1.getWorld(), x, y, z); + } - /** - * Returns the absolute max. of the cube - * - * @return abs. max - */ - public Location maxLoc() { - int x = Math.max(this.l1.getBlockX(), this.l2.getBlockX()); - int y = Math.max(this.l1.getBlockY(), this.l2.getBlockY()); - int z = Math.max(this.l1.getBlockZ(), this.l2.getBlockZ()); - return new Location(this.l1.getWorld(), x, y, z); - } + /** + * Returns the absolute max. of the cube + * + * @return abs. max + */ + public Location maxLoc() { + int x = Math.max(this.l1.getBlockX(), this.l2.getBlockX()); + int y = Math.max(this.l1.getBlockY(), this.l2.getBlockY()); + int z = Math.max(this.l1.getBlockZ(), this.l2.getBlockZ()); + return new Location(this.l1.getWorld(), x, y, z); + } - /** - * Creates a LCycler for the cube. - * - * @return new lcycler - */ - public LCycler getCycler() { - return new LCycler(this); - } + /** + * Creates a LCycler for the cube. + * + * @return new lcycler + */ + public LCycler getCycler() { + return new LCycler(this); + } - /** - * @author Citymonstret - */ - protected class LCycler { - /** - * - */ - private Location min; - /** - * - */ - private Location max; - /** - * - */ - private Location current; + /** + * @author Citymonstret + */ + protected class LCycler { + /** + * + */ + private Location min; + /** + * + */ + private Location max; + /** + * + */ + private Location current; - /** - * - * @param cube - */ - public LCycler(LSetCube cube) { - this.min = cube.minLoc(); - this.max = cube.maxLoc(); - this.current = this.min; - } + /** + * + * @param cube + */ + public LCycler(LSetCube cube) { + this.min = cube.minLoc(); + this.max = cube.maxLoc(); + this.current = this.min; + } - /** - * - * @return - */ - public boolean hasNext() { - return ((this.current.getBlockX() + 1) <= this.max.getBlockX()) && ((this.current.getBlockY() + 1) <= this.max.getBlockY()) && ((this.current.getBlockZ() + 1) <= this.max.getBlockZ()); - } + /** + * + * @return + */ + public boolean hasNext() { + return ((this.current.getBlockX() + 1) <= this.max.getBlockX()) + && ((this.current.getBlockY() + 1) <= this.max.getBlockY()) + && ((this.current.getBlockZ() + 1) <= this.max.getBlockZ()); + } - /** - * - * @return - */ - public Location getNext() { - if (!hasNext()) { - return null; - } - this.current = this.current.add(1, 1, 1); - return this.current; - } - } + /** + * + * @return + */ + public Location getNext() { + if (!hasNext()) { + return null; + } + this.current = this.current.add(1, 1, 1); + return this.current; + } + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/Lag.java b/PlotSquared/src/com/intellectualcrafters/plot/Lag.java index d9fe36fe9..cc5679d4a 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/Lag.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/Lag.java @@ -11,85 +11,86 @@ package com.intellectualcrafters.plot; /** * TPS and Lag Checker. - * + * * @author Citymonstret - * + * */ public class Lag implements Runnable { - /** - * Tick count - */ - public static int TC = 0; - /** - * Ticks - */ - public static long[] T = new long[600]; - /** - * something :_: - */ - @SuppressWarnings("unused") - public static long LT = 0L; + /** + * Tick count + */ + public static int TC = 0; + /** + * Ticks + */ + public static long[] T = new long[600]; + /** + * something :_: + */ + @SuppressWarnings("unused") + public static long LT = 0L; - /** - * Get the server TPS - * - * @return server tick per second - */ - public static double getTPS() { - return Math.round(getTPS(100)) > 20.0D ? 20.0D : Math.round(getTPS(100)); - } + /** + * Get the server TPS + * + * @return server tick per second + */ + public static double getTPS() { + return Math.round(getTPS(100)) > 20.0D ? 20.0D : Math + .round(getTPS(100)); + } - /** - * Return the tick per second (measured in $ticks) - * - * @param ticks - * Ticks - * @return ticks per second - */ - public static double getTPS(int ticks) { - if (TC < ticks) { - return 20.0D; - } - int t = (TC - 1 - ticks) % T.length; - long e = System.currentTimeMillis() - T[t]; - return ticks / (e / 1000.0D); - } + /** + * Return the tick per second (measured in $ticks) + * + * @param ticks + * Ticks + * @return ticks per second + */ + public static double getTPS(int ticks) { + if (TC < ticks) { + return 20.0D; + } + int t = (TC - 1 - ticks) % T.length; + long e = System.currentTimeMillis() - T[t]; + return ticks / (e / 1000.0D); + } - /** - * Get number of ticks since - * - * @param tI - * Ticks < - * @return number of ticks since $tI - */ - @SuppressWarnings("unused") - public static long getElapsed(int tI) { - long t = T[tI % T.length]; - return System.currentTimeMillis() - t; - } + /** + * Get number of ticks since + * + * @param tI + * Ticks < + * @return number of ticks since $tI + */ + @SuppressWarnings("unused") + public static long getElapsed(int tI) { + long t = T[tI % T.length]; + return System.currentTimeMillis() - t; + } - @Override - public void run() { - T[TC % T.length] = System.currentTimeMillis(); - TC++; - } + @Override + public void run() { + T[TC % T.length] = System.currentTimeMillis(); + TC++; + } - /** - * Get lag percentage - * - * @return lag percentage - */ - public static double getPercentage() { - return Math.round((1.0D - (Lag.getTPS() / 20.0D)) * 100.0D); - } + /** + * Get lag percentage + * + * @return lag percentage + */ + public static double getPercentage() { + return Math.round((1.0D - (Lag.getTPS() / 20.0D)) * 100.0D); + } - /** - * Get TPS percentage (of 20) - * - * @return TPS percentage - */ - public static double getFullPercentage() { - return getTPS() * 5.0D; - } + /** + * Get TPS percentage (of 20) + * + * @return TPS percentage + */ + public static double getFullPercentage() { + return getTPS() * 5.0D; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/Logger.java b/PlotSquared/src/com/intellectualcrafters/plot/Logger.java index 42e8b7d9b..f79155ef9 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/Logger.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/Logger.java @@ -19,57 +19,58 @@ import java.util.Date; /** * Logging of errors and debug messages. - * + * * @author Citymonstret - * + * */ public class Logger { - private static ArrayList entries; - private static File log; + private static ArrayList entries; + private static File log; - public static void setup(File file) { - log = file; - entries = new ArrayList<>(); - try { - BufferedReader reader = new BufferedReader(new FileReader(file)); - String line; - while ((line = reader.readLine()) != null) { - entries.add(line); - } - reader.close(); - } catch (IOException e) { - PlotMain.sendConsoleSenderMessage(C.PREFIX.s() + "File setup error Logger#setup"); - } - } + public static void setup(File file) { + log = file; + entries = new ArrayList<>(); + try { + BufferedReader reader = new BufferedReader(new FileReader(file)); + String line; + while ((line = reader.readLine()) != null) { + entries.add(line); + } + reader.close(); + } catch (IOException e) { + PlotMain.sendConsoleSenderMessage(C.PREFIX.s() + + "File setup error Logger#setup"); + } + } - public enum LogLevel { - GENERAL("General"), WARNING("Warning"), DANGER("Danger"); - private String name; + public enum LogLevel { + GENERAL("General"), WARNING("Warning"), DANGER("Danger"); + private String name; - LogLevel(String name) { - this.name = name; - } + LogLevel(String name) { + this.name = name; + } - @Override - public String toString() { - return this.name; - } - } + @Override + public String toString() { + return this.name; + } + } - public static void write() throws IOException { - FileWriter writer = new FileWriter(log); - for (String string : entries) { - writer.write(string + System.lineSeparator()); - } - writer.close(); - } + public static void write() throws IOException { + FileWriter writer = new FileWriter(log); + for (String string : entries) { + writer.write(string + System.lineSeparator()); + } + writer.close(); + } - public static void add(LogLevel level, String string) { - append("[" + level.toString() + "] " + string); - } + public static void add(LogLevel level, String string) { + append("[" + level.toString() + "] " + string); + } - private static void append(String string) { - entries.add("[" + new Date().toString() + "]" + string); - } + private static void append(String string) { + entries.add("[" + new Date().toString() + "]" + string); + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/Metrics.java b/PlotSquared/src/com/intellectualcrafters/plot/Metrics.java index c9b2ddcfc..568313fe1 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/Metrics.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/Metrics.java @@ -56,662 +56,690 @@ import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.scheduler.BukkitTask; public class Metrics { - /** - * The current revision number - */ - private final static int REVISION = 7; - /** - * The base url of the metrics domain - */ - private static final String BASE_URL = "http://report.mcstats.org"; - /** - * The url used to report a server's status - */ - private static final String REPORT_URL = "/plugin/%s"; - /** - * Interval of time to ping (in minutes) - */ - private static final int PING_INTERVAL = 15; - /** - * The plugin this metrics submits for - */ - private final Plugin plugin; - /** - * All of the custom graphs to submit to metrics - */ - private final Set graphs = Collections.synchronizedSet(new HashSet()); - /** - * The plugin configuration file - */ - private final YamlConfiguration configuration; - /** - * The plugin configuration file - */ - private final File configurationFile; - /** - * Unique server id - */ - private final String guid; - /** - * Debug mode - */ - private final boolean debug; - /** - * Lock for synchronization - */ - private final Object optOutLock = new Object(); - /** - * The scheduled task - */ - private volatile BukkitTask task = null; + /** + * The current revision number + */ + private final static int REVISION = 7; + /** + * The base url of the metrics domain + */ + private static final String BASE_URL = "http://report.mcstats.org"; + /** + * The url used to report a server's status + */ + private static final String REPORT_URL = "/plugin/%s"; + /** + * Interval of time to ping (in minutes) + */ + private static final int PING_INTERVAL = 15; + /** + * The plugin this metrics submits for + */ + private final Plugin plugin; + /** + * All of the custom graphs to submit to metrics + */ + private final Set graphs = Collections + .synchronizedSet(new HashSet()); + /** + * The plugin configuration file + */ + private final YamlConfiguration configuration; + /** + * The plugin configuration file + */ + private final File configurationFile; + /** + * Unique server id + */ + private final String guid; + /** + * Debug mode + */ + private final boolean debug; + /** + * Lock for synchronization + */ + private final Object optOutLock = new Object(); + /** + * The scheduled task + */ + private volatile BukkitTask task = null; - public Metrics(final Plugin plugin) throws IOException { - if (plugin == null) { - throw new IllegalArgumentException("Plugin cannot be null"); - } - this.plugin = plugin; - // load the config - this.configurationFile = getConfigFile(); - this.configuration = YamlConfiguration.loadConfiguration(this.configurationFile); - // add some defaults - this.configuration.addDefault("opt-out", false); - this.configuration.addDefault("guid", UUID.randomUUID().toString()); - this.configuration.addDefault("debug", false); - // Do we need to create the file? - if (this.configuration.get("guid", null) == null) { - this.configuration.options().header("http://mcstats.org").copyDefaults(true); - this.configuration.save(this.configurationFile); - } - // Load the guid then - this.guid = this.configuration.getString("guid"); - this.debug = this.configuration.getBoolean("debug", false); - } + public Metrics(final Plugin plugin) throws IOException { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null"); + } + this.plugin = plugin; + // load the config + this.configurationFile = getConfigFile(); + this.configuration = YamlConfiguration + .loadConfiguration(this.configurationFile); + // add some defaults + this.configuration.addDefault("opt-out", false); + this.configuration.addDefault("guid", UUID.randomUUID().toString()); + this.configuration.addDefault("debug", false); + // Do we need to create the file? + if (this.configuration.get("guid", null) == null) { + this.configuration.options().header("http://mcstats.org") + .copyDefaults(true); + this.configuration.save(this.configurationFile); + } + // Load the guid then + this.guid = this.configuration.getString("guid"); + this.debug = this.configuration.getBoolean("debug", false); + } - /** - * Construct and create a Graph that can be used to separate specific - * plotters to their own graphs on the metrics website. Plotters can be - * added to the graph object returned. - * - * @param name - * The name of the graph - * @return Graph object created. Will never return NULL under normal - * circumstances unless bad parameters are given - */ - public Graph createGraph(final String name) { - if (name == null) { - throw new IllegalArgumentException("Graph name cannot be null"); - } - // Construct the graph object - final Graph graph = new Graph(name); - // Now we can add our graph - this.graphs.add(graph); - // and return back - return graph; - } + /** + * Construct and create a Graph that can be used to separate specific + * plotters to their own graphs on the metrics website. Plotters can be + * added to the graph object returned. + * + * @param name + * The name of the graph + * @return Graph object created. Will never return NULL under normal + * circumstances unless bad parameters are given + */ + public Graph createGraph(final String name) { + if (name == null) { + throw new IllegalArgumentException("Graph name cannot be null"); + } + // Construct the graph object + final Graph graph = new Graph(name); + // Now we can add our graph + this.graphs.add(graph); + // and return back + return graph; + } - /** - * Add a Graph object to BukkitMetrics that represents data for the plugin - * that should be sent to the backend - * - * @param graph - * The name of the graph - */ - public void addGraph(final Graph graph) { - if (graph == null) { - throw new IllegalArgumentException("Graph cannot be null"); - } - this.graphs.add(graph); - } + /** + * Add a Graph object to BukkitMetrics that represents data for the plugin + * that should be sent to the backend + * + * @param graph + * The name of the graph + */ + public void addGraph(final Graph graph) { + if (graph == null) { + throw new IllegalArgumentException("Graph cannot be null"); + } + this.graphs.add(graph); + } - /** - * Start measuring statistics. This will immediately create an async - * repeating task as the plugin and send the initial data to the metrics - * backend, and then after that it will post in increments of PING_INTERVAL - * * 1200 ticks. - * - * @return True if statistics measuring is running, otherwise false. - */ - public boolean start() { - synchronized (this.optOutLock) { - // Did we opt out? - if (isOptOut()) { - return false; - } - // Is metrics already running? - if (this.task != null) { - return true; - } - // Begin hitting the server with glorious data - this.task = this.plugin.getServer().getScheduler().runTaskTimerAsynchronously(this.plugin, new Runnable() { - private boolean firstPost = true; + /** + * Start measuring statistics. This will immediately create an async + * repeating task as the plugin and send the initial data to the metrics + * backend, and then after that it will post in increments of PING_INTERVAL + * * 1200 ticks. + * + * @return True if statistics measuring is running, otherwise false. + */ + public boolean start() { + synchronized (this.optOutLock) { + // Did we opt out? + if (isOptOut()) { + return false; + } + // Is metrics already running? + if (this.task != null) { + return true; + } + // Begin hitting the server with glorious data + this.task = this.plugin.getServer().getScheduler() + .runTaskTimerAsynchronously(this.plugin, new Runnable() { + private boolean firstPost = true; - @Override - public void run() { - try { - // This has to be synchronized or it can collide with - // the disable method. - synchronized (Metrics.this.optOutLock) { - // Disable Task, if it is running and the server - // owner decided to opt-out - if (isOptOut() && (Metrics.this.task != null)) { - Metrics.this.task.cancel(); - Metrics.this.task = null; - // Tell all plotters to stop gathering - // information. - for (Graph graph : Metrics.this.graphs) { - graph.onOptOut(); - } - } - } - // We use the inverse of firstPost because if it is the - // first time we are posting, - // it is not a interval ping, so it evaluates to FALSE - // Each time thereafter it will evaluate to TRUE, i.e - // PING! - postPlugin(!this.firstPost); - // After the first post we set firstPost to false - // Each post thereafter will be a ping - this.firstPost = false; - } catch (IOException e) { - if (Metrics.this.debug) { - Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage()); - } - } - } - }, 0, PING_INTERVAL * 1200); - return true; - } - } + @Override + public void run() { + try { + // This has to be synchronized or it can collide + // with + // the disable method. + synchronized (Metrics.this.optOutLock) { + // Disable Task, if it is running and the + // server + // owner decided to opt-out + if (isOptOut() + && (Metrics.this.task != null)) { + Metrics.this.task.cancel(); + Metrics.this.task = null; + // Tell all plotters to stop gathering + // information. + for (Graph graph : Metrics.this.graphs) { + graph.onOptOut(); + } + } + } + // We use the inverse of firstPost because if it + // is the + // first time we are posting, + // it is not a interval ping, so it evaluates to + // FALSE + // Each time thereafter it will evaluate to + // TRUE, i.e + // PING! + postPlugin(!this.firstPost); + // After the first post we set firstPost to + // false + // Each post thereafter will be a ping + this.firstPost = false; + } catch (IOException e) { + if (Metrics.this.debug) { + Bukkit.getLogger().log(Level.INFO, + "[Metrics] " + e.getMessage()); + } + } + } + }, 0, PING_INTERVAL * 1200); + return true; + } + } - /** - * Has the server owner denied plugin metrics? - * - * @return true if metrics should be opted out of it - */ - public boolean isOptOut() { - synchronized (this.optOutLock) { - try { - // Reload the metrics file - this.configuration.load(getConfigFile()); - } catch (IOException ex) { - if (this.debug) { - Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); - } - return true; - } catch (InvalidConfigurationException ex) { - if (this.debug) { - Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); - } - return true; - } - return this.configuration.getBoolean("opt-out", false); - } - } + /** + * Has the server owner denied plugin metrics? + * + * @return true if metrics should be opted out of it + */ + public boolean isOptOut() { + synchronized (this.optOutLock) { + try { + // Reload the metrics file + this.configuration.load(getConfigFile()); + } catch (IOException ex) { + if (this.debug) { + Bukkit.getLogger().log(Level.INFO, + "[Metrics] " + ex.getMessage()); + } + return true; + } catch (InvalidConfigurationException ex) { + if (this.debug) { + Bukkit.getLogger().log(Level.INFO, + "[Metrics] " + ex.getMessage()); + } + return true; + } + return this.configuration.getBoolean("opt-out", false); + } + } - /** - * Enables metrics for the server by setting "opt-out" to false in the - * config file and starting the metrics task. - * - * @throws java.io.IOException - */ - public void enable() throws IOException { - // This has to be synchronized or it can collide with the check in the - // task. - synchronized (this.optOutLock) { - // Check if the server owner has already set opt-out, if not, set - // it. - if (isOptOut()) { - this.configuration.set("opt-out", false); - this.configuration.save(this.configurationFile); - } - // Enable Task, if it is not running - if (this.task == null) { - start(); - } - } - } + /** + * Enables metrics for the server by setting "opt-out" to false in the + * config file and starting the metrics task. + * + * @throws java.io.IOException + */ + public void enable() throws IOException { + // This has to be synchronized or it can collide with the check in the + // task. + synchronized (this.optOutLock) { + // Check if the server owner has already set opt-out, if not, set + // it. + if (isOptOut()) { + this.configuration.set("opt-out", false); + this.configuration.save(this.configurationFile); + } + // Enable Task, if it is not running + if (this.task == null) { + start(); + } + } + } - /** - * Disables metrics for the server by setting "opt-out" to true in the - * config file and canceling the metrics task. - * - * @throws java.io.IOException - */ - public void disable() throws IOException { - // This has to be synchronized or it can collide with the check in the - // task. - synchronized (this.optOutLock) { - // Check if the server owner has already set opt-out, if not, set - // it. - if (!isOptOut()) { - this.configuration.set("opt-out", true); - this.configuration.save(this.configurationFile); - } - // Disable Task, if it is running - if (this.task != null) { - this.task.cancel(); - this.task = null; - } - } - } + /** + * Disables metrics for the server by setting "opt-out" to true in the + * config file and canceling the metrics task. + * + * @throws java.io.IOException + */ + public void disable() throws IOException { + // This has to be synchronized or it can collide with the check in the + // task. + synchronized (this.optOutLock) { + // Check if the server owner has already set opt-out, if not, set + // it. + if (!isOptOut()) { + this.configuration.set("opt-out", true); + this.configuration.save(this.configurationFile); + } + // Disable Task, if it is running + if (this.task != null) { + this.task.cancel(); + this.task = null; + } + } + } - /** - * Gets the File object of the config file that should be used to store data - * such as the GUID and opt-out status - * - * @return the File object for the config file - */ - public File getConfigFile() { - // I believe the easiest way to get the base folder (e.g craftbukkit set - // via -P) for plugins to use - // is to abuse the plugin object we already have - // plugin.getDataFolder() => base/plugins/PluginA/ - // pluginsFolder => base/plugins/ - // The base is not necessarily relative to the startup directory. - File pluginsFolder = this.plugin.getDataFolder().getParentFile(); - // return => base/plugins/PluginMetrics/config.yml - return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml"); - } + /** + * Gets the File object of the config file that should be used to store data + * such as the GUID and opt-out status + * + * @return the File object for the config file + */ + public File getConfigFile() { + // I believe the easiest way to get the base folder (e.g craftbukkit set + // via -P) for plugins to use + // is to abuse the plugin object we already have + // plugin.getDataFolder() => base/plugins/PluginA/ + // pluginsFolder => base/plugins/ + // The base is not necessarily relative to the startup directory. + File pluginsFolder = this.plugin.getDataFolder().getParentFile(); + // return => base/plugins/PluginMetrics/config.yml + return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml"); + } - /** - * Generic method that posts a plugin to the metrics website - */ - private void postPlugin(final boolean isPing) throws IOException { - // Server software specific section - PluginDescriptionFile description = this.plugin.getDescription(); - String pluginName = description.getName(); - boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE if - // online mode - // is enabled - String pluginVersion = description.getVersion(); - String serverVersion = Bukkit.getVersion(); - int playersOnline = Bukkit.getServer().getOnlinePlayers().length; - // END server software specific section -- all code below does not use - // any code outside of this class / Java - // Construct the post data - StringBuilder json = new StringBuilder(1024); - json.append('{'); - // The plugin's description file containg all of the plugin data such as - // name, version, author, etc - appendJSONPair(json, "guid", this.guid); - appendJSONPair(json, "plugin_version", pluginVersion); - appendJSONPair(json, "server_version", serverVersion); - appendJSONPair(json, "players_online", Integer.toString(playersOnline)); - // New data as of R6 - String osname = System.getProperty("os.name"); - String osarch = System.getProperty("os.arch"); - String osversion = System.getProperty("os.version"); - String java_version = System.getProperty("java.version"); - int coreCount = Runtime.getRuntime().availableProcessors(); - // normalize os arch .. amd64 -> x86_64 - if (osarch.equals("amd64")) { - osarch = "x86_64"; - } - appendJSONPair(json, "osname", osname); - appendJSONPair(json, "osarch", osarch); - appendJSONPair(json, "osversion", osversion); - appendJSONPair(json, "cores", Integer.toString(coreCount)); - appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0"); - appendJSONPair(json, "java_version", java_version); - // If we're pinging, append it - if (isPing) { - appendJSONPair(json, "ping", "1"); - } - if (this.graphs.size() > 0) { - synchronized (this.graphs) { - json.append(','); - json.append('"'); - json.append("graphs"); - json.append('"'); - json.append(':'); - json.append('{'); - boolean firstGraph = true; - final Iterator iter = this.graphs.iterator(); - while (iter.hasNext()) { - Graph graph = iter.next(); - StringBuilder graphJson = new StringBuilder(); - graphJson.append('{'); - for (Plotter plotter : graph.getPlotters()) { - appendJSONPair(graphJson, plotter.getColumnName(), Integer.toString(plotter.getValue())); - } - graphJson.append('}'); - if (!firstGraph) { - json.append(','); - } - json.append(escapeJSON(graph.getName())); - json.append(':'); - json.append(graphJson); - firstGraph = false; - } - json.append('}'); - } - } - // close json - json.append('}'); - // Create the url - URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName))); - // Connect to the website - URLConnection connection; - // Mineshafter creates a socks proxy, so we can safely bypass it - // It does not reroute POST requests so we need to go around it - if (isMineshafterPresent()) { - connection = url.openConnection(Proxy.NO_PROXY); - } else { - connection = url.openConnection(); - } - byte[] uncompressed = json.toString().getBytes(); - byte[] compressed = gzip(json.toString()); - // Headers - connection.addRequestProperty("User-Agent", "MCStats/" + REVISION); - connection.addRequestProperty("Content-Type", "application/json"); - connection.addRequestProperty("Content-Encoding", "gzip"); - connection.addRequestProperty("Content-Length", Integer.toString(compressed.length)); - connection.addRequestProperty("Accept", "application/json"); - connection.addRequestProperty("Connection", "close"); - connection.setDoOutput(true); - if (this.debug) { - System.out.println("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" + compressed.length); - } - // Write the data - OutputStream os = connection.getOutputStream(); - os.write(compressed); - os.flush(); - // Now read the response - final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); - String response = reader.readLine(); - // close resources - os.close(); - reader.close(); - if ((response == null) || response.startsWith("ERR") || response.startsWith("7")) { - if (response == null) { - response = "null"; - } else if (response.startsWith("7")) { - response = response.substring(response.startsWith("7,") ? 2 : 1); - } - throw new IOException(response); - } else { - // Is this the first update this hour? - if (response.equals("1") || response.contains("This is your first update this hour")) { - synchronized (this.graphs) { - final Iterator iter = this.graphs.iterator(); - while (iter.hasNext()) { - final Graph graph = iter.next(); - for (Plotter plotter : graph.getPlotters()) { - plotter.reset(); - } - } - } - } - } - } + /** + * Generic method that posts a plugin to the metrics website + */ + private void postPlugin(final boolean isPing) throws IOException { + // Server software specific section + PluginDescriptionFile description = this.plugin.getDescription(); + String pluginName = description.getName(); + boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE if + // online + // mode + // is + // enabled + String pluginVersion = description.getVersion(); + String serverVersion = Bukkit.getVersion(); + int playersOnline = Bukkit.getServer().getOnlinePlayers().length; + // END server software specific section -- all code below does not use + // any code outside of this class / Java + // Construct the post data + StringBuilder json = new StringBuilder(1024); + json.append('{'); + // The plugin's description file containg all of the plugin data such as + // name, version, author, etc + appendJSONPair(json, "guid", this.guid); + appendJSONPair(json, "plugin_version", pluginVersion); + appendJSONPair(json, "server_version", serverVersion); + appendJSONPair(json, "players_online", Integer.toString(playersOnline)); + // New data as of R6 + String osname = System.getProperty("os.name"); + String osarch = System.getProperty("os.arch"); + String osversion = System.getProperty("os.version"); + String java_version = System.getProperty("java.version"); + int coreCount = Runtime.getRuntime().availableProcessors(); + // normalize os arch .. amd64 -> x86_64 + if (osarch.equals("amd64")) { + osarch = "x86_64"; + } + appendJSONPair(json, "osname", osname); + appendJSONPair(json, "osarch", osarch); + appendJSONPair(json, "osversion", osversion); + appendJSONPair(json, "cores", Integer.toString(coreCount)); + appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0"); + appendJSONPair(json, "java_version", java_version); + // If we're pinging, append it + if (isPing) { + appendJSONPair(json, "ping", "1"); + } + if (this.graphs.size() > 0) { + synchronized (this.graphs) { + json.append(','); + json.append('"'); + json.append("graphs"); + json.append('"'); + json.append(':'); + json.append('{'); + boolean firstGraph = true; + final Iterator iter = this.graphs.iterator(); + while (iter.hasNext()) { + Graph graph = iter.next(); + StringBuilder graphJson = new StringBuilder(); + graphJson.append('{'); + for (Plotter plotter : graph.getPlotters()) { + appendJSONPair(graphJson, plotter.getColumnName(), + Integer.toString(plotter.getValue())); + } + graphJson.append('}'); + if (!firstGraph) { + json.append(','); + } + json.append(escapeJSON(graph.getName())); + json.append(':'); + json.append(graphJson); + firstGraph = false; + } + json.append('}'); + } + } + // close json + json.append('}'); + // Create the url + URL url = new URL(BASE_URL + + String.format(REPORT_URL, urlEncode(pluginName))); + // Connect to the website + URLConnection connection; + // Mineshafter creates a socks proxy, so we can safely bypass it + // It does not reroute POST requests so we need to go around it + if (isMineshafterPresent()) { + connection = url.openConnection(Proxy.NO_PROXY); + } else { + connection = url.openConnection(); + } + byte[] uncompressed = json.toString().getBytes(); + byte[] compressed = gzip(json.toString()); + // Headers + connection.addRequestProperty("User-Agent", "MCStats/" + REVISION); + connection.addRequestProperty("Content-Type", "application/json"); + connection.addRequestProperty("Content-Encoding", "gzip"); + connection.addRequestProperty("Content-Length", + Integer.toString(compressed.length)); + connection.addRequestProperty("Accept", "application/json"); + connection.addRequestProperty("Connection", "close"); + connection.setDoOutput(true); + if (this.debug) { + System.out.println("[Metrics] Prepared request for " + pluginName + + " uncompressed=" + uncompressed.length + " compressed=" + + compressed.length); + } + // Write the data + OutputStream os = connection.getOutputStream(); + os.write(compressed); + os.flush(); + // Now read the response + final BufferedReader reader = new BufferedReader(new InputStreamReader( + connection.getInputStream())); + String response = reader.readLine(); + // close resources + os.close(); + reader.close(); + if ((response == null) || response.startsWith("ERR") + || response.startsWith("7")) { + if (response == null) { + response = "null"; + } else if (response.startsWith("7")) { + response = response + .substring(response.startsWith("7,") ? 2 : 1); + } + throw new IOException(response); + } else { + // Is this the first update this hour? + if (response.equals("1") + || response.contains("This is your first update this hour")) { + synchronized (this.graphs) { + final Iterator iter = this.graphs.iterator(); + while (iter.hasNext()) { + final Graph graph = iter.next(); + for (Plotter plotter : graph.getPlotters()) { + plotter.reset(); + } + } + } + } + } + } - /** - * GZip compress a string of bytes - * - * @param input - * @return - */ - public static byte[] gzip(String input) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - GZIPOutputStream gzos = null; - try { - gzos = new GZIPOutputStream(baos); - gzos.write(input.getBytes("UTF-8")); - } catch (IOException e) { - e.printStackTrace(); - } finally { - if (gzos != null) { - try { - gzos.close(); - } catch (IOException ignore) { - } - } - } - return baos.toByteArray(); - } + /** + * GZip compress a string of bytes + * + * @param input + * @return + */ + public static byte[] gzip(String input) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + GZIPOutputStream gzos = null; + try { + gzos = new GZIPOutputStream(baos); + gzos.write(input.getBytes("UTF-8")); + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (gzos != null) { + try { + gzos.close(); + } catch (IOException ignore) { + } + } + } + return baos.toByteArray(); + } - /** - * Check if mineshafter is present. If it is, we need to bypass it to send - * POST requests - * - * @return true if mineshafter is installed on the server - */ - private boolean isMineshafterPresent() { - try { - Class.forName("mineshafter.MineServer"); - return true; - } catch (Exception e) { - return false; - } - } + /** + * Check if mineshafter is present. If it is, we need to bypass it to send + * POST requests + * + * @return true if mineshafter is installed on the server + */ + private boolean isMineshafterPresent() { + try { + Class.forName("mineshafter.MineServer"); + return true; + } catch (Exception e) { + return false; + } + } - /** - * Appends a json encoded key/value pair to the given string builder. - * - * @param json - * @param key - * @param value - * @throws UnsupportedEncodingException - */ - private static void appendJSONPair(StringBuilder json, String key, String value) throws UnsupportedEncodingException { - boolean isValueNumeric = false; - try { - if (value.equals("0") || !value.endsWith("0")) { - Double.parseDouble(value); - isValueNumeric = true; - } - } catch (NumberFormatException e) { - isValueNumeric = false; - } - if (json.charAt(json.length() - 1) != '{') { - json.append(','); - } - json.append(escapeJSON(key)); - json.append(':'); - if (isValueNumeric) { - json.append(value); - } else { - json.append(escapeJSON(value)); - } - } + /** + * Appends a json encoded key/value pair to the given string builder. + * + * @param json + * @param key + * @param value + * @throws UnsupportedEncodingException + */ + private static void appendJSONPair(StringBuilder json, String key, + String value) throws UnsupportedEncodingException { + boolean isValueNumeric = false; + try { + if (value.equals("0") || !value.endsWith("0")) { + Double.parseDouble(value); + isValueNumeric = true; + } + } catch (NumberFormatException e) { + isValueNumeric = false; + } + if (json.charAt(json.length() - 1) != '{') { + json.append(','); + } + json.append(escapeJSON(key)); + json.append(':'); + if (isValueNumeric) { + json.append(value); + } else { + json.append(escapeJSON(value)); + } + } - /** - * Escape a string to create a valid JSON string - * - * @param text - * @return - */ - private static String escapeJSON(String text) { - StringBuilder builder = new StringBuilder(); - builder.append('"'); - for (int index = 0; index < text.length(); index++) { - char chr = text.charAt(index); - switch (chr) { - case '"': - case '\\': - builder.append('\\'); - builder.append(chr); - break; - case '\b': - builder.append("\\b"); - break; - case '\t': - builder.append("\\t"); - break; - case '\n': - builder.append("\\n"); - break; - case '\r': - builder.append("\\r"); - break; - default: - if (chr < ' ') { - String t = "000" + Integer.toHexString(chr); - builder.append("\\u" + t.substring(t.length() - 4)); - } else { - builder.append(chr); - } - break; - } - } - builder.append('"'); - return builder.toString(); - } + /** + * Escape a string to create a valid JSON string + * + * @param text + * @return + */ + private static String escapeJSON(String text) { + StringBuilder builder = new StringBuilder(); + builder.append('"'); + for (int index = 0; index < text.length(); index++) { + char chr = text.charAt(index); + switch (chr) { + case '"': + case '\\': + builder.append('\\'); + builder.append(chr); + break; + case '\b': + builder.append("\\b"); + break; + case '\t': + builder.append("\\t"); + break; + case '\n': + builder.append("\\n"); + break; + case '\r': + builder.append("\\r"); + break; + default: + if (chr < ' ') { + String t = "000" + Integer.toHexString(chr); + builder.append("\\u" + t.substring(t.length() - 4)); + } else { + builder.append(chr); + } + break; + } + } + builder.append('"'); + return builder.toString(); + } - /** - * Encode text as UTF-8 - * - * @param text - * the text to encode - * @return the encoded text, as UTF-8 - */ - private static String urlEncode(final String text) throws UnsupportedEncodingException { - return URLEncoder.encode(text, "UTF-8"); - } + /** + * Encode text as UTF-8 + * + * @param text + * the text to encode + * @return the encoded text, as UTF-8 + */ + private static String urlEncode(final String text) + throws UnsupportedEncodingException { + return URLEncoder.encode(text, "UTF-8"); + } - /** - * Represents a custom graph on the website - */ - public static class Graph { - /** - * The graph's name, alphanumeric and spaces only :) If it does not - * comply to the above when submitted, it is rejected - */ - private final String name; - /** - * The set of plotters that are contained within this graph - */ - private final Set plotters = new LinkedHashSet(); + /** + * Represents a custom graph on the website + */ + public static class Graph { + /** + * The graph's name, alphanumeric and spaces only :) If it does not + * comply to the above when submitted, it is rejected + */ + private final String name; + /** + * The set of plotters that are contained within this graph + */ + private final Set plotters = new LinkedHashSet(); - private Graph(final String name) { - this.name = name; - } + private Graph(final String name) { + this.name = name; + } - /** - * Gets the graph's name - * - * @return the Graph's name - */ - public String getName() { - return this.name; - } + /** + * Gets the graph's name + * + * @return the Graph's name + */ + public String getName() { + return this.name; + } - /** - * Add a plotter to the graph, which will be used to plot entries - * - * @param plotter - * the plotter to add to the graph - */ - public void addPlotter(final Plotter plotter) { - this.plotters.add(plotter); - } + /** + * Add a plotter to the graph, which will be used to plot entries + * + * @param plotter + * the plotter to add to the graph + */ + public void addPlotter(final Plotter plotter) { + this.plotters.add(plotter); + } - /** - * Remove a plotter from the graph - * - * @param plotter - * the plotter to remove from the graph - */ - public void removePlotter(final Plotter plotter) { - this.plotters.remove(plotter); - } + /** + * Remove a plotter from the graph + * + * @param plotter + * the plotter to remove from the graph + */ + public void removePlotter(final Plotter plotter) { + this.plotters.remove(plotter); + } - /** - * Gets an unmodifiable set of the plotter objects in the graph - * - * @return an unmodifiable {@link java.util.Set} of the plotter objects - */ - public Set getPlotters() { - return Collections.unmodifiableSet(this.plotters); - } + /** + * Gets an unmodifiable set of the plotter objects in the graph + * + * @return an unmodifiable {@link java.util.Set} of the plotter objects + */ + public Set getPlotters() { + return Collections.unmodifiableSet(this.plotters); + } - @Override - public int hashCode() { - return this.name.hashCode(); - } + @Override + public int hashCode() { + return this.name.hashCode(); + } - @Override - public boolean equals(final Object object) { - if (!(object instanceof Graph)) { - return false; - } - final Graph graph = (Graph) object; - return graph.name.equals(this.name); - } + @Override + public boolean equals(final Object object) { + if (!(object instanceof Graph)) { + return false; + } + final Graph graph = (Graph) object; + return graph.name.equals(this.name); + } - /** - * Called when the server owner decides to opt-out of BukkitMetrics - * while the server is running. - */ - protected void onOptOut() { - } - } + /** + * Called when the server owner decides to opt-out of BukkitMetrics + * while the server is running. + */ + protected void onOptOut() { + } + } - /** - * Interface used to collect custom data for a plugin - */ - public static abstract class Plotter { - /** - * The plot's name - */ - private final String name; + /** + * Interface used to collect custom data for a plugin + */ + public static abstract class Plotter { + /** + * The plot's name + */ + private final String name; - /** - * Construct a plotter with the default plot name - */ - public Plotter() { - this("Default"); - } + /** + * Construct a plotter with the default plot name + */ + public Plotter() { + this("Default"); + } - /** - * Construct a plotter with a specific plot name - * - * @param name - * the name of the plotter to use, which will show up on the - * website - */ - public Plotter(final String name) { - this.name = name; - } + /** + * Construct a plotter with a specific plot name + * + * @param name + * the name of the plotter to use, which will show up on the + * website + */ + public Plotter(final String name) { + this.name = name; + } - /** - * Get the current value for the plotted point. Since this function - * defers to an external function it may or may not return immediately - * thus cannot be guaranteed to be thread friendly or safe. This - * function can be called from any thread so care should be taken when - * accessing resources that need to be synchronized. - * - * @return the current value for the point to be plotted. - */ - public abstract int getValue(); + /** + * Get the current value for the plotted point. Since this function + * defers to an external function it may or may not return immediately + * thus cannot be guaranteed to be thread friendly or safe. This + * function can be called from any thread so care should be taken when + * accessing resources that need to be synchronized. + * + * @return the current value for the point to be plotted. + */ + public abstract int getValue(); - /** - * Get the column name for the plotted point - * - * @return the plotted point's column name - */ - public String getColumnName() { - return this.name; - } + /** + * Get the column name for the plotted point + * + * @return the plotted point's column name + */ + public String getColumnName() { + return this.name; + } - /** - * Called after the website graphs have been updated - */ - public void reset() { - } + /** + * Called after the website graphs have been updated + */ + public void reset() { + } - @Override - public int hashCode() { - return getColumnName().hashCode(); - } + @Override + public int hashCode() { + return getColumnName().hashCode(); + } - @Override - public boolean equals(final Object object) { - if (!(object instanceof Plotter)) { - return false; - } - final Plotter plotter = (Plotter) object; - return plotter.name.equals(this.name) && (plotter.getValue() == getValue()); - } - } + @Override + public boolean equals(final Object object) { + if (!(object instanceof Plotter)) { + return false; + } + final Plotter plotter = (Plotter) object; + return plotter.name.equals(this.name) + && (plotter.getValue() == getValue()); + } + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/PWE.java b/PlotSquared/src/com/intellectualcrafters/plot/PWE.java index ba3cf3881..834c89afa 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/PWE.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/PWE.java @@ -13,92 +13,104 @@ import com.sk89q.worldedit.bukkit.BukkitPlayer; import com.sk89q.worldedit.regions.CuboidRegion; /** - * + * * @author Citymonstret - * + * */ public class PWE { - public static void setMask(Player p, Location l) { - try { - LocalSession s; - if (PlotMain.worldEdit == null) { - s = WorldEdit.getInstance().getSession(p.getName()); - } else { - s = PlotMain.worldEdit.getSession(p); - } + public static void setMask(Player p, Location l) { + try { + LocalSession s; + if (PlotMain.worldEdit == null) { + s = WorldEdit.getInstance().getSession(p.getName()); + } else { + s = PlotMain.worldEdit.getSession(p); + } - PlotId id = PlayerFunctions.getPlot(l); - if (id != null) { - Plot plot = PlotMain.getPlots(l.getWorld()).get(id); - if (plot != null) { - boolean r; - r = (plot.getOwner() != null) && plot.getOwner().equals(p.getUniqueId()) || plot.helpers.contains(DBFunc.everyone) || plot.helpers.contains(p.getUniqueId()); - if (!r) { - if (p.hasPermission("plots.worldedit.bypass")) { - removeMask(p, s); - return; - } - } else { + PlotId id = PlayerFunctions.getPlot(l); + if (id != null) { + Plot plot = PlotMain.getPlots(l.getWorld()).get(id); + if (plot != null) { + boolean r; + r = (plot.getOwner() != null) + && plot.getOwner().equals(p.getUniqueId()) + || plot.helpers.contains(DBFunc.everyone) + || plot.helpers.contains(p.getUniqueId()); + if (!r) { + if (p.hasPermission("plots.worldedit.bypass")) { + removeMask(p, s); + return; + } + } else { - World w = p.getWorld(); + World w = p.getWorld(); - Location bloc = PlotHelper.getPlotBottomLoc(w, plot.id); - Location tloc = PlotHelper.getPlotTopLoc(w, plot.id); + Location bloc = PlotHelper.getPlotBottomLoc(w, plot.id); + Location tloc = PlotHelper.getPlotTopLoc(w, plot.id); - Vector bvec = new Vector(bloc.getBlockX() + 1, bloc.getBlockY() + 1, bloc.getBlockZ() + 1); - Vector tvec = new Vector(tloc.getBlockX(), tloc.getBlockY(), tloc.getBlockZ()); + Vector bvec = new Vector(bloc.getBlockX() + 1, + bloc.getBlockY() + 1, bloc.getBlockZ() + 1); + Vector tvec = new Vector(tloc.getBlockX(), + tloc.getBlockY(), tloc.getBlockZ()); - LocalWorld lw = PlotMain.worldEdit.wrapPlayer(p).getWorld(); + LocalWorld lw = PlotMain.worldEdit.wrapPlayer(p) + .getWorld(); - CuboidRegion region = new CuboidRegion(lw, bvec, tvec); - com.sk89q.worldedit.masks.RegionMask mask = new com.sk89q.worldedit.masks.RegionMask(region); + CuboidRegion region = new CuboidRegion(lw, bvec, tvec); + com.sk89q.worldedit.masks.RegionMask mask = new com.sk89q.worldedit.masks.RegionMask( + region); - s.setMask(mask); - return; - } - } - } - if (noMask(s)) { - BukkitPlayer plr = PlotMain.worldEdit.wrapPlayer(p); - Vector p1 = new Vector(69, 69, 69), p2 = new Vector(69, 69, 69); + s.setMask(mask); + return; + } + } + } + if (noMask(s)) { + BukkitPlayer plr = PlotMain.worldEdit.wrapPlayer(p); + Vector p1 = new Vector(69, 69, 69), p2 = new Vector(69, 69, 69); - s.setMask(new com.sk89q.worldedit.masks.RegionMask(new CuboidRegion(plr.getWorld(), p1, p2))); - } - } catch (Exception e) { -// throw new PlotSquaredException(PlotSquaredException.PlotError.MISSING_DEPENDENCY, "WorldEdit == Null?"); - } - } + s.setMask(new com.sk89q.worldedit.masks.RegionMask( + new CuboidRegion(plr.getWorld(), p1, p2))); + } + } catch (Exception e) { + // throw new + // PlotSquaredException(PlotSquaredException.PlotError.MISSING_DEPENDENCY, + // "WorldEdit == Null?"); + } + } - public static boolean noMask(LocalSession s) { - try { - com.sk89q.worldedit.masks.Mask mask = s.getMask(); - return mask == null; - } catch (Throwable e) { - return true; - } - } + public static boolean noMask(LocalSession s) { + try { + com.sk89q.worldedit.masks.Mask mask = s.getMask(); + return mask == null; + } catch (Throwable e) { + return true; + } + } - public static void removeMask(Player p, LocalSession s) { - try { - s.setMask(null); - } catch (Throwable e) { - com.sk89q.worldedit.masks.Mask mask = null; - s.setMask(mask); - } - } + public static void removeMask(Player p, LocalSession s) { + try { + s.setMask(null); + } catch (Throwable e) { + com.sk89q.worldedit.masks.Mask mask = null; + s.setMask(mask); + } + } - public static void removeMask(Player p) { - try { - LocalSession s; - if (PlotMain.worldEdit == null) { - s = WorldEdit.getInstance().getSession(p.getName()); - } else { - s = PlotMain.worldEdit.getSession(p); - } - removeMask(p, s); - } catch (Exception e) { -// throw new PlotSquaredException(PlotSquaredException.PlotError.MISSING_DEPENDENCY, "WorldEdit == Null?"); - } - } + public static void removeMask(Player p) { + try { + LocalSession s; + if (PlotMain.worldEdit == null) { + s = WorldEdit.getInstance().getSession(p.getName()); + } else { + s = PlotMain.worldEdit.getSession(p); + } + removeMask(p, s); + } catch (Exception e) { + // throw new + // PlotSquaredException(PlotSquaredException.PlotError.MISSING_DEPENDENCY, + // "WorldEdit == Null?"); + } + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/PlayerFunctions.java b/PlotSquared/src/com/intellectualcrafters/plot/PlayerFunctions.java index 5da87f98b..74e2db2b6 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/PlayerFunctions.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/PlayerFunctions.java @@ -26,238 +26,254 @@ import org.bukkit.entity.Player; /** * Functions involving players, plots and locations. - * + * * @author Citymonstret - * + * */ @SuppressWarnings("javadoc") public class PlayerFunctions { - /** - * - * @param player - * player - * @return - */ - public static boolean isInPlot(Player player) { - return getCurrentPlot(player) != null; - } + /** + * + * @param player + * player + * @return + */ + public static boolean isInPlot(Player player) { + return getCurrentPlot(player) != null; + } - /** - * - * @param plot - * plot - * @return - */ - public static boolean hasExpired(Plot plot) { - OfflinePlayer player = Bukkit.getOfflinePlayer(plot.owner); - long lp = player.getLastPlayed(); - long cu = System.currentTimeMillis(); - return (lp - cu) > 30l; - } + /** + * + * @param plot + * plot + * @return + */ + public static boolean hasExpired(Plot plot) { + OfflinePlayer player = Bukkit.getOfflinePlayer(plot.owner); + long lp = player.getLastPlayed(); + long cu = System.currentTimeMillis(); + return (lp - cu) > 30l; + } - public static ArrayList getPlotSelectionIds(World world, PlotId pos1, PlotId pos2) { - ArrayList myplots = new ArrayList(); - for (int x = pos1.x; x <= pos2.x; x++) { - for (int y = pos1.y; y <= pos2.y; y++) { - myplots.add(new PlotId(x, y)); - } - } + public static ArrayList getPlotSelectionIds(World world, + PlotId pos1, PlotId pos2) { + ArrayList myplots = new ArrayList(); + for (int x = pos1.x; x <= pos2.x; x++) { + for (int y = pos1.y; y <= pos2.y; y++) { + myplots.add(new PlotId(x, y)); + } + } - return myplots; - } + return myplots; + } - public static Plot getBottomPlot(World world, Plot plot) { - if (plot.settings.getMerged(0)) { - return getBottomPlot(world, PlotMain.getPlots(world).get(new PlotId(plot.id.x, plot.id.y - 1))); - } - if (plot.settings.getMerged(3)) { - return getBottomPlot(world, PlotMain.getPlots(world).get(new PlotId(plot.id.x - 1, plot.id.y))); - } - return plot; - } + public static Plot getBottomPlot(World world, Plot plot) { + if (plot.settings.getMerged(0)) { + return getBottomPlot( + world, + PlotMain.getPlots(world).get( + new PlotId(plot.id.x, plot.id.y - 1))); + } + if (plot.settings.getMerged(3)) { + return getBottomPlot( + world, + PlotMain.getPlots(world).get( + new PlotId(plot.id.x - 1, plot.id.y))); + } + return plot; + } - public static Plot getTopPlot(World world, Plot plot) { - if (plot.settings.getMerged(2)) { - return getTopPlot(world, PlotMain.getPlots(world).get(new PlotId(plot.id.x, plot.id.y + 1))); - } - if (plot.settings.getMerged(1)) { - return getTopPlot(world, PlotMain.getPlots(world).get(new PlotId(plot.id.x + 1, plot.id.y))); - } - return plot; - } + public static Plot getTopPlot(World world, Plot plot) { + if (plot.settings.getMerged(2)) { + return getTopPlot( + world, + PlotMain.getPlots(world).get( + new PlotId(plot.id.x, plot.id.y + 1))); + } + if (plot.settings.getMerged(1)) { + return getTopPlot( + world, + PlotMain.getPlots(world).get( + new PlotId(plot.id.x + 1, plot.id.y))); + } + return plot; + } - /** - * - * @param loc - * @return - */ - public static PlotId getPlotAbs(Location loc) { - String world = loc.getWorld().getName(); - PlotManager manager = PlotMain.getPlotManager(world); - if (manager == null) { - return null; - } - PlotWorld plotworld = PlotMain.getWorldSettings(world); - return manager.getPlotIdAbs(plotworld, loc); - } + /** + * + * @param loc + * @return + */ + public static PlotId getPlotAbs(Location loc) { + String world = loc.getWorld().getName(); + PlotManager manager = PlotMain.getPlotManager(world); + if (manager == null) { + return null; + } + PlotWorld plotworld = PlotMain.getWorldSettings(world); + return manager.getPlotIdAbs(plotworld, loc); + } - public static PlotId getPlot(Location loc) { - String world = loc.getWorld().getName(); - PlotManager manager = PlotMain.getPlotManager(world); - if (manager == null) { - return null; - } - PlotWorld plotworld = PlotMain.getWorldSettings(world); - return manager.getPlotId(plotworld, loc); - } + public static PlotId getPlot(Location loc) { + String world = loc.getWorld().getName(); + PlotManager manager = PlotMain.getPlotManager(world); + if (manager == null) { + return null; + } + PlotWorld plotworld = PlotMain.getWorldSettings(world); + return manager.getPlotId(plotworld, loc); + } - /** - * - * @param player - * @param plot - */ - public static void togglePlotWeather(Player player, Plot plot) { - player.setPlayerWeather(plot.settings.getRain() ? WeatherType.DOWNFALL : WeatherType.CLEAR); - } + /** + * + * @param player + * @param plot + */ + public static void togglePlotWeather(Player player, Plot plot) { + player.setPlayerWeather(plot.settings.getRain() ? WeatherType.DOWNFALL + : WeatherType.CLEAR); + } - /** - * - * @param player - * @param plot - */ - public static void togglePlotTime(Player player, Plot plot) { - player.setPlayerTime(plot.settings.getTime(), false); - } + /** + * + * @param player + * @param plot + */ + public static void togglePlotTime(Player player, Plot plot) { + player.setPlayerTime(plot.settings.getTime(), false); + } - /** - * - * @param player - * @return - */ - public static Plot getCurrentPlot(Player player) { - if (!PlotMain.isPlotWorld(player.getWorld())) { - return null; - } - PlotId id = getPlot(player.getLocation()); - World world = player.getWorld(); - if (id == null) { - return null; - } - HashMap plots = PlotMain.getPlots(world); - if (plots != null) { - if (plots.containsKey(id)) { - return plots.get(id); - } - } - return new Plot(id, null, Biome.FOREST, new ArrayList(), new ArrayList(), world.getName()); + /** + * + * @param player + * @return + */ + public static Plot getCurrentPlot(Player player) { + if (!PlotMain.isPlotWorld(player.getWorld())) { + return null; + } + PlotId id = getPlot(player.getLocation()); + World world = player.getWorld(); + if (id == null) { + return null; + } + HashMap plots = PlotMain.getPlots(world); + if (plots != null) { + if (plots.containsKey(id)) { + return plots.get(id); + } + } + return new Plot(id, null, Biome.FOREST, new ArrayList(), + new ArrayList(), world.getName()); - } + } - /** - * @deprecated - * @param id - * @param plot - */ - @Deprecated - public static void set(Integer[] id, Plot plot) { - PlotMain.updatePlot(plot); - } + /** + * @deprecated + * @param id + * @param plot + */ + @Deprecated + public static void set(Integer[] id, Plot plot) { + PlotMain.updatePlot(plot); + } - /** - * - * @param plr - * @return - */ - // public static Set getPlayerPlots(Player plr) { - // return PlotMain.getPlots(plr); - // } - // - public static Set getPlayerPlots(World world, Player plr) { - Set p = PlotMain.getPlots(world, plr); - if (p == null) { - return new HashSet(); - } - return p; - } + /** + * + * @param plr + * @return + */ + // public static Set getPlayerPlots(Player plr) { + // return PlotMain.getPlots(plr); + // } + // + public static Set getPlayerPlots(World world, Player plr) { + Set p = PlotMain.getPlots(world, plr); + if (p == null) { + return new HashSet(); + } + return p; + } - /** - * - * @param plr - * @return - */ - // public static int getPlayerPlotCount(Player plr) { - // return getPlayerPlots(plr).size(); - // } - // - public static int getPlayerPlotCount(World world, Player plr) { - return getPlayerPlots(world, plr).size(); - } + /** + * + * @param plr + * @return + */ + // public static int getPlayerPlotCount(Player plr) { + // return getPlayerPlots(plr).size(); + // } + // + public static int getPlayerPlotCount(World world, Player plr) { + return getPlayerPlots(world, plr).size(); + } - /** - * - * @param p - * @return - */ - @SuppressWarnings("SuspiciousNameCombination") - public static int getAllowedPlots(Player p) { - return PlotMain.hasPermissionRange(p, "plots.plot", Settings.MAX_PLOTS); - } + /** + * + * @param p + * @return + */ + @SuppressWarnings("SuspiciousNameCombination") + public static int getAllowedPlots(Player p) { + return PlotMain.hasPermissionRange(p, "plots.plot", Settings.MAX_PLOTS); + } - /** - * - * @return PlotMain.getPlots(); - * @deprecated - */ - @Deprecated - public static Set getPlots() { - return PlotMain.getPlots(); - } + /** + * + * @return PlotMain.getPlots(); + * @deprecated + */ + @Deprecated + public static Set getPlots() { + return PlotMain.getPlots(); + } - /** - * \\previous\\ - * - * @param plr - * @param msg - * Was used to wrap the chat client length (Packets out--) - */ - public static void sendMessageWrapped(Player plr, String msg) { - plr.sendMessage(msg); - } + /** + * \\previous\\ + * + * @param plr + * @param msg + * Was used to wrap the chat client length (Packets out--) + */ + public static void sendMessageWrapped(Player plr, String msg) { + plr.sendMessage(msg); + } - /** - * Send a message to the player - * - * @param plr - * Player to recieve message - * @param msg - * Message to send - */ - public static void sendMessage(Player plr, String msg) { - if ((msg.length() == 0) || msg.equalsIgnoreCase("")) { - return; - } - sendMessageWrapped(plr, ChatColor.translateAlternateColorCodes('&', C.PREFIX.s() + msg)); - } + /** + * Send a message to the player + * + * @param plr + * Player to recieve message + * @param msg + * Message to send + */ + public static void sendMessage(Player plr, String msg) { + if ((msg.length() == 0) || msg.equalsIgnoreCase("")) { + return; + } + sendMessageWrapped(plr, + ChatColor.translateAlternateColorCodes('&', C.PREFIX.s() + msg)); + } - /** - * Send a message to the player - * - * @param plr - * Player to recieve message - * @param c - * Caption to send - */ - public static void sendMessage(Player plr, C c, String... args) { - if (c.s().length() < 1) { - return; - } - String msg = c.s(); - if ((args != null) && (args.length > 0)) { - for (String str : args) { - msg = msg.replaceFirst("%s", str); - } - } - sendMessage(plr, msg); - } + /** + * Send a message to the player + * + * @param plr + * Player to recieve message + * @param c + * Caption to send + */ + public static void sendMessage(Player plr, C c, String... args) { + if (c.s().length() < 1) { + return; + } + String msg = c.s(); + if ((args != null) && (args.length > 0)) { + for (String str : args) { + msg = msg.replaceFirst("%s", str); + } + } + sendMessage(plr, msg); + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/Plot.java b/PlotSquared/src/com/intellectualcrafters/plot/Plot.java index 2d19fb0ef..88e3bb21c 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/Plot.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/Plot.java @@ -21,268 +21,286 @@ import com.intellectualcrafters.plot.database.DBFunc; /** * The plot class - * + * * @author Citymonstret - * + * */ @SuppressWarnings("javadoc") public class Plot implements Cloneable { - /** - * plot ID - */ - public PlotId id; - /** - * plot world - */ - public String world; - /** - * plot owner - */ - public UUID owner; - /** - * Deny Entry - */ - public boolean deny_entry; - /** - * List of helpers (with plot permissions) - */ - public ArrayList helpers; - /** - * List of trusted users (with plot permissions) - */ - public ArrayList trusted; - /** - * List of denied players - */ - public ArrayList denied; - /** - * External settings class - */ - public PlotSettings settings; - /** - * Delete on next save cycle? - */ - public boolean delete; - /** - * Has the plot changed since the last save cycle? - */ - public boolean hasChanged = false; + /** + * plot ID + */ + public PlotId id; + /** + * plot world + */ + public String world; + /** + * plot owner + */ + public UUID owner; + /** + * Deny Entry + */ + public boolean deny_entry; + /** + * List of helpers (with plot permissions) + */ + public ArrayList helpers; + /** + * List of trusted users (with plot permissions) + */ + public ArrayList trusted; + /** + * List of denied players + */ + public ArrayList denied; + /** + * External settings class + */ + public PlotSettings settings; + /** + * Delete on next save cycle? + */ + public boolean delete; + /** + * Has the plot changed since the last save cycle? + */ + public boolean hasChanged = false; - /** - * Primary constructor - * - * @param id - * @param owner - * @param plotBiome - * @param helpers - * @param denied - */ - public Plot(PlotId id, UUID owner, Biome plotBiome, ArrayList helpers, ArrayList denied, String world) { - this.id = id; - this.settings = new PlotSettings(this); - this.settings.setBiome(plotBiome); - this.owner = owner; - this.deny_entry = this.owner == null; - this.helpers = helpers; - this.denied = denied; - this.trusted = new ArrayList(); - this.settings.setTime(8000l); - this.settings.setRain(false); - this.settings.setTimeChange(false); - this.settings.setAlias(""); - this.settings.setPosition(PlotHomePosition.DEFAULT); - this.delete = false; - this.settings.setFlags(new Flag[0]); - this.world = world; - } + /** + * Primary constructor + * + * @param id + * @param owner + * @param plotBiome + * @param helpers + * @param denied + */ + public Plot(PlotId id, UUID owner, Biome plotBiome, + ArrayList helpers, ArrayList denied, String world) { + this.id = id; + this.settings = new PlotSettings(this); + this.settings.setBiome(plotBiome); + this.owner = owner; + this.deny_entry = this.owner == null; + this.helpers = helpers; + this.denied = denied; + this.trusted = new ArrayList(); + this.settings.setTime(8000l); + this.settings.setRain(false); + this.settings.setTimeChange(false); + this.settings.setAlias(""); + this.settings.setPosition(PlotHomePosition.DEFAULT); + this.delete = false; + this.settings.setFlags(new Flag[0]); + this.world = world; + } - /** - * Constructor for saved plots - * - * @param id - * @param owner - * @param plotBiome - * @param helpers - * @param denied - * @param changeTime - * @param time - * @param merged - */ - public Plot(PlotId id, UUID owner, Biome plotBiome, ArrayList helpers, ArrayList trusted, ArrayList denied, boolean changeTime, long time, boolean rain, String alias, PlotHomePosition position, Flag[] flags, String world, boolean[] merged) { - this.id = id; - this.settings = new PlotSettings(this); - this.settings.setBiome(plotBiome); - this.owner = owner; - this.deny_entry = this.owner != null; - this.trusted = trusted; - this.helpers = helpers; - this.denied = denied; - this.settings.setTime(time); - this.settings.setRain(rain); - this.settings.setTimeChange(changeTime); - this.settings.setAlias(alias); - this.settings.setPosition(position); - this.settings.setMerged(merged); - this.delete = false; - if (flags != null) { - this.settings.setFlags(flags); - } else { - this.settings.setFlags(new Flag[0]); - } - this.world = world; - } + /** + * Constructor for saved plots + * + * @param id + * @param owner + * @param plotBiome + * @param helpers + * @param denied + * @param changeTime + * @param time + * @param merged + */ + public Plot(PlotId id, UUID owner, Biome plotBiome, + ArrayList helpers, ArrayList trusted, + ArrayList denied, boolean changeTime, long time, + boolean rain, String alias, PlotHomePosition position, + Flag[] flags, String world, boolean[] merged) { + this.id = id; + this.settings = new PlotSettings(this); + this.settings.setBiome(plotBiome); + this.owner = owner; + this.deny_entry = this.owner != null; + this.trusted = trusted; + this.helpers = helpers; + this.denied = denied; + this.settings.setTime(time); + this.settings.setRain(rain); + this.settings.setTimeChange(changeTime); + this.settings.setAlias(alias); + this.settings.setPosition(position); + this.settings.setMerged(merged); + this.delete = false; + if (flags != null) { + this.settings.setFlags(flags); + } else { + this.settings.setFlags(new Flag[0]); + } + this.world = world; + } - /** - * Check if the plot has a set owner - * - * @return false if there is no owner - */ - public boolean hasOwner() { - return this.owner != null; - } + /** + * Check if the plot has a set owner + * + * @return false if there is no owner + */ + public boolean hasOwner() { + return this.owner != null; + } - /** - * Set the owner - * - * @param player - */ - public void setOwner(Player player) { - this.owner = player.getUniqueId(); - } + /** + * Set the owner + * + * @param player + */ + public void setOwner(Player player) { + this.owner = player.getUniqueId(); + } - /** - * Check if the player is either the owner or on the helpers list - * - * @param player - * @return true if the player is added as a helper or is the owner - */ - public boolean hasRights(Player player) { - return player.hasPermission("plots.admin") || ((this.helpers != null) && this.helpers.contains(DBFunc.everyone)) || ((this.helpers != null) && this.helpers.contains(player.getUniqueId())) || ((this.owner != null) && this.owner.equals(player.getUniqueId())) || ((this.owner != null) && (this.trusted != null) && (Bukkit.getPlayer(this.owner) != null) && (this.trusted.contains(player.getUniqueId()) || this.trusted.contains(DBFunc.everyone))); - } + /** + * Check if the player is either the owner or on the helpers list + * + * @param player + * @return true if the player is added as a helper or is the owner + */ + public boolean hasRights(Player player) { + return player.hasPermission("plots.admin") + || ((this.helpers != null) && this.helpers + .contains(DBFunc.everyone)) + || ((this.helpers != null) && this.helpers.contains(player + .getUniqueId())) + || ((this.owner != null) && this.owner.equals(player + .getUniqueId())) + || ((this.owner != null) && (this.trusted != null) + && (Bukkit.getPlayer(this.owner) != null) && (this.trusted + .contains(player.getUniqueId()) || this.trusted + .contains(DBFunc.everyone))); + } - /** - * Should the player be allowed to enter? - * - * @param player - * @return false if the player is allowed to enter - */ - public boolean deny_entry(Player player) { - return (this.denied != null) && ((this.denied.contains(DBFunc.everyone) && !this.hasRights(player)) || (!this.hasRights(player) && this.denied.contains(player.getUniqueId()))); - } + /** + * Should the player be allowed to enter? + * + * @param player + * @return false if the player is allowed to enter + */ + public boolean deny_entry(Player player) { + return (this.denied != null) + && ((this.denied.contains(DBFunc.everyone) && !this + .hasRights(player)) || (!this.hasRights(player) && this.denied + .contains(player.getUniqueId()))); + } - /** - * Get the UUID of the owner - * - */ - public UUID getOwner() { - return this.owner; - } + /** + * Get the UUID of the owner + * + */ + public UUID getOwner() { + return this.owner; + } - /** - * Get the plot ID - * - */ - public PlotId getId() { - return this.id; - } + /** + * Get the plot ID + * + */ + public PlotId getId() { + return this.id; + } - /** - * Get the plot World - * - */ - public World getWorld() { - return Bukkit.getWorld(this.world); - } + /** + * Get the plot World + * + */ + public World getWorld() { + return Bukkit.getWorld(this.world); + } - /** - * Get a clone of the plot - * - * @return - */ - @Override - public Object clone() throws CloneNotSupportedException { - try { - return super.clone(); - } catch (CloneNotSupportedException e) { - return null; - } - } + /** + * Get a clone of the plot + * + * @return + */ + @Override + public Object clone() throws CloneNotSupportedException { + try { + return super.clone(); + } catch (CloneNotSupportedException e) { + return null; + } + } - /** - * Deny someone (use DBFunc.addDenied() as well) - * - * @param uuid - */ - public void addDenied(UUID uuid) { - this.denied.add(uuid); - } + /** + * Deny someone (use DBFunc.addDenied() as well) + * + * @param uuid + */ + public void addDenied(UUID uuid) { + this.denied.add(uuid); + } - /** - * Add someone as a helper (use DBFunc as well) - * - * @param uuid - */ - public void addHelper(UUID uuid) { - this.helpers.add(uuid); - } + /** + * Add someone as a helper (use DBFunc as well) + * + * @param uuid + */ + public void addHelper(UUID uuid) { + this.helpers.add(uuid); + } - /** - * Add someone as a trusted user (use DBFunc as well) - * - * @param uuid - */ - public void addTrusted(UUID uuid) { - this.trusted.add(uuid); - } + /** + * Add someone as a trusted user (use DBFunc as well) + * + * @param uuid + */ + public void addTrusted(UUID uuid) { + this.trusted.add(uuid); + } - /** - * Get plot display name - * - * @return alias if set, else id - */ - public String getDisplayName() { - if (this.settings.getAlias().length() > 1) { - return this.settings.getAlias(); - } - return this.getId().x + ";" + this.getId().y; - } + /** + * Get plot display name + * + * @return alias if set, else id + */ + public String getDisplayName() { + if (this.settings.getAlias().length() > 1) { + return this.settings.getAlias(); + } + return this.getId().x + ";" + this.getId().y; + } - /** - * Remove a denied player (use DBFunc as well) - * - * @param uuid - */ - public void removeDenied(UUID uuid) { - this.denied.remove(uuid); - } + /** + * Remove a denied player (use DBFunc as well) + * + * @param uuid + */ + public void removeDenied(UUID uuid) { + this.denied.remove(uuid); + } - /** - * Remove a helper (use DBFunc as well) - * - * @param uuid - */ - public void removeHelper(UUID uuid) { - this.helpers.remove(uuid); - } + /** + * Remove a helper (use DBFunc as well) + * + * @param uuid + */ + public void removeHelper(UUID uuid) { + this.helpers.remove(uuid); + } - /** - * Remove a trusted user (use DBFunc as well) - * - * @param uuid - */ - public void removeTrusted(UUID uuid) { - this.trusted.remove(uuid); - } + /** + * Remove a trusted user (use DBFunc as well) + * + * @param uuid + */ + public void removeTrusted(UUID uuid) { + this.trusted.remove(uuid); + } - /** - * Clear a plot - * - * @param plr - * initiator - */ - public void clear(Player plr) { - PlotHelper.clear(plr, this); - } + /** + * Clear a plot + * + * @param plr + * initiator + */ + public void clear(Player plr) { + PlotHelper.clear(plr, this); + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/PlotBlock.java b/PlotSquared/src/com/intellectualcrafters/plot/PlotBlock.java index 92297cc01..c8f3c4c2c 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/PlotBlock.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/PlotBlock.java @@ -1,10 +1,11 @@ package com.intellectualcrafters.plot; public class PlotBlock { - public short id; - public byte data; - public PlotBlock(short id, byte data) { - this.id = id; - this.data = data; - } + public short id; + public byte data; + + public PlotBlock(short id, byte data) { + this.id = id; + this.data = data; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/PlotGenerator.java b/PlotSquared/src/com/intellectualcrafters/plot/PlotGenerator.java index 77bee2cdd..d8fab8b27 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/PlotGenerator.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/PlotGenerator.java @@ -3,8 +3,8 @@ package com.intellectualcrafters.plot; import org.bukkit.generator.ChunkGenerator; public abstract class PlotGenerator extends ChunkGenerator { - - public abstract PlotWorld getPlotWorld(); - - public abstract PlotManager getPlotManager(); + + public abstract PlotWorld getPlotWorld(); + + public abstract PlotManager getPlotManager(); } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/PlotHelper.java b/PlotSquared/src/com/intellectualcrafters/plot/PlotHelper.java index 4874c68e5..1b7bbb21b 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/PlotHelper.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/PlotHelper.java @@ -9,11 +9,19 @@ package com.intellectualcrafters.plot; -import com.intellectualcrafters.plot.database.DBFunc; +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.UUID; import net.milkbowl.vault.economy.Economy; -import org.bukkit.*; +import org.bukkit.Bukkit; +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.OfflinePlayer; +import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.block.Block; import org.bukkit.block.BlockState; @@ -21,805 +29,844 @@ import org.bukkit.block.Sign; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; -import java.io.File; -import java.util.*; +import com.intellectualcrafters.plot.database.DBFunc; /** * plot functions - * + * * @author Citymonstret - * + * */ public class PlotHelper { - public static boolean canSetFast = false; - static long state = 1; + public static boolean canSetFast = false; + static long state = 1; - private static double calculateNeededTime(double blocks, double blocks_per_second) { - return (blocks / blocks_per_second); - } + /** + * direction 0 = north, 1 = south, etc: + * + * @param id + * @param direction + * @return + */ + public static PlotId getPlotIdRelative(PlotId id, int direction) { + switch (direction) { + case 0: + return new PlotId(id.x, id.y - 1); + case 1: + return new PlotId(id.x + 1, id.y); + case 2: + return new PlotId(id.x, id.y + 1); + case 3: + return new PlotId(id.x - 1, id.y); + } + return id; + } - /** - * direction 0 = north, 1 = south, etc: - * - * @param id - * @param direction - * @return - */ - public static PlotId getPlotIdRelative(PlotId id, int direction) { - switch (direction) { - case 0: - return new PlotId(id.x, id.y - 1); - case 1: - return new PlotId(id.x + 1, id.y); - case 2: - return new PlotId(id.x, id.y + 1); - case 3: - return new PlotId(id.x - 1, id.y); - } - return id; - } + public static boolean mergePlots(Player plr, World world, + ArrayList plotIds) { + PlotWorld plotworld = PlotMain.getWorldSettings(world); + if (PlotMain.useEconomy && plotworld.USE_ECONOMY) { + double cost = plotIds.size() * plotworld.MERGE_PRICE; + if (cost > 0d) { + Economy economy = PlotMain.economy; + if (economy.getBalance(plr) < cost) { + PlayerFunctions.sendMessage(plr, C.CANNOT_AFFORD_MERGE, "" + + cost); + return false; + } + economy.withdrawPlayer(plr, cost); + PlayerFunctions.sendMessage(plr, C.REMOVED_BALANCE, cost + ""); + } + } + return mergePlots(world, plotIds); + } - public static boolean mergePlots(Player plr, World world, ArrayList plotIds) { - PlotWorld plotworld = PlotMain.getWorldSettings(world); - if(PlotMain.useEconomy && plotworld.USE_ECONOMY) { - double cost = plotIds.size() * plotworld.MERGE_PRICE; - if (cost > 0d) { - Economy economy = PlotMain.economy; - if (economy.getBalance(plr) < cost) { - PlayerFunctions.sendMessage(plr, C.CANNOT_AFFORD_MERGE, "" + cost); - return false; - } - economy.withdrawPlayer(plr, cost); - PlayerFunctions.sendMessage(plr, C.REMOVED_BALANCE, cost + ""); - } - } - return mergePlots(world, plotIds); - } + /** + * Completely merges a set of plots
+ * (There are no checks to make sure you supply the correct + * arguments)
+ * - Misuse of this method can result in unusable plots
+ * - the set of plots must belong to one owner and be rectangular
+ * - the plot array must be sorted in ascending order
+ * - Road will be removed where required
+ * - changes will be saved to DB
+ * + * @param world + * @param plotIds + * @return boolean (success) + */ + public static boolean mergePlots(World world, ArrayList plotIds) { + if (plotIds.size() < 2) { + return false; + } + PlotId pos1 = plotIds.get(0); + PlotId pos2 = plotIds.get(plotIds.size() - 1); - /** - * Completely merges a set of plots
- * (There are no checks to make sure you supply the correct - * arguments)
- * - Misuse of this method can result in unusable plots
- * - the set of plots must belong to one owner and be rectangular
- * - the plot array must be sorted in ascending order
- * - Road will be removed where required
- * - changes will be saved to DB
- * - * @param world - * @param plotIds - * @return boolean (success) - */ - public static boolean mergePlots(World world, ArrayList plotIds) { - if (plotIds.size() < 2) { - return false; - } - PlotId pos1 = plotIds.get(0); - PlotId pos2 = plotIds.get(plotIds.size() - 1); + PlotManager manager = PlotMain.getPlotManager(world); + PlotWorld plotworld = PlotMain.getWorldSettings(world); - PlotManager manager = PlotMain.getPlotManager(world); - PlotWorld plotworld = PlotMain.getWorldSettings(world); - - for (int x = pos1.x; x <= pos2.x; x++) { - for (int y = pos1.y; y <= pos2.y; y++) { + for (int x = pos1.x; x <= pos2.x; x++) { + for (int y = pos1.y; y <= pos2.y; y++) { - boolean lx = x < pos2.x; - boolean ly = y < pos2.y; + boolean lx = x < pos2.x; + boolean ly = y < pos2.y; - PlotId id = new PlotId(x, y); - Plot plot = PlotMain.getPlots(world).get(id); + PlotId id = new PlotId(x, y); + Plot plot = PlotMain.getPlots(world).get(id); - if (lx) { - if (ly) { - if (!plot.settings.getMerged(1) || !plot.settings.getMerged(2)) { - manager.createRoadSouthEast(plotworld, plot); - } - } - if (!plot.settings.getMerged(1)) { - Plot plot2 = PlotMain.getPlots(world).get(new PlotId(x + 1, y)); - mergePlot(world, plot, plot2); - plot.settings.setMerged(1, true); - plot2.settings.setMerged(3, true); - } - } - if (ly) { - if (!plot.settings.getMerged(2)) { - Plot plot2 = PlotMain.getPlots(world).get(new PlotId(x, y + 1)); - mergePlot(world, plot, plot2); - plot.settings.setMerged(2, true); - plot2.settings.setMerged(0, true); - } - } + if (lx) { + if (ly) { + if (!plot.settings.getMerged(1) + || !plot.settings.getMerged(2)) { + manager.createRoadSouthEast(plotworld, plot); + } + } + if (!plot.settings.getMerged(1)) { + Plot plot2 = PlotMain.getPlots(world).get( + new PlotId(x + 1, y)); + mergePlot(world, plot, plot2); + plot.settings.setMerged(1, true); + plot2.settings.setMerged(3, true); + } + } + if (ly) { + if (!plot.settings.getMerged(2)) { + Plot plot2 = PlotMain.getPlots(world).get( + new PlotId(x, y + 1)); + mergePlot(world, plot, plot2); + plot.settings.setMerged(2, true); + plot2.settings.setMerged(0, true); + } + } - } - } - - manager.finishPlotMerge(world, plotworld, plotIds); - return true; - } + } + } - /** - * Merges 2 plots Removes the road inbetween
- * - Assumes the first plot parameter is lower
- * - Assumes neither are a Mega-plot
- * - Assumes plots are directly next to each other
- * - Saves to DB - * - * @param world - * @param lesserPlot - * @param greaterPlot - */ - public static void mergePlot(World world, Plot lesserPlot, Plot greaterPlot) { - PlotManager manager = PlotMain.getPlotManager(world); - PlotWorld plotworld = PlotMain.getWorldSettings(world); - - if (lesserPlot.id.x == greaterPlot.id.x) { - if (!lesserPlot.settings.getMerged(2)) { - lesserPlot.settings.setMerged(2, true); - greaterPlot.settings.setMerged(0, true); - manager.createRoadSouth(plotworld, lesserPlot); - } - } else { - if (!lesserPlot.settings.getMerged(1)) { - lesserPlot.settings.setMerged(1, true); - greaterPlot.settings.setMerged(3, true); - manager.createRoadSouth(plotworld, lesserPlot); - } - } - } + manager.finishPlotMerge(world, plotworld, plotIds); + return true; + } - public static final long nextLong() { - long a = state; - state = xorShift64(a); - return a; - } + /** + * Merges 2 plots Removes the road inbetween
+ * - Assumes the first plot parameter is lower
+ * - Assumes neither are a Mega-plot
+ * - Assumes plots are directly next to each other
+ * - Saves to DB + * + * @param world + * @param lesserPlot + * @param greaterPlot + */ + public static void mergePlot(World world, Plot lesserPlot, Plot greaterPlot) { + PlotManager manager = PlotMain.getPlotManager(world); + PlotWorld plotworld = PlotMain.getWorldSettings(world); - public static final long xorShift64(long a) { - a ^= (a << 21); - a ^= (a >>> 35); - a ^= (a << 4); - return a; - } + if (lesserPlot.id.x == greaterPlot.id.x) { + if (!lesserPlot.settings.getMerged(2)) { + lesserPlot.settings.setMerged(2, true); + greaterPlot.settings.setMerged(0, true); + manager.createRoadSouth(plotworld, lesserPlot); + } + } else { + if (!lesserPlot.settings.getMerged(1)) { + lesserPlot.settings.setMerged(1, true); + greaterPlot.settings.setMerged(3, true); + manager.createRoadSouth(plotworld, lesserPlot); + } + } + } - public static final int random(int n) { - if (n == 1) { - return 0; - } - long r = ((nextLong() >>> 32) * n) >> 32; - return (int) r; - } + public static final long nextLong() { + long a = state; + state = xorShift64(a); + return a; + } - public static void removeSign(Player plr, Plot p) { - World world = plr.getWorld(); - PlotManager manager = PlotMain.getPlotManager(world); - PlotWorld plotworld = PlotMain.getWorldSettings(world); - Location loc = manager.getSignLoc(plr, plotworld, p); - loc.getBlock().setType(Material.AIR); - } + public static final long xorShift64(long a) { + a ^= (a << 21); + a ^= (a >>> 35); + a ^= (a << 4); + return a; + } - @SuppressWarnings("deprecation") - public static void setSign(Player plr, Plot p) { - World world = plr.getWorld(); - PlotManager manager = PlotMain.getPlotManager(world); - PlotWorld plotworld = PlotMain.getWorldSettings(world); - Location loc = manager.getSignLoc(plr, plotworld, p); - Block bs = loc.getBlock(); - bs.setType(Material.AIR); - bs.setTypeIdAndData(Material.WALL_SIGN.getId(), (byte) 2, false); - String id = p.id.y + ";" + p.id.x; - Sign sign = (Sign) bs.getState(); - sign.setLine(0, C.OWNER_SIGN_LINE_1.translated().replaceAll("%id%", id)); - sign.setLine(1, C.OWNER_SIGN_LINE_2.translated().replaceAll("%id%", id).replaceAll("%plr%", plr.getName())); - sign.setLine(2, C.OWNER_SIGN_LINE_3.translated().replaceAll("%id%", id).replaceAll("%plr%", plr.getName())); - sign.setLine(3, C.OWNER_SIGN_LINE_4.translated().replaceAll("%id%", id).replaceAll("%plr%", plr.getName())); - sign.update(true); - } + public static final int random(int n) { + if (n == 1) { + return 0; + } + long r = ((nextLong() >>> 32) * n) >> 32; + return (int) r; + } - public static String getPlayerName(UUID uuid) { - if (uuid == null) { - return "unknown"; - } - OfflinePlayer plr = Bukkit.getOfflinePlayer(uuid); - if (plr == null) { - return "unknown"; - } - return plr.getName(); - } + public static void removeSign(Player plr, Plot p) { + World world = plr.getWorld(); + PlotManager manager = PlotMain.getPlotManager(world); + PlotWorld plotworld = PlotMain.getWorldSettings(world); + Location loc = manager.getSignLoc(plr, plotworld, p); + loc.getBlock().setType(Material.AIR); + } - public static String getStringSized(int max, String string) { - if (string.length() > max) { - return string.substring(0, max); - } - return string; - } - - public static void setBlock(Block block, PlotBlock plotblock) { - - if (canSetFast) { - if (block.getTypeId() != plotblock.id && plotblock.data != block.getData()) { - try { - SetBlockFast.set(block.getWorld(), block.getX(), block.getY(), block.getZ(), plotblock.id, plotblock.data); + @SuppressWarnings("deprecation") + public static void setSign(Player plr, Plot p) { + World world = plr.getWorld(); + PlotManager manager = PlotMain.getPlotManager(world); + PlotWorld plotworld = PlotMain.getWorldSettings(world); + Location loc = manager.getSignLoc(plr, plotworld, p); + Block bs = loc.getBlock(); + bs.setType(Material.AIR); + bs.setTypeIdAndData(Material.WALL_SIGN.getId(), (byte) 2, false); + String id = p.id.y + ";" + p.id.x; + Sign sign = (Sign) bs.getState(); + sign.setLine(0, C.OWNER_SIGN_LINE_1.translated().replaceAll("%id%", id)); + sign.setLine(1, C.OWNER_SIGN_LINE_2.translated().replaceAll("%id%", id) + .replaceAll("%plr%", plr.getName())); + sign.setLine(2, C.OWNER_SIGN_LINE_3.translated().replaceAll("%id%", id) + .replaceAll("%plr%", plr.getName())); + sign.setLine(3, C.OWNER_SIGN_LINE_4.translated().replaceAll("%id%", id) + .replaceAll("%plr%", plr.getName())); + sign.update(true); + } + + public static String getPlayerName(UUID uuid) { + if (uuid == null) { + return "unknown"; + } + OfflinePlayer plr = Bukkit.getOfflinePlayer(uuid); + if (plr == null) { + return "unknown"; + } + return plr.getName(); + } + + public static String getStringSized(int max, String string) { + if (string.length() > max) { + return string.substring(0, max); + } + return string; + } + + public static void setBlock(Block block, PlotBlock plotblock) { + + if (canSetFast) { + if (block.getTypeId() != plotblock.id + && plotblock.data != block.getData()) { + try { + SetBlockFast.set(block.getWorld(), block.getX(), + block.getY(), block.getZ(), plotblock.id, + plotblock.data); return; } catch (NoSuchMethodException e) { canSetFast = false; } - } - } - if (block.getData() == plotblock.data) { - if (block.getTypeId() != plotblock.id) { - block.setTypeId(plotblock.id); - } - } - else { + } + } + if (block.getData() == plotblock.data) { + if (block.getTypeId() != plotblock.id) { + block.setTypeId(plotblock.id); + } + } else { if (block.getTypeId() == plotblock.id) { block.setData(plotblock.data); - } - else { - block.setTypeIdAndData(plotblock.id, plotblock.data, false); - } - } - } + } else { + block.setTypeIdAndData(plotblock.id, plotblock.data, false); + } + } + } - public static void adjustWall(Player player, World w, Plot plot, short id, byte data) { - World world = player.getWorld(); - PlotManager manager = PlotMain.getPlotManager(world); - PlotWorld plotworld = PlotMain.getWorldSettings(world); - - manager.setWall(player, plotworld, plot.id, new PlotBlock(id,data)); - } + public static void adjustWall(Player player, Plot plot, PlotBlock block) { + World world = player.getWorld(); + PlotManager manager = PlotMain.getPlotManager(world); + PlotWorld plotworld = PlotMain.getWorldSettings(world); - public static void autoMerge(World world, Plot plot, Player player) { - if (plot == null) { - return; - } - if (plot.owner == null) { - return; - } - if (!plot.owner.equals(player.getUniqueId())) { - return; - } + manager.setWall(player, plotworld, plot.id, block); + } - ArrayList plots; - boolean merge = true; - while (merge) { - PlotId bot = PlayerFunctions.getBottomPlot(world, plot).id; - PlotId top = PlayerFunctions.getTopPlot(world, plot).id; - merge = false; - plots = PlayerFunctions.getPlotSelectionIds(world, new PlotId(bot.x, bot.y - 1), new PlotId(top.x, top.y)); - if (ownsPlots(world, plots, player, 0)) { - merge = true; - mergePlots(world, plots); - continue; - } - plots = PlayerFunctions.getPlotSelectionIds(world, new PlotId(bot.x, bot.y), new PlotId(top.x + 1, top.y)); - if (ownsPlots(world, plots, player, 1)) { - merge = true; - mergePlots(world, plots); - continue; - } - plots = PlayerFunctions.getPlotSelectionIds(world, new PlotId(bot.x, bot.y), new PlotId(top.x, top.y + 1)); - if (ownsPlots(world, plots, player, 2)) { - merge = true; - mergePlots(world, plots); - continue; - } - plots = PlayerFunctions.getPlotSelectionIds(world, new PlotId(bot.x - 1, bot.y), new PlotId(top.x, top.y)); - if (ownsPlots(world, plots, player, 3)) { - merge = true; - mergePlots(world, plots); - continue; - } - } - if (canSetFast) { - SetBlockFast.update(player); - } - } + public static void autoMerge(World world, Plot plot, Player player) { + if (plot == null) { + return; + } + if (plot.owner == null) { + return; + } + if (!plot.owner.equals(player.getUniqueId())) { + return; + } - private static boolean ownsPlots(World world, ArrayList plots, Player player, int dir) { - PlotId id_min = plots.get(0); - PlotId id_max = plots.get(plots.size() - 1); - for (PlotId myid : plots) { - Plot myplot = PlotMain.getPlots(world).get(myid); - if ((myplot == null) || !myplot.hasOwner() || !(myplot.getOwner().equals(player.getUniqueId()))) { - return false; - } - PlotId top = PlayerFunctions.getTopPlot(world, myplot).id; - if (((top.x > id_max.x) && (dir != 1)) || ((top.y > id_max.y) && (dir != 2))) { - return false; - } - PlotId bot = PlayerFunctions.getBottomPlot(world, myplot).id; - if (((bot.x < id_min.x) && (dir != 3)) || ((bot.y < id_min.y) && (dir != 0))) { - return false; - } - } - return true; - } + ArrayList plots; + boolean merge = true; + while (merge) { + PlotId bot = PlayerFunctions.getBottomPlot(world, plot).id; + PlotId top = PlayerFunctions.getTopPlot(world, plot).id; + merge = false; + plots = PlayerFunctions.getPlotSelectionIds(world, new PlotId( + bot.x, bot.y - 1), new PlotId(top.x, top.y)); + if (ownsPlots(world, plots, player, 0)) { + merge = true; + mergePlots(world, plots); + continue; + } + plots = PlayerFunctions.getPlotSelectionIds(world, new PlotId( + bot.x, bot.y), new PlotId(top.x + 1, top.y)); + if (ownsPlots(world, plots, player, 1)) { + merge = true; + mergePlots(world, plots); + continue; + } + plots = PlayerFunctions.getPlotSelectionIds(world, new PlotId( + bot.x, bot.y), new PlotId(top.x, top.y + 1)); + if (ownsPlots(world, plots, player, 2)) { + merge = true; + mergePlots(world, plots); + continue; + } + plots = PlayerFunctions.getPlotSelectionIds(world, new PlotId( + bot.x - 1, bot.y), new PlotId(top.x, top.y)); + if (ownsPlots(world, plots, player, 3)) { + merge = true; + mergePlots(world, plots); + continue; + } + } + if (canSetFast) { + SetBlockFast.update(player); + } + } - public static boolean createPlot(Player player, Plot plot) { - World w = plot.getWorld(); - Plot p = new Plot(plot.id, player.getUniqueId(), plot.settings.getBiome(), new ArrayList(), new ArrayList(), w.getName()); - PlotMain.updatePlot(p); - DBFunc.createPlot(p); - DBFunc.createPlotSettings(DBFunc.getId(w.getName(), p.id), p); - PlotWorld plotworld = PlotMain.getWorldSettings(w); - if (plotworld.AUTO_MERGE) { - autoMerge(w, p, player); - } + private static boolean ownsPlots(World world, ArrayList plots, + Player player, int dir) { + PlotId id_min = plots.get(0); + PlotId id_max = plots.get(plots.size() - 1); + for (PlotId myid : plots) { + Plot myplot = PlotMain.getPlots(world).get(myid); + if ((myplot == null) || !myplot.hasOwner() + || !(myplot.getOwner().equals(player.getUniqueId()))) { + return false; + } + PlotId top = PlayerFunctions.getTopPlot(world, myplot).id; + if (((top.x > id_max.x) && (dir != 1)) + || ((top.y > id_max.y) && (dir != 2))) { + return false; + } + PlotId bot = PlayerFunctions.getBottomPlot(world, myplot).id; + if (((bot.x < id_min.x) && (dir != 3)) + || ((bot.y < id_min.y) && (dir != 0))) { + return false; + } + } + return true; + } - return true; - } + public static boolean createPlot(Player player, Plot plot) { + World w = plot.getWorld(); + Plot p = new Plot(plot.id, player.getUniqueId(), + plot.settings.getBiome(), new ArrayList(), + new ArrayList(), w.getName()); + PlotMain.updatePlot(p); + DBFunc.createPlot(p); + DBFunc.createPlotSettings(DBFunc.getId(w.getName(), p.id), p); + PlotWorld plotworld = PlotMain.getWorldSettings(w); + if (plotworld.AUTO_MERGE) { + autoMerge(w, p, player); + } - public static int getLoadedChunks(World world) { - return world.getLoadedChunks().length; - } + return true; + } - public static int getEntities(World world) { - return world.getEntities().size(); - } + public static int getLoadedChunks(World world) { + return world.getLoadedChunks().length; + } - public static int getTileEntities(World world) { - PlotMain.getWorldSettings(world); - int x = 0; - for (Chunk chunk : world.getLoadedChunks()) { - x += chunk.getTileEntities().length; - } - return x; - } + public static int getEntities(World world) { + return world.getEntities().size(); + } - public static double getWorldFolderSize(World world) { - // long size = FileUtil.sizeOfDirectory(world.getWorldFolder()); - File folder = world.getWorldFolder(); - long size = folder.length(); - return (((size) / 1024) / 1024); - } + public static int getTileEntities(World world) { + PlotMain.getWorldSettings(world); + int x = 0; + for (Chunk chunk : world.getLoadedChunks()) { + x += chunk.getTileEntities().length; + } + return x; + } - // public static void adjustLinkedPlots(String id) { - // World world = Bukkit.getWorld(Settings.PLOT_WORLD); - // int x = getIdX(id); - // int z = getIdZ(id); - // - // plot p11 = getPlot(id); - // if (p11 != null) { - // plot p01, p10, p12, p21, p00, p02, p20, p22; - // p01 = getPlot(x - 1, z); - // p10 = getPlot(x, z - 1); - // p12 = getPlot(x, z + 1); - // p21 = getPlot(x + 1, z); - // p00 = getPlot(x - 1, z - 1); - // p02 = getPlot(x - 1, z + 1); - // p20 = getPlot(x + 1, z - 1); - // p22 = getPlot(x + 1, z + 1); - // if (p01 != null && p01.owner.equals(p11.owner)) { - // fillroad(p01, p11, world); - // } - // - // if (p10 != null && p10.owner.equals(p11.owner)) { - // fillroad(p10, p11, world); - // } - // - // if (p12 != null && p12.owner.equals(p11.owner)) { - // fillroad(p12, p11, world); - // } - // - // if (p21 != null && p21.owner.equals(p11.owner)) { - // fillroad(p21, p11, world); - // } - // - // if (p00 != null && p10 != null && p01 != null - // && p00.owner.equals(p11.owner) - // && p11.owner.equals(p10.owner) - // && p10.owner.equals(p01.owner)) { - // fillmiddleroad(p00, p11, world); - // } - // - // if (p10 != null && p20 != null && p21 != null - // && p10.owner.equals(p11.owner) - // && p11.owner.equals(p20.owner) - // && p20.owner.equals(p21.owner)) { - // fillmiddleroad(p20, p11, world); - // } - // - // if (p01 != null && p02 != null && p12 != null - // && p01.owner.equals(p11.owner) - // && p11.owner.equals(p02.owner) - // && p02.owner.equals(p12.owner)) { - // fillmiddleroad(p02, p11, world); - // } - // - // if (p12 != null && p21 != null && p22 != null - // && p12.owner.equals(p11.owner) - // && p11.owner.equals(p21.owner) - // && p21.owner.equals(p22.owner)) { - // fillmiddleroad(p22, p11, world); - // } - // } - // } - // - // public static void fillroad(plot plot1, plot plot2, World w) { - // Location bottomPlot1, topPlot1, bottomPlot2, topPlot2; - // bottomPlot1 = getPlotBottomLoc(w, plot1.id); - // topPlot1 = getPlotTopLoc(w, plot1.id); - // bottomPlot2 = getPlotBottomLoc(w, plot2.id); - // topPlot2 = getPlotTopLoc(w, plot2.id); - // - // int minX, maxX, minZ, maxZ; - // - // boolean isWallX; - // - // int h = Settings.ROAD_HEIGHT; - // int wallId = Settings.WALL_BLOCK; - // int fillId = Settings.TOP_BLOCK; - // - // if(bottomPlot1.getBlockX() == bottomPlot2.getBlockX()) { - // minX = bottomPlot1.getBlockX(); - // maxX = topPlot1.getBlockX(); - // - // minZ = Math.min(bottomPlot1.getBlockZ(), bottomPlot2.getBlockZ()) + - // Settings.PLOT_WIDTH; - // maxZ = Math.min(topPlot1.getBlockZ(), topPlot2.getBlockZ()) - - // Settings.PLOT_WIDTH; - // } else { - // minZ = bottomPlot1.getBlockZ(); - // maxZ = topPlot1.getBlockZ(); - // - // minX = Math.min(bottomPlot1.getBlockX(), bottomPlot2.getBlockX()) + - // Settings.PLOT_WIDTH; - // maxX = Math.max(topPlot1.getBlockX(), topPlot2.getBlockX()) - - // Settings.PLOT_WIDTH; - // } - // - // isWallX = (maxX - minX) > (maxZ - minZ); - // - // if(isWallX) { - // minX--; - // maxX++; - // } else { - // minZ--; - // maxZ++; - // } - // - // for(int x = minX; x <= maxX; x++) { - // for(int z = minZ; x <= maxZ; z++) { - // for(int y = h; y < h + 3; y++) { - // if(y >= (h + 2)) { - // w.getBlockAt(x,y,z).setType(Material.AIR); - // } else if(y == (h + 1)) { - // if(isWallX && (x == minX || x == maxX)) { - // w.getBlockAt(x,y,z).setTypeIdAndData(wallId, (byte) 0, true); - // } else if(!isWallX && (z == minZ || z == maxZ)) { - // w.getBlockAt(x,y,z).setTypeIdAndData(wallId, (byte) 0, true); - // } else { - // w.getBlockAt(x,y,z).setType(Material.AIR); - // } - // } else { - // w.getBlockAt(x,y,z).setTypeIdAndData(fillId, (byte) 0, true); - // } - // } - // } - // } - // } - // - // public static void fillmiddleroad(plot p1, plot p2, World w) { - // Location b1 = getPlotBottomLoc(w, p1.id); - // Location t1 = getPlotTopLoc(w, p1.id); - // Location b2 = getPlotBottomLoc(w, p2.id); - // Location t2 = getPlotTopLoc(w, p2.id); - // - // int minX, maxX, minZ, maxZ; - // - // int h = Settings.ROAD_HEIGHT; - // int fillID = Settings.TOP_BLOCK; - // - // minX = Math.min(t1.getBlockX(), t2.getBlockX()); - // maxX = Math.max(b1.getBlockX(), b2.getBlockX()); - // - // minZ = Math.min(t1.getBlockZ(), t2.getBlockZ()); - // maxZ = Math.max(b1.getBlockZ(), b2.getBlockZ()); - // - // for(int x = minX; x <= maxX; x++) { - // for(int z = minZ; z <= maxZ; z++) { - // for(int y = h; y < h + 3; y++) { - // if(y >= (h + 1)) { - // w.getBlockAt(x,y,z).setType(Material.AIR); - // } else { - // w.getBlockAt(x,y,z).setTypeId(fillID); - // } - // } - // } - // } - // } + public static double getWorldFolderSize(World world) { + // long size = FileUtil.sizeOfDirectory(world.getWorldFolder()); + File folder = world.getWorldFolder(); + long size = folder.length(); + return (((size) / 1024) / 1024); + } - public static String createId(int x, int z) { - return x + ";" + z; - } + // public static void adjustLinkedPlots(String id) { + // World world = Bukkit.getWorld(Settings.PLOT_WORLD); + // int x = getIdX(id); + // int z = getIdZ(id); + // + // plot p11 = getPlot(id); + // if (p11 != null) { + // plot p01, p10, p12, p21, p00, p02, p20, p22; + // p01 = getPlot(x - 1, z); + // p10 = getPlot(x, z - 1); + // p12 = getPlot(x, z + 1); + // p21 = getPlot(x + 1, z); + // p00 = getPlot(x - 1, z - 1); + // p02 = getPlot(x - 1, z + 1); + // p20 = getPlot(x + 1, z - 1); + // p22 = getPlot(x + 1, z + 1); + // if (p01 != null && p01.owner.equals(p11.owner)) { + // fillroad(p01, p11, world); + // } + // + // if (p10 != null && p10.owner.equals(p11.owner)) { + // fillroad(p10, p11, world); + // } + // + // if (p12 != null && p12.owner.equals(p11.owner)) { + // fillroad(p12, p11, world); + // } + // + // if (p21 != null && p21.owner.equals(p11.owner)) { + // fillroad(p21, p11, world); + // } + // + // if (p00 != null && p10 != null && p01 != null + // && p00.owner.equals(p11.owner) + // && p11.owner.equals(p10.owner) + // && p10.owner.equals(p01.owner)) { + // fillmiddleroad(p00, p11, world); + // } + // + // if (p10 != null && p20 != null && p21 != null + // && p10.owner.equals(p11.owner) + // && p11.owner.equals(p20.owner) + // && p20.owner.equals(p21.owner)) { + // fillmiddleroad(p20, p11, world); + // } + // + // if (p01 != null && p02 != null && p12 != null + // && p01.owner.equals(p11.owner) + // && p11.owner.equals(p02.owner) + // && p02.owner.equals(p12.owner)) { + // fillmiddleroad(p02, p11, world); + // } + // + // if (p12 != null && p21 != null && p22 != null + // && p12.owner.equals(p11.owner) + // && p11.owner.equals(p21.owner) + // && p21.owner.equals(p22.owner)) { + // fillmiddleroad(p22, p11, world); + // } + // } + // } + // + // public static void fillroad(plot plot1, plot plot2, World w) { + // Location bottomPlot1, topPlot1, bottomPlot2, topPlot2; + // bottomPlot1 = getPlotBottomLoc(w, plot1.id); + // topPlot1 = getPlotTopLoc(w, plot1.id); + // bottomPlot2 = getPlotBottomLoc(w, plot2.id); + // topPlot2 = getPlotTopLoc(w, plot2.id); + // + // int minX, maxX, minZ, maxZ; + // + // boolean isWallX; + // + // int h = Settings.ROAD_HEIGHT; + // int wallId = Settings.WALL_BLOCK; + // int fillId = Settings.TOP_BLOCK; + // + // if(bottomPlot1.getBlockX() == bottomPlot2.getBlockX()) { + // minX = bottomPlot1.getBlockX(); + // maxX = topPlot1.getBlockX(); + // + // minZ = Math.min(bottomPlot1.getBlockZ(), bottomPlot2.getBlockZ()) + + // Settings.PLOT_WIDTH; + // maxZ = Math.min(topPlot1.getBlockZ(), topPlot2.getBlockZ()) - + // Settings.PLOT_WIDTH; + // } else { + // minZ = bottomPlot1.getBlockZ(); + // maxZ = topPlot1.getBlockZ(); + // + // minX = Math.min(bottomPlot1.getBlockX(), bottomPlot2.getBlockX()) + + // Settings.PLOT_WIDTH; + // maxX = Math.max(topPlot1.getBlockX(), topPlot2.getBlockX()) - + // Settings.PLOT_WIDTH; + // } + // + // isWallX = (maxX - minX) > (maxZ - minZ); + // + // if(isWallX) { + // minX--; + // maxX++; + // } else { + // minZ--; + // maxZ++; + // } + // + // for(int x = minX; x <= maxX; x++) { + // for(int z = minZ; x <= maxZ; z++) { + // for(int y = h; y < h + 3; y++) { + // if(y >= (h + 2)) { + // w.getBlockAt(x,y,z).setType(Material.AIR); + // } else if(y == (h + 1)) { + // if(isWallX && (x == minX || x == maxX)) { + // w.getBlockAt(x,y,z).setTypeIdAndData(wallId, (byte) 0, true); + // } else if(!isWallX && (z == minZ || z == maxZ)) { + // w.getBlockAt(x,y,z).setTypeIdAndData(wallId, (byte) 0, true); + // } else { + // w.getBlockAt(x,y,z).setType(Material.AIR); + // } + // } else { + // w.getBlockAt(x,y,z).setTypeIdAndData(fillId, (byte) 0, true); + // } + // } + // } + // } + // } + // + // public static void fillmiddleroad(plot p1, plot p2, World w) { + // Location b1 = getPlotBottomLoc(w, p1.id); + // Location t1 = getPlotTopLoc(w, p1.id); + // Location b2 = getPlotBottomLoc(w, p2.id); + // Location t2 = getPlotTopLoc(w, p2.id); + // + // int minX, maxX, minZ, maxZ; + // + // int h = Settings.ROAD_HEIGHT; + // int fillID = Settings.TOP_BLOCK; + // + // minX = Math.min(t1.getBlockX(), t2.getBlockX()); + // maxX = Math.max(b1.getBlockX(), b2.getBlockX()); + // + // minZ = Math.min(t1.getBlockZ(), t2.getBlockZ()); + // maxZ = Math.max(b1.getBlockZ(), b2.getBlockZ()); + // + // for(int x = minX; x <= maxX; x++) { + // for(int z = minZ; z <= maxZ; z++) { + // for(int y = h; y < h + 3; y++) { + // if(y >= (h + 1)) { + // w.getBlockAt(x,y,z).setType(Material.AIR); + // } else { + // w.getBlockAt(x,y,z).setTypeId(fillID); + // } + // } + // } + // } + // } - public static ArrayList runners_p = new ArrayList(); - public static HashMap runners = new HashMap(); + public static String createId(int x, int z) { + return x + ";" + z; + } - public static void adjustWallFilling(final Player requester, final World w, final Plot plot, PlotBlock block) { - if (runners.containsKey(plot)) { - PlayerFunctions.sendMessage(requester, C.WAIT_FOR_TIMER); - return; - } - PlayerFunctions.sendMessage(requester, C.GENERATING_WALL_FILLING); - World world = requester.getWorld(); - PlotManager manager = PlotMain.getPlotManager(world); - PlotWorld plotworld = PlotMain.getWorldSettings(world); - - manager.setWall(requester, plotworld, plot.id, block); - PlayerFunctions.sendMessage(requester, C.SET_BLOCK_ACTION_FINISHED); - } + public static ArrayList runners_p = new ArrayList(); + public static HashMap runners = new HashMap(); - public static void setFloor(final Player requester, final Plot plot, PlotBlock[] blocks) { - if (runners.containsKey(plot)) { - PlayerFunctions.sendMessage(requester, C.WAIT_FOR_TIMER); - return; - } - - PlayerFunctions.sendMessage(requester, C.GENERATING_FLOOR); - World world = requester.getWorld(); - PlotManager manager = PlotMain.getPlotManager(world); - PlotWorld plotworld = PlotMain.getWorldSettings(world); - PlayerFunctions.sendMessage(requester, C.SET_BLOCK_ACTION_FINISHED); - manager.setFloor(requester, plotworld, plot.id, blocks); - } + public static void adjustWallFilling(final Player requester, + final Plot plot, PlotBlock block) { + if (runners.containsKey(plot)) { + PlayerFunctions.sendMessage(requester, C.WAIT_FOR_TIMER); + return; + } + PlayerFunctions.sendMessage(requester, C.GENERATING_WALL_FILLING); + World world = requester.getWorld(); + PlotManager manager = PlotMain.getPlotManager(world); + PlotWorld plotworld = PlotMain.getWorldSettings(world); - public static int square(int x) { - return x * x; - } + manager.setWall(requester, plotworld, plot.id, block); + PlayerFunctions.sendMessage(requester, C.SET_BLOCK_ACTION_FINISHED); + } - public static short[] getBlock(String block) { - if (block.contains(":")) { - String[] split = block.split(":"); - return new short[] { Short.parseShort(split[0]), Short.parseShort(split[1]) }; - } - return new short[] { Short.parseShort(block), 0 }; - } + public static void setFloor(final Player requester, final Plot plot, + PlotBlock[] blocks) { + if (runners.containsKey(plot)) { + PlayerFunctions.sendMessage(requester, C.WAIT_FOR_TIMER); + return; + } - public static void clearAllEntities(World world, Plot plot, boolean tile) { - final Location pos1 = getPlotBottomLoc(world, plot.id).add(1, 0, 1); - final Location pos2 = getPlotTopLoc(world, plot.id); - for (int i = (pos1.getBlockX() / 16) * 16; i < (16 + ((pos2.getBlockX() / 16) * 16)); i += 16) { - for (int j = (pos1.getBlockZ() / 16) * 16; j < (16 + ((pos2.getBlockZ() / 16) * 16)); j += 16) { - Chunk chunk = world.getChunkAt(i, j); - for (Entity entity : chunk.getEntities()) { - PlotId id = PlayerFunctions.getPlot(entity.getLocation()); - if ((id != null) && id.equals(plot.id)) { - if (entity instanceof Player) { - PlotMain.teleportPlayer((Player) entity, entity.getLocation(), plot); - } else { - entity.remove(); - } - } - } - if (tile) { - for (BlockState entity : chunk.getTileEntities()) { - entity.setRawData((byte) 0); - } - } - } - } - } + PlayerFunctions.sendMessage(requester, C.GENERATING_FLOOR); + World world = requester.getWorld(); + PlotManager manager = PlotMain.getPlotManager(world); + PlotWorld plotworld = PlotMain.getWorldSettings(world); + PlayerFunctions.sendMessage(requester, C.SET_BLOCK_ACTION_FINISHED); + manager.setFloor(requester, plotworld, plot.id, blocks); + } - /** - * Clear a plot - * - * @param requester - * @param plot - */ - public static void clear(final Player requester, final Plot plot) { + public static int square(int x) { + return x * x; + } - if (runners.containsKey(plot)) { - PlayerFunctions.sendMessage(requester, C.WAIT_FOR_TIMER); - return; - } - - final long start = System.nanoTime(); - final World world = requester.getWorld(); + public static short[] getBlock(String block) { + if (block.contains(":")) { + String[] split = block.split(":"); + return new short[] { Short.parseShort(split[0]), + Short.parseShort(split[1]) }; + } + return new short[] { Short.parseShort(block), 0 }; + } - /* - * keep - */ - clearAllEntities(world, plot, false); - PlotManager manager = PlotMain.getPlotManager(world); - - Location pos1 = PlotHelper.getPlotBottomLoc(world, plot.id).add(1, 0, 1); - - final int prime = 31; - int h = 1; - h = (prime * h) + pos1.getBlockX(); - h = (prime * h) + pos1.getBlockZ(); - state = h; - - PlotHelper.setBiome(requester.getWorld(), plot, Biome.FOREST); - PlayerFunctions.sendMessage(requester, C.CLEARING_PLOT); + public static void clearAllEntities(World world, Plot plot, boolean tile) { + final Location pos1 = getPlotBottomLoc(world, plot.id).add(1, 0, 1); + final Location pos2 = getPlotTopLoc(world, plot.id); + for (int i = (pos1.getBlockX() / 16) * 16; i < (16 + ((pos2.getBlockX() / 16) * 16)); i += 16) { + for (int j = (pos1.getBlockZ() / 16) * 16; j < (16 + ((pos2 + .getBlockZ() / 16) * 16)); j += 16) { + Chunk chunk = world.getChunkAt(i, j); + for (Entity entity : chunk.getEntities()) { + PlotId id = PlayerFunctions.getPlot(entity.getLocation()); + if ((id != null) && id.equals(plot.id)) { + if (entity instanceof Player) { + PlotMain.teleportPlayer((Player) entity, + entity.getLocation(), plot); + } else { + entity.remove(); + } + } + } + if (tile) { + for (BlockState entity : chunk.getTileEntities()) { + entity.setRawData((byte) 0); + } + } + } + } + } - manager.clearPlot(requester, plot); - - removeSign(requester, plot); - setSign(requester, plot); - - PlayerFunctions.sendMessage(requester, C.CLEARING_DONE.s().replaceAll("%time%", "" + ((System.nanoTime() - start) / 1000000.0))); - if (canSetFast) { - refreshPlotChunks(world, plot); -// SetBlockFast.update(requester); - } - return; - } + /** + * Clear a plot + * + * @param requester + * @param plot + */ + public static void clear(final Player requester, final Plot plot) { - public static void setCuboid(World world, Location pos1, Location pos2, PlotBlock[] blocks) { - if (!canSetFast) { - for (int y = pos1.getBlockY(); y < pos2.getBlockY(); y++) { - for (int x = pos1.getBlockX(); x < pos2.getBlockX(); x++) { - for (int z = pos1.getBlockZ(); z < pos2.getBlockZ(); z++) { - int i = random(blocks.length); - PlotBlock newblock = blocks[i]; - Block block = world.getBlockAt(x, y, z); - if (!((block.getTypeId() == newblock.id) && (block.getData() == newblock.data))) { - block.setTypeIdAndData(newblock.id, newblock.data, false); - } - } - } - } - } else { - try { - for (int y = pos1.getBlockY(); y < pos2.getBlockY(); y++) { - for (int x = pos1.getBlockX(); x < pos2.getBlockX(); x++) { - for (int z = pos1.getBlockZ(); z < pos2.getBlockZ(); z++) { - int i = random(blocks.length); - PlotBlock newblock = blocks[i]; - Block block = world.getBlockAt(x, y, z); - if (!((block.getTypeId() == newblock.id) && (block.getData() == newblock.data))) { - SetBlockFast.set(world, x, y, z, newblock.id, newblock.data); - } - } - } - } - } catch (Exception e) { - } - } - } + if (runners.containsKey(plot)) { + PlayerFunctions.sendMessage(requester, C.WAIT_FOR_TIMER); + return; + } - public static void setSimpleCuboid(World world, Location pos1, Location pos2, PlotBlock newblock) { - if (!canSetFast) { - for (int y = pos1.getBlockY(); y < pos2.getBlockY(); y++) { - for (int x = pos1.getBlockX(); x < pos2.getBlockX(); x++) { - for (int z = pos1.getBlockZ(); z < pos2.getBlockZ(); z++) { - Block block = world.getBlockAt(x, y, z); - if (!((block.getTypeId() == newblock.id))) { - block.setTypeId(newblock.id, false); - } - } - } - } - } else { - try { - for (int y = pos1.getBlockY(); y < pos2.getBlockY(); y++) { - for (int x = pos1.getBlockX(); x < pos2.getBlockX(); x++) { - for (int z = pos1.getBlockZ(); z < pos2.getBlockZ(); z++) { - Block block = world.getBlockAt(x, y, z); - if (!((block.getTypeId() == newblock.id))) { - SetBlockFast.set(world, x, y, z, newblock.id, (byte) 0); - } - } - } - } - } catch (Exception e) { + final long start = System.nanoTime(); + final World world = requester.getWorld(); - } - } - } + /* + * keep + */ + clearAllEntities(world, plot, false); + PlotManager manager = PlotMain.getPlotManager(world); - public static void setBiome(World world, Plot plot, Biome b) { - int bottomX = getPlotBottomLoc(world, plot.id).getBlockX() - 1; - int topX = getPlotTopLoc(world, plot.id).getBlockX() + 1; - int bottomZ = getPlotBottomLoc(world, plot.id).getBlockZ() - 1; - int topZ = getPlotTopLoc(world, plot.id).getBlockZ() + 1; + Location pos1 = PlotHelper.getPlotBottomLoc(world, plot.id) + .add(1, 0, 1); - for (int x = bottomX; x <= topX; x++) { - for (int z = bottomZ; z <= topZ; z++) { - world.getBlockAt(x, 0, z).setBiome(b); - } - } + final int prime = 31; + int h = 1; + h = (prime * h) + pos1.getBlockX(); + h = (prime * h) + pos1.getBlockZ(); + state = h; - plot.settings.setBiome(b); - PlotMain.updatePlot(plot); - refreshPlotChunks(world, plot); - } + PlotHelper.setBiome(requester.getWorld(), plot, Biome.FOREST); + PlayerFunctions.sendMessage(requester, C.CLEARING_PLOT); - public static Location getPlotHome(World w, PlotId plotid) { - PlotMain.getWorldSettings(w); - if (getPlot(w, plotid).settings.getPosition() == PlotHomePosition.DEFAULT) { - int x = getPlotBottomLoc(w, plotid).getBlockX() + (getPlotTopLoc(w, plotid).getBlockX() - getPlotBottomLoc(w, plotid).getBlockX()); - int z = getPlotBottomLoc(w, plotid).getBlockZ() - 2; - int y = w.getHighestBlockYAt(x, z); - return new Location(w, x, y + 2, z); - } else { - World world = w; - - Location bot, top; - bot = getPlotBottomLoc(world, plotid); - top = getPlotTopLoc(world, plotid); - - int x = top.getBlockX()-bot.getBlockX(); - int z = top.getBlockZ()-bot.getBlockZ(); - int y = w.getHighestBlockYAt(x, z); - return new Location(w, x, y + 2, z); - } - } + manager.clearPlot(requester, plot); - public static Location getPlotHome(World w, Plot plot) { - return getPlotBottomLoc(w, plot.id); - } + removeSign(requester, plot); + setSign(requester, plot); - public static void refreshPlotChunks(World world, Plot plot) { - int bottomX = getPlotBottomLoc(world, plot.id).getBlockX(); - int topX = getPlotTopLoc(world, plot.id).getBlockX(); - int bottomZ = getPlotBottomLoc(world, plot.id).getBlockZ(); - int topZ = getPlotTopLoc(world, plot.id).getBlockZ(); + PlayerFunctions.sendMessage( + requester, + C.CLEARING_DONE.s().replaceAll("%time%", + "" + ((System.nanoTime() - start) / 1000000.0))); + if (canSetFast) { + refreshPlotChunks(world, plot); + // SetBlockFast.update(requester); + } + return; + } - int minChunkX = (int) Math.floor((double) bottomX / 16); - int maxChunkX = (int) Math.floor((double) topX / 16); - int minChunkZ = (int) Math.floor((double) bottomZ / 16); - int maxChunkZ = (int) Math.floor((double) topZ / 16); + public static void setCuboid(World world, Location pos1, Location pos2, + PlotBlock[] blocks) { + if (!canSetFast) { + for (int y = pos1.getBlockY(); y < pos2.getBlockY(); y++) { + for (int x = pos1.getBlockX(); x < pos2.getBlockX(); x++) { + for (int z = pos1.getBlockZ(); z < pos2.getBlockZ(); z++) { + int i = random(blocks.length); + PlotBlock newblock = blocks[i]; + Block block = world.getBlockAt(x, y, z); + if (!((block.getTypeId() == newblock.id) && (block + .getData() == newblock.data))) { + block.setTypeIdAndData(newblock.id, newblock.data, + false); + } + } + } + } + } else { + try { + for (int y = pos1.getBlockY(); y < pos2.getBlockY(); y++) { + for (int x = pos1.getBlockX(); x < pos2.getBlockX(); x++) { + for (int z = pos1.getBlockZ(); z < pos2.getBlockZ(); z++) { + int i = random(blocks.length); + PlotBlock newblock = blocks[i]; + Block block = world.getBlockAt(x, y, z); + if (!((block.getTypeId() == newblock.id) && (block + .getData() == newblock.data))) { + SetBlockFast.set(world, x, y, z, newblock.id, + newblock.data); + } + } + } + } + } catch (Exception e) { + } + } + } - for (int x = minChunkX; x <= maxChunkX; x++) { - for (int z = minChunkZ; z <= maxChunkZ; z++) { - world.refreshChunk(x, z); - } - } - } + public static void setSimpleCuboid(World world, Location pos1, + Location pos2, PlotBlock newblock) { + if (!canSetFast) { + for (int y = pos1.getBlockY(); y < pos2.getBlockY(); y++) { + for (int x = pos1.getBlockX(); x < pos2.getBlockX(); x++) { + for (int z = pos1.getBlockZ(); z < pos2.getBlockZ(); z++) { + Block block = world.getBlockAt(x, y, z); + if (!((block.getTypeId() == newblock.id))) { + block.setTypeId(newblock.id, false); + } + } + } + } + } else { + try { + for (int y = pos1.getBlockY(); y < pos2.getBlockY(); y++) { + for (int x = pos1.getBlockX(); x < pos2.getBlockX(); x++) { + for (int z = pos1.getBlockZ(); z < pos2.getBlockZ(); z++) { + Block block = world.getBlockAt(x, y, z); + if (!((block.getTypeId() == newblock.id))) { + SetBlockFast.set(world, x, y, z, newblock.id, + (byte) 0); + } + } + } + } + } catch (Exception e) { - public static Location getPlotTopLocAbs(World world, PlotId id) { - PlotWorld plotworld = PlotMain.getWorldSettings(world); - PlotManager manager = PlotMain.getPlotManager(world); - return manager.getPlotTopLocAbs(plotworld, id); - } + } + } + } - public static Location getPlotBottomLocAbs(World world, PlotId id) { - PlotWorld plotworld = PlotMain.getWorldSettings(world); - PlotManager manager = PlotMain.getPlotManager(world); - return manager.getPlotBottomLocAbs(plotworld, id); - } + public static void setBiome(World world, Plot plot, Biome b) { + int bottomX = getPlotBottomLoc(world, plot.id).getBlockX() - 1; + int topX = getPlotTopLoc(world, plot.id).getBlockX() + 1; + int bottomZ = getPlotBottomLoc(world, plot.id).getBlockZ() - 1; + int topZ = getPlotTopLoc(world, plot.id).getBlockZ() + 1; - public static Location getPlotTopLoc(World world, PlotId id) { - Plot plot = PlotMain.getPlots(world).get(id); - if (plot != null) { - id = PlayerFunctions.getTopPlot(world, plot).id; - } - PlotWorld plotworld = PlotMain.getWorldSettings(world); - PlotManager manager = PlotMain.getPlotManager(world); - return manager.getPlotTopLocAbs(plotworld, id); - } + for (int x = bottomX; x <= topX; x++) { + for (int z = bottomZ; z <= topZ; z++) { + world.getBlockAt(x, 0, z).setBiome(b); + } + } - public static Location getPlotBottomLoc(World world, PlotId id) { - Plot plot = PlotMain.getPlots(world).get(id); - if (plot != null) { - id = PlayerFunctions.getBottomPlot(world, plot).id; - } - PlotWorld plotworld = PlotMain.getWorldSettings(world); - PlotManager manager = PlotMain.getPlotManager(world); - return manager.getPlotBottomLocAbs(plotworld, id); - } + plot.settings.setBiome(b); + PlotMain.updatePlot(plot); + refreshPlotChunks(world, plot); + } - public static Plot getPlot(World world, PlotId id) { - if (id == null) { - return null; - } - if (PlotMain.getPlots(world).containsKey(id)) { - return PlotMain.getPlots(world).get(id); - } - return new Plot(id, null, Biome.FOREST, new ArrayList(), new ArrayList(), world.getName()); - } + public static Location getPlotHome(World w, PlotId plotid) { + PlotMain.getWorldSettings(w); + if (getPlot(w, plotid).settings.getPosition() == PlotHomePosition.DEFAULT) { + int x = getPlotBottomLoc(w, plotid).getBlockX() + + (getPlotTopLoc(w, plotid).getBlockX() - getPlotBottomLoc( + w, plotid).getBlockX()); + int z = getPlotBottomLoc(w, plotid).getBlockZ() - 2; + int y = w.getHighestBlockYAt(x, z); + return new Location(w, x, y + 2, z); + } else { + World world = w; - public static Plot getCurrentPlot(Location loc) { - PlotId id = PlayerFunctions.getPlot(loc); - if (id == null) { - return null; - } - if (PlotMain.getPlots(loc.getWorld()).containsKey(id)) { - return PlotMain.getPlots(loc.getWorld()).get(id); - } - return new Plot(id, null, Biome.FOREST, new ArrayList(), new ArrayList(), loc.getWorld().getName()); - } + Location bot, top; + bot = getPlotBottomLoc(world, plotid); + top = getPlotTopLoc(world, plotid); + + int x = top.getBlockX() - bot.getBlockX(); + int z = top.getBlockZ() - bot.getBlockZ(); + int y = w.getHighestBlockYAt(x, z); + return new Location(w, x, y + 2, z); + } + } + + public static Location getPlotHome(World w, Plot plot) { + return getPlotBottomLoc(w, plot.id); + } + + public static void refreshPlotChunks(World world, Plot plot) { + int bottomX = getPlotBottomLoc(world, plot.id).getBlockX(); + int topX = getPlotTopLoc(world, plot.id).getBlockX(); + int bottomZ = getPlotBottomLoc(world, plot.id).getBlockZ(); + int topZ = getPlotTopLoc(world, plot.id).getBlockZ(); + + int minChunkX = (int) Math.floor((double) bottomX / 16); + int maxChunkX = (int) Math.floor((double) topX / 16); + int minChunkZ = (int) Math.floor((double) bottomZ / 16); + int maxChunkZ = (int) Math.floor((double) topZ / 16); + + for (int x = minChunkX; x <= maxChunkX; x++) { + for (int z = minChunkZ; z <= maxChunkZ; z++) { + world.refreshChunk(x, z); + } + } + } + + public static Location getPlotTopLocAbs(World world, PlotId id) { + PlotWorld plotworld = PlotMain.getWorldSettings(world); + PlotManager manager = PlotMain.getPlotManager(world); + return manager.getPlotTopLocAbs(plotworld, id); + } + + public static Location getPlotBottomLocAbs(World world, PlotId id) { + PlotWorld plotworld = PlotMain.getWorldSettings(world); + PlotManager manager = PlotMain.getPlotManager(world); + return manager.getPlotBottomLocAbs(plotworld, id); + } + + public static int getPlotWidth(World world, PlotId id) { + return getPlotTopLoc(world, id).getBlockX() + - getPlotBottomLoc(world, id).getBlockX(); + } + + public static Location getPlotTopLoc(World world, PlotId id) { + Plot plot = PlotMain.getPlots(world).get(id); + if (plot != null) { + id = PlayerFunctions.getTopPlot(world, plot).id; + } + PlotWorld plotworld = PlotMain.getWorldSettings(world); + PlotManager manager = PlotMain.getPlotManager(world); + return manager.getPlotTopLocAbs(plotworld, id); + } + + public static Location getPlotBottomLoc(World world, PlotId id) { + Plot plot = PlotMain.getPlots(world).get(id); + if (plot != null) { + id = PlayerFunctions.getBottomPlot(world, plot).id; + } + PlotWorld plotworld = PlotMain.getWorldSettings(world); + PlotManager manager = PlotMain.getPlotManager(world); + return manager.getPlotBottomLocAbs(plotworld, id); + } + + public static Plot getPlot(World world, PlotId id) { + if (id == null) { + return null; + } + if (PlotMain.getPlots(world).containsKey(id)) { + return PlotMain.getPlots(world).get(id); + } + return new Plot(id, null, Biome.FOREST, new ArrayList(), + new ArrayList(), world.getName()); + } + + public static Plot getCurrentPlot(Location loc) { + PlotId id = PlayerFunctions.getPlot(loc); + if (id == null) { + return null; + } + if (PlotMain.getPlots(loc.getWorld()).containsKey(id)) { + return PlotMain.getPlots(loc.getWorld()).get(id); + } + return new Plot(id, null, Biome.FOREST, new ArrayList(), + new ArrayList(), loc.getWorld().getName()); + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/PlotHomePosition.java b/PlotSquared/src/com/intellectualcrafters/plot/PlotHomePosition.java index 2474232c7..b72e29c6f 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/PlotHomePosition.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/PlotHomePosition.java @@ -13,24 +13,24 @@ package com.intellectualcrafters.plot; * Created by Citymonstret on 2014-08-05. */ public enum PlotHomePosition { - CENTER("Center", 'c'), DEFAULT("Default", 'd'); + CENTER("Center", 'c'), DEFAULT("Default", 'd'); - private String string; - private char ch; + private String string; + private char ch; - PlotHomePosition(String string, char ch) { - this.string = string; - this.ch = ch; - } + PlotHomePosition(String string, char ch) { + this.string = string; + this.ch = ch; + } - public boolean isMatching(String string) { - if ((string.length() < 2) && (string.charAt(0) == this.ch)) { - return true; - } - if (string.equalsIgnoreCase(this.string)) { - return true; - } - return false; - } + public boolean isMatching(String string) { + if ((string.length() < 2) && (string.charAt(0) == this.ch)) { + return true; + } + if (string.equalsIgnoreCase(this.string)) { + return true; + } + return false; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/PlotId.java b/PlotSquared/src/com/intellectualcrafters/plot/PlotId.java index 744a426e2..2d86fdcc2 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/PlotId.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/PlotId.java @@ -1,54 +1,54 @@ package com.intellectualcrafters.plot; public class PlotId { - /** - * x value - */ - public Integer x; - /** - * y value - */ - public Integer y; + /** + * x value + */ + public Integer x; + /** + * y value + */ + public Integer y; - /** - * PlotId class (PlotId x,y values do not correspond to Block locations) - * - * @param x - * The plot x coordinate - * @param y - * The plot y coordinate - */ - public PlotId(int x, int y) { - this.x = x; - this.y = y; - } + /** + * PlotId class (PlotId x,y values do not correspond to Block locations) + * + * @param x + * The plot x coordinate + * @param y + * The plot y coordinate + */ + public PlotId(int x, int y) { + this.x = x; + this.y = y; + } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - PlotId other = (PlotId) obj; - return ((this.x == other.x) && (this.y == other.y)); - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + PlotId other = (PlotId) obj; + return ((this.x == other.x) && (this.y == other.y)); + } - @Override - public String toString() { - return this.x + ";" + this.y; - } + @Override + public String toString() { + return this.x + ";" + this.y; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = (prime * result) + this.x; - result = (prime * result) + this.y; - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + this.x; + result = (prime * result) + this.y; + return result; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/PlotMain.java b/PlotSquared/src/com/intellectualcrafters/plot/PlotMain.java index 3245c05f6..f128dfa8e 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/PlotMain.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/PlotMain.java @@ -67,1091 +67,1184 @@ import com.sk89q.worldguard.bukkit.WorldGuardPlugin; */ public class PlotMain extends JavaPlugin { - /** - * settings.properties - */ - public static File configFile; - public static YamlConfiguration config; - private static int config_ver = 1; - /** - * storage.properties - */ - public static File storageFile; - public static YamlConfiguration storage; - public static int storage_ver = 1; - /** - * translations.properties - */ - public static File translationsFile; - public static YamlConfiguration translations; - public static int translations_ver = 1; - /** - * MySQL Object - */ - private static MySQL mySQL; - /** - * MySQL Connection - */ - public static Connection connection; - /** - * WorldEdit object - */ - public static WorldEditPlugin worldEdit = null; - /** - * BarAPI object - */ - public static BarAPI barAPI = null; - /** - * CameraAPI object - */ - public static CameraAPI cameraAPI; + /** + * settings.properties + */ + public static File configFile; + public static YamlConfiguration config; + private static int config_ver = 1; + /** + * storage.properties + */ + public static File storageFile; + public static YamlConfiguration storage; + public static int storage_ver = 1; + /** + * translations.properties + */ + public static File translationsFile; + public static YamlConfiguration translations; + public static int translations_ver = 1; + /** + * MySQL Object + */ + private static MySQL mySQL; + /** + * MySQL Connection + */ + public static Connection connection; + /** + * WorldEdit object + */ + public static WorldEditPlugin worldEdit = null; + /** + * BarAPI object + */ + public static BarAPI barAPI = null; + /** + * CameraAPI object + */ + public static CameraAPI cameraAPI; - public static WorldGuardPlugin worldGuard = null; - public static WorldGuardListener worldGuardListener = null; + public static WorldGuardPlugin worldGuard = null; + public static WorldGuardListener worldGuardListener = null; - public static Economy economy; - public static boolean useEconomy; + public static Economy economy; + public static boolean useEconomy; - /** - * !!WorldGeneration!! - */ - @Override - public ChunkGenerator getDefaultWorldGenerator(String worldname, String id) { - return new WorldGenerator(worldname); - } + /** + * !!WorldGeneration!! + */ + @Override + public ChunkGenerator getDefaultWorldGenerator(String worldname, String id) { + return new WorldGenerator(worldname); + } - @SuppressWarnings("deprecation") - public static void checkForExpiredPlots() { - final JavaPlugin plugin = PlotMain.getMain(); - Bukkit.getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable() { - @Override - public void run() { - checkExpired(plugin, true); - } - }, 0l, 12 * 60 * 60 * 20l); - } + @SuppressWarnings("deprecation") + public static void checkForExpiredPlots() { + final JavaPlugin plugin = PlotMain.getMain(); + Bukkit.getScheduler().scheduleAsyncRepeatingTask(plugin, + new Runnable() { + @Override + public void run() { + checkExpired(plugin, true); + } + }, 0l, 12 * 60 * 60 * 20l); + } - /** - * Check a range of permissions e.g. 'plots.plot.<0-100>'
- * Returns highest integer in range. - * - * @param player - * @param stub - * @param range - * @return - */ - public static int hasPermissionRange(Player player, String stub, int range) { - if (player.isOp()) { - return range; - } - if (player.hasPermission(stub + ".*")) { - return range; - } - for (int i = range; i > 0; i--) { - if (player.hasPermission(stub + "." + i)) { - return i; - } - } - return 0; - } + /** + * Check a range of permissions e.g. 'plots.plot.<0-100>'
+ * Returns highest integer in range. + * + * @param player + * @param stub + * @param range + * @return + */ + public static int hasPermissionRange(Player player, String stub, int range) { + if (player.isOp()) { + return range; + } + if (player.hasPermission(stub + ".*")) { + return range; + } + for (int i = range; i > 0; i--) { + if (player.hasPermission(stub + "." + i)) { + return i; + } + } + return 0; + } - /** - * Check a player for a permission
- * - Op has all permissions
- * - checks for '*' nodes - * - * @param player - * @param perm - * @return - */ - public static boolean hasPermissions(Player player, String[] perms) { - if (player.isOp()) { - return true; - } - for (String perm : perms) { - boolean hasperm = false; - if (player.hasPermission(perm)) { - hasperm = true; - } else { - String[] nodes = perm.split("\\."); - StringBuilder n = new StringBuilder(); - for (int i = 0; i < (nodes.length - 1); i++) { - n.append(nodes[i] + "."); - if (player.hasPermission(n + "*")) { - hasperm = true; - break; - } - } - } - if (!hasperm) { - return false; - } - } + /** + * Check a player for a permission
+ * - Op has all permissions
+ * - checks for '*' nodes + * + * @param player + * @param perm + * @return + */ + public static boolean hasPermissions(Player player, String[] perms) { + if (player.isOp()) { + return true; + } + for (String perm : perms) { + boolean hasperm = false; + if (player.hasPermission(perm)) { + hasperm = true; + } else { + String[] nodes = perm.split("\\."); + StringBuilder n = new StringBuilder(); + for (int i = 0; i < (nodes.length - 1); i++) { + n.append(nodes[i] + "."); + if (player.hasPermission(n + "*")) { + hasperm = true; + break; + } + } + } + if (!hasperm) { + return false; + } + } - return true; - } + return true; + } - /** - * Check a player for a permission
- * - Op has all permissions
- * - checks for '*' nodes - * - * @param player - * @param perm - * @return - */ - public static boolean hasPermission(Player player, String perm) { - if (player.isOp()) { - return true; - } - if (player.hasPermission(perm)) { - return true; - } - String[] nodes = perm.split("\\."); - StringBuilder n = new StringBuilder(); - for (int i = 0; i < (nodes.length - 1); i++) { - n.append(nodes[i] + "."); - if (player.hasPermission(n + "*")) { - return true; - } - } + /** + * Check a player for a permission
+ * - Op has all permissions
+ * - checks for '*' nodes + * + * @param player + * @param perm + * @return + */ + public static boolean hasPermission(Player player, String perm) { + if (player.isOp()) { + return true; + } + if (player.hasPermission(perm)) { + return true; + } + String[] nodes = perm.split("\\."); + StringBuilder n = new StringBuilder(); + for (int i = 0; i < (nodes.length - 1); i++) { + n.append(nodes[i] + "."); + if (player.hasPermission(n + "*")) { + return true; + } + } - return false; - } + return false; + } - /** - * All loaded plots - */ - private static HashMap> plots; - /** - * All loaded plot worlds - */ - private static HashMap worlds = new HashMap(); - private static HashMap managers = new HashMap(); + /** + * All loaded plots + */ + private static HashMap> plots; + /** + * All loaded plot worlds + */ + private static HashMap worlds = new HashMap(); + private static HashMap managers = new HashMap(); - /** - * Get all plots - * - * @return HashMap containing the plot ID and the plot object. - */ - public static Set getPlots() { - ArrayList myplots = new ArrayList(); - for (HashMap world : plots.values()) { - myplots.addAll(world.values()); - } - return new HashSet(myplots); - } + /** + * Get all plots + * + * @return HashMap containing the plot ID and the plot object. + */ + public static Set getPlots() { + ArrayList myplots = new ArrayList(); + for (HashMap world : plots.values()) { + myplots.addAll(world.values()); + } + return new HashSet(myplots); + } - /** - * - * @param player - * @return - */ - public static Set getPlots(Player player) { - UUID uuid = player.getUniqueId(); - ArrayList myplots = new ArrayList(); - for (HashMap world : plots.values()) { - for (Plot plot : world.values()) { - if (plot.hasOwner()) { - if (plot.getOwner().equals(uuid)) { - myplots.add(plot); - } - } - } - } - return new HashSet(myplots); - } + /** + * + * @param player + * @return + */ + public static Set getPlots(Player player) { + UUID uuid = player.getUniqueId(); + ArrayList myplots = new ArrayList(); + for (HashMap world : plots.values()) { + for (Plot plot : world.values()) { + if (plot.hasOwner()) { + if (plot.getOwner().equals(uuid)) { + myplots.add(plot); + } + } + } + } + return new HashSet(myplots); + } - /** - * - * @param world - * @param player - * @return - */ - public static Set getPlots(World world, Player player) { - int i = 0; - UUID uuid = player.getUniqueId(); - ArrayList myplots = new ArrayList(); - for (Plot plot : getPlots(world).values()) { - if (plot.hasOwner()) { - if (plot.getOwner().equals(uuid)) { - myplots.add(plot); - } - } - } - return new HashSet(myplots); - } + /** + * + * @param world + * @param player + * @return + */ + public static Set getPlots(World world, Player player) { + UUID uuid = player.getUniqueId(); + ArrayList myplots = new ArrayList(); + for (Plot plot : getPlots(world).values()) { + if (plot.hasOwner()) { + if (plot.getOwner().equals(uuid)) { + myplots.add(plot); + } + } + } + return new HashSet(myplots); + } - /** - * - * @param world - * @return - */ - public static HashMap getPlots(World world) { - if (plots.containsKey(world.getName())) { - return plots.get(world.getName()); - } - return new HashMap(); - } + /** + * + * @param world + * @return + */ + public static HashMap getPlots(World world) { + if (plots.containsKey(world.getName())) { + return plots.get(world.getName()); + } + return new HashMap(); + } - /** - * get all plot worlds - */ - public static String[] getPlotWorlds() { - return (worlds.keySet().toArray(new String[0])); - } + /** + * get all plot worlds + */ + public static String[] getPlotWorlds() { + return (worlds.keySet().toArray(new String[0])); + } - /** - * - * @return - */ - public static String[] getPlotWorldsString() { - return plots.keySet().toArray(new String[0]); - } + /** + * + * @return + */ + public static String[] getPlotWorldsString() { + return plots.keySet().toArray(new String[0]); + } - /** - * - * @param world - * @return - */ - public static boolean isPlotWorld(World world) { - return (worlds.containsKey(world.getName())); - } + /** + * + * @param world + * @return + */ + public static boolean isPlotWorld(World world) { + return (worlds.containsKey(world.getName())); + } - /** - * - * @param world - * @return - */ - public static PlotManager getPlotManager(World world) { - if (managers.containsKey(world.getName())) { - return managers.get(world.getName()); - } - return null; - } + /** + * + * @param world + * @return + */ + public static PlotManager getPlotManager(World world) { + if (managers.containsKey(world.getName())) { + return managers.get(world.getName()); + } + return null; + } - /** - * - * @param world - * @return - */ - public static PlotManager getPlotManager(String world) { - if (managers.containsKey(world)) { - return managers.get(world); - } - return null; - } - - /** - * - * @param world - * @return - */ - public static PlotWorld getWorldSettings(World world) { - if (worlds.containsKey(world.getName())) { - return worlds.get(world.getName()); - } - return null; - } + /** + * + * @param world + * @return + */ + public static PlotManager getPlotManager(String world) { + if (managers.containsKey(world)) { + return managers.get(world); + } + return null; + } - /** - * - * @param world - * @return - */ - public static PlotWorld getWorldSettings(String world) { - if (worlds.containsKey(world)) { - return worlds.get(world); - } - return null; - } + /** + * + * @param world + * @return + */ + public static PlotWorld getWorldSettings(World world) { + if (worlds.containsKey(world.getName())) { + return worlds.get(world.getName()); + } + return null; + } - /** - * - * @param world - * @return set containing the plots for a world - */ - public static Plot[] getWorldPlots(World world) { - return (plots.get(world.getName()).values().toArray(new Plot[0])); - } + /** + * + * @param world + * @return + */ + public static PlotWorld getWorldSettings(String world) { + if (worlds.containsKey(world)) { + return worlds.get(world); + } + return null; + } - public static boolean removePlot(String world, PlotId id, boolean callEvent) { - if (callEvent) { - PlotDeleteEvent event = new PlotDeleteEvent(world, id); - Bukkit.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) { - event.setCancelled(true); - return false; - } - } - plots.get(world).remove(id); - return true; - } + /** + * + * @param world + * @return set containing the plots for a world + */ + public static Plot[] getWorldPlots(World world) { + return (plots.get(world.getName()).values().toArray(new Plot[0])); + } - /** - * Replace the plot object with an updated version - * - * @param plot - * plot object - */ - public static void updatePlot(Plot plot) { - String world = plot.world; - if (!plots.containsKey(world)) { - plots.put(world, new HashMap()); - } - plot.hasChanged = true; - plots.get(world).put(plot.id, plot); - } + public static boolean removePlot(String world, PlotId id, boolean callEvent) { + if (callEvent) { + PlotDeleteEvent event = new PlotDeleteEvent(world, id); + Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + event.setCancelled(true); + return false; + } + } + plots.get(world).remove(id); + return true; + } - /** - * TODO: Implement better system - * The whole point of this system is to recycle old plots So why not just allow users to claim old plots, and try - * to hide the fact that the are owned. Reduce amount of expired plots: - On - * /plot auto - allow claiming of old plot, clear it so the user doesn't - * know - On /plot info, - show that the plot is expired and allowed to be - * claimed - * - * Have the task run less often: - Run the task when there are very little, - * or no players online (great for small servers) - Run the task at startup - * (also only useful for small servers) - * - * Also, in terms of faster code: - Have an array of plots, sorted by expiry - * time. - Add new plots to the end. - The task then only needs to go - * through the first few plots - * - * @param plugin - * Plugin - * @param async - * Call async? - */ - private static void checkExpired(JavaPlugin plugin, boolean async) { - if (async) { - Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { - @Override - public void run() { - for (String world : getPlotWorldsString()) { - if (plots.containsKey(world)) { - for (Plot plot : plots.get(world).values()) { - if (plot.owner == null) { - continue; - } - long lastPlayed = getLastPlayed(plot.owner); - if (lastPlayed == 0) { - continue; - } - int days = (int) (lastPlayed / (1000 * 60 * 60 * 24)); - if (days >= Settings.AUTO_CLEAR_DAYS) { - PlotDeleteEvent event = new PlotDeleteEvent(world, plot.id); - Bukkit.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) { - event.setCancelled(true); - } else { - DBFunc.delete(world, plot); - } - } - } - } - } - } - }); - } else { - for (String world : getPlotWorldsString()) { - if (PlotMain.plots.containsKey(world)) { - for (Plot plot : PlotMain.plots.get(world).values()) { - if (PlayerFunctions.hasExpired(plot)) { - PlotDeleteEvent event = new PlotDeleteEvent(world, plot.id); - Bukkit.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) { - event.setCancelled(true); - } else { - DBFunc.delete(world, plot); - } - } - } - } - } - } - } + /** + * Replace the plot object with an updated version + * + * @param plot + * plot object + */ + public static void updatePlot(Plot plot) { + String world = plot.world; + if (!plots.containsKey(world)) { + plots.put(world, new HashMap()); + } + plot.hasChanged = true; + plots.get(world).put(plot.id, plot); + } - private void setupLogger() { - File log = new File(getMain().getDataFolder() + File.separator + "logs" + File.separator + "plots.log"); - if (!log.exists()) { - try { - if (!new File(getMain().getDataFolder() + File.separator + "logs").mkdirs()) { - sendConsoleSenderMessage(C.PREFIX.s() + "&cFailed to create logs folder. Do it manually."); - } - if (log.createNewFile()) { - FileWriter writer = new FileWriter(log); - writer.write("Created at: " + new Date().toString() + "\n\n\n"); - writer.close(); - } - } catch (IOException e) { + /** + * TODO: Implement better system The whole point of this system is to + * recycle old plots So why not just allow users to claim old plots, and try + * to hide the fact that the are owned. Reduce amount of expired plots: - On + * /plot auto - allow claiming of old plot, clear it so the user doesn't + * know - On /plot info, - show that the plot is expired and allowed to be + * claimed + * + * Have the task run less often: - Run the task when there are very little, + * or no players online (great for small servers) - Run the task at startup + * (also only useful for small servers) + * + * Also, in terms of faster code: - Have an array of plots, sorted by expiry + * time. - Add new plots to the end. - The task then only needs to go + * through the first few plots + * + * @param plugin + * Plugin + * @param async + * Call async? + */ + private static void checkExpired(JavaPlugin plugin, boolean async) { + if (async) { + Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { + @Override + public void run() { + for (String world : getPlotWorldsString()) { + if (plots.containsKey(world)) { + for (Plot plot : plots.get(world).values()) { + if (plot.owner == null) { + continue; + } + long lastPlayed = getLastPlayed(plot.owner); + if (lastPlayed == 0) { + continue; + } + int days = (int) (lastPlayed / (1000 * 60 * 60 * 24)); + if (days >= Settings.AUTO_CLEAR_DAYS) { + PlotDeleteEvent event = new PlotDeleteEvent( + world, plot.id); + Bukkit.getServer().getPluginManager() + .callEvent(event); + if (event.isCancelled()) { + event.setCancelled(true); + } else { + DBFunc.delete(world, plot); + } + } + } + } + } + } + }); + } else { + for (String world : getPlotWorldsString()) { + if (PlotMain.plots.containsKey(world)) { + for (Plot plot : PlotMain.plots.get(world).values()) { + if (PlayerFunctions.hasExpired(plot)) { + PlotDeleteEvent event = new PlotDeleteEvent(world, + plot.id); + Bukkit.getServer().getPluginManager() + .callEvent(event); + if (event.isCancelled()) { + event.setCancelled(true); + } else { + DBFunc.delete(world, plot); + } + } + } + } + } + } + } - e.printStackTrace(); - } - } - Logger.setup(log); - Logger.add(LogLevel.GENERAL, "Logger enabled"); - } + private void setupLogger() { + File log = new File(getMain().getDataFolder() + File.separator + "logs" + + File.separator + "plots.log"); + if (!log.exists()) { + try { + if (!new File(getMain().getDataFolder() + File.separator + + "logs").mkdirs()) { + sendConsoleSenderMessage(C.PREFIX.s() + + "&cFailed to create logs folder. Do it manually."); + } + if (log.createNewFile()) { + FileWriter writer = new FileWriter(log); + writer.write("Created at: " + new Date().toString() + + "\n\n\n"); + writer.close(); + } + } catch (IOException e) { - private static double getJavaVersion() { - return Double.parseDouble(System.getProperty("java.specification.version")); - } + e.printStackTrace(); + } + } + Logger.setup(log); + Logger.add(LogLevel.GENERAL, "Logger enabled"); + } - /** - * On Load. - */ - @Override - @SuppressWarnings("deprecation") - public void onEnable() { - setupLogger(); + private static double getJavaVersion() { + return Double.parseDouble(System + .getProperty("java.specification.version")); + } - // Check for outdated java version. - if (getJavaVersion() < 1.7) { - sendConsoleSenderMessage(C.PREFIX.s() + "&cYour java version is outdated. Please update to at least 1.7."); - sendConsoleSenderMessage(C.PREFIX.s() + "&cURL: &6https://java.com/en/download/index.jsp"); - Bukkit.getPluginManager().disablePlugin(this); - return; - } + /** + * On Load. + */ + @Override + @SuppressWarnings("deprecation") + public void onEnable() { + setupLogger(); - configs(); + // Check for outdated java version. + if (getJavaVersion() < 1.7) { + sendConsoleSenderMessage(C.PREFIX.s() + + "&cYour java version is outdated. Please update to at least 1.7."); + sendConsoleSenderMessage(C.PREFIX.s() + + "&cURL: &6https://java.com/en/download/index.jsp"); + Bukkit.getPluginManager().disablePlugin(this); + return; + } - if (Settings.METRICS) { - try { - Metrics metrics = new Metrics(this); - metrics.start(); - sendConsoleSenderMessage(C.PREFIX.s() + "&6Metrics enabled."); - } catch (Exception e) { - sendConsoleSenderMessage(C.PREFIX.s() + "&cFailed to load up metrics."); - } - } + configs(); - if (Settings.KILL_ROAD_MOBS) { - killAllEntities(); - } + if (Settings.METRICS) { + try { + Metrics metrics = new Metrics(this); + metrics.start(); + sendConsoleSenderMessage(C.PREFIX.s() + "&6Metrics enabled."); + } catch (Exception e) { + sendConsoleSenderMessage(C.PREFIX.s() + + "&cFailed to load up metrics."); + } + } - if (C.ENABLED.s().length() > 0) { - Broadcast(C.ENABLED); - } - if (Settings.DB.USE_MYSQL) { - try { - mySQL = new MySQL(this, Settings.DB.HOST_NAME, Settings.DB.PORT, Settings.DB.DATABASE, Settings.DB.USER, Settings.DB.PASSWORD); - connection = mySQL.openConnection(); - { - DatabaseMetaData meta = connection.getMetaData(); - ResultSet res = meta.getTables(null, null, "plot", null); - if (!res.next()) { - DBFunc.createTables("mysql", true); - } else { - res = meta.getTables(null, null, "plot_trusted", null); - if (!res.next()) { - DBFunc.createTables("mysql", false); - } - else { - res = meta.getTables(null, null, "plot_ratings", null); - if (!res.next()) { - DBFunc.createTables("mysql", false); - } - } - } - } - } catch (ClassNotFoundException | SQLException e) { - Logger.add(LogLevel.DANGER, "MySQL connection failed."); - System.out.print("\u001B[31m[Plots] MySQL is not setup correctly. The plugin will disable itself.\u001B[0m"); - System.out.print("\u001B[36m==== Here is an ugly stacktrace if you are interested in those things ====\u001B[0m"); - e.printStackTrace(); - Bukkit.getPluginManager().disablePlugin(this); - return; - } - plots = DBFunc.getPlots(); + if (Settings.KILL_ROAD_MOBS) { + killAllEntities(); + } - } else if (Settings.DB.USE_MONGO) { - sendConsoleSenderMessage(C.PREFIX.s() + "MongoDB is not yet implemented"); - } else if (Settings.DB.USE_SQLITE) { - try { - connection = new SQLite(this, Settings.DB.SQLITE_DB + ".db").openConnection(); - { - DatabaseMetaData meta = connection.getMetaData(); - ResultSet res = meta.getTables(null, null, "plot", null); - if (!res.next()) { - DBFunc.createTables("sqlite", true); - } else { - res = meta.getTables(null, null, "plot_trusted", null); - if (!res.next()) { - DBFunc.createTables("sqlite", false); - } - else { - res = meta.getTables(null, null, "plot_ratings", null); - if (!res.next()) { - DBFunc.createTables("sqlite", false); - } - } - } - } - } catch (ClassNotFoundException | SQLException e) { - Logger.add(LogLevel.DANGER, "SQLite connection failed"); - sendConsoleSenderMessage(C.PREFIX.s() + "&cFailed to open SQLite connection. The plugin will disable itself."); - sendConsoleSenderMessage("&9==== Here is an ugly stacktrace, if you are interested in those things ==="); - e.printStackTrace(); - Bukkit.getPluginManager().disablePlugin(this); - return; - } - plots = DBFunc.getPlots(); - } else { - Logger.add(LogLevel.DANGER, "No storage type is set."); - sendConsoleSenderMessage(C.PREFIX + "&cNo storage type is set!"); - getServer().getPluginManager().disablePlugin(this); - return; - } - if (getServer().getPluginManager().getPlugin("PlotMe") != null) { - try { - new PlotMeConverter(this).runAsync(); - } catch (Exception e) { - e.printStackTrace(); - } - } + if (C.ENABLED.s().length() > 0) { + Broadcast(C.ENABLED); + } + if (Settings.DB.USE_MYSQL) { + try { + mySQL = new MySQL(this, Settings.DB.HOST_NAME, + Settings.DB.PORT, Settings.DB.DATABASE, + Settings.DB.USER, Settings.DB.PASSWORD); + connection = mySQL.openConnection(); + { + DatabaseMetaData meta = connection.getMetaData(); + ResultSet res = meta.getTables(null, null, "plot", null); + if (!res.next()) { + DBFunc.createTables("mysql", true); + } else { + res = meta.getTables(null, null, "plot_trusted", null); + if (!res.next()) { + DBFunc.createTables("mysql", false); + } else { + res = meta.getTables(null, null, "plot_ratings", + null); + if (!res.next()) { + DBFunc.createTables("mysql", false); + } + } + } + } + } catch (ClassNotFoundException | SQLException e) { + Logger.add(LogLevel.DANGER, "MySQL connection failed."); + System.out + .print("\u001B[31m[Plots] MySQL is not setup correctly. The plugin will disable itself.\u001B[0m"); + System.out + .print("\u001B[36m==== Here is an ugly stacktrace if you are interested in those things ====\u001B[0m"); + e.printStackTrace(); + Bukkit.getPluginManager().disablePlugin(this); + return; + } + plots = DBFunc.getPlots(); - getCommand("plots").setExecutor(new MainCommand()); - getCommand("plots").setAliases(new ArrayList() { - { - add("p"); - add("plotme"); - add("plot"); - } - }); + } else if (Settings.DB.USE_MONGO) { + sendConsoleSenderMessage(C.PREFIX.s() + + "MongoDB is not yet implemented"); + } else if (Settings.DB.USE_SQLITE) { + try { + connection = new SQLite(this, Settings.DB.SQLITE_DB + ".db") + .openConnection(); + { + DatabaseMetaData meta = connection.getMetaData(); + ResultSet res = meta.getTables(null, null, "plot", null); + if (!res.next()) { + DBFunc.createTables("sqlite", true); + } else { + res = meta.getTables(null, null, "plot_trusted", null); + if (!res.next()) { + DBFunc.createTables("sqlite", false); + } else { + res = meta.getTables(null, null, "plot_ratings", + null); + if (!res.next()) { + DBFunc.createTables("sqlite", false); + } + } + } + } + } catch (ClassNotFoundException | SQLException e) { + Logger.add(LogLevel.DANGER, "SQLite connection failed"); + sendConsoleSenderMessage(C.PREFIX.s() + + "&cFailed to open SQLite connection. The plugin will disable itself."); + sendConsoleSenderMessage("&9==== Here is an ugly stacktrace, if you are interested in those things ==="); + e.printStackTrace(); + Bukkit.getPluginManager().disablePlugin(this); + return; + } + plots = DBFunc.getPlots(); + } else { + Logger.add(LogLevel.DANGER, "No storage type is set."); + sendConsoleSenderMessage(C.PREFIX + "&cNo storage type is set!"); + getServer().getPluginManager().disablePlugin(this); + return; + } + if (getServer().getPluginManager().getPlugin("PlotMe") != null) { + try { + new PlotMeConverter(this).runAsync(); + } catch (Exception e) { + e.printStackTrace(); + } + } - getServer().getPluginManager().registerEvents(new PlayerEvents(), this); + getCommand("plots").setExecutor(new MainCommand()); + getCommand("plots").setAliases(new ArrayList() { + { + add("p"); + add("plotme"); + add("plot"); + } + }); - if (getServer().getPluginManager().getPlugin("CameraAPI") != null) { - cameraAPI = CameraAPI.getInstance(); - Camera camera = new Camera(); - MainCommand.subCommands.add(camera); - getServer().getPluginManager().registerEvents(camera, this); - } - if (getServer().getPluginManager().getPlugin("BarAPI") != null) { - barAPI = (BarAPI) getServer().getPluginManager().getPlugin("BarAPI"); - } - if (getServer().getPluginManager().getPlugin("WorldEdit") != null) { - worldEdit = (WorldEditPlugin) getServer().getPluginManager().getPlugin("WorldEdit"); - getServer().getPluginManager().registerEvents(new WorldEditListener(), this); - } - if (Settings.WORLDGUARD) { - if (getServer().getPluginManager().getPlugin("WorldGuard") != null) { - worldGuard = (WorldGuardPlugin) getServer().getPluginManager().getPlugin("WorldGuard"); - worldGuardListener = new WorldGuardListener(this); - getServer().getPluginManager().registerEvents(worldGuardListener, this); - } - } - if (Settings.AUTO_CLEAR) { - checkExpired(PlotMain.getMain(), true); - checkForExpiredPlots(); - } - if (getServer().getPluginManager().getPlugin("Vault") != null) { - RegisteredServiceProvider economyProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); - if (economyProvider != null) { - economy = economyProvider.getProvider(); - } - useEconomy = (economy != null); - } - getServer().getScheduler().scheduleSyncRepeatingTask(this, new Lag(), 100L, 1L); + getServer().getPluginManager().registerEvents(new PlayerEvents(), this); - if (Web.ENABLED) { - sendConsoleSenderMessage(C.PREFIX.s() + "Web Is not implemented yet. Please bear with us."); - } + if (getServer().getPluginManager().getPlugin("CameraAPI") != null) { + cameraAPI = CameraAPI.getInstance(); + Camera camera = new Camera(); + MainCommand.subCommands.add(camera); + getServer().getPluginManager().registerEvents(camera, this); + } + if (getServer().getPluginManager().getPlugin("BarAPI") != null) { + barAPI = (BarAPI) getServer().getPluginManager() + .getPlugin("BarAPI"); + } + if (getServer().getPluginManager().getPlugin("WorldEdit") != null) { + worldEdit = (WorldEditPlugin) getServer().getPluginManager() + .getPlugin("WorldEdit"); + getServer().getPluginManager().registerEvents( + new WorldEditListener(), this); + } + if (Settings.WORLDGUARD) { + if (getServer().getPluginManager().getPlugin("WorldGuard") != null) { + worldGuard = (WorldGuardPlugin) getServer().getPluginManager() + .getPlugin("WorldGuard"); + worldGuardListener = new WorldGuardListener(this); + getServer().getPluginManager().registerEvents( + worldGuardListener, this); + } + } + if (Settings.AUTO_CLEAR) { + checkExpired(PlotMain.getMain(), true); + checkForExpiredPlots(); + } + if (getServer().getPluginManager().getPlugin("Vault") != null) { + RegisteredServiceProvider economyProvider = getServer() + .getServicesManager().getRegistration( + net.milkbowl.vault.economy.Economy.class); + if (economyProvider != null) { + economy = economyProvider.getProvider(); + } + useEconomy = (economy != null); + } + getServer().getScheduler().scheduleSyncRepeatingTask(this, new Lag(), + 100L, 1L); - try { - new SetBlockFast(); - PlotHelper.canSetFast = true; - } catch (Exception e) { - PlotHelper.canSetFast = false; - } + if (Web.ENABLED) { + sendConsoleSenderMessage(C.PREFIX.s() + + "Web Is not implemented yet. Please bear with us."); + } - //TODO Test... - UUIDHandler.startFetch(this); - } + try { + new SetBlockFast(); + PlotHelper.canSetFast = true; + } catch (Exception e) { + PlotHelper.canSetFast = false; + } - /** - * Get MySQL Connection - * - * @return connection MySQL Connection. - */ - @SuppressWarnings("unused") - public static Connection getConnection() { - return connection; - } + // TODO Test... + UUIDHandler.startFetch(this); + } - /** .. */ + /** + * Get MySQL Connection + * + * @return connection MySQL Connection. + */ + @SuppressWarnings("unused") + public static Connection getConnection() { + return connection; + } - // Old Stuff - /* - * private static boolean checkForUpdate() throws IOException { URL call = - * new URL(Settings.Update.VERSION_URL); InputStream stream = - * call.openStream(); BufferedReader reader = new BufferedReader(new - * InputStreamReader(stream)); String latest = reader.readLine(); - * reader.close(); return - * !getPlotMain().getDescription().getVersion().equalsIgnoreCase(latest); } - * private static String getNextUpdateString() throws IOException { URL call - * = new URL(Settings.Update.VERSION_URL); InputStream stream = - * call.openStream(); BufferedReader reader = new BufferedReader(new - * InputStreamReader(stream)); return reader.readLine(); } private static - * void update() throws IOException { sendConsoleSenderMessage(C.PREFIX.s() - * + "&c&lThere is an update! New Update: &6&l" + getNextUpdateString() + - * "&c&l, Current Update: &6&l" + - * getPlotMain().getDescription().getVersion()); } - */ + /** .. */ - /** - * Send a message to the console. - * - * @param string - * message - */ - public static void sendConsoleSenderMessage(String string) { - if (getMain().getServer().getConsoleSender() == null) { - System.out.println(ChatColor.stripColor(ConsoleColors.fromString(string))); - } else { - getMain().getServer().getConsoleSender().sendMessage(ChatColor.translateAlternateColorCodes('&', string)); - } - } + // Old Stuff + /* + * private static boolean checkForUpdate() throws IOException { URL call = + * new URL(Settings.Update.VERSION_URL); InputStream stream = + * call.openStream(); BufferedReader reader = new BufferedReader(new + * InputStreamReader(stream)); String latest = reader.readLine(); + * reader.close(); return + * !getPlotMain().getDescription().getVersion().equalsIgnoreCase(latest); } + * private static String getNextUpdateString() throws IOException { URL call + * = new URL(Settings.Update.VERSION_URL); InputStream stream = + * call.openStream(); BufferedReader reader = new BufferedReader(new + * InputStreamReader(stream)); return reader.readLine(); } private static + * void update() throws IOException { sendConsoleSenderMessage(C.PREFIX.s() + * + "&c&lThere is an update! New Update: &6&l" + getNextUpdateString() + + * "&c&l, Current Update: &6&l" + + * getPlotMain().getDescription().getVersion()); } + */ - public static boolean teleportPlayer(Player player, Location from, Plot plot) { - PlayerTeleportToPlotEvent event = new PlayerTeleportToPlotEvent(player, from, plot); - Bukkit.getServer().getPluginManager().callEvent(event); - if (!event.isCancelled()) { - Location location = PlotHelper.getPlotHome(Bukkit.getWorld(plot.world), plot); - if ((location.getBlockX() >= 29999999) || (location.getBlockX() <= -29999999) || (location.getBlockZ() >= 299999999) || (location.getBlockZ() <= -29999999)) { - event.setCancelled(true); - return false; - } - player.teleport(location); - PlayerFunctions.sendMessage(player, C.TELEPORTED_TO_PLOT); - } - return event.isCancelled(); - } + /** + * Send a message to the console. + * + * @param string + * message + */ + public static void sendConsoleSenderMessage(String string) { + if (getMain().getServer().getConsoleSender() == null) { + System.out.println(ChatColor.stripColor(ConsoleColors + .fromString(string))); + } else { + getMain() + .getServer() + .getConsoleSender() + .sendMessage( + ChatColor.translateAlternateColorCodes('&', string)); + } + } - /** - * Send a message to the console - * - * @param c - * message - */ - @SuppressWarnings("unused") - public static void sendConsoleSenderMessage(C c) { - sendConsoleSenderMessage(c.s()); - } + public static boolean teleportPlayer(Player player, Location from, Plot plot) { + PlayerTeleportToPlotEvent event = new PlayerTeleportToPlotEvent(player, + from, plot); + Bukkit.getServer().getPluginManager().callEvent(event); + if (!event.isCancelled()) { + Location location = PlotHelper.getPlotHome( + Bukkit.getWorld(plot.world), plot); + if ((location.getBlockX() >= 29999999) + || (location.getBlockX() <= -29999999) + || (location.getBlockZ() >= 299999999) + || (location.getBlockZ() <= -29999999)) { + event.setCancelled(true); + return false; + } + player.teleport(location); + PlayerFunctions.sendMessage(player, C.TELEPORTED_TO_PLOT); + } + return event.isCancelled(); + } - /** - * Broadcast publicly - * - * @param c - * message - */ - public static void Broadcast(C c) { - Bukkit.broadcastMessage(ChatColor.translateAlternateColorCodes('&', C.PREFIX.s() + c.s())); - } + /** + * Send a message to the console + * + * @param c + * message + */ + @SuppressWarnings("unused") + public static void sendConsoleSenderMessage(C c) { + sendConsoleSenderMessage(c.s()); + } - /** - * Returns the main class. - * - * @return (this class) - */ - public static PlotMain getMain() { - return JavaPlugin.getPlugin(PlotMain.class); - } + /** + * Broadcast publicly + * + * @param c + * message + */ + public static void Broadcast(C c) { + Bukkit.broadcastMessage(ChatColor.translateAlternateColorCodes('&', + C.PREFIX.s() + c.s())); + } - /** - * Broadcast a message to all admins - * - * @param c - * message - */ - public static void BroadcastWithPerms(C c) { - for (Player player : Bukkit.getOnlinePlayers()) { - if (player.hasPermission("plots.admin")) { - PlayerFunctions.sendMessage(player, c); - } - } - System.out.println(ChatColor.stripColor(ChatColor.translateAlternateColorCodes('&', C.PREFIX.s() + c.s()))); - } + /** + * Returns the main class. + * + * @return (this class) + */ + public static PlotMain getMain() { + return JavaPlugin.getPlugin(PlotMain.class); + } - public static void reloadTranslations() throws IOException { - translations = YamlConfiguration.loadConfiguration(translationsFile); - } + /** + * Broadcast a message to all admins + * + * @param c + * message + */ + public static void BroadcastWithPerms(C c) { + for (Player player : Bukkit.getOnlinePlayers()) { + if (player.hasPermission("plots.admin")) { + PlayerFunctions.sendMessage(player, c); + } + } + System.out.println(ChatColor.stripColor(ChatColor + .translateAlternateColorCodes('&', C.PREFIX.s() + c.s()))); + } - public static long getLastPlayed(UUID uuid) { - if (uuid == null) { - return 0; - } - OfflinePlayer player; - if (((player = Bukkit.getOfflinePlayer(uuid)) == null) || !player.hasPlayedBefore()) { - return 0; - } - return player.getLastPlayed(); - } + public static void reloadTranslations() throws IOException { + translations = YamlConfiguration.loadConfiguration(translationsFile); + } - /** - * Load configuration files - */ - @SuppressWarnings("deprecation") - public static void configs() { - File folder = new File(getMain().getDataFolder() + File.separator + "config"); - if (!folder.exists() && !folder.mkdirs()) { - sendConsoleSenderMessage(C.PREFIX.s() + "&cFailed to create the /plugins/config folder. Please create it manually."); - } - try { - configFile = new File(getMain().getDataFolder() + File.separator + "config" + File.separator + "settings.yml"); - if (!configFile.exists()) { - configFile.createNewFile(); - } - config = YamlConfiguration.loadConfiguration(configFile); - setupConfig(); - } catch (Exception err_trans) { - Logger.add(LogLevel.DANGER, "Failed to save settings.yml"); - System.out.println("Failed to save settings.yml"); - } - try { - storageFile = new File(getMain().getDataFolder() + File.separator + "config" + File.separator + "storage.yml"); - if (!storageFile.exists()) { - storageFile.createNewFile(); - } - storage = YamlConfiguration.loadConfiguration(storageFile); - setupStorage(); - } catch (Exception err_trans) { - Logger.add(LogLevel.DANGER, "Failed to save storage.yml"); - System.out.println("Failed to save storage.yml"); - } - try { - translationsFile = new File(getMain().getDataFolder() + File.separator + "config" + File.separator + "translations.yml"); - if (!translationsFile.exists()) { - translationsFile.createNewFile(); - } - translations = YamlConfiguration.loadConfiguration(translationsFile); - setupTranslations(); - } catch (Exception err_trans) { - Logger.add(LogLevel.DANGER, "Failed to save translations.yml"); - System.out.println("Failed to save translations.yml"); - } + public static long getLastPlayed(UUID uuid) { + if (uuid == null) { + return 0; + } + OfflinePlayer player; + if (((player = Bukkit.getOfflinePlayer(uuid)) == null) + || !player.hasPlayedBefore()) { + return 0; + } + return player.getLastPlayed(); + } - try { - config.save(configFile); - storage.save(storageFile); - translations.save(translationsFile); - } catch (IOException e) { - Logger.add(LogLevel.DANGER, "Configuration file saving failed"); - e.printStackTrace(); - } - { - Settings.DB.USE_MYSQL = storage.getBoolean("mysql.use"); - Settings.DB.USER = storage.getString("mysql.user"); - Settings.DB.PASSWORD = storage.getString("mysql.password"); - Settings.DB.HOST_NAME = storage.getString("mysql.host"); - Settings.DB.PORT = storage.getString("mysql.port"); - Settings.DB.DATABASE = storage.getString("mysql.database"); - Settings.DB.USE_SQLITE = storage.getBoolean("sqlite.use"); - Settings.DB.SQLITE_DB = storage.getString("sqlite.db"); - } - { - Settings.METRICS = config.getBoolean("metrics"); - // Web - // Web.ENABLED = config.getBoolean("web.enabled"); - // Web.PORT = config.getInt("web.port"); + /** + * Load configuration files + */ + @SuppressWarnings("deprecation") + public static void configs() { + File folder = new File(getMain().getDataFolder() + File.separator + + "config"); + if (!folder.exists() && !folder.mkdirs()) { + sendConsoleSenderMessage(C.PREFIX.s() + + "&cFailed to create the /plugins/config folder. Please create it manually."); + } + try { + configFile = new File(getMain().getDataFolder() + File.separator + + "config" + File.separator + "settings.yml"); + if (!configFile.exists()) { + configFile.createNewFile(); + } + config = YamlConfiguration.loadConfiguration(configFile); + setupConfig(); + } catch (Exception err_trans) { + Logger.add(LogLevel.DANGER, "Failed to save settings.yml"); + System.out.println("Failed to save settings.yml"); + } + try { + storageFile = new File(getMain().getDataFolder() + File.separator + + "config" + File.separator + "storage.yml"); + if (!storageFile.exists()) { + storageFile.createNewFile(); + } + storage = YamlConfiguration.loadConfiguration(storageFile); + setupStorage(); + } catch (Exception err_trans) { + Logger.add(LogLevel.DANGER, "Failed to save storage.yml"); + System.out.println("Failed to save storage.yml"); + } + try { + translationsFile = new File(getMain().getDataFolder() + + File.separator + "config" + File.separator + + "translations.yml"); + if (!translationsFile.exists()) { + translationsFile.createNewFile(); + } + translations = YamlConfiguration + .loadConfiguration(translationsFile); + setupTranslations(); + } catch (Exception err_trans) { + Logger.add(LogLevel.DANGER, "Failed to save translations.yml"); + System.out.println("Failed to save translations.yml"); + } - Settings.AUTO_CLEAR = config.getBoolean("clear.auto.enabled"); - Settings.AUTO_CLEAR_DAYS = config.getInt("clear.auto.days"); - } - if (Settings.DEBUG) { - Map settings = new HashMap<>(); - settings.put("Kill Road Mobs", "" + Settings.KILL_ROAD_MOBS); - settings.put("Use Metrics", "" + Settings.METRICS); - settings.put("Mob Pathfinding", "" + Settings.MOB_PATHFINDING); - settings.put("Web Enabled", "" + Web.ENABLED); - settings.put("Web Port", "" + Web.PORT); - settings.put("DB Mysql Enabled", "" + Settings.DB.USE_MYSQL); - settings.put("DB SQLite Enabled", "" + Settings.DB.USE_SQLITE); - settings.put("Auto Clear Enabled", "" + Settings.AUTO_CLEAR); - settings.put("Auto Clear Days", "" + Settings.AUTO_CLEAR_DAYS); - for (Entry setting : settings.entrySet()) { - sendConsoleSenderMessage(C.PREFIX.s() + String.format("&cKey: &6%s&c, Value: &6%s", setting.getKey(), setting.getValue())); - } - } - } + try { + config.save(configFile); + storage.save(storageFile); + translations.save(translationsFile); + } catch (IOException e) { + Logger.add(LogLevel.DANGER, "Configuration file saving failed"); + e.printStackTrace(); + } + { + Settings.DB.USE_MYSQL = storage.getBoolean("mysql.use"); + Settings.DB.USER = storage.getString("mysql.user"); + Settings.DB.PASSWORD = storage.getString("mysql.password"); + Settings.DB.HOST_NAME = storage.getString("mysql.host"); + Settings.DB.PORT = storage.getString("mysql.port"); + Settings.DB.DATABASE = storage.getString("mysql.database"); + Settings.DB.USE_SQLITE = storage.getBoolean("sqlite.use"); + Settings.DB.SQLITE_DB = storage.getString("sqlite.db"); + } + { + Settings.METRICS = config.getBoolean("metrics"); + // Web + // Web.ENABLED = config.getBoolean("web.enabled"); + // Web.PORT = config.getInt("web.port"); - /** - * Kill all entities on roads - */ - @SuppressWarnings("deprecation") - public static void killAllEntities() { - Bukkit.getScheduler().scheduleAsyncRepeatingTask(getMain(), new Runnable() { - Location location; - long ticked = 0l; - long error = 0l; - { - sendConsoleSenderMessage(C.PREFIX.s() + "KillAllEntities started."); - } + Settings.AUTO_CLEAR = config.getBoolean("clear.auto.enabled"); + Settings.AUTO_CLEAR_DAYS = config.getInt("clear.auto.days"); + } + if (Settings.DEBUG) { + Map settings = new HashMap<>(); + settings.put("Kill Road Mobs", "" + Settings.KILL_ROAD_MOBS); + settings.put("Use Metrics", "" + Settings.METRICS); + settings.put("Mob Pathfinding", "" + Settings.MOB_PATHFINDING); + settings.put("Web Enabled", "" + Web.ENABLED); + settings.put("Web Port", "" + Web.PORT); + settings.put("DB Mysql Enabled", "" + Settings.DB.USE_MYSQL); + settings.put("DB SQLite Enabled", "" + Settings.DB.USE_SQLITE); + settings.put("Auto Clear Enabled", "" + Settings.AUTO_CLEAR); + settings.put("Auto Clear Days", "" + Settings.AUTO_CLEAR_DAYS); + for (Entry setting : settings.entrySet()) { + sendConsoleSenderMessage(C.PREFIX.s() + + String.format("&cKey: &6%s&c, Value: &6%s", + setting.getKey(), setting.getValue())); + } + } + } - @Override - public void run() { - if (this.ticked > 36000l) { - this.ticked = 0l; - sendConsoleSenderMessage(C.PREFIX.s() + "KillAllEntities has been running for 60 minutes. Errors: " + this.error); - this.error = 0l; - } - for (String w : getPlotWorlds()) { - PlotWorld plotworld = getWorldSettings(w); - World world = Bukkit.getServer().getWorld(w); - try { - if (world.getLoadedChunks().length < 1) { - continue; - } - for (Chunk chunk : world.getLoadedChunks()) { - Entity[] entities = chunk.getEntities(); - for (int i = entities.length - 1; i >= 0; i--) { - Entity entity = entities[i]; - if (!(entity instanceof Player)) { - this.location = entity.getLocation(); - if (!PlayerEvents.isInPlot(this.location)) { - boolean tamed = false; - if (Settings.MOB_PATHFINDING) { - if (entity instanceof Tameable) { - Tameable tameable = (Tameable) entity; - if (tameable.isTamed()) { - tamed = true; - } - } else if (entity instanceof LivingEntity) { - LivingEntity livingEntity = ((LivingEntity) entity); - if (livingEntity.getCustomName() != null) { - tamed = true; - } - } - if (tamed) { - boolean found = false; - int radius = 1; - int dir = 0; - int x = this.location.getBlockX(); - int y = this.location.getBlockY(); - int z = this.location.getBlockZ(); - while (!found && (radius < 4)) { - Location pos; - switch (dir) { - case 0: - pos = new Location(world, x + radius, y, z); - dir++; - break; - case 1: - pos = new Location(world, x, y, z + radius); - dir++; - break; - case 2: - pos = new Location(world, x - radius, y, z); - dir++; - break; - case 3: - pos = new Location(world, x, y, z - radius); - dir = 0; - radius++; - break; - default: - pos = this.location; - break; + /** + * Kill all entities on roads + */ + @SuppressWarnings("deprecation") + public static void killAllEntities() { + Bukkit.getScheduler().scheduleAsyncRepeatingTask(getMain(), + new Runnable() { + Location location; + long ticked = 0l; + long error = 0l; + { + sendConsoleSenderMessage(C.PREFIX.s() + + "KillAllEntities started."); + } - } - if (PlayerEvents.isInPlot(pos)) { - entity.teleport(pos.add(0.5, 0, 0.5)); - found = true; - break; - } - } - // Welp! how did this entity get - // here? - entity.teleport(this.location.subtract(this.location.getDirection().normalize().multiply(2))); - } - } - if (!tamed) { - entity.remove(); - } - } - } - } - } - } catch (Exception e) { - ++this.error; - } finally { - ++this.ticked; - } - } - } - }, 0l, 2l); - } + @Override + public void run() { + if (this.ticked > 36000l) { + this.ticked = 0l; + sendConsoleSenderMessage(C.PREFIX.s() + + "KillAllEntities has been running for 60 minutes. Errors: " + + this.error); + this.error = 0l; + } + for (String w : getPlotWorlds()) { + getWorldSettings(w); + World world = Bukkit.getServer().getWorld(w); + try { + if (world.getLoadedChunks().length < 1) { + continue; + } + for (Chunk chunk : world.getLoadedChunks()) { + Entity[] entities = chunk.getEntities(); + for (int i = entities.length - 1; i >= 0; i--) { + Entity entity = entities[i]; + if (!(entity instanceof Player)) { + this.location = entity + .getLocation(); + if (!PlayerEvents + .isInPlot(this.location)) { + boolean tamed = false; + if (Settings.MOB_PATHFINDING) { + if (entity instanceof Tameable) { + Tameable tameable = (Tameable) entity; + if (tameable.isTamed()) { + tamed = true; + } + } else if (entity instanceof LivingEntity) { + LivingEntity livingEntity = ((LivingEntity) entity); + if (livingEntity + .getCustomName() != null) { + tamed = true; + } + } + if (tamed) { + boolean found = false; + int radius = 1; + int dir = 0; + int x = this.location + .getBlockX(); + int y = this.location + .getBlockY(); + int z = this.location + .getBlockZ(); + while (!found + && (radius < 4)) { + Location pos; + switch (dir) { + case 0: + pos = new Location( + world, + x + + radius, + y, z); + dir++; + break; + case 1: + pos = new Location( + world, + x, + y, + z + + radius); + dir++; + break; + case 2: + pos = new Location( + world, + x + - radius, + y, z); + dir++; + break; + case 3: + pos = new Location( + world, + x, + y, + z + - radius); + dir = 0; + radius++; + break; + default: + pos = this.location; + break; - /** - * SETUP: settings.yml - */ - private static void setupConfig() { - config.set("version", config_ver); - Map options = new HashMap(); - options.put("auto_update", false); - options.put("worldguard.enabled", Settings.WORLDGUARD); - options.put("kill_road_mobs", Settings.KILL_ROAD_MOBS_DEFAULT); - options.put("mob_pathfinding", Settings.MOB_PATHFINDING_DEFAULT); - options.put("web.enabled", Web.ENABLED); - options.put("web.port", Web.PORT); - options.put("metrics", true); - options.put("debug", true); - options.put("clear.auto.enabled", false); - options.put("clear.auto.days", 365); - options.put("max_plots", Settings.MAX_PLOTS); + } + if (PlayerEvents + .isInPlot(pos)) { + entity.teleport(pos + .add(0.5, + 0, + 0.5)); + found = true; + break; + } + } + // Welp! how did this + // entity get + // here? + entity.teleport(this.location + .subtract(this.location + .getDirection() + .normalize() + .multiply( + 2))); + } + } + if (!tamed) { + entity.remove(); + } + } + } + } + } + } catch (Exception e) { + ++this.error; + } finally { + ++this.ticked; + } + } + } + }, 0l, 2l); + } - for (Entry node : options.entrySet()) { - if (!config.contains(node.getKey())) { - config.set(node.getKey(), node.getValue()); - } - } - Settings.DEBUG = config.getBoolean("debug"); - if (Settings.DEBUG) { - sendConsoleSenderMessage(C.PREFIX.s() + "&6Debug Mode Enabled (Default). Edit the config to turn this off."); - } - Web.ENABLED = config.getBoolean("web.enabled"); - Web.PORT = config.getInt("web.port"); - Settings.KILL_ROAD_MOBS = config.getBoolean("kill_road_mobs"); - Settings.WORLDGUARD = config.getBoolean("worldguard.enabled"); - Settings.MOB_PATHFINDING = config.getBoolean("mob_pathfinding"); - Settings.METRICS = config.getBoolean("metrics"); - Settings.AUTO_CLEAR_DAYS = config.getInt("clear.auto.days"); - Settings.AUTO_CLEAR = config.getBoolean("clear.auto.enabled"); - Settings.MAX_PLOTS = config.getInt("max_plots"); - } - - public static void createConfiguration(PlotWorld plotworld) { - String w = plotworld.worldname; - Map options = new HashMap(); - - for (ConfigurationNode setting:plotworld.getSettingNodes()) { - setting.getConstant(); - setting.getValue(); - } - - for (Entry node : options.entrySet()) { - if (!config.contains(node.getKey())) { - config.set(node.getKey(), node.getValue()); - } - } - - try { - config.save(PlotMain.configFile); - } catch (IOException e) { - PlotMain.sendConsoleSenderMessage("&c[Warning] PlotSquared failed to save the configuration&7 (settings.yml may differ from the one in memory)\n - To force a save from console use /plots save"); - } - } - - /** - * Adds an external world as a recognized PlotSquared world - * - The PlotWorld class created is based off the configuration in the settings.yml - * - Do not use this method unless the required world is preconfigured in the settings.yml - * - * @param world - */ - public static void loadWorld(World world) { - if (world == null) { - return; - } - Set worlds; - if (config.contains("worlds")) { - worlds = config.getConfigurationSection("worlds").getKeys(false); - } - else { - worlds = new HashSet(); - } - ChunkGenerator generator = world.getGenerator(); - if (generator instanceof PlotGenerator) { - sendConsoleSenderMessage(C.PREFIX.s()+"&aDetected world load for '"+world.getName()+"'."); - PlotGenerator plotgen = (PlotGenerator) generator; - - PlotWorld plotworld = plotgen.getPlotWorld(); - - PlotManager manager = plotgen.getPlotManager(); - - config.createSection("worlds."+world.getName()); - - plotworld.saveConfiguration(config.getConfigurationSection("worlds."+world.getName())); - - plotworld.loadConfiguration(config.getConfigurationSection("worlds."+world.getName())); - - addPlotWorld(world.getName(), plotworld, manager); - - - } - else { - if (worlds.contains(world.getName())) { - sendConsoleSenderMessage("&cWorld '" + world.getName() + "' in settings.yml is not using PlotSquared generator!"); - } - } - } + /** + * SETUP: settings.yml + */ + private static void setupConfig() { + config.set("version", config_ver); + Map options = new HashMap(); + options.put("auto_update", false); + options.put("worldguard.enabled", Settings.WORLDGUARD); + options.put("kill_road_mobs", Settings.KILL_ROAD_MOBS_DEFAULT); + options.put("mob_pathfinding", Settings.MOB_PATHFINDING_DEFAULT); + options.put("web.enabled", Web.ENABLED); + options.put("web.port", Web.PORT); + options.put("metrics", true); + options.put("debug", true); + options.put("clear.auto.enabled", false); + options.put("clear.auto.days", 365); + options.put("max_plots", Settings.MAX_PLOTS); - /** - * SETUP: storage.properties - */ - private static void setupStorage() { - storage.set("version", storage_ver); - Map options = new HashMap(); - options.put("mysql.use", true); - options.put("sqlite.use", false); - options.put("sqlite.db", "storage"); - options.put("mysql.host", "localhost"); - options.put("mysql.port", "3306"); - options.put("mysql.user", "root"); - options.put("mysql.password", "password"); - options.put("mysql.database", "plot_db"); - for (Entry node : options.entrySet()) { - if (!storage.contains(node.getKey())) { - storage.set(node.getKey(), node.getValue()); - } - } - } + for (Entry node : options.entrySet()) { + if (!config.contains(node.getKey())) { + config.set(node.getKey(), node.getValue()); + } + } + Settings.DEBUG = config.getBoolean("debug"); + if (Settings.DEBUG) { + sendConsoleSenderMessage(C.PREFIX.s() + + "&6Debug Mode Enabled (Default). Edit the config to turn this off."); + } + Web.ENABLED = config.getBoolean("web.enabled"); + Web.PORT = config.getInt("web.port"); + Settings.KILL_ROAD_MOBS = config.getBoolean("kill_road_mobs"); + Settings.WORLDGUARD = config.getBoolean("worldguard.enabled"); + Settings.MOB_PATHFINDING = config.getBoolean("mob_pathfinding"); + Settings.METRICS = config.getBoolean("metrics"); + Settings.AUTO_CLEAR_DAYS = config.getInt("clear.auto.days"); + Settings.AUTO_CLEAR = config.getBoolean("clear.auto.enabled"); + Settings.MAX_PLOTS = config.getInt("max_plots"); + } - /** - * SETUP: translations.properties - */ - public static void setupTranslations() { - translations.set("version", translations_ver); - for (C c : C.values()) { - if (!translations.contains(c.toString())) { - translations.set(c.toString(), c.s()); - } + public static void createConfiguration(PlotWorld plotworld) { + Map options = new HashMap(); - } - } + for (ConfigurationNode setting : plotworld.getSettingNodes()) { + setting.getConstant(); + setting.getValue(); + } - /** - * On unload - */ - @Override - public void onDisable() { - Logger.add(LogLevel.GENERAL, "Logger disabled"); - try { - Logger.write(); - } catch (IOException e1) { - e1.printStackTrace(); - } - try { - connection.close(); - mySQL.closeConnection(); - } catch (NullPointerException | SQLException e) { - if (connection != null) { - Logger.add(LogLevel.DANGER, "Could not close mysql connection"); - } - } - /* - * if(PlotWeb.PLOTWEB != null) { try { PlotWeb.PLOTWEB.stop(); } catch - * (Exception e) { e.printStackTrace(); } } - */ - } + for (Entry node : options.entrySet()) { + if (!config.contains(node.getKey())) { + config.set(node.getKey(), node.getValue()); + } + } - public static void addPlotWorld(String world, PlotWorld plotworld, PlotManager manager) { - worlds.put(world, plotworld); - managers.put(world, manager); - if (!plots.containsKey(world)) { - plots.put(world, new HashMap()); - } - } + try { + config.save(PlotMain.configFile); + } catch (IOException e) { + PlotMain.sendConsoleSenderMessage("&c[Warning] PlotSquared failed to save the configuration&7 (settings.yml may differ from the one in memory)\n - To force a save from console use /plots save"); + } + } + + /** + * Adds an external world as a recognized PlotSquared world - The PlotWorld + * class created is based off the configuration in the settings.yml - Do not + * use this method unless the required world is preconfigured in the + * settings.yml + * + * @param world + */ + public static void loadWorld(World world) { + if (world == null) { + return; + } + Set worlds; + if (config.contains("worlds")) { + worlds = config.getConfigurationSection("worlds").getKeys(false); + } else { + worlds = new HashSet(); + } + ChunkGenerator generator = world.getGenerator(); + if (generator instanceof PlotGenerator) { + sendConsoleSenderMessage(C.PREFIX.s() + + "&aDetected world load for '" + world.getName() + "'."); + PlotGenerator plotgen = (PlotGenerator) generator; + + PlotWorld plotworld = plotgen.getPlotWorld(); + + PlotManager manager = plotgen.getPlotManager(); + + config.createSection("worlds." + world.getName()); + + plotworld.saveConfiguration(config + .getConfigurationSection("worlds." + world.getName())); + + plotworld.loadConfiguration(config + .getConfigurationSection("worlds." + world.getName())); + + addPlotWorld(world.getName(), plotworld, manager); + + } else { + if (worlds.contains(world.getName())) { + sendConsoleSenderMessage("&cWorld '" + + world.getName() + + "' in settings.yml is not using PlotSquared generator!"); + } + } + } + + /** + * SETUP: storage.properties + */ + private static void setupStorage() { + storage.set("version", storage_ver); + Map options = new HashMap(); + options.put("mysql.use", true); + options.put("sqlite.use", false); + options.put("sqlite.db", "storage"); + options.put("mysql.host", "localhost"); + options.put("mysql.port", "3306"); + options.put("mysql.user", "root"); + options.put("mysql.password", "password"); + options.put("mysql.database", "plot_db"); + for (Entry node : options.entrySet()) { + if (!storage.contains(node.getKey())) { + storage.set(node.getKey(), node.getValue()); + } + } + } + + /** + * SETUP: translations.properties + */ + public static void setupTranslations() { + translations.set("version", translations_ver); + for (C c : C.values()) { + if (!translations.contains(c.toString())) { + translations.set(c.toString(), c.s()); + } + + } + } + + /** + * On unload + */ + @Override + public void onDisable() { + Logger.add(LogLevel.GENERAL, "Logger disabled"); + try { + Logger.write(); + } catch (IOException e1) { + e1.printStackTrace(); + } + try { + connection.close(); + mySQL.closeConnection(); + } catch (NullPointerException | SQLException e) { + if (connection != null) { + Logger.add(LogLevel.DANGER, "Could not close mysql connection"); + } + } + /* + * if(PlotWeb.PLOTWEB != null) { try { PlotWeb.PLOTWEB.stop(); } catch + * (Exception e) { e.printStackTrace(); } } + */ + } + + public static void addPlotWorld(String world, PlotWorld plotworld, + PlotManager manager) { + worlds.put(world, plotworld); + managers.put(world, manager); + if (!plots.containsKey(world)) { + plots.put(world, new HashMap()); + } + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/PlotManager.java b/PlotSquared/src/com/intellectualcrafters/plot/PlotManager.java index 05e14c66a..3e9f1ab65 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/PlotManager.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/PlotManager.java @@ -5,63 +5,68 @@ import java.util.ArrayList; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Biome; -import org.bukkit.block.Block; import org.bukkit.entity.Player; public abstract class PlotManager { - /* - * Plot locations (methods with Abs in them will not need to consider mega - * plots) - */ + /* + * Plot locations (methods with Abs in them will not need to consider mega + * plots) + */ - public abstract PlotId getPlotIdAbs(PlotWorld plotworld, Location loc); - - public abstract PlotId getPlotId(PlotWorld plotworld, Location loc); + public abstract PlotId getPlotIdAbs(PlotWorld plotworld, Location loc); - public abstract boolean isInPlotAbs(PlotWorld plotworld, Location loc, PlotId plotid); - // If you have a circular plot, just return the corner if it were a square - public abstract Location getPlotBottomLocAbs(PlotWorld plotworld, PlotId plotid); - // the same applies here - public abstract Location getPlotTopLocAbs(PlotWorld plotworld, PlotId plotid); - - /* - * Plot clearing (return false if you do not support some method) - * - * - */ + public abstract PlotId getPlotId(PlotWorld plotworld, Location loc); - public abstract boolean clearPlot(Player player, Plot plot); + public abstract boolean isInPlotAbs(PlotWorld plotworld, Location loc, + PlotId plotid); - public abstract Location getSignLoc(Player player, PlotWorld plotworld, Plot plot); + // If you have a circular plot, just return the corner if it were a square + public abstract Location getPlotBottomLocAbs(PlotWorld plotworld, + PlotId plotid); - /* - * Plot set functions (return false if you do not support the specific set - * method) - */ + // the same applies here + public abstract Location getPlotTopLocAbs(PlotWorld plotworld, PlotId plotid); - public abstract boolean setWall(Player player, PlotWorld plotworld, PlotId plotid, PlotBlock block); - - public abstract boolean setFloor(Player player, PlotWorld plotworld, PlotId plotid, PlotBlock[] block); + /* + * Plot clearing (return false if you do not support some method) + */ - public abstract boolean setBiome(Player player, Plot plot, Biome biome); + public abstract boolean clearPlot(Player player, Plot plot); - /* - * PLOT MERGING (return false if your generator does not support plot - * merging) - */ - public abstract boolean createRoadEast(PlotWorld plotworld, Plot plot); + public abstract Location getSignLoc(Player player, PlotWorld plotworld, + Plot plot); - public abstract boolean createRoadSouth(PlotWorld plotworld, Plot plot); + /* + * Plot set functions (return false if you do not support the specific set + * method) + */ - public abstract boolean createRoadSouthEast(PlotWorld plotworld, Plot plot); + public abstract boolean setWall(Player player, PlotWorld plotworld, + PlotId plotid, PlotBlock block); - public abstract boolean removeRoadEast(PlotWorld plotworld, Plot plot); + public abstract boolean setFloor(Player player, PlotWorld plotworld, + PlotId plotid, PlotBlock[] block); - public abstract boolean removeRoadSouth(PlotWorld plotworld, Plot plot); + public abstract boolean setBiome(Player player, Plot plot, Biome biome); - public abstract boolean removeRoadSouthEast(PlotWorld plotworld, Plot plot); - - public abstract boolean finishPlotMerge(World world, PlotWorld plotworld, ArrayList plotIds); + /* + * PLOT MERGING (return false if your generator does not support plot + * merging) + */ + public abstract boolean createRoadEast(PlotWorld plotworld, Plot plot); + + public abstract boolean createRoadSouth(PlotWorld plotworld, Plot plot); + + public abstract boolean createRoadSouthEast(PlotWorld plotworld, Plot plot); + + public abstract boolean removeRoadEast(PlotWorld plotworld, Plot plot); + + public abstract boolean removeRoadSouth(PlotWorld plotworld, Plot plot); + + public abstract boolean removeRoadSouthEast(PlotWorld plotworld, Plot plot); + + public abstract boolean finishPlotMerge(World world, PlotWorld plotworld, + ArrayList plotIds); } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/PlotSettings.java b/PlotSquared/src/com/intellectualcrafters/plot/PlotSettings.java index 6d61526b5..e2b414456 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/PlotSettings.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/PlotSettings.java @@ -17,209 +17,209 @@ import org.bukkit.block.Biome; /** * plot settings - * + * * @author Citymonstret - * + * */ public class PlotSettings { - /** - * merged plots - */ - private boolean[] merged = new boolean[] { false, false, false, false }; - /** - * plot alias - */ - private String alias; - /** - * plot biome - */ - private Biome biome; - /** - * plot rain - */ - private boolean rain; - /** - * - */ - private Set flags; - /** - * plot time - */ - private Long time; - /** - * Change time? - */ - private boolean changeTime; - private PlotHomePosition position; + /** + * merged plots + */ + private boolean[] merged = new boolean[] { false, false, false, false }; + /** + * plot alias + */ + private String alias; + /** + * plot biome + */ + private Biome biome; + /** + * plot rain + */ + private boolean rain; + /** + * + */ + private Set flags; + /** + * plot time + */ + private Long time; + /** + * Change time? + */ + private boolean changeTime; + private PlotHomePosition position; - /** - * Constructor - * - * @param plot - */ - public PlotSettings(Plot plot) { - this.alias = ""; - } + /** + * Constructor + * + * @param plot + */ + public PlotSettings(Plot plot) { + this.alias = ""; + } - /** - * Check if the plot is merged in a direction
- * 0 = North
- * 1 = East
- * 2 = South
- * 3 = West
- * - * @param direction - * @return boolean - */ - public boolean getMerged(int direction) { - return this.merged[direction]; - } + /** + * Check if the plot is merged in a direction
+ * 0 = North
+ * 1 = East
+ * 2 = South
+ * 3 = West
+ * + * @param direction + * @return boolean + */ + public boolean getMerged(int direction) { + return this.merged[direction]; + } - public boolean isMerged() { - return (this.merged[0] || this.merged[1] || this.merged[2] || this.merged[3]); - } + public boolean isMerged() { + return (this.merged[0] || this.merged[1] || this.merged[2] || this.merged[3]); + } - public boolean[] getMerged() { - return this.merged; - } + public boolean[] getMerged() { + return this.merged; + } - public void setMerged(boolean[] merged) { - this.merged = merged; - } + public void setMerged(boolean[] merged) { + this.merged = merged; + } - public void setMerged(int direction, boolean merged) { - this.merged[direction] = merged; - } + public void setMerged(int direction, boolean merged) { + this.merged[direction] = merged; + } - /** - * - * @param b - */ - public void setBiome(Biome b) { - this.biome = b; - } + /** + * + * @param b + */ + public void setBiome(Biome b) { + this.biome = b; + } - /** - * - * @param b - */ - public void setTimeChange(boolean b) { - this.changeTime = b; - } + /** + * + * @param b + */ + public void setTimeChange(boolean b) { + this.changeTime = b; + } - /** - * - * @param l - */ - public void setTime(long l) { - this.time = l; - } + /** + * + * @param l + */ + public void setTime(long l) { + this.time = l; + } - /** - * - * @return - * @deprecated - */ - @Deprecated - public Biome getBiome() { - return this.biome; - } + /** + * + * @return + * @deprecated + */ + @Deprecated + public Biome getBiome() { + return this.biome; + } - /** - * - * @return - */ - public boolean getRain() { - return this.rain; - } + /** + * + * @return + */ + public boolean getRain() { + return this.rain; + } - public void setRain(boolean b) { - this.rain = b; - } + public void setRain(boolean b) { + this.rain = b; + } - /** - * - * @return - */ - public long getTime() { - return this.time; - } + /** + * + * @return + */ + public long getTime() { + return this.time; + } - /** - * - * @return - */ - public boolean getChangeTime() { - return this.changeTime; - } + /** + * + * @return + */ + public boolean getChangeTime() { + return this.changeTime; + } - /** - * - * @param alias - */ - public void setAlias(String alias) { - this.alias = alias; - } + /** + * + * @param alias + */ + public void setAlias(String alias) { + this.alias = alias; + } - /** - * - * @param flag - */ - public void addFlag(Flag flag) { - Flag hasFlag = getFlag(flag.getKey()); - if (hasFlag != null) { - this.flags.remove(hasFlag); - } - this.flags.add(flag); - } + /** + * + * @param flag + */ + public void addFlag(Flag flag) { + Flag hasFlag = getFlag(flag.getKey()); + if (hasFlag != null) { + this.flags.remove(hasFlag); + } + this.flags.add(flag); + } - /** - * - * @param flags - */ - public void setFlags(Flag[] flags) { - this.flags = new HashSet(Arrays.asList(flags)); - } + /** + * + * @param flags + */ + public void setFlags(Flag[] flags) { + this.flags = new HashSet(Arrays.asList(flags)); + } - /** - * - * @return - */ - public Set getFlags() { - return this.flags; - } + /** + * + * @return + */ + public Set getFlags() { + return this.flags; + } - /** - * - * @param flag - * @return - */ - public Flag getFlag(String flag) { - for (Flag myflag : this.flags) { - if (myflag.getKey().equals(flag)) { - return myflag; - } - } - return null; - } + /** + * + * @param flag + * @return + */ + public Flag getFlag(String flag) { + for (Flag myflag : this.flags) { + if (myflag.getKey().equals(flag)) { + return myflag; + } + } + return null; + } - public PlotHomePosition getPosition() { - return this.position; - } + public PlotHomePosition getPosition() { + return this.position; + } - public void setPosition(PlotHomePosition position) { - this.position = position; - } + public void setPosition(PlotHomePosition position) { + this.position = position; + } - public String getAlias() { - return this.alias; - } + public String getAlias() { + return this.alias; + } - public String getJoinMessage() { - return ""; - } + public String getJoinMessage() { + return ""; + } - public String getLeaveMessage() { - return ""; - } + public String getLeaveMessage() { + return ""; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/PlotSquaredException.java b/PlotSquared/src/com/intellectualcrafters/plot/PlotSquaredException.java index af84478f4..2de367dfd 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/PlotSquaredException.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/PlotSquaredException.java @@ -5,26 +5,27 @@ package com.intellectualcrafters.plot; */ public class PlotSquaredException extends RuntimeException { - public PlotSquaredException(PlotError error, String details) { - super("PlotError >> " + error.getHeader() + ": " + details); - PlotMain.sendConsoleSenderMessage("&cPlotError &6>> &c" + error.getHeader() + ": &6" + details); - } + public PlotSquaredException(PlotError error, String details) { + super("PlotError >> " + error.getHeader() + ": " + details); + PlotMain.sendConsoleSenderMessage("&cPlotError &6>> &c" + + error.getHeader() + ": &6" + details); + } - public static enum PlotError { - MISSING_DEPENDENCY("Missing Dependency"); - private String errorHeader; + public static enum PlotError { + MISSING_DEPENDENCY("Missing Dependency"); + private String errorHeader; - PlotError(String errorHeader) { - this.errorHeader = errorHeader; - } + PlotError(String errorHeader) { + this.errorHeader = errorHeader; + } - public String getHeader() { - return this.errorHeader; - } + public String getHeader() { + return this.errorHeader; + } - @Override - public String toString() { - return this.getHeader(); - } - } + @Override + public String toString() { + return this.getHeader(); + } + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/PlotWorld.java b/PlotSquared/src/com/intellectualcrafters/plot/PlotWorld.java index 2fa30c2b7..91c40772d 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/PlotWorld.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/PlotWorld.java @@ -1,109 +1,229 @@ package com.intellectualcrafters.plot; +import static org.bukkit.Material.ACACIA_STAIRS; +import static org.bukkit.Material.BEACON; +import static org.bukkit.Material.BEDROCK; +import static org.bukkit.Material.BIRCH_WOOD_STAIRS; +import static org.bukkit.Material.BOOKSHELF; +import static org.bukkit.Material.BREWING_STAND; +import static org.bukkit.Material.BRICK; +import static org.bukkit.Material.BRICK_STAIRS; +import static org.bukkit.Material.BURNING_FURNACE; +import static org.bukkit.Material.CAKE_BLOCK; +import static org.bukkit.Material.CAULDRON; +import static org.bukkit.Material.CLAY; +import static org.bukkit.Material.CLAY_BRICK; +import static org.bukkit.Material.COAL_BLOCK; +import static org.bukkit.Material.COAL_ORE; +import static org.bukkit.Material.COBBLESTONE; +import static org.bukkit.Material.COBBLESTONE_STAIRS; +import static org.bukkit.Material.COBBLE_WALL; +import static org.bukkit.Material.COMMAND; +import static org.bukkit.Material.DARK_OAK_STAIRS; +import static org.bukkit.Material.DAYLIGHT_DETECTOR; +import static org.bukkit.Material.DIAMOND_BLOCK; +import static org.bukkit.Material.DIAMOND_ORE; +import static org.bukkit.Material.DIRT; +import static org.bukkit.Material.DISPENSER; +import static org.bukkit.Material.DROPPER; +import static org.bukkit.Material.EMERALD_BLOCK; +import static org.bukkit.Material.EMERALD_ORE; +import static org.bukkit.Material.ENCHANTMENT_TABLE; +import static org.bukkit.Material.ENDER_PORTAL_FRAME; +import static org.bukkit.Material.ENDER_STONE; +import static org.bukkit.Material.FURNACE; +import static org.bukkit.Material.GLASS; +import static org.bukkit.Material.GLOWSTONE; +import static org.bukkit.Material.GOLD_BLOCK; +import static org.bukkit.Material.GOLD_ORE; +import static org.bukkit.Material.GRASS; +import static org.bukkit.Material.GRAVEL; +import static org.bukkit.Material.HARD_CLAY; +import static org.bukkit.Material.HAY_BLOCK; +import static org.bukkit.Material.HUGE_MUSHROOM_1; +import static org.bukkit.Material.HUGE_MUSHROOM_2; +import static org.bukkit.Material.IRON_BLOCK; +import static org.bukkit.Material.IRON_ORE; +import static org.bukkit.Material.JACK_O_LANTERN; +import static org.bukkit.Material.JUKEBOX; +import static org.bukkit.Material.JUNGLE_WOOD_STAIRS; +import static org.bukkit.Material.LAPIS_BLOCK; +import static org.bukkit.Material.LAPIS_ORE; +import static org.bukkit.Material.LEAVES; +import static org.bukkit.Material.LEAVES_2; +import static org.bukkit.Material.LOG; +import static org.bukkit.Material.LOG_2; +import static org.bukkit.Material.MELON_BLOCK; +import static org.bukkit.Material.MOB_SPAWNER; +import static org.bukkit.Material.MOSSY_COBBLESTONE; +import static org.bukkit.Material.MYCEL; +import static org.bukkit.Material.NETHERRACK; +import static org.bukkit.Material.NETHER_BRICK; +import static org.bukkit.Material.NETHER_BRICK_STAIRS; +import static org.bukkit.Material.NOTE_BLOCK; +import static org.bukkit.Material.OBSIDIAN; +import static org.bukkit.Material.PACKED_ICE; +import static org.bukkit.Material.PUMPKIN; +import static org.bukkit.Material.QUARTZ_BLOCK; +import static org.bukkit.Material.QUARTZ_ORE; +import static org.bukkit.Material.QUARTZ_STAIRS; +import static org.bukkit.Material.REDSTONE_BLOCK; +import static org.bukkit.Material.SAND; +import static org.bukkit.Material.SANDSTONE; +import static org.bukkit.Material.SANDSTONE_STAIRS; +import static org.bukkit.Material.SMOOTH_BRICK; +import static org.bukkit.Material.SMOOTH_STAIRS; +import static org.bukkit.Material.SNOW_BLOCK; +import static org.bukkit.Material.SOUL_SAND; +import static org.bukkit.Material.SPONGE; +import static org.bukkit.Material.SPRUCE_WOOD_STAIRS; +import static org.bukkit.Material.STONE; +import static org.bukkit.Material.WOOD; +import static org.bukkit.Material.WOOD_STAIRS; +import static org.bukkit.Material.WOOL; +import static org.bukkit.Material.WORKBENCH; +import static org.bukkit.Material.getMaterial; + import java.util.ArrayList; +import java.util.Arrays; import java.util.List; +import org.bukkit.Material; import org.bukkit.block.Biome; import org.bukkit.configuration.ConfigurationSection; + public abstract class PlotWorld { - - public boolean AUTO_MERGE; - public static boolean AUTO_MERGE_DEFAULT = false; - - public boolean MOB_SPAWNING; - public static boolean MOB_SPAWNING_DEFAULT = false; - - public Biome PLOT_BIOME; - public static Biome PLOT_BIOME_DEFAULT = Biome.FOREST; - - public boolean PLOT_CHAT; - public static boolean PLOT_CHAT_DEFAULT = false; - - public boolean SCHEMATIC_CLAIM_SPECIFY = false; - public static boolean SCHEMATIC_CLAIM_SPECIFY_DEFAULT = false; - - public boolean SCHEMATIC_ON_CLAIM; - public static boolean SCHEMATIC_ON_CLAIM_DEFAULT = false; - - public String SCHEMATIC_FILE; - public static String SCHEMATIC_FILE_DEFAULT = "null"; - - public List SCHEMATICS; - public static List SCHEMATICS_DEFAULT = null; - - public List DEFAULT_FLAGS; - public static List DEFAULT_FLAGS_DEFAULT = new ArrayList(); - - public boolean USE_ECONOMY; - public static boolean USE_ECONOMY_DEFAULT = false; - - public double PLOT_PRICE; - public static double PLOT_PRICE_DEFAULT = 100; - - public double MERGE_PRICE; - public static double MERGE_PRICE_DEFAULT = 100; - public PlotWorld(String worldname) { - this.worldname = worldname; - } - - /** - * When a world is created, the following method will be called for each node set in the configuration - * - You may ignore this if you generator does not support configuration, or if you want to implement your own methods - * - * @param key - * @param value - */ - public void loadConfiguration(ConfigurationSection config) { - this.MOB_SPAWNING = config.getBoolean("natural_mob_spawning"); - this.AUTO_MERGE = config.getBoolean("plot.auto_merge"); - this.PLOT_BIOME = (Biome) Configuration.BIOME.parseString(config.getString("plot.biome")); - this.SCHEMATIC_ON_CLAIM = config.getBoolean("schematic.on_claim"); - this.SCHEMATIC_FILE = config.getString("schematic.file"); - this.SCHEMATIC_CLAIM_SPECIFY = config.getBoolean("schematic.specify_on_claim"); - this.SCHEMATICS = config.getStringList("schematic.schematics"); - this.USE_ECONOMY = config.getBoolean("economy.use"); - this.PLOT_PRICE = config.getDouble("economy.prices.claim"); - this.MERGE_PRICE = config.getDouble("economy.prices.merge"); - this.PLOT_CHAT = config.getBoolean("chat.enabled"); - this.DEFAULT_FLAGS = config.getStringList("flags.default"); - } - - public void saveConfiguration(ConfigurationSection config) { - - /* - * Saving core plotworld settings - */ - config.set("natural_mob_spawning",this.MOB_SPAWNING); - config.set("plot.auto_merge",this.AUTO_MERGE); - config.set("plot.biome",this.PLOT_BIOME.name()); - config.set("schematic.on_claim",this.SCHEMATIC_ON_CLAIM); - config.set("schematic.file",this.SCHEMATIC_FILE); - config.set("schematic.specify_on_claim",this.SCHEMATIC_CLAIM_SPECIFY); - config.set("schematic.schematics",this.SCHEMATICS); - config.set("economy.use",this.USE_ECONOMY); - config.set("economy.prices.claim",this.PLOT_PRICE); - config.set("economy.prices.merge",this.MERGE_PRICE); - config.set("chat.enabled",this.PLOT_CHAT); - config.set("flags.default",this.DEFAULT_FLAGS); - - ConfigurationNode[] settings = getSettingNodes(); - - /* - * Saving generator specific settings - */ - for (ConfigurationNode setting:settings) { - config.set(setting.getConstant(), setting.getValue()); - } - } - - public String worldname; + // TODO make this configurable + // make non static and static_default_valu + add config option + public static ArrayList BLOCKS = new ArrayList( + Arrays.asList(new Material[] { ACACIA_STAIRS, BEACON, BEDROCK, + BIRCH_WOOD_STAIRS, BOOKSHELF, BREWING_STAND, BRICK, + BRICK_STAIRS, BURNING_FURNACE, CAKE_BLOCK, CAULDRON, + CLAY_BRICK, CLAY, COAL_BLOCK, COAL_ORE, COBBLE_WALL, + COBBLESTONE, COBBLESTONE_STAIRS, COMMAND, DARK_OAK_STAIRS, + DAYLIGHT_DETECTOR, DIAMOND_ORE, DIAMOND_BLOCK, DIRT, + DISPENSER, DROPPER, EMERALD_BLOCK, EMERALD_ORE, + ENCHANTMENT_TABLE, ENDER_PORTAL_FRAME, ENDER_STONE, + FURNACE, GLOWSTONE, GOLD_ORE, GOLD_BLOCK, GRASS, GRAVEL, + GLASS, HARD_CLAY, HAY_BLOCK, HUGE_MUSHROOM_1, + HUGE_MUSHROOM_2, IRON_BLOCK, IRON_ORE, JACK_O_LANTERN, + JUKEBOX, JUNGLE_WOOD_STAIRS, LAPIS_BLOCK, LAPIS_ORE, + LEAVES, LEAVES_2, LOG, LOG_2, MELON_BLOCK, MOB_SPAWNER, + MOSSY_COBBLESTONE, MYCEL, NETHER_BRICK, + NETHER_BRICK_STAIRS, NETHERRACK, NOTE_BLOCK, OBSIDIAN, + PACKED_ICE, PUMPKIN, QUARTZ_BLOCK, QUARTZ_ORE, + QUARTZ_STAIRS, REDSTONE_BLOCK, SANDSTONE, SAND, + SANDSTONE_STAIRS, SMOOTH_BRICK, SMOOTH_STAIRS, SNOW_BLOCK, + SOUL_SAND, SPONGE, SPRUCE_WOOD_STAIRS, STONE, WOOD, + WOOD_STAIRS, WORKBENCH, WOOL, getMaterial(44), + getMaterial(126) })); - /** - * Used for the /plot setup command - * Return null if you do not want to support this feature - * - * @return ConfigurationNode[] - */ - public abstract ConfigurationNode[] getSettingNodes(); + public boolean AUTO_MERGE; + public static boolean AUTO_MERGE_DEFAULT = false; + + public boolean MOB_SPAWNING; + public static boolean MOB_SPAWNING_DEFAULT = false; + + public Biome PLOT_BIOME; + public static Biome PLOT_BIOME_DEFAULT = Biome.FOREST; + + public boolean PLOT_CHAT; + public static boolean PLOT_CHAT_DEFAULT = false; + + public boolean SCHEMATIC_CLAIM_SPECIFY = false; + public static boolean SCHEMATIC_CLAIM_SPECIFY_DEFAULT = false; + + public boolean SCHEMATIC_ON_CLAIM; + public static boolean SCHEMATIC_ON_CLAIM_DEFAULT = false; + + public String SCHEMATIC_FILE; + public static String SCHEMATIC_FILE_DEFAULT = "null"; + + public List SCHEMATICS; + public static List SCHEMATICS_DEFAULT = null; + + public List DEFAULT_FLAGS; + public static List DEFAULT_FLAGS_DEFAULT = new ArrayList(); + + public boolean USE_ECONOMY; + public static boolean USE_ECONOMY_DEFAULT = false; + + public double PLOT_PRICE; + public static double PLOT_PRICE_DEFAULT = 100; + + public double MERGE_PRICE; + public static double MERGE_PRICE_DEFAULT = 100; + + public double SELL_PRICE; + public static double SELL_PRICE_DEFAULT = 75; + + public PlotWorld(String worldname) { + this.worldname = worldname; + } + + /** + * When a world is created, the following method will be called for each + * node set in the configuration - You may ignore this if you generator does + * not support configuration, or if you want to implement your own methods + * + * @param key + * @param value + */ + public void loadConfiguration(ConfigurationSection config) { + this.MOB_SPAWNING = config.getBoolean("natural_mob_spawning"); + this.AUTO_MERGE = config.getBoolean("plot.auto_merge"); + this.PLOT_BIOME = (Biome) Configuration.BIOME.parseString(config + .getString("plot.biome")); + this.SCHEMATIC_ON_CLAIM = config.getBoolean("schematic.on_claim"); + this.SCHEMATIC_FILE = config.getString("schematic.file"); + this.SCHEMATIC_CLAIM_SPECIFY = config + .getBoolean("schematic.specify_on_claim"); + this.SCHEMATICS = config.getStringList("schematic.schematics"); + this.USE_ECONOMY = config.getBoolean("economy.use"); + this.PLOT_PRICE = config.getDouble("economy.prices.claim"); + this.MERGE_PRICE = config.getDouble("economy.prices.merge"); + this.SELL_PRICE = config.getDouble("economy.prices.sell"); + this.PLOT_CHAT = config.getBoolean("chat.enabled"); + this.DEFAULT_FLAGS = config.getStringList("flags.default"); + } + + public void saveConfiguration(ConfigurationSection config) { + + /* + * Saving core plotworld settings + */ + config.set("natural_mob_spawning", this.MOB_SPAWNING); + config.set("plot.auto_merge", this.AUTO_MERGE); + config.set("plot.biome", this.PLOT_BIOME.name()); + config.set("schematic.on_claim", this.SCHEMATIC_ON_CLAIM); + config.set("schematic.file", this.SCHEMATIC_FILE); + config.set("schematic.specify_on_claim", this.SCHEMATIC_CLAIM_SPECIFY); + config.set("schematic.schematics", this.SCHEMATICS); + config.set("economy.use", this.USE_ECONOMY); + config.set("economy.prices.claim", this.PLOT_PRICE); + config.set("economy.prices.merge", this.MERGE_PRICE); + config.set("economy.prices.sell", this.SELL_PRICE); + config.set("chat.enabled", this.PLOT_CHAT); + config.set("flags.default", this.DEFAULT_FLAGS); + + ConfigurationNode[] settings = getSettingNodes(); + + /* + * Saving generator specific settings + */ + for (ConfigurationNode setting : settings) { + config.set(setting.getConstant(), setting.getValue()); + } + } + + public String worldname; + + /** + * Used for the /plot setup command Return null if you do not want to + * support this feature + * + * @return ConfigurationNode[] + */ + public abstract ConfigurationNode[] getSettingNodes(); } \ No newline at end of file diff --git a/PlotSquared/src/com/intellectualcrafters/plot/RUtils.java b/PlotSquared/src/com/intellectualcrafters/plot/RUtils.java index 867be0378..427e0fad5 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/RUtils.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/RUtils.java @@ -14,76 +14,77 @@ import org.bukkit.entity.Player; /** * Random utilities - * + * * @author Citymonstret - * + * */ public class RUtils { - public static long getTotalRam() { - return (Runtime.getRuntime().maxMemory() / 1024) / 1024; - } + public static long getTotalRam() { + return (Runtime.getRuntime().maxMemory() / 1024) / 1024; + } - public static long getFreeRam() { - return (Runtime.getRuntime().freeMemory() / 1024) / 1024; - } + public static long getFreeRam() { + return (Runtime.getRuntime().freeMemory() / 1024) / 1024; + } - public static long getRamPercentage() { - return (getFreeRam() / getTotalRam()) * 100; - } + public static long getRamPercentage() { + return (getFreeRam() / getTotalRam()) * 100; + } - public static String formatTime(double sec) { - double h = sec / 3600; - double m = (sec % 3600) / 60; - double s = sec % 60; - String string = C.TIME_FORMAT.s(); + public static String formatTime(double sec) { + double h = sec / 3600; + double m = (sec % 3600) / 60; + double s = sec % 60; + String string = C.TIME_FORMAT.s(); - @SuppressWarnings("unused") - // String s_d = (int) d + " " + (d != 1 ? "days" : "day"); - String s_h = (int) h + " " + ((int) h != 1 ? "hours" : "hour"); - String s_m = (int) m + " " + ((int) m != 1 ? "minutes" : "minute"); - String s_s = (int) s + " " + ((int) s != 1 ? "seconds" : "second"); - return string.replaceAll("%sec%", s_s).replaceAll("%min%", s_m).replaceAll("%hours%", s_h); - } + @SuppressWarnings("unused") + // String s_d = (int) d + " " + (d != 1 ? "days" : "day"); + String s_h = (int) h + " " + ((int) h != 1 ? "hours" : "hour"); + String s_m = (int) m + " " + ((int) m != 1 ? "minutes" : "minute"); + String s_s = (int) s + " " + ((int) s != 1 ? "seconds" : "second"); + return string.replaceAll("%sec%", s_s).replaceAll("%min%", s_m) + .replaceAll("%hours%", s_h); + } - enum Direction { - SOUTH(0), EAST(1), NORTH(2), WEST(3); - private int i; + enum Direction { + SOUTH(0), EAST(1), NORTH(2), WEST(3); + private int i; - Direction(int i) { - this.i = i; - } + Direction(int i) { + this.i = i; + } - public int getInt() { - return this.i; - } - } + public int getInt() { + return this.i; + } + } - public void forceTexture(Player p) { - p.setResourcePack(Settings.PLOT_SPECIFIC_RESOURCE_PACK); - } + public void forceTexture(Player p) { + p.setResourcePack(Settings.PLOT_SPECIFIC_RESOURCE_PACK); + } - public Direction getDirection(Location l) { - double d = ((l.getYaw() * 4.0F) / 360.0F) + 0.5D; - int i = (int) d; - int x = d < i ? i - 1 : i; + public Direction getDirection(Location l) { + double d = ((l.getYaw() * 4.0F) / 360.0F) + 0.5D; + int i = (int) d; + int x = d < i ? i - 1 : i; - switch (x) { - case 0: - return Direction.SOUTH; - case 1: - return Direction.EAST; - case 2: - return Direction.NORTH; - case 3: - return Direction.WEST; - default: - return null; - } - } + switch (x) { + case 0: + return Direction.SOUTH; + case 1: + return Direction.EAST; + case 2: + return Direction.NORTH; + case 3: + return Direction.WEST; + default: + return null; + } + } - public boolean compareDirections(Location l1, Location l2) { - return getDirection(l1) == getDirection(l2); - } + public boolean compareDirections(Location l1, Location l2) { + return getDirection(l1) == getDirection(l2); + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/ReflectionUtils.java b/PlotSquared/src/com/intellectualcrafters/plot/ReflectionUtils.java index 086464566..e9796b46f 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/ReflectionUtils.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/ReflectionUtils.java @@ -17,555 +17,564 @@ import org.bukkit.Server; @SuppressWarnings({ "UnusedDeclaration", "rawtypes" }) public class ReflectionUtils { - /** prefix of bukkit classes */ - private static String preClassB = "org.bukkit.craftbukkit"; - /** prefix of minecraft classes */ - private static String preClassM = "net.minecraft.server"; - /** boolean value, TRUE if server uses forge or MCPC+ */ - private static boolean forge = false; + /** prefix of bukkit classes */ + private static String preClassB = "org.bukkit.craftbukkit"; + /** prefix of minecraft classes */ + private static String preClassM = "net.minecraft.server"; + /** boolean value, TRUE if server uses forge or MCPC+ */ + private static boolean forge = false; - /** check server version and class names */ - static { - if (Bukkit.getServer() != null) { - if (Bukkit.getVersion().contains("MCPC") || Bukkit.getVersion().contains("Forge")) { - forge = true; - } - Server server = Bukkit.getServer(); - Class bukkitServerClass = server.getClass(); - String[] pas = bukkitServerClass.getName().split("\\."); - if (pas.length == 5) { - String verB = pas[3]; - preClassB += "." + verB; - } - try { - Method getHandle = bukkitServerClass.getDeclaredMethod("getHandle"); - Object handle = getHandle.invoke(server); - Class handleServerClass = handle.getClass(); - pas = handleServerClass.getName().split("\\."); - if (pas.length == 5) { - String verM = pas[3]; - preClassM += "." + verM; - } - } catch (Exception ignored) { - } - } - } + /** check server version and class names */ + static { + if (Bukkit.getServer() != null) { + if (Bukkit.getVersion().contains("MCPC") + || Bukkit.getVersion().contains("Forge")) { + forge = true; + } + Server server = Bukkit.getServer(); + Class bukkitServerClass = server.getClass(); + String[] pas = bukkitServerClass.getName().split("\\."); + if (pas.length == 5) { + String verB = pas[3]; + preClassB += "." + verB; + } + try { + Method getHandle = bukkitServerClass + .getDeclaredMethod("getHandle"); + Object handle = getHandle.invoke(server); + Class handleServerClass = handle.getClass(); + pas = handleServerClass.getName().split("\\."); + if (pas.length == 5) { + String verM = pas[3]; + preClassM += "." + verM; + } + } catch (Exception ignored) { + } + } + } - /** - * @return true if server has forge classes - */ - public static boolean isForge() { - return forge; - } + /** + * @return true if server has forge classes + */ + public static boolean isForge() { + return forge; + } - /** - * Get class for name. Replace {nms} to net.minecraft.server.V*. Replace - * {cb} to org.bukkit.craftbukkit.V*. Replace {nm} to net.minecraft - * - * @param classes - * possible class paths - * @return RefClass object - * @throws RuntimeException - * if no class found - */ - public static RefClass getRefClass(String... classes) { - for (String className : classes) { - try { - className = className.replace("{cb}", preClassB).replace("{nms}", preClassM).replace("{nm}", "net.minecraft"); - return getRefClass(Class.forName(className)); - } catch (ClassNotFoundException ignored) { - } - } - throw new RuntimeException("no class found"); - } + /** + * Get class for name. Replace {nms} to net.minecraft.server.V*. Replace + * {cb} to org.bukkit.craftbukkit.V*. Replace {nm} to net.minecraft + * + * @param classes + * possible class paths + * @return RefClass object + * @throws RuntimeException + * if no class found + */ + public static RefClass getRefClass(String... classes) { + for (String className : classes) { + try { + className = className.replace("{cb}", preClassB) + .replace("{nms}", preClassM) + .replace("{nm}", "net.minecraft"); + return getRefClass(Class.forName(className)); + } catch (ClassNotFoundException ignored) { + } + } + throw new RuntimeException("no class found"); + } - /** - * get RefClass object by real class - * - * @param clazz - * class - * @return RefClass based on passed class - */ - public static RefClass getRefClass(Class clazz) { - return new RefClass(clazz); - } + /** + * get RefClass object by real class + * + * @param clazz + * class + * @return RefClass based on passed class + */ + public static RefClass getRefClass(Class clazz) { + return new RefClass(clazz); + } - /** - * RefClass - utility to simplify work with reflections. - */ - public static class RefClass { - private final Class clazz; + /** + * RefClass - utility to simplify work with reflections. + */ + public static class RefClass { + private final Class clazz; - /** - * get passed class - * - * @return class - */ - public Class getRealClass() { - return this.clazz; - } + /** + * get passed class + * + * @return class + */ + public Class getRealClass() { + return this.clazz; + } - private RefClass(Class clazz) { - this.clazz = clazz; - } + private RefClass(Class clazz) { + this.clazz = clazz; + } - /** - * see {@link Class#isInstance(Object)} - * - * @param object - * the object to check - * @return true if object is an instance of this class - */ - public boolean isInstance(Object object) { - return this.clazz.isInstance(object); - } + /** + * see {@link Class#isInstance(Object)} + * + * @param object + * the object to check + * @return true if object is an instance of this class + */ + public boolean isInstance(Object object) { + return this.clazz.isInstance(object); + } - /** - * get existing method by name and types - * - * @param name - * name - * @param types - * method parameters. can be Class or RefClass - * @return RefMethod object - * @throws RuntimeException - * if method not found - */ - public RefMethod getMethod(String name, Object... types) throws NoSuchMethodException { - try { - Class[] classes = new Class[types.length]; - int i = 0; - for (Object e : types) { - if (e instanceof Class) { - classes[i++] = (Class) e; - } else if (e instanceof RefClass) { - classes[i++] = ((RefClass) e).getRealClass(); - } else { - classes[i++] = e.getClass(); - } - } - try { - return new RefMethod(this.clazz.getMethod(name, classes)); - } catch (NoSuchMethodException ignored) { - return new RefMethod(this.clazz.getDeclaredMethod(name, classes)); - } - } catch (Exception e) { - throw new RuntimeException(e); - } - } + /** + * get existing method by name and types + * + * @param name + * name + * @param types + * method parameters. can be Class or RefClass + * @return RefMethod object + * @throws RuntimeException + * if method not found + */ + public RefMethod getMethod(String name, Object... types) + throws NoSuchMethodException { + try { + Class[] classes = new Class[types.length]; + int i = 0; + for (Object e : types) { + if (e instanceof Class) { + classes[i++] = (Class) e; + } else if (e instanceof RefClass) { + classes[i++] = ((RefClass) e).getRealClass(); + } else { + classes[i++] = e.getClass(); + } + } + try { + return new RefMethod(this.clazz.getMethod(name, classes)); + } catch (NoSuchMethodException ignored) { + return new RefMethod(this.clazz.getDeclaredMethod(name, + classes)); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } - /** - * get existing constructor by types - * - * @param types - * parameters. can be Class or RefClass - * @return RefMethod object - * @throws RuntimeException - * if constructor not found - */ - public RefConstructor getConstructor(Object... types) { - try { - Class[] classes = new Class[types.length]; - int i = 0; - for (Object e : types) { - if (e instanceof Class) { - classes[i++] = (Class) e; - } else if (e instanceof RefClass) { - classes[i++] = ((RefClass) e).getRealClass(); - } else { - classes[i++] = e.getClass(); - } - } - try { - return new RefConstructor(this.clazz.getConstructor(classes)); - } catch (NoSuchMethodException ignored) { - return new RefConstructor(this.clazz.getDeclaredConstructor(classes)); - } - } catch (Exception e) { - throw new RuntimeException(e); - } - } + /** + * get existing constructor by types + * + * @param types + * parameters. can be Class or RefClass + * @return RefMethod object + * @throws RuntimeException + * if constructor not found + */ + public RefConstructor getConstructor(Object... types) { + try { + Class[] classes = new Class[types.length]; + int i = 0; + for (Object e : types) { + if (e instanceof Class) { + classes[i++] = (Class) e; + } else if (e instanceof RefClass) { + classes[i++] = ((RefClass) e).getRealClass(); + } else { + classes[i++] = e.getClass(); + } + } + try { + return new RefConstructor( + this.clazz.getConstructor(classes)); + } catch (NoSuchMethodException ignored) { + return new RefConstructor( + this.clazz.getDeclaredConstructor(classes)); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } - /** - * find method by type parameters - * - * @param types - * parameters. can be Class or RefClass - * @return RefMethod object - * @throws RuntimeException - * if method not found - */ - public RefMethod findMethod(Object... types) { - Class[] classes = new Class[types.length]; - int t = 0; - for (Object e : types) { - if (e instanceof Class) { - classes[t++] = (Class) e; - } else if (e instanceof RefClass) { - classes[t++] = ((RefClass) e).getRealClass(); - } else { - classes[t++] = e.getClass(); - } - } - List methods = new ArrayList<>(); - Collections.addAll(methods, this.clazz.getMethods()); - Collections.addAll(methods, this.clazz.getDeclaredMethods()); - findMethod: for (Method m : methods) { - Class[] methodTypes = m.getParameterTypes(); - if (methodTypes.length != classes.length) { - continue; - } - for (int i = 0; i < classes.length; i++) { - if (!classes.equals(methodTypes)) { - continue findMethod; - } - return new RefMethod(m); - } - } - throw new RuntimeException("no such method"); - } + /** + * find method by type parameters + * + * @param types + * parameters. can be Class or RefClass + * @return RefMethod object + * @throws RuntimeException + * if method not found + */ + public RefMethod findMethod(Object... types) { + Class[] classes = new Class[types.length]; + int t = 0; + for (Object e : types) { + if (e instanceof Class) { + classes[t++] = (Class) e; + } else if (e instanceof RefClass) { + classes[t++] = ((RefClass) e).getRealClass(); + } else { + classes[t++] = e.getClass(); + } + } + List methods = new ArrayList<>(); + Collections.addAll(methods, this.clazz.getMethods()); + Collections.addAll(methods, this.clazz.getDeclaredMethods()); + findMethod: for (Method m : methods) { + Class[] methodTypes = m.getParameterTypes(); + if (methodTypes.length != classes.length) { + continue; + } + for (int i = 0; i < classes.length; i++) { + if (!classes.equals(methodTypes)) { + continue findMethod; + } + return new RefMethod(m); + } + } + throw new RuntimeException("no such method"); + } - /** - * find method by name - * - * @param names - * possible names of method - * @return RefMethod object - * @throws RuntimeException - * if method not found - */ - public RefMethod findMethodByName(String... names) { - List methods = new ArrayList<>(); - Collections.addAll(methods, this.clazz.getMethods()); - Collections.addAll(methods, this.clazz.getDeclaredMethods()); - for (Method m : methods) { - for (String name : names) { - if (m.getName().equals(name)) { - return new RefMethod(m); - } - } - } - throw new RuntimeException("no such method"); - } + /** + * find method by name + * + * @param names + * possible names of method + * @return RefMethod object + * @throws RuntimeException + * if method not found + */ + public RefMethod findMethodByName(String... names) { + List methods = new ArrayList<>(); + Collections.addAll(methods, this.clazz.getMethods()); + Collections.addAll(methods, this.clazz.getDeclaredMethods()); + for (Method m : methods) { + for (String name : names) { + if (m.getName().equals(name)) { + return new RefMethod(m); + } + } + } + throw new RuntimeException("no such method"); + } - /** - * find method by return value - * - * @param type - * type of returned value - * @throws RuntimeException - * if method not found - * @return RefMethod - */ - public RefMethod findMethodByReturnType(RefClass type) { - return findMethodByReturnType(type.clazz); - } + /** + * find method by return value + * + * @param type + * type of returned value + * @throws RuntimeException + * if method not found + * @return RefMethod + */ + public RefMethod findMethodByReturnType(RefClass type) { + return findMethodByReturnType(type.clazz); + } - /** - * find method by return value - * - * @param type - * type of returned value - * @return RefMethod - * @throws RuntimeException - * if method not found - */ - public RefMethod findMethodByReturnType(Class type) { - if (type == null) { - type = void.class; - } - List methods = new ArrayList<>(); - Collections.addAll(methods, this.clazz.getMethods()); - Collections.addAll(methods, this.clazz.getDeclaredMethods()); - for (Method m : methods) { - if (type.equals(m.getReturnType())) { - return new RefMethod(m); - } - } - throw new RuntimeException("no such method"); - } + /** + * find method by return value + * + * @param type + * type of returned value + * @return RefMethod + * @throws RuntimeException + * if method not found + */ + public RefMethod findMethodByReturnType(Class type) { + if (type == null) { + type = void.class; + } + List methods = new ArrayList<>(); + Collections.addAll(methods, this.clazz.getMethods()); + Collections.addAll(methods, this.clazz.getDeclaredMethods()); + for (Method m : methods) { + if (type.equals(m.getReturnType())) { + return new RefMethod(m); + } + } + throw new RuntimeException("no such method"); + } - /** - * find constructor by number of arguments - * - * @param number - * number of arguments - * @return RefConstructor - * @throws RuntimeException - * if constructor not found - */ - public RefConstructor findConstructor(int number) { - List constructors = new ArrayList<>(); - Collections.addAll(constructors, this.clazz.getConstructors()); - Collections.addAll(constructors, this.clazz.getDeclaredConstructors()); - for (Constructor m : constructors) { - if (m.getParameterTypes().length == number) { - return new RefConstructor(m); - } - } - throw new RuntimeException("no such constructor"); - } + /** + * find constructor by number of arguments + * + * @param number + * number of arguments + * @return RefConstructor + * @throws RuntimeException + * if constructor not found + */ + public RefConstructor findConstructor(int number) { + List constructors = new ArrayList<>(); + Collections.addAll(constructors, this.clazz.getConstructors()); + Collections.addAll(constructors, + this.clazz.getDeclaredConstructors()); + for (Constructor m : constructors) { + if (m.getParameterTypes().length == number) { + return new RefConstructor(m); + } + } + throw new RuntimeException("no such constructor"); + } - /** - * get field by name - * - * @param name - * field name - * @return RefField - * @throws RuntimeException - * if field not found - */ - public RefField getField(String name) { - try { - try { - return new RefField(this.clazz.getField(name)); - } catch (NoSuchFieldException ignored) { - return new RefField(this.clazz.getDeclaredField(name)); - } - } catch (Exception e) { - throw new RuntimeException(e); - } - } + /** + * get field by name + * + * @param name + * field name + * @return RefField + * @throws RuntimeException + * if field not found + */ + public RefField getField(String name) { + try { + try { + return new RefField(this.clazz.getField(name)); + } catch (NoSuchFieldException ignored) { + return new RefField(this.clazz.getDeclaredField(name)); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } - /** - * find field by type - * - * @param type - * field type - * @return RefField - * @throws RuntimeException - * if field not found - */ - public RefField findField(RefClass type) { - return findField(type.clazz); - } + /** + * find field by type + * + * @param type + * field type + * @return RefField + * @throws RuntimeException + * if field not found + */ + public RefField findField(RefClass type) { + return findField(type.clazz); + } - /** - * find field by type - * - * @param type - * field type - * @return RefField - * @throws RuntimeException - * if field not found - */ - public RefField findField(Class type) { - if (type == null) { - type = void.class; - } - List fields = new ArrayList<>(); - Collections.addAll(fields, this.clazz.getFields()); - Collections.addAll(fields, this.clazz.getDeclaredFields()); - for (Field f : fields) { - if (type.equals(f.getType())) { - return new RefField(f); - } - } - throw new RuntimeException("no such field"); - } - } + /** + * find field by type + * + * @param type + * field type + * @return RefField + * @throws RuntimeException + * if field not found + */ + public RefField findField(Class type) { + if (type == null) { + type = void.class; + } + List fields = new ArrayList<>(); + Collections.addAll(fields, this.clazz.getFields()); + Collections.addAll(fields, this.clazz.getDeclaredFields()); + for (Field f : fields) { + if (type.equals(f.getType())) { + return new RefField(f); + } + } + throw new RuntimeException("no such field"); + } + } - /** - * Method wrapper - */ - public static class RefMethod { - private final Method method; + /** + * Method wrapper + */ + public static class RefMethod { + private final Method method; - /** - * @return passed method - */ - public Method getRealMethod() { - return this.method; - } + /** + * @return passed method + */ + public Method getRealMethod() { + return this.method; + } - /** - * @return owner class of method - */ - public RefClass getRefClass() { - return new RefClass(this.method.getDeclaringClass()); - } + /** + * @return owner class of method + */ + public RefClass getRefClass() { + return new RefClass(this.method.getDeclaringClass()); + } - /** - * @return class of method return type - */ - public RefClass getReturnRefClass() { - return new RefClass(this.method.getReturnType()); - } + /** + * @return class of method return type + */ + public RefClass getReturnRefClass() { + return new RefClass(this.method.getReturnType()); + } - private RefMethod(Method method) { - this.method = method; - method.setAccessible(true); - } + private RefMethod(Method method) { + this.method = method; + method.setAccessible(true); + } - /** - * apply method to object - * - * @param e - * object to which the method is applied - * @return RefExecutor with method call(...) - */ - public RefExecutor of(Object e) { - return new RefExecutor(e); - } + /** + * apply method to object + * + * @param e + * object to which the method is applied + * @return RefExecutor with method call(...) + */ + public RefExecutor of(Object e) { + return new RefExecutor(e); + } - /** - * call static method - * - * @param params - * sent parameters - * @return return value - */ - public Object call(Object... params) { - try { - return this.method.invoke(null, params); - } catch (Exception e) { - throw new RuntimeException(e); - } - } + /** + * call static method + * + * @param params + * sent parameters + * @return return value + */ + public Object call(Object... params) { + try { + return this.method.invoke(null, params); + } catch (Exception e) { + throw new RuntimeException(e); + } + } - public class RefExecutor { - Object e; + public class RefExecutor { + Object e; - public RefExecutor(Object e) { - this.e = e; - } + public RefExecutor(Object e) { + this.e = e; + } - /** - * apply method for selected object - * - * @param params - * sent parameters - * @return return value - * @throws RuntimeException - * if something went wrong - */ - public Object call(Object... params) { - try { - return RefMethod.this.method.invoke(this.e, params); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - } - } + /** + * apply method for selected object + * + * @param params + * sent parameters + * @return return value + * @throws RuntimeException + * if something went wrong + */ + public Object call(Object... params) { + try { + return RefMethod.this.method.invoke(this.e, params); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + } + } - /** - * Constructor wrapper - */ - public static class RefConstructor { - private final Constructor constructor; + /** + * Constructor wrapper + */ + public static class RefConstructor { + private final Constructor constructor; - /** - * @return passed constructor - */ - public Constructor getRealConstructor() { - return this.constructor; - } + /** + * @return passed constructor + */ + public Constructor getRealConstructor() { + return this.constructor; + } - /** - * @return owner class of method - */ - public RefClass getRefClass() { - return new RefClass(this.constructor.getDeclaringClass()); - } + /** + * @return owner class of method + */ + public RefClass getRefClass() { + return new RefClass(this.constructor.getDeclaringClass()); + } - private RefConstructor(Constructor constructor) { - this.constructor = constructor; - constructor.setAccessible(true); - } + private RefConstructor(Constructor constructor) { + this.constructor = constructor; + constructor.setAccessible(true); + } - /** - * create new instance with constructor - * - * @param params - * parameters for constructor - * @return new object - * @throws RuntimeException - * if something went wrong - */ - public Object create(Object... params) { - try { - return this.constructor.newInstance(params); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - } + /** + * create new instance with constructor + * + * @param params + * parameters for constructor + * @return new object + * @throws RuntimeException + * if something went wrong + */ + public Object create(Object... params) { + try { + return this.constructor.newInstance(params); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + } - public static class RefField { - private Field field; + public static class RefField { + private Field field; - /** - * @return passed field - */ - public Field getRealField() { - return this.field; - } + /** + * @return passed field + */ + public Field getRealField() { + return this.field; + } - /** - * @return owner class of field - */ - public RefClass getRefClass() { - return new RefClass(this.field.getDeclaringClass()); - } + /** + * @return owner class of field + */ + public RefClass getRefClass() { + return new RefClass(this.field.getDeclaringClass()); + } - /** - * @return type of field - */ - public RefClass getFieldRefClass() { - return new RefClass(this.field.getType()); - } + /** + * @return type of field + */ + public RefClass getFieldRefClass() { + return new RefClass(this.field.getType()); + } - private RefField(Field field) { - this.field = field; - field.setAccessible(true); - } + private RefField(Field field) { + this.field = field; + field.setAccessible(true); + } - /** - * apply fiend for object - * - * @param e - * applied object - * @return RefExecutor with getter and setter - */ - public RefExecutor of(Object e) { - return new RefExecutor(e); - } + /** + * apply fiend for object + * + * @param e + * applied object + * @return RefExecutor with getter and setter + */ + public RefExecutor of(Object e) { + return new RefExecutor(e); + } - public class RefExecutor { - Object e; + public class RefExecutor { + Object e; - public RefExecutor(Object e) { - this.e = e; - } + public RefExecutor(Object e) { + this.e = e; + } - /** - * set field value for applied object - * - * @param param - * value - */ - public void set(Object param) { - try { - RefField.this.field.set(this.e, param); - } catch (Exception e) { - throw new RuntimeException(e); - } - } + /** + * set field value for applied object + * + * @param param + * value + */ + public void set(Object param) { + try { + RefField.this.field.set(this.e, param); + } catch (Exception e) { + throw new RuntimeException(e); + } + } - /** - * get field value for applied object - * - * @return value of field - */ - public Object get() { - try { - return RefField.this.field.get(this.e); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - } - } + /** + * get field value for applied object + * + * @return value of field + */ + public Object get() { + try { + return RefField.this.field.get(this.e); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + } + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/SchematicHandler.java b/PlotSquared/src/com/intellectualcrafters/plot/SchematicHandler.java index 70eae2e8a..bcfc377f5 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/SchematicHandler.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/SchematicHandler.java @@ -24,154 +24,166 @@ import com.sk89q.worldedit.bukkit.BukkitWorld; */ public class SchematicHandler { - @SuppressWarnings("deprecation") - public boolean paste(Location location, Schematic schematic, Plot plot) { - if (schematic == null) { - PlotMain.sendConsoleSenderMessage("Schematic == null :|"); - return false; - } - try { - EditSession session = new EditSession(new BukkitWorld(location.getWorld()), 999999999); - CuboidClipboard clipboard = CuboidClipboard.loadSchematic(schematic.getFile()); - Location l1 = PlotHelper.getPlotBottomLoc(plot.getWorld(), plot.getId()); - PlotHelper.getPlotTopLoc(plot.getWorld(), plot.getId()); - int x = l1.getBlockX() + 1; - int z = l1.getBlockZ() + 1; - int y = location.getWorld().getHighestBlockYAt(x,z); - Vector v1 = new Vector(x, y+1, z); - clipboard.paste(session, v1, true); - } catch (Exception e) { - return false; - } - return true; - } + @SuppressWarnings("deprecation") + public boolean paste(Location location, Schematic schematic, Plot plot) { + if (schematic == null) { + PlotMain.sendConsoleSenderMessage("Schematic == null :|"); + return false; + } + try { + EditSession session = new EditSession(new BukkitWorld( + location.getWorld()), 999999999); + CuboidClipboard clipboard = CuboidClipboard.loadSchematic(schematic + .getFile()); + Location l1 = PlotHelper.getPlotBottomLoc(plot.getWorld(), + plot.getId()); + PlotHelper.getPlotTopLoc(plot.getWorld(), plot.getId()); + int x = l1.getBlockX() + 1; + int z = l1.getBlockZ() + 1; + int y = location.getWorld().getHighestBlockYAt(x, z); + Vector v1 = new Vector(x, y + 1, z); + clipboard.paste(session, v1, true); + } catch (Exception e) { + return false; + } + return true; + } - public Schematic getSchematic(String name) { - { - File parent = new File(JavaPlugin.getPlugin(PlotMain.class).getDataFolder() + File.separator + "schematics"); - if (!parent.exists()) { - parent.mkdir(); - } - } - File file = new File(JavaPlugin.getPlugin(PlotMain.class).getDataFolder() + File.separator + "schematics" + File.separator + name + ".schematic"); - if (!file.exists()) { - PlotMain.sendConsoleSenderMessage(file.toString() + " doesn't exist"); - return null; - } + public Schematic getSchematic(String name) { + { + File parent = new File(JavaPlugin.getPlugin(PlotMain.class) + .getDataFolder() + File.separator + "schematics"); + if (!parent.exists()) { + parent.mkdir(); + } + } + File file = new File(JavaPlugin.getPlugin(PlotMain.class) + .getDataFolder() + + File.separator + + "schematics" + + File.separator + name + ".schematic"); + if (!file.exists()) { + PlotMain.sendConsoleSenderMessage(file.toString() + + " doesn't exist"); + return null; + } - Schematic schematic = null; - try { - InputStream iStream = new FileInputStream(file); - NBTInputStream stream = new NBTInputStream(new GZIPInputStream(iStream)); - CompoundTag tag = (CompoundTag) stream.readTag(); - Map tagMap = tag.getValue(); + Schematic schematic = null; + try { + InputStream iStream = new FileInputStream(file); + NBTInputStream stream = new NBTInputStream(new GZIPInputStream( + iStream)); + CompoundTag tag = (CompoundTag) stream.readTag(); + Map tagMap = tag.getValue(); - byte[] addId = new byte[0]; - if (tagMap.containsKey("AddBlocks")) { - addId = ByteArrayTag.class.cast(tagMap.get("AddBlocks")).getValue(); - } + byte[] addId = new byte[0]; + if (tagMap.containsKey("AddBlocks")) { + addId = ByteArrayTag.class.cast(tagMap.get("AddBlocks")) + .getValue(); + } - short width = ShortTag.class.cast(tagMap.get("Width")).getValue(); - short length = ShortTag.class.cast(tagMap.get("Length")).getValue(); - short height = ShortTag.class.cast(tagMap.get("Height")).getValue(); + short width = ShortTag.class.cast(tagMap.get("Width")).getValue(); + short length = ShortTag.class.cast(tagMap.get("Length")).getValue(); + short height = ShortTag.class.cast(tagMap.get("Height")).getValue(); - byte[] b = ByteArrayTag.class.cast(tagMap.get("Blocks")).getValue(); - byte[] d = ByteArrayTag.class.cast(tagMap.get("Data")).getValue(); - short[] blocks = new short[b.length]; + byte[] b = ByteArrayTag.class.cast(tagMap.get("Blocks")).getValue(); + byte[] d = ByteArrayTag.class.cast(tagMap.get("Data")).getValue(); + short[] blocks = new short[b.length]; - Dimension dimension = new Dimension(width, height, length); + Dimension dimension = new Dimension(width, height, length); - for (int index = 0; index < b.length; index++) { - if ((index >> 1) >= addId.length) { // No corresponding - // AddBlocks index - blocks[index] = (short) (b[index] & 0xFF); - } else { - if ((index & 1) == 0) { - blocks[index] = (short) (((addId[index >> 1] & 0x0F) << 8) + (b[index] & 0xFF)); - } else { - blocks[index] = (short) (((addId[index >> 1] & 0xF0) << 4) + (b[index] & 0xFF)); - } - } - } + for (int index = 0; index < b.length; index++) { + if ((index >> 1) >= addId.length) { // No corresponding + // AddBlocks index + blocks[index] = (short) (b[index] & 0xFF); + } else { + if ((index & 1) == 0) { + blocks[index] = (short) (((addId[index >> 1] & 0x0F) << 8) + (b[index] & 0xFF)); + } else { + blocks[index] = (short) (((addId[index >> 1] & 0xF0) << 4) + (b[index] & 0xFF)); + } + } + } - DataCollection[] collection = new DataCollection[b.length]; + DataCollection[] collection = new DataCollection[b.length]; - for (int x = 0; x < b.length; x++) { - collection[x] = new DataCollection(blocks[x], d[x]); - } + for (int x = 0; x < b.length; x++) { + collection[x] = new DataCollection(blocks[x], d[x]); + } - schematic = new Schematic(collection, dimension, file); - } catch (Exception e) { - e.printStackTrace(); - return null; - } finally { - return schematic; - } - } + schematic = new Schematic(collection, dimension, file); + } catch (Exception e) { + e.printStackTrace(); + return null; + } finally { + return schematic; + } + } - public static class Schematic { - private DataCollection[] blockCollection; - private Dimension schematicDimension; - private File file; + public static class Schematic { + private DataCollection[] blockCollection; + private Dimension schematicDimension; + private File file; - public Schematic(DataCollection[] blockCollection, Dimension schematicDimension, File file) { - this.blockCollection = blockCollection; - this.schematicDimension = schematicDimension; - this.file = file; - } + public Schematic(DataCollection[] blockCollection, + Dimension schematicDimension, File file) { + this.blockCollection = blockCollection; + this.schematicDimension = schematicDimension; + this.file = file; + } - public File getFile() { - return this.file; - } + public File getFile() { + return this.file; + } - public Dimension getSchematicDimension() { - return this.schematicDimension; - } + public Dimension getSchematicDimension() { + return this.schematicDimension; + } - public DataCollection[] getBlockCollection() { - return this.blockCollection; - } - } + public DataCollection[] getBlockCollection() { + return this.blockCollection; + } + } - public class Dimension { - private int x; - private int y; - private int z; + public class Dimension { + private int x; + private int y; + private int z; - public Dimension(int x, int y, int z) { - this.x = x; - this.y = y; - this.z = z; - } + public Dimension(int x, int y, int z) { + this.x = x; + this.y = y; + this.z = z; + } - public int getX() { - return this.x; - } + public int getX() { + return this.x; + } - public int getY() { - return this.y; - } + public int getY() { + return this.y; + } - public int getZ() { - return this.z; - } - } + public int getZ() { + return this.z; + } + } - public class DataCollection { - private short block; - private byte data; + public class DataCollection { + private short block; + private byte data; - public DataCollection(short block, byte data) { - this.block = block; - this.data = data; - } + public DataCollection(short block, byte data) { + this.block = block; + this.data = data; + } - public short getBlock() { - return this.block; - } + public short getBlock() { + return this.block; + } - public byte getData() { - return this.data; - } - } + public byte getData() { + return this.data; + } + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/SetBlockFast.java b/PlotSquared/src/com/intellectualcrafters/plot/SetBlockFast.java index 47a52c77b..c520befc5 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/SetBlockFast.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/SetBlockFast.java @@ -8,45 +8,50 @@ import com.intellectualcrafters.plot.ReflectionUtils.RefClass; import com.intellectualcrafters.plot.ReflectionUtils.RefMethod; /** - * + * * SetBlockFast class
* Used to do fast world editing - * + * */ public class SetBlockFast { - private static final RefClass classBlock = getRefClass("{nms}.Block"); - private static final RefClass classChunk = getRefClass("{nms}.Chunk"); - private static final RefClass classWorld = getRefClass("{nms}.World"); - private static final RefClass classCraftWorld = getRefClass("{cb}.CraftWorld"); + private static final RefClass classBlock = getRefClass("{nms}.Block"); + private static final RefClass classChunk = getRefClass("{nms}.Chunk"); + private static final RefClass classWorld = getRefClass("{nms}.World"); + private static final RefClass classCraftWorld = getRefClass("{cb}.CraftWorld"); - private static RefMethod methodGetHandle; - private static RefMethod methodGetChunkAt; - private static RefMethod methodA; - private static RefMethod methodGetById; + private static RefMethod methodGetHandle; + private static RefMethod methodGetChunkAt; + private static RefMethod methodA; + private static RefMethod methodGetById; - public SetBlockFast() throws NoSuchMethodException { - methodGetHandle = classCraftWorld.getMethod("getHandle"); - methodGetChunkAt = classWorld.getMethod("getChunkAt", int.class, int.class); - methodA = classChunk.getMethod("a", int.class, int.class, int.class, classBlock, int.class); - methodGetById = classBlock.getMethod("getById", int.class); - } + public SetBlockFast() throws NoSuchMethodException { + methodGetHandle = classCraftWorld.getMethod("getHandle"); + methodGetChunkAt = classWorld.getMethod("getChunkAt", int.class, + int.class); + methodA = classChunk.getMethod("a", int.class, int.class, int.class, + classBlock, int.class); + methodGetById = classBlock.getMethod("getById", int.class); + } - public static boolean set(org.bukkit.World world, int x, int y, int z, int blockId, byte data) throws NoSuchMethodException { + public static boolean set(org.bukkit.World world, int x, int y, int z, + int blockId, byte data) throws NoSuchMethodException { - Object w = methodGetHandle.of(world).call(); - Object chunk = methodGetChunkAt.of(w).call(x >> 4, z >> 4); - Object block = methodGetById.of(null).call(blockId); - methodA.of(chunk).call(x & 0x0f, y, z & 0x0f, block, data); - return true; - } + Object w = methodGetHandle.of(world).call(); + Object chunk = methodGetChunkAt.of(w).call(x >> 4, z >> 4); + Object block = methodGetById.of(null).call(blockId); + methodA.of(chunk).call(x & 0x0f, y, z & 0x0f, block, data); + return true; + } - public static void update(org.bukkit.entity.Player player) { - int distance = Bukkit.getViewDistance() + 1; - for (int cx = -distance; cx < distance; cx++) { - for (int cz = -distance; cz < distance; cz++) { - player.getWorld().refreshChunk(player.getLocation().getChunk().getX() + cx, player.getLocation().getChunk().getZ() + cz); - } - } - } + public static void update(org.bukkit.entity.Player player) { + int distance = Bukkit.getViewDistance() + 1; + for (int cx = -distance; cx < distance; cx++) { + for (int cz = -distance; cz < distance; cz++) { + player.getWorld().refreshChunk( + player.getLocation().getChunk().getX() + cx, + player.getLocation().getChunk().getZ() + cz); + } + } + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/Settings.java b/PlotSquared/src/com/intellectualcrafters/plot/Settings.java index cdc031aef..ba35b500b 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/Settings.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/Settings.java @@ -11,87 +11,88 @@ package com.intellectualcrafters.plot; /** * Updater and DB settings - * + * * @author Citymonstret - * + * * @author Empire92 */ public class Settings { - public static int MAX_PLOTS = 20; - /** - * WorldGuard region on claimed plots - */ - public static boolean WORLDGUARD = false; - /** - * metrics - */ - public static boolean METRICS = true; - /** - * plot specific resource pack - */ - public static String PLOT_SPECIFIC_RESOURCE_PACK = ""; - /** - * Kill road mobs? - */ - public static boolean KILL_ROAD_MOBS; - /** - * Default kill road mobs: true - */ - public static boolean KILL_ROAD_MOBS_DEFAULT = true; - /** - * mob pathfinding? - */ - public static boolean MOB_PATHFINDING; - /** - * Default mob pathfinding: true - */ - public static boolean MOB_PATHFINDING_DEFAULT = true; - /** - * Update settings - * - * @author Citymonstret - * - */ - public static String URL = "http://dev.bukkit.org/bukkit-plugins/plotsquared/"; + public static int MAX_PLOTS = 20; + /** + * WorldGuard region on claimed plots + */ + public static boolean WORLDGUARD = false; + /** + * metrics + */ + public static boolean METRICS = true; + /** + * plot specific resource pack + */ + public static String PLOT_SPECIFIC_RESOURCE_PACK = ""; + /** + * Kill road mobs? + */ + public static boolean KILL_ROAD_MOBS; + /** + * Default kill road mobs: true + */ + public static boolean KILL_ROAD_MOBS_DEFAULT = true; + /** + * mob pathfinding? + */ + public static boolean MOB_PATHFINDING; + /** + * Default mob pathfinding: true + */ + public static boolean MOB_PATHFINDING_DEFAULT = true; + /** + * Update settings + * + * @author Citymonstret + * + */ + public static String URL = "http://dev.bukkit.org/bukkit-plugins/plotsquared/"; - public static boolean DEBUG = true; + public static boolean DEBUG = true; - public static boolean AUTO_CLEAR = false; - public static int AUTO_CLEAR_DAYS = 365; + public static boolean AUTO_CLEAR = false; + public static int AUTO_CLEAR_DAYS = 365; - public static class Update { - /** - * Update plugin? - * - * @deprecated - */ - @Deprecated - public static boolean AUTO_UPDATE = false; - } + public static class Update { + /** + * Update plugin? + * + * @deprecated + */ + @Deprecated + public static boolean AUTO_UPDATE = false; + } - public static class Web { - public static boolean ENABLED = false; - public static int PORT = 9000; - } + public static class Web { + public static boolean ENABLED = false; + public static int PORT = 9000; + } - /** - * Database settings - * - * @author Citymonstret - * - */ - public static class DB { - public static boolean USE_MONGO = false; /* - * TODO: Implement Mongo - * @Brandon - */; - public static boolean USE_SQLITE = false; - public static boolean USE_MYSQL = true; /* NOTE: Fixed connector */ - public static String SQLITE_DB = "storage"; - public static String HOST_NAME = "localhost"; - public static String PORT = "3306"; - public static String DATABASE = "plot_db"; - public static String USER = "root"; - public static String PASSWORD = "password"; - } + /** + * Database settings + * + * @author Citymonstret + * + */ + public static class DB { + public static boolean USE_MONGO = false; /* + * TODO: Implement Mongo + * + * @Brandon + */; + public static boolean USE_SQLITE = false; + public static boolean USE_MYSQL = true; /* NOTE: Fixed connector */ + public static String SQLITE_DB = "storage"; + public static String HOST_NAME = "localhost"; + public static String PORT = "3306"; + public static String DATABASE = "plot_db"; + public static String USER = "root"; + public static String PASSWORD = "password"; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/Title.java b/PlotSquared/src/com/intellectualcrafters/plot/Title.java index 4d8e4c79f..c07c05ecc 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/Title.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/Title.java @@ -11,397 +11,437 @@ import org.bukkit.entity.Player; /** * Minecraft 1.8 Title - * + * * @version 1.0.3 * @author Maxim Van de Wynckel */ @SuppressWarnings("unused") public class Title { - /* Title packet */ - private Class packetTitle; - /* Title packet actions ENUM */ - private Class packetActions; - /* Chat serializer */ - private Class nmsChatSerializer; - /* Title text and color */ - private String title = ""; - private ChatColor titleColor = ChatColor.WHITE; - /* Subtitle text and color */ - private String subtitle = ""; - private ChatColor subtitleColor = ChatColor.WHITE; - /* Title timings */ - private int fadeInTime = -1; - private int stayTime = -1; - private int fadeOutTime = -1; - private boolean ticks = false; + /* Title packet */ + private Class packetTitle; + /* Title packet actions ENUM */ + private Class packetActions; + /* Chat serializer */ + private Class nmsChatSerializer; + /* Title text and color */ + private String title = ""; + private ChatColor titleColor = ChatColor.WHITE; + /* Subtitle text and color */ + private String subtitle = ""; + private ChatColor subtitleColor = ChatColor.WHITE; + /* Title timings */ + private int fadeInTime = -1; + private int stayTime = -1; + private int fadeOutTime = -1; + private boolean ticks = false; - private static final Map, Class> CORRESPONDING_TYPES; + private static final Map, Class> CORRESPONDING_TYPES; - static { - CORRESPONDING_TYPES = new HashMap<>(); - } + static { + CORRESPONDING_TYPES = new HashMap<>(); + } - /** - * Create a new 1.8 title - * - * @param title - * Title - */ - public Title(String title) { - this.title = title; - loadClasses(); - } + /** + * Create a new 1.8 title + * + * @param title + * Title + */ + public Title(String title) { + this.title = title; + loadClasses(); + } - /** - * Create a new 1.8 title - * - * @param title - * Title text - * @param subtitle - * Subtitle text - */ - public Title(String title, String subtitle) { - this.title = title; - this.subtitle = subtitle; - loadClasses(); - } + /** + * Create a new 1.8 title + * + * @param title + * Title text + * @param subtitle + * Subtitle text + */ + public Title(String title, String subtitle) { + this.title = title; + this.subtitle = subtitle; + loadClasses(); + } - /** - * Create a new 1.8 title - * - * @param title - * Title text - * @param subtitle - * Subtitle text - * @param fadeInTime - * Fade in time - * @param stayTime - * Stay on screen time - * @param fadeOutTime - * Fade out time - */ - public Title(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) { - this.title = title; - this.subtitle = subtitle; - this.fadeInTime = fadeInTime; - this.stayTime = stayTime; - this.fadeOutTime = fadeOutTime; - loadClasses(); - } + /** + * Create a new 1.8 title + * + * @param title + * Title text + * @param subtitle + * Subtitle text + * @param fadeInTime + * Fade in time + * @param stayTime + * Stay on screen time + * @param fadeOutTime + * Fade out time + */ + public Title(String title, String subtitle, int fadeInTime, int stayTime, + int fadeOutTime) { + this.title = title; + this.subtitle = subtitle; + this.fadeInTime = fadeInTime; + this.stayTime = stayTime; + this.fadeOutTime = fadeOutTime; + loadClasses(); + } - /** - * Load spigot and NMS classes - */ - private void loadClasses() { - this.packetTitle = getClass("org.spigotmc.ProtocolInjector$PacketTitle"); - this.packetActions = getClass("org.spigotmc.ProtocolInjector$PacketTitle$Action"); - this.nmsChatSerializer = getNMSClass("ChatSerializer"); - } + /** + * Load spigot and NMS classes + */ + private void loadClasses() { + this.packetTitle = getClass("org.spigotmc.ProtocolInjector$PacketTitle"); + this.packetActions = getClass("org.spigotmc.ProtocolInjector$PacketTitle$Action"); + this.nmsChatSerializer = getNMSClass("ChatSerializer"); + } - /** - * Set the title color - * - * @param color - * Chat color - */ - public void setTitleColor(ChatColor color) { - this.titleColor = color; - } + /** + * Set the title color + * + * @param color + * Chat color + */ + public void setTitleColor(ChatColor color) { + this.titleColor = color; + } - /** - * Set the subtitle color - * - * @param color - * Chat color - */ - public void setSubtitleColor(ChatColor color) { - this.subtitleColor = color; - } + /** + * Set the subtitle color + * + * @param color + * Chat color + */ + public void setSubtitleColor(ChatColor color) { + this.subtitleColor = color; + } - /** - * Set title fade in time - * - * @param time - * Time - */ - public void setFadeInTime(int time) { - this.fadeInTime = time; - } + /** + * Set title fade in time + * + * @param time + * Time + */ + public void setFadeInTime(int time) { + this.fadeInTime = time; + } - /** - * Set title fade out time - * - * @param time - * Time - */ - public void setFadeOutTime(int time) { - this.fadeOutTime = time; - } + /** + * Set title fade out time + * + * @param time + * Time + */ + public void setFadeOutTime(int time) { + this.fadeOutTime = time; + } - /** - * Set title stay time - * - * @param time - * Time - */ - public void setStayTime(int time) { - this.stayTime = time; - } + /** + * Set title stay time + * + * @param time + * Time + */ + public void setStayTime(int time) { + this.stayTime = time; + } - /** - * Set timings to ticks - */ - public void setTimingsToTicks() { - this.ticks = true; - } + /** + * Set timings to ticks + */ + public void setTimingsToTicks() { + this.ticks = true; + } - /** - * Set timings to seconds - */ - public void setTimingsToSeconds() { - this.ticks = false; - } + /** + * Set timings to seconds + */ + public void setTimingsToSeconds() { + this.ticks = false; + } - /** - * Send the title to a player - * - * @param player - * Player - */ - public void send(Player player) { - if ((getProtocolVersion(player) >= 47) && isSpigot() && (this.packetTitle != null)) { - // First reset previous settings - resetTitle(player); - try { - // Send timings first - Object handle = getHandle(player); - Object connection = getField(handle.getClass(), "playerConnection").get(handle); - Object[] actions = this.packetActions.getEnumConstants(); - Method sendPacket = getMethod(connection.getClass(), "sendPacket"); - Object packet = this.packetTitle.getConstructor(this.packetActions, Integer.TYPE, Integer.TYPE, Integer.TYPE).newInstance(actions[2], this.fadeInTime * (this.ticks ? 1 : 20), this.stayTime * (this.ticks ? 1 : 20), this.fadeOutTime * (this.ticks ? 1 : 20)); - // Send if set - if ((this.fadeInTime != -1) && (this.fadeOutTime != -1) && (this.stayTime != -1)) { - sendPacket.invoke(connection, packet); - } + /** + * Send the title to a player + * + * @param player + * Player + */ + public void send(Player player) { + if ((getProtocolVersion(player) >= 47) && isSpigot() + && (this.packetTitle != null)) { + // First reset previous settings + resetTitle(player); + try { + // Send timings first + Object handle = getHandle(player); + Object connection = getField(handle.getClass(), + "playerConnection").get(handle); + Object[] actions = this.packetActions.getEnumConstants(); + Method sendPacket = getMethod(connection.getClass(), + "sendPacket"); + Object packet = this.packetTitle.getConstructor( + this.packetActions, Integer.TYPE, Integer.TYPE, + Integer.TYPE).newInstance(actions[2], + this.fadeInTime * (this.ticks ? 1 : 20), + this.stayTime * (this.ticks ? 1 : 20), + this.fadeOutTime * (this.ticks ? 1 : 20)); + // Send if set + if ((this.fadeInTime != -1) && (this.fadeOutTime != -1) + && (this.stayTime != -1)) { + sendPacket.invoke(connection, packet); + } - // Send title - Object serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.title) + "\",color:" + this.titleColor.name().toLowerCase() + "}"); - packet = this.packetTitle.getConstructor(this.packetActions, getNMSClass("IChatBaseComponent")).newInstance(actions[0], serialized); - sendPacket.invoke(connection, packet); - if (!this.subtitle.equals("")) { - // Send subtitle if present - serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.subtitle) + "\",color:" + this.subtitleColor.name().toLowerCase() + "}"); - packet = this.packetTitle.getConstructor(this.packetActions, getNMSClass("IChatBaseComponent")).newInstance(actions[1], serialized); - sendPacket.invoke(connection, packet); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - } + // Send title + Object serialized = getMethod(this.nmsChatSerializer, "a", + String.class).invoke( + null, + "{text:\"" + + ChatColor.translateAlternateColorCodes('&', + this.title) + "\",color:" + + this.titleColor.name().toLowerCase() + "}"); + packet = this.packetTitle.getConstructor(this.packetActions, + getNMSClass("IChatBaseComponent")).newInstance( + actions[0], serialized); + sendPacket.invoke(connection, packet); + if (!this.subtitle.equals("")) { + // Send subtitle if present + serialized = getMethod(this.nmsChatSerializer, "a", + String.class).invoke( + null, + "{text:\"" + + ChatColor.translateAlternateColorCodes( + '&', this.subtitle) + "\",color:" + + this.subtitleColor.name().toLowerCase() + + "}"); + packet = this.packetTitle.getConstructor( + this.packetActions, + getNMSClass("IChatBaseComponent")).newInstance( + actions[1], serialized); + sendPacket.invoke(connection, packet); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } - /** - * Broadcast the title to all players - */ - public void broadcast() { - for (Player p : Bukkit.getOnlinePlayers()) { - send(p); - } - } + /** + * Broadcast the title to all players + */ + public void broadcast() { + for (Player p : Bukkit.getOnlinePlayers()) { + send(p); + } + } - /** - * Clear the title - * - * @param player - * Player - */ - public void clearTitle(Player player) { - if ((getProtocolVersion(player) >= 47) && isSpigot()) { - try { - // Send timings first - Object handle = getHandle(player); - Object connection = getField(handle.getClass(), "playerConnection").get(handle); - Object[] actions = this.packetActions.getEnumConstants(); - Method sendPacket = getMethod(connection.getClass(), "sendPacket"); - Object packet = this.packetTitle.getConstructor(this.packetActions).newInstance(actions[3]); - sendPacket.invoke(connection, packet); - } catch (Exception e) { - e.printStackTrace(); - } - } - } + /** + * Clear the title + * + * @param player + * Player + */ + public void clearTitle(Player player) { + if ((getProtocolVersion(player) >= 47) && isSpigot()) { + try { + // Send timings first + Object handle = getHandle(player); + Object connection = getField(handle.getClass(), + "playerConnection").get(handle); + Object[] actions = this.packetActions.getEnumConstants(); + Method sendPacket = getMethod(connection.getClass(), + "sendPacket"); + Object packet = this.packetTitle.getConstructor( + this.packetActions).newInstance(actions[3]); + sendPacket.invoke(connection, packet); + } catch (Exception e) { + e.printStackTrace(); + } + } + } - /** - * Reset the title settings - * - * @param player - * Player - */ - public void resetTitle(Player player) { - if ((getProtocolVersion(player) >= 47) && isSpigot()) { - try { - // Send timings first - Object handle = getHandle(player); - Object connection = getField(handle.getClass(), "playerConnection").get(handle); - Object[] actions = this.packetActions.getEnumConstants(); - Method sendPacket = getMethod(connection.getClass(), "sendPacket"); - Object packet = this.packetTitle.getConstructor(this.packetActions).newInstance(actions[4]); - sendPacket.invoke(connection, packet); - } catch (Exception e) { - e.printStackTrace(); - } - } - } + /** + * Reset the title settings + * + * @param player + * Player + */ + public void resetTitle(Player player) { + if ((getProtocolVersion(player) >= 47) && isSpigot()) { + try { + // Send timings first + Object handle = getHandle(player); + Object connection = getField(handle.getClass(), + "playerConnection").get(handle); + Object[] actions = this.packetActions.getEnumConstants(); + Method sendPacket = getMethod(connection.getClass(), + "sendPacket"); + Object packet = this.packetTitle.getConstructor( + this.packetActions).newInstance(actions[4]); + sendPacket.invoke(connection, packet); + } catch (Exception e) { + e.printStackTrace(); + } + } + } - /** - * Get the protocol version of the player - * - * @param player - * Player - * @return Protocol version - */ - private int getProtocolVersion(Player player) { - int version = 0; - try { - Object handle = getHandle(player); - Object connection = getField(handle.getClass(), "playerConnection").get(handle); - Object networkManager = getValue("networkManager", connection); - version = (Integer) getMethod("getVersion", networkManager.getClass()).invoke(networkManager); + /** + * Get the protocol version of the player + * + * @param player + * Player + * @return Protocol version + */ + private int getProtocolVersion(Player player) { + int version = 0; + try { + Object handle = getHandle(player); + Object connection = getField(handle.getClass(), "playerConnection") + .get(handle); + Object networkManager = getValue("networkManager", connection); + version = (Integer) getMethod("getVersion", + networkManager.getClass()).invoke(networkManager); - return version; - } catch (Exception ex) { - // ex.printStackTrace(); <-- spammy console - } - return version; - } + return version; + } catch (Exception ex) { + // ex.printStackTrace(); <-- spammy console + } + return version; + } - /** - * Check if running spigot - * - * @return Spigot - */ - private boolean isSpigot() { - return Bukkit.getVersion().contains("Spigot"); - } + /** + * Check if running spigot + * + * @return Spigot + */ + private boolean isSpigot() { + return Bukkit.getVersion().contains("Spigot"); + } - /** - * Get class by url - * - * @param namespace - * Namespace url - * @return Class - */ - private Class getClass(String namespace) { - try { - return Class.forName(namespace); - } catch (Exception e) { - return null; - } - } + /** + * Get class by url + * + * @param namespace + * Namespace url + * @return Class + */ + private Class getClass(String namespace) { + try { + return Class.forName(namespace); + } catch (Exception e) { + return null; + } + } - private Field getField(String name, Class clazz) throws Exception { - return clazz.getDeclaredField(name); - } + private Field getField(String name, Class clazz) throws Exception { + return clazz.getDeclaredField(name); + } - private Object getValue(String name, Object obj) throws Exception { - Field f = getField(name, obj.getClass()); - f.setAccessible(true); - return f.get(obj); - } + private Object getValue(String name, Object obj) throws Exception { + Field f = getField(name, obj.getClass()); + f.setAccessible(true); + return f.get(obj); + } - private Class getPrimitiveType(Class clazz) { - return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES.get(clazz) : clazz; - } + private Class getPrimitiveType(Class clazz) { + return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES + .get(clazz) : clazz; + } - private Class[] toPrimitiveTypeArray(Class[] classes) { - int a = classes != null ? classes.length : 0; - Class[] types = new Class[a]; - for (int i = 0; i < a; i++) { - types[i] = getPrimitiveType(classes[i]); - } - return types; - } + private Class[] toPrimitiveTypeArray(Class[] classes) { + int a = classes != null ? classes.length : 0; + Class[] types = new Class[a]; + for (int i = 0; i < a; i++) { + types[i] = getPrimitiveType(classes[i]); + } + return types; + } - private static boolean equalsTypeArray(Class[] a, Class[] o) { - if (a.length != o.length) { - return false; - } - for (int i = 0; i < a.length; i++) { - if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i])) { - return false; - } - } - return true; - } + private static boolean equalsTypeArray(Class[] a, Class[] o) { + if (a.length != o.length) { + return false; + } + for (int i = 0; i < a.length; i++) { + if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i])) { + return false; + } + } + return true; + } - private Object getHandle(Object obj) { - try { - return getMethod("getHandle", obj.getClass()).invoke(obj); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } + private Object getHandle(Object obj) { + try { + return getMethod("getHandle", obj.getClass()).invoke(obj); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } - private Method getMethod(String name, Class clazz, Class... paramTypes) { - Class[] t = toPrimitiveTypeArray(paramTypes); - for (Method m : clazz.getMethods()) { - Class[] types = toPrimitiveTypeArray(m.getParameterTypes()); - if (m.getName().equals(name) && equalsTypeArray(types, t)) { - return m; - } - } - return null; - } + private Method getMethod(String name, Class clazz, + Class... paramTypes) { + Class[] t = toPrimitiveTypeArray(paramTypes); + for (Method m : clazz.getMethods()) { + Class[] types = toPrimitiveTypeArray(m.getParameterTypes()); + if (m.getName().equals(name) && equalsTypeArray(types, t)) { + return m; + } + } + return null; + } - private String getVersion() { - String name = Bukkit.getServer().getClass().getPackage().getName(); - return name.substring(name.lastIndexOf('.') + 1) + "."; - } + private String getVersion() { + String name = Bukkit.getServer().getClass().getPackage().getName(); + return name.substring(name.lastIndexOf('.') + 1) + "."; + } - private Class getNMSClass(String className) { - String fullName = "net.minecraft.server." + getVersion() + className; - Class clazz = null; - try { - clazz = Class.forName(fullName); - } catch (Exception e) { - e.printStackTrace(); - } - return clazz; - } + private Class getNMSClass(String className) { + String fullName = "net.minecraft.server." + getVersion() + className; + Class clazz = null; + try { + clazz = Class.forName(fullName); + } catch (Exception e) { + e.printStackTrace(); + } + return clazz; + } - private Field getField(Class clazz, String name) { - try { - Field field = clazz.getDeclaredField(name); - field.setAccessible(true); - return field; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } + private Field getField(Class clazz, String name) { + try { + Field field = clazz.getDeclaredField(name); + field.setAccessible(true); + return field; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } - private Method getMethod(Class clazz, String name, Class... args) { - for (Method m : clazz.getMethods()) { - if (m.getName().equals(name) && ((args.length == 0) || ClassListEqual(args, m.getParameterTypes()))) { - m.setAccessible(true); - return m; - } - } - return null; - } + private Method getMethod(Class clazz, String name, Class... args) { + for (Method m : clazz.getMethods()) { + if (m.getName().equals(name) + && ((args.length == 0) || ClassListEqual(args, + m.getParameterTypes()))) { + m.setAccessible(true); + return m; + } + } + return null; + } - private boolean ClassListEqual(Class[] l1, Class[] l2) { - boolean equal = true; - if (l1.length != l2.length) { - return false; - } - for (int i = 0; i < l1.length; i++) { - if (l1[i] != l2[i]) { - equal = false; - break; - } - } - return equal; - } + private boolean ClassListEqual(Class[] l1, Class[] l2) { + boolean equal = true; + if (l1.length != l2.length) { + return false; + } + for (int i = 0; i < l1.length; i++) { + if (l1[i] != l2[i]) { + equal = false; + break; + } + } + return equal; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/UUIDHandler.java b/PlotSquared/src/com/intellectualcrafters/plot/UUIDHandler.java index ac6fe88b6..ba0666b9d 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/UUIDHandler.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/UUIDHandler.java @@ -1,205 +1,215 @@ package com.intellectualcrafters.plot; -import com.google.common.base.Charsets; -import com.intellectualcrafters.plot.uuid.NameFetcher; -import com.intellectualcrafters.plot.uuid.UUIDFetcher; -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.bukkit.entity.Player; -import org.bukkit.plugin.java.JavaPlugin; - import java.util.Arrays; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; + +import com.google.common.base.Charsets; +import com.intellectualcrafters.plot.uuid.NameFetcher; +import com.intellectualcrafters.plot.uuid.UUIDFetcher; + public class UUIDHandler { - private static ConcurrentHashMap uuidMap = new ConcurrentHashMap<>(); + private static ConcurrentHashMap uuidMap = new ConcurrentHashMap<>(); - public static boolean uuidExists(UUID uuid) { - return uuidMap.containsValue(uuid); - } + public static boolean uuidExists(UUID uuid) { + return uuidMap.containsValue(uuid); + } - public static boolean nameExists(String name) { - return uuidMap.containsKey(name); - } + public static boolean nameExists(String name) { + return uuidMap.containsKey(name); + } - public static void add(String name, UUID uuid) { - uuidMap.put(name, uuid); - } + public static void add(String name, UUID uuid) { + uuidMap.put(name, uuid); + } - /** - * - * @param plugin - */ - public static void startFetch(JavaPlugin plugin) { - plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() { - @Override - public void run() { - OfflinePlayer[] offlinePlayers = Bukkit.getOfflinePlayers(); - int lenght = offlinePlayers.length; - long start = System.currentTimeMillis(); + /** + * + * @param plugin + */ + public static void startFetch(JavaPlugin plugin) { + plugin.getServer().getScheduler() + .runTaskAsynchronously(plugin, new Runnable() { + @Override + public void run() { + OfflinePlayer[] offlinePlayers = Bukkit + .getOfflinePlayers(); + int lenght = offlinePlayers.length; + long start = System.currentTimeMillis(); - String name; - UUID uuid; - for(OfflinePlayer player : offlinePlayers) { - name = player.getName(); - uuid = player.getUniqueId(); - if(!uuidExists(uuid)) - add(name, uuid); - } + String name; + UUID uuid; + for (OfflinePlayer player : offlinePlayers) { + name = player.getName(); + uuid = player.getUniqueId(); + if (!uuidExists(uuid)) { + add(name, uuid); + } + } - long time = System.currentTimeMillis() - start; - PlotMain.sendConsoleSenderMessage("&cFinished caching of offlineplayers! Took &6" + time + "&cms, &6" + lenght + " &cUUID's were cached" + - " and there is now a grand total of &6" + uuidMap.size() + " &ccached."); - } - }); - } + long time = System.currentTimeMillis() - start; + PlotMain.sendConsoleSenderMessage("&cFinished caching of offlineplayers! Took &6" + + time + + "&cms, &6" + + lenght + + " &cUUID's were cached" + + " and there is now a grand total of &6" + + uuidMap.size() + " &ccached."); + } + }); + } - /** - * - * @param name - * @return - */ - public static UUID getUUID(String name) { - if (nameExists(name)) { - return uuidMap.get(name); - } - UUID uuid; - if ((uuid = getUuidOnlinePlayer(name)) != null) { - return uuid; - } - if ((uuid = getUuidOfflinePlayer(name)) != null) { - return uuid; - } - if(Bukkit.getOnlineMode()) { - try { - UUIDFetcher fetcher = new UUIDFetcher(Arrays.asList(name)); - uuid = fetcher.call().get(name); - add(name, uuid); - } catch(Exception e) { - e.printStackTrace(); - } - } else { - return getUuidOfflineMode(name); - } - return null; - } + /** + * + * @param name + * @return + */ + public static UUID getUUID(String name) { + if (nameExists(name)) { + return uuidMap.get(name); + } + UUID uuid; + if ((uuid = getUuidOnlinePlayer(name)) != null) { + return uuid; + } + if ((uuid = getUuidOfflinePlayer(name)) != null) { + return uuid; + } + if (Bukkit.getOnlineMode()) { + try { + UUIDFetcher fetcher = new UUIDFetcher(Arrays.asList(name)); + uuid = fetcher.call().get(name); + add(name, uuid); + } catch (Exception e) { + e.printStackTrace(); + } + } else { + return getUuidOfflineMode(name); + } + return null; + } - /** - * - * @param uuid - * @return - */ - private static String loopSearch(UUID uuid) { - for(Map.Entry entry : uuidMap.entrySet()) { - if(entry.getValue().equals(uuid)) { - return entry.getKey(); - } - } - return ""; - } + /** + * + * @param uuid + * @return + */ + private static String loopSearch(UUID uuid) { + for (Map.Entry entry : uuidMap.entrySet()) { + if (entry.getValue().equals(uuid)) { + return entry.getKey(); + } + } + return ""; + } - /** - * - * @param uuid - * @return - */ - public static String getName(UUID uuid) { - if(uuidExists(uuid)) { - return loopSearch(uuid); - } - String name; - if ((name = getNameOnlinePlayer(uuid)) != null) { - return name; - } - if ((name = getNameOfflinePlayer(uuid)) != null) { - return name; - } - if (Bukkit.getOnlineMode()) { - try { - NameFetcher fetcher = new NameFetcher(Arrays.asList(uuid)); - name = fetcher.call().get(uuid); - add(name, uuid); - return name; - } catch(Exception e) { - e.printStackTrace(); - } - } else { - return "unknown"; - } - return ""; - } + /** + * + * @param uuid + * @return + */ + public static String getName(UUID uuid) { + if (uuidExists(uuid)) { + return loopSearch(uuid); + } + String name; + if ((name = getNameOnlinePlayer(uuid)) != null) { + return name; + } + if ((name = getNameOfflinePlayer(uuid)) != null) { + return name; + } + if (Bukkit.getOnlineMode()) { + try { + NameFetcher fetcher = new NameFetcher(Arrays.asList(uuid)); + name = fetcher.call().get(uuid); + add(name, uuid); + return name; + } catch (Exception e) { + e.printStackTrace(); + } + } else { + return "unknown"; + } + return ""; + } - /** - * - * @param name - * @return - */ - private static UUID getUuidOfflineMode(String name) { - UUID uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8)); - add(name, uuid); - return uuid; - } + /** + * + * @param name + * @return + */ + private static UUID getUuidOfflineMode(String name) { + UUID uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name) + .getBytes(Charsets.UTF_8)); + add(name, uuid); + return uuid; + } - /** - * - * @param uuid - * @return - */ - private static String getNameOnlinePlayer(UUID uuid) { - Player player = Bukkit.getPlayer(uuid); - if(player == null || !player.isOnline()) { - return null; - } - String name = player.getName(); - add(name, uuid); - return name; - } + /** + * + * @param uuid + * @return + */ + private static String getNameOnlinePlayer(UUID uuid) { + Player player = Bukkit.getPlayer(uuid); + if (player == null || !player.isOnline()) { + return null; + } + String name = player.getName(); + add(name, uuid); + return name; + } - /** - * - * @param uuid - * @return - */ - private static String getNameOfflinePlayer(UUID uuid) { - OfflinePlayer player = Bukkit.getOfflinePlayer(uuid); - if (player == null || !player.hasPlayedBefore()) { - return null; - } - String name = player.getName(); - add(name, uuid); - return name; - } + /** + * + * @param uuid + * @return + */ + private static String getNameOfflinePlayer(UUID uuid) { + OfflinePlayer player = Bukkit.getOfflinePlayer(uuid); + if (player == null || !player.hasPlayedBefore()) { + return null; + } + String name = player.getName(); + add(name, uuid); + return name; + } - /** - * - * @param name - * @return - */ - private static UUID getUuidOnlinePlayer(String name) { - Player player = Bukkit.getPlayer(name); - if (player == null || !player.isOnline()) { - return null; - } - UUID uuid = player.getUniqueId(); - add(name, uuid); - return uuid; - } + /** + * + * @param name + * @return + */ + private static UUID getUuidOnlinePlayer(String name) { + Player player = Bukkit.getPlayer(name); + if (player == null || !player.isOnline()) { + return null; + } + UUID uuid = player.getUniqueId(); + add(name, uuid); + return uuid; + } - /** - * - * @param name - * @return - */ - private static UUID getUuidOfflinePlayer(String name) { - OfflinePlayer player = Bukkit.getOfflinePlayer(name); - if (player == null || !player.hasPlayedBefore()) { - return null; - } - UUID uuid = player.getUniqueId(); - add(name, uuid); - return uuid; - } + /** + * + * @param name + * @return + */ + private static UUID getUuidOfflinePlayer(String name) { + OfflinePlayer player = Bukkit.getOfflinePlayer(name); + if (player == null || !player.hasPlayedBefore()) { + return null; + } + UUID uuid = player.getUniqueId(); + add(name, uuid); + return uuid; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/api/PlotAPI.java b/PlotSquared/src/com/intellectualcrafters/plot/api/PlotAPI.java index 254dd24cf..33704f8b8 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/api/PlotAPI.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/api/PlotAPI.java @@ -32,291 +32,294 @@ import com.intellectualcrafters.plot.commands.SubCommand; /** * The plotMain api class. - * + * * @author Citymonstret */ @SuppressWarnings({ "unused", "javadoc" }) public class PlotAPI { - // To access plotMain stuff. - private PlotMain plotMain; - // Reference - public static final String ADMIN_PERMISSION = "plots.admin"; + // To access plotMain stuff. + private PlotMain plotMain; + // Reference + public static final String ADMIN_PERMISSION = "plots.admin"; - /** - * Constructor. Insert any Plugin. - * - * @param plugin - */ - public PlotAPI(JavaPlugin plugin) { - this.plotMain = JavaPlugin.getPlugin(PlotMain.class); - } + /** + * Constructor. Insert any Plugin. + * + * @param plugin + */ + public PlotAPI(JavaPlugin plugin) { + this.plotMain = JavaPlugin.getPlugin(PlotMain.class); + } - /** - * Send a message to a player. - * - * @param player - * @param c - * (Caption) - */ - public void sendMessage(Player player, C c) { - PlayerFunctions.sendMessage(player, c); - } + /** + * Send a message to a player. + * + * @param player + * @param c + * (Caption) + */ + public void sendMessage(Player player, C c) { + PlayerFunctions.sendMessage(player, c); + } - /** - * Send a message to a player. - * - * @param player - * @param string - */ - public void sendMessage(Player player, String string) { - PlayerFunctions.sendMessage(player, string); - } + /** + * Send a message to a player. + * + * @param player + * @param string + */ + public void sendMessage(Player player, String string) { + PlayerFunctions.sendMessage(player, string); + } - /** - * Send a message to the console. - * - * @param msg - */ - public void sendConsoleMessage(String msg) { - PlotMain.sendConsoleSenderMessage(msg); - } + /** + * Send a message to the console. + * + * @param msg + */ + public void sendConsoleMessage(String msg) { + PlotMain.sendConsoleSenderMessage(msg); + } - /** - * Send a message to the console - * - * @param c - * (Caption) - */ - public void sendConsoleMessage(C c) { - sendConsoleMessage(c.s()); - } + /** + * Send a message to the console + * + * @param c + * (Caption) + */ + public void sendConsoleMessage(C c) { + sendConsoleMessage(c.s()); + } - /** - * Register a flag for use in plots - * - * @param flag - */ - public void addFlag(AbstractFlag flag) { - FlagManager.addFlag(flag); - } + /** + * Register a flag for use in plots + * + * @param flag + */ + public void addFlag(AbstractFlag flag) { + FlagManager.addFlag(flag); + } - /** - * get all the currently registered flags - * - * @return array of Flag[] - */ - public AbstractFlag[] getFlags() { - return FlagManager.getFlags().toArray(new AbstractFlag[0]); - } + /** + * get all the currently registered flags + * + * @return array of Flag[] + */ + public AbstractFlag[] getFlags() { + return FlagManager.getFlags().toArray(new AbstractFlag[0]); + } - /** - * Get a plot based on the ID - * - * @param world - * @param x - * @param z - * @return plot, null if ID is wrong - */ - public Plot getPlot(World world, int x, int z) { - return PlotHelper.getPlot(world, new PlotId(x, z)); - } + /** + * Get a plot based on the ID + * + * @param world + * @param x + * @param z + * @return plot, null if ID is wrong + */ + public Plot getPlot(World world, int x, int z) { + return PlotHelper.getPlot(world, new PlotId(x, z)); + } - /** - * Get a plot based on the location - * - * @param l - * @return plot if found, otherwise it creates a temporary plot- - */ - public Plot getPlot(Location l) { - return PlotHelper.getCurrentPlot(l); - } + /** + * Get a plot based on the location + * + * @param l + * @return plot if found, otherwise it creates a temporary plot- + */ + public Plot getPlot(Location l) { + return PlotHelper.getCurrentPlot(l); + } - /** - * Get a plot based on the player location - * - * @param player - * @return plot if found, otherwise it creates a temporary plot - */ - public Plot getPlot(Player player) { - return this.getPlot(player.getLocation()); - } + /** + * Get a plot based on the player location + * + * @param player + * @return plot if found, otherwise it creates a temporary plot + */ + public Plot getPlot(Player player) { + return this.getPlot(player.getLocation()); + } - /** - * Check whether or not a player has a plot - * - * @param player - * @return true if player has a plot, false if not. - */ - public boolean hasPlot(World world, Player player) { - return (getPlots(world, player, true) != null) && (getPlots(world, player, true).length > 0); - } + /** + * Check whether or not a player has a plot + * + * @param player + * @return true if player has a plot, false if not. + */ + public boolean hasPlot(World world, Player player) { + return (getPlots(world, player, true) != null) + && (getPlots(world, player, true).length > 0); + } - /** - * Get all plots for the player - * - * @param plr - * to search for - * @param just_owner - * should we just search for owner? Or with rights? - */ - public Plot[] getPlots(World world, Player plr, boolean just_owner) { - ArrayList pPlots = new ArrayList<>(); - for (Plot plot : PlotMain.getPlots(world).values()) { - if (just_owner) { - if ((plot.owner != null) && (plot.owner == plr.getUniqueId())) { - pPlots.add(plot); - } - } else { - if (plot.hasRights(plr)) { - pPlots.add(plot); - } - } - } - return (Plot[]) pPlots.toArray(); - } + /** + * Get all plots for the player + * + * @param plr + * to search for + * @param just_owner + * should we just search for owner? Or with rights? + */ + public Plot[] getPlots(World world, Player plr, boolean just_owner) { + ArrayList pPlots = new ArrayList<>(); + for (Plot plot : PlotMain.getPlots(world).values()) { + if (just_owner) { + if ((plot.owner != null) && (plot.owner == plr.getUniqueId())) { + pPlots.add(plot); + } + } else { + if (plot.hasRights(plr)) { + pPlots.add(plot); + } + } + } + return (Plot[]) pPlots.toArray(); + } - /** - * Get all plots for the world - * - * @param world - * to get plots of - * @return Plot[] - array of plot objects in world - */ - public Plot[] getPlots(World world) { - return PlotMain.getWorldPlots(world); - } + /** + * Get all plots for the world + * + * @param world + * to get plots of + * @return Plot[] - array of plot objects in world + */ + public Plot[] getPlots(World world) { + return PlotMain.getWorldPlots(world); + } - /** - * Get all plot worlds - * - * @return World[] - array of plot worlds - */ - public String[] getPlotWorlds() { - return PlotMain.getPlotWorlds(); - } + /** + * Get all plot worlds + * + * @return World[] - array of plot worlds + */ + public String[] getPlotWorlds() { + return PlotMain.getPlotWorlds(); + } - /** - * Get if plot world - * - * @param world - * (to check if plot world) - * @return boolean (if plot world or not) - */ - public boolean isPlotWorld(World world) { - return PlotMain.isPlotWorld(world); - } + /** + * Get if plot world + * + * @param world + * (to check if plot world) + * @return boolean (if plot world or not) + */ + public boolean isPlotWorld(World world) { + return PlotMain.isPlotWorld(world); + } - /** - * Get the settings for a world (settings bundled in PlotWorld class) - * - * @param world - * (to get settings of) - * @return PlotWorld class for ther world ! will return null if not a plot - * world - */ - public PlotWorld getWorldSettings(World world) { - return PlotMain.getWorldSettings(world); - } + /** + * Get the settings for a world (settings bundled in PlotWorld class) + * + * @param world + * (to get settings of) + * @return PlotWorld class for ther world ! will return null if not a plot + * world + */ + public PlotWorld getWorldSettings(World world) { + return PlotMain.getWorldSettings(world); + } - /** - * Get plot locations - * - * @param p - * @return [0] = bottomLc, [1] = topLoc, [2] = home - */ - public Location[] getLocations(Plot p) { - World world = Bukkit.getWorld(p.world); - return new Location[] { PlotHelper.getPlotBottomLoc(world, p.id), PlotHelper.getPlotTopLoc(world, p.id), PlotHelper.getPlotHome(world, p.id) }; - } + /** + * Get plot locations + * + * @param p + * @return [0] = bottomLc, [1] = topLoc, [2] = home + */ + public Location[] getLocations(Plot p) { + World world = Bukkit.getWorld(p.world); + return new Location[] { PlotHelper.getPlotBottomLoc(world, p.id), + PlotHelper.getPlotTopLoc(world, p.id), + PlotHelper.getPlotHome(world, p.id) }; + } - /** - * Get home location - * - * @param p - * @return plot bottom location - */ - public Location getHomeLocation(Plot p) { - return PlotHelper.getPlotHome(p.getWorld(), p.id); - } + /** + * Get home location + * + * @param p + * @return plot bottom location + */ + public Location getHomeLocation(Plot p) { + return PlotHelper.getPlotHome(p.getWorld(), p.id); + } - /** - * Get Bottom Location - * - * @param p - * @return plot bottom location - */ - public Location getBottomLocation(Plot p) { - World world = Bukkit.getWorld(p.world); - return PlotHelper.getPlotBottomLoc(world, p.id); - } + /** + * Get Bottom Location + * + * @param p + * @return plot bottom location + */ + public Location getBottomLocation(Plot p) { + World world = Bukkit.getWorld(p.world); + return PlotHelper.getPlotBottomLoc(world, p.id); + } - /** - * Get Top Location - * - * @param p - * @return plot top location - */ - public Location getTopLocation(Plot p) { - World world = Bukkit.getWorld(p.world); - return PlotHelper.getPlotTopLoc(world, p.id); - } + /** + * Get Top Location + * + * @param p + * @return plot top location + */ + public Location getTopLocation(Plot p) { + World world = Bukkit.getWorld(p.world); + return PlotHelper.getPlotTopLoc(world, p.id); + } - /** - * Check whether or not a player is in a plot - * - * @param player - * @return true if the player is in a plot, false if not- - */ - public boolean isInPlot(Player player) { - return PlayerFunctions.isInPlot(player); - } + /** + * Check whether or not a player is in a plot + * + * @param player + * @return true if the player is in a plot, false if not- + */ + public boolean isInPlot(Player player) { + return PlayerFunctions.isInPlot(player); + } - /** - * Register a subcommand - * - * @param c - */ - public void registerCommand(SubCommand c) { - MainCommand.subCommands.add(c); - } + /** + * Register a subcommand + * + * @param c + */ + public void registerCommand(SubCommand c) { + MainCommand.subCommands.add(c); + } - /** - * Get the plotMain class - * - * @return PlotMain Class - */ - public PlotMain getPlotMain() { - return this.plotMain; - } + /** + * Get the plotMain class + * + * @return PlotMain Class + */ + public PlotMain getPlotMain() { + return this.plotMain; + } - /** - * Get the player plot count - * - * @param player - * @return - */ - public int getPlayerPlotCount(World world, Player player) { - return PlayerFunctions.getPlayerPlotCount(world, player); - } + /** + * Get the player plot count + * + * @param player + * @return + */ + public int getPlayerPlotCount(World world, Player player) { + return PlayerFunctions.getPlayerPlotCount(world, player); + } - /** - * Get a players plots - * - * @param player - * @return a set containing the players plots - */ - public Set getPlayerPlots(World world, Player player) { - return PlayerFunctions.getPlayerPlots(world, player); - } + /** + * Get a players plots + * + * @param player + * @return a set containing the players plots + */ + public Set getPlayerPlots(World world, Player player) { + return PlayerFunctions.getPlayerPlots(world, player); + } - /** - * Get the allowed plot count for a player - * - * @param player - * @return the number of allowed plots - */ - public int getAllowedPlots(Player player) { - return PlayerFunctions.getAllowedPlots(player); - } + /** + * Get the allowed plot count for a player + * + * @param player + * @return the number of allowed plots + */ + public int getAllowedPlots(Player player) { + return PlayerFunctions.getAllowedPlots(player); + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/commands/Auto.java b/PlotSquared/src/com/intellectualcrafters/plot/commands/Auto.java index 7943ae1ec..121e52240 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/commands/Auto.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/commands/Auto.java @@ -8,156 +8,172 @@ */ package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.*; import net.milkbowl.vault.economy.Economy; + import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.entity.Player; +import com.intellectualcrafters.plot.C; +import com.intellectualcrafters.plot.PlayerFunctions; +import com.intellectualcrafters.plot.Plot; +import com.intellectualcrafters.plot.PlotHelper; +import com.intellectualcrafters.plot.PlotId; +import com.intellectualcrafters.plot.PlotMain; +import com.intellectualcrafters.plot.PlotWorld; + @SuppressWarnings("deprecation") public class Auto extends SubCommand { - public Auto() { - super("auto", "plots.auto", "Claim the nearest plot", "auto", "a", CommandCategory.CLAIMING); - } + public Auto() { + super("auto", "plots.auto", "Claim the nearest plot", "auto", "a", + CommandCategory.CLAIMING); + } - // TODO auto claim a mega plot!!!!!!!!!!!! - @Override - public boolean execute(Player plr, String... args) { - World world; - int size_x = 1; - int size_z = 1; - String schematic = ""; - if (PlotMain.getPlotWorlds().length == 1) { - world = Bukkit.getWorld(PlotMain.getPlotWorlds()[0]); - } else { - if (PlotMain.isPlotWorld(plr.getWorld())) { - world = plr.getWorld(); - } else { - PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD); - return false; - } - } - if (args.length > 0) { - if (PlotMain.hasPermission(plr, "plots.auto.mega")) { - try { - String[] split = args[0].split(","); - size_x = Integer.parseInt(split[0]); - size_z = Integer.parseInt(split[1]); - if ((size_x < 1) || (size_z < 1)) { - PlayerFunctions.sendMessage(plr, "&cError: size<=0"); - } - if ((size_x > 4) || (size_z > 4)) { - PlayerFunctions.sendMessage(plr, "&cError: size>4"); - } - if(args.length > 1) { - schematic = args[1]; - } - } catch (Exception e) { - schematic = args[0]; - //PlayerFunctions.sendMessage(plr, "&cError: Invalid size (X,Y)"); - //return false; - } - } else { - schematic = args[0]; - //PlayerFunctions.sendMessage(plr, C.NO_PERMISSION); - //return false; - } - } - if (PlayerFunctions.getPlayerPlotCount(world, plr) >= PlayerFunctions.getAllowedPlots(plr)) { - PlayerFunctions.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS); - return false; - } - PlotWorld pWorld = PlotMain.getWorldSettings(world); - if(PlotMain.useEconomy && pWorld.USE_ECONOMY) { - double cost = pWorld.PLOT_PRICE; - cost = (size_x * size_z) * cost; - if (cost > 0d) { - Economy economy = PlotMain.economy; - if (economy.getBalance(plr) < cost) { - sendMessage(plr, C.CANNOT_AFFORD_PLOT, "" + cost); - return true; - } - economy.withdrawPlayer(plr, cost); - sendMessage(plr, C.REMOVED_BALANCE, cost + ""); - } - } - if(!schematic.equals("")) { - if (pWorld.SCHEMATIC_CLAIM_SPECIFY) { - if(pWorld.SCHEMATICS.contains(schematic.toLowerCase())) { - sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent: " + schematic); - return true; - } - if (!plr.hasPermission("plots.claim." + schematic) && !plr.hasPermission("plots.admin")) { - PlayerFunctions.sendMessage(plr, C.NO_SCHEMATIC_PERMISSION, schematic); - return true; - } - } - } - boolean br = false; - int x = 0, z = 0, q = 100; - PlotId id; - if ((size_x == 1) && (size_z == 1)) { - while (!br) { - id = new PlotId(x, z); - if (PlotHelper.getPlot(world, id).owner == null) { - Plot plot = PlotHelper.getPlot(world, id); - boolean result = Claim.claimPlot(plr, plot, true); - br = !result; - } - if ((z < q) && ((z - x) < q)) { - z++; - } else if (x < q) { - x++; - z = q - 100; - } else { - q += 100; - x = q; - z = q; - } - } - } else { - while (!br) { - PlotId start = new PlotId(x, z); - PlotId end = new PlotId((x + size_x) - 1, (z + size_z) - 1); - if (isUnowned(world, start, end)) { - for (int i = start.x; i <= end.x; i++) { - for (int j = start.y; j <= end.y; j++) { - Plot plot = PlotHelper.getPlot(world, new PlotId(i, j)); - boolean teleport = ((i == end.x) && (j == end.y)); - Claim.claimPlot(plr, plot, teleport); - } - } - if(!PlotHelper.mergePlots(plr, world, PlayerFunctions.getPlotSelectionIds(world, start, end))) { - return false; - } - br = true; - } - if ((z < q) && ((z - x) < q)) { - z += size_z; - } else if (x < q) { - x += size_x; - z = q - 100; - } else { - q += 100; - x = q; - z = q; - } - } - } - return true; - } + // TODO auto claim a mega plot!!!!!!!!!!!! + @Override + public boolean execute(Player plr, String... args) { + World world; + int size_x = 1; + int size_z = 1; + String schematic = ""; + if (PlotMain.getPlotWorlds().length == 1) { + world = Bukkit.getWorld(PlotMain.getPlotWorlds()[0]); + } else { + if (PlotMain.isPlotWorld(plr.getWorld())) { + world = plr.getWorld(); + } else { + PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD); + return false; + } + } + if (args.length > 0) { + if (PlotMain.hasPermission(plr, "plots.auto.mega")) { + try { + String[] split = args[0].split(","); + size_x = Integer.parseInt(split[0]); + size_z = Integer.parseInt(split[1]); + if ((size_x < 1) || (size_z < 1)) { + PlayerFunctions.sendMessage(plr, "&cError: size<=0"); + } + if ((size_x > 4) || (size_z > 4)) { + PlayerFunctions.sendMessage(plr, "&cError: size>4"); + } + if (args.length > 1) { + schematic = args[1]; + } + } catch (Exception e) { + schematic = args[0]; + // PlayerFunctions.sendMessage(plr, + // "&cError: Invalid size (X,Y)"); + // return false; + } + } else { + schematic = args[0]; + // PlayerFunctions.sendMessage(plr, C.NO_PERMISSION); + // return false; + } + } + if (PlayerFunctions.getPlayerPlotCount(world, plr) >= PlayerFunctions + .getAllowedPlots(plr)) { + PlayerFunctions.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS); + return false; + } + PlotWorld pWorld = PlotMain.getWorldSettings(world); + if (PlotMain.useEconomy && pWorld.USE_ECONOMY) { + double cost = pWorld.PLOT_PRICE; + cost = (size_x * size_z) * cost; + if (cost > 0d) { + Economy economy = PlotMain.economy; + if (economy.getBalance(plr) < cost) { + sendMessage(plr, C.CANNOT_AFFORD_PLOT, "" + cost); + return true; + } + economy.withdrawPlayer(plr, cost); + sendMessage(plr, C.REMOVED_BALANCE, cost + ""); + } + } + if (!schematic.equals("")) { + if (pWorld.SCHEMATIC_CLAIM_SPECIFY) { + if (pWorld.SCHEMATICS.contains(schematic.toLowerCase())) { + sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent: " + + schematic); + return true; + } + if (!plr.hasPermission("plots.claim." + schematic) + && !plr.hasPermission("plots.admin")) { + PlayerFunctions.sendMessage(plr, C.NO_SCHEMATIC_PERMISSION, + schematic); + return true; + } + } + } + boolean br = false; + int x = 0, z = 0, q = 100; + PlotId id; + if ((size_x == 1) && (size_z == 1)) { + while (!br) { + id = new PlotId(x, z); + if (PlotHelper.getPlot(world, id).owner == null) { + Plot plot = PlotHelper.getPlot(world, id); + boolean result = Claim.claimPlot(plr, plot, true); + br = !result; + } + if ((z < q) && ((z - x) < q)) { + z++; + } else if (x < q) { + x++; + z = q - 100; + } else { + q += 100; + x = q; + z = q; + } + } + } else { + while (!br) { + PlotId start = new PlotId(x, z); + PlotId end = new PlotId((x + size_x) - 1, (z + size_z) - 1); + if (isUnowned(world, start, end)) { + for (int i = start.x; i <= end.x; i++) { + for (int j = start.y; j <= end.y; j++) { + Plot plot = PlotHelper.getPlot(world, new PlotId(i, + j)); + boolean teleport = ((i == end.x) && (j == end.y)); + Claim.claimPlot(plr, plot, teleport); + } + } + if (!PlotHelper.mergePlots(plr, world, PlayerFunctions + .getPlotSelectionIds(world, start, end))) { + return false; + } + br = true; + } + if ((z < q) && ((z - x) < q)) { + z += size_z; + } else if (x < q) { + x += size_x; + z = q - 100; + } else { + q += 100; + x = q; + z = q; + } + } + } + return true; + } - public boolean isUnowned(World world, PlotId pos1, PlotId pos2) { - for (int x = pos1.x; x <= pos2.x; x++) { - for (int y = pos1.y; y <= pos2.y; y++) { - PlotId id = new PlotId(x, y); - if (PlotMain.getPlots(world).get(id) != null) { - if (PlotMain.getPlots(world).get(id).owner != null) { - return false; - } - } - } - } - return true; - } + public boolean isUnowned(World world, PlotId pos1, PlotId pos2) { + for (int x = pos1.x; x <= pos2.x; x++) { + for (int y = pos1.y; y <= pos2.y; y++) { + PlotId id = new PlotId(x, y); + if (PlotMain.getPlots(world).get(id) != null) { + if (PlotMain.getPlots(world).get(id).owner != null) { + return false; + } + } + } + } + return true; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/commands/Camera.java b/PlotSquared/src/com/intellectualcrafters/plot/commands/Camera.java index c057c5c24..51641dec9 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/commands/Camera.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/commands/Camera.java @@ -17,78 +17,78 @@ import com.intellectualcrafters.plot.C; import com.intellectualcrafters.plot.PlayerFunctions; import com.intellectualcrafters.plot.Plot; import com.intellectualcrafters.plot.PlotHelper; -import com.intellectualcrafters.plot.PlotMain; -import com.intellectualcrafters.plot.PlotWorld; /** * Created by Citymonstret on 2014-08-15. */ public class Camera extends SubCommand implements Listener { - private CameraAPI api; + private CameraAPI api; - public Camera() { - super("camera", "plots.camera", "Go into camera mode", "camera", "c", CommandCategory.TELEPORT); - this.api = CameraAPI.getInstance(); - this.travelers = new ArrayList(); - } + public Camera() { + super("camera", "plots.camera", "Go into camera mode", "camera", "c", + CommandCategory.TELEPORT); + this.api = CameraAPI.getInstance(); + this.travelers = new ArrayList(); + } - private ArrayList travelers; + private ArrayList travelers; - @Override - public boolean execute(Player player, String... args) { - if (!PlayerFunctions.isInPlot(player)) { - PlayerFunctions.sendMessage(player, C.NOT_IN_PLOT); - return false; - } - this.api = CameraAPI.getInstance(); - Plot plot = PlotHelper.getCurrentPlot(player.getLocation()); - if (this.api.isTravelling(player)) { - this.api.stopTravel(player); - PlayerFunctions.sendMessage(player, C.CAMERA_STOPPED); - return true; - } - this.api.travel(getController(player, plot)); - PlayerFunctions.sendMessage(player, C.CAMERA_STARTED, plot.getId().x + ";" + plot.getId().y); - this.travelers.add(player.getName()); - return true; - } + @Override + public boolean execute(Player player, String... args) { + if (!PlayerFunctions.isInPlot(player)) { + PlayerFunctions.sendMessage(player, C.NOT_IN_PLOT); + return false; + } + this.api = CameraAPI.getInstance(); + Plot plot = PlotHelper.getCurrentPlot(player.getLocation()); + if (this.api.isTravelling(player)) { + this.api.stopTravel(player); + PlayerFunctions.sendMessage(player, C.CAMERA_STOPPED); + return true; + } + this.api.travel(getController(player, plot)); + PlayerFunctions.sendMessage(player, C.CAMERA_STARTED, plot.getId().x + + ";" + plot.getId().y); + this.travelers.add(player.getName()); + return true; + } - @EventHandler - public void onTravelEnded(TravelEndEvent event) { - if (this.travelers.contains(event.getPlayer().getName())) { + @EventHandler + public void onTravelEnded(TravelEndEvent event) { + if (this.travelers.contains(event.getPlayer().getName())) { - this.travelers.remove(event.getPlayer().getName()); - PlayerFunctions.sendMessage(event.getPlayer(), C.CAMERA_STOPPED); - } - if (this.travelers.contains(event.getPlayer().getName())) { - event.getHandlers().bake(); - } - } + this.travelers.remove(event.getPlayer().getName()); + PlayerFunctions.sendMessage(event.getPlayer(), C.CAMERA_STOPPED); + } + if (this.travelers.contains(event.getPlayer().getName())) { + event.getHandlers().bake(); + } + } - public CameraController getController(Player player, Plot plot) { - World w = Bukkit.getWorld(plot.world); - PlotWorld plotworld = PlotMain.getWorldSettings(w); - int seconds = plotworld.PLOT_WIDTH * 5; - Location loc1, loc2, loc3, loc4, loc5; - double y = player.getLocation().getY(); - Location bottomLoc = PlotHelper.getPlotBottomLoc(w, plot.id); - Location topLoc = PlotHelper.getPlotTopLoc(w, plot.id); - World world = bottomLoc.getWorld(); - int maxX = Math.max(bottomLoc.getBlockX(), topLoc.getBlockX()); - int maxZ = Math.max(bottomLoc.getBlockZ(), topLoc.getBlockZ()); - int minX = Math.min(bottomLoc.getBlockX(), topLoc.getBlockX()); - int minZ = Math.min(bottomLoc.getBlockZ(), topLoc.getBlockZ()); - loc1 = new Location(world, maxX, y, maxZ); - loc2 = new Location(world, maxX, y, minZ); - loc3 = new Location(world, minX, y, minZ); - loc4 = new Location(world, minX, y, maxZ); - loc1.setYaw(((3 / 4.0F) * 360.0F) - 0.5F); - loc3.setYaw(((1 / 4.0F) * 360.0F) - 0.5F); - loc4.setYaw(((2 / 4.0F) * 360.0F) - 0.5F); - loc2.setYaw(((0 / 4.0F) * 360.0F) - 0.5F); - loc5 = loc1.clone(); - CameraController controller = this.api.createController(player, seconds, loc1, loc2, loc3, loc4, loc5); - return controller; - } + public CameraController getController(Player player, Plot plot) { + World w = Bukkit.getWorld(plot.world); + int seconds = PlotHelper.getPlotWidth(w, plot.id) * 5; + Location loc1, loc2, loc3, loc4, loc5; + double y = player.getLocation().getY(); + Location bottomLoc = PlotHelper.getPlotBottomLoc(w, plot.id); + Location topLoc = PlotHelper.getPlotTopLoc(w, plot.id); + World world = bottomLoc.getWorld(); + int maxX = Math.max(bottomLoc.getBlockX(), topLoc.getBlockX()); + int maxZ = Math.max(bottomLoc.getBlockZ(), topLoc.getBlockZ()); + int minX = Math.min(bottomLoc.getBlockX(), topLoc.getBlockX()); + int minZ = Math.min(bottomLoc.getBlockZ(), topLoc.getBlockZ()); + loc1 = new Location(world, maxX, y, maxZ); + loc2 = new Location(world, maxX, y, minZ); + loc3 = new Location(world, minX, y, minZ); + loc4 = new Location(world, minX, y, maxZ); + loc1.setYaw(((3 / 4.0F) * 360.0F) - 0.5F); + loc3.setYaw(((1 / 4.0F) * 360.0F) - 0.5F); + loc4.setYaw(((2 / 4.0F) * 360.0F) - 0.5F); + loc2.setYaw(((0 / 4.0F) * 360.0F) - 0.5F); + loc5 = loc1.clone(); + CameraController controller = this.api.createController(player, + seconds, loc1, loc2, loc3, loc4, loc5); + return controller; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/commands/Claim.java b/PlotSquared/src/com/intellectualcrafters/plot/commands/Claim.java index 35c1524e7..db475cd88 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/commands/Claim.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/commands/Claim.java @@ -15,6 +15,7 @@ import org.bukkit.Bukkit; import org.bukkit.entity.Player; import com.intellectualcrafters.plot.C; +import com.intellectualcrafters.plot.FlagManager; import com.intellectualcrafters.plot.PlayerFunctions; import com.intellectualcrafters.plot.Plot; import com.intellectualcrafters.plot.PlotHelper; @@ -24,99 +25,106 @@ import com.intellectualcrafters.plot.SchematicHandler; import com.intellectualcrafters.plot.events.PlayerClaimPlotEvent; /** - * + * * @author Citymonstret - * + * */ public class Claim extends SubCommand { - public Claim() { - super(Command.CLAIM, "Claim the current plot you're standing on.", "claim", CommandCategory.CLAIMING); - } + public Claim() { + super(Command.CLAIM, "Claim the current plot you're standing on.", + "claim", CommandCategory.CLAIMING); + } - @Override - public boolean execute(Player plr, String... args) { - String schematic = ""; - if (args.length >= 1) { - schematic = args[0]; - } - if (!PlayerFunctions.isInPlot(plr)) { - PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); - return true; - } - if (PlayerFunctions.getPlayerPlotCount(plr.getWorld(), plr) >= PlayerFunctions.getAllowedPlots(plr)) { - PlayerFunctions.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS); - return true; - } - Plot plot = PlayerFunctions.getCurrentPlot(plr); - if (plot.hasOwner()) { - PlayerFunctions.sendMessage(plr, C.PLOT_IS_CLAIMED); - return false; - } - PlotWorld world = PlotMain.getWorldSettings(plot.getWorld()); - if (PlotMain.useEconomy && world.USE_ECONOMY) { - double cost = world.PLOT_PRICE; - if (cost > 0d) { - Economy economy = PlotMain.economy; - if (economy.getBalance(plr) < cost) { - sendMessage(plr, C.CANNOT_AFFORD_PLOT, "" + cost); - return true; - } - economy.withdrawPlayer(plr, cost); - sendMessage(plr, C.REMOVED_BALANCE, cost + ""); - } - } - if (!schematic.equals("")) { - if (world.SCHEMATIC_CLAIM_SPECIFY) { - if (!world.SCHEMATICS.contains(schematic.toLowerCase())) { - sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent: " + schematic); - return true; - } - if (!plr.hasPermission("plots.claim." + schematic) && !plr.hasPermission("plots.admin")) { - PlayerFunctions.sendMessage(plr, C.NO_SCHEMATIC_PERMISSION, schematic); - return true; - } - } - } - boolean result = claimPlot(plr, plot, false, schematic); - if (result) { - PlayerFunctions.sendMessage(plr, C.PLOT_NOT_CLAIMED); - return false; - } - return true; + @Override + public boolean execute(Player plr, String... args) { + String schematic = ""; + if (args.length >= 1) { + schematic = args[0]; + } + if (!PlayerFunctions.isInPlot(plr)) { + PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); + return true; + } + if (PlayerFunctions.getPlayerPlotCount(plr.getWorld(), plr) >= PlayerFunctions + .getAllowedPlots(plr)) { + PlayerFunctions.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS); + return true; + } + Plot plot = PlayerFunctions.getCurrentPlot(plr); + if (plot.hasOwner()) { + PlayerFunctions.sendMessage(plr, C.PLOT_IS_CLAIMED); + return false; + } + PlotWorld world = PlotMain.getWorldSettings(plot.getWorld()); + if (PlotMain.useEconomy && world.USE_ECONOMY) { + double cost = world.PLOT_PRICE; + if (cost > 0d) { + Economy economy = PlotMain.economy; + if (economy.getBalance(plr) < cost) { + sendMessage(plr, C.CANNOT_AFFORD_PLOT, "" + cost); + return true; + } + economy.withdrawPlayer(plr, cost); + sendMessage(plr, C.REMOVED_BALANCE, cost + ""); + } + } + if (!schematic.equals("")) { + if (world.SCHEMATIC_CLAIM_SPECIFY) { + if (!world.SCHEMATICS.contains(schematic.toLowerCase())) { + sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent: " + + schematic); + return true; + } + if (!plr.hasPermission("plots.claim." + schematic) + && !plr.hasPermission("plots.admin")) { + PlayerFunctions.sendMessage(plr, C.NO_SCHEMATIC_PERMISSION, + schematic); + return true; + } + } + } + boolean result = claimPlot(plr, plot, false, schematic); + if (result) { + PlayerFunctions.sendMessage(plr, C.PLOT_NOT_CLAIMED); + return false; + } + return true; - } + } - public static boolean claimPlot(Player player, Plot plot, boolean teleport) { - return claimPlot(player, plot, teleport, ""); - } + public static boolean claimPlot(Player player, Plot plot, boolean teleport) { + return claimPlot(player, plot, teleport, ""); + } - public static boolean claimPlot(Player player, Plot plot, boolean teleport, String schematic) { - PlayerClaimPlotEvent event = new PlayerClaimPlotEvent(player, plot); - Bukkit.getPluginManager().callEvent(event); - if (!event.isCancelled()) { - PlotHelper.createPlot(player, plot); - PlotHelper.setSign(player, plot); - PlayerFunctions.sendMessage(player, C.CLAIMED); - if (teleport) { - PlotMain.teleportPlayer(player, player.getLocation(), plot); - } - PlotWorld world = PlotMain.getWorldSettings(plot.getWorld()); - if (world.SCHEMATIC_ON_CLAIM) { - SchematicHandler handler = new SchematicHandler(); - SchematicHandler.Schematic sch; - if (schematic.equals("")) { - sch = handler.getSchematic(world.SCHEMATIC_FILE); - } else { - sch = handler.getSchematic(schematic); - if (sch == null) { - sch = handler.getSchematic(world.SCHEMATIC_FILE); - } - } - handler.paste(player.getLocation(), sch, plot); - } - plot.settings.setFlags(PlotMain.getWorldSettings(player.getWorld()).DEFAULT_FLAGS); - } - return event.isCancelled(); - } + public static boolean claimPlot(Player player, Plot plot, boolean teleport, + String schematic) { + PlayerClaimPlotEvent event = new PlayerClaimPlotEvent(player, plot); + Bukkit.getPluginManager().callEvent(event); + if (!event.isCancelled()) { + PlotHelper.createPlot(player, plot); + PlotHelper.setSign(player, plot); + PlayerFunctions.sendMessage(player, C.CLAIMED); + if (teleport) { + PlotMain.teleportPlayer(player, player.getLocation(), plot); + } + PlotWorld world = PlotMain.getWorldSettings(plot.getWorld()); + if (world.SCHEMATIC_ON_CLAIM) { + SchematicHandler handler = new SchematicHandler(); + SchematicHandler.Schematic sch; + if (schematic.equals("")) { + sch = handler.getSchematic(world.SCHEMATIC_FILE); + } else { + sch = handler.getSchematic(schematic); + if (sch == null) { + sch = handler.getSchematic(world.SCHEMATIC_FILE); + } + } + handler.paste(player.getLocation(), sch, plot); + } + plot.settings.setFlags(FlagManager.parseFlags(PlotMain + .getWorldSettings(player.getWorld()).DEFAULT_FLAGS)); + } + return event.isCancelled(); + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/commands/Clear.java b/PlotSquared/src/com/intellectualcrafters/plot/commands/Clear.java index 5f599450f..63a341a06 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/commands/Clear.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/commands/Clear.java @@ -20,22 +20,24 @@ import com.intellectualcrafters.plot.Plot; */ public class Clear extends SubCommand { - public Clear() { - super(Command.CLEAR, "Clear a plot", "clear", CommandCategory.ACTIONS); - } + public Clear() { + super(Command.CLEAR, "Clear a plot", "clear", CommandCategory.ACTIONS); + } - @Override - public boolean execute(Player plr, String... args) { - if (!PlayerFunctions.isInPlot(plr)) { - PlayerFunctions.sendMessage(plr, "You're not in a plot."); - return false; - } - Plot plot = PlayerFunctions.getCurrentPlot(plr); - if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId())) && !plr.hasPermission("plots.admin")) { - PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); - return false; - } - plot.clear(plr); - return true; - } + @Override + public boolean execute(Player plr, String... args) { + if (!PlayerFunctions.isInPlot(plr)) { + PlayerFunctions.sendMessage(plr, "You're not in a plot."); + return false; + } + Plot plot = PlayerFunctions.getCurrentPlot(plr); + if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals( + plr.getUniqueId())) + && !plr.hasPermission("plots.admin")) { + PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); + return false; + } + plot.clear(plr); + return true; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/commands/Command.java b/PlotSquared/src/com/intellectualcrafters/plot/commands/Command.java index 84eb86db4..7279e477e 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/commands/Command.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/commands/Command.java @@ -11,167 +11,167 @@ package com.intellectualcrafters.plot.commands; /** * Created by Citymonstret on 2014-08-03. - * + * * @author Citymonstret */ public enum Command { - // TODO new commands - // (allow a plot to be transferred from one plot to another of the same - // size) - // - /plot copy - // - /plot paste - // (economy) - // - /plot buy - // - /plot sell - // (Rating system) (ratings can be stored as the average, and number of - // ratings) - // - /plot rate - // - /plot list - TRUSTED("trusted", "trust"), - /** - * - */ - COPY("copy"), - /** - * - */ - KICK("kick", "k"), - /** - * - */ - HELPERS("helpers", "hp"), - /** - * - */ - DENIED("denied", "dn"), - /** - * - */ - CLAIM("claim", "c"), - /** - * - */ - MERGE("merge", "m"), - /** - * - */ - UNLINK("unlink", "u"), - /** - * - */ - CLEAR("clear", "clear", new CommandPermission("plots.clear")), - /** - * - */ - DELETE("delete", "d", new CommandPermission("plots.delete")), - /** - * - */ - DEBUG("debug", "database", new CommandPermission("plots.admin")), - /** - * - */ - HOME("home", "h"), - /** - * - */ - INFO("info", "i"), - /** - * - */ - LIST("list", "l"), - /** - * - */ - SET("set", "s"), - /** - * - */ - SETUP("setup"), - /** - * - */ - TP("tp", "tp"); - /** - * - */ - private String command; - /** - * - */ - private String alias; - /** - * - */ - private CommandPermission permission; + // TODO new commands + // (allow a plot to be transferred from one plot to another of the same + // size) + // - /plot copy + // - /plot paste + // (economy) + // - /plot buy + // - /plot sell + // (Rating system) (ratings can be stored as the average, and number of + // ratings) + // - /plot rate + // - /plot list + TRUSTED("trusted", "trust"), + /** + * + */ + COPY("copy"), + /** + * + */ + KICK("kick", "k"), + /** + * + */ + HELPERS("helpers", "hp"), + /** + * + */ + DENIED("denied", "dn"), + /** + * + */ + CLAIM("claim", "c"), + /** + * + */ + MERGE("merge", "m"), + /** + * + */ + UNLINK("unlink", "u"), + /** + * + */ + CLEAR("clear", "clear", new CommandPermission("plots.clear")), + /** + * + */ + DELETE("delete", "d", new CommandPermission("plots.delete")), + /** + * + */ + DEBUG("debug", "database", new CommandPermission("plots.admin")), + /** + * + */ + HOME("home", "h"), + /** + * + */ + INFO("info", "i"), + /** + * + */ + LIST("list", "l"), + /** + * + */ + SET("set", "s"), + /** + * + */ + SETUP("setup"), + /** + * + */ + TP("tp", "tp"); + /** + * + */ + private String command; + /** + * + */ + private String alias; + /** + * + */ + private CommandPermission permission; - /** - * - * @param command - */ - Command(String command) { - this.command = command; - this.alias = command; - this.permission = new CommandPermission("plots." + command); - } + /** + * + * @param command + */ + Command(String command) { + this.command = command; + this.alias = command; + this.permission = new CommandPermission("plots." + command); + } - /** - * - * @param command - * @param permission - */ - Command(String command, CommandPermission permission) { - this.command = command; - this.permission = permission; - this.alias = command; - } + /** + * + * @param command + * @param permission + */ + Command(String command, CommandPermission permission) { + this.command = command; + this.permission = permission; + this.alias = command; + } - /** - * - * @param command - * @param alias - */ - Command(String command, String alias) { - this.command = command; - this.alias = alias; - this.permission = new CommandPermission("plots." + command); - } + /** + * + * @param command + * @param alias + */ + Command(String command, String alias) { + this.command = command; + this.alias = alias; + this.permission = new CommandPermission("plots." + command); + } - /** - * - * @param Command - * @param alias - * @param permission - */ - Command(String command, String alias, CommandPermission permission) { - this.command = command; - this.alias = alias; - this.permission = permission; - } + /** + * + * @param Command + * @param alias + * @param permission + */ + Command(String command, String alias, CommandPermission permission) { + this.command = command; + this.alias = alias; + this.permission = permission; + } - /** - * - * @return - */ - public String getCommand() { - return this.command; - } + /** + * + * @return + */ + public String getCommand() { + return this.command; + } - /** - * - * @return - */ - public String getAlias() { - return this.alias; - } + /** + * + * @return + */ + public String getAlias() { + return this.alias; + } - /** - * - * @return - */ - public CommandPermission getPermission() { - return this.permission; - } + /** + * + * @return + */ + public CommandPermission getPermission() { + return this.permission; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/commands/CommandPermission.java b/PlotSquared/src/com/intellectualcrafters/plot/commands/CommandPermission.java index e051bb631..8c0053f3f 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/commands/CommandPermission.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/commands/CommandPermission.java @@ -13,29 +13,30 @@ import org.bukkit.entity.Player; /** * Created by Citymonstret on 2014-08-03. - * + * * @author Citymonstret */ public class CommandPermission { - /** - * - */ - private String permission; + /** + * + */ + private String permission; - /** - * @param permission - */ - public CommandPermission(String permission) { - this.permission = permission.toLowerCase(); - } + /** + * @param permission + */ + public CommandPermission(String permission) { + this.permission = permission.toLowerCase(); + } - /** - * - * @param player - * @return - */ - public boolean hasPermission(Player player) { - return player.hasPermission(this.permission) || player.hasPermission("plots.admin"); - } + /** + * + * @param player + * @return + */ + public boolean hasPermission(Player player) { + return player.hasPermission(this.permission) + || player.hasPermission("plots.admin"); + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/commands/Copy.java b/PlotSquared/src/com/intellectualcrafters/plot/commands/Copy.java index ecd8ad95a..32a254a4c 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/commands/Copy.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/commands/Copy.java @@ -20,22 +20,24 @@ import com.intellectualcrafters.plot.Plot; */ public class Copy extends SubCommand { - public Copy() { - super(Command.COPY, "Copy a plot", "clear", CommandCategory.ACTIONS); - } + public Copy() { + super(Command.COPY, "Copy a plot", "clear", CommandCategory.ACTIONS); + } - @Override - public boolean execute(Player plr, String... args) { - if (!PlayerFunctions.isInPlot(plr)) { - PlayerFunctions.sendMessage(plr, "You're not in a plot."); - return false; - } - Plot plot = PlayerFunctions.getCurrentPlot(plr); - if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId())) && !plr.hasPermission("plots.admin")) { - PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); - return false; - } - plot.clear(plr); - return true; - } + @Override + public boolean execute(Player plr, String... args) { + if (!PlayerFunctions.isInPlot(plr)) { + PlayerFunctions.sendMessage(plr, "You're not in a plot."); + return false; + } + Plot plot = PlayerFunctions.getCurrentPlot(plr); + if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals( + plr.getUniqueId())) + && !plr.hasPermission("plots.admin")) { + PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); + return false; + } + plot.clear(plr); + return true; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/commands/Debug.java b/PlotSquared/src/com/intellectualcrafters/plot/commands/Debug.java index fb7ea0961..a74b6fa08 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/commands/Debug.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/commands/Debug.java @@ -31,92 +31,105 @@ import com.intellectualcrafters.plot.RUtils; */ public class Debug extends SubCommand { - // private extends SubCommand^Implements {Command, Information} from - // >>\\S.txt6\\ - public Debug() { - super(Command.DEBUG, "Show debug information", "debug [msg]", CommandCategory.INFO); - { - /** - * This. - */ - } - } + // private extends SubCommand^Implements {Command, Information} from + // >>\\S.txt6\\ + public Debug() { + super(Command.DEBUG, "Show debug information", "debug [msg]", + CommandCategory.INFO); + { + /** + * This. + */ + } + } - @Override - public boolean execute(Player plr, String... args) { - PlotMain.getWorldSettings(plr.getWorld()); - if ((args.length > 0) && args[0].equalsIgnoreCase("msg")) { - StringBuilder msg = new StringBuilder(); - for (C c : C.values()) { - msg.append(c.s() + "\n"); - } - PlayerFunctions.sendMessage(plr, msg.toString()); - return true; - } - StringBuilder information; - String header, line, section; - /** - * {$notnull || compile:: \\Debug:Captions\\} - */ - { - information = new StringBuilder(); - header = C.DEUBG_HEADER.s(); - line = C.DEBUG_LINE.s(); - section = C.DEBUG_SECTION.s(); - } - /** - * {||direct:: load: debug::I>Captions::trsl} \\ if(missing) - * set(default) -> this->(){} \\ echo line->line(Compiler.cpp -> - * lineCompiler); when finished: now = this(); - * now(getter)->setter(this())->{ "string" = getter(this); - * setter(string) = getter(this->setter); } when ^ finished compile; - * if(^compile failed -> |this->failed.|tests->failed.| ||run test - * {this->test}|on fail(action(){return FAILED})| - */ - { - StringBuilder worlds = new StringBuilder(""); - for (String world : PlotMain.getPlotWorlds()) { - worlds.append(world + " "); - } - information.append(header); - information.append(getSection(section, "Lag / TPS")); - information.append(getLine(line, "Ticks Per Second", Lag.getTPS())); - information.append(getLine(line, "Lag Percentage", (int) Lag.getPercentage() + "%")); - information.append(getLine(line, "TPS Percentage", (int) Lag.getFullPercentage() + "%")); - information.append(getSection(section, "PlotWorld")); - information.append(getLine(line, "Plot Worlds", worlds)); - information.append(getLine(line, "Owned Plots", PlotMain.getPlots().size())); - // information.append(getLine(line, "PlotWorld Size", - // PlotHelper.getWorldFolderSize() + "MB")); - for (String world : PlotMain.getPlotWorlds()) { - information.append(getLine(line, "World: " + world + " size", PlotHelper.getWorldFolderSize(Bukkit.getWorld(world)))); - } - information.append(getLine(line, "Entities", PlotHelper.getEntities(plr.getWorld()))); - information.append(getLine(line, "Loaded Tile Entities", PlotHelper.getTileEntities(plr.getWorld()))); - information.append(getLine(line, "Loaded Chunks", PlotHelper.getLoadedChunks(plr.getWorld()))); - information.append(getSection(section, "RAM")); - information.append(getLine(line, "Free Ram", RUtils.getFreeRam() + "MB")); - information.append(getLine(line, "Total Ram", RUtils.getTotalRam() + "MB")); - information.append(getSection(section, "Messages")); - information.append(getLine(line, "Total Messages", C.values().length)); - information.append(getLine(line, "View all captions", "/plot debug msg")); - } - /** - * {function:: SEND_MESSAGE |local player -> plr|local string -> - * information.toString())} - */ - { - PlayerFunctions.sendMessage(plr, information.toString()); - } - return true; - } + @Override + public boolean execute(Player plr, String... args) { + PlotMain.getWorldSettings(plr.getWorld()); + if ((args.length > 0) && args[0].equalsIgnoreCase("msg")) { + StringBuilder msg = new StringBuilder(); + for (C c : C.values()) { + msg.append(c.s() + "\n"); + } + PlayerFunctions.sendMessage(plr, msg.toString()); + return true; + } + StringBuilder information; + String header, line, section; + /** + * {$notnull || compile:: \\Debug:Captions\\} + */ + { + information = new StringBuilder(); + header = C.DEUBG_HEADER.s(); + line = C.DEBUG_LINE.s(); + section = C.DEBUG_SECTION.s(); + } + /** + * {||direct:: load: debug::I>Captions::trsl} \\ if(missing) + * set(default) -> this->(){} \\ echo line->line(Compiler.cpp -> + * lineCompiler); when finished: now = this(); + * now(getter)->setter(this())->{ "string" = getter(this); + * setter(string) = getter(this->setter); } when ^ finished compile; + * if(^compile failed -> |this->failed.|tests->failed.| ||run test + * {this->test}|on fail(action(){return FAILED})| + */ + { + StringBuilder worlds = new StringBuilder(""); + for (String world : PlotMain.getPlotWorlds()) { + worlds.append(world + " "); + } + information.append(header); + information.append(getSection(section, "Lag / TPS")); + information.append(getLine(line, "Ticks Per Second", Lag.getTPS())); + information.append(getLine(line, "Lag Percentage", + (int) Lag.getPercentage() + "%")); + information.append(getLine(line, "TPS Percentage", + (int) Lag.getFullPercentage() + "%")); + information.append(getSection(section, "PlotWorld")); + information.append(getLine(line, "Plot Worlds", worlds)); + information.append(getLine(line, "Owned Plots", PlotMain.getPlots() + .size())); + // information.append(getLine(line, "PlotWorld Size", + // PlotHelper.getWorldFolderSize() + "MB")); + for (String world : PlotMain.getPlotWorlds()) { + information.append(getLine(line, "World: " + world + " size", + PlotHelper.getWorldFolderSize(Bukkit.getWorld(world)))); + } + information.append(getLine(line, "Entities", + PlotHelper.getEntities(plr.getWorld()))); + information.append(getLine(line, "Loaded Tile Entities", + PlotHelper.getTileEntities(plr.getWorld()))); + information.append(getLine(line, "Loaded Chunks", + PlotHelper.getLoadedChunks(plr.getWorld()))); + information.append(getSection(section, "RAM")); + information.append(getLine(line, "Free Ram", RUtils.getFreeRam() + + "MB")); + information.append(getLine(line, "Total Ram", RUtils.getTotalRam() + + "MB")); + information.append(getSection(section, "Messages")); + information.append(getLine(line, "Total Messages", + C.values().length)); + information.append(getLine(line, "View all captions", + "/plot debug msg")); + } + /** + * {function:: SEND_MESSAGE |local player -> plr|local string -> + * information.toString())} + */ + { + PlayerFunctions.sendMessage(plr, information.toString()); + } + return true; + } - private String getSection(String line, String val) { - return line.replaceAll("%val%", val) + "\n"; - } + private String getSection(String line, String val) { + return line.replaceAll("%val%", val) + "\n"; + } - private String getLine(String line, String var, Object val) { - return line.replaceAll("%var%", var).replaceAll("%val%", "" + val) + "\n"; - } + private String getLine(String line, String var, Object val) { + return line.replaceAll("%var%", var).replaceAll("%val%", "" + val) + + "\n"; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/commands/Delete.java b/PlotSquared/src/com/intellectualcrafters/plot/commands/Delete.java index 888e9dac9..f33e2e58b 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/commands/Delete.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/commands/Delete.java @@ -9,52 +9,64 @@ package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.*; -import com.intellectualcrafters.plot.database.DBFunc; import net.milkbowl.vault.economy.Economy; + import org.bukkit.entity.Player; +import com.intellectualcrafters.plot.C; +import com.intellectualcrafters.plot.PlayerFunctions; +import com.intellectualcrafters.plot.Plot; +import com.intellectualcrafters.plot.PlotHelper; +import com.intellectualcrafters.plot.PlotMain; +import com.intellectualcrafters.plot.PlotWorld; +import com.intellectualcrafters.plot.database.DBFunc; + /** * Created by Citymonstret on 2014-08-01. */ public class Delete extends SubCommand { - public Delete() { - super(Command.DELETE, "Delete a plot", "delete", CommandCategory.ACTIONS); - } + public Delete() { + super(Command.DELETE, "Delete a plot", "delete", + CommandCategory.ACTIONS); + } - @Override - public boolean execute(Player plr, String... args) { - if (!PlayerFunctions.isInPlot(plr)) { - PlayerFunctions.sendMessage(plr, "You're not in a plot."); - return false; - } - Plot plot = PlayerFunctions.getCurrentPlot(plr); - if (!PlayerFunctions.getTopPlot(plr.getWorld(), plot).equals(PlayerFunctions.getBottomPlot(plr.getWorld(), plot))) { - PlayerFunctions.sendMessage(plr, C.UNLINK_REQUIRED); - return false; - } - if ((((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId()))) && !plr.hasPermission("plots.admin")) { - PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); - return false; - } - PlotWorld pWorld = PlotMain.getWorldSettings(plot.getWorld()); - if(PlotMain.useEconomy && pWorld.USE_ECONOMY) { - double c = pWorld.SELL_PRICE; - if(c > 0d) { - Economy economy = PlotMain.economy; - economy.depositPlayer(plr, c); - sendMessage(plr, C.ADDED_BALANCE, c + ""); - } - } - boolean result = PlotMain.removePlot(plr.getWorld().getName(), plot.id, true); - if (result) { - PlotHelper.removeSign(plr, plot); - plot.clear(plr); - DBFunc.delete(plr.getWorld().getName(), plot); - } else { - PlayerFunctions.sendMessage(plr, "Plot clearing has been denied."); - } - return true; - } + @Override + public boolean execute(Player plr, String... args) { + if (!PlayerFunctions.isInPlot(plr)) { + PlayerFunctions.sendMessage(plr, "You're not in a plot."); + return false; + } + Plot plot = PlayerFunctions.getCurrentPlot(plr); + if (!PlayerFunctions.getTopPlot(plr.getWorld(), plot).equals( + PlayerFunctions.getBottomPlot(plr.getWorld(), plot))) { + PlayerFunctions.sendMessage(plr, C.UNLINK_REQUIRED); + return false; + } + if ((((plot == null) || !plot.hasOwner() || !plot.getOwner().equals( + plr.getUniqueId()))) + && !plr.hasPermission("plots.admin")) { + PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); + return false; + } + PlotWorld pWorld = PlotMain.getWorldSettings(plot.getWorld()); + if (PlotMain.useEconomy && pWorld.USE_ECONOMY) { + double c = pWorld.SELL_PRICE; + if (c > 0d) { + Economy economy = PlotMain.economy; + economy.depositPlayer(plr, c); + sendMessage(plr, C.ADDED_BALANCE, c + ""); + } + } + boolean result = PlotMain.removePlot(plr.getWorld().getName(), plot.id, + true); + if (result) { + PlotHelper.removeSign(plr, plot); + plot.clear(plr); + DBFunc.delete(plr.getWorld().getName(), plot); + } else { + PlayerFunctions.sendMessage(plr, "Plot clearing has been denied."); + } + return true; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/commands/Denied.java b/PlotSquared/src/com/intellectualcrafters/plot/commands/Denied.java index fcb8e55e0..b3909e1a5 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/commands/Denied.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/commands/Denied.java @@ -9,17 +9,17 @@ package com.intellectualcrafters.plot.commands; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + import com.intellectualcrafters.plot.C; import com.intellectualcrafters.plot.PlayerFunctions; import com.intellectualcrafters.plot.Plot; import com.intellectualcrafters.plot.UUIDHandler; import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.events.PlayerPlotDeniedEvent; -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.bukkit.entity.Player; - -import java.util.UUID; /** * Created by Citymonstret on 2014-08-03. @@ -27,118 +27,100 @@ import java.util.UUID; @SuppressWarnings("deprecated") public class Denied extends SubCommand { - public Denied() { - super(Command.DENIED, "Manage plot helpers", "denied {add|remove} {player}", CommandCategory.ACTIONS); - } + public Denied() { + super(Command.DENIED, "Manage plot helpers", + "denied {add|remove} {player}", CommandCategory.ACTIONS); + } - private boolean hasBeenOnServer(String name) { - Player plr = Bukkit.getPlayer(name); - if (plr == null) { - OfflinePlayer oplr = Bukkit.getPlayer(name); - if (oplr == null) { - return false; - } else { - return oplr.hasPlayedBefore(); - } - } else { - if (plr.isOnline()) { - return true; - } else { - return plr.hasPlayedBefore(); - } - } - } - - @Override - public boolean execute(Player plr, String... args) { - if (args.length < 2) { - PlayerFunctions.sendMessage(plr, C.DENIED_NEED_ARGUMENT); - return true; - } - if (!PlayerFunctions.isInPlot(plr)) { - PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); - return true; - } - Plot plot = PlayerFunctions.getCurrentPlot(plr); - if ((plot.owner == null) || !plot.hasRights(plr)) { - PlayerFunctions.sendMessage(plr, C.NO_PERMISSION); - return true; - } - if (args[0].equalsIgnoreCase("add")) { - if (args[1].equalsIgnoreCase("*")) { - UUID uuid = DBFunc.everyone; - plot.addDenied(uuid); - DBFunc.setDenied(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); - PlayerFunctions.sendMessage(plr, C.DENIED_ADDED); - return true; - } - /*if (!hasBeenOnServer(args[1])) { - PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); - return true; - } - UUID uuid = null; - if ((Bukkit.getPlayer(args[1]) != null)) { - uuid = Bukkit.getPlayer(args[1]).getUniqueId(); - } else { - uuid = Bukkit.getOfflinePlayer(args[1]).getUniqueId(); - } - if (uuid == null) { - PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); - return true; - }*/ - UUID uuid = UUIDHandler.getUUID(args[1]); - plot.addDenied(uuid); - DBFunc.setDenied(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); - PlayerPlotDeniedEvent event = new PlayerPlotDeniedEvent(plr, plot, uuid, true); - Bukkit.getPluginManager().callEvent(event); - PlayerFunctions.sendMessage(plr, C.DENIED_ADDED); - if ((Bukkit.getPlayer(uuid) != null) && Bukkit.getPlayer(uuid).isOnline()) { - Plot pl = PlayerFunctions.getCurrentPlot(Bukkit.getPlayer((uuid))); - if (pl.id == plot.id) { - PlayerFunctions.sendMessage(Bukkit.getPlayer(uuid), C.YOU_BE_DENIED); - Bukkit.getPlayer(uuid).teleport(Bukkit.getPlayer(uuid).getWorld().getSpawnLocation()); - } - } - } else if (args[0].equalsIgnoreCase("remove")) { - if (args[1].equalsIgnoreCase("*")) { - UUID uuid = DBFunc.everyone; - if (!plot.denied.contains(uuid)) { - PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED); - return true; - } - plot.removeDenied(uuid); - DBFunc.removeDenied(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); - PlayerFunctions.sendMessage(plr, C.DENIED_REMOVED); - return true; - } - /*if (!hasBeenOnServer(args[1])) { - PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); - return true; - } - UUID uuid = null; - if (Bukkit.getPlayer(args[1])!=null) { - uuid = Bukkit.getPlayer(args[1]).getUniqueId(); - } else { - uuid = Bukkit.getOfflinePlayer(args[1]).getUniqueId(); - } - if (!plot.denied.contains(uuid)) { - PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED); - return true; - } - if (uuid == null) { - PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); - return true; - }*/ - UUID uuid = UUIDHandler.getUUID(args[1]); - plot.removeDenied(uuid); - DBFunc.removeDenied(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); - PlayerPlotDeniedEvent event = new PlayerPlotDeniedEvent(plr, plot, uuid, false); - Bukkit.getPluginManager().callEvent(event); - PlayerFunctions.sendMessage(plr, C.DENIED_REMOVED); - } else { - PlayerFunctions.sendMessage(plr, C.DENIED_NEED_ARGUMENT); - return true; - } - return true; - } + @Override + public boolean execute(Player plr, String... args) { + if (args.length < 2) { + PlayerFunctions.sendMessage(plr, C.DENIED_NEED_ARGUMENT); + return true; + } + if (!PlayerFunctions.isInPlot(plr)) { + PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); + return true; + } + Plot plot = PlayerFunctions.getCurrentPlot(plr); + if ((plot.owner == null) || !plot.hasRights(plr)) { + PlayerFunctions.sendMessage(plr, C.NO_PERMISSION); + return true; + } + if (args[0].equalsIgnoreCase("add")) { + if (args[1].equalsIgnoreCase("*")) { + UUID uuid = DBFunc.everyone; + plot.addDenied(uuid); + DBFunc.setDenied(plr.getWorld().getName(), plot, + Bukkit.getOfflinePlayer(args[1])); + PlayerFunctions.sendMessage(plr, C.DENIED_ADDED); + return true; + } + /* + * if (!hasBeenOnServer(args[1])) { PlayerFunctions.sendMessage(plr, + * C.PLAYER_HAS_NOT_BEEN_ON); return true; } UUID uuid = null; if + * ((Bukkit.getPlayer(args[1]) != null)) { uuid = + * Bukkit.getPlayer(args[1]).getUniqueId(); } else { uuid = + * Bukkit.getOfflinePlayer(args[1]).getUniqueId(); } if (uuid == + * null) { PlayerFunctions.sendMessage(plr, + * C.PLAYER_HAS_NOT_BEEN_ON); return true; } + */ + UUID uuid = UUIDHandler.getUUID(args[1]); + plot.addDenied(uuid); + DBFunc.setDenied(plr.getWorld().getName(), plot, + Bukkit.getOfflinePlayer(args[1])); + PlayerPlotDeniedEvent event = new PlayerPlotDeniedEvent(plr, plot, + uuid, true); + Bukkit.getPluginManager().callEvent(event); + PlayerFunctions.sendMessage(plr, C.DENIED_ADDED); + if ((Bukkit.getPlayer(uuid) != null) + && Bukkit.getPlayer(uuid).isOnline()) { + Plot pl = PlayerFunctions.getCurrentPlot(Bukkit + .getPlayer((uuid))); + if (pl.id == plot.id) { + PlayerFunctions.sendMessage(Bukkit.getPlayer(uuid), + C.YOU_BE_DENIED); + Bukkit.getPlayer(uuid).teleport( + Bukkit.getPlayer(uuid).getWorld() + .getSpawnLocation()); + } + } + } else if (args[0].equalsIgnoreCase("remove")) { + if (args[1].equalsIgnoreCase("*")) { + UUID uuid = DBFunc.everyone; + if (!plot.denied.contains(uuid)) { + PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED); + return true; + } + plot.removeDenied(uuid); + DBFunc.removeDenied(plr.getWorld().getName(), plot, + Bukkit.getOfflinePlayer(args[1])); + PlayerFunctions.sendMessage(plr, C.DENIED_REMOVED); + return true; + } + /* + * if (!hasBeenOnServer(args[1])) { PlayerFunctions.sendMessage(plr, + * C.PLAYER_HAS_NOT_BEEN_ON); return true; } UUID uuid = null; if + * (Bukkit.getPlayer(args[1])!=null) { uuid = + * Bukkit.getPlayer(args[1]).getUniqueId(); } else { uuid = + * Bukkit.getOfflinePlayer(args[1]).getUniqueId(); } if + * (!plot.denied.contains(uuid)) { PlayerFunctions.sendMessage(plr, + * C.WAS_NOT_ADDED); return true; } if (uuid == null) { + * PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); + * return true; } + */ + UUID uuid = UUIDHandler.getUUID(args[1]); + plot.removeDenied(uuid); + DBFunc.removeDenied(plr.getWorld().getName(), plot, + Bukkit.getOfflinePlayer(args[1])); + PlayerPlotDeniedEvent event = new PlayerPlotDeniedEvent(plr, plot, + uuid, false); + Bukkit.getPluginManager().callEvent(event); + PlayerFunctions.sendMessage(plr, C.DENIED_REMOVED); + } else { + PlayerFunctions.sendMessage(plr, C.DENIED_NEED_ARGUMENT); + return true; + } + return true; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/commands/Help.java b/PlotSquared/src/com/intellectualcrafters/plot/commands/Help.java index 7a3324f22..9fe5651d5 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/commands/Help.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/commands/Help.java @@ -15,12 +15,13 @@ import org.bukkit.entity.Player; * Created by Citymonstret on 2014-08-11. */ public class Help extends SubCommand { - public Help() { - super("help", "", "Get this help menu", "help", "he", SubCommand.CommandCategory.INFO); - } + public Help() { + super("help", "", "Get this help menu", "help", "he", + SubCommand.CommandCategory.INFO); + } - @Override - public boolean execute(Player plr, String... args) { - return false; - } + @Override + public boolean execute(Player plr, String... args) { + return false; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/commands/Helpers.java b/PlotSquared/src/com/intellectualcrafters/plot/commands/Helpers.java index 38a70d2f0..54abdf9c3 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/commands/Helpers.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/commands/Helpers.java @@ -9,126 +9,103 @@ package com.intellectualcrafters.plot.commands; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + import com.intellectualcrafters.plot.C; import com.intellectualcrafters.plot.PlayerFunctions; import com.intellectualcrafters.plot.Plot; import com.intellectualcrafters.plot.UUIDHandler; import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.events.PlayerPlotHelperEvent; -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.bukkit.entity.Player; - -import java.util.UUID; @SuppressWarnings("deprecation") public class Helpers extends SubCommand { - public Helpers() { - super(Command.HELPERS, "Manage plot helpers", "helpers {add|remove} {player}", CommandCategory.ACTIONS); - } + public Helpers() { + super(Command.HELPERS, "Manage plot helpers", + "helpers {add|remove} {player}", CommandCategory.ACTIONS); + } - private boolean hasBeenOnServer(String name) { - Player plr = Bukkit.getPlayer(name); - if (plr == null) { - OfflinePlayer oplr = Bukkit.getOfflinePlayer(name); - if (oplr == null) { - return false; - } else { - return oplr.hasPlayedBefore(); - } - } else { - if (plr.isOnline()) { - return true; - } else { - return plr.hasPlayedBefore(); - } - } - } - - @Override - public boolean execute(Player plr, String... args) { - if (args.length < 2) { - PlayerFunctions.sendMessage(plr, C.HELPER_NEED_ARGUMENT); - return true; - } - if (!PlayerFunctions.isInPlot(plr)) { - PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); - return true; - } - Plot plot = PlayerFunctions.getCurrentPlot(plr); - if ((plot.owner == null) || !plot.hasRights(plr)) { - PlayerFunctions.sendMessage(plr, C.NO_PERMISSION); - return true; - } - if (args[0].equalsIgnoreCase("add")) { - if (args[1].equalsIgnoreCase("*")) { - UUID uuid = DBFunc.everyone; - plot.addHelper(uuid); - DBFunc.setHelper(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); - PlayerFunctions.sendMessage(plr, C.HELPER_ADDED); - return true; - } - /*if (!hasBeenOnServer(args[1])) { - PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); - return true; - } - UUID uuid = null; - if ((Bukkit.getPlayer(args[1]) != null)) { - uuid = Bukkit.getPlayer(args[1]).getUniqueId(); - } else { - uuid = Bukkit.getOfflinePlayer(args[1]).getUniqueId(); - } - if (uuid == null) { - PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); - return true; - }*/ - UUID uuid = UUIDHandler.getUUID(args[1]); - plot.addHelper(uuid); - DBFunc.setHelper(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); - PlayerPlotHelperEvent event = new PlayerPlotHelperEvent(plr, plot, uuid, true); - Bukkit.getPluginManager().callEvent(event); - PlayerFunctions.sendMessage(plr, C.HELPER_ADDED); - } else if (args[0].equalsIgnoreCase("remove")) { - if (args[1].equalsIgnoreCase("*")) { - UUID uuid = DBFunc.everyone; - if (!plot.helpers.contains(uuid)) { - PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED); - return true; - } - plot.removeHelper(uuid); - DBFunc.removeHelper(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); - PlayerFunctions.sendMessage(plr, C.HELPER_REMOVED); - return true; - } - /*if (!hasBeenOnServer(args[1])) { - PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); - return true; - } - UUID uuid = null; - if (Bukkit.getPlayer(args[1]) != null) { - uuid = Bukkit.getPlayer(args[1]).getUniqueId(); - } else { - uuid = Bukkit.getOfflinePlayer(args[1]).getUniqueId(); - } - if (uuid == null) { - PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); - return true; - } - if (!plot.helpers.contains(uuid)) { - PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED); - return true; - }*/ - UUID uuid = UUIDHandler.getUUID(args[1]); - plot.removeHelper(uuid); - DBFunc.removeHelper(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); - PlayerPlotHelperEvent event = new PlayerPlotHelperEvent(plr, plot, uuid, false); - Bukkit.getPluginManager().callEvent(event); - PlayerFunctions.sendMessage(plr, C.HELPER_REMOVED); - } else { - PlayerFunctions.sendMessage(plr, C.HELPER_NEED_ARGUMENT); - return true; - } - return true; - } + @Override + public boolean execute(Player plr, String... args) { + if (args.length < 2) { + PlayerFunctions.sendMessage(plr, C.HELPER_NEED_ARGUMENT); + return true; + } + if (!PlayerFunctions.isInPlot(plr)) { + PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); + return true; + } + Plot plot = PlayerFunctions.getCurrentPlot(plr); + if ((plot.owner == null) || !plot.hasRights(plr)) { + PlayerFunctions.sendMessage(plr, C.NO_PERMISSION); + return true; + } + if (args[0].equalsIgnoreCase("add")) { + if (args[1].equalsIgnoreCase("*")) { + UUID uuid = DBFunc.everyone; + plot.addHelper(uuid); + DBFunc.setHelper(plr.getWorld().getName(), plot, + Bukkit.getOfflinePlayer(args[1])); + PlayerFunctions.sendMessage(plr, C.HELPER_ADDED); + return true; + } + /* + * if (!hasBeenOnServer(args[1])) { PlayerFunctions.sendMessage(plr, + * C.PLAYER_HAS_NOT_BEEN_ON); return true; } UUID uuid = null; if + * ((Bukkit.getPlayer(args[1]) != null)) { uuid = + * Bukkit.getPlayer(args[1]).getUniqueId(); } else { uuid = + * Bukkit.getOfflinePlayer(args[1]).getUniqueId(); } if (uuid == + * null) { PlayerFunctions.sendMessage(plr, + * C.PLAYER_HAS_NOT_BEEN_ON); return true; } + */ + UUID uuid = UUIDHandler.getUUID(args[1]); + plot.addHelper(uuid); + DBFunc.setHelper(plr.getWorld().getName(), plot, + Bukkit.getOfflinePlayer(args[1])); + PlayerPlotHelperEvent event = new PlayerPlotHelperEvent(plr, plot, + uuid, true); + Bukkit.getPluginManager().callEvent(event); + PlayerFunctions.sendMessage(plr, C.HELPER_ADDED); + } else if (args[0].equalsIgnoreCase("remove")) { + if (args[1].equalsIgnoreCase("*")) { + UUID uuid = DBFunc.everyone; + if (!plot.helpers.contains(uuid)) { + PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED); + return true; + } + plot.removeHelper(uuid); + DBFunc.removeHelper(plr.getWorld().getName(), plot, + Bukkit.getOfflinePlayer(args[1])); + PlayerFunctions.sendMessage(plr, C.HELPER_REMOVED); + return true; + } + /* + * if (!hasBeenOnServer(args[1])) { PlayerFunctions.sendMessage(plr, + * C.PLAYER_HAS_NOT_BEEN_ON); return true; } UUID uuid = null; if + * (Bukkit.getPlayer(args[1]) != null) { uuid = + * Bukkit.getPlayer(args[1]).getUniqueId(); } else { uuid = + * Bukkit.getOfflinePlayer(args[1]).getUniqueId(); } if (uuid == + * null) { PlayerFunctions.sendMessage(plr, + * C.PLAYER_HAS_NOT_BEEN_ON); return true; } if + * (!plot.helpers.contains(uuid)) { PlayerFunctions.sendMessage(plr, + * C.WAS_NOT_ADDED); return true; } + */ + UUID uuid = UUIDHandler.getUUID(args[1]); + plot.removeHelper(uuid); + DBFunc.removeHelper(plr.getWorld().getName(), plot, + Bukkit.getOfflinePlayer(args[1])); + PlayerPlotHelperEvent event = new PlayerPlotHelperEvent(plr, plot, + uuid, false); + Bukkit.getPluginManager().callEvent(event); + PlayerFunctions.sendMessage(plr, C.HELPER_REMOVED); + } else { + PlayerFunctions.sendMessage(plr, C.HELPER_NEED_ARGUMENT); + return true; + } + return true; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/commands/Home.java b/PlotSquared/src/com/intellectualcrafters/plot/commands/Home.java index 290e944fe..6aefd3656 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/commands/Home.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/commands/Home.java @@ -9,8 +9,6 @@ package com.intellectualcrafters.plot.commands; -import java.util.ArrayList; - import org.bukkit.entity.Player; import com.intellectualcrafters.plot.C; @@ -19,62 +17,65 @@ import com.intellectualcrafters.plot.Plot; import com.intellectualcrafters.plot.PlotMain; /** - * + * * @author Citymonstret - * + * */ public class Home extends SubCommand { - public Home() { - super(Command.HOME, "Go to your plot", "home {id|alias}", CommandCategory.TELEPORT); - } + public Home() { + super(Command.HOME, "Go to your plot", "home {id|alias}", + CommandCategory.TELEPORT); + } - private Plot isAlias(String a) { - for (Plot p : PlotMain.getPlots()) { - if ((p.settings.getAlias().length() > 0) && p.settings.getAlias().equalsIgnoreCase(a)) { - return p; - } - } - return null; - } + private Plot isAlias(String a) { + for (Plot p : PlotMain.getPlots()) { + if ((p.settings.getAlias().length() > 0) + && p.settings.getAlias().equalsIgnoreCase(a)) { + return p; + } + } + return null; + } - @Override - public boolean execute(Player plr, String... args) { - Plot[] plots = PlotMain.getPlots(plr).toArray(new Plot[0]); - if (plots.length == 1) { - PlotMain.teleportPlayer(plr, plr.getLocation(), plots[0]); - return true; - } else if (plots.length > 1) { - if (args.length < 1) { - args = new String[] {"1"}; - } - int id = 0; - try { - id = Integer.parseInt(args[0]); - } catch (Exception e) { - Plot temp; - if ((temp = isAlias(args[0])) != null) { - if (temp.hasOwner()) { - if (temp.getOwner().equals(plr.getUniqueId())) { - PlotMain.teleportPlayer(plr, plr.getLocation(), temp); - return true; - } - } - PlayerFunctions.sendMessage(plr, C.NOT_YOUR_PLOT); - return false; - } - PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER); - return true; - } - if ((id > (plots.length)) || (id < 1)) { - PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER); - return false; - } - PlotMain.teleportPlayer(plr, plr.getLocation(), plots[id - 1]); - return true; - } else { - PlayerFunctions.sendMessage(plr, C.NO_PLOTS); - return true; - } - } + @Override + public boolean execute(Player plr, String... args) { + Plot[] plots = PlotMain.getPlots(plr).toArray(new Plot[0]); + if (plots.length == 1) { + PlotMain.teleportPlayer(plr, plr.getLocation(), plots[0]); + return true; + } else if (plots.length > 1) { + if (args.length < 1) { + args = new String[] { "1" }; + } + int id = 0; + try { + id = Integer.parseInt(args[0]); + } catch (Exception e) { + Plot temp; + if ((temp = isAlias(args[0])) != null) { + if (temp.hasOwner()) { + if (temp.getOwner().equals(plr.getUniqueId())) { + PlotMain.teleportPlayer(plr, plr.getLocation(), + temp); + return true; + } + } + PlayerFunctions.sendMessage(plr, C.NOT_YOUR_PLOT); + return false; + } + PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER); + return true; + } + if ((id > (plots.length)) || (id < 1)) { + PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER); + return false; + } + PlotMain.teleportPlayer(plr, plr.getLocation(), plots[id - 1]); + return true; + } else { + PlayerFunctions.sendMessage(plr, C.NO_PLOTS); + return true; + } + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/commands/Info.java b/PlotSquared/src/com/intellectualcrafters/plot/commands/Info.java index 009aafdd5..fb969e55f 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/commands/Info.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/commands/Info.java @@ -9,8 +9,9 @@ package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.*; -import com.intellectualcrafters.plot.database.DBFunc; +import java.util.ArrayList; +import java.util.UUID; + import org.apache.commons.lang.StringUtils; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -18,120 +19,135 @@ import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.entity.Player; -import java.util.ArrayList; -import java.util.UUID; +import com.intellectualcrafters.plot.C; +import com.intellectualcrafters.plot.PlayerFunctions; +import com.intellectualcrafters.plot.Plot; +import com.intellectualcrafters.plot.PlotHelper; +import com.intellectualcrafters.plot.UUIDHandler; +import com.intellectualcrafters.plot.database.DBFunc; /** - * + * * @author Citymonstret - * + * */ public class Info extends SubCommand { - public Info() { - super(Command.INFO, "Display plot info", "info", CommandCategory.INFO); - } + public Info() { + super(Command.INFO, "Display plot info", "info", CommandCategory.INFO); + } - @Override - public boolean execute(Player player, String... args) { - if (!PlayerFunctions.isInPlot(player)) { - PlayerFunctions.sendMessage(player, C.NOT_IN_PLOT); - return true; - } + @Override + public boolean execute(Player player, String... args) { + if (!PlayerFunctions.isInPlot(player)) { + PlayerFunctions.sendMessage(player, C.NOT_IN_PLOT); + return true; + } - // || - Plot plot = PlayerFunctions.getCurrentPlot(player); + // || + Plot plot = PlayerFunctions.getCurrentPlot(player); - boolean hasOwner = plot.hasOwner(); - boolean containsEveryone; - boolean trustedEveryone; + boolean hasOwner = plot.hasOwner(); + boolean containsEveryone; + boolean trustedEveryone; - // Wildcard player {added} - { - if (plot.helpers == null) { - containsEveryone = false; - } else { - containsEveryone = plot.helpers.contains(DBFunc.everyone); - } - if (plot.trusted == null) { - trustedEveryone = false; - } else { - trustedEveryone = plot.trusted.contains(DBFunc.everyone); - } - } + // Wildcard player {added} + { + if (plot.helpers == null) { + containsEveryone = false; + } else { + containsEveryone = plot.helpers.contains(DBFunc.everyone); + } + if (plot.trusted == null) { + trustedEveryone = false; + } else { + trustedEveryone = plot.trusted.contains(DBFunc.everyone); + } + } - // Unclaimed? - if (!hasOwner && !containsEveryone && !trustedEveryone) { - PlayerFunctions.sendMessage(player, C.PLOT_INFO_UNCLAIMED, plot.id.x + ";" + plot.id.y); - return true; - } + // Unclaimed? + if (!hasOwner && !containsEveryone && !trustedEveryone) { + PlayerFunctions.sendMessage(player, C.PLOT_INFO_UNCLAIMED, + plot.id.x + ";" + plot.id.y); + return true; + } - new StringBuilder(); + new StringBuilder(); - String owner = "none"; - if (plot.owner != null) { - owner = Bukkit.getOfflinePlayer(plot.owner).getName(); - } - if (owner == null) { - owner = plot.owner.toString(); - } + String owner = "none"; + if (plot.owner != null) { + owner = Bukkit.getOfflinePlayer(plot.owner).getName(); + } + if (owner == null) { + owner = plot.owner.toString(); + } - String info = C.PLOT_INFO.s(); - info = info.replaceAll("%alias%", plot.settings.getAlias().length() > 0 ? plot.settings.getAlias() : "none"); - info = info.replaceAll("%id%", plot.id.toString()); - info = info.replaceAll("%biome%", getBiomeAt(plot).toString()); - info = info.replaceAll("%owner%", owner); - info = info.replaceAll("%time%", plot.settings.getChangeTime() ? plot.settings.getTime() + "" : "default"); - info = info.replaceAll("%weather%", plot.settings.getRain() ? "rain" : "default"); - info = info.replaceAll("%helpers%", getPlayerList(plot.helpers)); - info = info.replaceAll("%trusted%", getPlayerList(plot.trusted)); - info = info.replaceAll("%denied%", getPlayerList(plot.denied)); - info = info.replaceAll("%rating%", "" + DBFunc.getRatings(plot)); - info = info.replaceAll("%flags%", StringUtils.join(plot.settings.getFlags(), "").length() > 0 ? StringUtils.join(plot.settings.getFlags(), ",") : "none"); - // PlayerFunctions.sendMessage(player, - // PlayerFunctions.getTopPlot(player.getWorld(), plot).id.toString()); - // PlayerFunctions.sendMessage(player, - // PlayerFunctions.getBottomPlot(player.getWorld(), - // plot).id.toString()); - PlayerFunctions.sendMessage(player, info); - return true; - } + String info = C.PLOT_INFO.s(); + info = info.replaceAll( + "%alias%", + plot.settings.getAlias().length() > 0 ? plot.settings + .getAlias() : "none"); + info = info.replaceAll("%id%", plot.id.toString()); + info = info.replaceAll("%biome%", getBiomeAt(plot).toString()); + info = info.replaceAll("%owner%", owner); + info = info.replaceAll("%time%", + plot.settings.getChangeTime() ? plot.settings.getTime() + "" + : "default"); + info = info.replaceAll("%weather%", plot.settings.getRain() ? "rain" + : "default"); + info = info.replaceAll("%helpers%", getPlayerList(plot.helpers)); + info = info.replaceAll("%trusted%", getPlayerList(plot.trusted)); + info = info.replaceAll("%denied%", getPlayerList(plot.denied)); + info = info.replaceAll("%rating%", "" + DBFunc.getRatings(plot)); + info = info + .replaceAll( + "%flags%", + StringUtils.join(plot.settings.getFlags(), "").length() > 0 ? StringUtils + .join(plot.settings.getFlags(), ",") : "none"); + // PlayerFunctions.sendMessage(player, + // PlayerFunctions.getTopPlot(player.getWorld(), plot).id.toString()); + // PlayerFunctions.sendMessage(player, + // PlayerFunctions.getBottomPlot(player.getWorld(), + // plot).id.toString()); + PlayerFunctions.sendMessage(player, info); + return true; + } - private String getPlayerList(ArrayList l) { - if ((l == null) || (l.size() < 1)) { - return " none"; - } - String c = C.PLOT_USER_LIST.s(); - StringBuilder list = new StringBuilder(); - for (int x = 0; x < l.size(); x++) { - if ((x + 1) == l.size()) { - list.append(c.replace("%user%", getPlayerName(l.get(x))).replace(",", "")); - } else { - list.append(c.replace("%user%", getPlayerName(l.get(x)))); - } - } - return list.toString(); - } + private String getPlayerList(ArrayList l) { + if ((l == null) || (l.size() < 1)) { + return " none"; + } + String c = C.PLOT_USER_LIST.s(); + StringBuilder list = new StringBuilder(); + for (int x = 0; x < l.size(); x++) { + if ((x + 1) == l.size()) { + list.append(c.replace("%user%", getPlayerName(l.get(x))) + .replace(",", "")); + } else { + list.append(c.replace("%user%", getPlayerName(l.get(x)))); + } + } + return list.toString(); + } - private String getPlayerName(UUID uuid) { - if (uuid == null) { - return "unknown"; - } - if (uuid.equals(DBFunc.everyone) || uuid.toString().equalsIgnoreCase(DBFunc.everyone.toString())) { - return "everyone"; - } - /* - OfflinePlayer plr = Bukkit.getOfflinePlayer(uuid); - if (plr.getName() == null) { - return "unknown"; - } - return plr.getName();*/ - return UUIDHandler.getName(uuid); - } + private String getPlayerName(UUID uuid) { + if (uuid == null) { + return "unknown"; + } + if (uuid.equals(DBFunc.everyone) + || uuid.toString().equalsIgnoreCase(DBFunc.everyone.toString())) { + return "everyone"; + } + /* + * OfflinePlayer plr = Bukkit.getOfflinePlayer(uuid); if (plr.getName() + * == null) { return "unknown"; } return plr.getName(); + */ + return UUIDHandler.getName(uuid); + } - private Biome getBiomeAt(Plot plot) { - World w = Bukkit.getWorld(plot.world); - Location bl = PlotHelper.getPlotTopLoc(w, plot.id); - return bl.getBlock().getBiome(); - } + private Biome getBiomeAt(Plot plot) { + World w = Bukkit.getWorld(plot.world); + Location bl = PlotHelper.getPlotTopLoc(w, plot.id); + return bl.getBlock().getBiome(); + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/commands/Inventory.java b/PlotSquared/src/com/intellectualcrafters/plot/commands/Inventory.java index 8c80d8f79..a3b7278d7 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/commands/Inventory.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/commands/Inventory.java @@ -20,41 +20,48 @@ import org.bukkit.inventory.meta.ItemMeta; public class Inventory extends SubCommand { - public Inventory() { - super("inventory", "plots.inventory", "Open a command inventory", "inventory", "inv", CommandCategory.INFO); - } + public Inventory() { + super("inventory", "plots.inventory", "Open a command inventory", + "inventory", "inv", CommandCategory.INFO); + } - @Override - public boolean execute(final Player plr, String... args) { - ArrayList cmds = new ArrayList<>(); - for (SubCommand cmd : MainCommand.subCommands) { - if (cmd.permission.hasPermission(plr)) { - cmds.add(cmd); - } - } - int size = 9 * (int) Math.ceil(cmds.size() / 9.0); - org.bukkit.inventory.Inventory inventory = Bukkit.createInventory(null, size, "PlotSquared Commands"); - for (SubCommand cmd : cmds) { - inventory.addItem(getItem(cmd)); - } - plr.openInventory(inventory); - return true; - } + @Override + public boolean execute(final Player plr, String... args) { + ArrayList cmds = new ArrayList<>(); + for (SubCommand cmd : MainCommand.subCommands) { + if (cmd.permission.hasPermission(plr)) { + cmds.add(cmd); + } + } + int size = 9 * (int) Math.ceil(cmds.size() / 9.0); + org.bukkit.inventory.Inventory inventory = Bukkit.createInventory(null, + size, "PlotSquared Commands"); + for (SubCommand cmd : cmds) { + inventory.addItem(getItem(cmd)); + } + plr.openInventory(inventory); + return true; + } - private ItemStack getItem(final SubCommand cmd) { - ItemStack stack = new ItemStack(Material.COMMAND); - ItemMeta meta = stack.getItemMeta(); - { - meta.setDisplayName(ChatColor.GREEN + cmd.cmd + ChatColor.DARK_GRAY + " [" + ChatColor.GREEN + cmd.alias + ChatColor.DARK_GRAY + "]"); - meta.setLore(new ArrayList() { - { - add(ChatColor.RED + "Category: " + ChatColor.GOLD + cmd.category.toString()); - add(ChatColor.RED + "Description: " + ChatColor.GOLD + cmd.description); - add(ChatColor.RED + "Usage: " + ChatColor.GOLD + "/plot " + cmd.usage); - } - }); - } - stack.setItemMeta(meta); - return stack; - } + private ItemStack getItem(final SubCommand cmd) { + ItemStack stack = new ItemStack(Material.COMMAND); + ItemMeta meta = stack.getItemMeta(); + { + meta.setDisplayName(ChatColor.GREEN + cmd.cmd + ChatColor.DARK_GRAY + + " [" + ChatColor.GREEN + cmd.alias + ChatColor.DARK_GRAY + + "]"); + meta.setLore(new ArrayList() { + { + add(ChatColor.RED + "Category: " + ChatColor.GOLD + + cmd.category.toString()); + add(ChatColor.RED + "Description: " + ChatColor.GOLD + + cmd.description); + add(ChatColor.RED + "Usage: " + ChatColor.GOLD + "/plot " + + cmd.usage); + } + }); + } + stack.setItemMeta(meta); + return stack; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/commands/Kick.java b/PlotSquared/src/com/intellectualcrafters/plot/commands/Kick.java index 03f77481a..24281d734 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/commands/Kick.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/commands/Kick.java @@ -21,35 +21,43 @@ import com.intellectualcrafters.plot.Plot; */ public class Kick extends SubCommand { - public Kick() { - super(Command.KICK, "Kick a player from your plot", "kick", CommandCategory.ACTIONS); - } + public Kick() { + super(Command.KICK, "Kick a player from your plot", "kick", + CommandCategory.ACTIONS); + } - @Override - public boolean execute(Player plr, String... args) { - if (!PlayerFunctions.isInPlot(plr)) { - PlayerFunctions.sendMessage(plr, "You're not in a plot."); - return false; - } - Plot plot = PlayerFunctions.getCurrentPlot(plr); - if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId())) && !plr.hasPermission("plots.admin")) { - PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); - return false; - } - if (args.length != 1) { - PlayerFunctions.sendMessage(plr, "&c/plot kick "); - return false; - } - if (Bukkit.getPlayer(args[0]) != null) { - PlayerFunctions.sendMessage(plr, C.INVALID_PLAYER.s().replaceAll("%player%", args[0])); - return false; - } - Player player = Bukkit.getPlayer(args[0]); - if (!player.getWorld().equals(plr.getWorld()) || !PlayerFunctions.isInPlot(player) || (PlayerFunctions.getCurrentPlot(player) == null) || !PlayerFunctions.getCurrentPlot(player).equals(plot)) { - PlayerFunctions.sendMessage(plr, C.INVALID_PLAYER.s().replaceAll("%player%", args[0])); - return false; - } - player.teleport(player.getWorld().getSpawnLocation()); - return true; - } + @Override + public boolean execute(Player plr, String... args) { + if (!PlayerFunctions.isInPlot(plr)) { + PlayerFunctions.sendMessage(plr, "You're not in a plot."); + return false; + } + Plot plot = PlayerFunctions.getCurrentPlot(plr); + if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals( + plr.getUniqueId())) + && !plr.hasPermission("plots.admin")) { + PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); + return false; + } + if (args.length != 1) { + PlayerFunctions.sendMessage(plr, "&c/plot kick "); + return false; + } + if (Bukkit.getPlayer(args[0]) != null) { + PlayerFunctions.sendMessage(plr, + C.INVALID_PLAYER.s().replaceAll("%player%", args[0])); + return false; + } + Player player = Bukkit.getPlayer(args[0]); + if (!player.getWorld().equals(plr.getWorld()) + || !PlayerFunctions.isInPlot(player) + || (PlayerFunctions.getCurrentPlot(player) == null) + || !PlayerFunctions.getCurrentPlot(player).equals(plot)) { + PlayerFunctions.sendMessage(plr, + C.INVALID_PLAYER.s().replaceAll("%player%", args[0])); + return false; + } + player.teleport(player.getWorld().getSpawnLocation()); + return true; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/commands/MainCommand.java b/PlotSquared/src/com/intellectualcrafters/plot/commands/MainCommand.java index a4b2920dd..b85d2ff83 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/commands/MainCommand.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/commands/MainCommand.java @@ -9,133 +9,164 @@ package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.C; -import com.intellectualcrafters.plot.PlayerFunctions; -import com.intellectualcrafters.plot.PlotMain; +import java.util.ArrayList; +import java.util.Arrays; + import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import java.util.ArrayList; -import java.util.Arrays; +import com.intellectualcrafters.plot.C; +import com.intellectualcrafters.plot.PlayerFunctions; +import com.intellectualcrafters.plot.PlotMain; /** * PlotMain command class - * + * * @author Citymonstret - * + * */ public class MainCommand implements CommandExecutor { - private static SubCommand[] _subCommands = new SubCommand[] { new Claim(), new Auto(), new Home(), new Visit(), new TP(), new Set(), new Clear(), new Delete(), new SetOwner(), new Denied(), new Helpers(), new Trusted(), new Info(), new list(), new Help(), new Debug(), new Schematic(), new plugin(), new Inventory(), new Reload(), new Merge(), new Unlink(), new Kick(), new Setup() }; + private static SubCommand[] _subCommands = new SubCommand[] { new Claim(), + new Auto(), new Home(), new Visit(), new TP(), new Set(), + new Clear(), new Delete(), new SetOwner(), new Denied(), + new Helpers(), new Trusted(), new Info(), new list(), new Help(), + new Debug(), new Schematic(), new plugin(), new Inventory(), + new Reload(), new Merge(), new Unlink(), new Kick(), new Setup() }; - public static ArrayList subCommands = new ArrayList() { - { - addAll(Arrays.asList(_subCommands)); - } - }; + public static ArrayList subCommands = new ArrayList() { + { + addAll(Arrays.asList(_subCommands)); + } + }; - public static boolean no_permission(Player player) { - PlayerFunctions.sendMessage(player, C.NO_PERMISSION); - return false; - } + public static boolean no_permission(Player player) { + PlayerFunctions.sendMessage(player, C.NO_PERMISSION); + return false; + } - @Override - public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { - if (!(sender instanceof Player)) { - if (args.length > 0) { - if (args[0].equalsIgnoreCase("reload")) { - new Reload().executeConsole(args); - } - } else { - PlotMain.sendConsoleSenderMessage(C.PREFIX.s() + C.HELP_HEADER.s()); - PlotMain.sendConsoleSenderMessage("&6/plots reload &c-&6 reloads the plugin"); - } - return false; - } - Player player = (Player) sender; - if (!player.hasPermission("plots.use")) { - return no_permission(player); - } - if ((args.length < 1) || ((args.length >= 1) && (args[0].equalsIgnoreCase("help") || args[0].equalsIgnoreCase("he")))) { - if (args.length < 2) { - StringBuilder builder = new StringBuilder(); - builder.append(C.HELP_INFO.s()); - for (SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) { - builder.append("\n" + C.HELP_INFO_ITEM.s().replaceAll("%category%", category.toString().toLowerCase()).replaceAll("%category_desc%", category.toString())); - } - PlayerFunctions.sendMessage(player, builder.toString()); - return true; - } - String cat = args[1]; - SubCommand.CommandCategory cato = null; - for (SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) { - if (cat.equalsIgnoreCase(category.toString())) { - cato = category; - break; - } - } - if (cato == null) { - StringBuilder builder = new StringBuilder(); - builder.append(C.HELP_INFO.s()); - for (SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) { - builder.append("\n" + C.HELP_INFO_ITEM.s().replaceAll("%category%", category.toString().toLowerCase()).replaceAll("%category_desc%", category.toString())); - } - PlayerFunctions.sendMessage(player, builder.toString()); - return true; - } - StringBuilder help = new StringBuilder(); - for (String string : helpMenu(player, cato)) { - help.append(string + "\n"); - } - PlayerFunctions.sendMessage(player, help.toString()); - return true; - } else { - for (SubCommand command : subCommands) { - if (command.cmd.equalsIgnoreCase(args[0]) || command.alias.equalsIgnoreCase(args[0])) { - String[] arguments = new String[args.length - 1]; - for (int x = 1; x < args.length; x++) { - arguments[x - 1] = args[x]; - } - if (command.permission.hasPermission(player)) { - return command.execute(player, arguments); - } else { - return no_permission(player); - } - } - } - PlayerFunctions.sendMessage(player, C.NOT_VALID_SUBCOMMAND); - } - return false; - } + @Override + public boolean onCommand(CommandSender sender, Command cmd, + String commandLabel, String[] args) { + if (!(sender instanceof Player)) { + if (args.length > 0) { + if (args[0].equalsIgnoreCase("reload")) { + new Reload().executeConsole(args); + } + } else { + PlotMain.sendConsoleSenderMessage(C.PREFIX.s() + + C.HELP_HEADER.s()); + PlotMain.sendConsoleSenderMessage("&6/plots reload &c-&6 reloads the plugin"); + } + return false; + } + Player player = (Player) sender; + if (!player.hasPermission("plots.use")) { + return no_permission(player); + } + if ((args.length < 1) + || ((args.length >= 1) && (args[0].equalsIgnoreCase("help") || args[0] + .equalsIgnoreCase("he")))) { + if (args.length < 2) { + StringBuilder builder = new StringBuilder(); + builder.append(C.HELP_INFO.s()); + for (SubCommand.CommandCategory category : SubCommand.CommandCategory + .values()) { + builder.append("\n" + + C.HELP_INFO_ITEM + .s() + .replaceAll("%category%", + category.toString().toLowerCase()) + .replaceAll("%category_desc%", + category.toString())); + } + PlayerFunctions.sendMessage(player, builder.toString()); + return true; + } + String cat = args[1]; + SubCommand.CommandCategory cato = null; + for (SubCommand.CommandCategory category : SubCommand.CommandCategory + .values()) { + if (cat.equalsIgnoreCase(category.toString())) { + cato = category; + break; + } + } + if (cato == null) { + StringBuilder builder = new StringBuilder(); + builder.append(C.HELP_INFO.s()); + for (SubCommand.CommandCategory category : SubCommand.CommandCategory + .values()) { + builder.append("\n" + + C.HELP_INFO_ITEM + .s() + .replaceAll("%category%", + category.toString().toLowerCase()) + .replaceAll("%category_desc%", + category.toString())); + } + PlayerFunctions.sendMessage(player, builder.toString()); + return true; + } + StringBuilder help = new StringBuilder(); + for (String string : helpMenu(player, cato)) { + help.append(string + "\n"); + } + PlayerFunctions.sendMessage(player, help.toString()); + return true; + } else { + for (SubCommand command : subCommands) { + if (command.cmd.equalsIgnoreCase(args[0]) + || command.alias.equalsIgnoreCase(args[0])) { + String[] arguments = new String[args.length - 1]; + for (int x = 1; x < args.length; x++) { + arguments[x - 1] = args[x]; + } + if (command.permission.hasPermission(player)) { + return command.execute(player, arguments); + } else { + return no_permission(player); + } + } + } + PlayerFunctions.sendMessage(player, C.NOT_VALID_SUBCOMMAND); + } + return false; + } - public static ArrayList helpMenu(Player player, final SubCommand.CommandCategory category) { - ArrayList help = new ArrayList() { - { - add(t(C.HELP_HEADER.s())); - add(t(C.HELP_CATEGORY.s().replaceAll("%category%", category.toString()))); - } - }; - for (SubCommand cmd : subCommands) { - if (cmd.permission.hasPermission(player) && (cmd.category == category)) { - String s = t(C.HELP_PAGE.s()); - s = s.replaceAll("%alias%", cmd.alias); - s = s.replaceAll("%usage%", cmd.usage.contains("plot") ? cmd.usage : "/plot " + cmd.usage); - s = s.replaceAll("%cmd%", cmd.cmd); - s = s.replaceAll("%desc%", cmd.description); - help.add(s); - } - } - if (help.size() < 2) { - help.add(t(C.NO_COMMANDS.s())); - } - return help; - } + public static ArrayList helpMenu(Player player, + final SubCommand.CommandCategory category) { + ArrayList help = new ArrayList() { + { + add(t(C.HELP_HEADER.s())); + add(t(C.HELP_CATEGORY.s().replaceAll("%category%", + category.toString()))); + } + }; + for (SubCommand cmd : subCommands) { + if (cmd.permission.hasPermission(player) + && (cmd.category == category)) { + String s = t(C.HELP_PAGE.s()); + s = s.replaceAll("%alias%", cmd.alias); + s = s.replaceAll("%usage%", + cmd.usage.contains("plot") ? cmd.usage : "/plot " + + cmd.usage); + s = s.replaceAll("%cmd%", cmd.cmd); + s = s.replaceAll("%desc%", cmd.description); + help.add(s); + } + } + if (help.size() < 2) { + help.add(t(C.NO_COMMANDS.s())); + } + return help; + } - private static String t(String s) { - return ChatColor.translateAlternateColorCodes('&', s); - } + private static String t(String s) { + return ChatColor.translateAlternateColorCodes('&', s); + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/commands/Merge.java b/PlotSquared/src/com/intellectualcrafters/plot/commands/Merge.java index 2fb53e1eb..e6f2ec72e 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/commands/Merge.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/commands/Merge.java @@ -9,140 +9,173 @@ package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.*; -import com.intellectualcrafters.plot.events.PlotMergeEvent; +import java.util.ArrayList; + import net.milkbowl.vault.economy.Economy; + import org.apache.commons.lang.StringUtils; import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.entity.Player; -import java.util.ArrayList; +import com.intellectualcrafters.plot.C; +import com.intellectualcrafters.plot.PlayerFunctions; +import com.intellectualcrafters.plot.Plot; +import com.intellectualcrafters.plot.PlotHelper; +import com.intellectualcrafters.plot.PlotId; +import com.intellectualcrafters.plot.PlotMain; +import com.intellectualcrafters.plot.PlotWorld; +import com.intellectualcrafters.plot.SetBlockFast; +import com.intellectualcrafters.plot.events.PlotMergeEvent; /** - * + * * @author Citymonstret - * + * */ public class Merge extends SubCommand { - public static String[] values = new String[] { "north", "east", "south", "west" }; - public static String[] aliases = new String[] { "n", "e", "s", "w" }; + public static String[] values = new String[] { "north", "east", "south", + "west" }; + public static String[] aliases = new String[] { "n", "e", "s", "w" }; - public Merge() { - super(Command.MERGE, "Merge the plot you are standing on with another plot.", "merge", CommandCategory.ACTIONS); - } + public Merge() { + super(Command.MERGE, + "Merge the plot you are standing on with another plot.", + "merge", CommandCategory.ACTIONS); + } - public static String direction(float yaw) { - yaw = yaw / 90; - int i = Math.round(yaw); - switch (i) { - case -4: - case 0: - case 4: - return "SOUTH"; - case -1: - case 3: - return "EAST"; - case -2: - case 2: - return "NORTH"; - case -3: - case 1: - return "WEST"; - default: - return ""; - } - } + public static String direction(float yaw) { + yaw = yaw / 90; + int i = Math.round(yaw); + switch (i) { + case -4: + case 0: + case 4: + return "SOUTH"; + case -1: + case 3: + return "EAST"; + case -2: + case 2: + return "NORTH"; + case -3: + case 1: + return "WEST"; + default: + return ""; + } + } - @Override - public boolean execute(Player plr, String... args) { - if (!PlayerFunctions.isInPlot(plr)) { - PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); - return true; - } - Plot plot = PlayerFunctions.getCurrentPlot(plr); - if ((plot == null) || !plot.hasOwner()) { - PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); - return false; - } - if (!plot.getOwner().equals(plr.getUniqueId())) { - PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); - return false; - } - if (args.length < 1) { - PlayerFunctions.sendMessage(plr, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + StringUtils.join(values, C.BLOCK_LIST_SEPARATER.s())); - PlayerFunctions.sendMessage(plr, C.DIRECTION.s().replaceAll("%dir%", direction(plr.getLocation().getYaw()))); - return false; - } - int direction = -1; - for (int i = 0; i < values.length; i++) { - if (args[0].equalsIgnoreCase(values[i]) || args[0].equalsIgnoreCase(aliases[i])) { - direction = i; - break; - } - } - if (direction == -1) { - PlayerFunctions.sendMessage(plr, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + StringUtils.join(values, C.BLOCK_LIST_SEPARATER.s())); - PlayerFunctions.sendMessage(plr, C.DIRECTION.s().replaceAll("%dir%", direction(plr.getLocation().getYaw()))); - return false; - } - World world = plr.getWorld(); - PlotId bot = PlayerFunctions.getBottomPlot(world, plot).id; - PlotId top = PlayerFunctions.getTopPlot(world, plot).id; - ArrayList plots; - switch (direction) { - case 0: // north = -y - plots = PlayerFunctions.getPlotSelectionIds(plr.getWorld(), new PlotId(bot.x, bot.y - 1), new PlotId(top.x, top.y)); - break; - case 1: // east = +x - plots = PlayerFunctions.getPlotSelectionIds(plr.getWorld(), new PlotId(bot.x, bot.y), new PlotId(top.x + 1, top.y)); - break; - case 2: // south = +y - plots = PlayerFunctions.getPlotSelectionIds(plr.getWorld(), new PlotId(bot.x, bot.y), new PlotId(top.x, top.y + 1)); - break; - case 3: // west = -x - plots = PlayerFunctions.getPlotSelectionIds(plr.getWorld(), new PlotId(bot.x - 1, bot.y), new PlotId(top.x, top.y)); - break; - default: - return false; - } - for (PlotId myid : plots) { - Plot myplot = PlotMain.getPlots(world).get(myid); - if ((myplot == null) || !myplot.hasOwner() || !(myplot.getOwner().equals(plr.getUniqueId()))) { - PlayerFunctions.sendMessage(plr, C.NO_PERM_MERGE.s().replaceAll("%plot%", myid.toString())); - return false; - } - } + @Override + public boolean execute(Player plr, String... args) { + if (!PlayerFunctions.isInPlot(plr)) { + PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); + return true; + } + Plot plot = PlayerFunctions.getCurrentPlot(plr); + if ((plot == null) || !plot.hasOwner()) { + PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); + return false; + } + if (!plot.getOwner().equals(plr.getUniqueId())) { + PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); + return false; + } + if (args.length < 1) { + PlayerFunctions.sendMessage( + plr, + C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + + StringUtils.join(values, + C.BLOCK_LIST_SEPARATER.s())); + PlayerFunctions.sendMessage( + plr, + C.DIRECTION.s().replaceAll("%dir%", + direction(plr.getLocation().getYaw()))); + return false; + } + int direction = -1; + for (int i = 0; i < values.length; i++) { + if (args[0].equalsIgnoreCase(values[i]) + || args[0].equalsIgnoreCase(aliases[i])) { + direction = i; + break; + } + } + if (direction == -1) { + PlayerFunctions.sendMessage( + plr, + C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + + StringUtils.join(values, + C.BLOCK_LIST_SEPARATER.s())); + PlayerFunctions.sendMessage( + plr, + C.DIRECTION.s().replaceAll("%dir%", + direction(plr.getLocation().getYaw()))); + return false; + } + World world = plr.getWorld(); + PlotId bot = PlayerFunctions.getBottomPlot(world, plot).id; + PlotId top = PlayerFunctions.getTopPlot(world, plot).id; + ArrayList plots; + switch (direction) { + case 0: // north = -y + plots = PlayerFunctions.getPlotSelectionIds(plr.getWorld(), + new PlotId(bot.x, bot.y - 1), new PlotId(top.x, top.y)); + break; + case 1: // east = +x + plots = PlayerFunctions.getPlotSelectionIds(plr.getWorld(), + new PlotId(bot.x, bot.y), new PlotId(top.x + 1, top.y)); + break; + case 2: // south = +y + plots = PlayerFunctions.getPlotSelectionIds(plr.getWorld(), + new PlotId(bot.x, bot.y), new PlotId(top.x, top.y + 1)); + break; + case 3: // west = -x + plots = PlayerFunctions.getPlotSelectionIds(plr.getWorld(), + new PlotId(bot.x - 1, bot.y), new PlotId(top.x, top.y)); + break; + default: + return false; + } + for (PlotId myid : plots) { + Plot myplot = PlotMain.getPlots(world).get(myid); + if ((myplot == null) || !myplot.hasOwner() + || !(myplot.getOwner().equals(plr.getUniqueId()))) { + PlayerFunctions.sendMessage(plr, C.NO_PERM_MERGE.s() + .replaceAll("%plot%", myid.toString())); + return false; + } + } - PlotWorld plotWorld = PlotMain.getWorldSettings(world); - if (PlotMain.useEconomy && plotWorld.USE_ECONOMY) { - double cost = plotWorld.MERGE_PRICE; - cost = plots.size() * cost; - if (cost > 0d) { - Economy economy = PlotMain.economy; - if (economy.getBalance(plr) < cost) { - sendMessage(plr, C.CANNOT_AFFORD_MERGE, cost + ""); - return false; - } - economy.withdrawPlayer(plr, cost); - sendMessage(plr, C.REMOVED_BALANCE, cost + ""); - } - } + PlotWorld plotWorld = PlotMain.getWorldSettings(world); + if (PlotMain.useEconomy && plotWorld.USE_ECONOMY) { + double cost = plotWorld.MERGE_PRICE; + cost = plots.size() * cost; + if (cost > 0d) { + Economy economy = PlotMain.economy; + if (economy.getBalance(plr) < cost) { + sendMessage(plr, C.CANNOT_AFFORD_MERGE, cost + ""); + return false; + } + economy.withdrawPlayer(plr, cost); + sendMessage(plr, C.REMOVED_BALANCE, cost + ""); + } + } - PlotMergeEvent event = new PlotMergeEvent(world, plot, plots); + PlotMergeEvent event = new PlotMergeEvent(world, plot, plots); - Bukkit.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) { - event.setCancelled(true); - PlayerFunctions.sendMessage(plr, "&cMerge has been cancelled"); - return false; - } - PlayerFunctions.sendMessage(plr, "&cPlots have been merged"); - PlotHelper.mergePlots(world, plots); - if (PlotHelper.canSetFast) { - SetBlockFast.update(plr); - } - return true; - } + Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + event.setCancelled(true); + PlayerFunctions.sendMessage(plr, "&cMerge has been cancelled"); + return false; + } + PlayerFunctions.sendMessage(plr, "&cPlots have been merged"); + PlotHelper.mergePlots(world, plots); + if (PlotHelper.canSetFast) { + SetBlockFast.update(plr); + } + return true; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/commands/Rate.java b/PlotSquared/src/com/intellectualcrafters/plot/commands/Rate.java index 893f8cad2..2429f8004 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/commands/Rate.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/commands/Rate.java @@ -11,62 +11,63 @@ import com.intellectualcrafters.plot.Plot; */ public class Rate extends SubCommand { - /* - * String cmd, String permission, String description, String usage, String - * alias, CommandCategory category - */ + /* + * String cmd, String permission, String description, String usage, String + * alias, CommandCategory category + */ - public Rate() { - super("rate", "plots.rate", "Rate the plot", "rate {0-10}", "rt", CommandCategory.ACTIONS); - } + public Rate() { + super("rate", "plots.rate", "Rate the plot", "rate {0-10}", "rt", + CommandCategory.ACTIONS); + } - @Override - public boolean execute(Player plr, String... args) { - if (args.length < 1) { - sendMessage(plr, C.RATING_NOT_VALID); - return true; - } - if (!PlayerFunctions.isInPlot(plr)) { - sendMessage(plr, C.NOT_IN_PLOT); - return true; - } - Plot plot = PlayerFunctions.getCurrentPlot(plr); - if (!plot.hasOwner()) { - sendMessage(plr, C.RATING_NOT_OWNED); - return true; - } - if (plot.getOwner().equals(plr.getUniqueId())) { - sendMessage(plr, C.RATING_NOT_YOUR_OWN); - return true; - } - String arg = args[0]; - boolean o = false; - for (char c : arg.toCharArray()) { - if (!Character.isDigit(c)) { - o = true; - break; - } - } - int rating = 0; - if (!o) { - rating = Integer.parseInt(arg); - } - if (o || ((rating < 0) || (rating > 10))) { - sendMessage(plr, C.RATING_NOT_VALID); - return true; - } - // TODO implement check for already rated - boolean rated = false; - if (rated) { - sendMessage(plr, C.RATING_ALREADY_EXISTS, plot.getId().toString()); - } - // TODO actually do something... - boolean success = false; - if (success) { - sendMessage(plr, C.RATING_APPLIED, plot.getId().toString()); - } else { - sendMessage(plr, C.COMMAND_WENT_WRONG); - } - return true; - } + @Override + public boolean execute(Player plr, String... args) { + if (args.length < 1) { + sendMessage(plr, C.RATING_NOT_VALID); + return true; + } + if (!PlayerFunctions.isInPlot(plr)) { + sendMessage(plr, C.NOT_IN_PLOT); + return true; + } + Plot plot = PlayerFunctions.getCurrentPlot(plr); + if (!plot.hasOwner()) { + sendMessage(plr, C.RATING_NOT_OWNED); + return true; + } + if (plot.getOwner().equals(plr.getUniqueId())) { + sendMessage(plr, C.RATING_NOT_YOUR_OWN); + return true; + } + String arg = args[0]; + boolean o = false; + for (char c : arg.toCharArray()) { + if (!Character.isDigit(c)) { + o = true; + break; + } + } + int rating = 0; + if (!o) { + rating = Integer.parseInt(arg); + } + if (o || ((rating < 0) || (rating > 10))) { + sendMessage(plr, C.RATING_NOT_VALID); + return true; + } + // TODO implement check for already rated + boolean rated = false; + if (rated) { + sendMessage(plr, C.RATING_ALREADY_EXISTS, plot.getId().toString()); + } + // TODO actually do something... + boolean success = false; + if (success) { + sendMessage(plr, C.RATING_APPLIED, plot.getId().toString()); + } else { + sendMessage(plr, C.COMMAND_WENT_WRONG); + } + return true; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/commands/Reload.java b/PlotSquared/src/com/intellectualcrafters/plot/commands/Reload.java index f8528fa3c..1eee8214f 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/commands/Reload.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/commands/Reload.java @@ -20,23 +20,24 @@ import com.intellectualcrafters.plot.PlotMain; */ public class Reload extends SubCommand { - public Reload() { - super("reload", "plots.admin", "Reload configurations", "", "reload", CommandCategory.INFO); - } + public Reload() { + super("reload", "plots.admin", "Reload configurations", "", "reload", + CommandCategory.INFO); + } - @Override - public boolean execute(Player plr, String... args) { - try { - PlotMain.reloadTranslations(); - PlotMain.BroadcastWithPerms(C.RELOADED_CONFIGS); - } catch (Exception e) { - if (plr != null) { - PlayerFunctions.sendMessage(plr, C.RELOAD_FAILED); - } else { - PlotMain.sendConsoleSenderMessage(C.RELOAD_FAILED); - } - } - return true; - } + @Override + public boolean execute(Player plr, String... args) { + try { + PlotMain.reloadTranslations(); + PlotMain.BroadcastWithPerms(C.RELOADED_CONFIGS); + } catch (Exception e) { + if (plr != null) { + PlayerFunctions.sendMessage(plr, C.RELOAD_FAILED); + } else { + PlotMain.sendConsoleSenderMessage(C.RELOAD_FAILED); + } + } + return true; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/commands/Schematic.java b/PlotSquared/src/com/intellectualcrafters/plot/commands/Schematic.java index 619401649..a0ddc090d 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/commands/Schematic.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/commands/Schematic.java @@ -4,67 +4,78 @@ import org.bukkit.entity.Player; import com.intellectualcrafters.plot.C; import com.intellectualcrafters.plot.PlayerFunctions; -import com.intellectualcrafters.plot.PlotMain; +import com.intellectualcrafters.plot.Plot; +import com.intellectualcrafters.plot.PlotHelper; import com.intellectualcrafters.plot.SchematicHandler; public class Schematic extends SubCommand { - public Schematic() { - super("schematic", "plots.admin", "Schematic Command", "schematic {arg}", "sch", CommandCategory.ACTIONS); - } + public Schematic() { + super("schematic", "plots.admin", "Schematic Command", + "schematic {arg}", "sch", CommandCategory.ACTIONS); + } - @Override - public boolean execute(Player plr, String... args) { - if (args.length < 1) { - sendMessage(plr, C.SCHEMATIC_MISSING_ARG); - return true; - } - String arg = args[0]; - String file; - SchematicHandler.Schematic schematic; - switch (arg) { - case "paste": - if (args.length < 2) { - sendMessage(plr, C.SCHEMATIC_MISSING_ARG); - break; - } - if (!PlayerFunctions.isInPlot(plr)) { - sendMessage(plr, C.NOT_IN_PLOT); - break; - } - file = args[1]; - schematic = new SchematicHandler().getSchematic(file); - boolean s = new SchematicHandler().paste(plr.getLocation(), schematic, PlayerFunctions.getCurrentPlot(plr)); - if (s) { - sendMessage(plr, C.SCHEMATIC_PASTE_SUCCESS); - } else { - sendMessage(plr, C.SCHEMATIC_PASTE_FAILED); - } - break; - case "test": - if (args.length < 2) { - sendMessage(plr, C.SCHEMATIC_MISSING_ARG); - break; - } - file = args[1]; - schematic = new SchematicHandler().getSchematic(file); - if (schematic == null) { - sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent"); - break; - } - int l1 = schematic.getSchematicDimension().getX(); - int l2 = schematic.getSchematicDimension().getZ(); - int length = PlotMain.getWorldSettings(plr.getWorld()).PLOT_WIDTH; - if ((l1 != length) || (l2 != length)) { - sendMessage(plr, C.SCHEMATIC_INVALID, String.format("Wrong size (x: %s, z: %d) vs %d ", l1, l2, length)); - break; - } - sendMessage(plr, C.SCHEMATIC_VALID); - break; - default: - sendMessage(plr, C.SCHEMATIC_MISSING_ARG); - break; - } - return true; - } + @Override + public boolean execute(Player plr, String... args) { + if (args.length < 1) { + sendMessage(plr, C.SCHEMATIC_MISSING_ARG); + return true; + } + String arg = args[0]; + String file; + SchematicHandler.Schematic schematic; + switch (arg) { + case "paste": + if (args.length < 2) { + sendMessage(plr, C.SCHEMATIC_MISSING_ARG); + break; + } + if (!PlayerFunctions.isInPlot(plr)) { + sendMessage(plr, C.NOT_IN_PLOT); + break; + } + file = args[1]; + schematic = new SchematicHandler().getSchematic(file); + boolean s = new SchematicHandler().paste(plr.getLocation(), + schematic, PlayerFunctions.getCurrentPlot(plr)); + if (s) { + sendMessage(plr, C.SCHEMATIC_PASTE_SUCCESS); + } else { + sendMessage(plr, C.SCHEMATIC_PASTE_FAILED); + } + break; + case "test": + if (args.length < 2) { + sendMessage(plr, C.SCHEMATIC_MISSING_ARG); + break; + } + file = args[1]; + schematic = new SchematicHandler().getSchematic(file); + if (schematic == null) { + sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent"); + break; + } + if (!PlayerFunctions.isInPlot(plr)) { + sendMessage(plr, C.NOT_IN_PLOT); + break; + } + int l1 = schematic.getSchematicDimension().getX(); + int l2 = schematic.getSchematicDimension().getZ(); + + Plot plot = PlayerFunctions.getCurrentPlot(plr); + int length = PlotHelper.getPlotWidth(plr.getWorld(), plot.id); + + if ((l1 != length) || (l2 != length)) { + sendMessage(plr, C.SCHEMATIC_INVALID, String.format( + "Wrong size (x: %s, z: %d) vs %d ", l1, l2, length)); + break; + } + sendMessage(plr, C.SCHEMATIC_VALID); + break; + default: + sendMessage(plr, C.SCHEMATIC_MISSING_ARG); + break; + } + return true; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/commands/Set.java b/PlotSquared/src/com/intellectualcrafters/plot/commands/Set.java index e382596d4..5acdba638 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/commands/Set.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/commands/Set.java @@ -26,6 +26,7 @@ import com.intellectualcrafters.plot.Flag; import com.intellectualcrafters.plot.FlagManager; import com.intellectualcrafters.plot.PlayerFunctions; import com.intellectualcrafters.plot.Plot; +import com.intellectualcrafters.plot.PlotBlock; import com.intellectualcrafters.plot.PlotHelper; import com.intellectualcrafters.plot.PlotHomePosition; import com.intellectualcrafters.plot.PlotMain; @@ -35,380 +36,413 @@ import com.intellectualcrafters.plot.events.PlotFlagAddEvent; import com.intellectualcrafters.plot.events.PlotFlagRemoveEvent; /** - * + * * @author Citymonstret - * + * */ public class Set extends SubCommand { - public Set() { - super(Command.SET, "Set a plot value", "set {arg} {value...}", CommandCategory.ACTIONS); - } + public Set() { + super(Command.SET, "Set a plot value", "set {arg} {value...}", + CommandCategory.ACTIONS); + } - public static String[] values = new String[] { "biome", "wall", "wall_filling", "floor", "alias", "home", "rain", "flag" }; - public static String[] aliases = new String[] { "b", "w", "wf", "f", "a", "h", "r", "fl" }; + public static String[] values = new String[] { "biome", "wall", + "wall_filling", "floor", "alias", "home", "rain", "flag" }; + public static String[] aliases = new String[] { "b", "w", "wf", "f", "a", + "h", "r", "fl" }; - @SuppressWarnings("deprecation") - @Override - public boolean execute(Player plr, String... args) { - if (!PlayerFunctions.isInPlot(plr)) { - PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); - return false; - } - Plot plot = PlayerFunctions.getCurrentPlot(plr); + @SuppressWarnings("deprecation") + @Override + public boolean execute(Player plr, String... args) { + if (!PlayerFunctions.isInPlot(plr)) { + PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); + return false; + } + Plot plot = PlayerFunctions.getCurrentPlot(plr); - if (!plot.hasRights(plr) && !plr.hasPermission("plots.admin")) { - PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); - return false; - } - if (args.length < 1) { - StringBuilder builder = new StringBuilder(); - builder.append(C.SUBCOMMAND_SET_OPTIONS_HEADER.s()); - builder.append(getArgumentList(values)); - PlayerFunctions.sendMessage(plr, builder.toString()); - return false; - } - for (int i = 0; i < aliases.length; i++) { - if (aliases[i].equalsIgnoreCase(args[0])) { - args[0] = values[i]; - break; - } - } - /* TODO: Implement option */ - boolean advanced_permissions = true; - if (advanced_permissions) { - if (!plr.hasPermission("plots.set." + args[0].toLowerCase())) { - PlayerFunctions.sendMessage(plr, C.NO_PERMISSION); - return false; - } - } + if (!plot.hasRights(plr) && !plr.hasPermission("plots.admin")) { + PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); + return false; + } + if (args.length < 1) { + StringBuilder builder = new StringBuilder(); + builder.append(C.SUBCOMMAND_SET_OPTIONS_HEADER.s()); + builder.append(getArgumentList(values)); + PlayerFunctions.sendMessage(plr, builder.toString()); + return false; + } + for (int i = 0; i < aliases.length; i++) { + if (aliases[i].equalsIgnoreCase(args[0])) { + args[0] = values[i]; + break; + } + } + /* TODO: Implement option */ + boolean advanced_permissions = true; + if (advanced_permissions) { + if (!plr.hasPermission("plots.set." + args[0].toLowerCase())) { + PlayerFunctions.sendMessage(plr, C.NO_PERMISSION); + return false; + } + } - if (args[0].equalsIgnoreCase("flag")) { - if (args.length < 2) { - String message = StringUtils.join(FlagManager.getFlags(), "&c, &6"); - if (PlotMain.worldGuardListener != null) { - if (message.equals("")) { - message = StringUtils.join(PlotMain.worldGuardListener.str_flags, "&c, &6"); - } else { - message += "," + StringUtils.join(PlotMain.worldGuardListener.str_flags, "&c, &6"); - } - } - PlayerFunctions.sendMessage(plr, C.NEED_KEY.s().replaceAll("%values%", message)); - return false; - } - if (!FlagManager.getFlags().contains(args[1].toLowerCase()) && (PlotMain.worldGuardListener != null) && !PlotMain.worldGuardListener.str_flags.contains(args[1].toLowerCase())) { - PlayerFunctions.sendMessage(plr, C.NOT_VALID_FLAG); - return false; - } - if (!plr.hasPermission("plots.set.flag" + args[1].toLowerCase())) { - PlayerFunctions.sendMessage(plr, C.NO_PERMISSION); - return false; - } - if (args.length == 2) { - if (plot.settings.getFlag(args[1].toLowerCase()) == null) { - if (PlotMain.worldGuardListener != null) { - if (PlotMain.worldGuardListener.str_flags.contains(args[1].toLowerCase())) { - PlotMain.worldGuardListener.removeFlag(plr, plr.getWorld(), plot, args[1]); - return false; - } - } - PlayerFunctions.sendMessage(plr, C.FLAG_NOT_IN_PLOT); - return false; - } - Flag flag = plot.settings.getFlag(args[1].toLowerCase()); - PlotFlagRemoveEvent event = new PlotFlagRemoveEvent(flag, plot); - Bukkit.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) { - PlayerFunctions.sendMessage(plr, C.FLAG_NOT_REMOVED); - event.setCancelled(true); - return false; - } - java.util.Set newflags = plot.settings.getFlags(); - Flag oldFlag = plot.settings.getFlag(args[1].toLowerCase()); - if (oldFlag != null) { - newflags.remove(oldFlag); - } - plot.settings.setFlags(newflags.toArray(new Flag[0])); - DBFunc.setFlags(plr.getWorld().getName(), plot, newflags.toArray(new Flag[0])); - PlayerFunctions.sendMessage(plr, C.FLAG_REMOVED); - return true; - } - try { - String value = StringUtils.join(Arrays.copyOfRange(args, 2, args.length), " "); - if ((FlagManager.getFlag(args[1].toLowerCase()) == null) && (PlotMain.worldGuardListener != null)) { - PlotMain.worldGuardListener.addFlag(plr, plr.getWorld(), plot, args[1], value); - return false; - } - Flag flag = new Flag(FlagManager.getFlag(args[1].toLowerCase(), true), value); - PlotFlagAddEvent event = new PlotFlagAddEvent(flag, plot); - Bukkit.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) { - PlayerFunctions.sendMessage(plr, C.FLAG_NOT_ADDED); - event.setCancelled(true); - return false; - } - plot.settings.addFlag(flag); - DBFunc.setFlags(plr.getWorld().getName(), plot, plot.settings.getFlags().toArray(new Flag[0])); - PlayerFunctions.sendMessage(plr, C.FLAG_ADDED); - return true; - } catch (Exception e) { - PlayerFunctions.sendMessage(plr, "&c" + e.getMessage()); - return false; - } - } - if (args[0].equalsIgnoreCase("rain")) { - if (args.length < 2) { - PlayerFunctions.sendMessage(plr, C.NEED_ON_OFF); - return false; - } - String word = args[1]; - if (!word.equalsIgnoreCase("on") && !word.equalsIgnoreCase("off")) { - PlayerFunctions.sendMessage(plr, C.NEED_ON_OFF); - return true; - } - boolean b = word.equalsIgnoreCase("on"); - DBFunc.setWeather(plr.getWorld().getName(), plot, b); - PlayerFunctions.sendMessage(plr, C.SETTING_UPDATED); - for (Player p : Bukkit.getOnlinePlayers()) { - if (PlayerFunctions.getCurrentPlot(plr).id == plot.id) { - if (b) { - p.setPlayerWeather(WeatherType.DOWNFALL); - } else { - p.resetPlayerWeather(); - } - } - } - return true; - } + if (args[0].equalsIgnoreCase("flag")) { + if (args.length < 2) { + String message = StringUtils.join(FlagManager.getFlags(), + "&c, &6"); + if (PlotMain.worldGuardListener != null) { + if (message.equals("")) { + message = StringUtils + .join(PlotMain.worldGuardListener.str_flags, + "&c, &6"); + } else { + message += "," + + StringUtils.join( + PlotMain.worldGuardListener.str_flags, + "&c, &6"); + } + } + PlayerFunctions.sendMessage(plr, + C.NEED_KEY.s().replaceAll("%values%", message)); + return false; + } + if (!FlagManager.getFlags().contains(args[1].toLowerCase()) + && (PlotMain.worldGuardListener != null) + && !PlotMain.worldGuardListener.str_flags.contains(args[1] + .toLowerCase())) { + PlayerFunctions.sendMessage(plr, C.NOT_VALID_FLAG); + return false; + } + if (!plr.hasPermission("plots.set.flag" + args[1].toLowerCase())) { + PlayerFunctions.sendMessage(plr, C.NO_PERMISSION); + return false; + } + if (args.length == 2) { + if (plot.settings.getFlag(args[1].toLowerCase()) == null) { + if (PlotMain.worldGuardListener != null) { + if (PlotMain.worldGuardListener.str_flags + .contains(args[1].toLowerCase())) { + PlotMain.worldGuardListener.removeFlag(plr, + plr.getWorld(), plot, args[1]); + return false; + } + } + PlayerFunctions.sendMessage(plr, C.FLAG_NOT_IN_PLOT); + return false; + } + Flag flag = plot.settings.getFlag(args[1].toLowerCase()); + PlotFlagRemoveEvent event = new PlotFlagRemoveEvent(flag, plot); + Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + PlayerFunctions.sendMessage(plr, C.FLAG_NOT_REMOVED); + event.setCancelled(true); + return false; + } + java.util.Set newflags = plot.settings.getFlags(); + Flag oldFlag = plot.settings.getFlag(args[1].toLowerCase()); + if (oldFlag != null) { + newflags.remove(oldFlag); + } + plot.settings.setFlags(newflags.toArray(new Flag[0])); + DBFunc.setFlags(plr.getWorld().getName(), plot, + newflags.toArray(new Flag[0])); + PlayerFunctions.sendMessage(plr, C.FLAG_REMOVED); + return true; + } + try { + String value = StringUtils.join( + Arrays.copyOfRange(args, 2, args.length), " "); + if ((FlagManager.getFlag(args[1].toLowerCase()) == null) + && (PlotMain.worldGuardListener != null)) { + PlotMain.worldGuardListener.addFlag(plr, plr.getWorld(), + plot, args[1], value); + return false; + } + Flag flag = new Flag(FlagManager.getFlag(args[1].toLowerCase(), + true), value); + PlotFlagAddEvent event = new PlotFlagAddEvent(flag, plot); + Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + PlayerFunctions.sendMessage(plr, C.FLAG_NOT_ADDED); + event.setCancelled(true); + return false; + } + plot.settings.addFlag(flag); + DBFunc.setFlags(plr.getWorld().getName(), plot, plot.settings + .getFlags().toArray(new Flag[0])); + PlayerFunctions.sendMessage(plr, C.FLAG_ADDED); + return true; + } catch (Exception e) { + PlayerFunctions.sendMessage(plr, "&c" + e.getMessage()); + return false; + } + } + if (args[0].equalsIgnoreCase("rain")) { + if (args.length < 2) { + PlayerFunctions.sendMessage(plr, C.NEED_ON_OFF); + return false; + } + String word = args[1]; + if (!word.equalsIgnoreCase("on") && !word.equalsIgnoreCase("off")) { + PlayerFunctions.sendMessage(plr, C.NEED_ON_OFF); + return true; + } + boolean b = word.equalsIgnoreCase("on"); + DBFunc.setWeather(plr.getWorld().getName(), plot, b); + PlayerFunctions.sendMessage(plr, C.SETTING_UPDATED); + for (Player p : Bukkit.getOnlinePlayers()) { + if (PlayerFunctions.getCurrentPlot(plr).id == plot.id) { + if (b) { + p.setPlayerWeather(WeatherType.DOWNFALL); + } else { + p.resetPlayerWeather(); + } + } + } + return true; + } - if (args[0].equalsIgnoreCase("home")) { - if (args.length < 2) { - PlayerFunctions.sendMessage(plr, C.MISSING_POSITION); - return false; - } - PlotHomePosition position = null; - for (PlotHomePosition p : PlotHomePosition.values()) { - if (p.isMatching(args[1])) { - position = p; - } - } - if (position == null) { - PlayerFunctions.sendMessage(plr, C.INVALID_POSITION); - return false; - } - DBFunc.setPosition(plr.getWorld().getName(), plot, position.toString()); - PlayerFunctions.sendMessage(plr, C.POSITION_SET); - return true; - } + if (args[0].equalsIgnoreCase("home")) { + if (args.length < 2) { + PlayerFunctions.sendMessage(plr, C.MISSING_POSITION); + return false; + } + PlotHomePosition position = null; + for (PlotHomePosition p : PlotHomePosition.values()) { + if (p.isMatching(args[1])) { + position = p; + } + } + if (position == null) { + PlayerFunctions.sendMessage(plr, C.INVALID_POSITION); + return false; + } + DBFunc.setPosition(plr.getWorld().getName(), plot, + position.toString()); + PlayerFunctions.sendMessage(plr, C.POSITION_SET); + return true; + } - if (args[0].equalsIgnoreCase("alias")) { - if (args.length < 2) { - PlayerFunctions.sendMessage(plr, C.MISSING_ALIAS); - return false; - } - String alias = args[1]; - for (Plot p : PlotMain.getPlots(plr.getWorld()).values()) { - if (p.settings.getAlias().equalsIgnoreCase(alias)) { - PlayerFunctions.sendMessage(plr, C.ALIAS_IS_TAKEN); - return false; - } - if (Bukkit.getOfflinePlayer(alias).hasPlayedBefore()) { - PlayerFunctions.sendMessage(plr, C.ALIAS_IS_TAKEN); - return false; - } - } - DBFunc.setAlias(plr.getWorld().getName(), plot, alias); - PlayerFunctions.sendMessage(plr, C.ALIAS_SET_TO.s().replaceAll("%alias%", alias)); - return true; - } - if (args[0].equalsIgnoreCase("biome")) { - if (args.length < 2) { - PlayerFunctions.sendMessage(plr, C.NEED_BIOME); - return true; - } - Biome biome = null; - for (Biome b : Biome.values()) { - if (b.toString().equalsIgnoreCase(args[1])) { - biome = b; - break; - } - } - if (biome == null) { - PlayerFunctions.sendMessage(plr, getBiomeList(Arrays.asList(Biome.values()))); - return true; - } - PlotHelper.setBiome(plr.getWorld(), plot, biome); - PlayerFunctions.sendMessage(plr, C.BIOME_SET_TO.s() + biome.toString().toLowerCase()); - return true; - } - if (args[0].equalsIgnoreCase("wall")) { - PlotWorld plotworld = PlotMain.getWorldSettings(plr.getWorld()); - if (plotworld == null) { - PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD); - return true; - } - if (args.length < 2) { - PlayerFunctions.sendMessage(plr, C.NEED_BLOCK); - return true; - } - Material material = null; - for (Material m : PlotWorld.BLOCKS) { - if (m.toString().equalsIgnoreCase(args[1])) { - material = m; - break; - } - } - if (material == null) { - PlayerFunctions.sendMessage(plr, getBlockList(PlotWorld.BLOCKS)); - return true; - } - byte data = 0; + if (args[0].equalsIgnoreCase("alias")) { + if (args.length < 2) { + PlayerFunctions.sendMessage(plr, C.MISSING_ALIAS); + return false; + } + String alias = args[1]; + for (Plot p : PlotMain.getPlots(plr.getWorld()).values()) { + if (p.settings.getAlias().equalsIgnoreCase(alias)) { + PlayerFunctions.sendMessage(plr, C.ALIAS_IS_TAKEN); + return false; + } + if (Bukkit.getOfflinePlayer(alias).hasPlayedBefore()) { + PlayerFunctions.sendMessage(plr, C.ALIAS_IS_TAKEN); + return false; + } + } + DBFunc.setAlias(plr.getWorld().getName(), plot, alias); + PlayerFunctions.sendMessage(plr, + C.ALIAS_SET_TO.s().replaceAll("%alias%", alias)); + return true; + } + if (args[0].equalsIgnoreCase("biome")) { + if (args.length < 2) { + PlayerFunctions.sendMessage(plr, C.NEED_BIOME); + return true; + } + Biome biome = null; + for (Biome b : Biome.values()) { + if (b.toString().equalsIgnoreCase(args[1])) { + biome = b; + break; + } + } + if (biome == null) { + PlayerFunctions.sendMessage(plr, + getBiomeList(Arrays.asList(Biome.values()))); + return true; + } + PlotHelper.setBiome(plr.getWorld(), plot, biome); + PlayerFunctions.sendMessage(plr, C.BIOME_SET_TO.s() + + biome.toString().toLowerCase()); + return true; + } + if (args[0].equalsIgnoreCase("wall")) { + PlotWorld plotworld = PlotMain.getWorldSettings(plr.getWorld()); + if (plotworld == null) { + PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD); + return true; + } + if (args.length < 2) { + PlayerFunctions.sendMessage(plr, C.NEED_BLOCK); + return true; + } + Material material = null; + for (Material m : PlotWorld.BLOCKS) { + if (m.toString().equalsIgnoreCase(args[1])) { + material = m; + break; + } + } + if (material == null) { + PlayerFunctions + .sendMessage(plr, getBlockList(PlotWorld.BLOCKS)); + return true; + } + byte data = 0; - if (args.length > 2) { - try { - data = (byte) Integer.parseInt(args[2]); - } catch (Exception e) { - PlayerFunctions.sendMessage(plr, C.NOT_VALID_DATA); - return true; - } - } - PlayerFunctions.sendMessage(plr, C.GENERATING_WALL); - PlotHelper.adjustWall(plr.getWorld(), plot, (short) material.getId(), data); - return true; - } - if (args[0].equalsIgnoreCase("floor")) { - if (args.length < 2) { - PlayerFunctions.sendMessage(plr, C.NEED_BLOCK); - return true; - } - PlotWorld plotworld = PlotMain.getWorldSettings(plr.getWorld()); - if (plotworld == null) { - PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD); - return true; - } - // - @SuppressWarnings("unchecked") - ArrayList materials = (ArrayList) PlotWorld.BLOCKS.clone(); - materials.add(Material.AIR); - // - String[] strings = args[1].split(","); - // - Material[] material = new Material[strings.length]; - byte[] data = new byte[strings.length]; - // - int index = 0; - // - byte b = (byte) 0; - Material m = null; - // - for (String s : strings) { - s = s.replaceAll(",", ""); - String[] ss = s.split(";"); - ss[0] = ss[0].replaceAll(";", ""); - for (Material ma : materials) { - if (ma.toString().equalsIgnoreCase(ss[0])) { - m = ma; - } - } - if (m == null) { - PlayerFunctions.sendMessage(plr, C.NOT_VALID_BLOCK); - return true; - } - if (ss.length == 1) { - data[index] = (byte) 0; - material[index] = m; - } else { - try { - b = (byte) Integer.parseInt(ss[1]); - } catch (Exception e) { - PlayerFunctions.sendMessage(plr, C.NOT_VALID_DATA); - return true; - } - data[index] = b; - material[index] = m; - } - index++; - } - PlotHelper.setFloor(plr, plot, material, data); - return true; - } - if (args[0].equalsIgnoreCase("wall_filling")) { - if (args.length < 2) { - PlayerFunctions.sendMessage(plr, C.NEED_BLOCK); - return true; - } - PlotWorld plotworld = PlotMain.getWorldSettings(plr.getWorld()); - if (plotworld == null) { - PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD); - return true; - } - Material material = null; - for (Material m : PlotWorld.BLOCKS) { - if (m.toString().equalsIgnoreCase(args[1])) { - material = m; - break; - } - } - if (material == null) { - PlayerFunctions.sendMessage(plr, getBlockList(PlotWorld.BLOCKS)); - return true; - } - byte data = 0; + if (args.length > 2) { + try { + data = (byte) Integer.parseInt(args[2]); + } catch (Exception e) { + PlayerFunctions.sendMessage(plr, C.NOT_VALID_DATA); + return true; + } + } + PlayerFunctions.sendMessage(plr, C.GENERATING_WALL); + PlotHelper.adjustWall(plr, plot, + new PlotBlock((short) material.getId(), data)); + return true; + } + if (args[0].equalsIgnoreCase("floor")) { + if (args.length < 2) { + PlayerFunctions.sendMessage(plr, C.NEED_BLOCK); + return true; + } + PlotWorld plotworld = PlotMain.getWorldSettings(plr.getWorld()); + if (plotworld == null) { + PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD); + return true; + } + // + @SuppressWarnings("unchecked") + ArrayList materials = (ArrayList) PlotWorld.BLOCKS + .clone(); + materials.add(Material.AIR); + // + String[] strings = args[1].split(","); + // + int index = 0; + // + byte b = (byte) 0; + Material m = null; + // + PlotBlock[] blocks = new PlotBlock[strings.length]; - if (args.length > 2) { - try { - data = (byte) Integer.parseInt(args[2]); - } catch (Exception e) { - PlayerFunctions.sendMessage(plr, C.NOT_VALID_DATA); - return true; - } - } - PlotHelper.adjustWallFilling(plr, plr.getWorld(), plot, (short) material.getId(), data); - return true; - } - StringBuilder builder = new StringBuilder(); - builder.append(C.SUBCOMMAND_SET_OPTIONS_HEADER.s()); - builder.append(getArgumentList(values)); - PlayerFunctions.sendMessage(plr, builder.toString()); - return false; - } + for (String s : strings) { + s = s.replaceAll(",", ""); + String[] ss = s.split(";"); + ss[0] = ss[0].replaceAll(";", ""); + for (Material ma : materials) { + if (ma.toString().equalsIgnoreCase(ss[0])) { + m = ma; + } + } + if (m == null) { + PlayerFunctions.sendMessage(plr, C.NOT_VALID_BLOCK); + return true; + } + if (ss.length == 1) { - private String getMaterial(Material m) { - return ChatColor.translateAlternateColorCodes('&', C.BLOCK_LIST_ITEM.s().replaceAll("%mat%", m.toString().toLowerCase())); - } + blocks[index] = new PlotBlock((short) m.getId(), (byte) 0); + } else { + try { + b = (byte) Integer.parseInt(ss[1]); + } catch (Exception e) { + PlayerFunctions.sendMessage(plr, C.NOT_VALID_DATA); + return true; + } + blocks[index] = new PlotBlock((short) m.getId(), b); + } + index++; + } + PlotHelper.setFloor(plr, plot, blocks); + return true; + } + if (args[0].equalsIgnoreCase("wall_filling")) { + if (args.length < 2) { + PlayerFunctions.sendMessage(plr, C.NEED_BLOCK); + return true; + } + PlotWorld plotworld = PlotMain.getWorldSettings(plr.getWorld()); + if (plotworld == null) { + PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD); + return true; + } + Material material = null; + for (Material m : PlotWorld.BLOCKS) { + if (m.toString().equalsIgnoreCase(args[1])) { + material = m; + break; + } + } + if (material == null) { + PlayerFunctions + .sendMessage(plr, getBlockList(PlotWorld.BLOCKS)); + return true; + } + byte data = 0; - private String getBiome(Biome b) { - return ChatColor.translateAlternateColorCodes('&', C.BLOCK_LIST_ITEM.s().replaceAll("%mat%", b.toString().toLowerCase())); - } + if (args.length > 2) { + try { + data = (byte) Integer.parseInt(args[2]); + } catch (Exception e) { + PlayerFunctions.sendMessage(plr, C.NOT_VALID_DATA); + return true; + } + } + PlotHelper.adjustWallFilling(plr, plot, new PlotBlock( + (short) material.getId(), data)); + return true; + } + StringBuilder builder = new StringBuilder(); + builder.append(C.SUBCOMMAND_SET_OPTIONS_HEADER.s()); + builder.append(getArgumentList(values)); + PlayerFunctions.sendMessage(plr, builder.toString()); + return false; + } - private String getString(String s) { - return ChatColor.translateAlternateColorCodes('&', C.BLOCK_LIST_ITEM.s().replaceAll("%mat%", s)); - } + private String getMaterial(Material m) { + return ChatColor.translateAlternateColorCodes('&', C.BLOCK_LIST_ITEM + .s().replaceAll("%mat%", m.toString().toLowerCase())); + } - private String getArgumentList(String[] strings) { - StringBuilder builder = new StringBuilder(); - for (String s : strings) { - builder.append(getString(s)); - } - return builder.toString().substring(1, builder.toString().length() - 1); - } + private String getBiome(Biome b) { + return ChatColor.translateAlternateColorCodes('&', C.BLOCK_LIST_ITEM + .s().replaceAll("%mat%", b.toString().toLowerCase())); + } - private String getBiomeList(List biomes) { - StringBuilder builder = new StringBuilder(); - builder.append(ChatColor.translateAlternateColorCodes('&', C.NOT_VALID_BLOCK_LIST_HEADER.s())); - for (Biome b : biomes) { - builder.append(getBiome(b)); - } - return builder.toString().substring(1, builder.toString().length() - 1); - } + private String getString(String s) { + return ChatColor.translateAlternateColorCodes('&', C.BLOCK_LIST_ITEM + .s().replaceAll("%mat%", s)); + } - private String getBlockList(List blocks) { - StringBuilder builder = new StringBuilder(); - builder.append(ChatColor.translateAlternateColorCodes('&', C.NOT_VALID_BLOCK_LIST_HEADER.s())); - for (Material b : blocks) { - builder.append(getMaterial(b)); - } - return builder.toString().substring(1, builder.toString().length() - 1); - } + private String getArgumentList(String[] strings) { + StringBuilder builder = new StringBuilder(); + for (String s : strings) { + builder.append(getString(s)); + } + return builder.toString().substring(1, builder.toString().length() - 1); + } + + private String getBiomeList(List biomes) { + StringBuilder builder = new StringBuilder(); + builder.append(ChatColor.translateAlternateColorCodes('&', + C.NOT_VALID_BLOCK_LIST_HEADER.s())); + for (Biome b : biomes) { + builder.append(getBiome(b)); + } + return builder.toString().substring(1, builder.toString().length() - 1); + } + + private String getBlockList(List blocks) { + StringBuilder builder = new StringBuilder(); + builder.append(ChatColor.translateAlternateColorCodes('&', + C.NOT_VALID_BLOCK_LIST_HEADER.s())); + for (Material b : blocks) { + builder.append(getMaterial(b)); + } + return builder.toString().substring(1, builder.toString().length() - 1); + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/commands/SetOwner.java b/PlotSquared/src/com/intellectualcrafters/plot/commands/SetOwner.java index 8856ad539..b759ac1d1 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/commands/SetOwner.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/commands/SetOwner.java @@ -9,44 +9,50 @@ package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.*; -import com.intellectualcrafters.plot.database.DBFunc; +import java.util.UUID; + import org.bukkit.entity.Player; -import java.util.UUID; +import com.intellectualcrafters.plot.C; +import com.intellectualcrafters.plot.PlayerFunctions; +import com.intellectualcrafters.plot.Plot; +import com.intellectualcrafters.plot.PlotMain; +import com.intellectualcrafters.plot.UUIDHandler; +import com.intellectualcrafters.plot.database.DBFunc; @SuppressWarnings("deprecation") public class SetOwner extends SubCommand { - public SetOwner() { - super("setowner", "plots.admin", "Set the plot owner", "setowner {player}", "so", CommandCategory.ACTIONS); - } + public SetOwner() { + super("setowner", "plots.admin", "Set the plot owner", + "setowner {player}", "so", CommandCategory.ACTIONS); + } - /* - private UUID getUUID(String string) { - OfflinePlayer player = Bukkit.getOfflinePlayer(string); - return ((player != null) && player.hasPlayedBefore()) ? player.getUniqueId() : null; - }*/ + /* + * private UUID getUUID(String string) { OfflinePlayer player = + * Bukkit.getOfflinePlayer(string); return ((player != null) && + * player.hasPlayedBefore()) ? player.getUniqueId() : null; } + */ - private UUID getUUID(String string) { - return UUIDHandler.getUUID(string); - } + private UUID getUUID(String string) { + return UUIDHandler.getUUID(string); + } - @Override - public boolean execute(Player plr, String... args) { - if (!PlayerFunctions.isInPlot(plr)) { - PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); - return true; - } - Plot plot = PlayerFunctions.getCurrentPlot(plr); - if (args.length < 1) { - PlayerFunctions.sendMessage(plr, C.NEED_USER); - return true; - } - plot.owner = getUUID(args[0]); - PlotMain.updatePlot(plot); - DBFunc.setOwner(plot, plot.owner); - PlayerFunctions.sendMessage(plr, C.SET_OWNER); - return true; - } + @Override + public boolean execute(Player plr, String... args) { + if (!PlayerFunctions.isInPlot(plr)) { + PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); + return true; + } + Plot plot = PlayerFunctions.getCurrentPlot(plr); + if (args.length < 1) { + PlayerFunctions.sendMessage(plr, C.NEED_USER); + return true; + } + plot.owner = getUUID(args[0]); + PlotMain.updatePlot(plot); + DBFunc.setOwner(plot, plot.owner); + PlayerFunctions.sendMessage(plr, C.SET_OWNER); + return true; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/commands/Setup.java b/PlotSquared/src/com/intellectualcrafters/plot/commands/Setup.java index f1f4f91f7..39754b5b5 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/commands/Setup.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/commands/Setup.java @@ -1,16 +1,15 @@ package com.intellectualcrafters.plot.commands; import java.io.IOException; -import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; -import org.bukkit.block.Biome; import org.bukkit.entity.Player; import org.bukkit.event.Listener; import com.intellectualcrafters.plot.C; +import com.intellectualcrafters.plot.ConfigurationNode; import com.intellectualcrafters.plot.PlayerFunctions; import com.intellectualcrafters.plot.PlotMain; import com.intellectualcrafters.plot.PlotWorld; @@ -20,244 +19,148 @@ import com.intellectualcrafters.plot.PlotWorld; */ public class Setup extends SubCommand implements Listener { - public static Map setupMap = new HashMap<>(); + public static Map setupMap = new HashMap<>(); - private static class SetupStep { - private String constant; - private Object default_value; - private String description; - private Object value = 0; - private String type; + private class SetupObject { + String world; + int current = 0; - public SetupStep(String constant, Object default_value, String description, String type, boolean require_previous) { - this.constant = constant; - this.default_value = default_value; - this.description = description; - this.type = type; - } + ConfigurationNode[] step; - public String getType() { - return this.type; - } + public SetupObject(String world, PlotWorld plotworld) { + this.world = world; + this.step = plotworld.getSettingNodes(); + } - public boolean setValue(String string) { - if (!validValue(string)) { - return false; - } - switch (this.type) { - case "integer": - this.value = Integer.parseInt(string); - break; - case "boolean": - this.value = Boolean.parseBoolean(string); - break; - case "double": - this.value = Double.parseDouble(string); - break; - case "float": - this.value = Float.parseFloat(string); - break; - case "biome": - this.value = (string.toUpperCase()); - break; - case "block": - this.value = string; - break; - case "blocklist": - this.value = string.split(","); - break; - case "string": - this.value = string; - break; - } - return true; - } + public int getCurrent() { + return this.current; + } - public boolean validValue(String string) { - try { - if (this.type.equals("integer")) { - Integer.parseInt(string); - return true; - } - if (this.type.equals("boolean")) { - Boolean.parseBoolean(string); - return true; - } - if (this.type.equals("double")) { - Double.parseDouble(string); - return true; - } - if (this.type.equals("float")) { - Float.parseFloat(string); - return true; - } - if (this.type.equals("biome")) { - Biome.valueOf(string.toUpperCase()); - return true; - } - if (this.type.equals("block")) { - if (string.contains(":")) { - String[] split = string.split(":"); - Short.parseShort(split[0]); - Short.parseShort(split[1]); - } else { - Short.parseShort(string); - } - return true; - } - if (this.type.equals("blocklist")) { - for (String block : string.split(",")) { - if (block.contains(":")) { - String[] split = block.split(":"); - Short.parseShort(split[0]); - Short.parseShort(split[1]); - } else { - Short.parseShort(block); - } - } - return true; - } - if (this.type.equals("string")) { - return true; - } - } catch (Exception e) { - } - return false; - } + public int getMax() { + return this.step.length; + } + } - public Object getValue() { - if (this.value instanceof String[]) { - return Arrays.asList((String[]) this.value); - } - return this.value; - } + public Setup() { + super("setup", "plots.admin", "Setup a PlotWorld", "setup {world}", + "setup", CommandCategory.ACTIONS); + } - public String getConstant() { - return this.constant; - } + @Override + public boolean execute(Player plr, String... args) { + boolean finished = false; - public Object getDefaultValue() { - if (this.default_value instanceof String[]) { - return StringUtils.join((String[]) this.default_value, ","); - } - return this.default_value; - } + if (!finished) { + // TODO recode this to work with the multiple generators + PlayerFunctions + .sendMessage(plr, "&4CURRENTLY NOT IMPLEMENTED YET!"); - public String getDescription() { - return this.description; - } - } + return false; + } - private class SetupObject { - String world; - int current = 0; + if (setupMap.containsKey(plr.getName())) { + SetupObject object = setupMap.get(plr.getName()); + if (object.getCurrent() == object.getMax()) { + sendMessage(plr, C.SETUP_FINISHED, object.world); - SetupStep[] step = new SetupStep[] { new SetupStep("road.height", PlotWorld.ROAD_HEIGHT_DEFAULT, "Height of road", "integer", false), new SetupStep("plot.height", PlotWorld.PLOT_HEIGHT_DEFAULT, "Height of plot", "integer", false), new SetupStep("wall.height", PlotWorld.WALL_HEIGHT_DEFAULT, "Height of wall", "integer", false), new SetupStep("plot.size", PlotWorld.PLOT_WIDTH_DEFAULT, "Size of plot", "integer", false), new SetupStep("road.width", PlotWorld.ROAD_WIDTH_DEFAULT, "Width of road", "integer", false), new SetupStep("plot.biome", PlotWorld.PLOT_BIOME_DEFAULT, "Plot biome", "biome", false), new SetupStep("plot.filling", PlotWorld.MAIN_BLOCK_DEFAULT, "Plot filling", "blocklist", false), new SetupStep("plot.floor", PlotWorld.TOP_BLOCK_DEFAULT, "Plot floor", "blocklist", false), new SetupStep("wall.block", PlotWorld.WALL_BLOCK_DEFAULT, "Wall block", "block", false), new SetupStep("wall.filling", PlotWorld.WALL_FILLING_DEFAULT, "Wall filling", "block", false), - new SetupStep("road.enable_stripes", PlotWorld.ROAD_STRIPES_ENABLED_DEFAULT, "Enable road stripes", "boolean", false), new SetupStep("road.stripes", PlotWorld.ROAD_STRIPES_DEFAULT, "Road stripes block", "block", true), new SetupStep("road.block", PlotWorld.ROAD_BLOCK_DEFAULT, "Road block", "block", false), }; + ConfigurationNode[] steps = object.step; + String world = object.world; + for (ConfigurationNode step : steps) { + PlotMain.config.set( + "worlds." + world + "." + step.getConstant(), + step.getValue()); + } + try { + PlotMain.config.save(PlotMain.configFile); + } catch (IOException e) { + e.printStackTrace(); + } - public SetupObject(String world) { - this.world = world; - } + // World newWorld = WorldCreator.name(world).generator(new + // WorldGenerator(world)).createWorld(); + // plr.teleport(newWorld.getSpawnLocation()); - public int getCurrent() { - return this.current; - } + setupMap.remove(plr.getName()); - public int getMax() { - return this.step.length; - } - } + return true; + } + ConfigurationNode step = object.step[object.current]; + if (args.length < 1) { + sendMessage(plr, C.SETUP_STEP, object.current + 1 + "", + step.getDescription(), step.getType(), + step.getDefaultValue() + ""); + return true; + } else { + if (args[0].equalsIgnoreCase("cancel")) { + setupMap.remove(plr.getName()); + PlayerFunctions.sendMessage(plr, "&cCancelled setup."); + return true; + } + if (args[0].equalsIgnoreCase("back")) { + if (object.current > 0) { + object.current--; + step = object.step[object.current]; + sendMessage(plr, C.SETUP_STEP, object.current + 1 + "", + step.getDescription(), step.getType(), + step.getDefaultValue() + ""); + return true; + } else { + sendMessage(plr, C.SETUP_STEP, object.current + 1 + "", + step.getDescription(), step.getType(), + step.getDefaultValue() + ""); + return true; + } + } + boolean valid = step.isValid(args[0]); + if (valid) { + sendMessage(plr, C.SETUP_VALID_ARG, step.getConstant(), + args[0]); + step.setValue(args[0]); + object.current++; + if (object.getCurrent() == object.getMax()) { + execute(plr, args); + return true; + } + step = object.step[object.current]; + sendMessage(plr, C.SETUP_STEP, object.current + 1 + "", + step.getDescription(), step.getType(), + step.getDefaultValue() + ""); + return true; + } else { + sendMessage(plr, C.SETUP_INVALID_ARG, args[0], + step.getConstant()); + sendMessage(plr, C.SETUP_STEP, object.current + 1 + "", + step.getDescription(), step.getType(), + step.getDefaultValue() + ""); + return true; + } + } + } else { + if (args.length < 1) { + sendMessage(plr, C.SETUP_MISSING_WORLD); + return true; + } + String world = args[0]; + if (StringUtils.isNumeric(args[0])) { + sendMessage(plr, C.SETUP_WORLD_TAKEN, world); + return true; + } + if (PlotMain.getWorldSettings(world) != null) { + sendMessage(plr, C.SETUP_WORLD_TAKEN, world); + return true; + } - public Setup() { - super("setup", "plots.admin", "Setup a PlotWorld", "setup {world}", "setup", CommandCategory.ACTIONS); - } + PlotWorld plotworld = PlotMain.getWorldSettings("//TODO"); // TODO - @Override - public boolean execute(Player plr, String... args) { - if (setupMap.containsKey(plr.getName())) { - SetupObject object = setupMap.get(plr.getName()); - if (object.getCurrent() == object.getMax()) { - sendMessage(plr, C.SETUP_FINISHED, object.world); - - SetupStep[] steps = object.step; - String world = object.world; - for (SetupStep step : steps) { - PlotMain.config.set("worlds." + world + "." + step.constant, step.getValue()); - } - try { - PlotMain.config.save(PlotMain.configFile); - } catch (IOException e) { - e.printStackTrace(); - } - - // World newWorld = WorldCreator.name(world).generator(new - // WorldGenerator(world)).createWorld(); - // plr.teleport(newWorld.getSpawnLocation()); - - setupMap.remove(plr.getName()); - - return true; - } - SetupStep step = object.step[object.current]; - if (args.length < 1) { - sendMessage(plr, C.SETUP_STEP, object.current + 1 + "", step.getDescription(), step.getType(), step.getDefaultValue() + ""); - return true; - } else { - if (args[0].equalsIgnoreCase("cancel")) { - setupMap.remove(plr.getName()); - PlayerFunctions.sendMessage(plr, "&cCancelled setup."); - return true; - } - if (args[0].equalsIgnoreCase("back")) { - if (object.current > 0) { - object.current--; - step = object.step[object.current]; - sendMessage(plr, C.SETUP_STEP, object.current + 1 + "", step.getDescription(), step.getType(), step.getDefaultValue() + ""); - return true; - } else { - sendMessage(plr, C.SETUP_STEP, object.current + 1 + "", step.getDescription(), step.getType(), step.getDefaultValue() + ""); - return true; - } - } - boolean valid = step.validValue(args[0]); - if (valid) { - sendMessage(plr, C.SETUP_VALID_ARG, step.getConstant(), args[0]); - step.setValue(args[0]); - object.current++; - if (object.getCurrent() == object.getMax()) { - execute(plr, args); - return true; - } - step = object.step[object.current]; - sendMessage(plr, C.SETUP_STEP, object.current + 1 + "", step.getDescription(), step.getType(), step.getDefaultValue() + ""); - return true; - } else { - sendMessage(plr, C.SETUP_INVALID_ARG, args[0], step.getConstant()); - sendMessage(plr, C.SETUP_STEP, object.current + 1 + "", step.getDescription(), step.getType(), step.getDefaultValue() + ""); - return true; - } - } - } else { - if (args.length < 1) { - sendMessage(plr, C.SETUP_MISSING_WORLD); - return true; - } - String world = args[0]; - if (StringUtils.isNumeric(args[0])) { - sendMessage(plr, C.SETUP_WORLD_TAKEN, world); - return true; - } - if (PlotMain.getWorldSettings(world) != null) { - sendMessage(plr, C.SETUP_WORLD_TAKEN, world); - return true; - } - setupMap.put(plr.getName(), new SetupObject(world)); - sendMessage(plr, C.SETUP_INIT); - SetupObject object = setupMap.get(plr.getName()); - SetupStep step = object.step[object.current]; - sendMessage(plr, C.SETUP_STEP, object.current + 1 + "", step.getDescription(), step.getType(), step.getDefaultValue() + ""); - return true; - } - } + setupMap.put(plr.getName(), new SetupObject(world, plotworld)); + sendMessage(plr, C.SETUP_INIT); + SetupObject object = setupMap.get(plr.getName()); + ConfigurationNode step = object.step[object.current]; + sendMessage(plr, C.SETUP_STEP, object.current + 1 + "", + step.getDescription(), step.getType(), + step.getDefaultValue() + ""); + return true; + } + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/commands/SubCommand.java b/PlotSquared/src/com/intellectualcrafters/plot/commands/SubCommand.java index 37e93996d..a7d3bb11d 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/commands/SubCommand.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/commands/SubCommand.java @@ -16,117 +16,120 @@ import com.intellectualcrafters.plot.PlayerFunctions; /** * SubCommand class - * + * * @author Citymonstret - * + * */ public abstract class SubCommand { - /** - * Command - */ - public String cmd; - /** - * Permission node - */ - public CommandPermission permission; - /** - * Simple description - */ - public String description; - /** - * Alias - */ - public String alias; + /** + * Command + */ + public String cmd; + /** + * Permission node + */ + public CommandPermission permission; + /** + * Simple description + */ + public String description; + /** + * Alias + */ + public String alias; - /** - * Command usage - */ - public String usage; + /** + * Command usage + */ + public String usage; - public CommandCategory category; + public CommandCategory category; - /** - * - * @param cmd - * Command /plot {cmd} <-- That! - * @param permission - * Permission Node - * @param description - * Simple description - * @param usage - * Usage description: /plot command {args...} - * @param alias - * Command alias - * @param category - * CommandCategory. Pick whichever closests to what you want. - */ - public SubCommand(String cmd, String permission, String description, String usage, String alias, CommandCategory category) { - this.cmd = cmd; - this.permission = new CommandPermission(permission); - this.description = description; - this.alias = alias; - this.usage = usage; - this.category = category; - } + /** + * + * @param cmd + * Command /plot {cmd} <-- That! + * @param permission + * Permission Node + * @param description + * Simple description + * @param usage + * Usage description: /plot command {args...} + * @param alias + * Command alias + * @param category + * CommandCategory. Pick whichever closests to what you want. + */ + public SubCommand(String cmd, String permission, String description, + String usage, String alias, CommandCategory category) { + this.cmd = cmd; + this.permission = new CommandPermission(permission); + this.description = description; + this.alias = alias; + this.usage = usage; + this.category = category; + } - /** - * - * @param command - * Command /plot {cmd} <-- That! - * @param description - * Simple description - * @param usage - * Usage description: /plot command {args...} - * @param category - * CommandCategory. Pick whichever closests to what you want. - */ - public SubCommand(Command command, String description, String usage, CommandCategory category) { - this.cmd = command.getCommand(); - this.permission = command.getPermission(); - this.alias = command.getAlias(); - this.description = description; - this.usage = usage; - this.category = category; - } + /** + * + * @param command + * Command /plot {cmd} <-- That! + * @param description + * Simple description + * @param usage + * Usage description: /plot command {args...} + * @param category + * CommandCategory. Pick whichever closests to what you want. + */ + public SubCommand(Command command, String description, String usage, + CommandCategory category) { + this.cmd = command.getCommand(); + this.permission = command.getPermission(); + this.alias = command.getAlias(); + this.description = description; + this.usage = usage; + this.category = category; + } - /** - * Execute. - * - * @param plr - * executor - * @param args - * arguments - * @return true on success, false on failure - */ - public abstract boolean execute(Player plr, String... args); + /** + * Execute. + * + * @param plr + * executor + * @param args + * arguments + * @return true on success, false on failure + */ + public abstract boolean execute(Player plr, String... args); - public void executeConsole(String... args) { - this.execute(null, args); - } + public void executeConsole(String... args) { + this.execute(null, args); + } - /** - * Send a message - * - * @param plr - * @param c - * @param args - */ - public void sendMessage(Player plr, C c, String... args) { - PlayerFunctions.sendMessage(plr, c, args); - } + /** + * Send a message + * + * @param plr + * @param c + * @param args + */ + public void sendMessage(Player plr, C c, String... args) { + PlayerFunctions.sendMessage(plr, c, args); + } - public enum CommandCategory { - CLAIMING("Claiming"), TELEPORT("Teleportation"), ACTIONS("Actions"), INFO("Information"); - private String name; + public enum CommandCategory { + CLAIMING("Claiming"), TELEPORT("Teleportation"), ACTIONS("Actions"), INFO( + "Information"); + private String name; - CommandCategory(String name) { - this.name = name; - } + CommandCategory(String name) { + this.name = name; + } - @Override - public String toString() { - return this.name; - } - } + @Override + public String toString() { + return this.name; + } + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/commands/TP.java b/PlotSquared/src/com/intellectualcrafters/plot/commands/TP.java index e555f3096..0373a5e99 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/commands/TP.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/commands/TP.java @@ -22,71 +22,76 @@ import com.intellectualcrafters.plot.PlotId; import com.intellectualcrafters.plot.PlotMain; /** - * + * * @author Citymonstret - * + * */ public class TP extends SubCommand { - public TP() { - super(Command.TP, "Teleport to a plot", "tp {alias|id}", CommandCategory.TELEPORT); - } + public TP() { + super(Command.TP, "Teleport to a plot", "tp {alias|id}", + CommandCategory.TELEPORT); + } - @Override - public boolean execute(Player plr, String... args) { - if (args.length < 1) { - PlayerFunctions.sendMessage(plr, C.NEED_PLOT_ID); - return false; - } - String id = args[0]; - PlotId plotid; - World world = plr.getWorld(); - if (args.length == 2) { - if (Bukkit.getWorld(args[1]) != null) { - world = Bukkit.getWorld(args[1]); - } - } - if (!PlotMain.isPlotWorld(world)) { - PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD); - return false; - } - Plot temp; - if ((temp = isAlias(world, id)) != null) { - PlotMain.teleportPlayer(plr, plr.getLocation(), temp); - return true; - } - try { - plotid = new PlotId(Integer.parseInt(id.split(";")[0]), Integer.parseInt(id.split(";")[1])); - PlotMain.teleportPlayer(plr, plr.getLocation(), PlotHelper.getPlot(world, plotid)); - return true; - } catch (Exception e) { - PlayerFunctions.sendMessage(plr, C.NOT_VALID_PLOT_ID); - } - return false; - } + @Override + public boolean execute(Player plr, String... args) { + if (args.length < 1) { + PlayerFunctions.sendMessage(plr, C.NEED_PLOT_ID); + return false; + } + String id = args[0]; + PlotId plotid; + World world = plr.getWorld(); + if (args.length == 2) { + if (Bukkit.getWorld(args[1]) != null) { + world = Bukkit.getWorld(args[1]); + } + } + if (!PlotMain.isPlotWorld(world)) { + PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD); + return false; + } + Plot temp; + if ((temp = isAlias(world, id)) != null) { + PlotMain.teleportPlayer(plr, plr.getLocation(), temp); + return true; + } + try { + plotid = new PlotId(Integer.parseInt(id.split(";")[0]), + Integer.parseInt(id.split(";")[1])); + PlotMain.teleportPlayer(plr, plr.getLocation(), + PlotHelper.getPlot(world, plotid)); + return true; + } catch (Exception e) { + PlayerFunctions.sendMessage(plr, C.NOT_VALID_PLOT_ID); + } + return false; + } - private Plot isAlias(World world, String a) { - int index = 0; - if (a.contains(";")) { - String[] split = a.split(";"); - if ((split[1].length() > 0) && StringUtils.isNumeric(split[1])) { - index = Integer.parseInt(split[1]); - } - a = split[0]; - } - Player player = Bukkit.getPlayer(a); - if (player != null) { - Plot[] plots = PlotMain.getPlots(world, player).toArray(new Plot[0]); - if (plots.length > index) { - return plots[index]; - } - return null; - } - for (Plot p : PlotMain.getPlots(world).values()) { - if ((p.settings.getAlias().length() > 0) && p.settings.getAlias().equalsIgnoreCase(a)) { - return p; - } - } - return null; - } + private Plot isAlias(World world, String a) { + int index = 0; + if (a.contains(";")) { + String[] split = a.split(";"); + if ((split[1].length() > 0) && StringUtils.isNumeric(split[1])) { + index = Integer.parseInt(split[1]); + } + a = split[0]; + } + Player player = Bukkit.getPlayer(a); + if (player != null) { + Plot[] plots = PlotMain.getPlots(world, player) + .toArray(new Plot[0]); + if (plots.length > index) { + return plots[index]; + } + return null; + } + for (Plot p : PlotMain.getPlots(world).values()) { + if ((p.settings.getAlias().length() > 0) + && p.settings.getAlias().equalsIgnoreCase(a)) { + return p; + } + } + return null; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/commands/Trusted.java b/PlotSquared/src/com/intellectualcrafters/plot/commands/Trusted.java index 2271683c9..743f82eaf 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/commands/Trusted.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/commands/Trusted.java @@ -9,127 +9,103 @@ package com.intellectualcrafters.plot.commands; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + import com.intellectualcrafters.plot.C; import com.intellectualcrafters.plot.PlayerFunctions; import com.intellectualcrafters.plot.Plot; import com.intellectualcrafters.plot.UUIDHandler; import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.events.PlayerPlotTrustedEvent; -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.bukkit.entity.Player; - -import java.util.UUID; @SuppressWarnings("deprecation") public class Trusted extends SubCommand { - public Trusted() { - super(Command.TRUSTED, "Manage trusted users for a plot", "trusted {add|remove} {player}", CommandCategory.ACTIONS); - } + public Trusted() { + super(Command.TRUSTED, "Manage trusted users for a plot", + "trusted {add|remove} {player}", CommandCategory.ACTIONS); + } - private boolean hasBeenOnServer(String name) { - Player plr = Bukkit.getPlayer(name); - if (plr == null) { - OfflinePlayer oplr = Bukkit.getOfflinePlayer(name); - if (oplr == null) { - return false; - } else { - return oplr.hasPlayedBefore(); - } - } else { - if (plr.isOnline()) { - return true; - } else { - return plr.hasPlayedBefore(); - } - } - } - - @Override - public boolean execute(Player plr, String... args) { - if (args.length < 2) { - PlayerFunctions.sendMessage(plr, C.TRUSTED_NEED_ARGUMENT); - return true; - } - if (!PlayerFunctions.isInPlot(plr)) { - PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); - return true; - } - Plot plot = PlayerFunctions.getCurrentPlot(plr); - if ((plot.owner == null) || !plot.hasRights(plr)) { - PlayerFunctions.sendMessage(plr, C.NO_PERMISSION); - return true; - } - if (args[0].equalsIgnoreCase("add")) { - if (args[1].equalsIgnoreCase("*")) { - UUID uuid = DBFunc.everyone; - plot.addTrusted(uuid); - DBFunc.setTrusted(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); - PlayerFunctions.sendMessage(plr, C.TRUSTED_ADDED); - return true; - } - /*if (!hasBeenOnServer(args[1])) { - PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); - return true; - } - UUID uuid = null; - if ((Bukkit.getPlayer(args[1]) != null)) { - uuid = Bukkit.getPlayer(args[1]).getUniqueId(); - } else { - uuid = Bukkit.getOfflinePlayer(args[1]).getUniqueId(); - } - if (uuid == null) { - PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); - return true; - }*/ - UUID uuid = UUIDHandler.getUUID(args[1]); - plot.addTrusted(uuid); - DBFunc.setTrusted(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); - PlayerPlotTrustedEvent event = new PlayerPlotTrustedEvent(plr, plot, uuid, true); - Bukkit.getPluginManager().callEvent(event); - PlayerFunctions.sendMessage(plr, C.TRUSTED_ADDED); - } else if (args[0].equalsIgnoreCase("remove")) { - if (args[1].equalsIgnoreCase("*")) { - UUID uuid = DBFunc.everyone; - if (!plot.trusted.contains(uuid)) { - PlayerFunctions.sendMessage(plr, C.T_WAS_NOT_ADDED); - return true; - } - plot.removeTrusted(uuid); - DBFunc.removeTrusted(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); - PlayerFunctions.sendMessage(plr, C.TRUSTED_REMOVED); - return true; - } - /* - if (!hasBeenOnServer(args[1])) { - PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); - return true; - } - UUID uuid = null; - if (Bukkit.getPlayer(args[1]) != null) { - uuid = Bukkit.getPlayer(args[1]).getUniqueId(); - } else { - uuid = Bukkit.getOfflinePlayer(args[1]).getUniqueId(); - } - if (uuid == null) { - PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); - return true; - } - if (!plot.trusted.contains(uuid)) { - PlayerFunctions.sendMessage(plr, C.T_WAS_NOT_ADDED); - return true; - }*/ - UUID uuid = UUIDHandler.getUUID(args[1]); - plot.removeTrusted(uuid); - DBFunc.removeTrusted(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); - PlayerPlotTrustedEvent event = new PlayerPlotTrustedEvent(plr, plot, uuid, false); - Bukkit.getPluginManager().callEvent(event); - PlayerFunctions.sendMessage(plr, C.TRUSTED_REMOVED); - } else { - PlayerFunctions.sendMessage(plr, C.TRUSTED_NEED_ARGUMENT); - return true; - } - return true; - } + @Override + public boolean execute(Player plr, String... args) { + if (args.length < 2) { + PlayerFunctions.sendMessage(plr, C.TRUSTED_NEED_ARGUMENT); + return true; + } + if (!PlayerFunctions.isInPlot(plr)) { + PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); + return true; + } + Plot plot = PlayerFunctions.getCurrentPlot(plr); + if ((plot.owner == null) || !plot.hasRights(plr)) { + PlayerFunctions.sendMessage(plr, C.NO_PERMISSION); + return true; + } + if (args[0].equalsIgnoreCase("add")) { + if (args[1].equalsIgnoreCase("*")) { + UUID uuid = DBFunc.everyone; + plot.addTrusted(uuid); + DBFunc.setTrusted(plr.getWorld().getName(), plot, + Bukkit.getOfflinePlayer(args[1])); + PlayerFunctions.sendMessage(plr, C.TRUSTED_ADDED); + return true; + } + /* + * if (!hasBeenOnServer(args[1])) { PlayerFunctions.sendMessage(plr, + * C.PLAYER_HAS_NOT_BEEN_ON); return true; } UUID uuid = null; if + * ((Bukkit.getPlayer(args[1]) != null)) { uuid = + * Bukkit.getPlayer(args[1]).getUniqueId(); } else { uuid = + * Bukkit.getOfflinePlayer(args[1]).getUniqueId(); } if (uuid == + * null) { PlayerFunctions.sendMessage(plr, + * C.PLAYER_HAS_NOT_BEEN_ON); return true; } + */ + UUID uuid = UUIDHandler.getUUID(args[1]); + plot.addTrusted(uuid); + DBFunc.setTrusted(plr.getWorld().getName(), plot, + Bukkit.getOfflinePlayer(args[1])); + PlayerPlotTrustedEvent event = new PlayerPlotTrustedEvent(plr, + plot, uuid, true); + Bukkit.getPluginManager().callEvent(event); + PlayerFunctions.sendMessage(plr, C.TRUSTED_ADDED); + } else if (args[0].equalsIgnoreCase("remove")) { + if (args[1].equalsIgnoreCase("*")) { + UUID uuid = DBFunc.everyone; + if (!plot.trusted.contains(uuid)) { + PlayerFunctions.sendMessage(plr, C.T_WAS_NOT_ADDED); + return true; + } + plot.removeTrusted(uuid); + DBFunc.removeTrusted(plr.getWorld().getName(), plot, + Bukkit.getOfflinePlayer(args[1])); + PlayerFunctions.sendMessage(plr, C.TRUSTED_REMOVED); + return true; + } + /* + * if (!hasBeenOnServer(args[1])) { PlayerFunctions.sendMessage(plr, + * C.PLAYER_HAS_NOT_BEEN_ON); return true; } UUID uuid = null; if + * (Bukkit.getPlayer(args[1]) != null) { uuid = + * Bukkit.getPlayer(args[1]).getUniqueId(); } else { uuid = + * Bukkit.getOfflinePlayer(args[1]).getUniqueId(); } if (uuid == + * null) { PlayerFunctions.sendMessage(plr, + * C.PLAYER_HAS_NOT_BEEN_ON); return true; } if + * (!plot.trusted.contains(uuid)) { PlayerFunctions.sendMessage(plr, + * C.T_WAS_NOT_ADDED); return true; } + */ + UUID uuid = UUIDHandler.getUUID(args[1]); + plot.removeTrusted(uuid); + DBFunc.removeTrusted(plr.getWorld().getName(), plot, + Bukkit.getOfflinePlayer(args[1])); + PlayerPlotTrustedEvent event = new PlayerPlotTrustedEvent(plr, + plot, uuid, false); + Bukkit.getPluginManager().callEvent(event); + PlayerFunctions.sendMessage(plr, C.TRUSTED_REMOVED); + } else { + PlayerFunctions.sendMessage(plr, C.TRUSTED_NEED_ARGUMENT); + return true; + } + return true; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/commands/Unlink.java b/PlotSquared/src/com/intellectualcrafters/plot/commands/Unlink.java index 047d7eac3..9be96adf7 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/commands/Unlink.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/commands/Unlink.java @@ -12,16 +12,15 @@ package com.intellectualcrafters.plot.commands; import java.util.ArrayList; import org.bukkit.Bukkit; -import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; import com.intellectualcrafters.plot.C; import com.intellectualcrafters.plot.PlayerFunctions; import com.intellectualcrafters.plot.Plot; -import com.intellectualcrafters.plot.PlotHelper; import com.intellectualcrafters.plot.PlotId; import com.intellectualcrafters.plot.PlotMain; +import com.intellectualcrafters.plot.PlotManager; import com.intellectualcrafters.plot.PlotWorld; import com.intellectualcrafters.plot.SetBlockFast; import com.intellectualcrafters.plot.database.DBFunc; @@ -32,186 +31,91 @@ import com.intellectualcrafters.plot.events.PlotUnlinkEvent; */ public class Unlink extends SubCommand { - private short w_id; - private byte w_v; - private short wf_id; - private byte wf_v; - private short f1_id; - private byte f1_v; - private int pathsize; - private int wallheight; - private int roadheight; + public Unlink() { + super(Command.UNLINK, "Unlink a mega-plot", "unlink", + CommandCategory.ACTIONS); + } - public Unlink() { - super(Command.UNLINK, "Unlink a mega-plot", "unlink", CommandCategory.ACTIONS); - } + @Override + public boolean execute(Player plr, String... args) { + if (!PlayerFunctions.isInPlot(plr)) { + PlayerFunctions.sendMessage(plr, "You're not in a plot."); + return true; + } + Plot plot = PlayerFunctions.getCurrentPlot(plr); + if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals( + plr.getUniqueId())) + && !plr.hasPermission("plots.admin")) { + PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); + return true; + } + if (PlayerFunctions.getTopPlot(plr.getWorld(), plot).equals( + PlayerFunctions.getBottomPlot(plr.getWorld(), plot))) { + PlayerFunctions.sendMessage(plr, C.UNLINK_IMPOSSIBLE); + return true; + } + World world = plr.getWorld(); + PlotId pos1 = PlayerFunctions.getBottomPlot(world, plot).id; + PlotId pos2 = PlayerFunctions.getTopPlot(world, plot).id; + ArrayList ids = PlayerFunctions.getPlotSelectionIds(world, + pos1, pos2); - @Override - public boolean execute(Player plr, String... args) { - if (!PlayerFunctions.isInPlot(plr)) { - PlayerFunctions.sendMessage(plr, "You're not in a plot."); - return true; - } - Plot plot = PlayerFunctions.getCurrentPlot(plr); - if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId())) && !plr.hasPermission("plots.admin")) { - PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); - return true; - } - if (PlayerFunctions.getTopPlot(plr.getWorld(), plot).equals(PlayerFunctions.getBottomPlot(plr.getWorld(), plot))) { - PlayerFunctions.sendMessage(plr, C.UNLINK_IMPOSSIBLE); - return true; - } - World world = plr.getWorld(); - PlotId pos1 = PlayerFunctions.getBottomPlot(world, plot).id; - PlotId pos2 = PlayerFunctions.getTopPlot(world, plot).id; - ArrayList ids = PlayerFunctions.getPlotSelectionIds(world, pos1, pos2); + PlotUnlinkEvent event = new PlotUnlinkEvent(world, ids); - PlotUnlinkEvent event = new PlotUnlinkEvent(world, ids); + Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + event.setCancelled(true); + PlayerFunctions.sendMessage(plr, "&cUnlink has been cancelled"); + return false; + } - Bukkit.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) { - event.setCancelled(true); - PlayerFunctions.sendMessage(plr, "&cUnlink has been cancelled"); - return false; - } + for (PlotId id : ids) { + Plot myplot = PlotMain.getPlots(world).get(id); - for (PlotId id : ids) { - Plot myplot = PlotMain.getPlots(world).get(id); + if (plot.helpers != null) { + myplot.helpers = plot.helpers; + } + if (plot.denied != null) { + myplot.denied = plot.denied; + } + myplot.deny_entry = plot.deny_entry; + myplot.settings.setMerged(new boolean[] { false, false, false, + false }); + DBFunc.setMerged(world.getName(), myplot, + myplot.settings.getMerged()); + } + PlotManager manager = PlotMain.getPlotManager(world); + PlotWorld plotworld = PlotMain.getWorldSettings(world); + for (int x = pos1.x; x <= pos2.x; x++) { + for (int y = pos1.y; y <= pos2.y; y++) { + boolean lx = x < pos2.x; + boolean ly = y < pos2.y; - if (plot.helpers != null) { - myplot.helpers = plot.helpers; - } - if (plot.denied != null) { - myplot.denied = plot.denied; - } - myplot.deny_entry = plot.deny_entry; - myplot.settings.setMerged(new boolean[] { false, false, false, false }); - DBFunc.setMerged(world.getName(), myplot, myplot.settings.getMerged()); - } + new PlotId(x, y); - PlotWorld plotworld = PlotMain.getWorldSettings(world); - this.pathsize = plotworld.ROAD_WIDTH; - this.roadheight = plotworld.ROAD_HEIGHT; - this.wallheight = plotworld.WALL_HEIGHT; - // WALL - short[] result_w = PlotHelper.getBlock(plotworld.WALL_BLOCK); - this.w_id = result_w[0]; - this.w_v = (byte) result_w[1]; + if (lx) { + manager.removeRoadEast(plotworld, plot); - // WALL FILLING - short[] result_wf = PlotHelper.getBlock(plotworld.WALL_FILLING); - this.wf_id = result_wf[0]; - this.wf_v = (byte) result_wf[1]; + if (ly) { + manager.removeRoadSouthEast(plotworld, plot); + } - // ROAD - short[] result_f1 = PlotHelper.getBlock(plotworld.ROAD_BLOCK); - this.f1_id = result_f1[0]; - this.f1_v = (byte) result_f1[1]; - // + } - PlotHelper.getBlock(plotworld.ROAD_STRIPES); - for (int x = pos1.x; x <= pos2.x; x++) { - for (int y = pos1.y; y <= pos2.y; y++) { - boolean lx = x < pos2.x; - boolean ly = y < pos2.y; + if (ly) { + manager.removeRoadSouth(plotworld, plot); + } - PlotId id = new PlotId(x, y); + } + } - if (lx) { - setRoadX(world, id); + try { + SetBlockFast.update(plr); + } catch (Exception e) { - if (ly) { - setRoadXY(world, id); - } + } - } - - if (ly) { - setRoadY(world, id); - } - - } - } - - try { - SetBlockFast.update(plr); - } catch (Exception e) { - - } - - PlayerFunctions.sendMessage(plr, "&6Plots unlinked successfully!"); - return true; - } - - /** - * Setting the road with the greatest X value - * - * @param world - * @param id - */ - public void setRoadX(World w, PlotId id) { - Location pos1 = PlotHelper.getPlotBottomLocAbs(w, id); - Location pos2 = PlotHelper.getPlotTopLocAbs(w, id); - - int sx = pos2.getBlockX(); - int ex = (sx + this.pathsize); - int sz = pos1.getBlockZ() - 1; - int ez = pos2.getBlockZ() + 2; - - PlotHelper.setSimpleCuboid(w, new Location(w, sx, Math.min(this.wallheight, this.roadheight) + 1, sz + 1), new Location(w, ex + 1, 257 + 1, ez), (short) 0); - - PlotHelper.setCuboid(w, new Location(w, sx, 1, sz + 1), new Location(w, sx + 1, this.wallheight + 1, ez), new short[] { this.wf_id }, new short[] { this.wf_v }); - PlotHelper.setCuboid(w, new Location(w, sx, this.wallheight + 1, sz + 1), new Location(w, sx + 1, this.wallheight + 2, ez), new short[] { this.w_id }, new short[] { this.w_v }); - - PlotHelper.setCuboid(w, new Location(w, ex, 1, sz + 1), new Location(w, ex + 1, this.wallheight + 1, ez), new short[] { this.wf_id }, new short[] { this.wf_v }); - PlotHelper.setCuboid(w, new Location(w, ex, this.wallheight + 1, sz + 1), new Location(w, ex + 1, this.wallheight + 2, ez), new short[] { this.w_id }, new short[] { this.w_v }); - - PlotHelper.setCuboid(w, new Location(w, sx + 1, 1, sz + 1), new Location(w, ex, this.roadheight + 1, ez), new short[] { this.f1_id }, new short[] { this.f1_v }); - } - - /** - * Setting the road with the greatest Y value - * - * @param world - * @param id - */ - - public void setRoadY(World w, PlotId id) { - Location pos1 = PlotHelper.getPlotBottomLocAbs(w, id); - Location pos2 = PlotHelper.getPlotTopLocAbs(w, id); - - int sz = pos2.getBlockZ(); - int ez = (sz + this.pathsize); - int sx = pos1.getBlockX() - 1; - int ex = pos2.getBlockX() + 2; - - PlotHelper.setSimpleCuboid(w, new Location(w, sx, Math.min(this.wallheight, this.roadheight) + 1, sz + 1), new Location(w, ex + 1, 257 + 1, ez), (short) 0); - - PlotHelper.setCuboid(w, new Location(w, sx + 1, 1, sz), new Location(w, ex, this.wallheight + 1, sz + 1), new short[] { this.wf_id }, new short[] { this.wf_v }); - PlotHelper.setCuboid(w, new Location(w, sx + 1, this.wallheight + 1, sz), new Location(w, ex, this.wallheight + 2, sz + 1), new short[] { this.w_id }, new short[] { this.w_v }); - - PlotHelper.setCuboid(w, new Location(w, sx + 1, 1, ez), new Location(w, ex, this.wallheight + 1, ez + 1), new short[] { this.wf_id }, new short[] { this.wf_v }); - PlotHelper.setCuboid(w, new Location(w, sx + 1, this.wallheight + 1, ez), new Location(w, ex, this.wallheight + 2, ez + 1), new short[] { this.w_id }, new short[] { this.w_v }); - - PlotHelper.setCuboid(w, new Location(w, sx + 1, 1, sz + 1), new Location(w, ex, this.roadheight + 1, ez), new short[] { this.f1_id }, new short[] { this.f1_v }); - } - - /** - * Setting the intersection with the greatest X and Y value - * - * @param world - * @param id - */ - public void setRoadXY(World w, PlotId id) { - Location pos2 = PlotHelper.getPlotTopLocAbs(w, id); - - int sx = pos2.getBlockX() + 1; - int ex = (sx + this.pathsize) - 1; - int sz = pos2.getBlockZ() + 1; - int ez = (sz + this.pathsize) - 1; - - PlotHelper.setSimpleCuboid(w, new Location(w, sx, this.roadheight + 1, sz + 1), new Location(w, ex + 1, 257 + 1, ez), (short) 0); - - PlotHelper.setCuboid(w, new Location(w, sx + 1, 1, sz + 1), new Location(w, ex, this.roadheight + 1, ez), new short[] { this.f1_id }, new short[] { this.f1_v }); - } + PlayerFunctions.sendMessage(plr, "&6Plots unlinked successfully!"); + return true; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/commands/Visit.java b/PlotSquared/src/com/intellectualcrafters/plot/commands/Visit.java index 949280841..7ac0fabf5 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/commands/Visit.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/commands/Visit.java @@ -22,51 +22,53 @@ import com.intellectualcrafters.plot.Plot; import com.intellectualcrafters.plot.PlotMain; public class Visit extends SubCommand { - public Visit() { - super("visit", "plots.visit", "Visit someones plot", "visit {player} [#]", "v", CommandCategory.TELEPORT); - } + public Visit() { + super("visit", "plots.visit", "Visit someones plot", + "visit {player} [#]", "v", CommandCategory.TELEPORT); + } - public List getPlots(UUID uuid) { - List plots = new ArrayList<>(); - for (Plot p : PlotMain.getPlots()) { - if (p.owner.equals(uuid)) { - plots.add(p); - } - } - return plots; - } + public List getPlots(UUID uuid) { + List plots = new ArrayList<>(); + for (Plot p : PlotMain.getPlots()) { + if (p.owner.equals(uuid)) { + plots.add(p); + } + } + return plots; + } - @SuppressWarnings("deprecation") - @Override - public boolean execute(Player plr, String... args) { - if (args.length < 1) { - PlayerFunctions.sendMessage(plr, C.NEED_USER); - return true; - } - String username = args[0]; - List plots = getPlots(Bukkit.getOfflinePlayer(username).getUniqueId()); - if (plots.isEmpty()) { - PlayerFunctions.sendMessage(plr, C.FOUND_NO_PLOTS); - return true; - } - if (args.length < 2) { - Plot plot = plots.get(0); - PlotMain.teleportPlayer(plr, plr.getLocation(), plot); - return true; - } - int i; - try { - i = Integer.parseInt(args[1]); - } catch (Exception e) { - PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER); - return true; - } - if ((i < 0) || (i > plots.size())) { - PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER); - return true; - } - Plot plot = plots.get(i); - PlotMain.teleportPlayer(plr, plr.getLocation(), plot); - return true; - } + @SuppressWarnings("deprecation") + @Override + public boolean execute(Player plr, String... args) { + if (args.length < 1) { + PlayerFunctions.sendMessage(plr, C.NEED_USER); + return true; + } + String username = args[0]; + List plots = getPlots(Bukkit.getOfflinePlayer(username) + .getUniqueId()); + if (plots.isEmpty()) { + PlayerFunctions.sendMessage(plr, C.FOUND_NO_PLOTS); + return true; + } + if (args.length < 2) { + Plot plot = plots.get(0); + PlotMain.teleportPlayer(plr, plr.getLocation(), plot); + return true; + } + int i; + try { + i = Integer.parseInt(args[1]); + } catch (Exception e) { + PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER); + return true; + } + if ((i < 0) || (i > plots.size())) { + PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER); + return true; + } + Plot plot = plots.get(i); + PlotMain.teleportPlayer(plr, plr.getLocation(), plot); + return true; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/commands/list.java b/PlotSquared/src/com/intellectualcrafters/plot/commands/list.java index b91c90154..0e1921bbe 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/commands/list.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/commands/list.java @@ -9,106 +9,156 @@ package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.*; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; - import java.util.HashMap; import java.util.UUID; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +import com.intellectualcrafters.plot.C; +import com.intellectualcrafters.plot.PlayerFunctions; +import com.intellectualcrafters.plot.Plot; +import com.intellectualcrafters.plot.PlotId; +import com.intellectualcrafters.plot.PlotMain; +import com.intellectualcrafters.plot.UUIDHandler; + /** - * + * * @author Citymonstret - * + * */ public class list extends SubCommand { - public list() { - super(Command.LIST, "List all plots", "list {mine|all|world}", CommandCategory.INFO); - } + public list() { + super(Command.LIST, "List all plots", "list {mine|all|world}", + CommandCategory.INFO); + } - @Override - public boolean execute(Player plr, String... args) { - if (args.length < 1) { - StringBuilder builder = new StringBuilder(); - builder.append(C.SUBCOMMAND_SET_OPTIONS_HEADER.s()); - builder.append(getArgumentList(new String[] { "mine", "shared", "world", "all" })); - PlayerFunctions.sendMessage(plr, builder.toString()); - return true; - } - if (args[0].equalsIgnoreCase("mine")) { - StringBuilder string = new StringBuilder(); - string.append(C.PLOT_LIST_HEADER.s().replaceAll("%word%", "your") + "\n"); - int idx = 0; - for (Plot p : PlotMain.getPlots(plr)) { - string.append(C.PLOT_LIST_ITEM.s().replaceAll("%id%", p.id.x + ";" + p.id.y + ";" + p.world).replaceAll("%owner%", getName(p.owner)) + "\n"); - idx++; - } - if (idx == 0) { - PlayerFunctions.sendMessage(plr, C.NO_PLOTS); - return true; - } - string.append(C.PLOT_LIST_FOOTER.s().replaceAll("%word%", "You have").replaceAll("%num%", idx + "").replaceAll("%plot%", idx == 1 ? "plot" : "plots")); - PlayerFunctions.sendMessage(plr, string.toString()); - return true; - } else if (args[0].equalsIgnoreCase("shared")) { - StringBuilder string = new StringBuilder(); - string.append(C.PLOT_LIST_HEADER.s().replaceAll("%word%", "all") + "\n"); - for (Plot p : PlotMain.getPlots()) { - if (p.helpers.contains(plr.getUniqueId())) { - string.append(C.PLOT_LIST_ITEM.s().replaceAll("%id%", p.id.x + ";" + p.id.y + ";" + p.world).replaceAll("%owner%", getName(p.owner)) + "\n"); - } - } - string.append(C.PLOT_LIST_FOOTER.s().replaceAll("%word%", "There is").replaceAll("%num%", PlotMain.getPlots().size() + "").replaceAll("%plot%", PlotMain.getPlots().size() == 1 ? "plot" : "plots")); - PlayerFunctions.sendMessage(plr, string.toString()); - return true; - } else if (args[0].equalsIgnoreCase("all")) { - StringBuilder string = new StringBuilder(); - string.append(C.PLOT_LIST_HEADER.s().replaceAll("%word%", "all") + "\n"); - for (Plot p : PlotMain.getPlots()) { - string.append(C.PLOT_LIST_ITEM.s().replaceAll("%id%", p.id.x + ";" + p.id.y + ";" + p.world).replaceAll("%owner%", getName(p.owner)) + "\n"); - } - string.append(C.PLOT_LIST_FOOTER.s().replaceAll("%word%", "There is").replaceAll("%num%", PlotMain.getPlots().size() + "").replaceAll("%plot%", PlotMain.getPlots().size() == 1 ? "plot" : "plots")); - PlayerFunctions.sendMessage(plr, string.toString()); - return true; - } else if (args[0].equalsIgnoreCase("world")) { - StringBuilder string = new StringBuilder(); - string.append(C.PLOT_LIST_HEADER.s().replaceAll("%word%", "all") + "\n"); - HashMap plots = PlotMain.getPlots(plr.getWorld()); - for (Plot p : plots.values()) { - string.append(C.PLOT_LIST_ITEM.s().replaceAll("%id%", p.id.x + ";" + p.id.y + ";" + p.world).replaceAll("%owner%", getName(p.owner)) + "\n"); - } - string.append(C.PLOT_LIST_FOOTER.s().replaceAll("%word%", "There is").replaceAll("%num%", plots.values().size() + "").replaceAll("%plot%", plots.values().size() == 1 ? "plot" : "plots")); - PlayerFunctions.sendMessage(plr, string.toString()); - return true; - } else { - execute(plr); - return false; - } - } + @Override + public boolean execute(Player plr, String... args) { + if (args.length < 1) { + StringBuilder builder = new StringBuilder(); + builder.append(C.SUBCOMMAND_SET_OPTIONS_HEADER.s()); + builder.append(getArgumentList(new String[] { "mine", "shared", + "world", "all" })); + PlayerFunctions.sendMessage(plr, builder.toString()); + return true; + } + if (args[0].equalsIgnoreCase("mine")) { + StringBuilder string = new StringBuilder(); + string.append(C.PLOT_LIST_HEADER.s().replaceAll("%word%", "your") + + "\n"); + int idx = 0; + for (Plot p : PlotMain.getPlots(plr)) { + string.append(C.PLOT_LIST_ITEM + .s() + .replaceAll("%id%", + p.id.x + ";" + p.id.y + ";" + p.world) + .replaceAll("%owner%", getName(p.owner)) + + "\n"); + idx++; + } + if (idx == 0) { + PlayerFunctions.sendMessage(plr, C.NO_PLOTS); + return true; + } + string.append(C.PLOT_LIST_FOOTER.s() + .replaceAll("%word%", "You have") + .replaceAll("%num%", idx + "") + .replaceAll("%plot%", idx == 1 ? "plot" : "plots")); + PlayerFunctions.sendMessage(plr, string.toString()); + return true; + } else if (args[0].equalsIgnoreCase("shared")) { + StringBuilder string = new StringBuilder(); + string.append(C.PLOT_LIST_HEADER.s().replaceAll("%word%", "all") + + "\n"); + for (Plot p : PlotMain.getPlots()) { + if (p.helpers.contains(plr.getUniqueId())) { + string.append(C.PLOT_LIST_ITEM + .s() + .replaceAll("%id%", + p.id.x + ";" + p.id.y + ";" + p.world) + .replaceAll("%owner%", getName(p.owner)) + + "\n"); + } + } + string.append(C.PLOT_LIST_FOOTER + .s() + .replaceAll("%word%", "There is") + .replaceAll("%num%", PlotMain.getPlots().size() + "") + .replaceAll("%plot%", + PlotMain.getPlots().size() == 1 ? "plot" : "plots")); + PlayerFunctions.sendMessage(plr, string.toString()); + return true; + } else if (args[0].equalsIgnoreCase("all")) { + StringBuilder string = new StringBuilder(); + string.append(C.PLOT_LIST_HEADER.s().replaceAll("%word%", "all") + + "\n"); + for (Plot p : PlotMain.getPlots()) { + string.append(C.PLOT_LIST_ITEM + .s() + .replaceAll("%id%", + p.id.x + ";" + p.id.y + ";" + p.world) + .replaceAll("%owner%", getName(p.owner)) + + "\n"); + } + string.append(C.PLOT_LIST_FOOTER + .s() + .replaceAll("%word%", "There is") + .replaceAll("%num%", PlotMain.getPlots().size() + "") + .replaceAll("%plot%", + PlotMain.getPlots().size() == 1 ? "plot" : "plots")); + PlayerFunctions.sendMessage(plr, string.toString()); + return true; + } else if (args[0].equalsIgnoreCase("world")) { + StringBuilder string = new StringBuilder(); + string.append(C.PLOT_LIST_HEADER.s().replaceAll("%word%", "all") + + "\n"); + HashMap plots = PlotMain.getPlots(plr.getWorld()); + for (Plot p : plots.values()) { + string.append(C.PLOT_LIST_ITEM + .s() + .replaceAll("%id%", + p.id.x + ";" + p.id.y + ";" + p.world) + .replaceAll("%owner%", getName(p.owner)) + + "\n"); + } + string.append(C.PLOT_LIST_FOOTER + .s() + .replaceAll("%word%", "There is") + .replaceAll("%num%", plots.values().size() + "") + .replaceAll("%plot%", + plots.values().size() == 1 ? "plot" : "plots")); + PlayerFunctions.sendMessage(plr, string.toString()); + return true; + } else { + execute(plr); + return false; + } + } - private static String getName(UUID id) { - if (id == null) { - return "none"; - } - /*String name = Bukkit.getOfflinePlayer(id).getName(); - if (name == null) { - return "none"; - } - return name;*/ - return UUIDHandler.getName(id); - } + private static String getName(UUID id) { + if (id == null) { + return "none"; + } + /* + * String name = Bukkit.getOfflinePlayer(id).getName(); if (name == + * null) { return "none"; } return name; + */ + return UUIDHandler.getName(id); + } - private String getArgumentList(String[] strings) { - StringBuilder builder = new StringBuilder(); - for (String s : strings) { - builder.append(getString(s)); - } - return builder.toString().substring(1, builder.toString().length() - 1); - } + private String getArgumentList(String[] strings) { + StringBuilder builder = new StringBuilder(); + for (String s : strings) { + builder.append(getString(s)); + } + return builder.toString().substring(1, builder.toString().length() - 1); + } - private String getString(String s) { - return ChatColor.translateAlternateColorCodes('&', C.BLOCK_LIST_ITEM.s().replaceAll("%mat%", s)); - } + private String getString(String s) { + return ChatColor.translateAlternateColorCodes('&', C.BLOCK_LIST_ITEM + .s().replaceAll("%mat%", s)); + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/commands/plugin.java b/PlotSquared/src/com/intellectualcrafters/plot/commands/plugin.java index 00ca7ff68..dfa0c7f9d 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/commands/plugin.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/commands/plugin.java @@ -9,69 +9,80 @@ package com.intellectualcrafters.plot.commands; -import com.intellectualcrafters.plot.PlayerFunctions; -import com.intellectualcrafters.plot.PlotMain; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.plugin.java.JavaPlugin; - import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; + +import com.intellectualcrafters.plot.PlayerFunctions; +import com.intellectualcrafters.plot.PlotMain; + public class plugin extends SubCommand { - public plugin() { - super("plugin", "plots.use", "Show plugin information", "plugin", "pl", CommandCategory.INFO); - } + public plugin() { + super("plugin", "plots.use", "Show plugin information", "plugin", "pl", + CommandCategory.INFO); + } - @Override - public boolean execute(final Player plr, String... args) { - Bukkit.getScheduler().runTaskAsynchronously(JavaPlugin.getPlugin(PlotMain.class), new Runnable() { - @Override - public void run() { - ArrayList strings = new ArrayList() { - { - String - downloads = getInfo("https://intellectualsites.com/spigot_api.php?method=downloads&url=http://www.spigotmc.org/resources/plotsquared.1177/"), - version = getInfo("https://intellectualsites.com/spigot_api.php?method=version&resource=1177"); - add(String.format("&c>> &6PlotSquared (Version: %s)", PlotMain.getMain().getDescription().getVersion())); - add(String.format("&c>> &6Made by Citymonstret and Empire92")); - add(String.format("&c>> &6Download at &lhttp://i-s.link/ps")); - add(String.format("&c>> &cNewest Version (Spigot): %s", version)); - add(String.format("&c>> &cTotal Downloads (Spigot): %s", downloads)); - } - }; - for (String s : strings) { - PlayerFunctions.sendMessage(plr, s); - } - } - }); - return true; - } + @Override + public boolean execute(final Player plr, String... args) { + Bukkit.getScheduler().runTaskAsynchronously( + JavaPlugin.getPlugin(PlotMain.class), new Runnable() { + @Override + public void run() { + ArrayList strings = new ArrayList() { + { + String downloads = getInfo("https://intellectualsites.com/spigot_api.php?method=downloads&url=http://www.spigotmc.org/resources/plotsquared.1177/"), version = getInfo("https://intellectualsites.com/spigot_api.php?method=version&resource=1177"); + add(String.format( + "&c>> &6PlotSquared (Version: %s)", + PlotMain.getMain().getDescription() + .getVersion())); + add(String + .format("&c>> &6Made by Citymonstret and Empire92")); + add(String + .format("&c>> &6Download at &lhttp://i-s.link/ps")); + add(String.format( + "&c>> &cNewest Version (Spigot): %s", + version)); + add(String.format( + "&c>> &cTotal Downloads (Spigot): %s", + downloads)); + } + }; + for (String s : strings) { + PlayerFunctions.sendMessage(plr, s); + } + } + }); + return true; + } - /** - * - * @param link - * @return - */ - private String getInfo(String link) { - try { - URLConnection connection = new URL(link).openConnection(); - connection.addRequestProperty("User-Agent", "Mozilla/4.0"); - BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); - String document = "", line; - while ((line = reader.readLine()) != null) { - document += (line + "\n"); - } - reader.close(); - return document; - } catch(Exception e) { - e.printStackTrace(); - return ""; - } - } + /** + * + * @param link + * @return + */ + private String getInfo(String link) { + try { + URLConnection connection = new URL(link).openConnection(); + connection.addRequestProperty("User-Agent", "Mozilla/4.0"); + BufferedReader reader = new BufferedReader(new InputStreamReader( + connection.getInputStream())); + String document = "", line; + while ((line = reader.readLine()) != null) { + document += (line + "\n"); + } + reader.close(); + return document; + } catch (Exception e) { + e.printStackTrace(); + return ""; + } + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/database/DBFunc.java b/PlotSquared/src/com/intellectualcrafters/plot/database/DBFunc.java index 7ce481684..f84691267 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/database/DBFunc.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/database/DBFunc.java @@ -24,7 +24,6 @@ import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; -import org.bukkit.World; import org.bukkit.block.Biome; import com.intellectualcrafters.plot.Flag; @@ -41,835 +40,976 @@ import com.intellectualcrafters.plot.PlotMain; */ public class DBFunc { - // TODO MongoDB @Brandon + // TODO MongoDB @Brandon - /** - * Set Plot owner - * - * @param plot - * @param uuid - */ - public static void setOwner(final Plot plot, final UUID uuid) { - runTask(new Runnable() { - @Override - public void run() { - try { - PreparedStatement statement = connection.prepareStatement("UPDATE `plot` SET `owner` = ? WHERE `plot_id_x` = ? AND `plot_id_z` = ? "); - statement.setString(1, uuid.toString()); - statement.setInt(2, plot.id.x); - statement.setInt(3, plot.id.y); - statement.executeUpdate(); - statement.close(); - } catch (SQLException e) { - e.printStackTrace(); - Logger.add(LogLevel.DANGER, "Could not set owner for plot " + plot.id); - } - } - }); - } + /** + * Set Plot owner + * + * @param plot + * @param uuid + */ + public static void setOwner(final Plot plot, final UUID uuid) { + runTask(new Runnable() { + @Override + public void run() { + try { + PreparedStatement statement = connection + .prepareStatement("UPDATE `plot` SET `owner` = ? WHERE `plot_id_x` = ? AND `plot_id_z` = ? "); + statement.setString(1, uuid.toString()); + statement.setInt(2, plot.id.x); + statement.setInt(3, plot.id.y); + statement.executeUpdate(); + statement.close(); + } catch (SQLException e) { + e.printStackTrace(); + Logger.add(LogLevel.DANGER, "Could not set owner for plot " + + plot.id); + } + } + }); + } - public static void createAllSettingsAndHelpers(ArrayList plots) { - HashMap> stored = new HashMap>(); - HashMap> helpers = new HashMap>(); - try { - PreparedStatement stmt = connection.prepareStatement("SELECT `id`, `plot_id_x`, `plot_id_z`, `world` FROM `plot`"); - ResultSet result = stmt.executeQuery(); - while (result.next()) { - int id = result.getInt("id"); - int idx = result.getInt("plot_id_x"); - int idz = result.getInt("plot_id_z"); - String world = result.getString("world"); + public static void createAllSettingsAndHelpers(ArrayList plots) { + HashMap> stored = new HashMap>(); + HashMap> helpers = new HashMap>(); + try { + PreparedStatement stmt = connection + .prepareStatement("SELECT `id`, `plot_id_x`, `plot_id_z`, `world` FROM `plot`"); + ResultSet result = stmt.executeQuery(); + while (result.next()) { + int id = result.getInt("id"); + int idx = result.getInt("plot_id_x"); + int idz = result.getInt("plot_id_z"); + String world = result.getString("world"); - if (!stored.containsKey(world)) { - stored.put(world, new HashMap()); - } - stored.get(world).put(new PlotId(idx, idz), id); - } - } catch (SQLException e) { - e.printStackTrace(); - } + if (!stored.containsKey(world)) { + stored.put(world, new HashMap()); + } + stored.get(world).put(new PlotId(idx, idz), id); + } + } catch (SQLException e) { + e.printStackTrace(); + } - for (Plot plot : plots) { - String world = Bukkit.getWorld(plot.world).getName(); - if (stored.containsKey(world)) { - Integer id = stored.get(world).get(plot.id); - if (id != null) { - helpers.put(id, plot.helpers); - } - } - } + for (Plot plot : plots) { + String world = Bukkit.getWorld(plot.world).getName(); + if (stored.containsKey(world)) { + Integer id = stored.get(world).get(plot.id); + if (id != null) { + helpers.put(id, plot.helpers); + } + } + } - if (helpers.size() == 0) { - return; - } + if (helpers.size() == 0) { + return; + } - // add plot settings - Integer[] ids = helpers.keySet().toArray(new Integer[0]); - StringBuilder statement = new StringBuilder("INSERT INTO `plot_settings` (`plot_plot_id`) values "); - for (int i = 0; i < (ids.length - 1); i++) { - statement.append("(?),"); - } - statement.append("(?)"); - PreparedStatement stmt = null; - try { - stmt = connection.prepareStatement(statement.toString()); - for (int i = 0; i < ids.length; i++) { - stmt.setInt(i + 1, ids[i]); - } - stmt.executeUpdate(); - stmt.close(); - } catch (SQLException e) { - e.printStackTrace(); - } + // add plot settings + Integer[] ids = helpers.keySet().toArray(new Integer[0]); + StringBuilder statement = new StringBuilder( + "INSERT INTO `plot_settings` (`plot_plot_id`) values "); + for (int i = 0; i < (ids.length - 1); i++) { + statement.append("(?),"); + } + statement.append("(?)"); + PreparedStatement stmt = null; + try { + stmt = connection.prepareStatement(statement.toString()); + for (int i = 0; i < ids.length; i++) { + stmt.setInt(i + 1, ids[i]); + } + stmt.executeUpdate(); + stmt.close(); + } catch (SQLException e) { + e.printStackTrace(); + } - // add plot helpers - String prefix = ""; - statement = new StringBuilder("INSERT INTO `plot_helpers` (`plot_plot_id`, `user_uuid`) values "); - for (Integer id : helpers.keySet()) { - for (UUID helper : helpers.get(id)) { - statement.append(prefix + "(?, ?)"); - prefix = ","; - } - } - if (prefix.equals("")) { - return; - } - try { - stmt = connection.prepareStatement(statement.toString()); - int counter = 0; - for (Integer id : helpers.keySet()) { - for (UUID helper : helpers.get(id)) { + // add plot helpers + String prefix = ""; + statement = new StringBuilder( + "INSERT INTO `plot_helpers` (`plot_plot_id`, `user_uuid`) values "); + for (Integer id : helpers.keySet()) { + for (UUID helper : helpers.get(id)) { + statement.append(prefix + "(?, ?)"); + prefix = ","; + } + } + if (prefix.equals("")) { + return; + } + try { + stmt = connection.prepareStatement(statement.toString()); + int counter = 0; + for (Integer id : helpers.keySet()) { + for (UUID helper : helpers.get(id)) { - stmt.setInt((counter * 2) + 1, id); - stmt.setString((counter * 2) + 2, helper.toString()); - counter++; - } - } - stmt.executeUpdate(); - stmt.close(); - } catch (SQLException e) { - Logger.add(LogLevel.WARNING, "Failed to set helper for plots"); - e.printStackTrace(); - } - } + stmt.setInt((counter * 2) + 1, id); + stmt.setString((counter * 2) + 2, helper.toString()); + counter++; + } + } + stmt.executeUpdate(); + stmt.close(); + } catch (SQLException e) { + Logger.add(LogLevel.WARNING, "Failed to set helper for plots"); + e.printStackTrace(); + } + } - /** - * Create a plot - * - * @param plot - */ - public static void createPlots(ArrayList plots) { - if (plots.size() == 0) { - return; - } - StringBuilder statement = new StringBuilder("INSERT INTO `plot`(`plot_id_x`, `plot_id_z`, `owner`, `world`) values "); + /** + * Create a plot + * + * @param plot + */ + public static void createPlots(ArrayList plots) { + if (plots.size() == 0) { + return; + } + StringBuilder statement = new StringBuilder( + "INSERT INTO `plot`(`plot_id_x`, `plot_id_z`, `owner`, `world`) values "); - for (int i = 0; i < (plots.size() - 1); i++) { - statement.append("(?, ?, ?, ?),"); - } - statement.append("(?, ?, ?, ?)"); + for (int i = 0; i < (plots.size() - 1); i++) { + statement.append("(?, ?, ?, ?),"); + } + statement.append("(?, ?, ?, ?)"); - PreparedStatement stmt = null; - try { - stmt = connection.prepareStatement(statement.toString()); - for (int i = 0; i < plots.size(); i++) { - Plot plot = plots.get(i); - stmt.setInt((i * 4) + 1, plot.id.x); - stmt.setInt((i * 4) + 2, plot.id.y); - stmt.setString((i * 4) + 3, plot.owner.toString()); - stmt.setString((i * 4) + 4, plot.world); - } - stmt.executeUpdate(); - stmt.close(); - } catch (SQLException e) { - e.printStackTrace(); - Logger.add(LogLevel.DANGER, "Failed to save plots!"); - } - } + PreparedStatement stmt = null; + try { + stmt = connection.prepareStatement(statement.toString()); + for (int i = 0; i < plots.size(); i++) { + Plot plot = plots.get(i); + stmt.setInt((i * 4) + 1, plot.id.x); + stmt.setInt((i * 4) + 2, plot.id.y); + stmt.setString((i * 4) + 3, plot.owner.toString()); + stmt.setString((i * 4) + 4, plot.world); + } + stmt.executeUpdate(); + stmt.close(); + } catch (SQLException e) { + e.printStackTrace(); + Logger.add(LogLevel.DANGER, "Failed to save plots!"); + } + } - /** - * Create a plot - * - * @param plot - */ - public static void createPlot(Plot plot) { - PreparedStatement stmt = null; - try { - stmt = connection.prepareStatement("INSERT INTO `plot`(`plot_id_x`, `plot_id_z`, `owner`, `world`) VALUES(?, ?, ?, ?)"); - stmt.setInt(1, plot.id.x); - stmt.setInt(2, plot.id.y); - stmt.setString(3, plot.owner.toString()); - stmt.setString(4, plot.world); - stmt.executeUpdate(); - stmt.close(); - } catch (SQLException e) { - e.printStackTrace(); - Logger.add(LogLevel.DANGER, "Failed to save plot " + plot.id); - } - } + /** + * Create a plot + * + * @param plot + */ + public static void createPlot(Plot plot) { + PreparedStatement stmt = null; + try { + stmt = connection + .prepareStatement("INSERT INTO `plot`(`plot_id_x`, `plot_id_z`, `owner`, `world`) VALUES(?, ?, ?, ?)"); + stmt.setInt(1, plot.id.x); + stmt.setInt(2, plot.id.y); + stmt.setString(3, plot.owner.toString()); + stmt.setString(4, plot.world); + stmt.executeUpdate(); + stmt.close(); + } catch (SQLException e) { + e.printStackTrace(); + Logger.add(LogLevel.DANGER, "Failed to save plot " + plot.id); + } + } - /** - * Create tables - * - * @throws SQLException - */ - public static void createTables(String database, boolean add_constraint) throws SQLException { - boolean mysql = database.equals("mysql"); - Statement stmt = connection.createStatement(); + /** + * Create tables + * + * @throws SQLException + */ + public static void createTables(String database, boolean add_constraint) + throws SQLException { + boolean mysql = database.equals("mysql"); + Statement stmt = connection.createStatement(); - if (mysql) { - stmt.addBatch("CREATE TABLE IF NOT EXISTS `plot` (" + "`id` INT(11) NOT NULL AUTO_INCREMENT," + "`plot_id_x` INT(11) NOT NULL," + "`plot_id_z` INT(11) NOT NULL," + "`owner` VARCHAR(45) NOT NULL," + "`world` VARCHAR(45) NOT NULL," + "`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP," + "PRIMARY KEY (`id`)" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=0"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `plot_denied` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `plot_helpers` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `plot_trusted` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `plot_settings` (" + " `plot_plot_id` INT(11) NOT NULL," + " `biome` VARCHAR(45) DEFAULT 'FOREST'," + " `rain` INT(1) DEFAULT 0," + " `custom_time` TINYINT(1) DEFAULT '0'," + " `time` INT(11) DEFAULT '8000'," + " `deny_entry` TINYINT(1) DEFAULT '0'," + " `alias` VARCHAR(50) DEFAULT NULL," + " `flags` VARCHAR(512) DEFAULT NULL," + " `merged` INT(11) DEFAULT NULL," + " `position` VARCHAR(50) NOT NULL DEFAULT 'DEFAULT'," + " PRIMARY KEY (`plot_plot_id`)," + " UNIQUE KEY `unique_alias` (`alias`)" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `plot_ratings` ( `plot_plot_id` INT(11) NOT NULL, `rating` INT(2) NOT NULL, `player` VARCHAR(40) NOT NULL, PRIMARY KEY(`plot_plot_id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8"); - if (add_constraint) { - stmt.addBatch("ALTER TABLE `plot_settings` ADD CONSTRAINT `plot_settings_ibfk_1` FOREIGN KEY (`plot_plot_id`) REFERENCES `plot` (`id`) ON DELETE CASCADE"); - } + if (mysql) { + stmt.addBatch("CREATE TABLE IF NOT EXISTS `plot` (" + + "`id` INT(11) NOT NULL AUTO_INCREMENT," + + "`plot_id_x` INT(11) NOT NULL," + + "`plot_id_z` INT(11) NOT NULL," + + "`owner` VARCHAR(45) NOT NULL," + + "`world` VARCHAR(45) NOT NULL," + + "`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP," + + "PRIMARY KEY (`id`)" + + ") ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=0"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `plot_denied` (" + + "`plot_plot_id` INT(11) NOT NULL," + + "`user_uuid` VARCHAR(40) NOT NULL" + + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `plot_helpers` (" + + "`plot_plot_id` INT(11) NOT NULL," + + "`user_uuid` VARCHAR(40) NOT NULL" + + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `plot_trusted` (" + + "`plot_plot_id` INT(11) NOT NULL," + + "`user_uuid` VARCHAR(40) NOT NULL" + + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `plot_settings` (" + + " `plot_plot_id` INT(11) NOT NULL," + + " `biome` VARCHAR(45) DEFAULT 'FOREST'," + + " `rain` INT(1) DEFAULT 0," + + " `custom_time` TINYINT(1) DEFAULT '0'," + + " `time` INT(11) DEFAULT '8000'," + + " `deny_entry` TINYINT(1) DEFAULT '0'," + + " `alias` VARCHAR(50) DEFAULT NULL," + + " `flags` VARCHAR(512) DEFAULT NULL," + + " `merged` INT(11) DEFAULT NULL," + + " `position` VARCHAR(50) NOT NULL DEFAULT 'DEFAULT'," + + " PRIMARY KEY (`plot_plot_id`)," + + " UNIQUE KEY `unique_alias` (`alias`)" + + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `plot_ratings` ( `plot_plot_id` INT(11) NOT NULL, `rating` INT(2) NOT NULL, `player` VARCHAR(40) NOT NULL, PRIMARY KEY(`plot_plot_id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8"); + if (add_constraint) { + stmt.addBatch("ALTER TABLE `plot_settings` ADD CONSTRAINT `plot_settings_ibfk_1` FOREIGN KEY (`plot_plot_id`) REFERENCES `plot` (`id`) ON DELETE CASCADE"); + } - } else { - stmt.addBatch("CREATE TABLE IF NOT EXISTS `plot` (" + "`id` INTEGER(11) PRIMARY KEY," + "`plot_id_x` INT(11) NOT NULL," + "`plot_id_z` INT(11) NOT NULL," + "`owner` VARCHAR(45) NOT NULL," + "`world` VARCHAR(45) NOT NULL," + "`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP)"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `plot_denied` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ")"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `plot_helpers` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ")"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `plot_trusted` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ")"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `plot_settings` (" + " `plot_plot_id` INT(11) NOT NULL," + " `biome` VARCHAR(45) DEFAULT 'FOREST'," + " `rain` INT(1) DEFAULT 0," + " `custom_time` TINYINT(1) DEFAULT '0'," + " `time` INT(11) DEFAULT '8000'," + " `deny_entry` TINYINT(1) DEFAULT '0'," + " `alias` VARCHAR(50) DEFAULT NULL," + " `flags` VARCHAR(512) DEFAULT NULL," + " `merged` INT(11) DEFAULT NULL," + " `position` VARCHAR(50) NOT NULL DEFAULT 'DEFAULT'," + " PRIMARY KEY (`plot_plot_id`)" + ")"); - stmt.addBatch("CREATE TABLE IF NOT EXISTS `plot_ratings` (`plot_plot_id` INT(11) NOT NULL, `rating` INT(2) NOT NULL, `player` VARCHAR(40) NOT NULL, PRIMARY KEY(`plot_plot_id`))"); - } - stmt.executeBatch(); - stmt.clearBatch(); - stmt.close(); - } + } else { + stmt.addBatch("CREATE TABLE IF NOT EXISTS `plot` (" + + "`id` INTEGER(11) PRIMARY KEY," + + "`plot_id_x` INT(11) NOT NULL," + + "`plot_id_z` INT(11) NOT NULL," + + "`owner` VARCHAR(45) NOT NULL," + + "`world` VARCHAR(45) NOT NULL," + + "`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP)"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `plot_denied` (" + + "`plot_plot_id` INT(11) NOT NULL," + + "`user_uuid` VARCHAR(40) NOT NULL" + ")"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `plot_helpers` (" + + "`plot_plot_id` INT(11) NOT NULL," + + "`user_uuid` VARCHAR(40) NOT NULL" + ")"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `plot_trusted` (" + + "`plot_plot_id` INT(11) NOT NULL," + + "`user_uuid` VARCHAR(40) NOT NULL" + ")"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `plot_settings` (" + + " `plot_plot_id` INT(11) NOT NULL," + + " `biome` VARCHAR(45) DEFAULT 'FOREST'," + + " `rain` INT(1) DEFAULT 0," + + " `custom_time` TINYINT(1) DEFAULT '0'," + + " `time` INT(11) DEFAULT '8000'," + + " `deny_entry` TINYINT(1) DEFAULT '0'," + + " `alias` VARCHAR(50) DEFAULT NULL," + + " `flags` VARCHAR(512) DEFAULT NULL," + + " `merged` INT(11) DEFAULT NULL," + + " `position` VARCHAR(50) NOT NULL DEFAULT 'DEFAULT'," + + " PRIMARY KEY (`plot_plot_id`)" + ")"); + stmt.addBatch("CREATE TABLE IF NOT EXISTS `plot_ratings` (`plot_plot_id` INT(11) NOT NULL, `rating` INT(2) NOT NULL, `player` VARCHAR(40) NOT NULL, PRIMARY KEY(`plot_plot_id`))"); + } + stmt.executeBatch(); + stmt.clearBatch(); + stmt.close(); + } - /** - * Delete a plot - * - * @param plot - */ - public static void delete(final String world, final Plot plot) { - PlotMain.removePlot(world, plot.id, false); - runTask(new Runnable() { - @Override - public void run() { - PreparedStatement stmt = null; - int id = getId(world, plot.id); - try { - stmt = connection.prepareStatement("DELETE FROM `plot_settings` WHERE `plot_plot_id` = ?"); - stmt.setInt(1, id); - stmt.executeUpdate(); - stmt.close(); - stmt = connection.prepareStatement("DELETE FROM `plot_helpers` WHERE `plot_plot_id` = ?"); - stmt.setInt(1, id); - stmt.executeUpdate(); - stmt.close(); - stmt = connection.prepareStatement("DELETE FROM `plot_trusted` WHERE `plot_plot_id` = ?"); - stmt.setInt(1, id); - stmt.executeUpdate(); - stmt.close(); - stmt = connection.prepareStatement("DELETE FROM `plot` WHERE `id` = ?"); - stmt.setInt(1, id); - stmt.executeUpdate(); - stmt.close(); - } catch (SQLException e) { - e.printStackTrace(); - Logger.add(LogLevel.DANGER, "Failed to delete plot " + plot.id); - } - } - }); - } + /** + * Delete a plot + * + * @param plot + */ + public static void delete(final String world, final Plot plot) { + PlotMain.removePlot(world, plot.id, false); + runTask(new Runnable() { + @Override + public void run() { + PreparedStatement stmt = null; + int id = getId(world, plot.id); + try { + stmt = connection + .prepareStatement("DELETE FROM `plot_settings` WHERE `plot_plot_id` = ?"); + stmt.setInt(1, id); + stmt.executeUpdate(); + stmt.close(); + stmt = connection + .prepareStatement("DELETE FROM `plot_helpers` WHERE `plot_plot_id` = ?"); + stmt.setInt(1, id); + stmt.executeUpdate(); + stmt.close(); + stmt = connection + .prepareStatement("DELETE FROM `plot_trusted` WHERE `plot_plot_id` = ?"); + stmt.setInt(1, id); + stmt.executeUpdate(); + stmt.close(); + stmt = connection + .prepareStatement("DELETE FROM `plot` WHERE `id` = ?"); + stmt.setInt(1, id); + stmt.executeUpdate(); + stmt.close(); + } catch (SQLException e) { + e.printStackTrace(); + Logger.add(LogLevel.DANGER, "Failed to delete plot " + + plot.id); + } + } + }); + } - /** - * Create plot settings - * - * @param id - * @param plot - */ - public static void createPlotSettings(final int id, final Plot plot) { - runTask(new Runnable() { - @Override - public void run() { - PreparedStatement stmt = null; - try { - stmt = connection.prepareStatement("INSERT INTO `plot_settings`(`plot_plot_id`) VALUES(" + "?)"); - stmt.setInt(1, id); - stmt.executeUpdate(); - stmt.close(); - } catch (SQLException e) { - e.printStackTrace(); - } + /** + * Create plot settings + * + * @param id + * @param plot + */ + public static void createPlotSettings(final int id, final Plot plot) { + runTask(new Runnable() { + @Override + public void run() { + PreparedStatement stmt = null; + try { + stmt = connection + .prepareStatement("INSERT INTO `plot_settings`(`plot_plot_id`) VALUES(" + + "?)"); + stmt.setInt(1, id); + stmt.executeUpdate(); + stmt.close(); + } catch (SQLException e) { + e.printStackTrace(); + } - } - }); - } + } + }); + } - public static int getId(String world, PlotId id2) { - PreparedStatement stmt = null; - try { - stmt = connection.prepareStatement("SELECT `id` FROM `plot` WHERE `plot_id_x` = ? AND `plot_id_z` = ? AND world = ? ORDER BY `timestamp` ASC"); - stmt.setInt(1, id2.x); - stmt.setInt(2, id2.y); - stmt.setString(3, world); - ResultSet r = stmt.executeQuery(); - int id = Integer.MAX_VALUE; - while (r.next()) { - id = r.getInt("id"); - } - stmt.close(); - return id; - } catch (SQLException e) { - e.printStackTrace(); - } - return Integer.MAX_VALUE; - } + public static int getId(String world, PlotId id2) { + PreparedStatement stmt = null; + try { + stmt = connection + .prepareStatement("SELECT `id` FROM `plot` WHERE `plot_id_x` = ? AND `plot_id_z` = ? AND world = ? ORDER BY `timestamp` ASC"); + stmt.setInt(1, id2.x); + stmt.setInt(2, id2.y); + stmt.setString(3, world); + ResultSet r = stmt.executeQuery(); + int id = Integer.MAX_VALUE; + while (r.next()) { + id = r.getInt("id"); + } + stmt.close(); + return id; + } catch (SQLException e) { + e.printStackTrace(); + } + return Integer.MAX_VALUE; + } - /** - * Get a plot id - * - * @param plot_id - * @return - */ - /* - * public static int getId(String world, PlotId id2) { Statement stmt = - * null; try { stmt = connection.createStatement(); ResultSet r = - * stmt.executeQuery("SELECT `id` FROM `plot` WHERE `plot_id_x` = '" + id2.x - * + "' AND `plot_id_z` = '" + id2.y + "' AND `world` = '" + world + - * "' ORDER BY `timestamp` ASC"); int id = Integer.MAX_VALUE; - * while(r.next()) { id = r.getInt("id"); } stmt.close(); return id; } - * catch(SQLException e) { e.printStackTrace(); } return Integer.MAX_VALUE; - * } - */ + /** + * Get a plot id + * + * @param plot_id + * @return + */ + /* + * public static int getId(String world, PlotId id2) { Statement stmt = + * null; try { stmt = connection.createStatement(); ResultSet r = + * stmt.executeQuery("SELECT `id` FROM `plot` WHERE `plot_id_x` = '" + id2.x + * + "' AND `plot_id_z` = '" + id2.y + "' AND `world` = '" + world + + * "' ORDER BY `timestamp` ASC"); int id = Integer.MAX_VALUE; + * while(r.next()) { id = r.getInt("id"); } stmt.close(); return id; } + * catch(SQLException e) { e.printStackTrace(); } return Integer.MAX_VALUE; + * } + */ - /** - * @return - */ - public static HashMap> getPlots() { - try { - DatabaseMetaData data = connection.getMetaData(); - ResultSet rs = data.getColumns(null, null, "plot", "plot_id"); - boolean execute = rs.next(); - if (execute) { - Statement statement = connection.createStatement(); - statement.addBatch("ALTER IGNORE TABLE `plot` ADD `plot_id_x` int(11) DEFAULT 0"); - statement.addBatch("ALTER IGNORE TABLE `plot` ADD `plot_id_z` int(11) DEFAULT 0"); - statement.addBatch("UPDATE `plot` SET\n" + " `plot_id_x` = IF(" + " LOCATE(';', `plot_id`) > 0," + " SUBSTRING(`plot_id`, 1, LOCATE(';', `plot_id`) - 1)," + " `plot_id`" + " )," + " `plot_id_z` = IF(" + " LOCATE(';', `plot_id`) > 0," + " SUBSTRING(`plot_id`, LOCATE(';', `plot_id`) + 1)," + " NULL" + " )"); - statement.addBatch("ALTER TABLE `plot` DROP `plot_id`"); - statement.addBatch("ALTER IGNORE TABLE `plot_settings` ADD `flags` VARCHAR(512) DEFAULT NULL"); - statement.executeBatch(); - statement.close(); - } - rs = data.getColumns(null, null, "plot_settings", "merged"); - if (!rs.next()) { - Statement statement = connection.createStatement(); - statement.addBatch("ALTER TABLE `plot_settings` ADD `merged` int(11) DEFAULT NULL"); - statement.executeBatch(); - statement.close(); - } - } catch (Exception e) { - e.printStackTrace(); - } - HashMap> plots = new HashMap>(); - Statement stmt = null; - try { - - Set worlds = new HashSet(); - if (PlotMain.config.contains("worlds")) { - worlds = PlotMain.config.getConfigurationSection("worlds").getKeys(false); - } - - stmt = connection.createStatement(); - ResultSet r = stmt.executeQuery("SELECT `id`, `plot_id_x`, `plot_id_z`, `owner`, `world` FROM `plot`"); - PlotId plot_id; - int id; - Plot p; - while (r.next()) { - plot_id = new PlotId(r.getInt("plot_id_x"), r.getInt("plot_id_z")); - id = r.getInt("id"); - String worldname = r.getString("world"); - HashMap settings = getSettings(id); - UUID owner = UUID.fromString(r.getString("owner")); - Biome plotBiome = Biome.FOREST; - String[] flags_string; - if (settings.get("flags") == null) { - flags_string = new String[] {}; - } else { - flags_string = ((String) settings.get("flags")).split(","); - } - Flag[] flags = new Flag[flags_string.length]; - for (int i = 0; i < flags.length; i++) { - if (flags_string[i].contains(":")) { - String[] split = flags_string[i].split(":"); - flags[i] = new Flag(FlagManager.getFlag(split[0], true), split[1]); - } else { - flags[i] = new Flag(FlagManager.getFlag(flags_string[i], true), ""); - } - } - ArrayList helpers = plotHelpers(id); - ArrayList trusted = plotTrusted(id); - ArrayList denied = plotDenied(id); - // boolean changeTime = ((Short) settings.get("custom_time") == - // 0) ? false : true; - long time = 8000l; - // if(changeTime) { - // time = Long.parseLong(settings.get("time").toString()); - // } - // boolean rain = - // Integer.parseInt(settings.get("rain").toString()) == 1 ? true - // : false; - boolean rain; - try { - rain = (int) settings.get("rain") == 1 ? true : false; - } catch (Exception e) { - rain = false; - } - String alias = (String) settings.get("alias"); - if ((alias == null) || alias.equalsIgnoreCase("NEW")) { - alias = ""; - } - PlotHomePosition position = null; - for (PlotHomePosition plotHomePosition : PlotHomePosition.values()) { - if (settings.get("position") == null) { - position = PlotHomePosition.DEFAULT; - break; - } - if (plotHomePosition.isMatching((String) settings.get("position"))) { - position = plotHomePosition; - } - } - if (position == null) { - position = PlotHomePosition.DEFAULT; - } - int merged_int = settings.get("merged") == null ? 0 : (int) settings.get("merged"); + /** + * @return + */ + public static HashMap> getPlots() { + try { + DatabaseMetaData data = connection.getMetaData(); + ResultSet rs = data.getColumns(null, null, "plot", "plot_id"); + boolean execute = rs.next(); + if (execute) { + Statement statement = connection.createStatement(); + statement + .addBatch("ALTER IGNORE TABLE `plot` ADD `plot_id_x` int(11) DEFAULT 0"); + statement + .addBatch("ALTER IGNORE TABLE `plot` ADD `plot_id_z` int(11) DEFAULT 0"); + statement + .addBatch("UPDATE `plot` SET\n" + + " `plot_id_x` = IF(" + + " LOCATE(';', `plot_id`) > 0," + + " SUBSTRING(`plot_id`, 1, LOCATE(';', `plot_id`) - 1)," + + " `plot_id`" + + " )," + + " `plot_id_z` = IF(" + + " LOCATE(';', `plot_id`) > 0," + + " SUBSTRING(`plot_id`, LOCATE(';', `plot_id`) + 1)," + + " NULL" + " )"); + statement.addBatch("ALTER TABLE `plot` DROP `plot_id`"); + statement + .addBatch("ALTER IGNORE TABLE `plot_settings` ADD `flags` VARCHAR(512) DEFAULT NULL"); + statement.executeBatch(); + statement.close(); + } + rs = data.getColumns(null, null, "plot_settings", "merged"); + if (!rs.next()) { + Statement statement = connection.createStatement(); + statement + .addBatch("ALTER TABLE `plot_settings` ADD `merged` int(11) DEFAULT NULL"); + statement.executeBatch(); + statement.close(); + } + } catch (Exception e) { + e.printStackTrace(); + } + HashMap> plots = new HashMap>(); + Statement stmt = null; + try { - boolean[] merged = new boolean[4]; - for (int i = 0; i < 4; i++) { - merged[3 - i] = (merged_int & (1 << i)) != 0; - } - p = new Plot(plot_id, owner, plotBiome, helpers, trusted, denied, /* changeTime */false, time, rain, alias, position, flags, worldname, merged); - if (plots.containsKey(worldname)) { - plots.get(worldname).put((plot_id), p); - } else { - if (worlds.contains(p.world)) { - HashMap map = new HashMap(); - map.put((plot_id), p); - plots.put(worldname, map); - } - else { - PlotMain.sendConsoleSenderMessage("&cPlot '"+p.id+"' in DB for world '"+p.world+"' does not exist! Please create this world, or remove the plots from the DB!"); - } - } - } - stmt.close(); - } catch (SQLException e) { - Logger.add(LogLevel.WARNING, "Failed to load plots."); - e.printStackTrace(); - } - return plots; - } + Set worlds = new HashSet(); + if (PlotMain.config.contains("worlds")) { + worlds = PlotMain.config.getConfigurationSection("worlds") + .getKeys(false); + } - /** - * @param plot - * @param rain - */ - public static void setWeather(final String world, final Plot plot, final boolean rain) { - plot.settings.setRain(rain); - runTask(new Runnable() { - @Override - public void run() { - try { - int weather = rain ? 1 : 0; - PreparedStatement stmt = connection.prepareStatement("UPDATE `plot_settings` SET `rain` = ? WHERE `plot_plot_id` = ?"); - stmt.setInt(1, weather); - stmt.setInt(2, getId(world, plot.id)); - stmt.execute(); - stmt.close(); - } catch (SQLException e) { - e.printStackTrace(); - Logger.add(LogLevel.WARNING, "Could not set weather for plot " + plot.id); - } - } - }); - } + stmt = connection.createStatement(); + ResultSet r = stmt + .executeQuery("SELECT `id`, `plot_id_x`, `plot_id_z`, `owner`, `world` FROM `plot`"); + PlotId plot_id; + int id; + Plot p; + while (r.next()) { + plot_id = new PlotId(r.getInt("plot_id_x"), + r.getInt("plot_id_z")); + id = r.getInt("id"); + String worldname = r.getString("world"); + HashMap settings = getSettings(id); + UUID owner = UUID.fromString(r.getString("owner")); + Biome plotBiome = Biome.FOREST; + String[] flags_string; + if (settings.get("flags") == null) { + flags_string = new String[] {}; + } else { + flags_string = ((String) settings.get("flags")).split(","); + } + Flag[] flags = new Flag[flags_string.length]; + for (int i = 0; i < flags.length; i++) { + if (flags_string[i].contains(":")) { + String[] split = flags_string[i].split(":"); + flags[i] = new Flag( + FlagManager.getFlag(split[0], true), split[1]); + } else { + flags[i] = new Flag(FlagManager.getFlag( + flags_string[i], true), ""); + } + } + ArrayList helpers = plotHelpers(id); + ArrayList trusted = plotTrusted(id); + ArrayList denied = plotDenied(id); + // boolean changeTime = ((Short) settings.get("custom_time") == + // 0) ? false : true; + long time = 8000l; + // if(changeTime) { + // time = Long.parseLong(settings.get("time").toString()); + // } + // boolean rain = + // Integer.parseInt(settings.get("rain").toString()) == 1 ? true + // : false; + boolean rain; + try { + rain = (int) settings.get("rain") == 1 ? true : false; + } catch (Exception e) { + rain = false; + } + String alias = (String) settings.get("alias"); + if ((alias == null) || alias.equalsIgnoreCase("NEW")) { + alias = ""; + } + PlotHomePosition position = null; + for (PlotHomePosition plotHomePosition : PlotHomePosition + .values()) { + if (settings.get("position") == null) { + position = PlotHomePosition.DEFAULT; + break; + } + if (plotHomePosition.isMatching((String) settings + .get("position"))) { + position = plotHomePosition; + } + } + if (position == null) { + position = PlotHomePosition.DEFAULT; + } + int merged_int = settings.get("merged") == null ? 0 + : (int) settings.get("merged"); - public static void setMerged(final String world, final Plot plot, final boolean[] merged) { - plot.settings.setMerged(merged); - runTask(new Runnable() { - @Override - public void run() { - try { - int n = 0; - for (int i = 0; i < 4; ++i) { - n = (n << 1) + (merged[i] ? 1 : 0); - } - PreparedStatement stmt = connection.prepareStatement("UPDATE `plot_settings` SET `merged` = ? WHERE `plot_plot_id` = ?"); - stmt.setInt(1, n); - stmt.setInt(2, getId(world, plot.id)); - stmt.execute(); - stmt.close(); - } catch (SQLException e) { - e.printStackTrace(); - Logger.add(LogLevel.WARNING, "Could not set merged for plot " + plot.id); - } - } - }); - } + boolean[] merged = new boolean[4]; + for (int i = 0; i < 4; i++) { + merged[3 - i] = (merged_int & (1 << i)) != 0; + } + p = new Plot(plot_id, owner, plotBiome, helpers, trusted, + denied, /* changeTime */false, time, rain, alias, + position, flags, worldname, merged); + if (plots.containsKey(worldname)) { + plots.get(worldname).put((plot_id), p); + } else { + if (worlds.contains(p.world)) { + HashMap map = new HashMap(); + map.put((plot_id), p); + plots.put(worldname, map); + } else { + PlotMain.sendConsoleSenderMessage("&cPlot '" + + p.id + + "' in DB for world '" + + p.world + + "' does not exist! Please create this world, or remove the plots from the DB!"); + } + } + } + stmt.close(); + } catch (SQLException e) { + Logger.add(LogLevel.WARNING, "Failed to load plots."); + e.printStackTrace(); + } + return plots; + } - public static void setFlags(final String world, final Plot plot, final Flag[] flags) { - plot.settings.setFlags(flags); - final StringBuilder flag_string = new StringBuilder(); - int i = 0; - for (Flag flag : flags) { - if (i != 0) { - flag_string.append(","); - } - flag_string.append(flag.getKey() + ":" + flag.getValue()); - i++; - } - runTask(new Runnable() { - @Override - public void run() { - try { - PreparedStatement stmt = connection.prepareStatement("UPDATE `plot_settings` SET `flags` = ? WHERE `plot_plot_id` = ?"); - stmt.setString(1, flag_string.toString()); - stmt.setInt(2, getId(world, plot.id)); - stmt.execute(); - stmt.close(); - } catch (SQLException e) { - e.printStackTrace(); - Logger.add(LogLevel.WARNING, "Could not set flag for plot " + plot.id); - } - } - }); - } + /** + * @param plot + * @param rain + */ + public static void setWeather(final String world, final Plot plot, + final boolean rain) { + plot.settings.setRain(rain); + runTask(new Runnable() { + @Override + public void run() { + try { + int weather = rain ? 1 : 0; + PreparedStatement stmt = connection + .prepareStatement("UPDATE `plot_settings` SET `rain` = ? WHERE `plot_plot_id` = ?"); + stmt.setInt(1, weather); + stmt.setInt(2, getId(world, plot.id)); + stmt.execute(); + stmt.close(); + } catch (SQLException e) { + e.printStackTrace(); + Logger.add(LogLevel.WARNING, + "Could not set weather for plot " + plot.id); + } + } + }); + } - /** - * @param plot - * @param alias - */ - public static void setAlias(final String world, final Plot plot, final String alias) { - plot.settings.setAlias(alias); - runTask(new Runnable() { - @Override - public void run() { - PreparedStatement stmt = null; - try { - stmt = connection.prepareStatement("UPDATE `plot_settings` SET `alias` = ? WHERE `plot_plot_id` = ?"); - stmt.setString(1, alias); - stmt.setInt(2, getId(world, plot.id)); - stmt.executeUpdate(); - stmt.close(); - } catch (SQLException e) { - Logger.add(LogLevel.WARNING, "Failed to set alias for plot " + plot.id); - e.printStackTrace(); - } + public static void setMerged(final String world, final Plot plot, + final boolean[] merged) { + plot.settings.setMerged(merged); + runTask(new Runnable() { + @Override + public void run() { + try { + int n = 0; + for (int i = 0; i < 4; ++i) { + n = (n << 1) + (merged[i] ? 1 : 0); + } + PreparedStatement stmt = connection + .prepareStatement("UPDATE `plot_settings` SET `merged` = ? WHERE `plot_plot_id` = ?"); + stmt.setInt(1, n); + stmt.setInt(2, getId(world, plot.id)); + stmt.execute(); + stmt.close(); + } catch (SQLException e) { + e.printStackTrace(); + Logger.add(LogLevel.WARNING, + "Could not set merged for plot " + plot.id); + } + } + }); + } - } - }); - } + public static void setFlags(final String world, final Plot plot, + final Flag[] flags) { + plot.settings.setFlags(flags); + final StringBuilder flag_string = new StringBuilder(); + int i = 0; + for (Flag flag : flags) { + if (i != 0) { + flag_string.append(","); + } + flag_string.append(flag.getKey() + ":" + flag.getValue()); + i++; + } + runTask(new Runnable() { + @Override + public void run() { + try { + PreparedStatement stmt = connection + .prepareStatement("UPDATE `plot_settings` SET `flags` = ? WHERE `plot_plot_id` = ?"); + stmt.setString(1, flag_string.toString()); + stmt.setInt(2, getId(world, plot.id)); + stmt.execute(); + stmt.close(); + } catch (SQLException e) { + e.printStackTrace(); + Logger.add(LogLevel.WARNING, "Could not set flag for plot " + + plot.id); + } + } + }); + } - /** - * @param r - */ - private static void runTask(Runnable r) { - PlotMain.getMain().getServer().getScheduler().runTaskAsynchronously(PlotMain.getMain(), r); - } + /** + * @param plot + * @param alias + */ + public static void setAlias(final String world, final Plot plot, + final String alias) { + plot.settings.setAlias(alias); + runTask(new Runnable() { + @Override + public void run() { + PreparedStatement stmt = null; + try { + stmt = connection + .prepareStatement("UPDATE `plot_settings` SET `alias` = ? WHERE `plot_plot_id` = ?"); + stmt.setString(1, alias); + stmt.setInt(2, getId(world, plot.id)); + stmt.executeUpdate(); + stmt.close(); + } catch (SQLException e) { + Logger.add(LogLevel.WARNING, + "Failed to set alias for plot " + plot.id); + e.printStackTrace(); + } - /** - * @param plot - * @param position - */ - public static void setPosition(final String world, final Plot plot, final String position) { - plot.settings.setPosition(PlotHomePosition.valueOf(position)); - runTask(new Runnable() { - @Override - public void run() { - PreparedStatement stmt = null; - try { - stmt = connection.prepareStatement("UPDATE `plot_settings` SET `position` = ? WHERE `plot_plot_id` = ?"); - stmt.setString(1, position); - stmt.setInt(2, getId(world, plot.id)); - stmt.executeUpdate(); - stmt.close(); - } catch (SQLException e) { - Logger.add(LogLevel.WARNING, "Failed to set position for plot " + plot.id); - e.printStackTrace(); - } - } - }); - } + } + }); + } - /** - * @param id - * @return - */ - public static HashMap getSettings(int id) { - HashMap h = new HashMap(); - PreparedStatement stmt = null; - try { - stmt = connection.prepareStatement("SELECT * FROM `plot_settings` WHERE `plot_plot_id` = ?"); - stmt.setInt(1, id); - ResultSet r = stmt.executeQuery(); - String var; - Object val; - while (r.next()) { - var = "biome"; - val = r.getObject(var); - h.put(var, val); - var = "rain"; - val = r.getObject(var); - h.put(var, val); - var = "custom_time"; - val = r.getObject(var); - h.put(var, val); - var = "time"; - val = r.getObject(var); - h.put(var, val); - var = "deny_entry"; - val = r.getObject(var); - h.put(var, (short) 0); - var = "alias"; - val = r.getObject(var); - h.put(var, val); - var = "position"; - val = r.getObject(var); - h.put(var, val); - var = "flags"; - val = r.getObject(var); - h.put(var, val); - var = "merged"; - val = r.getObject(var); - h.put(var, val); - } - stmt.close(); - ; - } catch (SQLException e) { - Logger.add(LogLevel.WARNING, "Failed to load settings for plot: " + id); - e.printStackTrace(); - } - return h; - } + /** + * @param r + */ + private static void runTask(Runnable r) { + PlotMain.getMain().getServer().getScheduler() + .runTaskAsynchronously(PlotMain.getMain(), r); + } - /** - * - */ - public static UUID everyone = UUID.fromString("1-1-3-3-7"); + /** + * @param plot + * @param position + */ + public static void setPosition(final String world, final Plot plot, + final String position) { + plot.settings.setPosition(PlotHomePosition.valueOf(position)); + runTask(new Runnable() { + @Override + public void run() { + PreparedStatement stmt = null; + try { + stmt = connection + .prepareStatement("UPDATE `plot_settings` SET `position` = ? WHERE `plot_plot_id` = ?"); + stmt.setString(1, position); + stmt.setInt(2, getId(world, plot.id)); + stmt.executeUpdate(); + stmt.close(); + } catch (SQLException e) { + Logger.add(LogLevel.WARNING, + "Failed to set position for plot " + plot.id); + e.printStackTrace(); + } + } + }); + } - /** - * @param id - * @return - */ - private static ArrayList plotDenied(int id) { - ArrayList l = new ArrayList(); - PreparedStatement stmt = null; - try { - stmt = connection.prepareStatement("SELECT `user_uuid` FROM `plot_denied` WHERE `plot_plot_id` = ?"); - stmt.setInt(1, id); - ResultSet r = stmt.executeQuery(); - UUID u; - while (r.next()) { - u = UUID.fromString(r.getString("user_uuid")); - l.add(u); - } - stmt.close(); - } catch (Exception e) { - Logger.add(LogLevel.DANGER, "Failed to load denied for plot: " + id); - e.printStackTrace(); - } - return l; - } + /** + * @param id + * @return + */ + public static HashMap getSettings(int id) { + HashMap h = new HashMap(); + PreparedStatement stmt = null; + try { + stmt = connection + .prepareStatement("SELECT * FROM `plot_settings` WHERE `plot_plot_id` = ?"); + stmt.setInt(1, id); + ResultSet r = stmt.executeQuery(); + String var; + Object val; + while (r.next()) { + var = "biome"; + val = r.getObject(var); + h.put(var, val); + var = "rain"; + val = r.getObject(var); + h.put(var, val); + var = "custom_time"; + val = r.getObject(var); + h.put(var, val); + var = "time"; + val = r.getObject(var); + h.put(var, val); + var = "deny_entry"; + val = r.getObject(var); + h.put(var, (short) 0); + var = "alias"; + val = r.getObject(var); + h.put(var, val); + var = "position"; + val = r.getObject(var); + h.put(var, val); + var = "flags"; + val = r.getObject(var); + h.put(var, val); + var = "merged"; + val = r.getObject(var); + h.put(var, val); + } + stmt.close(); + ; + } catch (SQLException e) { + Logger.add(LogLevel.WARNING, "Failed to load settings for plot: " + + id); + e.printStackTrace(); + } + return h; + } - /** - * @param id - * @return - */ - private static ArrayList plotHelpers(int id) { - ArrayList l = new ArrayList(); - Statement stmt = null; - try { - stmt = connection.createStatement(); - ResultSet r = stmt.executeQuery("SELECT `user_uuid` FROM `plot_helpers` WHERE `plot_plot_id` = " + id); - UUID u; - while (r.next()) { - u = UUID.fromString(r.getString("user_uuid")); - l.add(u); - } - stmt.close(); - } catch (SQLException e) { - Logger.add(LogLevel.WARNING, "Failed to load helpers for plot: " + id); - e.printStackTrace(); - } - return l; - } + /** + * + */ + public static UUID everyone = UUID.fromString("1-1-3-3-7"); - /** - * @param id - * @return - */ - private static ArrayList plotTrusted(int id) { - ArrayList l = new ArrayList(); - Statement stmt = null; - try { - stmt = connection.createStatement(); - ResultSet r = stmt.executeQuery("SELECT `user_uuid` FROM `plot_trusted` WHERE `plot_plot_id` = " + id); - UUID u; - while (r.next()) { - u = UUID.fromString(r.getString("user_uuid")); - l.add(u); - } - stmt.close(); - } catch (SQLException e) { - Logger.add(LogLevel.WARNING, "Failed to load trusted users for plot: " + id); - e.printStackTrace(); - } - return l; - } + /** + * @param id + * @return + */ + private static ArrayList plotDenied(int id) { + ArrayList l = new ArrayList(); + PreparedStatement stmt = null; + try { + stmt = connection + .prepareStatement("SELECT `user_uuid` FROM `plot_denied` WHERE `plot_plot_id` = ?"); + stmt.setInt(1, id); + ResultSet r = stmt.executeQuery(); + UUID u; + while (r.next()) { + u = UUID.fromString(r.getString("user_uuid")); + l.add(u); + } + stmt.close(); + } catch (Exception e) { + Logger.add(LogLevel.DANGER, "Failed to load denied for plot: " + id); + e.printStackTrace(); + } + return l; + } - /** - * @param plot - * @param player - */ - public static void removeHelper(final String world, final Plot plot, final OfflinePlayer player) { - runTask(new Runnable() { - @Override - public void run() { - try { - PreparedStatement statement = connection.prepareStatement("DELETE FROM `plot_helpers` WHERE `plot_plot_id` = ? AND `user_uuid` = ?"); - statement.setInt(1, getId(world, plot.id)); - statement.setString(2, player.getUniqueId().toString()); - statement.executeUpdate(); - statement.close(); - } catch (SQLException e) { - e.printStackTrace(); - Logger.add(LogLevel.WARNING, "Failed to remove helper for plot " + plot.id); - } - } - }); - } + /** + * @param id + * @return + */ + private static ArrayList plotHelpers(int id) { + ArrayList l = new ArrayList(); + Statement stmt = null; + try { + stmt = connection.createStatement(); + ResultSet r = stmt + .executeQuery("SELECT `user_uuid` FROM `plot_helpers` WHERE `plot_plot_id` = " + + id); + UUID u; + while (r.next()) { + u = UUID.fromString(r.getString("user_uuid")); + l.add(u); + } + stmt.close(); + } catch (SQLException e) { + Logger.add(LogLevel.WARNING, "Failed to load helpers for plot: " + + id); + e.printStackTrace(); + } + return l; + } - /** - * @param plot - * @param player - */ - public static void removeTrusted(final String world, final Plot plot, final OfflinePlayer player) { - runTask(new Runnable() { - @Override - public void run() { - try { - PreparedStatement statement = connection.prepareStatement("DELETE FROM `plot_trusted` WHERE `plot_plot_id` = ? AND `user_uuid` = ?"); - statement.setInt(1, getId(world, plot.id)); - statement.setString(2, player.getUniqueId().toString()); - statement.executeUpdate(); - statement.close(); - } catch (SQLException e) { - e.printStackTrace(); - Logger.add(LogLevel.WARNING, "Failed to remove trusted user for plot " + plot.id); - } - } - }); - } + /** + * @param id + * @return + */ + private static ArrayList plotTrusted(int id) { + ArrayList l = new ArrayList(); + Statement stmt = null; + try { + stmt = connection.createStatement(); + ResultSet r = stmt + .executeQuery("SELECT `user_uuid` FROM `plot_trusted` WHERE `plot_plot_id` = " + + id); + UUID u; + while (r.next()) { + u = UUID.fromString(r.getString("user_uuid")); + l.add(u); + } + stmt.close(); + } catch (SQLException e) { + Logger.add(LogLevel.WARNING, + "Failed to load trusted users for plot: " + id); + e.printStackTrace(); + } + return l; + } - /** - * @param plot - * @param player - */ - public static void setHelper(final String world, final Plot plot, final OfflinePlayer player) { - runTask(new Runnable() { - @Override - public void run() { - try { - PreparedStatement statement = connection.prepareStatement("INSERT INTO `plot_helpers` (`plot_plot_id`, `user_uuid`) VALUES(?,?)"); - statement.setInt(1, getId(world, plot.id)); - statement.setString(2, player.getUniqueId().toString()); - statement.executeUpdate(); - statement.close(); - } catch (SQLException e) { - Logger.add(LogLevel.WARNING, "Failed to set helper for plot " + plot.id); - e.printStackTrace(); - } - } - }); - } + /** + * @param plot + * @param player + */ + public static void removeHelper(final String world, final Plot plot, + final OfflinePlayer player) { + runTask(new Runnable() { + @Override + public void run() { + try { + PreparedStatement statement = connection + .prepareStatement("DELETE FROM `plot_helpers` WHERE `plot_plot_id` = ? AND `user_uuid` = ?"); + statement.setInt(1, getId(world, plot.id)); + statement.setString(2, player.getUniqueId().toString()); + statement.executeUpdate(); + statement.close(); + } catch (SQLException e) { + e.printStackTrace(); + Logger.add(LogLevel.WARNING, + "Failed to remove helper for plot " + plot.id); + } + } + }); + } - /** - * @param plot - * @param player - */ - public static void setTrusted(final String world, final Plot plot, final OfflinePlayer player) { - runTask(new Runnable() { - @Override - public void run() { - try { - PreparedStatement statement = connection.prepareStatement("INSERT INTO `plot_trusted` (`plot_plot_id`, `user_uuid`) VALUES(?,?)"); - statement.setInt(1, getId(world, plot.id)); - statement.setString(2, player.getUniqueId().toString()); - statement.executeUpdate(); - statement.close(); - } catch (SQLException e) { - Logger.add(LogLevel.WARNING, "Failed to set plot trusted for plot " + plot.id); - e.printStackTrace(); - } - } - }); - } + /** + * @param plot + * @param player + */ + public static void removeTrusted(final String world, final Plot plot, + final OfflinePlayer player) { + runTask(new Runnable() { + @Override + public void run() { + try { + PreparedStatement statement = connection + .prepareStatement("DELETE FROM `plot_trusted` WHERE `plot_plot_id` = ? AND `user_uuid` = ?"); + statement.setInt(1, getId(world, plot.id)); + statement.setString(2, player.getUniqueId().toString()); + statement.executeUpdate(); + statement.close(); + } catch (SQLException e) { + e.printStackTrace(); + Logger.add(LogLevel.WARNING, + "Failed to remove trusted user for plot " + plot.id); + } + } + }); + } - /** - * @param plot - * @param player - */ - public static void removeDenied(final String world, final Plot plot, final OfflinePlayer player) { - runTask(new Runnable() { - @Override - public void run() { - try { - PreparedStatement statement = connection.prepareStatement("DELETE FROM `plot_denied` WHERE `plot_plot_id` = ? AND `user_uuid` = ?"); - statement.setInt(1, getId(world, plot.id)); - statement.setString(2, player.getUniqueId().toString()); - statement.executeUpdate(); - statement.close(); - } catch (SQLException e) { - e.printStackTrace(); - Logger.add(LogLevel.WARNING, "Failed to remove denied for plot " + plot.id); - } - } - }); - } + /** + * @param plot + * @param player + */ + public static void setHelper(final String world, final Plot plot, + final OfflinePlayer player) { + runTask(new Runnable() { + @Override + public void run() { + try { + PreparedStatement statement = connection + .prepareStatement("INSERT INTO `plot_helpers` (`plot_plot_id`, `user_uuid`) VALUES(?,?)"); + statement.setInt(1, getId(world, plot.id)); + statement.setString(2, player.getUniqueId().toString()); + statement.executeUpdate(); + statement.close(); + } catch (SQLException e) { + Logger.add(LogLevel.WARNING, + "Failed to set helper for plot " + plot.id); + e.printStackTrace(); + } + } + }); + } - /** - * @param plot - * @param player - */ - public static void setDenied(final String world, final Plot plot, final OfflinePlayer player) { - runTask(new Runnable() { - @Override - public void run() { - try { - PreparedStatement statement = connection.prepareStatement("INSERT INTO `plot_denied` (`plot_plot_id`, `user_uuid`) VALUES(?,?)"); - statement.setInt(1, getId(world, plot.id)); - statement.setString(2, player.getUniqueId().toString()); - statement.executeUpdate(); - statement.close(); - } catch (SQLException e) { - Logger.add(LogLevel.WARNING, "Failed to set denied for plot " + plot.id); - e.printStackTrace(); - } - } - }); - } + /** + * @param plot + * @param player + */ + public static void setTrusted(final String world, final Plot plot, + final OfflinePlayer player) { + runTask(new Runnable() { + @Override + public void run() { + try { + PreparedStatement statement = connection + .prepareStatement("INSERT INTO `plot_trusted` (`plot_plot_id`, `user_uuid`) VALUES(?,?)"); + statement.setInt(1, getId(world, plot.id)); + statement.setString(2, player.getUniqueId().toString()); + statement.executeUpdate(); + statement.close(); + } catch (SQLException e) { + Logger.add(LogLevel.WARNING, + "Failed to set plot trusted for plot " + plot.id); + e.printStackTrace(); + } + } + }); + } - public static double getRatings(final Plot plot) { - try { - PreparedStatement statement = connection.prepareStatement("SELECT AVG(`rating`) AS `rating` FROM `plot_ratings` WHERE `plot_plot_id` = ? "); - statement.setInt(1, getId(plot.getWorld().getName(), plot.id)); - ResultSet set = statement.executeQuery(); - double rating = 0; - while (set.next()) { - rating = set.getDouble("rating"); - } - statement.close(); - return rating; - } catch (SQLException e) { - Logger.add(LogLevel.WARNING, "Failed to fetch rating for plot " + plot.getId().toString()); - e.printStackTrace(); - } - return 0.0d; - } + /** + * @param plot + * @param player + */ + public static void removeDenied(final String world, final Plot plot, + final OfflinePlayer player) { + runTask(new Runnable() { + @Override + public void run() { + try { + PreparedStatement statement = connection + .prepareStatement("DELETE FROM `plot_denied` WHERE `plot_plot_id` = ? AND `user_uuid` = ?"); + statement.setInt(1, getId(world, plot.id)); + statement.setString(2, player.getUniqueId().toString()); + statement.executeUpdate(); + statement.close(); + } catch (SQLException e) { + e.printStackTrace(); + Logger.add(LogLevel.WARNING, + "Failed to remove denied for plot " + plot.id); + } + } + }); + } + + /** + * @param plot + * @param player + */ + public static void setDenied(final String world, final Plot plot, + final OfflinePlayer player) { + runTask(new Runnable() { + @Override + public void run() { + try { + PreparedStatement statement = connection + .prepareStatement("INSERT INTO `plot_denied` (`plot_plot_id`, `user_uuid`) VALUES(?,?)"); + statement.setInt(1, getId(world, plot.id)); + statement.setString(2, player.getUniqueId().toString()); + statement.executeUpdate(); + statement.close(); + } catch (SQLException e) { + Logger.add(LogLevel.WARNING, + "Failed to set denied for plot " + plot.id); + e.printStackTrace(); + } + } + }); + } + + public static double getRatings(final Plot plot) { + try { + PreparedStatement statement = connection + .prepareStatement("SELECT AVG(`rating`) AS `rating` FROM `plot_ratings` WHERE `plot_plot_id` = ? "); + statement.setInt(1, getId(plot.getWorld().getName(), plot.id)); + ResultSet set = statement.executeQuery(); + double rating = 0; + while (set.next()) { + rating = set.getDouble("rating"); + } + statement.close(); + return rating; + } catch (SQLException e) { + Logger.add(LogLevel.WARNING, "Failed to fetch rating for plot " + + plot.getId().toString()); + e.printStackTrace(); + } + return 0.0d; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/database/Database.java b/PlotSquared/src/com/intellectualcrafters/plot/database/Database.java index 6271e6ff6..88c48556d 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/database/Database.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/database/Database.java @@ -9,90 +9,93 @@ import org.bukkit.plugin.Plugin; /** * Abstract Database class, serves as a base for any connection method (MySQL, * SQLite, etc.) - * + * * @author -_Husky_- * @author tips48 */ public abstract class Database { - /** - * Plugin instance, use for plugin.getDataFolder() - */ - protected Plugin plugin; + /** + * Plugin instance, use for plugin.getDataFolder() + */ + protected Plugin plugin; - /** - * Creates a new Database - * - * @param plugin - * Plugin instance - */ - protected Database(Plugin plugin) { - this.plugin = plugin; - } + /** + * Creates a new Database + * + * @param plugin + * Plugin instance + */ + protected Database(Plugin plugin) { + this.plugin = plugin; + } - /** - * Opens a connection with the database - * - * @return Opened connection - * @throws SQLException - * if the connection can not be opened - * @throws ClassNotFoundException - * if the driver cannot be found - */ - public abstract Connection openConnection() throws SQLException, ClassNotFoundException; + /** + * Opens a connection with the database + * + * @return Opened connection + * @throws SQLException + * if the connection can not be opened + * @throws ClassNotFoundException + * if the driver cannot be found + */ + public abstract Connection openConnection() throws SQLException, + ClassNotFoundException; - /** - * Checks if a connection is open with the database - * - * @return true if the connection is open - * @throws SQLException - * if the connection cannot be checked - */ - public abstract boolean checkConnection() throws SQLException; + /** + * Checks if a connection is open with the database + * + * @return true if the connection is open + * @throws SQLException + * if the connection cannot be checked + */ + public abstract boolean checkConnection() throws SQLException; - /** - * Gets the connection with the database - * - * @return Connection with the database, null if none - */ - public abstract Connection getConnection(); + /** + * Gets the connection with the database + * + * @return Connection with the database, null if none + */ + public abstract Connection getConnection(); - /** - * Closes the connection with the database - * - * @return true if successful - * @throws SQLException - * if the connection cannot be closed - */ - public abstract boolean closeConnection() throws SQLException; + /** + * Closes the connection with the database + * + * @return true if successful + * @throws SQLException + * if the connection cannot be closed + */ + public abstract boolean closeConnection() throws SQLException; - /** - * Executes a SQL Query
- * - * If the connection is closed, it will be opened - * - * @param query - * Query to be run - * @return the results of the query - * @throws SQLException - * If the query cannot be executed - * @throws ClassNotFoundException - * If the driver cannot be found; see {@link #openConnection()} - */ - public abstract ResultSet querySQL(String query) throws SQLException, ClassNotFoundException; + /** + * Executes a SQL Query
+ * + * If the connection is closed, it will be opened + * + * @param query + * Query to be run + * @return the results of the query + * @throws SQLException + * If the query cannot be executed + * @throws ClassNotFoundException + * If the driver cannot be found; see {@link #openConnection()} + */ + public abstract ResultSet querySQL(String query) throws SQLException, + ClassNotFoundException; - /** - * Executes an Update SQL Query
- * See {@link java.sql.Statement#executeUpdate(String)}
- * If the connection is closed, it will be opened - * - * @param query - * Query to be run - * @return Result Code, see {@link java.sql.Statement#executeUpdate(String)} - * @throws SQLException - * If the query cannot be executed - * @throws ClassNotFoundException - * If the driver cannot be found; see {@link #openConnection()} - */ - public abstract int updateSQL(String query) throws SQLException, ClassNotFoundException; + /** + * Executes an Update SQL Query
+ * See {@link java.sql.Statement#executeUpdate(String)}
+ * If the connection is closed, it will be opened + * + * @param query + * Query to be run + * @return Result Code, see {@link java.sql.Statement#executeUpdate(String)} + * @throws SQLException + * If the query cannot be executed + * @throws ClassNotFoundException + * If the driver cannot be found; see {@link #openConnection()} + */ + public abstract int updateSQL(String query) throws SQLException, + ClassNotFoundException; } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/database/MySQL.java b/PlotSquared/src/com/intellectualcrafters/plot/database/MySQL.java index 255aa5e7b..0e70c3843 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/database/MySQL.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/database/MySQL.java @@ -10,98 +10,104 @@ import org.bukkit.plugin.Plugin; /** * Connects to and uses a MySQL database - * + * * @author -_Husky_- * @author tips48 */ public class MySQL extends Database { - private final String user; - private final String database; - private final String password; - private final String port; - private final String hostname; + private final String user; + private final String database; + private final String password; + private final String port; + private final String hostname; - private Connection connection; + private Connection connection; - /** - * Creates a new MySQL instance - * - * @param plugin - * Plugin instance - * @param hostname - * Name of the host - * @param port - * Port number - * @param database - * Database name - * @param username - * Username - * @param password - * Password - */ - public MySQL(Plugin plugin, String hostname, String port, String database, String username, String password) { - super(plugin); - this.hostname = hostname; - this.port = port; - this.database = database; - this.user = username; - this.password = password; - this.connection = null; - } + /** + * Creates a new MySQL instance + * + * @param plugin + * Plugin instance + * @param hostname + * Name of the host + * @param port + * Port number + * @param database + * Database name + * @param username + * Username + * @param password + * Password + */ + public MySQL(Plugin plugin, String hostname, String port, String database, + String username, String password) { + super(plugin); + this.hostname = hostname; + this.port = port; + this.database = database; + this.user = username; + this.password = password; + this.connection = null; + } - @Override - public Connection openConnection() throws SQLException, ClassNotFoundException { - if (checkConnection()) { - return this.connection; - } - Class.forName("com.mysql.jdbc.Driver"); - this.connection = DriverManager.getConnection("jdbc:mysql://" + this.hostname + ":" + this.port + "/" + this.database, this.user, this.password); - return this.connection; - } + @Override + public Connection openConnection() throws SQLException, + ClassNotFoundException { + if (checkConnection()) { + return this.connection; + } + Class.forName("com.mysql.jdbc.Driver"); + this.connection = DriverManager.getConnection("jdbc:mysql://" + + this.hostname + ":" + this.port + "/" + this.database, + this.user, this.password); + return this.connection; + } - @Override - public boolean checkConnection() throws SQLException { - return (this.connection != null) && !this.connection.isClosed(); - } + @Override + public boolean checkConnection() throws SQLException { + return (this.connection != null) && !this.connection.isClosed(); + } - @Override - public Connection getConnection() { - return this.connection; - } + @Override + public Connection getConnection() { + return this.connection; + } - @Override - public boolean closeConnection() throws SQLException { - if (this.connection == null) { - return false; - } - this.connection.close(); - return true; - } + @Override + public boolean closeConnection() throws SQLException { + if (this.connection == null) { + return false; + } + this.connection.close(); + return true; + } - @Override - public ResultSet querySQL(String query) throws SQLException, ClassNotFoundException { - if (checkConnection()) { - openConnection(); - } + @Override + public ResultSet querySQL(String query) throws SQLException, + ClassNotFoundException { + if (checkConnection()) { + openConnection(); + } - Statement statement = this.connection.createStatement(); + Statement statement = this.connection.createStatement(); - ResultSet result = statement.executeQuery(query); + ResultSet result = statement.executeQuery(query); - return result; - } + return result; + } - @Override - public int updateSQL(String query) throws SQLException, ClassNotFoundException { - if (checkConnection()) { - openConnection(); - } + @Override + public int updateSQL(String query) throws SQLException, + ClassNotFoundException { + if (checkConnection()) { + openConnection(); + } - Statement statement = this.connection.createStatement(); + Statement statement = this.connection.createStatement(); - int result = statement.executeUpdate(query); + int result = statement.executeUpdate(query); - return result; - } + return result; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/database/PlotMeConverter.java b/PlotSquared/src/com/intellectualcrafters/plot/database/PlotMeConverter.java index 37c4cc8e5..04e804e01 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/database/PlotMeConverter.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/database/PlotMeConverter.java @@ -1,7 +1,5 @@ package com.intellectualcrafters.plot.database; -import java.io.File; -import java.io.FilenameFilter; import java.io.PrintStream; import java.lang.reflect.Field; import java.util.ArrayList; @@ -25,130 +23,190 @@ import com.worldcretornica.plotme.PlotManager; */ public class PlotMeConverter { - private PlotMain plugin; + private PlotMain plugin; - public PlotMeConverter(PlotMain plugin) { - this.plugin = plugin; - } + public PlotMeConverter(PlotMain plugin) { + this.plugin = plugin; + } - public void runAsync() throws Exception { + public void runAsync() throws Exception { - final PrintStream stream = new PrintStream("converter_log.txt"); + final PrintStream stream = new PrintStream("converter_log.txt"); - Bukkit.getScheduler().runTaskAsynchronously(this.plugin, new Runnable() { - @Override - public void run() { - PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Conversion has started"); - PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Caching playerdata..."); - ArrayList createdPlots = new ArrayList(); - boolean online = Bukkit.getServer().getOnlineMode(); - for (World world : Bukkit.getWorlds()) { - HashMap plots = PlotManager.getPlots(world); - if (plots != null) { - PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Processing '" + plots.size() + "' plots for world '" + world.getName() + "'"); + Bukkit.getScheduler().runTaskAsynchronously(this.plugin, + new Runnable() { + @Override + public void run() { + PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Conversion has started"); + PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Caching playerdata..."); + ArrayList createdPlots = new ArrayList(); + boolean online = Bukkit.getServer().getOnlineMode(); + for (World world : Bukkit.getWorlds()) { + HashMap plots = PlotManager + .getPlots(world); + if (plots != null) { + PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Processing '" + + plots.size() + + "' plots for world '" + + world.getName() + "'"); - PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Converting " + plots.size() + " plots for '" + world.toString() + "'..."); - for (Plot plot : plots.values()) { - ArrayList psAdded = new ArrayList<>(); - ArrayList psTrusted = new ArrayList<>(); - ArrayList psDenied = new ArrayList<>(); - if (world == null) { - world = Bukkit.getWorld("world"); - } - long eR3040bl230 = 22392948l; - try { - if (online) { - PlayerList denied = null; - PlayerList added = null; - Field fAdded = plot.getClass().getDeclaredField("allowed"); - Field fDenied = plot.getClass().getDeclaredField("denied"); - fAdded.setAccessible(true); - fDenied.setAccessible(true); - added = (PlayerList) fAdded.get(plot); - denied = (PlayerList) fDenied.get(plot); - for (Map.Entry set : added.getAllPlayers().entrySet()) { - if ((set.getValue() != null) || set.getKey().equals("*")) { - if (set.getKey().equalsIgnoreCase("*") || set.getValue().toString().equals("*")) { - psAdded.add(DBFunc.everyone); - continue; - } - } - if (set.getValue() != null) { - psAdded.add(set.getValue()); - } - } - for (Map.Entry set : denied.getAllPlayers().entrySet()) { - if ((set.getValue() != null) || set.getKey().equals("*")) { - if (set.getKey().equals("*") || set.getValue().toString().equals("*")) { - psDenied.add(DBFunc.everyone); - continue; - } - } - if (set.getValue() != null) { - psDenied.add(set.getValue()); - } - } - } else { - for (String user : plot.getAllowed().split(",")) { - if (user.equals("*")) { - psAdded.add(DBFunc.everyone); - } else { - UUID uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + user).getBytes(Charsets.UTF_8)); - psAdded.add(uuid); - } - } - try { - for (String user : plot.getDenied().split(",")) { - if (user.equals("*")) { - psDenied.add(DBFunc.everyone); - } else { - UUID uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + user).getBytes(Charsets.UTF_8)); - psDenied.add(uuid); - } - } - } catch (Throwable e) { + PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Converting " + + plots.size() + + " plots for '" + + world.toString() + "'..."); + for (Plot plot : plots.values()) { + ArrayList psAdded = new ArrayList<>(); + ArrayList psTrusted = new ArrayList<>(); + ArrayList psDenied = new ArrayList<>(); + if (world == null) { + world = Bukkit.getWorld("world"); + } + long eR3040bl230 = 22392948l; + try { + if (online) { + PlayerList denied = null; + PlayerList added = null; + Field fAdded = plot + .getClass() + .getDeclaredField("allowed"); + Field fDenied = plot.getClass() + .getDeclaredField("denied"); + fAdded.setAccessible(true); + fDenied.setAccessible(true); + added = (PlayerList) fAdded + .get(plot); + denied = (PlayerList) fDenied + .get(plot); + for (Map.Entry set : added + .getAllPlayers().entrySet()) { + if ((set.getValue() != null) + || set.getKey().equals( + "*")) { + if (set.getKey() + .equalsIgnoreCase( + "*") + || set.getValue() + .toString() + .equals("*")) { + psAdded.add(DBFunc.everyone); + continue; + } + } + if (set.getValue() != null) { + psAdded.add(set.getValue()); + } + } + for (Map.Entry set : denied + .getAllPlayers().entrySet()) { + if ((set.getValue() != null) + || set.getKey().equals( + "*")) { + if (set.getKey() + .equals("*") + || set.getValue() + .toString() + .equals("*")) { + psDenied.add(DBFunc.everyone); + continue; + } + } + if (set.getValue() != null) { + psDenied.add(set.getValue()); + } + } + } else { + for (String user : plot + .getAllowed().split(",")) { + if (user.equals("*")) { + psAdded.add(DBFunc.everyone); + } else { + UUID uuid = UUID + .nameUUIDFromBytes(("OfflinePlayer:" + user) + .getBytes(Charsets.UTF_8)); + psAdded.add(uuid); + } + } + try { + for (String user : plot + .getDenied().split(",")) { + if (user.equals("*")) { + psDenied.add(DBFunc.everyone); + } else { + UUID uuid = UUID + .nameUUIDFromBytes(("OfflinePlayer:" + user) + .getBytes(Charsets.UTF_8)); + psDenied.add(uuid); + } + } + } catch (Throwable e) { - } - } - } catch (Throwable e) { - e.printStackTrace(); - eR3040bl230 = 232000499888388747l; - } finally { - eR3040bl230 = 232999304998392004l; - } - stream.println(eR3040bl230); - PlotId id = new PlotId(Integer.parseInt(plot.id.split(";")[0]), Integer.parseInt(plot.id.split(";")[1])); - com.intellectualcrafters.plot.Plot pl = null; - if (online) { - pl = new com.intellectualcrafters.plot.Plot(id, plot.getOwnerId(), plot.getBiome(), psAdded, psTrusted, psDenied, false, 8000l, false, "", PlotHomePosition.DEFAULT, null, world.getName(), new boolean[] { false, false, false, false }); - } else { - String owner = plot.getOwner(); - pl = new com.intellectualcrafters.plot.Plot(id, UUID.nameUUIDFromBytes(("OfflinePlayer:" + owner).getBytes(Charsets.UTF_8)), plot.getBiome(), psAdded, psTrusted, psDenied, false, 8000l, false, "", PlotHomePosition.DEFAULT, null, world.getName(), new boolean[] { false, false, false, false }); - } + } + } + } catch (Throwable e) { + e.printStackTrace(); + eR3040bl230 = 232000499888388747l; + } finally { + eR3040bl230 = 232999304998392004l; + } + stream.println(eR3040bl230); + PlotId id = new PlotId( + Integer.parseInt(plot.id.split(";")[0]), + Integer.parseInt(plot.id.split(";")[1])); + com.intellectualcrafters.plot.Plot pl = null; + if (online) { + pl = new com.intellectualcrafters.plot.Plot( + id, plot.getOwnerId(), plot + .getBiome(), psAdded, + psTrusted, psDenied, false, + 8000l, false, "", + PlotHomePosition.DEFAULT, null, + world.getName(), new boolean[] { + false, false, false, + false }); + } else { + String owner = plot.getOwner(); + pl = new com.intellectualcrafters.plot.Plot( + id, + UUID.nameUUIDFromBytes(("OfflinePlayer:" + owner) + .getBytes(Charsets.UTF_8)), + plot.getBiome(), psAdded, + psTrusted, psDenied, false, + 8000l, false, "", + PlotHomePosition.DEFAULT, null, + world.getName(), new boolean[] { + false, false, false, + false }); + } - // TODO createPlot doesn't add helpers / denied - // users - if (pl != null) { - createdPlots.add(pl); - } - } - } - } - PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Creating plot DB"); - DBFunc.createPlots(createdPlots); - PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Creating settings/helpers DB"); - DBFunc.createAllSettingsAndHelpers(createdPlots); - stream.close(); - PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Conversion has finished"); - // TODO disable PlotMe -> Unload all plot worlds, change the - // generator, restart the server automatically - // Possibly use multiverse / multiworld if it's to difficult - // modifying a world's generator while the server is running - // Should really do that? Would seem pretty bad from our side + - // bukkit wouldn't approve + // TODO createPlot doesn't add helpers / + // denied + // users + if (pl != null) { + createdPlots.add(pl); + } + } + } + } + PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Creating plot DB"); + DBFunc.createPlots(createdPlots); + PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Creating settings/helpers DB"); + DBFunc.createAllSettingsAndHelpers(createdPlots); + stream.close(); + PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Conversion has finished"); + // TODO disable PlotMe -> Unload all plot worlds, change + // the + // generator, restart the server automatically + // Possibly use multiverse / multiworld if it's to + // difficult + // modifying a world's generator while the server is + // running + // Should really do that? Would seem pretty bad from our + // side + + // bukkit wouldn't approve - Bukkit.getPluginManager().disablePlugin(PlotMeConverter.this.plugin); - } - }); - } + Bukkit.getPluginManager().disablePlugin( + PlotMeConverter.this.plugin); + } + }); + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/database/SQLite.java b/PlotSquared/src/com/intellectualcrafters/plot/database/SQLite.java index fe811a5ba..78402e4f6 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/database/SQLite.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/database/SQLite.java @@ -13,91 +13,97 @@ import org.bukkit.plugin.Plugin; /** * Connects to and uses a SQLite database - * + * * @author Citymonstret * @author tips48 */ public class SQLite extends Database { - private Connection connection; - private final String dbLocation; + private Connection connection; + private final String dbLocation; - /** - * Creates a new SQLite instance - * - * @param plugin - * Plugin instance - * @param dbLocation - * Location of the Database (Must end in .db) - */ - public SQLite(Plugin plugin, String dbLocation) { - super(plugin); - this.dbLocation = dbLocation; - } + /** + * Creates a new SQLite instance + * + * @param plugin + * Plugin instance + * @param dbLocation + * Location of the Database (Must end in .db) + */ + public SQLite(Plugin plugin, String dbLocation) { + super(plugin); + this.dbLocation = dbLocation; + } - @Override - public Connection openConnection() throws SQLException, ClassNotFoundException { - if (checkConnection()) { - return this.connection; - } - if (!this.plugin.getDataFolder().exists()) { - this.plugin.getDataFolder().mkdirs(); - } - File file = new File(this.plugin.getDataFolder(), this.dbLocation); - if (!(file.exists())) { - try { - file.createNewFile(); - } catch (IOException e) { - this.plugin.getLogger().log(Level.SEVERE, "Unable to create database!"); - } - } - Class.forName("org.sqlite.JDBC"); - this.connection = DriverManager.getConnection("jdbc:sqlite:" + this.plugin.getDataFolder().toPath().toString() + "/" + this.dbLocation); - return this.connection; - } + @Override + public Connection openConnection() throws SQLException, + ClassNotFoundException { + if (checkConnection()) { + return this.connection; + } + if (!this.plugin.getDataFolder().exists()) { + this.plugin.getDataFolder().mkdirs(); + } + File file = new File(this.plugin.getDataFolder(), this.dbLocation); + if (!(file.exists())) { + try { + file.createNewFile(); + } catch (IOException e) { + this.plugin.getLogger().log(Level.SEVERE, + "Unable to create database!"); + } + } + Class.forName("org.sqlite.JDBC"); + this.connection = DriverManager.getConnection("jdbc:sqlite:" + + this.plugin.getDataFolder().toPath().toString() + "/" + + this.dbLocation); + return this.connection; + } - @Override - public boolean checkConnection() throws SQLException { - return (this.connection != null) && !this.connection.isClosed(); - } + @Override + public boolean checkConnection() throws SQLException { + return (this.connection != null) && !this.connection.isClosed(); + } - @Override - public Connection getConnection() { - return this.connection; - } + @Override + public Connection getConnection() { + return this.connection; + } - @Override - public boolean closeConnection() throws SQLException { - if (this.connection == null) { - return false; - } - this.connection.close(); - return true; - } + @Override + public boolean closeConnection() throws SQLException { + if (this.connection == null) { + return false; + } + this.connection.close(); + return true; + } - @Override - public ResultSet querySQL(String query) throws SQLException, ClassNotFoundException { - if (checkConnection()) { - openConnection(); - } + @Override + public ResultSet querySQL(String query) throws SQLException, + ClassNotFoundException { + if (checkConnection()) { + openConnection(); + } - Statement statement = this.connection.createStatement(); + Statement statement = this.connection.createStatement(); - ResultSet result = statement.executeQuery(query); + ResultSet result = statement.executeQuery(query); - return result; - } + return result; + } - @Override - public int updateSQL(String query) throws SQLException, ClassNotFoundException { - if (checkConnection()) { - openConnection(); - } + @Override + public int updateSQL(String query) throws SQLException, + ClassNotFoundException { + if (checkConnection()) { + openConnection(); + } - Statement statement = this.connection.createStatement(); + Statement statement = this.connection.createStatement(); - int result = statement.executeUpdate(query); + int result = statement.executeUpdate(query); - return result; - } + return result; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/events/PlayerClaimPlotEvent.java b/PlotSquared/src/com/intellectualcrafters/plot/events/PlayerClaimPlotEvent.java index 1a6c554b3..d4bc95b41 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/events/PlayerClaimPlotEvent.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/events/PlayerClaimPlotEvent.java @@ -20,47 +20,47 @@ import com.intellectualcrafters.plot.Plot; * Created by Citymonstret on 2014-08-09. */ public class PlayerClaimPlotEvent extends PlayerEvent implements Cancellable { - private static HandlerList handlers = new HandlerList(); - private boolean cancelled; + private static HandlerList handlers = new HandlerList(); + private boolean cancelled; - private Plot plot; + private Plot plot; - /** - * PlayerClaimPlotEvent: Called when a plot is claimed - * - * @param player - * @param plot - */ - public PlayerClaimPlotEvent(Player player, Plot plot) { - super(player); - this.plot = plot; - } + /** + * PlayerClaimPlotEvent: Called when a plot is claimed + * + * @param player + * @param plot + */ + public PlayerClaimPlotEvent(Player player, Plot plot) { + super(player); + this.plot = plot; + } - /** - * Get the plot involved - * - * @return Plot - */ - public Plot getPlot() { - return this.plot; - } + /** + * Get the plot involved + * + * @return Plot + */ + public Plot getPlot() { + return this.plot; + } - public static HandlerList getHandlerList() { - return handlers; - } + public static HandlerList getHandlerList() { + return handlers; + } - @Override - public HandlerList getHandlers() { - return handlers; - } + @Override + public HandlerList getHandlers() { + return handlers; + } - @Override - public boolean isCancelled() { - return this.cancelled; - } + @Override + public boolean isCancelled() { + return this.cancelled; + } - @Override - public void setCancelled(boolean b) { - this.cancelled = b; - } + @Override + public void setCancelled(boolean b) { + this.cancelled = b; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/events/PlayerEnterPlotEvent.java b/PlotSquared/src/com/intellectualcrafters/plot/events/PlayerEnterPlotEvent.java index b1eca0e82..ecb53d4e5 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/events/PlayerEnterPlotEvent.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/events/PlayerEnterPlotEvent.java @@ -11,33 +11,33 @@ import com.intellectualcrafters.plot.Plot; */ public class PlayerEnterPlotEvent extends PlayerEvent { - private static HandlerList handlers = new HandlerList(); + private static HandlerList handlers = new HandlerList(); - private Plot plot; + private Plot plot; - /** - * PlayerEnterPlotEvent: Called when a player leaves a plot - * - * @param player - * @param plot - */ - public PlayerEnterPlotEvent(Player player, Plot plot) { - super(player); - this.plot = plot; - } + /** + * PlayerEnterPlotEvent: Called when a player leaves a plot + * + * @param player + * @param plot + */ + public PlayerEnterPlotEvent(Player player, Plot plot) { + super(player); + this.plot = plot; + } - /** - * Get the plot involved - * - * @return Plot - */ - public Plot getPlot() { - return this.plot; - } + /** + * Get the plot involved + * + * @return Plot + */ + public Plot getPlot() { + return this.plot; + } - @Override - public HandlerList getHandlers() { - return handlers; - } + @Override + public HandlerList getHandlers() { + return handlers; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/events/PlayerLeavePlotEvent.java b/PlotSquared/src/com/intellectualcrafters/plot/events/PlayerLeavePlotEvent.java index 2a54dbdcc..de87d4771 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/events/PlayerLeavePlotEvent.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/events/PlayerLeavePlotEvent.java @@ -10,32 +10,32 @@ import com.intellectualcrafters.plot.Plot; * Created by Citymonstret on 2014-08-16. */ public class PlayerLeavePlotEvent extends PlayerEvent { - private static HandlerList handlers = new HandlerList(); + private static HandlerList handlers = new HandlerList(); - private Plot plot; + private Plot plot; - /** - * PlayerLeavePlotEvent: Called when a player leaves a plot - * - * @param player - * @param plot - */ - public PlayerLeavePlotEvent(Player player, Plot plot) { - super(player); - this.plot = plot; - } + /** + * PlayerLeavePlotEvent: Called when a player leaves a plot + * + * @param player + * @param plot + */ + public PlayerLeavePlotEvent(Player player, Plot plot) { + super(player); + this.plot = plot; + } - /** - * Get the plot involved - * - * @return Plot - */ - public Plot getPlot() { - return this.plot; - } + /** + * Get the plot involved + * + * @return Plot + */ + public Plot getPlot() { + return this.plot; + } - @Override - public HandlerList getHandlers() { - return handlers; - } + @Override + public HandlerList getHandlers() { + return handlers; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/events/PlayerPlotDeniedEvent.java b/PlotSquared/src/com/intellectualcrafters/plot/events/PlayerPlotDeniedEvent.java index d53fb32ba..f6c90eeb0 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/events/PlayerPlotDeniedEvent.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/events/PlayerPlotDeniedEvent.java @@ -12,67 +12,68 @@ import com.intellectualcrafters.plot.Plot; * Created by Citymonstret on 2014-08-16. */ public class PlayerPlotDeniedEvent extends Event { - private static HandlerList handlers = new HandlerList(); + private static HandlerList handlers = new HandlerList(); - private Plot plot; - private Player initiator; - private boolean added; - private UUID player; + private Plot plot; + private Player initiator; + private boolean added; + private UUID player; - /** - * PlayerPlotDeniedEvent: Called when the denied UUID list is modified for a - * plot - * - * @param initiator - * @param plot - * @param player - * @param added - */ - public PlayerPlotDeniedEvent(Player initiator, Plot plot, UUID player, boolean added) { - this.initiator = initiator; - this.plot = plot; - this.added = added; - this.player = player; - } + /** + * PlayerPlotDeniedEvent: Called when the denied UUID list is modified for a + * plot + * + * @param initiator + * @param plot + * @param player + * @param added + */ + public PlayerPlotDeniedEvent(Player initiator, Plot plot, UUID player, + boolean added) { + this.initiator = initiator; + this.plot = plot; + this.added = added; + this.player = player; + } - /** - * If a user was added - * - * @return boolean - */ - public boolean wasAdded() { - return this.added; - } + /** + * If a user was added + * + * @return boolean + */ + public boolean wasAdded() { + return this.added; + } - /** - * The player added/removed - * - * @return UUID - */ - public UUID getPlayer() { - return this.player; - } + /** + * The player added/removed + * + * @return UUID + */ + public UUID getPlayer() { + return this.player; + } - /** - * The plot involved - * - * @return Plot - */ - public Plot getPlot() { - return this.plot; - } + /** + * The plot involved + * + * @return Plot + */ + public Plot getPlot() { + return this.plot; + } - /** - * The player initiating the action - * - * @return Player - */ - public Player getInitiator() { - return this.initiator; - } + /** + * The player initiating the action + * + * @return Player + */ + public Player getInitiator() { + return this.initiator; + } - @Override - public HandlerList getHandlers() { - return handlers; - } + @Override + public HandlerList getHandlers() { + return handlers; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/events/PlayerPlotHelperEvent.java b/PlotSquared/src/com/intellectualcrafters/plot/events/PlayerPlotHelperEvent.java index 2f111e425..d4d24c4d2 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/events/PlayerPlotHelperEvent.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/events/PlayerPlotHelperEvent.java @@ -12,66 +12,67 @@ import com.intellectualcrafters.plot.Plot; * Created by Citymonstret on 2014-08-16. */ public class PlayerPlotHelperEvent extends Event { - private static HandlerList handlers = new HandlerList(); + private static HandlerList handlers = new HandlerList(); - private Plot plot; - private Player initiator; - private boolean added; - private UUID player; + private Plot plot; + private Player initiator; + private boolean added; + private UUID player; - /** - * PlayerPlotHelperEvent: Called when a plot helper is added/removed - * - * @param initiator - * @param plot - * @param player - * @param added - */ - public PlayerPlotHelperEvent(Player initiator, Plot plot, UUID player, boolean added) { - this.initiator = initiator; - this.plot = plot; - this.added = added; - this.player = player; - } + /** + * PlayerPlotHelperEvent: Called when a plot helper is added/removed + * + * @param initiator + * @param plot + * @param player + * @param added + */ + public PlayerPlotHelperEvent(Player initiator, Plot plot, UUID player, + boolean added) { + this.initiator = initiator; + this.plot = plot; + this.added = added; + this.player = player; + } - /** - * If a player was added - * - * @return boolean - */ - public boolean wasAdded() { - return this.added; - } + /** + * If a player was added + * + * @return boolean + */ + public boolean wasAdded() { + return this.added; + } - /** - * The UUID added/removed - * - * @return UUID - */ - public UUID getPlayer() { - return this.player; - } + /** + * The UUID added/removed + * + * @return UUID + */ + public UUID getPlayer() { + return this.player; + } - /** - * The plot involved - * - * @return Plot - */ - public Plot getPlot() { - return this.plot; - } + /** + * The plot involved + * + * @return Plot + */ + public Plot getPlot() { + return this.plot; + } - /** - * The player initiating the action - * - * @return Player - */ - public Player getInitiator() { - return this.initiator; - } + /** + * The player initiating the action + * + * @return Player + */ + public Player getInitiator() { + return this.initiator; + } - @Override - public HandlerList getHandlers() { - return handlers; - } + @Override + public HandlerList getHandlers() { + return handlers; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/events/PlayerPlotTrustedEvent.java b/PlotSquared/src/com/intellectualcrafters/plot/events/PlayerPlotTrustedEvent.java index 59cf68ca7..bacb8804f 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/events/PlayerPlotTrustedEvent.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/events/PlayerPlotTrustedEvent.java @@ -12,66 +12,67 @@ import com.intellectualcrafters.plot.Plot; * Created by Citymonstret on 2014-08-16. */ public class PlayerPlotTrustedEvent extends Event { - private static HandlerList handlers = new HandlerList(); + private static HandlerList handlers = new HandlerList(); - private Plot plot; - private Player initiator; - private boolean added; - private UUID player; + private Plot plot; + private Player initiator; + private boolean added; + private UUID player; - /** - * PlayerPlotTrustedEvent: Called when a plot trusted user is added/removed - * - * @param initiator - * @param plot - * @param player - * @param added - */ - public PlayerPlotTrustedEvent(Player initiator, Plot plot, UUID player, boolean added) { - this.initiator = initiator; - this.plot = plot; - this.added = added; - this.player = player; - } + /** + * PlayerPlotTrustedEvent: Called when a plot trusted user is added/removed + * + * @param initiator + * @param plot + * @param player + * @param added + */ + public PlayerPlotTrustedEvent(Player initiator, Plot plot, UUID player, + boolean added) { + this.initiator = initiator; + this.plot = plot; + this.added = added; + this.player = player; + } - /** - * If a player was added - * - * @return boolean - */ - public boolean wasAdded() { - return this.added; - } + /** + * If a player was added + * + * @return boolean + */ + public boolean wasAdded() { + return this.added; + } - /** - * The UUID added/removed - * - * @return UUID - */ - public UUID getPlayer() { - return this.player; - } + /** + * The UUID added/removed + * + * @return UUID + */ + public UUID getPlayer() { + return this.player; + } - /** - * The plot involved - * - * @return Plot - */ - public Plot getPlot() { - return this.plot; - } + /** + * The plot involved + * + * @return Plot + */ + public Plot getPlot() { + return this.plot; + } - /** - * The player initiating the action - * - * @return Player - */ - public Player getInitiator() { - return this.initiator; - } + /** + * The player initiating the action + * + * @return Player + */ + public Player getInitiator() { + return this.initiator; + } - @Override - public HandlerList getHandlers() { - return handlers; - } + @Override + public HandlerList getHandlers() { + return handlers; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/events/PlayerTeleportToPlotEvent.java b/PlotSquared/src/com/intellectualcrafters/plot/events/PlayerTeleportToPlotEvent.java index e07f423fb..3ca03053b 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/events/PlayerTeleportToPlotEvent.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/events/PlayerTeleportToPlotEvent.java @@ -20,61 +20,62 @@ import com.intellectualcrafters.plot.Plot; /** * Called when a player teleports to a plot */ -public class PlayerTeleportToPlotEvent extends PlayerEvent implements Cancellable { - private static final HandlerList handlers = new HandlerList(); +public class PlayerTeleportToPlotEvent extends PlayerEvent implements + Cancellable { + private static final HandlerList handlers = new HandlerList(); - private Location from; - private Plot plot; + private Location from; + private Plot plot; - private boolean cancelled; + private boolean cancelled; - /** - * PlayerTeleportToPlotEvent: Called when a player teleports to a plot - * - * @param player - * @param from - * @param plot - */ - public PlayerTeleportToPlotEvent(Player player, Location from, Plot plot) { - super(player); - this.from = from; - this.plot = plot; - } + /** + * PlayerTeleportToPlotEvent: Called when a player teleports to a plot + * + * @param player + * @param from + * @param plot + */ + public PlayerTeleportToPlotEvent(Player player, Location from, Plot plot) { + super(player); + this.from = from; + this.plot = plot; + } - @Override - public HandlerList getHandlers() { - return handlers; - } + @Override + public HandlerList getHandlers() { + return handlers; + } - /** - * Get the from location - * - * @return Location - */ - public Location getFrom() { - return this.from; - } + /** + * Get the from location + * + * @return Location + */ + public Location getFrom() { + return this.from; + } - /** - * Get the plot involved - * - * @return Plot - */ - public Plot getPlot() { - return this.plot; - } + /** + * Get the plot involved + * + * @return Plot + */ + public Plot getPlot() { + return this.plot; + } - public static HandlerList getHandlerList() { - return handlers; - } + public static HandlerList getHandlerList() { + return handlers; + } - @Override - public boolean isCancelled() { - return this.cancelled; - } + @Override + public boolean isCancelled() { + return this.cancelled; + } - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/events/PlotClearEvent.java b/PlotSquared/src/com/intellectualcrafters/plot/events/PlotClearEvent.java index 330947c93..5b6a6751c 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/events/PlotClearEvent.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/events/PlotClearEvent.java @@ -19,57 +19,57 @@ import com.intellectualcrafters.plot.PlotId; * Called when a plot is cleared */ public class PlotClearEvent extends Event implements Cancellable { - private static HandlerList handlers = new HandlerList(); - private boolean cancelled; + private static HandlerList handlers = new HandlerList(); + private boolean cancelled; - private PlotId id; - private String world; + private PlotId id; + private String world; - /** - * PlotDeleteEvent: Called when a plot is cleared - * - * @param world - * @param id - */ - public PlotClearEvent(String world, PlotId id) { - this.id = id; - this.world = world; - } + /** + * PlotDeleteEvent: Called when a plot is cleared + * + * @param world + * @param id + */ + public PlotClearEvent(String world, PlotId id) { + this.id = id; + this.world = world; + } - /** - * Get the PlotId - * - * @return PlotId - */ - public PlotId getPlotId() { - return this.id; - } + /** + * Get the PlotId + * + * @return PlotId + */ + public PlotId getPlotId() { + return this.id; + } - /** - * Get the world name - * - * @return String - */ - public String getWorld() { - return this.world; - } + /** + * Get the world name + * + * @return String + */ + public String getWorld() { + return this.world; + } - public static HandlerList getHandlerList() { - return handlers; - } + public static HandlerList getHandlerList() { + return handlers; + } - @Override - public HandlerList getHandlers() { - return handlers; - } + @Override + public HandlerList getHandlers() { + return handlers; + } - @Override - public boolean isCancelled() { - return this.cancelled; - } + @Override + public boolean isCancelled() { + return this.cancelled; + } - @Override - public void setCancelled(boolean b) { - this.cancelled = b; - } + @Override + public void setCancelled(boolean b) { + this.cancelled = b; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/events/PlotDeleteEvent.java b/PlotSquared/src/com/intellectualcrafters/plot/events/PlotDeleteEvent.java index caa3a6e64..106af2d87 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/events/PlotDeleteEvent.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/events/PlotDeleteEvent.java @@ -19,57 +19,57 @@ import com.intellectualcrafters.plot.PlotId; * Called when a plot is deleted */ public class PlotDeleteEvent extends Event implements Cancellable { - private static HandlerList handlers = new HandlerList(); - private boolean cancelled; + private static HandlerList handlers = new HandlerList(); + private boolean cancelled; - private PlotId id; - private String world; + private PlotId id; + private String world; - /** - * PlotDeleteEvent: Called when a plot is deleted - * - * @param world - * @param id - */ - public PlotDeleteEvent(String world, PlotId id) { - this.id = id; - this.world = world; - } + /** + * PlotDeleteEvent: Called when a plot is deleted + * + * @param world + * @param id + */ + public PlotDeleteEvent(String world, PlotId id) { + this.id = id; + this.world = world; + } - /** - * Get the PlotId - * - * @return PlotId - */ - public PlotId getPlotId() { - return this.id; - } + /** + * Get the PlotId + * + * @return PlotId + */ + public PlotId getPlotId() { + return this.id; + } - /** - * Get the world name - * - * @return String - */ - public String getWorld() { - return this.world; - } + /** + * Get the world name + * + * @return String + */ + public String getWorld() { + return this.world; + } - public static HandlerList getHandlerList() { - return handlers; - } + public static HandlerList getHandlerList() { + return handlers; + } - @Override - public HandlerList getHandlers() { - return handlers; - } + @Override + public HandlerList getHandlers() { + return handlers; + } - @Override - public boolean isCancelled() { - return this.cancelled; - } + @Override + public boolean isCancelled() { + return this.cancelled; + } - @Override - public void setCancelled(boolean b) { - this.cancelled = b; - } + @Override + public void setCancelled(boolean b) { + this.cancelled = b; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/events/PlotFlagAddEvent.java b/PlotSquared/src/com/intellectualcrafters/plot/events/PlotFlagAddEvent.java index 0204b2f1b..b3ba5a98c 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/events/PlotFlagAddEvent.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/events/PlotFlagAddEvent.java @@ -20,57 +20,57 @@ import com.intellectualcrafters.plot.Plot; * Called when a Flag is added to a plot */ public class PlotFlagAddEvent extends Event implements Cancellable { - private static HandlerList handlers = new HandlerList(); - private boolean cancelled; + private static HandlerList handlers = new HandlerList(); + private boolean cancelled; - private Plot plot; - private Flag flag; + private Plot plot; + private Flag flag; - /** - * PlotFlagAddEvent: Called when a Flag is added to a plot - * - * @param flag - * @param plot - */ - public PlotFlagAddEvent(Flag flag, Plot plot) { - this.plot = plot; - this.flag = flag; - } + /** + * PlotFlagAddEvent: Called when a Flag is added to a plot + * + * @param flag + * @param plot + */ + public PlotFlagAddEvent(Flag flag, Plot plot) { + this.plot = plot; + this.flag = flag; + } - /** - * Get the plot involved - * - * @return Plot - */ - public Plot getPlot() { - return this.plot; - } + /** + * Get the plot involved + * + * @return Plot + */ + public Plot getPlot() { + return this.plot; + } - /** - * Get the flag involved - * - * @return Flag - */ - public Flag getFlag() { - return this.flag; - } + /** + * Get the flag involved + * + * @return Flag + */ + public Flag getFlag() { + return this.flag; + } - public static HandlerList getHandlerList() { - return handlers; - } + public static HandlerList getHandlerList() { + return handlers; + } - @Override - public HandlerList getHandlers() { - return handlers; - } + @Override + public HandlerList getHandlers() { + return handlers; + } - @Override - public boolean isCancelled() { - return this.cancelled; - } + @Override + public boolean isCancelled() { + return this.cancelled; + } - @Override - public void setCancelled(boolean b) { - this.cancelled = b; - } + @Override + public void setCancelled(boolean b) { + this.cancelled = b; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/events/PlotFlagRemoveEvent.java b/PlotSquared/src/com/intellectualcrafters/plot/events/PlotFlagRemoveEvent.java index 0f3007484..5c9724df2 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/events/PlotFlagRemoveEvent.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/events/PlotFlagRemoveEvent.java @@ -20,57 +20,57 @@ import com.intellectualcrafters.plot.Plot; * Called when a flag is removed from a plot */ public class PlotFlagRemoveEvent extends Event implements Cancellable { - private static HandlerList handlers = new HandlerList(); - private boolean cancelled; + private static HandlerList handlers = new HandlerList(); + private boolean cancelled; - private Plot plot; - private Flag flag; + private Plot plot; + private Flag flag; - /** - * PlotFlagRemoveEvent: Called when a flag is removed from a plot - * - * @param flag - * @param plot - */ - public PlotFlagRemoveEvent(Flag flag, Plot plot) { - this.plot = plot; - this.flag = flag; - } + /** + * PlotFlagRemoveEvent: Called when a flag is removed from a plot + * + * @param flag + * @param plot + */ + public PlotFlagRemoveEvent(Flag flag, Plot plot) { + this.plot = plot; + this.flag = flag; + } - /** - * Get the plot involved - * - * @return Plot - */ - public Plot getPlot() { - return this.plot; - } + /** + * Get the plot involved + * + * @return Plot + */ + public Plot getPlot() { + return this.plot; + } - /** - * Get the flag involved - * - * @return Flag - */ - public Flag getFlag() { - return this.flag; - } + /** + * Get the flag involved + * + * @return Flag + */ + public Flag getFlag() { + return this.flag; + } - public static HandlerList getHandlerList() { - return handlers; - } + public static HandlerList getHandlerList() { + return handlers; + } - @Override - public HandlerList getHandlers() { - return handlers; - } + @Override + public HandlerList getHandlers() { + return handlers; + } - @Override - public boolean isCancelled() { - return this.cancelled; - } + @Override + public boolean isCancelled() { + return this.cancelled; + } - @Override - public void setCancelled(boolean b) { - this.cancelled = b; - } + @Override + public void setCancelled(boolean b) { + this.cancelled = b; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/events/PlotMergeEvent.java b/PlotSquared/src/com/intellectualcrafters/plot/events/PlotMergeEvent.java index b836a5946..c04af33b4 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/events/PlotMergeEvent.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/events/PlotMergeEvent.java @@ -23,61 +23,61 @@ import com.intellectualcrafters.plot.PlotId; * Created by Citymonstret on 2014-08-09. */ public class PlotMergeEvent extends Event implements Cancellable { - private static HandlerList handlers = new HandlerList(); - private boolean cancelled; + private static HandlerList handlers = new HandlerList(); + private boolean cancelled; - private ArrayList plots; - private Plot plot; - private World world; + private ArrayList plots; + private Plot plot; + private World world; - /** - * PlotMergeEvent: Called when plots are merged - * - * @param player - * @param plot - */ - public PlotMergeEvent(World world, Plot plot, ArrayList plots) { - this.plots = plots; - } + /** + * PlotMergeEvent: Called when plots are merged + * + * @param player + * @param plot + */ + public PlotMergeEvent(World world, Plot plot, ArrayList plots) { + this.plots = plots; + } - /** - * Get the plots being added; - * - * @return Plot - */ - public ArrayList getPlots() { - return this.plots; - } + /** + * Get the plots being added; + * + * @return Plot + */ + public ArrayList getPlots() { + return this.plots; + } - /** - * Get the main plot - * - * @return Plot - */ - public Plot getPlot() { - return this.plot; - } + /** + * Get the main plot + * + * @return Plot + */ + public Plot getPlot() { + return this.plot; + } - public World getWorld() { - return this.world; - } + public World getWorld() { + return this.world; + } - public static HandlerList getHandlerList() { - return handlers; - } + public static HandlerList getHandlerList() { + return handlers; + } - @Override - public HandlerList getHandlers() { - return handlers; - } + @Override + public HandlerList getHandlers() { + return handlers; + } - @Override - public boolean isCancelled() { - return this.cancelled; - } + @Override + public boolean isCancelled() { + return this.cancelled; + } - @Override - public void setCancelled(boolean b) { - this.cancelled = b; - } + @Override + public void setCancelled(boolean b) { + this.cancelled = b; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/events/PlotUnlinkEvent.java b/PlotSquared/src/com/intellectualcrafters/plot/events/PlotUnlinkEvent.java index 7891a9fd1..24d24eaf7 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/events/PlotUnlinkEvent.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/events/PlotUnlinkEvent.java @@ -22,52 +22,52 @@ import com.intellectualcrafters.plot.PlotId; * Created by Citymonstret on 2014-08-09. */ public class PlotUnlinkEvent extends Event implements Cancellable { - private static HandlerList handlers = new HandlerList(); - private boolean cancelled; + private static HandlerList handlers = new HandlerList(); + private boolean cancelled; - private ArrayList plots; - private World world; + private ArrayList plots; + private World world; - /** - * Called when a mega-plot is unlinked. - * - * @param world - * @param plots - */ - public PlotUnlinkEvent(World world, ArrayList plots) { - this.plots = plots; - this.world = world; - } + /** + * Called when a mega-plot is unlinked. + * + * @param world + * @param plots + */ + public PlotUnlinkEvent(World world, ArrayList plots) { + this.plots = plots; + this.world = world; + } - /** - * Get the plots involved - * - * @return PlotId - */ - public ArrayList getPlots() { - return this.plots; - } + /** + * Get the plots involved + * + * @return PlotId + */ + public ArrayList getPlots() { + return this.plots; + } - public World getWorld() { - return this.world; - } + public World getWorld() { + return this.world; + } - public static HandlerList getHandlerList() { - return handlers; - } + public static HandlerList getHandlerList() { + return handlers; + } - @Override - public HandlerList getHandlers() { - return handlers; - } + @Override + public HandlerList getHandlers() { + return handlers; + } - @Override - public boolean isCancelled() { - return this.cancelled; - } + @Override + public boolean isCancelled() { + return this.cancelled; + } - @Override - public void setCancelled(boolean b) { - this.cancelled = b; - } + @Override + public void setCancelled(boolean b) { + this.cancelled = b; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/generator/DefaultPlotManager.java b/PlotSquared/src/com/intellectualcrafters/plot/generator/DefaultPlotManager.java index 14d817406..fc699c820 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/generator/DefaultPlotManager.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/generator/DefaultPlotManager.java @@ -1,6 +1,7 @@ package com.intellectualcrafters.plot.generator; import java.util.ArrayList; + import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; @@ -19,579 +20,814 @@ import com.intellectualcrafters.plot.PlotWorld; public class DefaultPlotManager extends PlotManager { - /* - * Default implementation of getting a plot at a given location - * - * For a simplified explanation of the math involved: - * - Get the current coords - * - shift these numbers down to something relatable for a single plot - * (similar to reducing trigonometric functions down to the first quadrant) - * - e.g. If the plot size is 20 blocks, and we are at x=25, it's equivalent to x=5 for that specific plot - * - * From this, and knowing how thick the road is, we can say whether x=5 is road, or plot. - * The number of shifts done, is also counted, and this number gives us the PlotId - * - * - */ - @Override - public PlotId getPlotIdAbs(PlotWorld plotworld, Location loc) { - DefaultPlotWorld dpw = ((DefaultPlotWorld) plotworld); - - // get x,z loc - int x = loc.getBlockX(); - int z = loc.getBlockZ(); - - // get plot size - int size = dpw.PLOT_WIDTH + dpw.ROAD_WIDTH; - - // get size of path on bottom part, and top part of plot - // (As 0,0 is in the middle of a road, not the very start) - int pathWidthLower; - if ((dpw.ROAD_WIDTH % 2) == 0) { - pathWidthLower = (int) (Math.floor(dpw.ROAD_WIDTH / 2) - 1); - } else { - pathWidthLower = (int) Math.floor(dpw.ROAD_WIDTH / 2); - } - - // calulating how many shifts need to be done - int dx = x / size; - int dz = z / size; - if (x < 0) { - dx--; - x += ((-dx) * size); - } - if (z < 0) { - dz--; - z += ((-dz) * size); - } - - // reducing to first plot - int rx = (x) % size; - int rz = (z) % size; - - // checking if road (return null if so) - int end = pathWidthLower + dpw.PLOT_WIDTH; - boolean northSouth = (rz <= pathWidthLower) || (rz > end); - boolean eastWest = (rx <= pathWidthLower) || (rx > end); - if (northSouth || eastWest) { - return null; - } - // returning the plot id (based on the number of shifts required) - return new PlotId(dx + 1, dz + 1); - } - - /* - * Some complex stuff for traversing mega plots (return getPlotIdAbs if you do not support mega plots) - */ - @Override - public PlotId getPlotId(PlotWorld plotworld, Location loc) { - DefaultPlotWorld dpw = ((DefaultPlotWorld) plotworld); - - int x = loc.getBlockX(); - int z = loc.getBlockZ(); - - if (plotworld == null) { - return null; - } - int size = dpw.PLOT_WIDTH + dpw.ROAD_WIDTH; - int pathWidthLower; - if ((dpw.ROAD_WIDTH % 2) == 0) { - pathWidthLower = (int) (Math.floor(dpw.ROAD_WIDTH / 2) - 1); - } else { - pathWidthLower = (int) Math.floor(dpw.ROAD_WIDTH / 2); - } - - int dx = x / size; - int dz = z / size; - - if (x < 0) { - dx--; - x += ((-dx) * size); - } - if (z < 0) { - dz--; - z += ((-dz) * size); - } - - int rx = (x) % size; - int rz = (z) % size; - - int end = pathWidthLower + dpw.PLOT_WIDTH; - - boolean northSouth = (rz <= pathWidthLower) || (rz > end); - boolean eastWest = (rx <= pathWidthLower) || (rx > end); - if (northSouth && eastWest) { - // This means you are in the intersection - PlotId id = PlayerFunctions.getPlotAbs(loc.add(dpw.ROAD_WIDTH, 0, dpw.ROAD_WIDTH)); - Plot plot = PlotMain.getPlots(loc.getWorld()).get(id); - if (plot == null) { - return null; - } - if ((plot.settings.getMerged(0) && plot.settings.getMerged(3))) { - return PlayerFunctions.getBottomPlot(loc.getWorld(), plot).id; - } - return null; - } - if (northSouth) { - // You are on a road running West to East (yeah, I named the var - // poorly) - PlotId id = PlayerFunctions.getPlotAbs(loc.add(0, 0, dpw.ROAD_WIDTH)); - Plot plot = PlotMain.getPlots(loc.getWorld()).get(id); - if (plot == null) { - return null; - } - if (plot.settings.getMerged(0)) { - return PlayerFunctions.getBottomPlot(loc.getWorld(), plot).id; - } - return null; - } - if (eastWest) { - // This is the road separating an Eastern and Western plot - PlotId id = PlayerFunctions.getPlotAbs(loc.add(dpw.ROAD_WIDTH, 0, 0)); - Plot plot = PlotMain.getPlots(loc.getWorld()).get(id); - if (plot == null) { - return null; - } - if (plot.settings.getMerged(3)) { - return PlayerFunctions.getBottomPlot(loc.getWorld(), plot).id; - } - return null; - } - PlotId id = new PlotId(dx + 1, dz + 1); - Plot plot = PlotMain.getPlots(loc.getWorld()).get(id); - if (plot == null) { - return id; - } - return PlayerFunctions.getBottomPlot(loc.getWorld(), plot).id; - } - - /* - * Check if a location is inside a specific plot(non-Javadoc) - * - For this implementation, we don't need to do anything fancier than referring to getPlotIdAbs(...) - */ - @Override - public boolean isInPlotAbs(PlotWorld plotworld, Location loc, PlotId plotid) { - PlotId result = getPlotIdAbs(plotworld, loc); - if (result==null) { - return false; - } - return result==plotid; - } - - /* - * Get the bottom plot loc - * (some basic math) - */ - @Override - public Location getPlotBottomLocAbs(PlotWorld plotworld, PlotId plotid) { - DefaultPlotWorld dpw = ((DefaultPlotWorld) plotworld); - - int px = plotid.x; - int pz = plotid.y; - - int x = (px * (dpw.ROAD_WIDTH + dpw.PLOT_WIDTH)) - dpw.PLOT_WIDTH - ((int) Math.floor(dpw.ROAD_WIDTH / 2)) - 1; - int z = (pz * (dpw.ROAD_WIDTH + dpw.PLOT_WIDTH)) - dpw.PLOT_WIDTH - ((int) Math.floor(dpw.ROAD_WIDTH / 2)) - 1; - - return new Location(Bukkit.getWorld(plotworld.worldname), x, 1, z); - } - - /* - * Get the top plot loc - * (some basic math) - */ - @Override - public Location getPlotTopLocAbs(PlotWorld plotworld, PlotId plotid) { - DefaultPlotWorld dpw = ((DefaultPlotWorld) plotworld); - - int px = plotid.x; - int pz = plotid.y; - - int x = (px * (dpw.ROAD_WIDTH + dpw.PLOT_WIDTH)) - ((int) Math.floor(dpw.ROAD_WIDTH / 2)) - 1; - int z = (pz * (dpw.ROAD_WIDTH + dpw.PLOT_WIDTH)) - ((int) Math.floor(dpw.ROAD_WIDTH / 2)) - 1; - - return new Location(Bukkit.getWorld(plotworld.worldname), x, 256, z); - } - - /* - * Clearing the plot needs to only consider removing the blocks - * - This implementation has used the SetCuboid function, as it is fast, and uses NMS code - * - It also makes use of the fact that deleting chunks is a lot faster than block updates - * - * This code is very messy, but you don't need to do something quite as complex unless you happen to have 512x512 sized plots - * - */ - @Override - public boolean clearPlot(Player player, Plot plot) { - World world = player.getWorld(); - DefaultPlotWorld dpw = ((DefaultPlotWorld) PlotMain.getWorldSettings(world)); - - final Location pos1 = PlotHelper.getPlotBottomLoc(world, plot.id).add(1, 0, 1); - final Location pos2 = PlotHelper.getPlotTopLoc(world, plot.id); - - PlotBlock[] plotfloor = dpw.TOP_BLOCK; - PlotBlock[] filling = dpw.TOP_BLOCK; - - if ((pos2.getBlockX() - pos1.getBlockX()) < 16) { - PlotHelper.setSimpleCuboid(world, new Location(world, pos1.getBlockX(), 0, pos1.getBlockZ()), new Location(world, pos2.getBlockX() + 1, 1, pos2.getBlockZ() + 1), new PlotBlock((short) 7, (byte) 0)); - PlotHelper.setSimpleCuboid(world, new Location(world, pos1.getBlockX(), dpw.PLOT_HEIGHT + 1, pos1.getBlockZ()), new Location(world, pos2.getBlockX() + 1, world.getMaxHeight() + 1, pos2.getBlockZ() + 1), new PlotBlock((short) 0, (byte) 0)); - PlotHelper.setCuboid(world, new Location(world, pos1.getBlockX(), 1, pos1.getBlockZ()), new Location(world, pos2.getBlockX() + 1, dpw.PLOT_HEIGHT, pos2.getBlockZ() + 1), filling); - PlotHelper.setCuboid(world, new Location(world, pos1.getBlockX(), dpw.PLOT_HEIGHT, pos1.getBlockZ()), new Location(world, pos2.getBlockX() + 1, dpw.PLOT_HEIGHT + 1, pos2.getBlockZ() + 1), plotfloor); - return true; - } - int startX = (pos1.getBlockX() / 16) * 16; - int startZ = (pos1.getBlockZ() / 16) * 16; - int chunkX = 16 + pos2.getBlockX(); - int chunkZ = 16 + pos2.getBlockZ(); - Location l1 = PlotHelper.getPlotBottomLoc(world, plot.id); - Location l2 = PlotHelper.getPlotTopLoc(world, plot.id); - int plotMinX = l1.getBlockX() + 1; - int plotMinZ = l1.getBlockZ() + 1; - int plotMaxX = l2.getBlockX(); - int plotMaxZ = l2.getBlockZ(); - Location min = null; - Location max = null; - for (int i = startX; i < chunkX; i += 16) { - for (int j = startZ; j < chunkZ; j += 16) { - Plot plot1 = PlotHelper.getCurrentPlot(new Location(world, i, 0, j)); - if ((plot1 != null) && (plot1.getId() != plot.getId()) && plot1.hasOwner()) { - break; - } - Plot plot2 = PlotHelper.getCurrentPlot(new Location(world, i + 15, 0, j)); - if ((plot2 != null) && (plot2.getId() != plot.getId()) && plot2.hasOwner()) { - break; - } - Plot plot3 = PlotHelper.getCurrentPlot(new Location(world, i + 15, 0, j + 15)); - if ((plot3 != null) && (plot3.getId() != plot.getId()) && plot3.hasOwner()) { - break; - } - Plot plot4 = PlotHelper.getCurrentPlot(new Location(world, i, 0, j + 15)); - if ((plot4 != null) && (plot4.getId() != plot.getId()) && plot4.hasOwner()) { - break; - } - Plot plot5 = PlotHelper.getCurrentPlot(new Location(world, i + 15, 0, j + 15)); - if ((plot5 != null) && (plot5.getId() != plot.getId()) && plot5.hasOwner()) { - break; - } - if (min == null) { - min = new Location(world, Math.max(i - 1, plotMinX), 0, Math.max(j - 1, plotMinZ)); - max = new Location(world, Math.min(i + 16, plotMaxX), 0, Math.min(j + 16, plotMaxZ)); - } else if ((max.getBlockZ() < (j + 15)) || (max.getBlockX() < (i + 15))) { - max = new Location(world, Math.min(i + 16, plotMaxX), 0, Math.min(j + 16, plotMaxZ)); - } - world.regenerateChunk(i / 16, j / 16); - } - } - - if (min == null) { - PlotHelper.setSimpleCuboid(world, new Location(world, pos1.getBlockX(), 0, pos1.getBlockZ()), new Location(world, pos2.getBlockX() + 1, 1, pos2.getBlockZ() + 1), new PlotBlock((short) 7, (byte) 0)); - PlotHelper.setSimpleCuboid(world, new Location(world, pos1.getBlockX(), dpw.PLOT_HEIGHT + 1, pos1.getBlockZ()), new Location(world, pos2.getBlockX() + 1, world.getMaxHeight() + 1, pos2.getBlockZ() + 1), new PlotBlock((short) 0, (byte) 0)); - PlotHelper.setCuboid(world, new Location(world, pos1.getBlockX(), 1, pos1.getBlockZ()), new Location(world, pos2.getBlockX() + 1, dpw.PLOT_HEIGHT, pos2.getBlockZ() + 1), filling); - PlotHelper.setCuboid(world, new Location(world, pos1.getBlockX(), dpw.PLOT_HEIGHT, pos1.getBlockZ()), new Location(world, pos2.getBlockX() + 1, dpw.PLOT_HEIGHT + 1, pos2.getBlockZ() + 1), plotfloor); - } else { - - if (min.getBlockX() < plotMinX) { - min.setX(plotMinX); - } - if (min.getBlockZ() < plotMinZ) { - min.setZ(plotMinZ); - } - if (max.getBlockX() > plotMaxX) { - max.setX(plotMaxX); - } - if (max.getBlockZ() > plotMaxZ) { - max.setZ(plotMaxZ); - } - - PlotHelper.setSimpleCuboid(world, new Location(world, plotMinX, 0, plotMinZ), new Location(world, min.getBlockX() + 1, 1, min.getBlockZ() + 1), new PlotBlock((short) 7, (byte) 0)); - PlotHelper.setSimpleCuboid(world, new Location(world, plotMinX, dpw.PLOT_HEIGHT + 1, plotMinZ), new Location(world, min.getBlockX() + 1, world.getMaxHeight() + 1, min.getBlockZ() + 1), new PlotBlock((short) 0, (byte) 0)); - PlotHelper.setCuboid(world, new Location(world, plotMinX, 1, plotMinZ), new Location(world, min.getBlockX() + 1, dpw.PLOT_HEIGHT + 1, min.getBlockZ() + 1), filling); - PlotHelper.setCuboid(world, new Location(world, plotMinX, dpw.PLOT_HEIGHT, plotMinZ), new Location(world, min.getBlockX() + 1, dpw.PLOT_HEIGHT + 1, min.getBlockZ() + 1), plotfloor); - - PlotHelper.setSimpleCuboid(world, new Location(world, min.getBlockX(), 0, plotMinZ), new Location(world, max.getBlockX() + 1, 1, min.getBlockZ() + 1), new PlotBlock((short) 7, (byte) 0)); - PlotHelper.setSimpleCuboid(world, new Location(world, min.getBlockX(), dpw.PLOT_HEIGHT + 1, plotMinZ), new Location(world, max.getBlockX() + 1, world.getMaxHeight() + 1, min.getBlockZ() + 1), new PlotBlock((short) 0, (byte) 0)); - PlotHelper.setCuboid(world, new Location(world, min.getBlockX(), 1, plotMinZ), new Location(world, max.getBlockX() + 1, dpw.PLOT_HEIGHT, min.getBlockZ() + 1), filling); - PlotHelper.setCuboid(world, new Location(world, min.getBlockX(), dpw.PLOT_HEIGHT, plotMinZ), new Location(world, max.getBlockX() + 1, dpw.PLOT_HEIGHT + 1, min.getBlockZ() + 1), plotfloor); - - PlotHelper.setSimpleCuboid(world, new Location(world, max.getBlockX(), 0, plotMinZ), new Location(world, plotMaxX + 1, 1, min.getBlockZ() + 1), new PlotBlock((short) 7, (byte) 0)); - PlotHelper.setSimpleCuboid(world, new Location(world, max.getBlockX(), dpw.PLOT_HEIGHT + 1, plotMinZ), new Location(world, plotMaxX + 1, world.getMaxHeight() + 1, min.getBlockZ() + 1), new PlotBlock((short) 0, (byte) 0)); - PlotHelper.setCuboid(world, new Location(world, max.getBlockX(), 1, plotMinZ), new Location(world, plotMaxX + 1, dpw.PLOT_HEIGHT, min.getBlockZ() + 1), filling); - PlotHelper.setCuboid(world, new Location(world, max.getBlockX(), dpw.PLOT_HEIGHT, plotMinZ), new Location(world, plotMaxX + 1, dpw.PLOT_HEIGHT + 1, min.getBlockZ() + 1), plotfloor); - - PlotHelper.setSimpleCuboid(world, new Location(world, plotMinX, 0, min.getBlockZ()), new Location(world, min.getBlockX() + 1, 1, max.getBlockZ() + 1), new PlotBlock((short) 7, (byte) 0)); - PlotHelper.setSimpleCuboid(world, new Location(world, plotMinX, dpw.PLOT_HEIGHT + 1, min.getBlockZ()), new Location(world, min.getBlockX() + 1, world.getMaxHeight() + 1, max.getBlockZ() + 1), new PlotBlock((short) 0, (byte) 0)); - PlotHelper.setCuboid(world, new Location(world, plotMinX, 1, min.getBlockZ()), new Location(world, min.getBlockX() + 1, dpw.PLOT_HEIGHT, max.getBlockZ() + 1), filling); - PlotHelper.setCuboid(world, new Location(world, plotMinX, dpw.PLOT_HEIGHT, min.getBlockZ()), new Location(world, min.getBlockX() + 1, dpw.PLOT_HEIGHT + 1, max.getBlockZ() + 1), plotfloor); - - PlotHelper.setSimpleCuboid(world, new Location(world, plotMinX, 0, max.getBlockZ()), new Location(world, min.getBlockX() + 1, 1, plotMaxZ + 1), new PlotBlock((short) 7, (byte) 0)); - PlotHelper.setSimpleCuboid(world, new Location(world, plotMinX, dpw.PLOT_HEIGHT + 1, max.getBlockZ()), new Location(world, min.getBlockX() + 1, world.getMaxHeight() + 1, plotMaxZ + 1), new PlotBlock((short) 0, (byte) 0)); - PlotHelper.setCuboid(world, new Location(world, plotMinX, 1, max.getBlockZ()), new Location(world, min.getBlockX() + 1, dpw.PLOT_HEIGHT, plotMaxZ + 1), filling); - PlotHelper.setCuboid(world, new Location(world, plotMinX, dpw.PLOT_HEIGHT, max.getBlockZ()), new Location(world, min.getBlockX() + 1, dpw.PLOT_HEIGHT + 1, plotMaxZ + 1), plotfloor); - - PlotHelper.setSimpleCuboid(world, new Location(world, min.getBlockX(), 0, max.getBlockZ()), new Location(world, max.getBlockX() + 1, 1, plotMaxZ + 1), new PlotBlock((short) 7, (byte) 0)); - PlotHelper.setSimpleCuboid(world, new Location(world, min.getBlockX(), dpw.PLOT_HEIGHT + 1, max.getBlockZ()), new Location(world, max.getBlockX() + 1, world.getMaxHeight() + 1, plotMaxZ + 1), new PlotBlock((short) 0, (byte) 0)); - PlotHelper.setCuboid(world, new Location(world, min.getBlockX(), 1, max.getBlockZ()), new Location(world, max.getBlockX() + 1, dpw.PLOT_HEIGHT, plotMaxZ + 1), filling); - PlotHelper.setCuboid(world, new Location(world, min.getBlockX(), dpw.PLOT_HEIGHT, max.getBlockZ()), new Location(world, max.getBlockX() + 1, dpw.PLOT_HEIGHT + 1, plotMaxZ + 1), plotfloor); - - PlotHelper.setSimpleCuboid(world, new Location(world, max.getBlockX(), 0, min.getBlockZ()), new Location(world, plotMaxX + 1, 1, max.getBlockZ() + 1), new PlotBlock((short) 7, (byte) 0)); - PlotHelper.setSimpleCuboid(world, new Location(world, max.getBlockX(), dpw.PLOT_HEIGHT + 1, max.getBlockZ()), new Location(world, plotMaxX + 1, world.getMaxHeight() + 1, plotMaxZ + 1), new PlotBlock((short) 0, (byte) 0)); - PlotHelper.setCuboid(world, new Location(world, max.getBlockX(), 1, min.getBlockZ()), new Location(world, plotMaxX + 1, dpw.PLOT_HEIGHT, max.getBlockZ() + 1), filling); - PlotHelper.setCuboid(world, new Location(world, max.getBlockX(), dpw.PLOT_HEIGHT, min.getBlockZ()), new Location(world, plotMaxX + 1, dpw.PLOT_HEIGHT + 1, max.getBlockZ() + 1), plotfloor); - - PlotHelper.setSimpleCuboid(world, new Location(world, max.getBlockX(), 0, max.getBlockZ()), new Location(world, plotMaxX + 1, 1, plotMaxZ + 1), new PlotBlock((short) 7, (byte) 0)); - PlotHelper.setSimpleCuboid(world, new Location(world, max.getBlockX(), dpw.PLOT_HEIGHT + 1, max.getBlockZ()), new Location(world, plotMaxX + 1, world.getMaxHeight() + 1, plotMaxZ + 1), new PlotBlock((short) 0, (byte) 0)); - PlotHelper.setCuboid(world, new Location(world, max.getBlockX(), 1, max.getBlockZ()), new Location(world, plotMaxX + 1, dpw.PLOT_HEIGHT, plotMaxZ + 1), filling); - PlotHelper.setCuboid(world, new Location(world, max.getBlockX(), dpw.PLOT_HEIGHT, max.getBlockZ()), new Location(world, plotMaxX + 1, dpw.PLOT_HEIGHT + 1, plotMaxZ + 1), plotfloor); - } - return true; - } - - /* - * Remove sign for a plot - */ - @Override - public Location getSignLoc(Player player, PlotWorld plotworld, Plot plot) { - DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; - World world = player.getWorld(); - return new Location(world, PlotHelper.getPlotBottomLoc(world, plot.id).getBlockX(), dpw.ROAD_HEIGHT + 1, PlotHelper.getPlotBottomLoc(world, plot.id).getBlockZ() - 1); - } - - + /* + * Default implementation of getting a plot at a given location + * + * For a simplified explanation of the math involved: - Get the current + * coords - shift these numbers down to something relatable for a single + * plot (similar to reducing trigonometric functions down to the first + * quadrant) - e.g. If the plot size is 20 blocks, and we are at x=25, it's + * equivalent to x=5 for that specific plot + * + * From this, and knowing how thick the road is, we can say whether x=5 is + * road, or plot. The number of shifts done, is also counted, and this + * number gives us the PlotId + */ @Override - public boolean setFloor(Player player, PlotWorld plotworld, PlotId plotid, PlotBlock[] blocks) { + public PlotId getPlotIdAbs(PlotWorld plotworld, Location loc) { + DefaultPlotWorld dpw = ((DefaultPlotWorld) plotworld); + + // get x,z loc + int x = loc.getBlockX(); + int z = loc.getBlockZ(); + + // get plot size + int size = dpw.PLOT_WIDTH + dpw.ROAD_WIDTH; + + // get size of path on bottom part, and top part of plot + // (As 0,0 is in the middle of a road, not the very start) + int pathWidthLower; + if ((dpw.ROAD_WIDTH % 2) == 0) { + pathWidthLower = (int) (Math.floor(dpw.ROAD_WIDTH / 2) - 1); + } else { + pathWidthLower = (int) Math.floor(dpw.ROAD_WIDTH / 2); + } + + // calulating how many shifts need to be done + int dx = x / size; + int dz = z / size; + if (x < 0) { + dx--; + x += ((-dx) * size); + } + if (z < 0) { + dz--; + z += ((-dz) * size); + } + + // reducing to first plot + int rx = (x) % size; + int rz = (z) % size; + + // checking if road (return null if so) + int end = pathWidthLower + dpw.PLOT_WIDTH; + boolean northSouth = (rz <= pathWidthLower) || (rz > end); + boolean eastWest = (rx <= pathWidthLower) || (rx > end); + if (northSouth || eastWest) { + return null; + } + // returning the plot id (based on the number of shifts required) + return new PlotId(dx + 1, dz + 1); + } + + /* + * Some complex stuff for traversing mega plots (return getPlotIdAbs if you + * do not support mega plots) + */ + @Override + public PlotId getPlotId(PlotWorld plotworld, Location loc) { + DefaultPlotWorld dpw = ((DefaultPlotWorld) plotworld); + + int x = loc.getBlockX(); + int z = loc.getBlockZ(); + + if (plotworld == null) { + return null; + } + int size = dpw.PLOT_WIDTH + dpw.ROAD_WIDTH; + int pathWidthLower; + if ((dpw.ROAD_WIDTH % 2) == 0) { + pathWidthLower = (int) (Math.floor(dpw.ROAD_WIDTH / 2) - 1); + } else { + pathWidthLower = (int) Math.floor(dpw.ROAD_WIDTH / 2); + } + + int dx = x / size; + int dz = z / size; + + if (x < 0) { + dx--; + x += ((-dx) * size); + } + if (z < 0) { + dz--; + z += ((-dz) * size); + } + + int rx = (x) % size; + int rz = (z) % size; + + int end = pathWidthLower + dpw.PLOT_WIDTH; + + boolean northSouth = (rz <= pathWidthLower) || (rz > end); + boolean eastWest = (rx <= pathWidthLower) || (rx > end); + if (northSouth && eastWest) { + // This means you are in the intersection + PlotId id = PlayerFunctions.getPlotAbs(loc.add(dpw.ROAD_WIDTH, 0, + dpw.ROAD_WIDTH)); + Plot plot = PlotMain.getPlots(loc.getWorld()).get(id); + if (plot == null) { + return null; + } + if ((plot.settings.getMerged(0) && plot.settings.getMerged(3))) { + return PlayerFunctions.getBottomPlot(loc.getWorld(), plot).id; + } + return null; + } + if (northSouth) { + // You are on a road running West to East (yeah, I named the var + // poorly) + PlotId id = PlayerFunctions.getPlotAbs(loc + .add(0, 0, dpw.ROAD_WIDTH)); + Plot plot = PlotMain.getPlots(loc.getWorld()).get(id); + if (plot == null) { + return null; + } + if (plot.settings.getMerged(0)) { + return PlayerFunctions.getBottomPlot(loc.getWorld(), plot).id; + } + return null; + } + if (eastWest) { + // This is the road separating an Eastern and Western plot + PlotId id = PlayerFunctions.getPlotAbs(loc + .add(dpw.ROAD_WIDTH, 0, 0)); + Plot plot = PlotMain.getPlots(loc.getWorld()).get(id); + if (plot == null) { + return null; + } + if (plot.settings.getMerged(3)) { + return PlayerFunctions.getBottomPlot(loc.getWorld(), plot).id; + } + return null; + } + PlotId id = new PlotId(dx + 1, dz + 1); + Plot plot = PlotMain.getPlots(loc.getWorld()).get(id); + if (plot == null) { + return id; + } + return PlayerFunctions.getBottomPlot(loc.getWorld(), plot).id; + } + + /* + * Check if a location is inside a specific plot(non-Javadoc) - For this + * implementation, we don't need to do anything fancier than referring to + * getPlotIdAbs(...) + */ + @Override + public boolean isInPlotAbs(PlotWorld plotworld, Location loc, PlotId plotid) { + PlotId result = getPlotIdAbs(plotworld, loc); + if (result == null) { + return false; + } + return result == plotid; + } + + /* + * Get the bottom plot loc (some basic math) + */ + @Override + public Location getPlotBottomLocAbs(PlotWorld plotworld, PlotId plotid) { + DefaultPlotWorld dpw = ((DefaultPlotWorld) plotworld); + + int px = plotid.x; + int pz = plotid.y; + + int x = (px * (dpw.ROAD_WIDTH + dpw.PLOT_WIDTH)) - dpw.PLOT_WIDTH + - ((int) Math.floor(dpw.ROAD_WIDTH / 2)) - 1; + int z = (pz * (dpw.ROAD_WIDTH + dpw.PLOT_WIDTH)) - dpw.PLOT_WIDTH + - ((int) Math.floor(dpw.ROAD_WIDTH / 2)) - 1; + + return new Location(Bukkit.getWorld(plotworld.worldname), x, 1, z); + } + + /* + * Get the top plot loc (some basic math) + */ + @Override + public Location getPlotTopLocAbs(PlotWorld plotworld, PlotId plotid) { + DefaultPlotWorld dpw = ((DefaultPlotWorld) plotworld); + + int px = plotid.x; + int pz = plotid.y; + + int x = (px * (dpw.ROAD_WIDTH + dpw.PLOT_WIDTH)) + - ((int) Math.floor(dpw.ROAD_WIDTH / 2)) - 1; + int z = (pz * (dpw.ROAD_WIDTH + dpw.PLOT_WIDTH)) + - ((int) Math.floor(dpw.ROAD_WIDTH / 2)) - 1; + + return new Location(Bukkit.getWorld(plotworld.worldname), x, 256, z); + } + + /* + * Clearing the plot needs to only consider removing the blocks - This + * implementation has used the SetCuboid function, as it is fast, and uses + * NMS code - It also makes use of the fact that deleting chunks is a lot + * faster than block updates + * + * This code is very messy, but you don't need to do something quite as + * complex unless you happen to have 512x512 sized plots + */ + @Override + public boolean clearPlot(Player player, Plot plot) { World world = player.getWorld(); - final Location pos1 = PlotHelper.getPlotBottomLoc(world, plotid).add(1, 0, 1); - final Location pos2 = PlotHelper.getPlotTopLoc(world, plotid); - PlotHelper.setCuboid(world, pos1, pos2, blocks); + DefaultPlotWorld dpw = ((DefaultPlotWorld) PlotMain + .getWorldSettings(world)); + + final Location pos1 = PlotHelper.getPlotBottomLoc(world, plot.id).add( + 1, 0, 1); + final Location pos2 = PlotHelper.getPlotTopLoc(world, plot.id); + + PlotBlock[] plotfloor = dpw.TOP_BLOCK; + PlotBlock[] filling = dpw.TOP_BLOCK; + + if ((pos2.getBlockX() - pos1.getBlockX()) < 16) { + PlotHelper.setSimpleCuboid( + world, + new Location(world, pos1.getBlockX(), 0, pos1.getBlockZ()), + new Location(world, pos2.getBlockX() + 1, 1, pos2 + .getBlockZ() + 1), new PlotBlock((short) 7, + (byte) 0)); + PlotHelper.setSimpleCuboid( + world, + new Location(world, pos1.getBlockX(), dpw.PLOT_HEIGHT + 1, + pos1.getBlockZ()), + new Location(world, pos2.getBlockX() + 1, world + .getMaxHeight() + 1, pos2.getBlockZ() + 1), + new PlotBlock((short) 0, (byte) 0)); + PlotHelper.setCuboid(world, new Location(world, pos1.getBlockX(), + 1, pos1.getBlockZ()), + new Location(world, pos2.getBlockX() + 1, dpw.PLOT_HEIGHT, + pos2.getBlockZ() + 1), filling); + PlotHelper.setCuboid(world, new Location(world, pos1.getBlockX(), + dpw.PLOT_HEIGHT, pos1.getBlockZ()), new Location(world, + pos2.getBlockX() + 1, dpw.PLOT_HEIGHT + 1, + pos2.getBlockZ() + 1), plotfloor); + return true; + } + int startX = (pos1.getBlockX() / 16) * 16; + int startZ = (pos1.getBlockZ() / 16) * 16; + int chunkX = 16 + pos2.getBlockX(); + int chunkZ = 16 + pos2.getBlockZ(); + Location l1 = PlotHelper.getPlotBottomLoc(world, plot.id); + Location l2 = PlotHelper.getPlotTopLoc(world, plot.id); + int plotMinX = l1.getBlockX() + 1; + int plotMinZ = l1.getBlockZ() + 1; + int plotMaxX = l2.getBlockX(); + int plotMaxZ = l2.getBlockZ(); + Location min = null; + Location max = null; + for (int i = startX; i < chunkX; i += 16) { + for (int j = startZ; j < chunkZ; j += 16) { + Plot plot1 = PlotHelper.getCurrentPlot(new Location(world, i, + 0, j)); + if ((plot1 != null) && (plot1.getId() != plot.getId()) + && plot1.hasOwner()) { + break; + } + Plot plot2 = PlotHelper.getCurrentPlot(new Location(world, + i + 15, 0, j)); + if ((plot2 != null) && (plot2.getId() != plot.getId()) + && plot2.hasOwner()) { + break; + } + Plot plot3 = PlotHelper.getCurrentPlot(new Location(world, + i + 15, 0, j + 15)); + if ((plot3 != null) && (plot3.getId() != plot.getId()) + && plot3.hasOwner()) { + break; + } + Plot plot4 = PlotHelper.getCurrentPlot(new Location(world, i, + 0, j + 15)); + if ((plot4 != null) && (plot4.getId() != plot.getId()) + && plot4.hasOwner()) { + break; + } + Plot plot5 = PlotHelper.getCurrentPlot(new Location(world, + i + 15, 0, j + 15)); + if ((plot5 != null) && (plot5.getId() != plot.getId()) + && plot5.hasOwner()) { + break; + } + if (min == null) { + min = new Location(world, Math.max(i - 1, plotMinX), 0, + Math.max(j - 1, plotMinZ)); + max = new Location(world, Math.min(i + 16, plotMaxX), 0, + Math.min(j + 16, plotMaxZ)); + } else if ((max.getBlockZ() < (j + 15)) + || (max.getBlockX() < (i + 15))) { + max = new Location(world, Math.min(i + 16, plotMaxX), 0, + Math.min(j + 16, plotMaxZ)); + } + world.regenerateChunk(i / 16, j / 16); + } + } + + if (min == null) { + PlotHelper.setSimpleCuboid( + world, + new Location(world, pos1.getBlockX(), 0, pos1.getBlockZ()), + new Location(world, pos2.getBlockX() + 1, 1, pos2 + .getBlockZ() + 1), new PlotBlock((short) 7, + (byte) 0)); + PlotHelper.setSimpleCuboid( + world, + new Location(world, pos1.getBlockX(), dpw.PLOT_HEIGHT + 1, + pos1.getBlockZ()), + new Location(world, pos2.getBlockX() + 1, world + .getMaxHeight() + 1, pos2.getBlockZ() + 1), + new PlotBlock((short) 0, (byte) 0)); + PlotHelper.setCuboid(world, new Location(world, pos1.getBlockX(), + 1, pos1.getBlockZ()), + new Location(world, pos2.getBlockX() + 1, dpw.PLOT_HEIGHT, + pos2.getBlockZ() + 1), filling); + PlotHelper.setCuboid(world, new Location(world, pos1.getBlockX(), + dpw.PLOT_HEIGHT, pos1.getBlockZ()), new Location(world, + pos2.getBlockX() + 1, dpw.PLOT_HEIGHT + 1, + pos2.getBlockZ() + 1), plotfloor); + } else { + + if (min.getBlockX() < plotMinX) { + min.setX(plotMinX); + } + if (min.getBlockZ() < plotMinZ) { + min.setZ(plotMinZ); + } + if (max.getBlockX() > plotMaxX) { + max.setX(plotMaxX); + } + if (max.getBlockZ() > plotMaxZ) { + max.setZ(plotMaxZ); + } + + PlotHelper.setSimpleCuboid(world, new Location(world, plotMinX, 0, + plotMinZ), + new Location(world, min.getBlockX() + 1, 1, + min.getBlockZ() + 1), new PlotBlock((short) 7, + (byte) 0)); + PlotHelper + .setSimpleCuboid( + world, + new Location(world, plotMinX, dpw.PLOT_HEIGHT + 1, + plotMinZ), + new Location(world, min.getBlockX() + 1, world + .getMaxHeight() + 1, min.getBlockZ() + 1), + new PlotBlock((short) 0, (byte) 0)); + PlotHelper.setCuboid(world, new Location(world, plotMinX, 1, + plotMinZ), new Location(world, min.getBlockX() + 1, + dpw.PLOT_HEIGHT + 1, min.getBlockZ() + 1), filling); + PlotHelper.setCuboid(world, new Location(world, plotMinX, + dpw.PLOT_HEIGHT, plotMinZ), + new Location(world, min.getBlockX() + 1, + dpw.PLOT_HEIGHT + 1, min.getBlockZ() + 1), + plotfloor); + + PlotHelper.setSimpleCuboid(world, + new Location(world, min.getBlockX(), 0, plotMinZ), + new Location(world, max.getBlockX() + 1, 1, + min.getBlockZ() + 1), new PlotBlock((short) 7, + (byte) 0)); + PlotHelper.setSimpleCuboid(world, + new Location(world, min.getBlockX(), dpw.PLOT_HEIGHT + 1, + plotMinZ), new Location(world, max.getBlockX() + 1, + world.getMaxHeight() + 1, min.getBlockZ() + 1), + new PlotBlock((short) 0, (byte) 0)); + PlotHelper.setCuboid(world, new Location(world, min.getBlockX(), 1, + plotMinZ), new Location(world, max.getBlockX() + 1, + dpw.PLOT_HEIGHT, min.getBlockZ() + 1), filling); + PlotHelper.setCuboid(world, new Location(world, min.getBlockX(), + dpw.PLOT_HEIGHT, plotMinZ), + new Location(world, max.getBlockX() + 1, + dpw.PLOT_HEIGHT + 1, min.getBlockZ() + 1), + plotfloor); + + PlotHelper.setSimpleCuboid(world, + new Location(world, max.getBlockX(), 0, plotMinZ), + new Location(world, plotMaxX + 1, 1, min.getBlockZ() + 1), + new PlotBlock((short) 7, (byte) 0)); + PlotHelper.setSimpleCuboid(world, + new Location(world, max.getBlockX(), dpw.PLOT_HEIGHT + 1, + plotMinZ), + new Location(world, plotMaxX + 1, world.getMaxHeight() + 1, + min.getBlockZ() + 1), new PlotBlock((short) 0, + (byte) 0)); + PlotHelper.setCuboid(world, new Location(world, max.getBlockX(), 1, + plotMinZ), new Location(world, plotMaxX + 1, + dpw.PLOT_HEIGHT, min.getBlockZ() + 1), filling); + PlotHelper.setCuboid(world, new Location(world, max.getBlockX(), + dpw.PLOT_HEIGHT, plotMinZ), new Location(world, + plotMaxX + 1, dpw.PLOT_HEIGHT + 1, min.getBlockZ() + 1), + plotfloor); + + PlotHelper + .setSimpleCuboid( + world, + new Location(world, plotMinX, 0, min.getBlockZ()), + new Location(world, min.getBlockX() + 1, 1, max + .getBlockZ() + 1), new PlotBlock((short) 7, + (byte) 0)); + PlotHelper.setSimpleCuboid( + world, + new Location(world, plotMinX, dpw.PLOT_HEIGHT + 1, min + .getBlockZ()), + new Location(world, min.getBlockX() + 1, world + .getMaxHeight() + 1, max.getBlockZ() + 1), + new PlotBlock((short) 0, (byte) 0)); + PlotHelper.setCuboid(world, + new Location(world, plotMinX, 1, min.getBlockZ()), + new Location(world, min.getBlockX() + 1, dpw.PLOT_HEIGHT, + max.getBlockZ() + 1), filling); + PlotHelper.setCuboid(world, new Location(world, plotMinX, + dpw.PLOT_HEIGHT, min.getBlockZ()), + new Location(world, min.getBlockX() + 1, + dpw.PLOT_HEIGHT + 1, max.getBlockZ() + 1), + plotfloor); + + PlotHelper.setSimpleCuboid(world, new Location(world, plotMinX, 0, + max.getBlockZ()), new Location(world, min.getBlockX() + 1, + 1, plotMaxZ + 1), new PlotBlock((short) 7, (byte) 0)); + PlotHelper.setSimpleCuboid( + world, + new Location(world, plotMinX, dpw.PLOT_HEIGHT + 1, max + .getBlockZ()), + new Location(world, min.getBlockX() + 1, world + .getMaxHeight() + 1, plotMaxZ + 1), new PlotBlock( + (short) 0, (byte) 0)); + PlotHelper.setCuboid(world, + new Location(world, plotMinX, 1, max.getBlockZ()), + new Location(world, min.getBlockX() + 1, dpw.PLOT_HEIGHT, + plotMaxZ + 1), filling); + PlotHelper.setCuboid(world, new Location(world, plotMinX, + dpw.PLOT_HEIGHT, max.getBlockZ()), + new Location(world, min.getBlockX() + 1, + dpw.PLOT_HEIGHT + 1, plotMaxZ + 1), plotfloor); + + PlotHelper.setSimpleCuboid(world, + new Location(world, min.getBlockX(), 0, max.getBlockZ()), + new Location(world, max.getBlockX() + 1, 1, plotMaxZ + 1), + new PlotBlock((short) 7, (byte) 0)); + PlotHelper.setSimpleCuboid( + world, + new Location(world, min.getBlockX(), dpw.PLOT_HEIGHT + 1, + max.getBlockZ()), + new Location(world, max.getBlockX() + 1, world + .getMaxHeight() + 1, plotMaxZ + 1), new PlotBlock( + (short) 0, (byte) 0)); + PlotHelper.setCuboid(world, new Location(world, min.getBlockX(), 1, + max.getBlockZ()), new Location(world, max.getBlockX() + 1, + dpw.PLOT_HEIGHT, plotMaxZ + 1), filling); + PlotHelper.setCuboid(world, new Location(world, min.getBlockX(), + dpw.PLOT_HEIGHT, max.getBlockZ()), + new Location(world, max.getBlockX() + 1, + dpw.PLOT_HEIGHT + 1, plotMaxZ + 1), plotfloor); + + PlotHelper.setSimpleCuboid(world, + new Location(world, max.getBlockX(), 0, min.getBlockZ()), + new Location(world, plotMaxX + 1, 1, max.getBlockZ() + 1), + new PlotBlock((short) 7, (byte) 0)); + PlotHelper.setSimpleCuboid(world, + new Location(world, max.getBlockX(), dpw.PLOT_HEIGHT + 1, + max.getBlockZ()), new Location(world, plotMaxX + 1, + world.getMaxHeight() + 1, plotMaxZ + 1), + new PlotBlock((short) 0, (byte) 0)); + PlotHelper.setCuboid(world, new Location(world, max.getBlockX(), 1, + min.getBlockZ()), new Location(world, plotMaxX + 1, + dpw.PLOT_HEIGHT, max.getBlockZ() + 1), filling); + PlotHelper.setCuboid(world, new Location(world, max.getBlockX(), + dpw.PLOT_HEIGHT, min.getBlockZ()), new Location(world, + plotMaxX + 1, dpw.PLOT_HEIGHT + 1, max.getBlockZ() + 1), + plotfloor); + + PlotHelper.setSimpleCuboid(world, + new Location(world, max.getBlockX(), 0, max.getBlockZ()), + new Location(world, plotMaxX + 1, 1, plotMaxZ + 1), + new PlotBlock((short) 7, (byte) 0)); + PlotHelper.setSimpleCuboid(world, + new Location(world, max.getBlockX(), dpw.PLOT_HEIGHT + 1, + max.getBlockZ()), new Location(world, plotMaxX + 1, + world.getMaxHeight() + 1, plotMaxZ + 1), + new PlotBlock((short) 0, (byte) 0)); + PlotHelper.setCuboid(world, new Location(world, max.getBlockX(), 1, + max.getBlockZ()), new Location(world, plotMaxX + 1, + dpw.PLOT_HEIGHT, plotMaxZ + 1), filling); + PlotHelper + .setCuboid(world, new Location(world, max.getBlockX(), + dpw.PLOT_HEIGHT, max.getBlockZ()), new Location( + world, plotMaxX + 1, dpw.PLOT_HEIGHT + 1, + plotMaxZ + 1), plotfloor); + } return true; } - - @Override - public boolean setWall(Player player, PlotWorld plotworld, PlotId plotid, PlotBlock plotblock) { - DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; - World w = player.getWorld(); - Location bottom = PlotHelper.getPlotBottomLoc(w, plotid); - Location top = PlotHelper.getPlotTopLoc(w, plotid); + /* + * Remove sign for a plot + */ + @Override + public Location getSignLoc(Player player, PlotWorld plotworld, Plot plot) { + DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; + World world = player.getWorld(); + return new Location(world, PlotHelper.getPlotBottomLoc(world, plot.id) + .getBlockX(), dpw.ROAD_HEIGHT + 1, PlotHelper.getPlotBottomLoc( + world, plot.id).getBlockZ() - 1); + } - int x, z; + @Override + public boolean setFloor(Player player, PlotWorld plotworld, PlotId plotid, + PlotBlock[] blocks) { + World world = player.getWorld(); + final Location pos1 = PlotHelper.getPlotBottomLoc(world, plotid).add(1, + 0, 1); + final Location pos2 = PlotHelper.getPlotTopLoc(world, plotid); + PlotHelper.setCuboid(world, pos1, pos2, blocks); + return true; + } - Block block; - - // TODO use PlotHelper.setSimpleCuboid rather than this for loop - - for (x = bottom.getBlockX(); x < (top.getBlockX() + 1); x++) { - z = bottom.getBlockZ(); + @Override + public boolean setWall(Player player, PlotWorld plotworld, PlotId plotid, + PlotBlock plotblock) { + DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; + World w = player.getWorld(); - block = w.getBlockAt(x, dpw.ROAD_HEIGHT + 1, z); - PlotHelper.setBlock(block, plotblock); - } + Location bottom = PlotHelper.getPlotBottomLoc(w, plotid); + Location top = PlotHelper.getPlotTopLoc(w, plotid); - for (z = bottom.getBlockZ(); z < (top.getBlockZ() + 1); z++) { - x = top.getBlockX() + 1; + int x, z; - block = w.getBlockAt(x, dpw.ROAD_HEIGHT + 1, z); - PlotHelper.setBlock(block, plotblock); - } + Block block; - for (x = top.getBlockX() + 1; x > (bottom.getBlockX() - 1); x--) { - z = top.getBlockZ() + 1; + // TODO use PlotHelper.setSimpleCuboid rather than this for loop - block = w.getBlockAt(x, dpw.ROAD_HEIGHT + 1, z); - PlotHelper.setBlock(block, plotblock); - } + for (x = bottom.getBlockX(); x < (top.getBlockX() + 1); x++) { + z = bottom.getBlockZ(); - for (z = top.getBlockZ() + 1; z > (bottom.getBlockZ() - 1); z--) { - x = bottom.getBlockX(); - block = w.getBlockAt(x, dpw.ROAD_HEIGHT + 1, z); - PlotHelper.setBlock(block, plotblock); - } - return true; - } + block = w.getBlockAt(x, dpw.ROAD_HEIGHT + 1, z); + PlotHelper.setBlock(block, plotblock); + } - /* - * Set a plot biome - */ - @Override - public boolean setBiome(Player player, Plot plot, Biome biome) { - - World world = player.getWorld(); - - int bottomX = PlotHelper.getPlotBottomLoc(world, plot.id).getBlockX() - 1; - int topX = PlotHelper.getPlotTopLoc(world, plot.id).getBlockX() + 1; - int bottomZ = PlotHelper.getPlotBottomLoc(world, plot.id).getBlockZ() - 1; - int topZ = PlotHelper.getPlotTopLoc(world, plot.id).getBlockZ() + 1; + for (z = bottom.getBlockZ(); z < (top.getBlockZ() + 1); z++) { + x = top.getBlockX() + 1; - for (int x = bottomX; x <= topX; x++) { - for (int z = bottomZ; z <= topZ; z++) { - world.getBlockAt(x, 0, z).setBiome(biome); - } - } + block = w.getBlockAt(x, dpw.ROAD_HEIGHT + 1, z); + PlotHelper.setBlock(block, plotblock); + } - plot.settings.setBiome(biome); - PlotMain.updatePlot(plot); - PlotHelper.refreshPlotChunks(world, plot); - - return true; - } + for (x = top.getBlockX() + 1; x > (bottom.getBlockX() - 1); x--) { + z = top.getBlockZ() + 1; - /* - * PLOT MERGING - */ - - @Override - public boolean createRoadEast(PlotWorld plotworld, Plot plot) { - DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; - World w = Bukkit.getWorld(plot.world); - - Location pos1 = getPlotBottomLocAbs(plotworld, plot.id); - Location pos2 = getPlotTopLocAbs(plotworld, plot.id); + block = w.getBlockAt(x, dpw.ROAD_HEIGHT + 1, z); + PlotHelper.setBlock(block, plotblock); + } - int sx = pos2.getBlockX(); - int ex = (sx + dpw.ROAD_WIDTH); - int sz = pos1.getBlockZ() - 1; - int ez = pos2.getBlockZ() + 2; - - PlotHelper.setSimpleCuboid(w, new Location(w, sx, Math.min(dpw.WALL_HEIGHT, dpw.ROAD_HEIGHT) + 1, sz + 1), new Location(w, ex + 1, 257 + 1, ez), new PlotBlock((short) 0, (byte) 0)); + for (z = top.getBlockZ() + 1; z > (bottom.getBlockZ() - 1); z--) { + x = bottom.getBlockX(); + block = w.getBlockAt(x, dpw.ROAD_HEIGHT + 1, z); + PlotHelper.setBlock(block, plotblock); + } + return true; + } - PlotHelper.setSimpleCuboid(w, new Location(w, sx, 1, sz + 1), new Location(w, sx + 1, dpw.WALL_HEIGHT + 1, ez), dpw.WALL_FILLING); - PlotHelper.setSimpleCuboid(w, new Location(w, sx, dpw.WALL_HEIGHT + 1, sz + 1), new Location(w, sx + 1, dpw.WALL_HEIGHT + 2, ez), dpw.WALL_BLOCK); + /* + * Set a plot biome + */ + @Override + public boolean setBiome(Player player, Plot plot, Biome biome) { - PlotHelper.setSimpleCuboid(w, new Location(w, ex, 1, sz + 1), new Location(w, ex + 1, dpw.WALL_HEIGHT + 1, ez), dpw.WALL_FILLING); - PlotHelper.setSimpleCuboid(w, new Location(w, ex, dpw.WALL_HEIGHT + 1, sz + 1), new Location(w, ex + 1, dpw.WALL_HEIGHT + 2, ez), dpw.WALL_BLOCK); + World world = player.getWorld(); - PlotHelper.setSimpleCuboid(w, new Location(w, sx + 1, 1, sz + 1), new Location(w, ex, dpw.ROAD_HEIGHT + 1, ez), dpw.ROAD_BLOCK); - - return true; - } + int bottomX = PlotHelper.getPlotBottomLoc(world, plot.id).getBlockX() - 1; + int topX = PlotHelper.getPlotTopLoc(world, plot.id).getBlockX() + 1; + int bottomZ = PlotHelper.getPlotBottomLoc(world, plot.id).getBlockZ() - 1; + int topZ = PlotHelper.getPlotTopLoc(world, plot.id).getBlockZ() + 1; - @Override - public boolean createRoadSouth(PlotWorld plotworld, Plot plot) { - DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; - World w = Bukkit.getWorld(plot.world); - - Location pos1 = getPlotBottomLocAbs(plotworld, plot.id); - Location pos2 = getPlotTopLocAbs(plotworld, plot.id); + for (int x = bottomX; x <= topX; x++) { + for (int z = bottomZ; z <= topZ; z++) { + world.getBlockAt(x, 0, z).setBiome(biome); + } + } - int sz = pos2.getBlockZ(); - int ez = (sz + dpw.ROAD_WIDTH); - int sx = pos1.getBlockX() - 1; - int ex = pos2.getBlockX() + 2; - - PlotHelper.setSimpleCuboid(w, new Location(w, sx, Math.min(dpw.WALL_HEIGHT, dpw.ROAD_HEIGHT) + 1, sz + 1), new Location(w, ex + 1, 257, ez), new PlotBlock((short) 0, (byte) 0)); + plot.settings.setBiome(biome); + PlotMain.updatePlot(plot); + PlotHelper.refreshPlotChunks(world, plot); - PlotHelper.setSimpleCuboid(w, new Location(w, sx + 1, 1, sz), new Location(w, ex, dpw.WALL_HEIGHT + 1, sz + 1), dpw.WALL_FILLING); - PlotHelper.setSimpleCuboid(w, new Location(w, sx + 1, dpw.WALL_HEIGHT + 1, sz), new Location(w, ex, dpw.WALL_HEIGHT + 2, sz + 1), dpw.WALL_BLOCK); + return true; + } - PlotHelper.setSimpleCuboid(w, new Location(w, sx + 1, 1, ez), new Location(w, ex, dpw.WALL_HEIGHT + 1, ez + 1), dpw.WALL_FILLING); - PlotHelper.setSimpleCuboid(w, new Location(w, sx + 1, dpw.WALL_HEIGHT + 1, ez), new Location(w, ex, dpw.WALL_HEIGHT + 2, ez + 1), dpw.WALL_BLOCK); + /* + * PLOT MERGING + */ - PlotHelper.setSimpleCuboid(w, new Location(w, sx + 1, 1, sz + 1), new Location(w, ex, dpw.ROAD_HEIGHT + 1, ez), dpw.ROAD_BLOCK); - - return true; - } + @Override + public boolean createRoadEast(PlotWorld plotworld, Plot plot) { + DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; + World w = Bukkit.getWorld(plot.world); - @Override - public boolean createRoadSouthEast(PlotWorld plotworld, Plot plot) { - DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; - World w = Bukkit.getWorld(plot.world); - - Location pos2 = getPlotTopLocAbs(plotworld, plot.id); + Location pos1 = getPlotBottomLocAbs(plotworld, plot.id); + Location pos2 = getPlotTopLocAbs(plotworld, plot.id); - int sx = pos2.getBlockX() + 1; - int ex = (sx + dpw.ROAD_WIDTH) - 1; - int sz = pos2.getBlockZ() + 1; - int ez = (sz + dpw.ROAD_WIDTH) - 1; - - PlotHelper.setSimpleCuboid(w, new Location(w, sx, dpw.ROAD_HEIGHT + 1, sz + 1), new Location(w, ex + 1, 257, ez), new PlotBlock((short) 0, (byte) 0)); - PlotHelper.setSimpleCuboid(w, new Location(w, sx + 1, 1, sz + 1), new Location(w, ex, dpw.ROAD_HEIGHT + 1, ez), dpw.ROAD_BLOCK); - - return true; - } + int sx = pos2.getBlockX(); + int ex = (sx + dpw.ROAD_WIDTH); + int sz = pos1.getBlockZ() - 1; + int ez = pos2.getBlockZ() + 2; - @Override - public boolean removeRoadEast(PlotWorld plotworld, Plot plot) { - DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; - World w = Bukkit.getWorld(plot.world); - - Location pos1 = getPlotBottomLocAbs(plotworld, plot.id); - Location pos2 = getPlotTopLocAbs(plotworld, plot.id); + PlotHelper + .setSimpleCuboid( + w, + new Location(w, sx, Math.min(dpw.WALL_HEIGHT, + dpw.ROAD_HEIGHT) + 1, sz + 1), new Location(w, + ex + 1, 257 + 1, ez), new PlotBlock((short) 0, + (byte) 0)); - int sx = pos2.getBlockX(); - int ex = (sx + dpw.ROAD_WIDTH); - int sz = pos1.getBlockZ() - 1; - int ez = pos2.getBlockZ() + 2; - - PlotHelper.setSimpleCuboid(w, new Location(w, sx, Math.min(dpw.PLOT_HEIGHT, dpw.ROAD_HEIGHT) + 1, sz), new Location(w, ex + 1, 257, ez + 1), new PlotBlock((short) 0, (byte) 0)); - PlotHelper.setCuboid(w, new Location(w, sx, 1, sz), new Location(w, ex + 1, dpw.PLOT_HEIGHT, ez + 1), dpw.MAIN_BLOCK); - PlotHelper.setCuboid(w, new Location(w, sx, dpw.PLOT_HEIGHT, sz), new Location(w, ex + 1, dpw.PLOT_HEIGHT+1, ez + 1), dpw.TOP_BLOCK); - - return true; - } + PlotHelper.setSimpleCuboid(w, new Location(w, sx, 1, sz + 1), + new Location(w, sx + 1, dpw.WALL_HEIGHT + 1, ez), + dpw.WALL_FILLING); + PlotHelper.setSimpleCuboid(w, new Location(w, sx, dpw.WALL_HEIGHT + 1, + sz + 1), new Location(w, sx + 1, dpw.WALL_HEIGHT + 2, ez), + dpw.WALL_BLOCK); - @Override - public boolean removeRoadSouth(PlotWorld plotworld, Plot plot) { - DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; - World w = Bukkit.getWorld(plot.world); - - Location pos1 = getPlotBottomLocAbs(plotworld, plot.id); - Location pos2 = getPlotTopLocAbs(plotworld, plot.id); + PlotHelper.setSimpleCuboid(w, new Location(w, ex, 1, sz + 1), + new Location(w, ex + 1, dpw.WALL_HEIGHT + 1, ez), + dpw.WALL_FILLING); + PlotHelper.setSimpleCuboid(w, new Location(w, ex, dpw.WALL_HEIGHT + 1, + sz + 1), new Location(w, ex + 1, dpw.WALL_HEIGHT + 2, ez), + dpw.WALL_BLOCK); - int sz = pos2.getBlockZ(); - int ez = (sz + dpw.ROAD_WIDTH); - int sx = pos1.getBlockX() - 1; - int ex = pos2.getBlockX() + 2; - - PlotHelper.setSimpleCuboid(w, new Location(w, sx, Math.min(dpw.PLOT_HEIGHT, dpw.ROAD_HEIGHT) + 1, sz), new Location(w, ex + 1, 257, ez + 1), new PlotBlock((short) 0, (byte) 0)); - PlotHelper.setCuboid(w, new Location(w, sx, 1, sz), new Location(w, ex + 1, dpw.PLOT_HEIGHT, ez + 1), dpw.MAIN_BLOCK); - PlotHelper.setCuboid(w, new Location(w, sx, dpw.PLOT_HEIGHT, sz), new Location(w, ex + 1, dpw.PLOT_HEIGHT+1, ez + 1), dpw.TOP_BLOCK); - - return true; - } + PlotHelper.setSimpleCuboid(w, new Location(w, sx + 1, 1, sz + 1), + new Location(w, ex, dpw.ROAD_HEIGHT + 1, ez), dpw.ROAD_BLOCK); - @Override - public boolean removeRoadSouthEast(PlotWorld plotworld, Plot plot) { - DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; - World world = Bukkit.getWorld(plot.world); - - Location loc = getPlotTopLocAbs(dpw, plot.id); + return true; + } - int sx = loc.getBlockX() + 1; - int ex = (sx + dpw.ROAD_WIDTH) - 1; - int sz = loc.getBlockZ() + 1; - int ez = (sz + dpw.ROAD_WIDTH) - 1; + @Override + public boolean createRoadSouth(PlotWorld plotworld, Plot plot) { + DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; + World w = Bukkit.getWorld(plot.world); - PlotHelper.setSimpleCuboid(world, new Location(world, sx, dpw.ROAD_HEIGHT + 1, sz), new Location(world, ex + 1, 257, ez + 1), new PlotBlock((short) 0, (byte) 0)); + Location pos1 = getPlotBottomLocAbs(plotworld, plot.id); + Location pos2 = getPlotTopLocAbs(plotworld, plot.id); - PlotHelper.setCuboid(world, new Location(world, sx + 1, 1, sz + 1), new Location(world, ex, dpw.ROAD_HEIGHT, ez), dpw.MAIN_BLOCK); - PlotHelper.setCuboid(world, new Location(world, sx + 1, dpw.ROAD_HEIGHT, sz + 1), new Location(world, ex, dpw.ROAD_HEIGHT + 1, ez), dpw.TOP_BLOCK); - return true; - } + int sz = pos2.getBlockZ(); + int ez = (sz + dpw.ROAD_WIDTH); + int sx = pos1.getBlockX() - 1; + int ex = pos2.getBlockX() + 2; - /* - * Finishing off plot merging by adding in the walls surrounding the plot - * (OPTIONAL)(UNFINISHED) - */ - @Override - public boolean finishPlotMerge(World world, PlotWorld plotworld, ArrayList plotIds) { - - // TODO set plot wall - - DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; - - PlotId pos1 = plotIds.get(0); - PlotId pos2 = plotIds.get(plotIds.size() - 1); - - PlotBlock block = dpw.WALL_BLOCK; - - Location megaPlotBot = PlotHelper.getPlotBottomLoc(world, pos1); - Location megaPlotTop = PlotHelper.getPlotTopLoc(world, pos2).add(1, 0, 1); - for (int x = megaPlotBot.getBlockX(); x <= megaPlotTop.getBlockX(); x++) { - for (int z = megaPlotBot.getBlockZ(); z <= megaPlotTop.getBlockZ(); z++) { - if ((z == megaPlotBot.getBlockZ()) || (z == megaPlotTop.getBlockZ()) || (x == megaPlotBot.getBlockX()) || (x == megaPlotTop.getBlockX())) { - world.getBlockAt(x, dpw.WALL_HEIGHT + 1, z).setTypeIdAndData(block.id, block.data, false); - } - } - } - return true; - } + PlotHelper + .setSimpleCuboid( + w, + new Location(w, sx, Math.min(dpw.WALL_HEIGHT, + dpw.ROAD_HEIGHT) + 1, sz + 1), new Location(w, + ex + 1, 257, ez), new PlotBlock((short) 0, + (byte) 0)); + + PlotHelper.setSimpleCuboid(w, new Location(w, sx + 1, 1, sz), + new Location(w, ex, dpw.WALL_HEIGHT + 1, sz + 1), + dpw.WALL_FILLING); + PlotHelper.setSimpleCuboid(w, new Location(w, sx + 1, + dpw.WALL_HEIGHT + 1, sz), new Location(w, ex, + dpw.WALL_HEIGHT + 2, sz + 1), dpw.WALL_BLOCK); + + PlotHelper.setSimpleCuboid(w, new Location(w, sx + 1, 1, ez), + new Location(w, ex, dpw.WALL_HEIGHT + 1, ez + 1), + dpw.WALL_FILLING); + PlotHelper.setSimpleCuboid(w, new Location(w, sx + 1, + dpw.WALL_HEIGHT + 1, ez), new Location(w, ex, + dpw.WALL_HEIGHT + 2, ez + 1), dpw.WALL_BLOCK); + + PlotHelper.setSimpleCuboid(w, new Location(w, sx + 1, 1, sz + 1), + new Location(w, ex, dpw.ROAD_HEIGHT + 1, ez), dpw.ROAD_BLOCK); + + return true; + } + + @Override + public boolean createRoadSouthEast(PlotWorld plotworld, Plot plot) { + DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; + World w = Bukkit.getWorld(plot.world); + + Location pos2 = getPlotTopLocAbs(plotworld, plot.id); + + int sx = pos2.getBlockX() + 1; + int ex = (sx + dpw.ROAD_WIDTH) - 1; + int sz = pos2.getBlockZ() + 1; + int ez = (sz + dpw.ROAD_WIDTH) - 1; + + PlotHelper.setSimpleCuboid(w, new Location(w, sx, dpw.ROAD_HEIGHT + 1, + sz + 1), new Location(w, ex + 1, 257, ez), new PlotBlock( + (short) 0, (byte) 0)); + PlotHelper.setSimpleCuboid(w, new Location(w, sx + 1, 1, sz + 1), + new Location(w, ex, dpw.ROAD_HEIGHT + 1, ez), dpw.ROAD_BLOCK); + + return true; + } + + @Override + public boolean removeRoadEast(PlotWorld plotworld, Plot plot) { + DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; + World w = Bukkit.getWorld(plot.world); + + Location pos1 = getPlotBottomLocAbs(plotworld, plot.id); + Location pos2 = getPlotTopLocAbs(plotworld, plot.id); + + int sx = pos2.getBlockX(); + int ex = (sx + dpw.ROAD_WIDTH); + int sz = pos1.getBlockZ() - 1; + int ez = pos2.getBlockZ() + 2; + + PlotHelper.setSimpleCuboid(w, + new Location(w, sx, + Math.min(dpw.PLOT_HEIGHT, dpw.ROAD_HEIGHT) + 1, sz), + new Location(w, ex + 1, 257, ez + 1), new PlotBlock((short) 0, + (byte) 0)); + PlotHelper.setCuboid(w, new Location(w, sx, 1, sz), new Location(w, + ex + 1, dpw.PLOT_HEIGHT, ez + 1), dpw.MAIN_BLOCK); + PlotHelper.setCuboid(w, new Location(w, sx, dpw.PLOT_HEIGHT, sz), + new Location(w, ex + 1, dpw.PLOT_HEIGHT + 1, ez + 1), + dpw.TOP_BLOCK); + + return true; + } + + @Override + public boolean removeRoadSouth(PlotWorld plotworld, Plot plot) { + DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; + World w = Bukkit.getWorld(plot.world); + + Location pos1 = getPlotBottomLocAbs(plotworld, plot.id); + Location pos2 = getPlotTopLocAbs(plotworld, plot.id); + + int sz = pos2.getBlockZ(); + int ez = (sz + dpw.ROAD_WIDTH); + int sx = pos1.getBlockX() - 1; + int ex = pos2.getBlockX() + 2; + + PlotHelper.setSimpleCuboid(w, + new Location(w, sx, + Math.min(dpw.PLOT_HEIGHT, dpw.ROAD_HEIGHT) + 1, sz), + new Location(w, ex + 1, 257, ez + 1), new PlotBlock((short) 0, + (byte) 0)); + PlotHelper.setCuboid(w, new Location(w, sx, 1, sz), new Location(w, + ex + 1, dpw.PLOT_HEIGHT, ez + 1), dpw.MAIN_BLOCK); + PlotHelper.setCuboid(w, new Location(w, sx, dpw.PLOT_HEIGHT, sz), + new Location(w, ex + 1, dpw.PLOT_HEIGHT + 1, ez + 1), + dpw.TOP_BLOCK); + + return true; + } + + @Override + public boolean removeRoadSouthEast(PlotWorld plotworld, Plot plot) { + DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; + World world = Bukkit.getWorld(plot.world); + + Location loc = getPlotTopLocAbs(dpw, plot.id); + + int sx = loc.getBlockX() + 1; + int ex = (sx + dpw.ROAD_WIDTH) - 1; + int sz = loc.getBlockZ() + 1; + int ez = (sz + dpw.ROAD_WIDTH) - 1; + + PlotHelper.setSimpleCuboid(world, new Location(world, sx, + dpw.ROAD_HEIGHT + 1, sz), new Location(world, ex + 1, 257, + ez + 1), new PlotBlock((short) 0, (byte) 0)); + + PlotHelper.setCuboid(world, new Location(world, sx + 1, 1, sz + 1), + new Location(world, ex, dpw.ROAD_HEIGHT, ez), dpw.MAIN_BLOCK); + PlotHelper.setCuboid(world, new Location(world, sx + 1, + dpw.ROAD_HEIGHT, sz + 1), new Location(world, ex, + dpw.ROAD_HEIGHT + 1, ez), dpw.TOP_BLOCK); + return true; + } + + /* + * Finishing off plot merging by adding in the walls surrounding the plot + * (OPTIONAL)(UNFINISHED) + */ + @Override + public boolean finishPlotMerge(World world, PlotWorld plotworld, + ArrayList plotIds) { + + // TODO set plot wall + + DefaultPlotWorld dpw = (DefaultPlotWorld) plotworld; + + PlotId pos1 = plotIds.get(0); + PlotId pos2 = plotIds.get(plotIds.size() - 1); + + PlotBlock block = dpw.WALL_BLOCK; + + Location megaPlotBot = PlotHelper.getPlotBottomLoc(world, pos1); + Location megaPlotTop = PlotHelper.getPlotTopLoc(world, pos2).add(1, 0, + 1); + for (int x = megaPlotBot.getBlockX(); x <= megaPlotTop.getBlockX(); x++) { + for (int z = megaPlotBot.getBlockZ(); z <= megaPlotTop.getBlockZ(); z++) { + if ((z == megaPlotBot.getBlockZ()) + || (z == megaPlotTop.getBlockZ()) + || (x == megaPlotBot.getBlockX()) + || (x == megaPlotTop.getBlockX())) { + world.getBlockAt(x, dpw.WALL_HEIGHT + 1, z) + .setTypeIdAndData(block.id, block.data, false); + } + } + } + return true; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/generator/DefaultPlotWorld.java b/PlotSquared/src/com/intellectualcrafters/plot/generator/DefaultPlotWorld.java index e94c69f5b..3cf73df15 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/generator/DefaultPlotWorld.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/generator/DefaultPlotWorld.java @@ -10,170 +10,194 @@ import com.intellectualcrafters.plot.PlotWorld; public class DefaultPlotWorld extends PlotWorld { - /* - * These variables are set to ensure fast access to config settings - * Strings are used as little as possible to optimize math performance in many of the functions/algorithms - * - */ - - - /** - * Road Height - */ - public int ROAD_HEIGHT; - /** - * Default Road Height: 64 - */ - public static int ROAD_HEIGHT_DEFAULT = 64; + /* + * These variables are set to ensure fast access to config settings Strings + * are used as little as possible to optimize math performance in many of + * the functions/algorithms + */ - /** - * plot height - */ - public int PLOT_HEIGHT; - /** - * Default plot height: 64 - */ - public static int PLOT_HEIGHT_DEFAULT = 64; + /** + * Road Height + */ + public int ROAD_HEIGHT; + /** + * Default Road Height: 64 + */ + public static int ROAD_HEIGHT_DEFAULT = 64; - /** - * Wall height - */ - public int WALL_HEIGHT; - /** - * Default Wall Height: 64 - */ - public static int WALL_HEIGHT_DEFAULT = 64; + /** + * plot height + */ + public int PLOT_HEIGHT; + /** + * Default plot height: 64 + */ + public static int PLOT_HEIGHT_DEFAULT = 64; - /** - * plot width - */ - public int PLOT_WIDTH; - /** - * Default plot width: 32 - */ - public static int PLOT_WIDTH_DEFAULT = 32; + /** + * Wall height + */ + public int WALL_HEIGHT; + /** + * Default Wall Height: 64 + */ + public static int WALL_HEIGHT_DEFAULT = 64; - /** - * Road width - */ - public int ROAD_WIDTH; - /** - * Default road width: 7 - */ - public static int ROAD_WIDTH_DEFAULT = 7; + /** + * plot width + */ + public int PLOT_WIDTH; + /** + * Default plot width: 32 + */ + public static int PLOT_WIDTH_DEFAULT = 32; - /** - * Plot biome - */ - public PlotBlock[] MAIN_BLOCK; - /** - * Default main block: 1 - */ - public static PlotBlock[] MAIN_BLOCK_DEFAULT = new PlotBlock[] { new PlotBlock((short) 1, (byte) 0) }; - /** - * Top blocks - */ - public PlotBlock[] TOP_BLOCK; - /** - * Default top blocks: {"2"} - */ - public static PlotBlock[] TOP_BLOCK_DEFAULT = new PlotBlock[] { new PlotBlock((short) 2, (byte) 0) }; + /** + * Road width + */ + public int ROAD_WIDTH; + /** + * Default road width: 7 + */ + public static int ROAD_WIDTH_DEFAULT = 7; - /** - * Wall block - */ - public PlotBlock WALL_BLOCK; - /** - * Default wall block: 44 - */ - public static String WALL_BLOCK_DEFAULT = "44:0"; + /** + * Plot biome + */ + public PlotBlock[] MAIN_BLOCK; + /** + * Default main block: 1 + */ + public static PlotBlock[] MAIN_BLOCK_DEFAULT = new PlotBlock[] { new PlotBlock( + (short) 1, (byte) 0) }; + /** + * Top blocks + */ + public PlotBlock[] TOP_BLOCK; + /** + * Default top blocks: {"2"} + */ + public static PlotBlock[] TOP_BLOCK_DEFAULT = new PlotBlock[] { new PlotBlock( + (short) 2, (byte) 0) }; - /** - * Wall filling - */ - public PlotBlock WALL_FILLING; - /** - * Default wall filling: 1 - */ - public static PlotBlock WALL_FILLING_DEFAULT = new PlotBlock((short) 1, (byte) 0); + /** + * Wall block + */ + public PlotBlock WALL_BLOCK; + /** + * Default wall block: 44 + */ + public static String WALL_BLOCK_DEFAULT = "44:0"; - /** - * Road stripes - */ - public PlotBlock ROAD_STRIPES; - /** - * Default road stripes: 35 - */ - public static PlotBlock ROAD_STRIPES_DEFAULT = new PlotBlock((short) 98, (byte) 0); - /** - * enable road stripes - */ - public boolean ROAD_STRIPES_ENABLED; - public static boolean ROAD_STRIPES_ENABLED_DEFAULT = false; - /** - * Road block - */ - public PlotBlock ROAD_BLOCK; - /** - * Default road block: 155 - */ - public static PlotBlock ROAD_BLOCK_DEFAULT = new PlotBlock((short) 155, (byte) 0); - - - /* - * Here we are just calling the super method, nothing special - */ - public DefaultPlotWorld(String worldname) { - super(worldname); - } + /** + * Wall filling + */ + public PlotBlock WALL_FILLING; + /** + * Default wall filling: 1 + */ + public static PlotBlock WALL_FILLING_DEFAULT = new PlotBlock((short) 1, + (byte) 0); - /* - * CONFIG NODE | DEFAULT VALUE | DESCRIPTION | CONFIGURATION TYPE | REQUIRED FOR INITIAL SETUP - * - * Set the last boolean to false if you do not require a specific config node to be set while using the setup command - * - this may be useful if a config value can be changed at a later date, and has no impact on the actual world generation - * - */ - @Override - public ConfigurationNode[] getSettingNodes() { - // TODO return a set of configuration nodes (used for setup command) - return - new ConfigurationNode[] { - new ConfigurationNode("plot.height", PLOT_HEIGHT, "Plot height", Configuration.INTEGER, true), - new ConfigurationNode("plot.width", PLOT_WIDTH, "Plot width", Configuration.INTEGER, true), - new ConfigurationNode("plot.filling", MAIN_BLOCK, "Plot block", Configuration.BLOCKLIST, true), - new ConfigurationNode("plot.floor", TOP_BLOCK, "Plot floor block", Configuration.BLOCKLIST, true), - new ConfigurationNode("wall.block", WALL_BLOCK, "Top wall block", Configuration.BLOCK, true), - new ConfigurationNode("road.width", ROAD_WIDTH, "Road width", Configuration.INTEGER, true), - new ConfigurationNode("road.height", ROAD_HEIGHT, "Road height", Configuration.INTEGER, true), - new ConfigurationNode("road.enable_stripes", ROAD_STRIPES_ENABLED, "Enable road stripes", Configuration.BOOLEAN, true), - new ConfigurationNode("road.block", ROAD_BLOCK, "Road block", Configuration.BLOCK, true), - new ConfigurationNode("road.stripes", ROAD_STRIPES, "Road stripe block", Configuration.BLOCK, true), - new ConfigurationNode("wall.filling", WALL_FILLING, "Wall filling block", Configuration.BLOCK, true), - new ConfigurationNode("wall.height", WALL_HEIGHT, "Wall height", Configuration.INTEGER, true), - }; - } + /** + * Road stripes + */ + public PlotBlock ROAD_STRIPES; + /** + * Default road stripes: 35 + */ + public static PlotBlock ROAD_STRIPES_DEFAULT = new PlotBlock((short) 98, + (byte) 0); + /** + * enable road stripes + */ + public boolean ROAD_STRIPES_ENABLED; + public static boolean ROAD_STRIPES_ENABLED_DEFAULT = false; + /** + * Road block + */ + public PlotBlock ROAD_BLOCK; + /** + * Default road block: 155 + */ + public static PlotBlock ROAD_BLOCK_DEFAULT = new PlotBlock((short) 155, + (byte) 0); - /* - * This method is called when a world loads. Make sure you set all your constants here. - * You are provided with the configuration section for that specific world. - */ - @Override - public void loadConfiguration(ConfigurationSection config) { - - this.PLOT_HEIGHT = config.getInt("plot.height"); - this.PLOT_WIDTH = config.getInt("plot.width"); - this.MAIN_BLOCK = (PlotBlock[]) Configuration.BLOCKLIST.parseString(StringUtils.join(config.getStringList("plot.filling"),',')); - this.TOP_BLOCK = (PlotBlock[]) Configuration.BLOCKLIST.parseString(StringUtils.join(config.getStringList("plot.floor"),',')); - this.WALL_BLOCK = (PlotBlock) Configuration.BLOCK.parseString(config.getString("wall.block")); - this.ROAD_WIDTH = config.getInt("road.width"); - this.ROAD_HEIGHT = config.getInt("road.height"); - this.ROAD_STRIPES_ENABLED = config.getBoolean("road.enable_stripes"); - this.ROAD_BLOCK = (PlotBlock) Configuration.BLOCK.parseString(config.getString("road.block")); - this.ROAD_STRIPES = (PlotBlock) Configuration.BLOCK.parseString(config.getString("road.stripes")); - this.WALL_FILLING = (PlotBlock) Configuration.BLOCK.parseString(config.getString("wall.filling")); - this.WALL_HEIGHT = config.getInt("wall.height"); - - } + /* + * Here we are just calling the super method, nothing special + */ + public DefaultPlotWorld(String worldname) { + super(worldname); + } + + /* + * CONFIG NODE | DEFAULT VALUE | DESCRIPTION | CONFIGURATION TYPE | REQUIRED + * FOR INITIAL SETUP + * + * Set the last boolean to false if you do not require a specific config + * node to be set while using the setup command - this may be useful if a + * config value can be changed at a later date, and has no impact on the + * actual world generation + */ + @Override + public ConfigurationNode[] getSettingNodes() { + // TODO return a set of configuration nodes (used for setup command) + return new ConfigurationNode[] { + new ConfigurationNode("plot.height", this.PLOT_HEIGHT, + "Plot height", Configuration.INTEGER, true), + new ConfigurationNode("plot.width", this.PLOT_WIDTH, + "Plot width", Configuration.INTEGER, true), + new ConfigurationNode("plot.filling", this.MAIN_BLOCK, + "Plot block", Configuration.BLOCKLIST, true), + new ConfigurationNode("plot.floor", this.TOP_BLOCK, + "Plot floor block", Configuration.BLOCKLIST, true), + new ConfigurationNode("wall.block", this.WALL_BLOCK, + "Top wall block", Configuration.BLOCK, true), + new ConfigurationNode("road.width", this.ROAD_WIDTH, + "Road width", Configuration.INTEGER, true), + new ConfigurationNode("road.height", this.ROAD_HEIGHT, + "Road height", Configuration.INTEGER, true), + new ConfigurationNode("road.enable_stripes", + this.ROAD_STRIPES_ENABLED, "Enable road stripes", + Configuration.BOOLEAN, true), + new ConfigurationNode("road.block", this.ROAD_BLOCK, + "Road block", Configuration.BLOCK, true), + new ConfigurationNode("road.stripes", this.ROAD_STRIPES, + "Road stripe block", Configuration.BLOCK, true), + new ConfigurationNode("wall.filling", this.WALL_FILLING, + "Wall filling block", Configuration.BLOCK, true), + new ConfigurationNode("wall.height", this.WALL_HEIGHT, + "Wall height", Configuration.INTEGER, true), }; + } + + /* + * This method is called when a world loads. Make sure you set all your + * constants here. You are provided with the configuration section for that + * specific world. + */ + @Override + public void loadConfiguration(ConfigurationSection config) { + + this.PLOT_HEIGHT = config.getInt("plot.height"); + this.PLOT_WIDTH = config.getInt("plot.width"); + this.MAIN_BLOCK = (PlotBlock[]) Configuration.BLOCKLIST + .parseString(StringUtils.join( + config.getStringList("plot.filling"), ',')); + this.TOP_BLOCK = (PlotBlock[]) Configuration.BLOCKLIST + .parseString(StringUtils.join( + config.getStringList("plot.floor"), ',')); + this.WALL_BLOCK = (PlotBlock) Configuration.BLOCK.parseString(config + .getString("wall.block")); + this.ROAD_WIDTH = config.getInt("road.width"); + this.ROAD_HEIGHT = config.getInt("road.height"); + this.ROAD_STRIPES_ENABLED = config.getBoolean("road.enable_stripes"); + this.ROAD_BLOCK = (PlotBlock) Configuration.BLOCK.parseString(config + .getString("road.block")); + this.ROAD_STRIPES = (PlotBlock) Configuration.BLOCK.parseString(config + .getString("road.stripes")); + this.WALL_FILLING = (PlotBlock) Configuration.BLOCK.parseString(config + .getString("wall.filling")); + this.WALL_HEIGHT = config.getInt("wall.height"); + + } } - \ No newline at end of file diff --git a/PlotSquared/src/com/intellectualcrafters/plot/generator/WorldGenerator.java b/PlotSquared/src/com/intellectualcrafters/plot/generator/WorldGenerator.java index 577fb6c87..f6c6e04d7 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/generator/WorldGenerator.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/generator/WorldGenerator.java @@ -8,7 +8,6 @@ import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.generator.BlockPopulator; -import org.bukkit.generator.ChunkGenerator; import com.intellectualcrafters.plot.PlotBlock; import com.intellectualcrafters.plot.PlotGenerator; @@ -16,511 +15,603 @@ import com.intellectualcrafters.plot.PlotManager; import com.intellectualcrafters.plot.PlotWorld; /** - * + * * @auther Empire92 * @author Citymonstret - * - * The default generator is very messy, as we have decided to try externalize all calculations from within the loop. - * - You will see a lot of slower implementations have a single for loop. - * - This is perfectly fine to do, it will just mean world generation may take somewhat longer - * + * + * The default generator is very messy, as we have decided to try + * externalize all calculations from within the loop. - You will see a + * lot of slower implementations have a single for loop. - This is + * perfectly fine to do, it will just mean world generation may take + * somewhat longer + * */ public class WorldGenerator extends PlotGenerator { - /* - * result object is returned for each generated chunk, do stuff to it - */ - short[][] result; - - /* - * plotworld object - */ - DefaultPlotWorld plotworld; - /* - * Set to static to re-use the same managet for all Default World Generators - */ - private static PlotManager manager = null; - - /* - * Some generator specific variables (implementation dependent) - */ - int plotsize; - int pathsize; - PlotBlock wall; - PlotBlock wallfilling; - PlotBlock floor1; - PlotBlock floor2; - int size; - Biome biome; - int roadheight; - int wallheight; - int plotheight; - PlotBlock[] plotfloors; - PlotBlock[] filling; - - /* - * Return the plot manager for this type of generator, or create one - * - */ - @Override - public PlotManager getPlotManager() { - if (manager==null) { - manager = new DefaultPlotManager(); - } - return null; - } - - // return the PlotWorld - - @Override - public PlotWorld getPlotWorld() { - return this.plotworld; - } + /* + * result object is returned for each generated chunk, do stuff to it + */ + short[][] result; - /* - * Faster sudo-random number generator than java.util.random - */ - private long state; - public final long nextLong() { - long a = this.state; - this.state = xorShift64(a); - return a; - } + /* + * plotworld object + */ + DefaultPlotWorld plotworld; + /* + * Set to static to re-use the same managet for all Default World Generators + */ + private static PlotManager manager = null; - public final long xorShift64(long a) { - a ^= (a << 21); - a ^= (a >>> 35); - a ^= (a << 4); - return a; - } + /* + * Some generator specific variables (implementation dependent) + */ + int plotsize; + int pathsize; + PlotBlock wall; + PlotBlock wallfilling; + PlotBlock floor1; + PlotBlock floor2; + int size; + Biome biome; + int roadheight; + int wallheight; + int plotheight; + PlotBlock[] plotfloors; + PlotBlock[] filling; - public final int random(int n) { - long r = ((nextLong() >>> 32) * n) >> 32; - return (int) r; - } - - /* - * Cuboid based plot generation is quick, as it requires no calculations inside the loop - * - You don't have to use this this method, but you may find it useful. - */ - public void setCuboidRegion(int x1, int x2, int y1, int y2, int z1, int z2, PlotBlock block) { - for (int x = x1; x < x2; x++) { - for (int z = z1; z < z2; z++) { - for (int y = y1; y < y2; y++) { - setBlock(this.result, x, y, z, block.data); - } - } - } - } + /* + * Return the plot manager for this type of generator, or create one + */ + @Override + public PlotManager getPlotManager() { + if (manager == null) { + manager = new DefaultPlotManager(); + } + return null; + } - private void setCuboidRegion(int x1, int x2, int y1, int y2, int z1, int z2, PlotBlock[] blocks) { - if (blocks.length == 1) { - setCuboidRegion(x1, x2, y1, y2, z1, z2, blocks[0]); - } else { - for (int x = x1; x < x2; x++) { - for (int z = z1; z < z2; z++) { - for (int y = y1; y < y2; y++) { - int i = random(blocks.length); - setBlock(this.result, x, y, z, blocks[i].id); - } - } - } - } - } - - /* - * Standard setblock method for world generation - */ - private void setBlock(short[][] result, int x, int y, int z, short blkid) { - if (result[y >> 4] == null) { - result[y >> 4] = new short[4096]; - } - result[y >> 4][((y & 0xF) << 8) | (z << 4) | x] = blkid; - } - - /* - * Initialize variables, and create plotworld object used in calculations - */ - public WorldGenerator(String world) { - this.plotworld = new DefaultPlotWorld(world); + // return the PlotWorld - plotsize = plotworld.PLOT_WIDTH; - pathsize = plotworld.ROAD_WIDTH; + @Override + public PlotWorld getPlotWorld() { + return this.plotworld; + } - floor1 = plotworld.ROAD_BLOCK; - floor2 = plotworld.ROAD_STRIPES; - - wallfilling = plotworld.WALL_FILLING; - size = pathsize + plotsize; - wall = plotworld.WALL_BLOCK; + /* + * Faster sudo-random number generator than java.util.random + */ + private long state; - plotfloors = plotworld.TOP_BLOCK; - filling = plotworld.MAIN_BLOCK; - wallheight = plotworld.WALL_HEIGHT; - roadheight = plotworld.ROAD_HEIGHT; - plotheight = plotworld.PLOT_HEIGHT; + public final long nextLong() { + long a = this.state; + this.state = xorShift64(a); + return a; + } - biome = plotworld.PLOT_BIOME; - } + public final long xorShift64(long a) { + a ^= (a << 21); + a ^= (a >>> 35); + a ^= (a << 4); + return a; + } - /* - * Return the block populator - */ - @Override - public List getDefaultPopulators(World world) { - // disabling spawning for this world - if (!this.plotworld.MOB_SPAWNING) { - world.setSpawnFlags(false, false); - world.setAmbientSpawnLimit(0); - world.setAnimalSpawnLimit(0); - world.setMonsterSpawnLimit(0); - world.setWaterAnimalSpawnLimit(0); - } - // You can have as many populators as you would like, e.g. tree populator, ore populator - return Arrays.asList((BlockPopulator) new XPopulator(plotworld)); - } + public final int random(int n) { + long r = ((nextLong() >>> 32) * n) >> 32; + return (int) r; + } - /* - * Return the default spawn location for this world - */ - @Override - public Location getFixedSpawnLocation(World world, Random random) { - return new Location(world, 0, plotworld.ROAD_HEIGHT + 2, 0); - } + /* + * Cuboid based plot generation is quick, as it requires no calculations + * inside the loop - You don't have to use this this method, but you may + * find it useful. + */ + public void setCuboidRegion(int x1, int x2, int y1, int y2, int z1, int z2, + PlotBlock block) { + for (int x = x1; x < x2; x++) { + for (int z = z1; z < z2; z++) { + for (int y = y1; y < y2; y++) { + setBlock(this.result, x, y, z, block.data); + } + } + } + } - /* - * This part is a fucking mess. - * - Refer to a proper tutorial if you would like to learn how to make a world generator - */ - @Override - public short[][] generateExtBlockSections(World world, Random random, int cx, int cz, BiomeGrid biomes) { - - final int prime = 31; - int h = 1; - h = (prime * h) + cx; - h = (prime * h) + cz; - this.state = h; - - int maxY = world.getMaxHeight(); + private void setCuboidRegion(int x1, int x2, int y1, int y2, int z1, + int z2, PlotBlock[] blocks) { + if (blocks.length == 1) { + setCuboidRegion(x1, x2, y1, y2, z1, z2, blocks[0]); + } else { + for (int x = x1; x < x2; x++) { + for (int z = z1; z < z2; z++) { + for (int y = y1; y < y2; y++) { + int i = random(blocks.length); + setBlock(this.result, x, y, z, blocks[i].id); + } + } + } + } + } - this.result = new short[maxY / 16][]; - double pathWidthLower; - if ((this.pathsize % 2) == 0) { - pathWidthLower = Math.floor(this.pathsize / 2) - 1; - } else { - pathWidthLower = Math.floor(this.pathsize / 2); - } - - cx = (cx % this.size) + (8 * this.size); - cz = (cz % this.size) + (8 * this.size); - int absX = (int) ((((cx * 16) + 16) - pathWidthLower - 1) + (8 * this.size)); - int absZ = (int) ((((cz * 16) + 16) - pathWidthLower - 1) + (8 * this.size)); - int plotMinX = (((absX) % this.size)); - int plotMinZ = (((absZ) % this.size)); - int roadStartX = (plotMinX + this.pathsize); - int roadStartZ = (plotMinZ + this.pathsize); - if (roadStartX >= this.size) { - roadStartX -= this.size; - } - if (roadStartZ >= this.size) { - roadStartZ -= this.size; - } + /* + * Standard setblock method for world generation + */ + private void setBlock(short[][] result, int x, int y, int z, short blkid) { + if (result[y >> 4] == null) { + result[y >> 4] = new short[4096]; + } + result[y >> 4][((y & 0xF) << 8) | (z << 4) | x] = blkid; + } - // BOTTOM (1/1 cuboids) - for (int x = 0; x < 16; x++) { - for (int z = 0; z < 16; z++) { - setBlock(this.result, x, 0, z, (short) 7); - biomes.setBiome(x, z, this.biome); - } - } - // ROAD (0/24) The following is an inefficient placeholder as it is too - // much work to finish it + /* + * Initialize variables, and create plotworld object used in calculations + */ + public WorldGenerator(String world) { + this.plotworld = new DefaultPlotWorld(world); - if ((this.pathsize > 16) && ((plotMinX > roadStartX) || (plotMinZ > roadStartZ)) && !((roadStartX < 16) && (roadStartZ < 16)) && (((roadStartX > 16) && (roadStartZ > 16)) || ((plotMinX > roadStartX) && (plotMinZ > roadStartZ)))) { - setCuboidRegion(0, 16, 1, this.roadheight + 1, 0, 16, this.floor1); - return this.result; - } + this.plotsize = this.plotworld.PLOT_WIDTH; + this.pathsize = this.plotworld.ROAD_WIDTH; - if (((plotMinZ + 1) <= 16) || ((roadStartZ <= 16) && (roadStartZ > 0))) { - int start = Math.max((16 - plotMinZ - this.pathsize) + 1, (16 - roadStartZ) + 1); - int end = Math.min(16 - plotMinZ - 1, (16 - roadStartZ) + this.pathsize); - if ((start >= 0) && (start <= 16) && (end < 0)) { - end = 16; - } - setCuboidRegion(0, 16, 1, this.roadheight + 1, Math.max(start, 0), Math.min(16, end), this.floor1); - } - if (((plotMinX + 1) <= 16) || ((roadStartX <= 16) && (roadStartX > 0))) { - int start = Math.max((16 - plotMinX - this.pathsize) + 1, (16 - roadStartX) + 1); - int end = Math.min(16 - plotMinX - 1, (16 - roadStartX) + this.pathsize); - if ((start >= 0) && (start <= 16) && (end < 0)) { - end = 16; - } - setCuboidRegion(Math.max(start, 0), Math.min(16, end), 1, this.roadheight + 1, 0, 16, this.floor1); - } + this.floor1 = this.plotworld.ROAD_BLOCK; + this.floor2 = this.plotworld.ROAD_STRIPES; - // ROAD STRIPES - if ((this.pathsize > 4) && this.plotworld.ROAD_STRIPES_ENABLED) { - if ((plotMinZ + 2) <= 16) { - int value = (plotMinZ + 2); - int start, end; - if ((plotMinX + 2) <= 16) { - start = 16 - plotMinX - 1; - } else { - start = 16; - } - if ((roadStartX - 1) <= 16) { - end = (16 - roadStartX) + 1; - } else { - end = 0; - } - if (!(((plotMinX + 2) <= 16) || ((roadStartX - 1) <= 16))) { - start = 0; - } - setCuboidRegion(0, end, this.wallheight, this.wallheight + 1, 16 - value, (16 - value) + 1, this.floor2); // - setCuboidRegion(start, 16, this.wallheight, this.wallheight + 1, 16 - value, (16 - value) + 1, this.floor2); // - } - if ((plotMinX + 2) <= 16) { - int value = (plotMinX + 2); - int start, end; - if ((plotMinZ + 2) <= 16) { - start = 16 - plotMinZ - 1; - } else { - start = 16; - } - if ((roadStartZ - 1) <= 16) { - end = (16 - roadStartZ) + 1; - } else { - end = 0; - } - if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) { - start = 0; - } - setCuboidRegion(16 - value, (16 - value) + 1, this.wallheight, this.wallheight + 1, 0, end, this.floor2); // - setCuboidRegion(16 - value, (16 - value) + 1, this.wallheight, this.wallheight + 1, start, 16, this.floor2); // - } - if ((roadStartZ <= 16) && (roadStartZ > 1)) { - int val = roadStartZ; - int start, end; - if ((plotMinX + 2) <= 16) { - start = 16 - plotMinX - 1; - } else { - start = 16; - } - if ((roadStartX - 1) <= 16) { - end = (16 - roadStartX) + 1; - } else { - end = 0; - } - if (!(((plotMinX + 2) <= 16) || ((roadStartX - 1) <= 16))) { - start = 0; - } - setCuboidRegion(0, end, this.wallheight, this.wallheight + 1, (16 - val) + 1, (16 - val) + 2, this.floor2); - setCuboidRegion(start, 16, this.wallheight, this.wallheight + 1, (16 - val) + 1, (16 - val) + 2, this.floor2); - } - if ((roadStartX <= 16) && (roadStartX > 1)) { - int val = roadStartX; - int start, end; - if ((plotMinZ + 2) <= 16) { - start = 16 - plotMinZ - 1; - } else { - start = 16; - } - if ((roadStartZ - 1) <= 16) { - end = (16 - roadStartZ) + 1; - } else { - end = 0; - } - if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) { - start = 0; - } - setCuboidRegion((16 - val) + 1, (16 - val) + 2, this.wallheight, this.wallheight + 1, 0, end, this.floor2); // - setCuboidRegion((16 - val) + 1, (16 - val) + 2, this.wallheight, this.wallheight + 1, start, 16, this.floor2); // - } - } + this.wallfilling = this.plotworld.WALL_FILLING; + this.size = this.pathsize + this.plotsize; + this.wall = this.plotworld.WALL_BLOCK; - // Plot filling (28/28 cuboids) (10x2 + 4x2) - if (this.plotsize > 16) { - if (roadStartX <= 16) { - if (roadStartZ <= 16) { - setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 0, 16 - roadStartZ, this.filling); - setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors); - } - if (plotMinZ <= 16) { - setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 16 - plotMinZ, 16, this.filling); - setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors); - } - } else { - if (roadStartZ <= 16) { - if (plotMinX > 16) { - setCuboidRegion(0, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.filling); - setCuboidRegion(0, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors); - } - } - } - if (plotMinX <= 16) { - if (plotMinZ <= 16) { - setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 16 - plotMinZ, 16, this.filling); - setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors); - } else { - int z = 16 - roadStartZ; - if (z < 0) { - z = 16; - } - setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, z, this.filling); - setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, z, this.plotfloors); - } - if (roadStartZ <= 16) { - setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.filling); - setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors); - } else { - if (roadStartX <= 16) { - if (plotMinZ > 16) { - int x = 16 - roadStartX; - if (x < 0) { - x = 16; - } - setCuboidRegion(0, x, 1, this.plotheight, 0, 16, this.filling); - setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, 16, this.plotfloors); - } - } - } - } else { - if (plotMinZ <= 16) { - if (roadStartX > 16) { - int x = 16 - roadStartX; - if (x < 0) { - x = 16; - } - setCuboidRegion(0, x, 1, this.plotheight, 16 - plotMinZ, 16, this.filling); - setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors); - } - } else { - if (roadStartZ > 16) { - int x = 16 - roadStartX; - if (x < 0) { - x = 16; - } - int z = 16 - roadStartZ; - if (z < 0) { - z = 16; - } - if (roadStartX > 16) { - setCuboidRegion(0, x, 1, this.plotheight, 0, z, this.filling); - setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, z, this.plotfloors); - } else { - setCuboidRegion(0, x, 1, this.plotheight, 0, z, this.filling); - setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, z, this.plotfloors); - } - } - } - } - } else { - if (roadStartX <= 16) { - if (roadStartZ <= 16) { - setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 0, 16 - roadStartZ, this.filling); - setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors); - } - if (plotMinZ <= 16) { - setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 16 - plotMinZ, 16, this.filling); - setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors); - } - } - if (plotMinX <= 16) { - if (plotMinZ <= 16) { - setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 16 - plotMinZ, 16, this.filling); - setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors); - } - if (roadStartZ <= 16) { - setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.filling); - setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors); - } - } - } + this.plotfloors = this.plotworld.TOP_BLOCK; + this.filling = this.plotworld.MAIN_BLOCK; + this.wallheight = this.plotworld.WALL_HEIGHT; + this.roadheight = this.plotworld.ROAD_HEIGHT; + this.plotheight = this.plotworld.PLOT_HEIGHT; - // WALLS (16/16 cuboids) - if (this.pathsize > 0) { - if ((plotMinZ + 1) <= 16) { - int start, end; - if ((plotMinX + 2) <= 16) { - start = 16 - plotMinX - 1; - } else { - start = 16; - } - if ((roadStartX - 1) <= 16) { - end = (16 - roadStartX) + 1; - } else { - end = 0; - } - if (!(((plotMinX + 2) <= 16) || ((roadStartX - 1) <= 16))) { - start = 0; - } - setCuboidRegion(0, end, 1, this.wallheight + 1, 16 - plotMinZ - 1, 16 - plotMinZ, this.wallfilling); - setCuboidRegion(0, end, this.wallheight + 1, this.wallheight + 2, 16 - plotMinZ - 1, 16 - plotMinZ, this.wall); - setCuboidRegion(start, 16, 1, this.wallheight + 1, 16 - plotMinZ - 1, 16 - plotMinZ, this.wallfilling); - setCuboidRegion(start, 16, this.wallheight + 1, this.wallheight + 2, 16 - plotMinZ - 1, 16 - plotMinZ, this.wall); - } - if ((plotMinX + 1) <= 16) { - int start, end; - if ((plotMinZ + 2) <= 16) { - start = 16 - plotMinZ - 1; - } else { - start = 16; - } - if ((roadStartZ - 1) <= 16) { - end = (16 - roadStartZ) + 1; - } else { - end = 0; - } - if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) { - start = 0; - } - setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, 1, this.wallheight + 1, 0, end, this.wallfilling); - setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, this.wallheight + 1, this.wallheight + 2, 0, end, this.wall); - setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, 1, this.wallheight + 1, start, 16, this.wallfilling); - setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, this.wallheight + 1, this.wallheight + 2, start, 16, this.wall); - } - if ((roadStartZ <= 16) && (roadStartZ > 0)) { - int start, end; - if ((plotMinX + 1) <= 16) { - start = 16 - plotMinX; - } else { - start = 16; - } - if ((roadStartX + 1) <= 16) { - end = (16 - roadStartX) + 1; - } else { - end = 0; - } - if (!(((plotMinX + 1) <= 16) || (roadStartX <= 16))) { - start = 0; - } - setCuboidRegion(0, end, 1, this.wallheight + 1, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wallfilling); - setCuboidRegion(0, end, this.wallheight + 1, this.wallheight + 2, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wall); - setCuboidRegion(start, 16, 1, this.wallheight + 1, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wallfilling); - setCuboidRegion(start, 16, this.wallheight + 1, this.wallheight + 2, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wall); - } - if ((roadStartX <= 16) && (roadStartX > 0)) { - int start, end; - if ((plotMinZ + 1) <= 16) { - start = 16 - plotMinZ; - } else { - start = 16; - } - if ((roadStartZ + 1) <= 16) { - end = (16 - roadStartZ) + 1; - } else { - end = 0; - } - if (!(((plotMinZ + 1) <= 16) || ((roadStartZ + 1) <= 16))) { - start = 0; - } - setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, 1, this.wallheight + 1, 0, end, this.wallfilling); - setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, this.wallheight + 1, this.roadheight + 2, 0, end, this.wall); - setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, 1, this.wallheight + 1, start, 16, this.wallfilling); - setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, this.wallheight + 1, this.wallheight + 2, start, 16, this.wall); - } - } - // Return the chunk - return this.result; - } + this.biome = this.plotworld.PLOT_BIOME; + } + + /* + * Return the block populator + */ + @Override + public List getDefaultPopulators(World world) { + // disabling spawning for this world + if (!this.plotworld.MOB_SPAWNING) { + world.setSpawnFlags(false, false); + world.setAmbientSpawnLimit(0); + world.setAnimalSpawnLimit(0); + world.setMonsterSpawnLimit(0); + world.setWaterAnimalSpawnLimit(0); + } + // You can have as many populators as you would like, e.g. tree + // populator, ore populator + return Arrays.asList((BlockPopulator) new XPopulator(this.plotworld)); + } + + /* + * Return the default spawn location for this world + */ + @Override + public Location getFixedSpawnLocation(World world, Random random) { + return new Location(world, 0, this.plotworld.ROAD_HEIGHT + 2, 0); + } + + /* + * This part is a fucking mess. - Refer to a proper tutorial if you would + * like to learn how to make a world generator + */ + @Override + public short[][] generateExtBlockSections(World world, Random random, + int cx, int cz, BiomeGrid biomes) { + + final int prime = 31; + int h = 1; + h = (prime * h) + cx; + h = (prime * h) + cz; + this.state = h; + + int maxY = world.getMaxHeight(); + + this.result = new short[maxY / 16][]; + double pathWidthLower; + if ((this.pathsize % 2) == 0) { + pathWidthLower = Math.floor(this.pathsize / 2) - 1; + } else { + pathWidthLower = Math.floor(this.pathsize / 2); + } + + cx = (cx % this.size) + (8 * this.size); + cz = (cz % this.size) + (8 * this.size); + int absX = (int) ((((cx * 16) + 16) - pathWidthLower - 1) + (8 * this.size)); + int absZ = (int) ((((cz * 16) + 16) - pathWidthLower - 1) + (8 * this.size)); + int plotMinX = (((absX) % this.size)); + int plotMinZ = (((absZ) % this.size)); + int roadStartX = (plotMinX + this.pathsize); + int roadStartZ = (plotMinZ + this.pathsize); + if (roadStartX >= this.size) { + roadStartX -= this.size; + } + if (roadStartZ >= this.size) { + roadStartZ -= this.size; + } + + // BOTTOM (1/1 cuboids) + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + setBlock(this.result, x, 0, z, (short) 7); + biomes.setBiome(x, z, this.biome); + } + } + // ROAD (0/24) The following is an inefficient placeholder as it is too + // much work to finish it + + if ((this.pathsize > 16) + && ((plotMinX > roadStartX) || (plotMinZ > roadStartZ)) + && !((roadStartX < 16) && (roadStartZ < 16)) + && (((roadStartX > 16) && (roadStartZ > 16)) || ((plotMinX > roadStartX) && (plotMinZ > roadStartZ)))) { + setCuboidRegion(0, 16, 1, this.roadheight + 1, 0, 16, this.floor1); + return this.result; + } + + if (((plotMinZ + 1) <= 16) || ((roadStartZ <= 16) && (roadStartZ > 0))) { + int start = Math.max((16 - plotMinZ - this.pathsize) + 1, + (16 - roadStartZ) + 1); + int end = Math.min(16 - plotMinZ - 1, (16 - roadStartZ) + + this.pathsize); + if ((start >= 0) && (start <= 16) && (end < 0)) { + end = 16; + } + setCuboidRegion(0, 16, 1, this.roadheight + 1, Math.max(start, 0), + Math.min(16, end), this.floor1); + } + if (((plotMinX + 1) <= 16) || ((roadStartX <= 16) && (roadStartX > 0))) { + int start = Math.max((16 - plotMinX - this.pathsize) + 1, + (16 - roadStartX) + 1); + int end = Math.min(16 - plotMinX - 1, (16 - roadStartX) + + this.pathsize); + if ((start >= 0) && (start <= 16) && (end < 0)) { + end = 16; + } + setCuboidRegion(Math.max(start, 0), Math.min(16, end), 1, + this.roadheight + 1, 0, 16, this.floor1); + } + + // ROAD STRIPES + if ((this.pathsize > 4) && this.plotworld.ROAD_STRIPES_ENABLED) { + if ((plotMinZ + 2) <= 16) { + int value = (plotMinZ + 2); + int start, end; + if ((plotMinX + 2) <= 16) { + start = 16 - plotMinX - 1; + } else { + start = 16; + } + if ((roadStartX - 1) <= 16) { + end = (16 - roadStartX) + 1; + } else { + end = 0; + } + if (!(((plotMinX + 2) <= 16) || ((roadStartX - 1) <= 16))) { + start = 0; + } + setCuboidRegion(0, end, this.wallheight, this.wallheight + 1, + 16 - value, (16 - value) + 1, this.floor2); // + setCuboidRegion(start, 16, this.wallheight, + this.wallheight + 1, 16 - value, (16 - value) + 1, + this.floor2); // + } + if ((plotMinX + 2) <= 16) { + int value = (plotMinX + 2); + int start, end; + if ((plotMinZ + 2) <= 16) { + start = 16 - plotMinZ - 1; + } else { + start = 16; + } + if ((roadStartZ - 1) <= 16) { + end = (16 - roadStartZ) + 1; + } else { + end = 0; + } + if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) { + start = 0; + } + setCuboidRegion(16 - value, (16 - value) + 1, this.wallheight, + this.wallheight + 1, 0, end, this.floor2); // + setCuboidRegion(16 - value, (16 - value) + 1, this.wallheight, + this.wallheight + 1, start, 16, this.floor2); // + } + if ((roadStartZ <= 16) && (roadStartZ > 1)) { + int val = roadStartZ; + int start, end; + if ((plotMinX + 2) <= 16) { + start = 16 - plotMinX - 1; + } else { + start = 16; + } + if ((roadStartX - 1) <= 16) { + end = (16 - roadStartX) + 1; + } else { + end = 0; + } + if (!(((plotMinX + 2) <= 16) || ((roadStartX - 1) <= 16))) { + start = 0; + } + setCuboidRegion(0, end, this.wallheight, this.wallheight + 1, + (16 - val) + 1, (16 - val) + 2, this.floor2); + setCuboidRegion(start, 16, this.wallheight, + this.wallheight + 1, (16 - val) + 1, (16 - val) + 2, + this.floor2); + } + if ((roadStartX <= 16) && (roadStartX > 1)) { + int val = roadStartX; + int start, end; + if ((plotMinZ + 2) <= 16) { + start = 16 - plotMinZ - 1; + } else { + start = 16; + } + if ((roadStartZ - 1) <= 16) { + end = (16 - roadStartZ) + 1; + } else { + end = 0; + } + if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) { + start = 0; + } + setCuboidRegion((16 - val) + 1, (16 - val) + 2, + this.wallheight, this.wallheight + 1, 0, end, + this.floor2); // + setCuboidRegion((16 - val) + 1, (16 - val) + 2, + this.wallheight, this.wallheight + 1, start, 16, + this.floor2); // + } + } + + // Plot filling (28/28 cuboids) (10x2 + 4x2) + if (this.plotsize > 16) { + if (roadStartX <= 16) { + if (roadStartZ <= 16) { + setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 0, + 16 - roadStartZ, this.filling); + setCuboidRegion(0, 16 - roadStartX, this.plotheight, + this.plotheight + 1, 0, 16 - roadStartZ, + this.plotfloors); + } + if (plotMinZ <= 16) { + setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, + 16 - plotMinZ, 16, this.filling); + setCuboidRegion(0, 16 - roadStartX, this.plotheight, + this.plotheight + 1, 16 - plotMinZ, 16, + this.plotfloors); + } + } else { + if (roadStartZ <= 16) { + if (plotMinX > 16) { + setCuboidRegion(0, 16, 1, this.plotheight, 0, + 16 - roadStartZ, this.filling); + setCuboidRegion(0, 16, this.plotheight, + this.plotheight + 1, 0, 16 - roadStartZ, + this.plotfloors); + } + } + } + if (plotMinX <= 16) { + if (plotMinZ <= 16) { + setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, + 16 - plotMinZ, 16, this.filling); + setCuboidRegion(16 - plotMinX, 16, this.plotheight, + this.plotheight + 1, 16 - plotMinZ, 16, + this.plotfloors); + } else { + int z = 16 - roadStartZ; + if (z < 0) { + z = 16; + } + setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, + z, this.filling); + setCuboidRegion(16 - plotMinX, 16, this.plotheight, + this.plotheight + 1, 0, z, this.plotfloors); + } + if (roadStartZ <= 16) { + setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, + 16 - roadStartZ, this.filling); + setCuboidRegion(16 - plotMinX, 16, this.plotheight, + this.plotheight + 1, 0, 16 - roadStartZ, + this.plotfloors); + } else { + if (roadStartX <= 16) { + if (plotMinZ > 16) { + int x = 16 - roadStartX; + if (x < 0) { + x = 16; + } + setCuboidRegion(0, x, 1, this.plotheight, 0, 16, + this.filling); + setCuboidRegion(0, x, this.plotheight, + this.plotheight + 1, 0, 16, this.plotfloors); + } + } + } + } else { + if (plotMinZ <= 16) { + if (roadStartX > 16) { + int x = 16 - roadStartX; + if (x < 0) { + x = 16; + } + setCuboidRegion(0, x, 1, this.plotheight, + 16 - plotMinZ, 16, this.filling); + setCuboidRegion(0, x, this.plotheight, + this.plotheight + 1, 16 - plotMinZ, 16, + this.plotfloors); + } + } else { + if (roadStartZ > 16) { + int x = 16 - roadStartX; + if (x < 0) { + x = 16; + } + int z = 16 - roadStartZ; + if (z < 0) { + z = 16; + } + if (roadStartX > 16) { + setCuboidRegion(0, x, 1, this.plotheight, 0, z, + this.filling); + setCuboidRegion(0, x, this.plotheight, + this.plotheight + 1, 0, z, this.plotfloors); + } else { + setCuboidRegion(0, x, 1, this.plotheight, 0, z, + this.filling); + setCuboidRegion(0, x, this.plotheight, + this.plotheight + 1, 0, z, this.plotfloors); + } + } + } + } + } else { + if (roadStartX <= 16) { + if (roadStartZ <= 16) { + setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 0, + 16 - roadStartZ, this.filling); + setCuboidRegion(0, 16 - roadStartX, this.plotheight, + this.plotheight + 1, 0, 16 - roadStartZ, + this.plotfloors); + } + if (plotMinZ <= 16) { + setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, + 16 - plotMinZ, 16, this.filling); + setCuboidRegion(0, 16 - roadStartX, this.plotheight, + this.plotheight + 1, 16 - plotMinZ, 16, + this.plotfloors); + } + } + if (plotMinX <= 16) { + if (plotMinZ <= 16) { + setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, + 16 - plotMinZ, 16, this.filling); + setCuboidRegion(16 - plotMinX, 16, this.plotheight, + this.plotheight + 1, 16 - plotMinZ, 16, + this.plotfloors); + } + if (roadStartZ <= 16) { + setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, + 16 - roadStartZ, this.filling); + setCuboidRegion(16 - plotMinX, 16, this.plotheight, + this.plotheight + 1, 0, 16 - roadStartZ, + this.plotfloors); + } + } + } + + // WALLS (16/16 cuboids) + if (this.pathsize > 0) { + if ((plotMinZ + 1) <= 16) { + int start, end; + if ((plotMinX + 2) <= 16) { + start = 16 - plotMinX - 1; + } else { + start = 16; + } + if ((roadStartX - 1) <= 16) { + end = (16 - roadStartX) + 1; + } else { + end = 0; + } + if (!(((plotMinX + 2) <= 16) || ((roadStartX - 1) <= 16))) { + start = 0; + } + setCuboidRegion(0, end, 1, this.wallheight + 1, + 16 - plotMinZ - 1, 16 - plotMinZ, this.wallfilling); + setCuboidRegion(0, end, this.wallheight + 1, + this.wallheight + 2, 16 - plotMinZ - 1, 16 - plotMinZ, + this.wall); + setCuboidRegion(start, 16, 1, this.wallheight + 1, + 16 - plotMinZ - 1, 16 - plotMinZ, this.wallfilling); + setCuboidRegion(start, 16, this.wallheight + 1, + this.wallheight + 2, 16 - plotMinZ - 1, 16 - plotMinZ, + this.wall); + } + if ((plotMinX + 1) <= 16) { + int start, end; + if ((plotMinZ + 2) <= 16) { + start = 16 - plotMinZ - 1; + } else { + start = 16; + } + if ((roadStartZ - 1) <= 16) { + end = (16 - roadStartZ) + 1; + } else { + end = 0; + } + if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) { + start = 0; + } + setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, 1, + this.wallheight + 1, 0, end, this.wallfilling); + setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, + this.wallheight + 1, this.wallheight + 2, 0, end, + this.wall); + setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, 1, + this.wallheight + 1, start, 16, this.wallfilling); + setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, + this.wallheight + 1, this.wallheight + 2, start, 16, + this.wall); + } + if ((roadStartZ <= 16) && (roadStartZ > 0)) { + int start, end; + if ((plotMinX + 1) <= 16) { + start = 16 - plotMinX; + } else { + start = 16; + } + if ((roadStartX + 1) <= 16) { + end = (16 - roadStartX) + 1; + } else { + end = 0; + } + if (!(((plotMinX + 1) <= 16) || (roadStartX <= 16))) { + start = 0; + } + setCuboidRegion(0, end, 1, this.wallheight + 1, + 16 - roadStartZ, (16 - roadStartZ) + 1, + this.wallfilling); + setCuboidRegion(0, end, this.wallheight + 1, + this.wallheight + 2, 16 - roadStartZ, + (16 - roadStartZ) + 1, this.wall); + setCuboidRegion(start, 16, 1, this.wallheight + 1, + 16 - roadStartZ, (16 - roadStartZ) + 1, + this.wallfilling); + setCuboidRegion(start, 16, this.wallheight + 1, + this.wallheight + 2, 16 - roadStartZ, + (16 - roadStartZ) + 1, this.wall); + } + if ((roadStartX <= 16) && (roadStartX > 0)) { + int start, end; + if ((plotMinZ + 1) <= 16) { + start = 16 - plotMinZ; + } else { + start = 16; + } + if ((roadStartZ + 1) <= 16) { + end = (16 - roadStartZ) + 1; + } else { + end = 0; + } + if (!(((plotMinZ + 1) <= 16) || ((roadStartZ + 1) <= 16))) { + start = 0; + } + setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, 1, + this.wallheight + 1, 0, end, this.wallfilling); + setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, + this.wallheight + 1, this.roadheight + 2, 0, end, + this.wall); + setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, 1, + this.wallheight + 1, start, 16, this.wallfilling); + setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, + this.wallheight + 1, this.wallheight + 2, start, 16, + this.wall); + } + } + // Return the chunk + return this.result; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/generator/XPopulator.java b/PlotSquared/src/com/intellectualcrafters/plot/generator/XPopulator.java index 73989f74f..e27cf1958 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/generator/XPopulator.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/generator/XPopulator.java @@ -11,442 +11,535 @@ import com.intellectualcrafters.plot.PlotBlock; import com.intellectualcrafters.plot.PlotWorld; /** - * + * * @author Citymonstret - * + * */ public class XPopulator extends BlockPopulator { - - /* - * Sorry, this isn't well documented at the moment. - * - * We advise you to take a look at a world generation tutorial for information about how a BlockPopulator works. - * - */ - - private int X; - private int Z; - private long state; - public final long nextLong() { - long a = this.state; - this.state = xorShift64(a); - return a; - } + /* + * Sorry, this isn't well documented at the moment. + * + * We advise you to take a look at a world generation tutorial for + * information about how a BlockPopulator works. + */ - public final long xorShift64(long a) { - a ^= (a << 21); - a ^= (a >>> 35); - a ^= (a << 4); - return a; - } + private int X; + private int Z; + private long state; - public final int random(int n) { - long result = ((nextLong() >>> 32) * n) >> 32; - return (int) result; - } + public final long nextLong() { + long a = this.state; + this.state = xorShift64(a); + return a; + } - public void setCuboidRegion(int x1, int x2, int y1, int y2, int z1, int z2, PlotBlock block, World w) { - if (block.data == 0) { - return; - } - for (int x = x1; x < x2; x++) { - for (int z = z1; z < z2; z++) { - for (int y = y1; y < y2; y++) { - setBlock(w, x, y, z, block.id, block.data); - } - } - } - } + public final long xorShift64(long a) { + a ^= (a << 21); + a ^= (a >>> 35); + a ^= (a << 4); + return a; + } - private void setCuboidRegion(int x1, int x2, int y1, int y2, int z1, int z2, PlotBlock[] blocks, World w) { - if (blocks.length == 1) { - setCuboidRegion(x1, x2, y1, y2, z1, z2, blocks[0], w); - } else { - for (int x = x1; x < x2; x++) { - for (int z = z1; z < z2; z++) { - for (int y = y1; y < y2; y++) { - int i = random(blocks.length); - if (blocks[i].data != 0) { - setBlock(w, x, y, z, blocks[i].id, blocks[i].data); - } - } - } - } - } + public final int random(int n) { + long result = ((nextLong() >>> 32) * n) >> 32; + return (int) result; + } - } + public void setCuboidRegion(int x1, int x2, int y1, int y2, int z1, int z2, + PlotBlock block, World w) { + if (block.data == 0) { + return; + } + for (int x = x1; x < x2; x++) { + for (int z = z1; z < z2; z++) { + for (int y = y1; y < y2; y++) { + setBlock(w, x, y, z, block.id, block.data); + } + } + } + } - public short[] getBlock(String block) { - if (block.contains(":")) { - String[] split = block.split(":"); - return new short[] { Short.parseShort(split[0]), Short.parseShort(split[1]) }; - } - return new short[] { Short.parseShort(block), 0 }; - } + private void setCuboidRegion(int x1, int x2, int y1, int y2, int z1, + int z2, PlotBlock[] blocks, World w) { + if (blocks.length == 1) { + setCuboidRegion(x1, x2, y1, y2, z1, z2, blocks[0], w); + } else { + for (int x = x1; x < x2; x++) { + for (int z = z1; z < z2; z++) { + for (int y = y1; y < y2; y++) { + int i = random(blocks.length); + if (blocks[i].data != 0) { + setBlock(w, x, y, z, blocks[i].id, blocks[i].data); + } + } + } + } + } - int plotsize; - int pathsize; - PlotBlock wall; - PlotBlock wallfilling; - PlotBlock floor1; - PlotBlock floor2; - int size; - Biome biome; - int roadheight; - int wallheight; - int plotheight; - PlotBlock[] plotfloors; - PlotBlock[] filling; + } - private double pathWidthLower; - private DefaultPlotWorld plotworld; + public short[] getBlock(String block) { + if (block.contains(":")) { + String[] split = block.split(":"); + return new short[] { Short.parseShort(split[0]), + Short.parseShort(split[1]) }; + } + return new short[] { Short.parseShort(block), 0 }; + } - public XPopulator(PlotWorld pw) { - this.plotworld = (DefaultPlotWorld) pw; + int plotsize; + int pathsize; + PlotBlock wall; + PlotBlock wallfilling; + PlotBlock floor1; + PlotBlock floor2; + int size; + Biome biome; + int roadheight; + int wallheight; + int plotheight; + PlotBlock[] plotfloors; + PlotBlock[] filling; - // save configuration + private double pathWidthLower; + private DefaultPlotWorld plotworld; - plotsize = plotworld.PLOT_WIDTH; - pathsize = plotworld.ROAD_WIDTH; + public XPopulator(PlotWorld pw) { + this.plotworld = (DefaultPlotWorld) pw; - floor1 = plotworld.ROAD_BLOCK; - floor2 = plotworld.ROAD_STRIPES; - - wallfilling = plotworld.WALL_FILLING; - size = pathsize + plotsize; - wall = plotworld.WALL_BLOCK; + // save configuration - plotfloors = plotworld.TOP_BLOCK; - filling = plotworld.MAIN_BLOCK; - - wallheight = plotworld.WALL_HEIGHT; - roadheight = plotworld.ROAD_HEIGHT; - plotheight = plotworld.PLOT_HEIGHT; + this.plotsize = this.plotworld.PLOT_WIDTH; + this.pathsize = this.plotworld.ROAD_WIDTH; - if ((this.pathsize % 2) == 0) { - this.pathWidthLower = Math.floor(this.pathsize / 2) - 1; - } else { - this.pathWidthLower = Math.floor(this.pathsize / 2); - } - } + this.floor1 = this.plotworld.ROAD_BLOCK; + this.floor2 = this.plotworld.ROAD_STRIPES; - @Override - public void populate(World w, Random r, Chunk c) { - int cx = c.getX(), cz = c.getZ(); + this.wallfilling = this.plotworld.WALL_FILLING; + this.size = this.pathsize + this.plotsize; + this.wall = this.plotworld.WALL_BLOCK; - final int prime = 31; - int h = 1; - h = (prime * h) + cx; - h = (prime * h) + cz; - this.state = h; + this.plotfloors = this.plotworld.TOP_BLOCK; + this.filling = this.plotworld.MAIN_BLOCK; - this.X = cx << 4; - this.Z = cz << 4; - cx = (cx % this.size) + (8 * this.size); - cz = (cz % this.size) + (8 * this.size); - double absX = ((((cx * 16) + 16) - this.pathWidthLower - 1) + (8 * this.size)), absZ = ((((cz * 16) + 16) - this.pathWidthLower - 1) + (8 * this.size)); - int plotMinX = (int) (((absX) % this.size)); - int plotMinZ = (int) (((absZ) % this.size)); - int roadStartX = (plotMinX + this.pathsize); - int roadStartZ = (plotMinZ + this.pathsize); - if (roadStartX >= this.size) { - roadStartX -= this.size; - } - if (roadStartZ >= this.size) { - roadStartZ -= this.size; - } + this.wallheight = this.plotworld.WALL_HEIGHT; + this.roadheight = this.plotworld.ROAD_HEIGHT; + this.plotheight = this.plotworld.PLOT_HEIGHT; - // ROADS + if ((this.pathsize % 2) == 0) { + this.pathWidthLower = Math.floor(this.pathsize / 2) - 1; + } else { + this.pathWidthLower = Math.floor(this.pathsize / 2); + } + } - if ((this.pathsize > 16) && ((plotMinX > roadStartX) || (plotMinZ > roadStartZ)) && !((roadStartX < 16) && (roadStartZ < 16)) && (((roadStartX > 16) && (roadStartZ > 16)) || ((plotMinX > roadStartX) && (plotMinZ > roadStartZ)))) { - setCuboidRegion(0, 16, 1, this.roadheight + 1, 0, 16, this.floor1, w); - return; - } + @Override + public void populate(World w, Random r, Chunk c) { + int cx = c.getX(), cz = c.getZ(); - if (((plotMinZ + 1) <= 16) || ((roadStartZ <= 16) && (roadStartZ > 0))) { - int start = Math.max((16 - plotMinZ - this.pathsize) + 1, (16 - roadStartZ) + 1); - int end = Math.min(16 - plotMinZ - 1, (16 - roadStartZ) + this.pathsize); - if ((start >= 0) && (start <= 16) && (end < 0)) { - end = 16; - } - setCuboidRegion(0, 16, 1, this.roadheight + 1, Math.max(start, 0), Math.min(16, end), this.floor1, w); - } - if (((plotMinX + 1) <= 16) || ((roadStartX <= 16) && (roadStartX > 0))) { - int start = Math.max((16 - plotMinX - this.pathsize) + 1, (16 - roadStartX) + 1); - int end = Math.min(16 - plotMinX - 1, (16 - roadStartX) + this.pathsize); - if ((start >= 0) && (start <= 16) && (end < 0)) { - end = 16; - } - setCuboidRegion(Math.max(start, 0), Math.min(16, end), 1, this.roadheight + 1, 0, 16, this.floor1, w); - } + final int prime = 31; + int h = 1; + h = (prime * h) + cx; + h = (prime * h) + cz; + this.state = h; - // STRIPES - if ((this.pathsize > 4) && this.plotworld.ROAD_STRIPES_ENABLED) { - if ((plotMinZ + 2) <= 16) { - int value = (plotMinZ + 2); - int start, end; - if ((plotMinX + 2) <= 16) { - start = 16 - plotMinX - 1; - } else { - start = 16; - } - if ((roadStartX - 1) <= 16) { - end = (16 - roadStartX) + 1; - } else { - end = 0; - } - if (!(((plotMinX + 2) <= 16) || ((roadStartX - 1) <= 16))) { - start = 0; - } - setCuboidRegion(0, end, this.roadheight, this.roadheight + 1, 16 - value, (16 - value) + 1, this.floor2, w); // - setCuboidRegion(start, 16, this.roadheight, this.roadheight + 1, 16 - value, (16 - value) + 1, this.floor2, w); // - } - if ((plotMinX + 2) <= 16) { - int value = (plotMinX + 2); - int start, end; - if ((plotMinZ + 2) <= 16) { - start = 16 - plotMinZ - 1; - } else { - start = 16; - } - if ((roadStartZ - 1) <= 16) { - end = (16 - roadStartZ) + 1; - } else { - end = 0; - } - if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) { - start = 0; - } - setCuboidRegion(16 - value, (16 - value) + 1, this.roadheight, this.roadheight + 1, 0, end, this.floor2, w); // - setCuboidRegion(16 - value, (16 - value) + 1, this.roadheight, this.roadheight + 1, start, 16, this.floor2, w); // - } - if ((roadStartZ <= 16) && (roadStartZ > 1)) { - int val = roadStartZ; - int start, end; - if ((plotMinX + 2) <= 16) { - start = 16 - plotMinX - 1; - } else { - start = 16; - } - if ((roadStartX - 1) <= 16) { - end = (16 - roadStartX) + 1; - } else { - end = 0; - } - if (!(((plotMinX + 2) <= 16) || ((roadStartX - 1) <= 16))) { - start = 0; - } - setCuboidRegion(0, end, this.roadheight, this.roadheight + 1, (16 - val) + 1, (16 - val) + 2, this.floor2, w); - setCuboidRegion(start, 16, this.roadheight, this.roadheight + 1, (16 - val) + 1, (16 - val) + 2, this.floor2, w); - } - if ((roadStartX <= 16) && (roadStartX > 1)) { - int val = roadStartX; - int start, end; - if ((plotMinZ + 2) <= 16) { - start = 16 - plotMinZ - 1; - } else { - start = 16; - } - if ((roadStartZ - 1) <= 16) { - end = (16 - roadStartZ) + 1; - } else { - end = 0; - } - if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) { - start = 0; - } - setCuboidRegion((16 - val) + 1, (16 - val) + 2, this.roadheight, this.roadheight + 1, 0, end, this.floor2, w); // - setCuboidRegion((16 - val) + 1, (16 - val) + 2, this.roadheight, this.roadheight + 1, start, 16, this.floor2, w); // - } - } - // WALLS - if (this.pathsize > 0) { - if ((plotMinZ + 1) <= 16) { - int start, end; - if ((plotMinX + 2) <= 16) { - start = 16 - plotMinX - 1; - } else { - start = 16; - } - if ((roadStartX - 1) <= 16) { - end = (16 - roadStartX) + 1; - } else { - end = 0; - } - if (!(((plotMinX + 2) <= 16) || ((roadStartX - 1) <= 16))) { - start = 0; - } - setCuboidRegion(0, end, 1, this.wallheight + 1, 16 - plotMinZ - 1, 16 - plotMinZ, this.wallfilling, w); - setCuboidRegion(0, end, this.wallheight + 1, this.wallheight + 2, 16 - plotMinZ - 1, 16 - plotMinZ, this.wall, w); - setCuboidRegion(start, 16, 1, this.wallheight + 1, 16 - plotMinZ - 1, 16 - plotMinZ, this.wallfilling, w); - setCuboidRegion(start, 16, this.wallheight + 1, this.wallheight + 2, 16 - plotMinZ - 1, 16 - plotMinZ, this.wall, w); - } - if ((plotMinX + 1) <= 16) { - int start, end; - if ((plotMinZ + 2) <= 16) { - start = 16 - plotMinZ - 1; - } else { - start = 16; - } - if ((roadStartZ - 1) <= 16) { - end = (16 - roadStartZ) + 1; - } else { - end = 0; - } - if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) { - start = 0; - } - setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, 1, this.wallheight + 1, 0, end, this.wallfilling, w); - setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, this.wallheight + 1, this.wallheight + 2, 0, end, this.wall, w); - setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, 1, this.wallheight + 1, start, 16, this.wallfilling, w); - setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, this.wallheight + 1, this.wallheight + 2, start, 16, this.wall, w); - } - if ((roadStartZ <= 16) && (roadStartZ > 0)) { - int start, end; - if ((plotMinX + 1) <= 16) { - start = 16 - plotMinX; - } else { - start = 16; - } - if ((roadStartX + 1) <= 16) { - end = (16 - roadStartX) + 1; - } else { - end = 0; - } - if (!(((plotMinX + 1) <= 16) || (roadStartX <= 16))) { - start = 0; - } - setCuboidRegion(0, end, 1, this.wallheight + 1, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wallfilling, w); - setCuboidRegion(0, end, this.wallheight + 1, this.wallheight + 2, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wall, w); - setCuboidRegion(start, 16, 1, this.wallheight + 1, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wallfilling, w); - setCuboidRegion(start, 16, this.wallheight + 1, this.wallheight + 2, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wall, w); - } - if ((roadStartX <= 16) && (roadStartX > 0)) { - int start, end; - if ((plotMinZ + 1) <= 16) { - start = 16 - plotMinZ; - } else { - start = 16; - } - if ((roadStartZ + 1) <= 16) { - end = (16 - roadStartZ) + 1; - } else { - end = 0; - } - if (!(((plotMinZ + 1) <= 16) || ((roadStartZ + 1) <= 16))) { - start = 0; - } - setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, 1, this.wallheight + 1, 0, end, this.wallfilling, w); - setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, this.wallheight + 1, this.roadheight + 2, 0, end, this.wall, w); - setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, 1, this.wallheight + 1, start, 16, this.wallfilling, w); - setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, this.wallheight + 1, this.wallheight + 2, start, 16, this.wall, w); - } - } + this.X = cx << 4; + this.Z = cz << 4; + cx = (cx % this.size) + (8 * this.size); + cz = (cz % this.size) + (8 * this.size); + double absX = ((((cx * 16) + 16) - this.pathWidthLower - 1) + (8 * this.size)), absZ = ((((cz * 16) + 16) + - this.pathWidthLower - 1) + (8 * this.size)); + int plotMinX = (int) (((absX) % this.size)); + int plotMinZ = (int) (((absZ) % this.size)); + int roadStartX = (plotMinX + this.pathsize); + int roadStartZ = (plotMinZ + this.pathsize); + if (roadStartX >= this.size) { + roadStartX -= this.size; + } + if (roadStartZ >= this.size) { + roadStartZ -= this.size; + } - // PLOT + // ROADS - if (this.plotsize > 16) { - if (roadStartX <= 16) { - if (roadStartZ <= 16) { - setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 0, 16 - roadStartZ, this.filling, w); - setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors, w); - } - if (plotMinZ <= 16) { - setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 16 - plotMinZ, 16, this.filling, w); - setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors, w); - } - } else { - if (roadStartZ <= 16) { - if (plotMinX > 16) { - setCuboidRegion(0, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.filling, w); - setCuboidRegion(0, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors, w); - } - } - } - if (plotMinX <= 16) { - if (plotMinZ <= 16) { - setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 16 - plotMinZ, 16, this.filling, w); - setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors, w); - } else { - int z = 16 - roadStartZ; - if (z < 0) { - z = 16; - } - setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, z, this.filling, w); - setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, z, this.plotfloors, w); - } - if (roadStartZ <= 16) { - setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.filling, w); - setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors, w); - } else { - if (roadStartX <= 16) { - if (plotMinZ > 16) { - int x = 16 - roadStartX; - if (x < 0) { - x = 16; - } - setCuboidRegion(0, x, 1, this.plotheight, 0, 16, this.filling, w); - setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, 16, this.plotfloors, w); - } - } - } - } else { - if (plotMinZ <= 16) { - if (roadStartX > 16) { - int x = 16 - roadStartX; - if (x < 0) { - x = 16; - } - setCuboidRegion(0, x, 1, this.plotheight, 16 - plotMinZ, 16, this.filling, w); - setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors, w); - } - } else { - if (roadStartZ > 16) { - int x = 16 - roadStartX; - if (x < 0) { - x = 16; - } - int z = 16 - roadStartZ; - if (z < 0) { - z = 16; - } - if (roadStartX > 16) { - setCuboidRegion(0, x, 1, this.plotheight, 0, z, this.filling, w); - setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, z, this.plotfloors, w); - } else { - setCuboidRegion(0, x, 1, this.plotheight, 0, z, this.filling, w); - setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, z, this.plotfloors, w); - } - } - } - } - } else { - if (roadStartX <= 16) { - if (roadStartZ <= 16) { - setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 0, 16 - roadStartZ, this.filling, w); - setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors, w); - } - if (plotMinZ <= 16) { - setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 16 - plotMinZ, 16, this.filling, w); - setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors, w); - } - } - if (plotMinX <= 16) { - if (plotMinZ <= 16) { - setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 16 - plotMinZ, 16, this.filling, w); - setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors, w); - } - if (roadStartZ <= 16) { - setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.filling, w); - setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors, w); - } - } - } - } + if ((this.pathsize > 16) + && ((plotMinX > roadStartX) || (plotMinZ > roadStartZ)) + && !((roadStartX < 16) && (roadStartZ < 16)) + && (((roadStartX > 16) && (roadStartZ > 16)) || ((plotMinX > roadStartX) && (plotMinZ > roadStartZ)))) { + setCuboidRegion(0, 16, 1, this.roadheight + 1, 0, 16, this.floor1, + w); + return; + } - private void setBlock(World w, int x, int y, int z, short id, byte val) { - w.getBlockAt(this.X + x, y, this.Z + z).setData(val, false); - } + if (((plotMinZ + 1) <= 16) || ((roadStartZ <= 16) && (roadStartZ > 0))) { + int start = Math.max((16 - plotMinZ - this.pathsize) + 1, + (16 - roadStartZ) + 1); + int end = Math.min(16 - plotMinZ - 1, (16 - roadStartZ) + + this.pathsize); + if ((start >= 0) && (start <= 16) && (end < 0)) { + end = 16; + } + setCuboidRegion(0, 16, 1, this.roadheight + 1, Math.max(start, 0), + Math.min(16, end), this.floor1, w); + } + if (((plotMinX + 1) <= 16) || ((roadStartX <= 16) && (roadStartX > 0))) { + int start = Math.max((16 - plotMinX - this.pathsize) + 1, + (16 - roadStartX) + 1); + int end = Math.min(16 - plotMinX - 1, (16 - roadStartX) + + this.pathsize); + if ((start >= 0) && (start <= 16) && (end < 0)) { + end = 16; + } + setCuboidRegion(Math.max(start, 0), Math.min(16, end), 1, + this.roadheight + 1, 0, 16, this.floor1, w); + } + + // STRIPES + if ((this.pathsize > 4) && this.plotworld.ROAD_STRIPES_ENABLED) { + if ((plotMinZ + 2) <= 16) { + int value = (plotMinZ + 2); + int start, end; + if ((plotMinX + 2) <= 16) { + start = 16 - plotMinX - 1; + } else { + start = 16; + } + if ((roadStartX - 1) <= 16) { + end = (16 - roadStartX) + 1; + } else { + end = 0; + } + if (!(((plotMinX + 2) <= 16) || ((roadStartX - 1) <= 16))) { + start = 0; + } + setCuboidRegion(0, end, this.roadheight, this.roadheight + 1, + 16 - value, (16 - value) + 1, this.floor2, w); // + setCuboidRegion(start, 16, this.roadheight, + this.roadheight + 1, 16 - value, (16 - value) + 1, + this.floor2, w); // + } + if ((plotMinX + 2) <= 16) { + int value = (plotMinX + 2); + int start, end; + if ((plotMinZ + 2) <= 16) { + start = 16 - plotMinZ - 1; + } else { + start = 16; + } + if ((roadStartZ - 1) <= 16) { + end = (16 - roadStartZ) + 1; + } else { + end = 0; + } + if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) { + start = 0; + } + setCuboidRegion(16 - value, (16 - value) + 1, this.roadheight, + this.roadheight + 1, 0, end, this.floor2, w); // + setCuboidRegion(16 - value, (16 - value) + 1, this.roadheight, + this.roadheight + 1, start, 16, this.floor2, w); // + } + if ((roadStartZ <= 16) && (roadStartZ > 1)) { + int val = roadStartZ; + int start, end; + if ((plotMinX + 2) <= 16) { + start = 16 - plotMinX - 1; + } else { + start = 16; + } + if ((roadStartX - 1) <= 16) { + end = (16 - roadStartX) + 1; + } else { + end = 0; + } + if (!(((plotMinX + 2) <= 16) || ((roadStartX - 1) <= 16))) { + start = 0; + } + setCuboidRegion(0, end, this.roadheight, this.roadheight + 1, + (16 - val) + 1, (16 - val) + 2, this.floor2, w); + setCuboidRegion(start, 16, this.roadheight, + this.roadheight + 1, (16 - val) + 1, (16 - val) + 2, + this.floor2, w); + } + if ((roadStartX <= 16) && (roadStartX > 1)) { + int val = roadStartX; + int start, end; + if ((plotMinZ + 2) <= 16) { + start = 16 - plotMinZ - 1; + } else { + start = 16; + } + if ((roadStartZ - 1) <= 16) { + end = (16 - roadStartZ) + 1; + } else { + end = 0; + } + if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) { + start = 0; + } + setCuboidRegion((16 - val) + 1, (16 - val) + 2, + this.roadheight, this.roadheight + 1, 0, end, + this.floor2, w); // + setCuboidRegion((16 - val) + 1, (16 - val) + 2, + this.roadheight, this.roadheight + 1, start, 16, + this.floor2, w); // + } + } + // WALLS + if (this.pathsize > 0) { + if ((plotMinZ + 1) <= 16) { + int start, end; + if ((plotMinX + 2) <= 16) { + start = 16 - plotMinX - 1; + } else { + start = 16; + } + if ((roadStartX - 1) <= 16) { + end = (16 - roadStartX) + 1; + } else { + end = 0; + } + if (!(((plotMinX + 2) <= 16) || ((roadStartX - 1) <= 16))) { + start = 0; + } + setCuboidRegion(0, end, 1, this.wallheight + 1, + 16 - plotMinZ - 1, 16 - plotMinZ, this.wallfilling, w); + setCuboidRegion(0, end, this.wallheight + 1, + this.wallheight + 2, 16 - plotMinZ - 1, 16 - plotMinZ, + this.wall, w); + setCuboidRegion(start, 16, 1, this.wallheight + 1, + 16 - plotMinZ - 1, 16 - plotMinZ, this.wallfilling, w); + setCuboidRegion(start, 16, this.wallheight + 1, + this.wallheight + 2, 16 - plotMinZ - 1, 16 - plotMinZ, + this.wall, w); + } + if ((plotMinX + 1) <= 16) { + int start, end; + if ((plotMinZ + 2) <= 16) { + start = 16 - plotMinZ - 1; + } else { + start = 16; + } + if ((roadStartZ - 1) <= 16) { + end = (16 - roadStartZ) + 1; + } else { + end = 0; + } + if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) { + start = 0; + } + setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, 1, + this.wallheight + 1, 0, end, this.wallfilling, w); + setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, + this.wallheight + 1, this.wallheight + 2, 0, end, + this.wall, w); + setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, 1, + this.wallheight + 1, start, 16, this.wallfilling, w); + setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, + this.wallheight + 1, this.wallheight + 2, start, 16, + this.wall, w); + } + if ((roadStartZ <= 16) && (roadStartZ > 0)) { + int start, end; + if ((plotMinX + 1) <= 16) { + start = 16 - plotMinX; + } else { + start = 16; + } + if ((roadStartX + 1) <= 16) { + end = (16 - roadStartX) + 1; + } else { + end = 0; + } + if (!(((plotMinX + 1) <= 16) || (roadStartX <= 16))) { + start = 0; + } + setCuboidRegion(0, end, 1, this.wallheight + 1, + 16 - roadStartZ, (16 - roadStartZ) + 1, + this.wallfilling, w); + setCuboidRegion(0, end, this.wallheight + 1, + this.wallheight + 2, 16 - roadStartZ, + (16 - roadStartZ) + 1, this.wall, w); + setCuboidRegion(start, 16, 1, this.wallheight + 1, + 16 - roadStartZ, (16 - roadStartZ) + 1, + this.wallfilling, w); + setCuboidRegion(start, 16, this.wallheight + 1, + this.wallheight + 2, 16 - roadStartZ, + (16 - roadStartZ) + 1, this.wall, w); + } + if ((roadStartX <= 16) && (roadStartX > 0)) { + int start, end; + if ((plotMinZ + 1) <= 16) { + start = 16 - plotMinZ; + } else { + start = 16; + } + if ((roadStartZ + 1) <= 16) { + end = (16 - roadStartZ) + 1; + } else { + end = 0; + } + if (!(((plotMinZ + 1) <= 16) || ((roadStartZ + 1) <= 16))) { + start = 0; + } + setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, 1, + this.wallheight + 1, 0, end, this.wallfilling, w); + setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, + this.wallheight + 1, this.roadheight + 2, 0, end, + this.wall, w); + setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, 1, + this.wallheight + 1, start, 16, this.wallfilling, w); + setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, + this.wallheight + 1, this.wallheight + 2, start, 16, + this.wall, w); + } + } + + // PLOT + + if (this.plotsize > 16) { + if (roadStartX <= 16) { + if (roadStartZ <= 16) { + setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 0, + 16 - roadStartZ, this.filling, w); + setCuboidRegion(0, 16 - roadStartX, this.plotheight, + this.plotheight + 1, 0, 16 - roadStartZ, + this.plotfloors, w); + } + if (plotMinZ <= 16) { + setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, + 16 - plotMinZ, 16, this.filling, w); + setCuboidRegion(0, 16 - roadStartX, this.plotheight, + this.plotheight + 1, 16 - plotMinZ, 16, + this.plotfloors, w); + } + } else { + if (roadStartZ <= 16) { + if (plotMinX > 16) { + setCuboidRegion(0, 16, 1, this.plotheight, 0, + 16 - roadStartZ, this.filling, w); + setCuboidRegion(0, 16, this.plotheight, + this.plotheight + 1, 0, 16 - roadStartZ, + this.plotfloors, w); + } + } + } + if (plotMinX <= 16) { + if (plotMinZ <= 16) { + setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, + 16 - plotMinZ, 16, this.filling, w); + setCuboidRegion(16 - plotMinX, 16, this.plotheight, + this.plotheight + 1, 16 - plotMinZ, 16, + this.plotfloors, w); + } else { + int z = 16 - roadStartZ; + if (z < 0) { + z = 16; + } + setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, + z, this.filling, w); + setCuboidRegion(16 - plotMinX, 16, this.plotheight, + this.plotheight + 1, 0, z, this.plotfloors, w); + } + if (roadStartZ <= 16) { + setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, + 16 - roadStartZ, this.filling, w); + setCuboidRegion(16 - plotMinX, 16, this.plotheight, + this.plotheight + 1, 0, 16 - roadStartZ, + this.plotfloors, w); + } else { + if (roadStartX <= 16) { + if (plotMinZ > 16) { + int x = 16 - roadStartX; + if (x < 0) { + x = 16; + } + setCuboidRegion(0, x, 1, this.plotheight, 0, 16, + this.filling, w); + setCuboidRegion(0, x, this.plotheight, + this.plotheight + 1, 0, 16, + this.plotfloors, w); + } + } + } + } else { + if (plotMinZ <= 16) { + if (roadStartX > 16) { + int x = 16 - roadStartX; + if (x < 0) { + x = 16; + } + setCuboidRegion(0, x, 1, this.plotheight, + 16 - plotMinZ, 16, this.filling, w); + setCuboidRegion(0, x, this.plotheight, + this.plotheight + 1, 16 - plotMinZ, 16, + this.plotfloors, w); + } + } else { + if (roadStartZ > 16) { + int x = 16 - roadStartX; + if (x < 0) { + x = 16; + } + int z = 16 - roadStartZ; + if (z < 0) { + z = 16; + } + if (roadStartX > 16) { + setCuboidRegion(0, x, 1, this.plotheight, 0, z, + this.filling, w); + setCuboidRegion(0, x, this.plotheight, + this.plotheight + 1, 0, z, this.plotfloors, + w); + } else { + setCuboidRegion(0, x, 1, this.plotheight, 0, z, + this.filling, w); + setCuboidRegion(0, x, this.plotheight, + this.plotheight + 1, 0, z, this.plotfloors, + w); + } + } + } + } + } else { + if (roadStartX <= 16) { + if (roadStartZ <= 16) { + setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 0, + 16 - roadStartZ, this.filling, w); + setCuboidRegion(0, 16 - roadStartX, this.plotheight, + this.plotheight + 1, 0, 16 - roadStartZ, + this.plotfloors, w); + } + if (plotMinZ <= 16) { + setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, + 16 - plotMinZ, 16, this.filling, w); + setCuboidRegion(0, 16 - roadStartX, this.plotheight, + this.plotheight + 1, 16 - plotMinZ, 16, + this.plotfloors, w); + } + } + if (plotMinX <= 16) { + if (plotMinZ <= 16) { + setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, + 16 - plotMinZ, 16, this.filling, w); + setCuboidRegion(16 - plotMinX, 16, this.plotheight, + this.plotheight + 1, 16 - plotMinZ, 16, + this.plotfloors, w); + } + if (roadStartZ <= 16) { + setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, + 16 - roadStartZ, this.filling, w); + setCuboidRegion(16 - plotMinX, 16, this.plotheight, + this.plotheight + 1, 0, 16 - roadStartZ, + this.plotfloors, w); + } + } + } + } + + private void setBlock(World w, int x, int y, int z, short id, byte val) { + w.getBlockAt(this.X + x, y, this.Z + z).setData(val, false); + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/listeners/PlayerEvents.java b/PlotSquared/src/com/intellectualcrafters/plot/listeners/PlayerEvents.java index df527ec9d..adbbc5bf0 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/listeners/PlayerEvents.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/listeners/PlayerEvents.java @@ -42,7 +42,6 @@ import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.block.BlockSpreadEvent; import org.bukkit.event.block.EntityBlockFormEvent; import org.bukkit.event.entity.CreatureSpawnEvent; -import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; import org.bukkit.event.entity.EntityChangeBlockEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityExplodeEvent; @@ -65,7 +64,6 @@ import org.bukkit.event.world.WorldLoadEvent; import com.intellectualcrafters.plot.C; import com.intellectualcrafters.plot.PlayerFunctions; import com.intellectualcrafters.plot.Plot; -import com.intellectualcrafters.plot.PlotHelper; import com.intellectualcrafters.plot.PlotId; import com.intellectualcrafters.plot.PlotMain; import com.intellectualcrafters.plot.PlotWorld; @@ -76,713 +74,749 @@ import com.intellectualcrafters.plot.events.PlayerLeavePlotEvent; /** * Player Events involving plots - * + * * @author Citymonstret */ @SuppressWarnings("unused") public class PlayerEvents implements Listener { - private String getName(UUID uuid) { - String player = Bukkit.getOfflinePlayer(uuid).getName(); - if (player != null) { - return player; - } - return "unknown"; - } + private String getName(UUID uuid) { + String player = Bukkit.getOfflinePlayer(uuid).getName(); + if (player != null) { + return player; + } + return "unknown"; + } - public boolean enteredPlot(Location l1, Location l2) { - PlotId p1 = PlayerFunctions.getPlot(new Location(l1.getWorld(),l1.getBlockX(),64,l1.getBlockZ())); - PlotId p2 = PlayerFunctions.getPlot(new Location(l2.getWorld(),l2.getBlockX(),64,l2.getBlockZ())); - if (p2==null) - return false; - if (p1==null) - return true; - if (p1.equals(p2)) - return false; - return true; - } + public boolean enteredPlot(Location l1, Location l2) { + PlotId p1 = PlayerFunctions.getPlot(new Location(l1.getWorld(), l1 + .getBlockX(), 64, l1.getBlockZ())); + PlotId p2 = PlayerFunctions.getPlot(new Location(l2.getWorld(), l2 + .getBlockX(), 64, l2.getBlockZ())); + if (p2 == null) { + return false; + } + if (p1 == null) { + return true; + } + if (p1.equals(p2)) { + return false; + } + return true; + } - public boolean leftPlot(Location l1, Location l2) { - PlotId p1 = PlayerFunctions.getPlot(new Location(l1.getWorld(),l1.getBlockX(),64,l1.getBlockZ())); - PlotId p2 = PlayerFunctions.getPlot(new Location(l2.getWorld(),l2.getBlockX(),64,l2.getBlockZ())); - if (p1==null) - return false; - if (p2==null) - return true; - if (p1.equals(p2)) - return false; - return true; - } + public boolean leftPlot(Location l1, Location l2) { + PlotId p1 = PlayerFunctions.getPlot(new Location(l1.getWorld(), l1 + .getBlockX(), 64, l1.getBlockZ())); + PlotId p2 = PlayerFunctions.getPlot(new Location(l2.getWorld(), l2 + .getBlockX(), 64, l2.getBlockZ())); + if (p1 == null) { + return false; + } + if (p2 == null) { + return true; + } + if (p1.equals(p2)) { + return false; + } + return true; + } - private boolean isPlotWorld(Location l) { - return PlotMain.isPlotWorld(l.getWorld()); - } + private boolean isPlotWorld(Location l) { + return PlotMain.isPlotWorld(l.getWorld()); + } - private boolean isPlotWorld(World w) { - return PlotMain.isPlotWorld(w); - } + private boolean isPlotWorld(World w) { + return PlotMain.isPlotWorld(w); + } - public static boolean isInPlot(Location loc) { - return getCurrentPlot(loc) != null; - } + public static boolean isInPlot(Location loc) { + return getCurrentPlot(loc) != null; + } - public static Plot getCurrentPlot(Location loc) { - PlotId id = PlayerFunctions.getPlot(loc); - if (id == null) { - return null; - } - World world = loc.getWorld(); - if (PlotMain.getPlots(world).containsKey(id)) { - return PlotMain.getPlots(world).get(id); - } - return new Plot(id, null, Biome.FOREST, new ArrayList(), new ArrayList(), loc.getWorld().getName()); - } + public static Plot getCurrentPlot(Location loc) { + PlotId id = PlayerFunctions.getPlot(loc); + if (id == null) { + return null; + } + World world = loc.getWorld(); + if (PlotMain.getPlots(world).containsKey(id)) { + return PlotMain.getPlots(world).get(id); + } + return new Plot(id, null, Biome.FOREST, new ArrayList(), + new ArrayList(), loc.getWorld().getName()); + } - @EventHandler - public void onWorldLoad(WorldLoadEvent event) { - PlotMain.loadWorld(event.getWorld()); - } + @EventHandler + public void onWorldLoad(WorldLoadEvent event) { + PlotMain.loadWorld(event.getWorld()); + } - @EventHandler - public void onJoin(PlayerJoinEvent event) { - if (!event.getPlayer().hasPlayedBefore()) { - event.getPlayer().saveData(); - } - textures(event.getPlayer()); - } + @EventHandler + public void onJoin(PlayerJoinEvent event) { + if (!event.getPlayer().hasPlayedBefore()) { + event.getPlayer().saveData(); + } + textures(event.getPlayer()); + } - private void textures(Player p) { - if ((Settings.PLOT_SPECIFIC_RESOURCE_PACK.length() > 1) && isPlotWorld(p.getWorld())) { - p.setResourcePack(Settings.PLOT_SPECIFIC_RESOURCE_PACK); - } - } + private void textures(Player p) { + if ((Settings.PLOT_SPECIFIC_RESOURCE_PACK.length() > 1) + && isPlotWorld(p.getWorld())) { + p.setResourcePack(Settings.PLOT_SPECIFIC_RESOURCE_PACK); + } + } - @EventHandler - public void onChangeWorld(PlayerChangedWorldEvent event) { - if (isPlotWorld(event.getFrom()) && (Settings.PLOT_SPECIFIC_RESOURCE_PACK.length() > 1)) { - event.getPlayer().setResourcePack(""); - } else { - textures(event.getPlayer()); - } - } + @EventHandler + public void onChangeWorld(PlayerChangedWorldEvent event) { + if (isPlotWorld(event.getFrom()) + && (Settings.PLOT_SPECIFIC_RESOURCE_PACK.length() > 1)) { + event.getPlayer().setResourcePack(""); + } else { + textures(event.getPlayer()); + } + } - public void plotEntry(Player player, Plot plot) { - if (plot.hasOwner()) { - if (C.TITLE_ENTERED_PLOT.s().length() > 2) { - String sTitleMain = C.TITLE_ENTERED_PLOT.s().replaceFirst("%s", plot.getDisplayName()); - String sTitleSub = C.TITLE_ENTERED_PLOT_SUB.s().replaceFirst("%s", getName(plot.owner)); - ChatColor sTitleMainColor = ChatColor.valueOf(C.TITLE_ENTERED_PLOT_COLOR.s()); - ChatColor sTitleSubColor = ChatColor.valueOf(C.TITLE_ENTERED_PLOT_SUB_COLOR.s()); - Title title = new Title(sTitleMain, sTitleSub, 10, 20, 10); - title.setTitleColor(sTitleMainColor); - title.setSubtitleColor(sTitleSubColor); - title.setTimingsToTicks(); - title.send(player); - } - { - PlayerEnterPlotEvent callEvent = new PlayerEnterPlotEvent(player, plot); - Bukkit.getPluginManager().callEvent(callEvent); - } - PlayerFunctions.sendMessage(player, plot.settings.getJoinMessage()); - if (plot.settings.getRain()) { - PlayerFunctions.togglePlotWeather(player, plot); - } - if (plot.settings.getChangeTime()) { - PlayerFunctions.togglePlotTime(player, plot); - } - } - } - public void plotExit(Player player, Plot plot) { - { - PlayerLeavePlotEvent callEvent = new PlayerLeavePlotEvent(player, plot); - Bukkit.getPluginManager().callEvent(callEvent); - } - player.resetPlayerTime(); - player.resetPlayerWeather(); - PlayerFunctions.sendMessage(player, plot.settings.getLeaveMessage()); - } - - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void PlayerMove(PlayerMoveEvent event) { - try { - Player player = event.getPlayer(); - Location from = event.getFrom(); - Location to = event.getTo(); - if ((from.getBlockX() != to.getBlockX()) || (from.getBlockZ() != to.getBlockZ())) { - if (!isPlotWorld(player.getWorld())) { - return; - } - if (enteredPlot(from,to)) { - Plot plot = getCurrentPlot(event.getTo()); - boolean admin = player.hasPermission("plots.admin"); - if (plot.deny_entry(player) && !admin) { - event.setCancelled(true); - return; - } - plotEntry(player, plot); - } else if (leftPlot(event.getFrom(), event.getTo())) { - Plot plot = getCurrentPlot(event.getFrom()); - plotExit(player, plot); - } - } - } catch (Exception e) { - // Gotta catch 'em all. - } - } + public void plotEntry(Player player, Plot plot) { + if (plot.hasOwner()) { + if (C.TITLE_ENTERED_PLOT.s().length() > 2) { + String sTitleMain = C.TITLE_ENTERED_PLOT.s().replaceFirst("%s", + plot.getDisplayName()); + String sTitleSub = C.TITLE_ENTERED_PLOT_SUB.s().replaceFirst( + "%s", getName(plot.owner)); + ChatColor sTitleMainColor = ChatColor + .valueOf(C.TITLE_ENTERED_PLOT_COLOR.s()); + ChatColor sTitleSubColor = ChatColor + .valueOf(C.TITLE_ENTERED_PLOT_SUB_COLOR.s()); + Title title = new Title(sTitleMain, sTitleSub, 10, 20, 10); + title.setTitleColor(sTitleMainColor); + title.setSubtitleColor(sTitleSubColor); + title.setTimingsToTicks(); + title.send(player); + } + { + PlayerEnterPlotEvent callEvent = new PlayerEnterPlotEvent( + player, plot); + Bukkit.getPluginManager().callEvent(callEvent); + } + PlayerFunctions.sendMessage(player, plot.settings.getJoinMessage()); + if (plot.settings.getRain()) { + PlayerFunctions.togglePlotWeather(player, plot); + } + if (plot.settings.getChangeTime()) { + PlayerFunctions.togglePlotTime(player, plot); + } + } + } - @EventHandler(priority = EventPriority.HIGHEST) - public void onChat(AsyncPlayerChatEvent event) { - World world = event.getPlayer().getWorld(); - if (!isPlotWorld(world)) { - return; - } - PlotWorld plotworld = PlotMain.getWorldSettings(world); - if (!plotworld.PLOT_CHAT) { - return; - } - if (getCurrentPlot(event.getPlayer().getLocation()) == null) { - return; - } - String message = event.getMessage(); - String format = C.PLOT_CHAT_FORMAT.s(); - String sender = event.getPlayer().getDisplayName(); - Plot plot = getCurrentPlot(event.getPlayer().getLocation()); - PlotId id = plot.id; - Set recipients = event.getRecipients(); - recipients.clear(); - for (Player p : Bukkit.getOnlinePlayers()) { - if (getCurrentPlot(p.getLocation()) == plot) { - recipients.add(p); - } - } - format = format.replaceAll("%plot_id%", id.x + ";" + id.y).replaceAll("%sender%", sender).replaceAll("%msg%", message); - format = ChatColor.translateAlternateColorCodes('&', format); - event.setFormat(format); - } + public void plotExit(Player player, Plot plot) { + { + PlayerLeavePlotEvent callEvent = new PlayerLeavePlotEvent(player, + plot); + Bukkit.getPluginManager().callEvent(callEvent); + } + player.resetPlayerTime(); + player.resetPlayerWeather(); + PlayerFunctions.sendMessage(player, plot.settings.getLeaveMessage()); + } - @EventHandler(priority = EventPriority.HIGH) - public void BlockDestroy(BlockBreakEvent event) { - World world = event.getPlayer().getWorld(); - if (!isPlotWorld(world)) { - return; - } - if (event.getPlayer().hasPermission("plots.admin")) { - return; - } - if (isInPlot(event.getBlock().getLocation())) { - Plot plot = getCurrentPlot(event.getBlock().getLocation()); - if (!plot.hasRights(event.getPlayer())) { - event.setCancelled(true); - } - } - if (PlayerFunctions.getPlot(event.getBlock().getLocation()) == null) { - event.setCancelled(true); - } - } + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void PlayerMove(PlayerMoveEvent event) { + try { + Player player = event.getPlayer(); + Location from = event.getFrom(); + Location to = event.getTo(); + if ((from.getBlockX() != to.getBlockX()) + || (from.getBlockZ() != to.getBlockZ())) { + if (!isPlotWorld(player.getWorld())) { + return; + } + if (enteredPlot(from, to)) { + Plot plot = getCurrentPlot(event.getTo()); + boolean admin = player.hasPermission("plots.admin"); + if (plot.deny_entry(player) && !admin) { + event.setCancelled(true); + return; + } + plotEntry(player, plot); + } else if (leftPlot(event.getFrom(), event.getTo())) { + Plot plot = getCurrentPlot(event.getFrom()); + plotExit(player, plot); + } + } + } catch (Exception e) { + // Gotta catch 'em all. + } + } - @EventHandler(priority = EventPriority.HIGH) - public void BlockCreate(BlockPlaceEvent event) { - World world = event.getPlayer().getWorld(); - if (!isPlotWorld(world)) { - return; - } - if (event.getPlayer().hasPermission("plots.admin")) { - return; - } - if (isInPlot(event.getBlock().getLocation())) { - Plot plot = getCurrentPlot(event.getBlockPlaced().getLocation()); - if (!plot.hasRights(event.getPlayer())) { - event.setCancelled(true); - } - } - if (PlayerFunctions.getPlot(event.getBlockPlaced().getLocation()) == null) { - event.setCancelled(true); - } - } + @EventHandler(priority = EventPriority.HIGHEST) + public void onChat(AsyncPlayerChatEvent event) { + World world = event.getPlayer().getWorld(); + if (!isPlotWorld(world)) { + return; + } + PlotWorld plotworld = PlotMain.getWorldSettings(world); + if (!plotworld.PLOT_CHAT) { + return; + } + if (getCurrentPlot(event.getPlayer().getLocation()) == null) { + return; + } + String message = event.getMessage(); + String format = C.PLOT_CHAT_FORMAT.s(); + String sender = event.getPlayer().getDisplayName(); + Plot plot = getCurrentPlot(event.getPlayer().getLocation()); + PlotId id = plot.id; + Set recipients = event.getRecipients(); + recipients.clear(); + for (Player p : Bukkit.getOnlinePlayers()) { + if (getCurrentPlot(p.getLocation()) == plot) { + recipients.add(p); + } + } + format = format.replaceAll("%plot_id%", id.x + ";" + id.y) + .replaceAll("%sender%", sender).replaceAll("%msg%", message); + format = ChatColor.translateAlternateColorCodes('&', format); + event.setFormat(format); + } - @EventHandler - public void onBigBoom(EntityExplodeEvent event) { - World world = event.getLocation().getWorld(); - if (!isPlotWorld(world)) { - return; - } - event.setCancelled(true); - } + @EventHandler(priority = EventPriority.HIGH) + public void BlockDestroy(BlockBreakEvent event) { + World world = event.getPlayer().getWorld(); + if (!isPlotWorld(world)) { + return; + } + if (event.getPlayer().hasPermission("plots.admin")) { + return; + } + if (isInPlot(event.getBlock().getLocation())) { + Plot plot = getCurrentPlot(event.getBlock().getLocation()); + if (!plot.hasRights(event.getPlayer())) { + event.setCancelled(true); + } + } + if (PlayerFunctions.getPlot(event.getBlock().getLocation()) == null) { + event.setCancelled(true); + } + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPeskyMobsChangeTheWorldLikeWTFEvent( // LOL! - EntityChangeBlockEvent event) { - World world = event.getBlock().getWorld(); - if (!isPlotWorld(world)) { - return; - } - Entity e = event.getEntity(); - if (!(e instanceof Player)) { - if (!(e instanceof org.bukkit.entity.FallingBlock)) { - event.setCancelled(true); - } - } else { - Block b = event.getBlock(); - Player p = (Player) e; - if (!isInPlot(b.getLocation())) { - if (!p.hasPermission("plots.admin")) { - event.setCancelled(true); - } - } else { - Plot plot = getCurrentPlot(b.getLocation()); - if (plot == null) { - if (!p.hasPermission("plots.admin")) { - event.setCancelled(true); - } - } else if (!plot.hasRights(p)) { - if (!p.hasPermission("plots.admin")) { - event.setCancelled(true); - } - } - } - } - } + @EventHandler(priority = EventPriority.HIGH) + public void BlockCreate(BlockPlaceEvent event) { + World world = event.getPlayer().getWorld(); + if (!isPlotWorld(world)) { + return; + } + if (event.getPlayer().hasPermission("plots.admin")) { + return; + } + if (isInPlot(event.getBlock().getLocation())) { + Plot plot = getCurrentPlot(event.getBlockPlaced().getLocation()); + if (!plot.hasRights(event.getPlayer())) { + event.setCancelled(true); + } + } + if (PlayerFunctions.getPlot(event.getBlockPlaced().getLocation()) == null) { + event.setCancelled(true); + } + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntityBlockForm(final EntityBlockFormEvent event) { - World world = event.getBlock().getWorld(); - if (!isPlotWorld(world)) { - return; - } - if ((!(event.getEntity() instanceof Player))) { - event.setCancelled(true); - } - } + @EventHandler + public void onBigBoom(EntityExplodeEvent event) { + World world = event.getLocation().getWorld(); + if (!isPlotWorld(world)) { + return; + } + event.setCancelled(true); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBS(final BlockSpreadEvent e) { - Block b = e.getBlock(); - if (isPlotWorld(b.getLocation())) { - if (!isInPlot(b.getLocation())) { - e.setCancelled(true); - } - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPeskyMobsChangeTheWorldLikeWTFEvent( // LOL! + EntityChangeBlockEvent event) { + World world = event.getBlock().getWorld(); + if (!isPlotWorld(world)) { + return; + } + Entity e = event.getEntity(); + if (!(e instanceof Player)) { + if (!(e instanceof org.bukkit.entity.FallingBlock)) { + event.setCancelled(true); + } + } else { + Block b = event.getBlock(); + Player p = (Player) e; + if (!isInPlot(b.getLocation())) { + if (!p.hasPermission("plots.admin")) { + event.setCancelled(true); + } + } else { + Plot plot = getCurrentPlot(b.getLocation()); + if (plot == null) { + if (!p.hasPermission("plots.admin")) { + event.setCancelled(true); + } + } else if (!plot.hasRights(p)) { + if (!p.hasPermission("plots.admin")) { + event.setCancelled(true); + } + } + } + } + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBF(final BlockFormEvent e) { - Block b = e.getBlock(); - if (isPlotWorld(b.getLocation())) { - if (!isInPlot(b.getLocation())) { - e.setCancelled(true); - } - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onEntityBlockForm(final EntityBlockFormEvent event) { + World world = event.getBlock().getWorld(); + if (!isPlotWorld(world)) { + return; + } + if ((!(event.getEntity() instanceof Player))) { + event.setCancelled(true); + } + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBD(final BlockDamageEvent e) { - Block b = e.getBlock(); - if (isPlotWorld(b.getLocation())) { - if (!isInPlot(b.getLocation())) { - e.setCancelled(true); - } - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBS(final BlockSpreadEvent e) { + Block b = e.getBlock(); + if (isPlotWorld(b.getLocation())) { + if (!isInPlot(b.getLocation())) { + e.setCancelled(true); + } + } + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onFade(final BlockFadeEvent e) { - Block b = e.getBlock(); - if (isPlotWorld(b.getLocation())) { - if (!isInPlot(b.getLocation())) { - e.setCancelled(true); - } - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBF(final BlockFormEvent e) { + Block b = e.getBlock(); + if (isPlotWorld(b.getLocation())) { + if (!isInPlot(b.getLocation())) { + e.setCancelled(true); + } + } + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onChange(final BlockFromToEvent e) { - Block b = e.getToBlock(); - if (isPlotWorld(b.getLocation())) { - if (!isInPlot(b.getLocation())) { - e.setCancelled(true); - } - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBD(final BlockDamageEvent e) { + Block b = e.getBlock(); + if (isPlotWorld(b.getLocation())) { + if (!isInPlot(b.getLocation())) { + e.setCancelled(true); + } + } + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onGrow(final BlockGrowEvent e) { - Block b = e.getBlock(); - if (isPlotWorld(b.getLocation())) { - if (!isInPlot(b.getLocation())) { - e.setCancelled(true); - } - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onFade(final BlockFadeEvent e) { + Block b = e.getBlock(); + if (isPlotWorld(b.getLocation())) { + if (!isInPlot(b.getLocation())) { + e.setCancelled(true); + } + } + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBlockPistonExtend(final BlockPistonExtendEvent e) { - if (isInPlot(e.getBlock().getLocation())) { + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onChange(final BlockFromToEvent e) { + Block b = e.getToBlock(); + if (isPlotWorld(b.getLocation())) { + if (!isInPlot(b.getLocation())) { + e.setCancelled(true); + } + } + } - e.getDirection(); - int modifier = e.getBlocks().size(); - Location l = e.getBlock().getLocation(); - { - if (e.getDirection() == BlockFace.EAST) { - l = e.getBlock().getLocation().subtract(modifier, 0, 0); - } else if (e.getDirection() == BlockFace.NORTH) { - l = e.getBlock().getLocation().subtract(0, 0, modifier); - } else if (e.getDirection() == BlockFace.SOUTH) { - l = e.getBlock().getLocation().add(0, 0, modifier); - } else if (e.getDirection() == BlockFace.WEST) { - l = e.getBlock().getLocation().add(modifier, 0, 0); - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onGrow(final BlockGrowEvent e) { + Block b = e.getBlock(); + if (isPlotWorld(b.getLocation())) { + if (!isInPlot(b.getLocation())) { + e.setCancelled(true); + } + } + } - if (!isInPlot(l)) { - e.setCancelled(true); - return; - } - } - for (Block b : e.getBlocks()) { - if (!isInPlot(b.getLocation())) { - return; - } - { - if (e.getDirection() == BlockFace.EAST) { - if (!isInPlot(b.getLocation().subtract(1, 0, 0))) { - e.setCancelled(true); - } - } else if (e.getDirection() == BlockFace.NORTH) { - if (!isInPlot(b.getLocation().subtract(0, 0, 1))) { - e.setCancelled(true); - } - } else if (e.getDirection() == BlockFace.SOUTH) { - if (!isInPlot(b.getLocation().add(0, 0, 1))) { - e.setCancelled(true); - } - } else if (e.getDirection() == BlockFace.WEST) { - if (!isInPlot(b.getLocation().add(1, 0, 0))) { - e.setCancelled(true); - } - } - } - } - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBlockPistonExtend(final BlockPistonExtendEvent e) { + if (isInPlot(e.getBlock().getLocation())) { - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBlockPistonRetract(final BlockPistonRetractEvent e) { - Block b = e.getRetractLocation().getBlock(); - if (isPlotWorld(b.getLocation()) && (e.getBlock().getType() == Material.PISTON_STICKY_BASE)) { - if (!isInPlot(b.getLocation())) { - e.setCancelled(true); - } - } - } + e.getDirection(); + int modifier = e.getBlocks().size(); + Location l = e.getBlock().getLocation(); + { + if (e.getDirection() == BlockFace.EAST) { + l = e.getBlock().getLocation().subtract(modifier, 0, 0); + } else if (e.getDirection() == BlockFace.NORTH) { + l = e.getBlock().getLocation().subtract(0, 0, modifier); + } else if (e.getDirection() == BlockFace.SOUTH) { + l = e.getBlock().getLocation().add(0, 0, modifier); + } else if (e.getDirection() == BlockFace.WEST) { + l = e.getBlock().getLocation().add(modifier, 0, 0); + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onStructureGrow(final StructureGrowEvent e) { - List blocks = e.getBlocks(); - boolean remove = false; - for (int i = blocks.size() -1; i >= 0; i--) { - if (remove || isPlotWorld(blocks.get(i).getLocation())) { - remove = true; - if (!isInPlot(blocks.get(i).getLocation())) { - e.getBlocks().remove(i); - } - } - } - } + if (!isInPlot(l)) { + e.setCancelled(true); + return; + } + } + for (Block b : e.getBlocks()) { + if (!isInPlot(b.getLocation())) { + return; + } + { + if (e.getDirection() == BlockFace.EAST) { + if (!isInPlot(b.getLocation().subtract(1, 0, 0))) { + e.setCancelled(true); + } + } else if (e.getDirection() == BlockFace.NORTH) { + if (!isInPlot(b.getLocation().subtract(0, 0, 1))) { + e.setCancelled(true); + } + } else if (e.getDirection() == BlockFace.SOUTH) { + if (!isInPlot(b.getLocation().add(0, 0, 1))) { + e.setCancelled(true); + } + } else if (e.getDirection() == BlockFace.WEST) { + if (!isInPlot(b.getLocation().add(1, 0, 0))) { + e.setCancelled(true); + } + } + } + } + } + } - @EventHandler - public void onInteract(PlayerInteractEvent event) { - if (event.getClickedBlock() == null) { - return; - } - World world = event.getPlayer().getWorld(); - if (!isPlotWorld(world)) { - return; - } - if (event.getPlayer().hasPermission("plots.admin")) { - return; - } - if (isInPlot(event.getClickedBlock().getLocation())) { - Plot plot = getCurrentPlot(event.getClickedBlock().getLocation()); - if (new ArrayList<>(Arrays.asList(new Material[] { Material.STONE_BUTTON, Material.WOOD_BUTTON, Material.LEVER, Material.STONE_PLATE, Material.WOOD_PLATE, Material.CHEST, Material.TRAPPED_CHEST, Material.TRAP_DOOR, Material.WOOD_DOOR, Material.WOODEN_DOOR, Material.DISPENSER, Material.DROPPER + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBlockPistonRetract(final BlockPistonRetractEvent e) { + Block b = e.getRetractLocation().getBlock(); + if (isPlotWorld(b.getLocation()) + && (e.getBlock().getType() == Material.PISTON_STICKY_BASE)) { + if (!isInPlot(b.getLocation())) { + e.setCancelled(true); + } + } + } - })).contains(event.getClickedBlock().getType())) { - return; - } - if (!plot.hasRights(event.getPlayer())) { - event.setCancelled(true); - } - } - if (PlayerFunctions.getPlot(event.getClickedBlock().getLocation()) == null) { - event.setCancelled(true); - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onStructureGrow(final StructureGrowEvent e) { + List blocks = e.getBlocks(); + boolean remove = false; + for (int i = blocks.size() - 1; i >= 0; i--) { + if (remove || isPlotWorld(blocks.get(i).getLocation())) { + remove = true; + if (!isInPlot(blocks.get(i).getLocation())) { + e.getBlocks().remove(i); + } + } + } + } - @EventHandler - public void MobSpawn(CreatureSpawnEvent event) { - World world = event.getLocation().getWorld(); - if (!isPlotWorld(world)) { - return; - } - if (event.getEntity() instanceof Player) { - return; - } - if (!isInPlot(event.getLocation())) { - event.setCancelled(true); - } - } + @EventHandler + public void onInteract(PlayerInteractEvent event) { + if (event.getClickedBlock() == null) { + return; + } + World world = event.getPlayer().getWorld(); + if (!isPlotWorld(world)) { + return; + } + if (event.getPlayer().hasPermission("plots.admin")) { + return; + } + if (isInPlot(event.getClickedBlock().getLocation())) { + Plot plot = getCurrentPlot(event.getClickedBlock().getLocation()); + if (new ArrayList<>(Arrays.asList(new Material[] { + Material.STONE_BUTTON, Material.WOOD_BUTTON, + Material.LEVER, Material.STONE_PLATE, Material.WOOD_PLATE, + Material.CHEST, Material.TRAPPED_CHEST, Material.TRAP_DOOR, + Material.WOOD_DOOR, Material.WOODEN_DOOR, + Material.DISPENSER, Material.DROPPER - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBlockIgnite(final BlockIgniteEvent e) { - if (e.getCause() == BlockIgniteEvent.IgniteCause.LIGHTNING) { - e.setCancelled(true); - return; - } - Block b = e.getBlock(); - if (b != null) { - if (e.getPlayer() != null) { - Player p = e.getPlayer(); - if (!isInPlot(b.getLocation())) { - if (!p.hasPermission("plots.admin")) { - e.setCancelled(true); - } - } else { - Plot plot = getCurrentPlot(b.getLocation()); - if (plot == null) { - if (!p.hasPermission("plots.admin")) { - e.setCancelled(true); - } - } else if (!plot.hasRights(p)) { - if (!p.hasPermission("plots.admin")) { - e.setCancelled(true); - } - } - } - } else { - e.setCancelled(true); - } - } - } + })).contains(event.getClickedBlock().getType())) { + return; + } + if (!plot.hasRights(event.getPlayer())) { + event.setCancelled(true); + } + } + if (PlayerFunctions.getPlot(event.getClickedBlock().getLocation()) == null) { + event.setCancelled(true); + } + } - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onTeleport(PlayerTeleportEvent event) { - - Location f = event.getFrom(); - Location t = event.getTo(); - - if (isPlotWorld(event.getTo())) { - if (isInPlot(event.getTo())) { - Plot plot = getCurrentPlot(event.getTo()); - if (plot.deny_entry(event.getPlayer())) { - PlayerFunctions.sendMessage(event.getPlayer(), C.YOU_BE_DENIED); - event.setCancelled(true); - } - else { - if (enteredPlot(f, t)) { - plotEntry(event.getPlayer(), plot); - } - } - } - else { - if (leftPlot(f, t)) { - Plot plot = getCurrentPlot(event.getTo()); - plotExit(event.getPlayer(), plot); - } - } - if ((event.getTo().getBlockX() >= 29999999) || (event.getTo().getBlockX() <= -29999999) || (event.getTo().getBlockZ() >= 29999999) || (event.getTo().getBlockZ() <= -29999999)) { - event.setCancelled(true); - } - } - } + @EventHandler + public void MobSpawn(CreatureSpawnEvent event) { + World world = event.getLocation().getWorld(); + if (!isPlotWorld(world)) { + return; + } + if (event.getEntity() instanceof Player) { + return; + } + if (!isInPlot(event.getLocation())) { + event.setCancelled(true); + } + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBucketEmpty(PlayerBucketEmptyEvent e) { - if (!e.getPlayer().hasPermission("plots.admin")) { - BlockFace bf = e.getBlockFace(); - Block b = e.getBlockClicked().getLocation().add(bf.getModX(), bf.getModY(), bf.getModZ()).getBlock(); - if (isPlotWorld(b.getLocation())) { - if (!isInPlot(b.getLocation())) { - PlayerFunctions.sendMessage(e.getPlayer(), C.NO_PERMISSION); - e.setCancelled(true); - } else { - Plot plot = getCurrentPlot(b.getLocation()); - if (plot == null) { - PlayerFunctions.sendMessage(e.getPlayer(), C.NO_PERMISSION); - e.setCancelled(true); - } else if (!plot.hasRights(e.getPlayer())) { - PlayerFunctions.sendMessage(e.getPlayer(), C.NO_PERMISSION); - e.setCancelled(true); - } - } - } - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBlockIgnite(final BlockIgniteEvent e) { + if (e.getCause() == BlockIgniteEvent.IgniteCause.LIGHTNING) { + e.setCancelled(true); + return; + } + Block b = e.getBlock(); + if (b != null) { + if (e.getPlayer() != null) { + Player p = e.getPlayer(); + if (!isInPlot(b.getLocation())) { + if (!p.hasPermission("plots.admin")) { + e.setCancelled(true); + } + } else { + Plot plot = getCurrentPlot(b.getLocation()); + if (plot == null) { + if (!p.hasPermission("plots.admin")) { + e.setCancelled(true); + } + } else if (!plot.hasRights(p)) { + if (!p.hasPermission("plots.admin")) { + e.setCancelled(true); + } + } + } + } else { + e.setCancelled(true); + } + } + } - @EventHandler(priority = EventPriority.HIGHEST) - public void onInventoryClick(InventoryClickEvent event) { - if (event.getInventory().getName().equalsIgnoreCase("PlotSquared Commands")) { - event.setCancelled(true); - } - } + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onTeleport(PlayerTeleportEvent event) { - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onBucketFill(PlayerBucketFillEvent e) { - if (!e.getPlayer().hasPermission("plots.admin")) { - Block b = e.getBlockClicked(); - if (isPlotWorld(b.getLocation())) { - if (!isInPlot(b.getLocation())) { - PlayerFunctions.sendMessage(e.getPlayer(), C.NO_PERMISSION); - e.setCancelled(true); - } else { - Plot plot = getCurrentPlot(b.getLocation()); - if (plot == null) { - PlayerFunctions.sendMessage(e.getPlayer(), C.NO_PERMISSION); - e.setCancelled(true); - } else if (!plot.hasRights(e.getPlayer())) { - PlayerFunctions.sendMessage(e.getPlayer(), C.NO_PERMISSION); - e.setCancelled(true); - } - } - } - } - } + Location f = event.getFrom(); + Location t = event.getTo(); - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onHangingPlace(final HangingPlaceEvent e) { - Block b = e.getBlock(); - if (isPlotWorld(b.getLocation())) { - Player p = e.getPlayer(); - if (!isInPlot(b.getLocation())) { - if (!p.hasPermission("plots.admin")) { - PlayerFunctions.sendMessage(p, C.NO_PERMISSION); - e.setCancelled(true); - } - } else { - Plot plot = getCurrentPlot(b.getLocation()); - if (plot == null) { - if (!p.hasPermission("plots.admin")) { - PlayerFunctions.sendMessage(p, C.NO_PERMISSION); - e.setCancelled(true); - } - } else if (!plot.hasRights(p)) { - if (!p.hasPermission("plots.admin")) { - PlayerFunctions.sendMessage(p, C.NO_PERMISSION); - e.setCancelled(true); - } - } - } - } - } + if (isPlotWorld(event.getTo())) { + if (isInPlot(event.getTo())) { + Plot plot = getCurrentPlot(event.getTo()); + if (plot.deny_entry(event.getPlayer())) { + PlayerFunctions.sendMessage(event.getPlayer(), + C.YOU_BE_DENIED); + event.setCancelled(true); + } else { + if (enteredPlot(f, t)) { + plotEntry(event.getPlayer(), plot); + } + } + } else { + if (leftPlot(f, t)) { + Plot plot = getCurrentPlot(event.getTo()); + plotExit(event.getPlayer(), plot); + } + } + if ((event.getTo().getBlockX() >= 29999999) + || (event.getTo().getBlockX() <= -29999999) + || (event.getTo().getBlockZ() >= 29999999) + || (event.getTo().getBlockZ() <= -29999999)) { + event.setCancelled(true); + } + } + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onHangingBreakByEntity(final HangingBreakByEntityEvent e) { - Entity r = e.getRemover(); - if (r instanceof Player) { - Player p = (Player) r; - Location l = e.getEntity().getLocation(); - if (isPlotWorld(l)) { - if (!isInPlot(l)) { - if (!p.hasPermission("plots.admin")) { - PlayerFunctions.sendMessage(p, C.NO_PERMISSION); - e.setCancelled(true); - } - } else { - Plot plot = getCurrentPlot(l); - if (plot == null) { - if (!p.hasPermission("plots.admin")) { - PlayerFunctions.sendMessage(p, C.NO_PERMISSION); - e.setCancelled(true); - } - } else if (!plot.hasRights(p)) { - if (!p.hasPermission("plots.admin")) { - PlayerFunctions.sendMessage(p, C.NO_PERMISSION); - e.setCancelled(true); - } - } - } - } - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBucketEmpty(PlayerBucketEmptyEvent e) { + if (!e.getPlayer().hasPermission("plots.admin")) { + BlockFace bf = e.getBlockFace(); + Block b = e.getBlockClicked().getLocation() + .add(bf.getModX(), bf.getModY(), bf.getModZ()).getBlock(); + if (isPlotWorld(b.getLocation())) { + if (!isInPlot(b.getLocation())) { + PlayerFunctions.sendMessage(e.getPlayer(), C.NO_PERMISSION); + e.setCancelled(true); + } else { + Plot plot = getCurrentPlot(b.getLocation()); + if (plot == null) { + PlayerFunctions.sendMessage(e.getPlayer(), + C.NO_PERMISSION); + e.setCancelled(true); + } else if (!plot.hasRights(e.getPlayer())) { + PlayerFunctions.sendMessage(e.getPlayer(), + C.NO_PERMISSION); + e.setCancelled(true); + } + } + } + } + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerInteractEntity(final PlayerInteractEntityEvent e) { - Location l = e.getRightClicked().getLocation(); - if (isPlotWorld(l)) { - Player p = e.getPlayer(); - if (!isInPlot(l)) { - if (!p.hasPermission("plots.admin")) { - PlayerFunctions.sendMessage(p, C.NO_PERMISSION); - e.setCancelled(true); - } - } else { - Plot plot = getCurrentPlot(l); - if (plot == null) { - if (!p.hasPermission("plots.admin")) { - PlayerFunctions.sendMessage(p, C.NO_PERMISSION); - e.setCancelled(true); - } - } else if (!plot.hasRights(p)) { - if (!p.hasPermission("plots.admin")) { - PlayerFunctions.sendMessage(p, C.NO_PERMISSION); - e.setCancelled(true); - } - } - } - } - } + @EventHandler(priority = EventPriority.HIGHEST) + public void onInventoryClick(InventoryClickEvent event) { + if (event.getInventory().getName() + .equalsIgnoreCase("PlotSquared Commands")) { + event.setCancelled(true); + } + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onEntityDamageByEntityEvent(final EntityDamageByEntityEvent e) { - Location l = e.getEntity().getLocation(); - Entity d = e.getDamager(); - if (isPlotWorld(l)) { - if (d instanceof Player) { - Player p = (Player) d; - if (!isInPlot(l)) { - if (!p.hasPermission("plots.admin")) { - PlayerFunctions.sendMessage(p, C.NO_PERMISSION); - e.setCancelled(true); - } - } else { - Plot plot = getCurrentPlot(l); - if (plot == null) { - if (!p.hasPermission("plots.admin")) { - PlayerFunctions.sendMessage(p, C.NO_PERMISSION); - e.setCancelled(true); - } - } else if (!plot.hasRights(p)) { - if (!p.hasPermission("plots.admin")) { - PlayerFunctions.sendMessage(p, C.NO_PERMISSION); - e.setCancelled(true); - } - } - } - } - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onBucketFill(PlayerBucketFillEvent e) { + if (!e.getPlayer().hasPermission("plots.admin")) { + Block b = e.getBlockClicked(); + if (isPlotWorld(b.getLocation())) { + if (!isInPlot(b.getLocation())) { + PlayerFunctions.sendMessage(e.getPlayer(), C.NO_PERMISSION); + e.setCancelled(true); + } else { + Plot plot = getCurrentPlot(b.getLocation()); + if (plot == null) { + PlayerFunctions.sendMessage(e.getPlayer(), + C.NO_PERMISSION); + e.setCancelled(true); + } else if (!plot.hasRights(e.getPlayer())) { + PlayerFunctions.sendMessage(e.getPlayer(), + C.NO_PERMISSION); + e.setCancelled(true); + } + } + } + } + } - @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) - public void onPlayerEggThrow(final PlayerEggThrowEvent e) { - Location l = e.getEgg().getLocation(); - if (isPlotWorld(l)) { - Player p = e.getPlayer(); - if (!isInPlot(l)) { - if (!p.hasPermission("plots.admin")) { - PlayerFunctions.sendMessage(p, C.NO_PERMISSION); - e.setHatching(false); - } - } else { - Plot plot = getCurrentPlot(l); - if (plot == null) { - if (!p.hasPermission("plots.admin")) { - PlayerFunctions.sendMessage(p, C.NO_PERMISSION); - e.setHatching(false); - } - } else if (!plot.hasRights(p)) { - if (!p.hasPermission("plots.admin")) { - PlayerFunctions.sendMessage(p, C.NO_PERMISSION); - e.setHatching(false); - } - } - } - } - } + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onHangingPlace(final HangingPlaceEvent e) { + Block b = e.getBlock(); + if (isPlotWorld(b.getLocation())) { + Player p = e.getPlayer(); + if (!isInPlot(b.getLocation())) { + if (!p.hasPermission("plots.admin")) { + PlayerFunctions.sendMessage(p, C.NO_PERMISSION); + e.setCancelled(true); + } + } else { + Plot plot = getCurrentPlot(b.getLocation()); + if (plot == null) { + if (!p.hasPermission("plots.admin")) { + PlayerFunctions.sendMessage(p, C.NO_PERMISSION); + e.setCancelled(true); + } + } else if (!plot.hasRights(p)) { + if (!p.hasPermission("plots.admin")) { + PlayerFunctions.sendMessage(p, C.NO_PERMISSION); + e.setCancelled(true); + } + } + } + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onHangingBreakByEntity(final HangingBreakByEntityEvent e) { + Entity r = e.getRemover(); + if (r instanceof Player) { + Player p = (Player) r; + Location l = e.getEntity().getLocation(); + if (isPlotWorld(l)) { + if (!isInPlot(l)) { + if (!p.hasPermission("plots.admin")) { + PlayerFunctions.sendMessage(p, C.NO_PERMISSION); + e.setCancelled(true); + } + } else { + Plot plot = getCurrentPlot(l); + if (plot == null) { + if (!p.hasPermission("plots.admin")) { + PlayerFunctions.sendMessage(p, C.NO_PERMISSION); + e.setCancelled(true); + } + } else if (!plot.hasRights(p)) { + if (!p.hasPermission("plots.admin")) { + PlayerFunctions.sendMessage(p, C.NO_PERMISSION); + e.setCancelled(true); + } + } + } + } + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerInteractEntity(final PlayerInteractEntityEvent e) { + Location l = e.getRightClicked().getLocation(); + if (isPlotWorld(l)) { + Player p = e.getPlayer(); + if (!isInPlot(l)) { + if (!p.hasPermission("plots.admin")) { + PlayerFunctions.sendMessage(p, C.NO_PERMISSION); + e.setCancelled(true); + } + } else { + Plot plot = getCurrentPlot(l); + if (plot == null) { + if (!p.hasPermission("plots.admin")) { + PlayerFunctions.sendMessage(p, C.NO_PERMISSION); + e.setCancelled(true); + } + } else if (!plot.hasRights(p)) { + if (!p.hasPermission("plots.admin")) { + PlayerFunctions.sendMessage(p, C.NO_PERMISSION); + e.setCancelled(true); + } + } + } + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onEntityDamageByEntityEvent(final EntityDamageByEntityEvent e) { + Location l = e.getEntity().getLocation(); + Entity d = e.getDamager(); + if (isPlotWorld(l)) { + if (d instanceof Player) { + Player p = (Player) d; + if (!isInPlot(l)) { + if (!p.hasPermission("plots.admin")) { + PlayerFunctions.sendMessage(p, C.NO_PERMISSION); + e.setCancelled(true); + } + } else { + Plot plot = getCurrentPlot(l); + if (plot == null) { + if (!p.hasPermission("plots.admin")) { + PlayerFunctions.sendMessage(p, C.NO_PERMISSION); + e.setCancelled(true); + } + } else if (!plot.hasRights(p)) { + if (!p.hasPermission("plots.admin")) { + PlayerFunctions.sendMessage(p, C.NO_PERMISSION); + e.setCancelled(true); + } + } + } + } + } + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onPlayerEggThrow(final PlayerEggThrowEvent e) { + Location l = e.getEgg().getLocation(); + if (isPlotWorld(l)) { + Player p = e.getPlayer(); + if (!isInPlot(l)) { + if (!p.hasPermission("plots.admin")) { + PlayerFunctions.sendMessage(p, C.NO_PERMISSION); + e.setHatching(false); + } + } else { + Plot plot = getCurrentPlot(l); + if (plot == null) { + if (!p.hasPermission("plots.admin")) { + PlayerFunctions.sendMessage(p, C.NO_PERMISSION); + e.setHatching(false); + } + } else if (!plot.hasRights(p)) { + if (!p.hasPermission("plots.admin")) { + PlayerFunctions.sendMessage(p, C.NO_PERMISSION); + e.setHatching(false); + } + } + } + } + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/listeners/WorldEditListener.java b/PlotSquared/src/com/intellectualcrafters/plot/listeners/WorldEditListener.java index 9ad868de8..79172d63e 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/listeners/WorldEditListener.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/listeners/WorldEditListener.java @@ -27,135 +27,146 @@ import com.intellectualcrafters.plot.PlotMain; import com.intellectualcrafters.plot.database.DBFunc; /** - * + * * @author Citymonstret - * + * */ public class WorldEditListener implements Listener { - public final Set blockedcmds = new HashSet(Arrays.asList("/gmask", "//gmask", "/worldedit:gmask")); - public final Set restrictedcmds = new HashSet(Arrays.asList("/up", "//up", "/worldedit:up")); + public final Set blockedcmds = new HashSet(Arrays.asList( + "/gmask", "//gmask", "/worldedit:gmask")); + public final Set restrictedcmds = new HashSet( + Arrays.asList("/up", "//up", "/worldedit:up")); - private boolean isPlotWorld(Location l) { - return (PlotMain.isPlotWorld(l.getWorld())); - } + private boolean isPlotWorld(Location l) { + return (PlotMain.isPlotWorld(l.getWorld())); + } - @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) - public void onInteract(PlayerInteractEvent e) { - Block b = e.getClickedBlock(); - if (b == null) { - return; - } - Player p = e.getPlayer(); - Location l = b.getLocation(); - if (!isPlotWorld(l)) { - return; - } - p.getItemInHand(); - if ((p.getItemInHand() == null) || (p.getItemInHand().getType() == Material.AIR)) { - return; - } - Plot plot = PlotHelper.getCurrentPlot(b.getLocation()); - if (plot != null) { - if ((plot != null) && plot.hasOwner() && (plot.helpers != null) && (plot.helpers.contains(DBFunc.everyone) || plot.helpers.contains(p.getUniqueId()))) { - PWE.setMask(p, l); - } - } - } + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + public void onInteract(PlayerInteractEvent e) { + Block b = e.getClickedBlock(); + if (b == null) { + return; + } + Player p = e.getPlayer(); + Location l = b.getLocation(); + if (!isPlotWorld(l)) { + return; + } + p.getItemInHand(); + if ((p.getItemInHand() == null) + || (p.getItemInHand().getType() == Material.AIR)) { + return; + } + Plot plot = PlotHelper.getCurrentPlot(b.getLocation()); + if (plot != null) { + if ((plot != null) + && plot.hasOwner() + && (plot.helpers != null) + && (plot.helpers.contains(DBFunc.everyone) || plot.helpers + .contains(p.getUniqueId()))) { + PWE.setMask(p, l); + } + } + } - @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) - public void onPlayerCommand(PlayerCommandPreprocessEvent e) { - Player p = e.getPlayer(); - if (PlotMain.hasPermission(p, "plots.worldedit.bypass") || !PlotMain.isPlotWorld(p.getWorld())) { - return; - } - String cmd = e.getMessage().toLowerCase(); + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + public void onPlayerCommand(PlayerCommandPreprocessEvent e) { + Player p = e.getPlayer(); + if (PlotMain.hasPermission(p, "plots.worldedit.bypass") + || !PlotMain.isPlotWorld(p.getWorld())) { + return; + } + String cmd = e.getMessage().toLowerCase(); - if (cmd.contains(" ")) { - cmd = cmd.substring(0, cmd.indexOf(" ")); - } - if (this.restrictedcmds.contains(cmd)) { - Plot plot = PlayerFunctions.getCurrentPlot(p); - if ((plot == null) || !(plot.helpers.contains(DBFunc.everyone) || plot.helpers.contains(p.getUniqueId()))) { - e.setCancelled(true); - } - } else if (this.blockedcmds.contains(cmd)) { - e.setCancelled(true); - } - } + if (cmd.contains(" ")) { + cmd = cmd.substring(0, cmd.indexOf(" ")); + } + if (this.restrictedcmds.contains(cmd)) { + Plot plot = PlayerFunctions.getCurrentPlot(p); + if ((plot == null) + || !(plot.helpers.contains(DBFunc.everyone) || plot.helpers + .contains(p.getUniqueId()))) { + e.setCancelled(true); + } + } else if (this.blockedcmds.contains(cmd)) { + e.setCancelled(true); + } + } - @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) - public void onPlayerJoin(final PlayerJoinEvent e) { - Player p = e.getPlayer(); - if (PlotMain.hasPermission(p, "plots.worldedit.bypass")) { - return; - } - Location l = p.getLocation(); - if (isPlotWorld(l)) { - PWE.setMask(p, l); - } else { - PWE.removeMask(p); - } - } + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + public void onPlayerJoin(final PlayerJoinEvent e) { + Player p = e.getPlayer(); + if (PlotMain.hasPermission(p, "plots.worldedit.bypass")) { + return; + } + Location l = p.getLocation(); + if (isPlotWorld(l)) { + PWE.setMask(p, l); + } else { + PWE.removeMask(p); + } + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPlayerMove(final PlayerMoveEvent e) { - Location t = e.getTo(); - if (!isPlotWorld(t)) { - return; - } - Location f = e.getFrom(); - Player p = e.getPlayer(); + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPlayerMove(final PlayerMoveEvent e) { + Location t = e.getTo(); + if (!isPlotWorld(t)) { + return; + } + Location f = e.getFrom(); + Player p = e.getPlayer(); - if ((f.getBlockX() != t.getBlockX()) || (f.getBlockZ() != t.getBlockZ())) { - PlotId idF = PlayerFunctions.getPlot(f); - PlotId idT = PlayerFunctions.getPlot(t); - if (PlotMain.hasPermission(e.getPlayer(), "plots.worldedit.bypass")) { - return; - } - if ((idT != null) && !(idF == idT)) { - PWE.setMask(p, t); - } - } - } + if ((f.getBlockX() != t.getBlockX()) + || (f.getBlockZ() != t.getBlockZ())) { + PlotId idF = PlayerFunctions.getPlot(f); + PlotId idT = PlayerFunctions.getPlot(t); + if (PlotMain.hasPermission(e.getPlayer(), "plots.worldedit.bypass")) { + return; + } + if ((idT != null) && !(idF == idT)) { + PWE.setMask(p, t); + } + } + } - @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) - public void onPortal(PlayerPortalEvent e) { - if (PlotMain.hasPermission(e.getPlayer(), "plots.worldedit.bypass")) { - return; - } - Player p = e.getPlayer(); - Location t = e.getTo(); - Location f = e.getFrom(); - if (t==null) { - PWE.removeMask(p); - return; - } - if (isPlotWorld(t)) { - PWE.setMask(p, t); - return; - } - if (f!=null && isPlotWorld(f)) { - PWE.removeMask(p); - return; - } - } + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + public void onPortal(PlayerPortalEvent e) { + if (PlotMain.hasPermission(e.getPlayer(), "plots.worldedit.bypass")) { + return; + } + Player p = e.getPlayer(); + Location t = e.getTo(); + Location f = e.getFrom(); + if (t == null) { + PWE.removeMask(p); + return; + } + if (isPlotWorld(t)) { + PWE.setMask(p, t); + return; + } + if (f != null && isPlotWorld(f)) { + PWE.removeMask(p); + return; + } + } - @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) - public void onTeleport(final PlayerTeleportEvent e) { - if (PlotMain.hasPermission(e.getPlayer(), "plots.worldedit.bypass")) { - return; - } - Player p = e.getPlayer(); - Location t = e.getTo(); - Location f = e.getFrom(); - if (!isPlotWorld(t)) { - if (isPlotWorld(f)) { - PWE.removeMask(p); - } else { - return; - } - } - PWE.setMask(p, t); - } + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + public void onTeleport(final PlayerTeleportEvent e) { + if (PlotMain.hasPermission(e.getPlayer(), "plots.worldedit.bypass")) { + return; + } + Player p = e.getPlayer(); + Location t = e.getTo(); + Location f = e.getFrom(); + if (!isPlotWorld(t)) { + if (isPlotWorld(f)) { + PWE.removeMask(p); + } else { + return; + } + } + PWE.setMask(p, t); + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/listeners/WorldGuardListener.java b/PlotSquared/src/com/intellectualcrafters/plot/listeners/WorldGuardListener.java index 1fc5ab339..3e5f2b46a 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/listeners/WorldGuardListener.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/listeners/WorldGuardListener.java @@ -31,147 +31,165 @@ import com.sk89q.worldguard.protection.regions.ProtectedRegion; * Created by Citymonstret on 2014-09-24. */ public class WorldGuardListener implements Listener { - public ArrayList str_flags = new ArrayList(); - public ArrayList> flags = new ArrayList>(); + public ArrayList str_flags = new ArrayList(); + public ArrayList> flags = new ArrayList>(); - public WorldGuardListener(PlotMain plugin) { - plugin.getServer().getPluginManager().registerEvents(this, plugin); - for (Flag flag : DefaultFlag.getFlags()) { - this.str_flags.add(flag.getName()); - this.flags.add(flag); - } - } + public WorldGuardListener(PlotMain plugin) { + plugin.getServer().getPluginManager().registerEvents(this, plugin); + for (Flag flag : DefaultFlag.getFlags()) { + this.str_flags.add(flag.getName()); + this.flags.add(flag); + } + } - public void removeFlag(Player requester, World world, Plot plot, String key) { - boolean op = requester.isOp(); - requester.setOp(true); - try { - RegionManager manager = PlotMain.worldGuard.getRegionManager(world); - manager.getRegion(plot.id.x + "-" + plot.id.y); - for (Flag flag : this.flags) { - if (flag.getName().equalsIgnoreCase(key)) { - requester.performCommand("region flag " + (plot.id.x + "-" + plot.id.y) + " " + key); - } - } - } catch (Exception e) { - requester.setOp(op); - } finally { - requester.setOp(op); - } - } + public void removeFlag(Player requester, World world, Plot plot, String key) { + boolean op = requester.isOp(); + requester.setOp(true); + try { + RegionManager manager = PlotMain.worldGuard.getRegionManager(world); + manager.getRegion(plot.id.x + "-" + plot.id.y); + for (Flag flag : this.flags) { + if (flag.getName().equalsIgnoreCase(key)) { + requester.performCommand("region flag " + + (plot.id.x + "-" + plot.id.y) + " " + key); + } + } + } catch (Exception e) { + requester.setOp(op); + } finally { + requester.setOp(op); + } + } - public void addFlag(Player requester, World world, Plot plot, String key, String value) { - boolean op = requester.isOp(); - requester.setOp(true); - try { - RegionManager manager = PlotMain.worldGuard.getRegionManager(world); - manager.getRegion(plot.id.x + "-" + plot.id.y); - for (Flag flag : this.flags) { - if (flag.getName().equalsIgnoreCase(key)) { - requester.performCommand("region flag " + (plot.id.x + "-" + plot.id.y) + " " + key + " " + value); - } - } - } catch (Exception e) { - requester.setOp(op); - } finally { - requester.setOp(op); - } - } + public void addFlag(Player requester, World world, Plot plot, String key, + String value) { + boolean op = requester.isOp(); + requester.setOp(true); + try { + RegionManager manager = PlotMain.worldGuard.getRegionManager(world); + manager.getRegion(plot.id.x + "-" + plot.id.y); + for (Flag flag : this.flags) { + if (flag.getName().equalsIgnoreCase(key)) { + requester.performCommand("region flag " + + (plot.id.x + "-" + plot.id.y) + " " + key + " " + + value); + } + } + } catch (Exception e) { + requester.setOp(op); + } finally { + requester.setOp(op); + } + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMerge(PlotMergeEvent event) { - Plot main = event.getPlot(); - ArrayList plots = event.getPlots(); - World world = event.getWorld(); - RegionManager manager = PlotMain.worldGuard.getRegionManager(world); - for (PlotId plot : plots) { - if (!plot.equals(main)) { - manager.removeRegion(plot.x + "-" + plot.y); - } - } - ProtectedRegion region = manager.getRegion(main.id.x + "-" + main.id.y); - DefaultDomain owner = region.getOwners(); - Map, Object> flags = region.getFlags(); - DefaultDomain members = region.getMembers(); - manager.removeRegion(main.id.x + "-" + main.id.y); + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onMerge(PlotMergeEvent event) { + Plot main = event.getPlot(); + ArrayList plots = event.getPlots(); + World world = event.getWorld(); + RegionManager manager = PlotMain.worldGuard.getRegionManager(world); + for (PlotId plot : plots) { + if (!plot.equals(main)) { + manager.removeRegion(plot.x + "-" + plot.y); + } + } + ProtectedRegion region = manager.getRegion(main.id.x + "-" + main.id.y); + DefaultDomain owner = region.getOwners(); + Map, Object> flags = region.getFlags(); + DefaultDomain members = region.getMembers(); + manager.removeRegion(main.id.x + "-" + main.id.y); - Location location1 = PlotHelper.getPlotBottomLocAbs(world, plots.get(0)); - Location location2 = PlotHelper.getPlotTopLocAbs(world, plots.get(plots.size() - 1)); + Location location1 = PlotHelper + .getPlotBottomLocAbs(world, plots.get(0)); + Location location2 = PlotHelper.getPlotTopLocAbs(world, + plots.get(plots.size() - 1)); - BlockVector vector1 = new BlockVector(location1.getBlockX(), 1, location1.getBlockZ()); - BlockVector vector2 = new BlockVector(location2.getBlockX(), world.getMaxHeight(), location2.getBlockZ()); - ProtectedRegion rg = new ProtectedCuboidRegion(main.id.x + "-" + main.id.y, vector1, vector2); + BlockVector vector1 = new BlockVector(location1.getBlockX(), 1, + location1.getBlockZ()); + BlockVector vector2 = new BlockVector(location2.getBlockX(), + world.getMaxHeight(), location2.getBlockZ()); + ProtectedRegion rg = new ProtectedCuboidRegion(main.id.x + "-" + + main.id.y, vector1, vector2); - rg.setFlags(flags); + rg.setFlags(flags); - rg.setOwners(owner); + rg.setOwners(owner); - rg.setMembers(members); + rg.setMembers(members); - manager.addRegion(rg); - } + manager.addRegion(rg); + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onUnlink(PlotUnlinkEvent event) { - World w = event.getWorld(); - ArrayList plots = event.getPlots(); - Plot main = PlotMain.getPlots(w).get(plots.get(0)); + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onUnlink(PlotUnlinkEvent event) { + World w = event.getWorld(); + ArrayList plots = event.getPlots(); + Plot main = PlotMain.getPlots(w).get(plots.get(0)); - RegionManager manager = PlotMain.worldGuard.getRegionManager(w); - ProtectedRegion region = manager.getRegion(main.id.x + "-" + main.id.y); + RegionManager manager = PlotMain.worldGuard.getRegionManager(w); + ProtectedRegion region = manager.getRegion(main.id.x + "-" + main.id.y); - DefaultDomain owner = region.getOwners(); - Map, Object> flags = region.getFlags(); - DefaultDomain members = region.getMembers(); + DefaultDomain owner = region.getOwners(); + Map, Object> flags = region.getFlags(); + DefaultDomain members = region.getMembers(); - manager.removeRegion(main.id.x + "-" + main.id.y); - for (int i = 1; i < plots.size(); i++) { - PlotId id = plots.get(i); - Location location1 = PlotHelper.getPlotBottomLocAbs(w, id); - Location location2 = PlotHelper.getPlotTopLocAbs(w, id); + manager.removeRegion(main.id.x + "-" + main.id.y); + for (int i = 1; i < plots.size(); i++) { + PlotId id = plots.get(i); + Location location1 = PlotHelper.getPlotBottomLocAbs(w, id); + Location location2 = PlotHelper.getPlotTopLocAbs(w, id); - BlockVector vector1 = new BlockVector(location1.getBlockX(), 1, location1.getBlockZ()); - BlockVector vector2 = new BlockVector(location2.getBlockX(), w.getMaxHeight(), location2.getBlockZ()); - ProtectedRegion rg = new ProtectedCuboidRegion(id.x + "-" + id.y, vector1, vector2); + BlockVector vector1 = new BlockVector(location1.getBlockX(), 1, + location1.getBlockZ()); + BlockVector vector2 = new BlockVector(location2.getBlockX(), + w.getMaxHeight(), location2.getBlockZ()); + ProtectedRegion rg = new ProtectedCuboidRegion(id.x + "-" + id.y, + vector1, vector2); - rg.setFlags(flags); + rg.setFlags(flags); - rg.setOwners(owner); + rg.setOwners(owner); - rg.setMembers(members); + rg.setMembers(members); - manager.addRegion(rg); - } - } + manager.addRegion(rg); + } + } - @EventHandler - public void onPlotClaim(PlayerClaimPlotEvent event) { - Player player = event.getPlayer(); - Plot plot = event.getPlot(); - RegionManager manager = PlotMain.worldGuard.getRegionManager(plot.getWorld()); + @EventHandler + public void onPlotClaim(PlayerClaimPlotEvent event) { + Player player = event.getPlayer(); + Plot plot = event.getPlot(); + RegionManager manager = PlotMain.worldGuard.getRegionManager(plot + .getWorld()); - Location location1 = PlotHelper.getPlotBottomLoc(plot.getWorld(), plot.getId()); - Location location2 = PlotHelper.getPlotTopLoc(plot.getWorld(), plot.getId()); + Location location1 = PlotHelper.getPlotBottomLoc(plot.getWorld(), + plot.getId()); + Location location2 = PlotHelper.getPlotTopLoc(plot.getWorld(), + plot.getId()); - BlockVector vector1 = new BlockVector(location1.getBlockX(), 1, location1.getBlockZ()); - BlockVector vector2 = new BlockVector(location2.getBlockX(), plot.getWorld().getMaxHeight(), location2.getBlockZ()); + BlockVector vector1 = new BlockVector(location1.getBlockX(), 1, + location1.getBlockZ()); + BlockVector vector2 = new BlockVector(location2.getBlockX(), plot + .getWorld().getMaxHeight(), location2.getBlockZ()); - ProtectedRegion region = new ProtectedCuboidRegion(plot.getId().x + "-" + plot.getId().y, vector1, vector2); + ProtectedRegion region = new ProtectedCuboidRegion(plot.getId().x + "-" + + plot.getId().y, vector1, vector2); - DefaultDomain owner = new DefaultDomain(); - owner.addPlayer(PlotMain.worldGuard.wrapPlayer(player)); + DefaultDomain owner = new DefaultDomain(); + owner.addPlayer(PlotMain.worldGuard.wrapPlayer(player)); - region.setOwners(owner); + region.setOwners(owner); - manager.addRegion(region); - } + manager.addRegion(region); + } - @EventHandler - public void onPlotDelete(PlotDeleteEvent event) { - PlotId plot = event.getPlotId(); - World world = Bukkit.getWorld(event.getWorld()); + @EventHandler + public void onPlotDelete(PlotDeleteEvent event) { + PlotId plot = event.getPlotId(); + World world = Bukkit.getWorld(event.getWorld()); - RegionManager manager = PlotMain.worldGuard.getRegionManager(world); - manager.removeRegion(plot.x + "-" + plot.y); - } + RegionManager manager = PlotMain.worldGuard.getRegionManager(world); + manager.removeRegion(plot.x + "-" + plot.y); + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/uuid/NameFetcher.java b/PlotSquared/src/com/intellectualcrafters/plot/uuid/NameFetcher.java index b5f42e93b..6403ef129 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/uuid/NameFetcher.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/uuid/NameFetcher.java @@ -15,39 +15,42 @@ import org.json.simple.parser.JSONParser; import com.google.common.collect.ImmutableList; /** - * + * * @author - * + * */ public class NameFetcher implements Callable> { - private static final String PROFILE_URL = "https://sessionserver.mojang.com/session/minecraft/profile/"; - private final JSONParser jsonParser = new JSONParser(); - private final List uuids; + private static final String PROFILE_URL = "https://sessionserver.mojang.com/session/minecraft/profile/"; + private final JSONParser jsonParser = new JSONParser(); + private final List uuids; - public NameFetcher(List uuids) { - this.uuids = ImmutableList.copyOf(uuids); - } + public NameFetcher(List uuids) { + this.uuids = ImmutableList.copyOf(uuids); + } - @Override - public Map call() throws Exception { - Map uuidStringMap = new HashMap(); - for (UUID uuid : this.uuids) { - if (uuidStringMap.containsKey(uuid)) { - continue; - } - HttpURLConnection connection = (HttpURLConnection) new URL(PROFILE_URL + uuid.toString().replace("-", "")).openConnection(); - JSONObject response = (JSONObject) this.jsonParser.parse(new InputStreamReader(connection.getInputStream())); - String name = (String) response.get("name"); - if (name == null) { - continue; - } - String cause = (String) response.get("cause"); - String errorMessage = (String) response.get("errorMessage"); - if ((cause != null) && (cause.length() > 0)) { - throw new IllegalStateException(errorMessage); - } - uuidStringMap.put(uuid, name); - } - return uuidStringMap; - } + @Override + public Map call() throws Exception { + Map uuidStringMap = new HashMap(); + for (UUID uuid : this.uuids) { + if (uuidStringMap.containsKey(uuid)) { + continue; + } + HttpURLConnection connection = (HttpURLConnection) new URL( + PROFILE_URL + uuid.toString().replace("-", "")) + .openConnection(); + JSONObject response = (JSONObject) this.jsonParser + .parse(new InputStreamReader(connection.getInputStream())); + String name = (String) response.get("name"); + if (name == null) { + continue; + } + String cause = (String) response.get("cause"); + String errorMessage = (String) response.get("errorMessage"); + if ((cause != null) && (cause.length() > 0)) { + throw new IllegalStateException(errorMessage); + } + uuidStringMap.put(uuid, name); + } + return uuidStringMap; + } } diff --git a/PlotSquared/src/com/intellectualcrafters/plot/uuid/UUIDFetcher.java b/PlotSquared/src/com/intellectualcrafters/plot/uuid/UUIDFetcher.java index 37916e858..614bc9e4c 100644 --- a/PlotSquared/src/com/intellectualcrafters/plot/uuid/UUIDFetcher.java +++ b/PlotSquared/src/com/intellectualcrafters/plot/uuid/UUIDFetcher.java @@ -22,84 +22,91 @@ import com.google.common.collect.ImmutableList; * @author */ public class UUIDFetcher implements Callable> { - private static final double PROFILES_PER_REQUEST = 100; - private static final String PROFILE_URL = "https://api.mojang.com/profiles/minecraft"; - private final JSONParser jsonParser = new JSONParser(); - private final List names; - private final boolean rateLimiting; + private static final double PROFILES_PER_REQUEST = 100; + private static final String PROFILE_URL = "https://api.mojang.com/profiles/minecraft"; + private final JSONParser jsonParser = new JSONParser(); + private final List names; + private final boolean rateLimiting; - public UUIDFetcher(List names, boolean rateLimiting) { - this.names = ImmutableList.copyOf(names); - this.rateLimiting = rateLimiting; - } + public UUIDFetcher(List names, boolean rateLimiting) { + this.names = ImmutableList.copyOf(names); + this.rateLimiting = rateLimiting; + } - public UUIDFetcher(List names) { - this(names, true); - } + public UUIDFetcher(List names) { + this(names, true); + } - @Override - public Map call() throws Exception { - Map uuidMap = new HashMap(); - int requests = (int) Math.ceil(this.names.size() / PROFILES_PER_REQUEST); - for (int i = 0; i < requests; i++) { - HttpURLConnection connection = createConnection(); - String body = JSONArray.toJSONString(this.names.subList(i * 100, Math.min((i + 1) * 100, this.names.size()))); - writeBody(connection, body); - JSONArray array = (JSONArray) this.jsonParser.parse(new InputStreamReader(connection.getInputStream())); - for (Object profile : array) { - JSONObject jsonProfile = (JSONObject) profile; - String id = (String) jsonProfile.get("id"); - String name = (String) jsonProfile.get("name"); - UUID uuid = UUIDFetcher.getUUID(id); - uuidMap.put(name, uuid); - } - if (this.rateLimiting && (i != (requests - 1))) { - Thread.sleep(100L); - } - } - return uuidMap; - } + @Override + public Map call() throws Exception { + Map uuidMap = new HashMap(); + int requests = (int) Math + .ceil(this.names.size() / PROFILES_PER_REQUEST); + for (int i = 0; i < requests; i++) { + HttpURLConnection connection = createConnection(); + String body = JSONArray.toJSONString(this.names.subList(i * 100, + Math.min((i + 1) * 100, this.names.size()))); + writeBody(connection, body); + JSONArray array = (JSONArray) this.jsonParser + .parse(new InputStreamReader(connection.getInputStream())); + for (Object profile : array) { + JSONObject jsonProfile = (JSONObject) profile; + String id = (String) jsonProfile.get("id"); + String name = (String) jsonProfile.get("name"); + UUID uuid = UUIDFetcher.getUUID(id); + uuidMap.put(name, uuid); + } + if (this.rateLimiting && (i != (requests - 1))) { + Thread.sleep(100L); + } + } + return uuidMap; + } - private static void writeBody(HttpURLConnection connection, String body) throws Exception { - OutputStream stream = connection.getOutputStream(); - stream.write(body.getBytes()); - stream.flush(); - stream.close(); - } + private static void writeBody(HttpURLConnection connection, String body) + throws Exception { + OutputStream stream = connection.getOutputStream(); + stream.write(body.getBytes()); + stream.flush(); + stream.close(); + } - private static HttpURLConnection createConnection() throws Exception { - URL url = new URL(PROFILE_URL); - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod("POST"); - connection.setRequestProperty("Content-Type", "application/json"); - connection.setUseCaches(false); - connection.setDoInput(true); - connection.setDoOutput(true); - return connection; - } + private static HttpURLConnection createConnection() throws Exception { + URL url = new URL(PROFILE_URL); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("POST"); + connection.setRequestProperty("Content-Type", "application/json"); + connection.setUseCaches(false); + connection.setDoInput(true); + connection.setDoOutput(true); + return connection; + } - public static UUID getUUID(String id) { - return UUID.fromString(id.substring(0, 8) + "-" + id.substring(8, 12) + "-" + id.substring(12, 16) + "-" + id.substring(16, 20) + "-" + id.substring(20, 32)); - } + public static UUID getUUID(String id) { + return UUID.fromString(id.substring(0, 8) + "-" + id.substring(8, 12) + + "-" + id.substring(12, 16) + "-" + id.substring(16, 20) + "-" + + id.substring(20, 32)); + } - public static byte[] toBytes(UUID uuid) { - ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]); - byteBuffer.putLong(uuid.getMostSignificantBits()); - byteBuffer.putLong(uuid.getLeastSignificantBits()); - return byteBuffer.array(); - } + public static byte[] toBytes(UUID uuid) { + ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]); + byteBuffer.putLong(uuid.getMostSignificantBits()); + byteBuffer.putLong(uuid.getLeastSignificantBits()); + return byteBuffer.array(); + } - public static UUID fromBytes(byte[] array) { - if (array.length != 16) { - throw new IllegalArgumentException("Illegal byte array length: " + array.length); - } - ByteBuffer byteBuffer = ByteBuffer.wrap(array); - long mostSignificant = byteBuffer.getLong(); - long leastSignificant = byteBuffer.getLong(); - return new UUID(mostSignificant, leastSignificant); - } + public static UUID fromBytes(byte[] array) { + if (array.length != 16) { + throw new IllegalArgumentException("Illegal byte array length: " + + array.length); + } + ByteBuffer byteBuffer = ByteBuffer.wrap(array); + long mostSignificant = byteBuffer.getLong(); + long leastSignificant = byteBuffer.getLong(); + return new UUID(mostSignificant, leastSignificant); + } - public static UUID getUUIDOf(String name) throws Exception { - return new UUIDFetcher(Arrays.asList(name)).call().get(name); - } + public static UUID getUUIDOf(String name) throws Exception { + return new UUIDFetcher(Arrays.asList(name)).call().get(name); + } } diff --git a/PlotSquared/src/com/intellectualsites/web/IndexHandler.java b/PlotSquared/src/com/intellectualsites/web/IndexHandler.java index 9e0a1bc2f..eeae18306 100644 --- a/PlotSquared/src/com/intellectualsites/web/IndexHandler.java +++ b/PlotSquared/src/com/intellectualsites/web/IndexHandler.java @@ -15,78 +15,89 @@ import org.simpleframework.http.core.Container; */ public class IndexHandler implements Container { - private JavaPlugin plugin; - private String title; + private JavaPlugin plugin; + private String title; - public IndexHandler(JavaPlugin plugin, String title) { - this.plugin = plugin; - this.title = title; - } + public IndexHandler(JavaPlugin plugin, String title) { + this.plugin = plugin; + this.title = title; + } - @Override - public void handle(Request request, Response response) { - try { - PrintStream body; - long time; - String coverage; + @Override + public void handle(Request request, Response response) { + try { + PrintStream body; + long time; + String coverage; - body = response.getPrintStream(); - time = System.currentTimeMillis(); - request.getQuery(); - request.getPath(); + body = response.getPrintStream(); + time = System.currentTimeMillis(); + request.getQuery(); + request.getPath(); - if ((request.getInteger("page")) < 0) { - } - if (((coverage = request.getTarget()) == null) || coverage.equals("/")) { - coverage = "index"; - } + if ((request.getInteger("page")) < 0) { + } + if (((coverage = request.getTarget()) == null) + || coverage.equals("/")) { + coverage = "index"; + } - coverage = coverage.toLowerCase(); + coverage = coverage.toLowerCase(); - List list = new ArrayList<>(Arrays.asList(new String[] { "install", "index", "stylesheet" })); + List list = new ArrayList<>(Arrays.asList(new String[] { + "install", "index", "stylesheet" })); - if (!list.contains(coverage)) { - coverage = "index"; - } + if (!list.contains(coverage)) { + coverage = "index"; + } - if (coverage.equals("stylesheet")) { - response.setValue("Content-Type", "text/css"); - response.setValue("Server", "PlotWeb/1.0 (Simple 5.0)"); - response.setDate("Date", time); - response.setDate("Last-Modified", time); + if (coverage.equals("stylesheet")) { + response.setValue("Content-Type", "text/css"); + response.setValue("Server", "PlotWeb/1.0 (Simple 5.0)"); + response.setDate("Date", time); + response.setDate("Last-Modified", time); - ResourceHandler stylesheet = new ResourceHandler("stylesheet", ResourceHandler.FileType.CSS, this.plugin.getDataFolder()); + ResourceHandler stylesheet = new ResourceHandler("stylesheet", + ResourceHandler.FileType.CSS, + this.plugin.getDataFolder()); - String stylesheetHTML = stylesheet.getHTML(); + String stylesheetHTML = stylesheet.getHTML(); - stylesheet.done(); + stylesheet.done(); - body.print(stylesheetHTML); - } else { - response.setValue("Content-Type", "html"); - response.setValue("Server", "PlotWeb/1.0 (Simple 5.0)"); - response.setDate("Date", time); - response.setDate("Last-Modified", time); + body.print(stylesheetHTML); + } else { + response.setValue("Content-Type", "html"); + response.setValue("Server", "PlotWeb/1.0 (Simple 5.0)"); + response.setDate("Date", time); + response.setDate("Last-Modified", time); - ResourceHandler header = new ResourceHandler("header", ResourceHandler.FileType.HTML, this.plugin.getDataFolder()); - ResourceHandler footer = new ResourceHandler("footer", ResourceHandler.FileType.HTML, this.plugin.getDataFolder()); - ResourceHandler cPage = new ResourceHandler(coverage, ResourceHandler.FileType.HTML, this.plugin.getDataFolder()); + ResourceHandler header = new ResourceHandler("header", + ResourceHandler.FileType.HTML, + this.plugin.getDataFolder()); + ResourceHandler footer = new ResourceHandler("footer", + ResourceHandler.FileType.HTML, + this.plugin.getDataFolder()); + ResourceHandler cPage = new ResourceHandler(coverage, + ResourceHandler.FileType.HTML, + this.plugin.getDataFolder()); - String headerHTML = header.getHTML().replace("@title", this.title); - String footerHTML = footer.getHTML(); - String cPageHTML = cPage.getHTML(); + String headerHTML = header.getHTML().replace("@title", + this.title); + String footerHTML = footer.getHTML(); + String cPageHTML = cPage.getHTML(); - header.done(); - footer.done(); - cPage.done(); + header.done(); + footer.done(); + cPage.done(); - body.print(headerHTML); - body.print(cPageHTML); - body.print(footerHTML); - } - body.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } + body.print(headerHTML); + body.print(cPageHTML); + body.print(footerHTML); + } + body.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } } diff --git a/PlotSquared/src/com/intellectualsites/web/PlotWeb.java b/PlotSquared/src/com/intellectualsites/web/PlotWeb.java index fc9cade88..3a1c69e5e 100644 --- a/PlotSquared/src/com/intellectualsites/web/PlotWeb.java +++ b/PlotSquared/src/com/intellectualsites/web/PlotWeb.java @@ -17,34 +17,35 @@ import com.intellectualcrafters.plot.PlotMain; */ public class PlotWeb { - // TODO instructions on how to setup and use PlotWeb. + // TODO instructions on how to setup and use PlotWeb. - public static PlotWeb PLOTWEB; + public static PlotWeb PLOTWEB; - private String title; - private int port; - private Server server; - private Connection connection; - private Container container; - private SocketAddress address; + private String title; + private int port; + private Server server; + private Connection connection; + private Container container; + private SocketAddress address; - public PlotWeb(String title, int port) { - this.title = title; - this.port = port; - } + public PlotWeb(String title, int port) { + this.title = title; + this.port = port; + } - public void start() throws Exception { - this.container = new IndexHandler(JavaPlugin.getPlugin(PlotMain.class), this.title); - this.server = new ContainerServer(this.container); - this.connection = new SocketConnection(this.server); - this.address = new InetSocketAddress(this.port); + public void start() throws Exception { + this.container = new IndexHandler(JavaPlugin.getPlugin(PlotMain.class), + this.title); + this.server = new ContainerServer(this.container); + this.connection = new SocketConnection(this.server); + this.address = new InetSocketAddress(this.port); - this.connection.connect(this.address); - PLOTWEB = this; - } + this.connection.connect(this.address); + PLOTWEB = this; + } - public void stop() throws Exception { - this.connection.close(); - PLOTWEB = null; - } + public void stop() throws Exception { + this.connection.close(); + PLOTWEB = null; + } } diff --git a/PlotSquared/src/com/intellectualsites/web/ResourceHandler.java b/PlotSquared/src/com/intellectualsites/web/ResourceHandler.java index b150cbccc..1196b2d4c 100644 --- a/PlotSquared/src/com/intellectualsites/web/ResourceHandler.java +++ b/PlotSquared/src/com/intellectualsites/web/ResourceHandler.java @@ -10,43 +10,49 @@ import java.io.InputStreamReader; */ public class ResourceHandler { - private File file; - private BufferedReader reader; + private File file; + private BufferedReader reader; - public ResourceHandler(String filePath, FileType fileType, File folder) throws Exception { - if (fileType == FileType.CSS) { - this.file = new File(folder.toPath().toString() + File.separator + "web" + File.separator + "css" + File.separator + filePath + "." + fileType.toString()); - } else { - this.file = new File(folder.toPath().toString() + File.separator + "web" + File.separator + filePath + "." + fileType.toString()); - } - } + public ResourceHandler(String filePath, FileType fileType, File folder) + throws Exception { + if (fileType == FileType.CSS) { + this.file = new File(folder.toPath().toString() + File.separator + + "web" + File.separator + "css" + File.separator + + filePath + "." + fileType.toString()); + } else { + this.file = new File(folder.toPath().toString() + File.separator + + "web" + File.separator + filePath + "." + + fileType.toString()); + } + } - public String getHTML() throws Exception { - StringBuilder html = new StringBuilder(); - this.reader = new BufferedReader(new InputStreamReader(new FileInputStream(this.file))); - String line = ""; - while ((line = this.reader.readLine()) != null) { - html.append(line); - } - return html.toString(); - } + public String getHTML() throws Exception { + StringBuilder html = new StringBuilder(); + this.reader = new BufferedReader(new InputStreamReader( + new FileInputStream(this.file))); + String line = ""; + while ((line = this.reader.readLine()) != null) { + html.append(line); + } + return html.toString(); + } - public void done() throws Exception { - this.reader.close(); - } + public void done() throws Exception { + this.reader.close(); + } - public static enum FileType { - CSS("css"), HTML("html"), JS("js"); + public static enum FileType { + CSS("css"), HTML("html"), JS("js"); - private String ext; + private String ext; - FileType(String ext) { - this.ext = ext; - } + FileType(String ext) { + this.ext = ext; + } - @Override - public String toString() { - return this.ext; - } - } + @Override + public String toString() { + return this.ext; + } + } } diff --git a/PlotSquared/src/com/intellectualsites/web/Test.java b/PlotSquared/src/com/intellectualsites/web/Test.java index 2b573831d..a6ba06daf 100644 --- a/PlotSquared/src/com/intellectualsites/web/Test.java +++ b/PlotSquared/src/com/intellectualsites/web/Test.java @@ -5,12 +5,12 @@ package com.intellectualsites.web; */ public class Test { - public static void main(String[] args) { - try { - new PlotWeb("Test", 9000).start(); - } catch (Exception e) { - e.printStackTrace(); - } - } + public static void main(String[] args) { + try { + new PlotWeb("Test", 9000).start(); + } catch (Exception e) { + e.printStackTrace(); + } + } }