No red files anymore. Some stuff still unfinished.

+ weekly code cleanup
This commit is contained in:
Jesse Boyd 2014-10-11 00:33:10 -07:00
parent 2f5f3ac8e2
commit a6375796c0
94 changed files with 14237 additions and 12908 deletions

View File

@ -7,37 +7,38 @@ import org.apache.commons.lang.StringUtils;
*/ */
public class AbstractFlag { public class AbstractFlag {
private final String key; private final String key;
/** /**
* AbstractFlag is a parameter used in creating a new Flag * AbstractFlag is a parameter used in creating a new Flag
* *
* @param key * @param key
* The key must be alphabetical characters and <= 16 characters * The key must be alphabetical characters and <= 16 characters
* in length * in length
*/ */
public AbstractFlag(String key) { public AbstractFlag(String key) {
if (!StringUtils.isAlpha(key)) { if (!StringUtils.isAlpha(key)) {
throw new IllegalArgumentException("Flag must be alphabetic characters"); throw new IllegalArgumentException(
} "Flag must be alphabetic characters");
if (key.length() > 16) { }
throw new IllegalArgumentException("Key must be <= 16 characters"); if (key.length() > 16) {
} throw new IllegalArgumentException("Key must be <= 16 characters");
this.key = key.toLowerCase(); }
} this.key = key.toLowerCase();
}
/** /**
* AbstractFlag key * AbstractFlag key
* *
* @return String * @return String
*/ */
public String getKey() { public String getKey() {
return this.key; return this.key;
} }
@Override @Override
public String toString() { public String toString() {
return this.key; return this.key;
} }
} }

View File

@ -18,241 +18,331 @@ import org.bukkit.ChatColor;
* *
*/ */
public enum C { public enum C {
/* /*
* Ratings * 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"), 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(
* Economy Stuff "&cYou successfully rated plot &6%s"), RATING_NOT_YOUR_OWN(
*/ "&cYou cannot rate your own plot"), RATING_NOT_OWNED(
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"), "&cYou cannot rate a plot that is not claimed by anyone"),
/* /*
* Setup Stuff * Economy Stuff
*/ */
SETUP_INIT("&6PlotSquared Setup -> Setup a new plotworld"), SETUP_STEP("&cStep &6%s&c: %s &c<Expecting: &6%s&c, Default: &6%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 <value>\n&c - &6/p setup back\n&c - &6/p setup cancel"), 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(
* Schematic Stuff "&6%s &chas been added to your balance"), REMOVED_BALANCE(
*/ "&6%s &chas been taken from your balance"),
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"), /*
/* * Setup Stuff
* Title Stuff */
*/ SETUP_INIT("&6PlotSquared Setup -> Setup a new plotworld"), SETUP_STEP(
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"), "&cStep &6%s&c: %s &c<Expecting: &6%s&c, Default: &6%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(
* Core Stuff "&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(
PREFIX("&c[&6&lPlot&c] "), ENABLED("&6Plots are now enabled"), EXAMPLE_MESSAGE("&cThis is an example message &k!!!"), "&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 <value>\n&c - &6/p setup back\n&c - &6/p setup cancel"),
* Reload /*
*/ * Schematic Stuff
RELOADED_CONFIGS("&6The translation files has been reloaded"), RELOAD_FAILED("&cFailed to reload the translations file"), */
/* SCHEMATIC_MISSING_ARG(
* BarAPI "&cYou need to specify an argument. Possible values: &6test {name}"), SCHEMATIC_INVALID(
*/ "&cThat is not a valid schematic. Reason: &c%s"), SCHEMATIC_VALID(
BOSSBAR_CLEARING("&cClearing plot: &6%id%"), "&cThat's a valid schematic"), SCHEMATIC_PASTE_FAILED(
/* "&cFailed to paste schematic"), SCHEMATIC_PASTE_SUCCESS(
* Alias "&cSchematic pasted successfully"),
*/ /*
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"), * Title Stuff
/* */
* Position 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(
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"), "You entered plot %s"), TITLE_LEFT_PLOT_COLOR("GOLD"), TITLE_LEFT_PLOT_SUB(
/* "Owned by %s"), TITLE_LEFT_PLOT_SUB_COLOR("RED"),
* Time /*
*/ * Core Stuff
TIME_FORMAT("&6%hours%, %min%, %sec%"), */
/* PREFIX("&c[&6&lPlot&c] "), ENABLED("&6Plots are now enabled"), EXAMPLE_MESSAGE(
* Permission "&cThis is an example message &k!!!"),
*/ /*
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"), * 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."), NO_PERM_MERGE("&cYou are not the owner of the plot: &6%plot%"), UNLINK_REQUIRED(
/* "&cAn unlink is required to do this."), UNLINK_IMPOSSIBLE(
* Commands "&cYou can only unlink a mega-plot"), NO_MERGE_TO_MEGA(
*/ "&cMega plots cannot be merged into. Please merge from the desired mega plot."),
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: "), /*
/* * Commands
* Player not found */
*/ NOT_VALID_SUBCOMMAND("&cThat is not a valid subcommand."), NO_COMMANDS(
INVALID_PLAYER("&cPlayer not found: &6%player%."), "&cI'm sorry, but you're not permitted to use any subcommands."), SUBCOMMAND_SET_OPTIONS_HEADER(
/* "&cPossible Values: "),
* /*
*/ * Player not found
COMMAND_WENT_WRONG("&cSomething went wrong when executing that command..."), */
/* INVALID_PLAYER("&cPlayer not found: &6%player%."),
* 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"), */
/* COMMAND_WENT_WRONG("&cSomething went wrong when executing that command..."),
* Block List /*
*/ * No {plot}
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 "), */
/* NOT_IN_PLOT("&cYou're not in a plot"), NOT_IN_PLOT_WORLD(
* Biome "&cYou're not in a plot world"), NOT_VALID_WORLD(
*/ "&cThat is not a valid world (case sensitive)"), NOT_VALID_PLOT_WORLD(
NEED_BIOME("&cYou've got to specify a biome"), BIOME_SET_TO("&cPlot biome set to &c"), "&cThat is not a valid plot world (case sensitive)"), NO_PLOTS(
/* "&cYou don't have any plots"),
* Teleport / Entry /*
*/ * Block List
TELEPORTED_TO_PLOT("&6You have been teleported"), */
/* NOT_VALID_BLOCK_LIST_HEADER(
* Set Block "&cThat's not a valid block. Valid blocks are:\\n"), BLOCK_LIST_ITEM(
*/ " &6%mat%&c,"), BLOCK_LIST_SEPARATER("&6,&c "),
SET_BLOCK_ACTION_FINISHED("&6The last setblock action is now finished."), /*
/* * Biome
* Debug */
*/ NEED_BIOME("&cYou've got to specify a biome"), BIOME_SET_TO(
DEUBG_HEADER("&6Debug Information\\n"), DEBUG_SECTION("&c>> &6&l%val%"), DEBUG_LINE("&c>> &6%var%&c:&6 %val%\\n"), "&cPlot biome set to &c"),
/* /*
* Invalid * Teleport / Entry
*/ */
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"), TELEPORTED_TO_PLOT("&6You have been teleported"),
/* /*
* Camera * Set Block
*/ */
CAMERA_STARTED("&cYou have entered camera mode for plot &6%s"), CAMERA_STOPPED("&cYou are no longer in camera mode"), SET_BLOCK_ACTION_FINISHED("&6The last setblock action is now finished."),
/* /*
* Need * Debug
*/ */
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"), DEUBG_HEADER("&6Debug Information\\n"), DEBUG_SECTION("&c>> &6&l%val%"), DEBUG_LINE(
/* "&c>> &6%var%&c:&6 %val%\\n"),
* Info /*
*/ * Invalid
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,"), */
/* NOT_VALID_DATA("&cThat's not a valid data id."), NOT_VALID_BLOCK(
* Generating "&cThat's not a valid block."), NOT_VALID_NUMBER(
*/ "&cThat's not a valid number"), NOT_VALID_PLOT_ID(
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."), "&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(
* Clearing "&cThat player hasn't been in the plotworld"), FOUND_NO_PLOTS(
*/ "&cFound no plots with your search query"),
CLEARING_PLOT("&cClearing plot."), CLEARING_DONE("&6Done, took &a%time%&6 ms!"), CLEARING_DONE_PACKETS("&6(&a%time% &6ms for packets)"), /*
/* * Camera
* Claiming */
*/ CAMERA_STARTED("&cYou have entered camera mode for plot &6%s"), CAMERA_STOPPED(
PLOT_NOT_CLAIMED("&cCannot claim plot"), PLOT_IS_CLAIMED("&cThis plot is already claimed"), CLAIMED("&6You successfully claimed the plot"), "&cYou are no longer in camera mode"),
/* /*
* List * Need
*/ */
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%."), 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(
* Left "&cYou've got to specify a plot id."), NEED_USER(
*/ "&cYou need to specify a username"),
LEFT_PLOT("&cYou left a plot"), /*
/* * Info
* Wait */
*/ PLOT_INFO_UNCLAIMED("&cPlot &6%s&c is not yet claimed"), PLOT_INFO(
WAIT_FOR_TIMER("&cA setblock timer is bound to either the current plot or you. Please wait for it to finish"), "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,"),
* Chat /*
*/ * Generating
PLOT_CHAT_FORMAT("&c[&6Plot Chat&c][&6%plot_id%&c] &6%sender%&c: &6%msg%"), */
/* GENERATING_FLOOR(
* Denied "&6Started generating floor from your settings. It will take %time%"), GENERATING_WALL(
*/ "&6Started generating wall from your settings"), GENERATING_WALL_FILLING(
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"), "&cStarted generating wall filling from your settings."),
/* /*
* Rain * Clearing
*/ */
NEED_ON_OFF("&cYou need to specify a value. Possible values: &6on&c, &6off"), SETTING_UPDATED("&cYou successfully updated the setting"), CLEARING_PLOT("&cClearing plot."), CLEARING_DONE(
/* "&6Done, took &a%time%&6 ms!"), CLEARING_DONE_PACKETS(
* Flag "&6(&a%time% &6ms for packets)"),
*/ /*
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"), * Claiming
/* */
* Helper PLOT_NOT_CLAIMED("&cCannot claim plot"), PLOT_IS_CLAIMED(
*/ "&cThis plot is already claimed"), CLAIMED(
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"), "&6You successfully claimed the plot"),
/* /*
* Trusted * List
*/ */
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"), PLOT_LIST_HEADER("&6List of %word% plots"), PLOT_LIST_ITEM(
/* "&c>> &6%id% &c- &6%owner%"), PLOT_LIST_FOOTER(
* Set Owner "&c>> &6%word% a total of &c%num% &6claimed %plot%."),
*/ /*
SET_OWNER("&6You successfully set the plot owner"), * Left
/* */
* Signs LEFT_PLOT("&cYou left a plot"),
*/ /*
OWNER_SIGN_LINE_1("&cID: &6%id%"), OWNER_SIGN_LINE_2("&cOwner:"), OWNER_SIGN_LINE_3("&6%plr%"), OWNER_SIGN_LINE_4("&2Claimed"), * Wait
/* */
* Help WAIT_FOR_TIMER(
*/ "&cA setblock timer is bound to either the current plot or you. Please wait for it to finish"),
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"), /*
/* * Chat
* Direction */
*/ PLOT_CHAT_FORMAT("&c[&6Plot Chat&c][&6%plot_id%&c] &6%sender%&c: &6%msg%"),
DIRECTION("&6Current direction: %dir%"), /*
/* * Denied
* Custom */
*/ DENIED_REMOVED("&cYou successfully undenied the player from this plot"), DENIED_ADDED(
CUSTOM_STRING("-"); "&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(
* Default "&cThat player was not denied on this plot"),
*/ /*
private String d; * Rain
/** */
* Translated NEED_ON_OFF("&cYou need to specify a value. Possible values: &6on&c, &6off"), SETTING_UPDATED(
*/ "&cYou successfully updated the setting"),
private String s; /*
* 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. * Constructor for custom strings.
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
C() { C() {
/* /*
* use setCustomString(); * use setCustomString();
*/ */
} }
/** /**
* Constructor * Constructor
* *
* @param d * @param d
* default * default
*/ */
C(String d) { C(String d) {
this.d = d; this.d = d;
if (PlotMain.translations == null) { if (PlotMain.translations == null) {
this.s = d; this.s = d;
} else { } else {
this.s = PlotMain.translations.getString(this.toString()); this.s = PlotMain.translations.getString(this.toString());
} }
if (this.s == null) { if (this.s == null) {
this.s = ""; this.s = "";
} }
} }
/** /**
* Get the default string * Get the default string
* *
* @return default * @return default
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
public String d() { public String d() {
return this.d; return this.d;
} }
/** /**
* Get translated if exists * Get translated if exists
* *
* @return translated if exists else default * @return translated if exists else default
*/ */
public String s() { public String s() {
if (this.s.length() < 1) { if (this.s.length() < 1) {
return this.d.replace("\\n", "\n"); return this.d.replace("\\n", "\n");
} }
return this.s.replace("\\n", "\n"); return this.s.replace("\\n", "\n");
} }
/** /**
* *
* @return translated and color decoded * @return translated and color decoded
*/ */
public String translated() { public String translated() {
return ChatColor.translateAlternateColorCodes('&', this.s()); return ChatColor.translateAlternateColorCodes('&', this.s());
} }
} }

View File

@ -5,203 +5,207 @@ import java.util.List;
import org.bukkit.block.Biome; import org.bukkit.block.Biome;
public class Configuration { public class Configuration {
public static final SettingValue STRING = new SettingValue("STRING") { public static final SettingValue STRING = new SettingValue("STRING") {
@Override @Override
public boolean validateValue(String string) { public boolean validateValue(String string) {
return true; return true;
} }
@Override @Override
public Object parseString(String string) { public Object parseString(String string) {
return string; return string;
} }
}; };
public static final SettingValue STRINGLIST = new SettingValue("STRINGLIST") { public static final SettingValue STRINGLIST = new SettingValue("STRINGLIST") {
@Override @Override
public boolean validateValue(String string) { public boolean validateValue(String string) {
return true; return true;
} }
@Override @Override
public Object parseString(String string) { public Object parseString(String string) {
return string.split(","); return string.split(",");
} }
}; };
public static final SettingValue INTEGER = new SettingValue("INTEGER") { public static final SettingValue INTEGER = new SettingValue("INTEGER") {
@Override @Override
public boolean validateValue(String string) { public boolean validateValue(String string) {
try { try {
Integer.parseInt(string); Integer.parseInt(string);
return true; return true;
} catch (Exception e) { } catch (Exception e) {
return false; return false;
} }
} }
@Override @Override
public Object parseString(String string) { public Object parseString(String string) {
return Integer.parseInt(string); return Integer.parseInt(string);
} }
}; };
public static final SettingValue BOOLEAN = new SettingValue("BOOLEAN") { public static final SettingValue BOOLEAN = new SettingValue("BOOLEAN") {
@Override @Override
public boolean validateValue(String string) { public boolean validateValue(String string) {
try { try {
Boolean.parseBoolean(string); Boolean.parseBoolean(string);
return true; return true;
} catch (Exception e) { } catch (Exception e) {
return false; return false;
} }
} }
@Override @Override
public Object parseString(String string) { public Object parseString(String string) {
return Boolean.parseBoolean(string); return Boolean.parseBoolean(string);
} }
}; };
public static final SettingValue DOUBLE = new SettingValue("DOUBLE") { public static final SettingValue DOUBLE = new SettingValue("DOUBLE") {
@Override @Override
public boolean validateValue(String string) { public boolean validateValue(String string) {
try { try {
Double.parseDouble(string); Double.parseDouble(string);
return true; return true;
} catch (Exception e) { } catch (Exception e) {
return false; return false;
} }
} }
@Override @Override
public Object parseString(String string) { public Object parseString(String string) {
return Double.parseDouble(string); return Double.parseDouble(string);
} }
}; };
public static final SettingValue BIOME = new SettingValue("BIOME") { public static final SettingValue BIOME = new SettingValue("BIOME") {
@Override @Override
public boolean validateValue(String string) { public boolean validateValue(String string) {
try { try {
Biome.valueOf(string.toUpperCase()); Biome.valueOf(string.toUpperCase());
return true; return true;
} catch (Exception e) { } catch (Exception e) {
return false; return false;
} }
} }
@Override @Override
public Object parseString(String string) { public Object parseString(String string) {
return Biome.valueOf(string.toUpperCase()); return Biome.valueOf(string.toUpperCase());
} }
@Override @Override
public Object parseObject(Object object) { public Object parseObject(Object object) {
return ((Biome) object).toString(); return ((Biome) object).toString();
} }
}; };
public static final SettingValue BLOCK = new SettingValue("BLOCK") { public static final SettingValue BLOCK = new SettingValue("BLOCK") {
@Override @Override
public boolean validateValue(String string) { public boolean validateValue(String string) {
try { try {
if (string.contains(":")) { if (string.contains(":")) {
String[] split = string.split(":"); String[] split = string.split(":");
Short.parseShort(split[0]); Short.parseShort(split[0]);
Short.parseShort(split[1]); Short.parseShort(split[1]);
} else { } else {
Short.parseShort(string); Short.parseShort(string);
} }
return true; return true;
} catch (Exception e) { } catch (Exception e) {
return false; return false;
} }
} }
@Override @Override
public Object parseString(String string) { public Object parseString(String string) {
if (string.contains(":")) { if (string.contains(":")) {
String[] split = string.split(":"); String[] split = string.split(":");
return new PlotBlock(Short.parseShort(split[0]), Byte.parseByte(split[1])); return new PlotBlock(Short.parseShort(split[0]),
} else { Byte.parseByte(split[1]));
return new PlotBlock(Short.parseShort(string), (byte) 0); } else {
} return new PlotBlock(Short.parseShort(string), (byte) 0);
} }
}
@Override @Override
public Object parseObject(Object object) { public Object parseObject(Object object) {
return ((PlotBlock) object).id+":"+((PlotBlock) object).data; return ((PlotBlock) object).id + ":" + ((PlotBlock) object).data;
} }
}; };
public static final SettingValue BLOCKLIST = new SettingValue("BLOCKLIST") { public static final SettingValue BLOCKLIST = new SettingValue("BLOCKLIST") {
@Override @Override
public boolean validateValue(String string) { public boolean validateValue(String string) {
try { try {
for (String block : string.split(",")) { for (String block : string.split(",")) {
if (block.contains(":")) { if (block.contains(":")) {
String[] split = block.split(":"); String[] split = block.split(":");
Short.parseShort(split[0]); Short.parseShort(split[0]);
Short.parseShort(split[1]); Short.parseShort(split[1]);
} else { } else {
Short.parseShort(block); Short.parseShort(block);
} }
} }
return true; return true;
} catch (Exception e) { } catch (Exception e) {
return false; return false;
} }
} }
@Override @Override
public Object parseString(String string) { public Object parseString(String string) {
String[] blocks = string.split(","); String[] blocks = string.split(",");
PlotBlock[] values = new PlotBlock[blocks.length]; PlotBlock[] values = new PlotBlock[blocks.length];
for (int i = 0; i<blocks.length; i++) { for (int i = 0; i < blocks.length; i++) {
if (string.contains(":")) { if (string.contains(":")) {
String[] split = string.split(":"); String[] split = string.split(":");
values[i] = new PlotBlock(Short.parseShort(split[0]), Byte.parseByte(split[1])); values[i] = new PlotBlock(Short.parseShort(split[0]),
} else { Byte.parseByte(split[1]));
values[i] = new PlotBlock(Short.parseShort(string), (byte) 0); } else {
} values[i] = new PlotBlock(Short.parseShort(string),
} (byte) 0);
return values; }
} }
@Override return values;
public Object parseObject(Object object) { }
List<String> list = new ArrayList<String>();
for (PlotBlock block:(PlotBlock[]) object) {
list.add((block.id+":"+(block.data)));
}
return list;
}
};
/** @Override
* public Object parseObject(Object object) {
* Create your own SettingValue object to make the management of plotworld configuration easier List<String> list = new ArrayList<String>();
* for (PlotBlock block : (PlotBlock[]) object) {
*/ list.add((block.id + ":" + (block.data)));
public static abstract class SettingValue { }
private String type; return list;
}
};
public SettingValue(String type) { /**
this.type = type; *
} * Create your own SettingValue object to make the management of plotworld
* configuration easier
*
*/
public static abstract class SettingValue {
private String type;
public String getType() { public SettingValue(String type) {
return this.type; this.type = type;
} }
public Object parseObject(Object object) { public String getType() {
return object; return this.type;
} }
public abstract Object parseString(String string); public Object parseObject(Object object) {
return object;
}
public abstract boolean validateValue(String string); public abstract Object parseString(String string);
}
public abstract boolean validateValue(String string);
}
} }

View File

@ -7,51 +7,64 @@ import org.apache.commons.lang.StringUtils;
import com.intellectualcrafters.plot.Configuration.SettingValue; import com.intellectualcrafters.plot.Configuration.SettingValue;
public class ConfigurationNode { public class ConfigurationNode {
private String constant; private String constant;
private Object default_value; private Object default_value;
private String description; private String description;
private Object value = 0; private Object value = 0;
private SettingValue type; private SettingValue type;
public ConfigurationNode(String constant, Object default_value, String description, SettingValue type, boolean required) { public ConfigurationNode(String constant, Object default_value,
this.constant = constant; String description, SettingValue type, boolean required) {
this.default_value = default_value; this.constant = constant;
this.description = description; this.default_value = default_value;
this.value = default_value; this.description = description;
this.type = type; this.value = default_value;
} this.type = type;
}
public String getType() { public String getType() {
return this.type.getType(); return this.type.getType();
} }
public boolean setValue(String string) { public boolean isValid(String string) {
if (!this.type.validateValue(string)) { try {
return false; Object result = this.type.parseString(string);
} if (result == null) {
this.value = this.type.parseString(string); return false;
return true; }
} return true;
} catch (Exception e) {
return false;
}
}
public Object getValue() { public boolean setValue(String string) {
if (this.value instanceof String[]) { if (!this.type.validateValue(string)) {
return Arrays.asList((String[]) this.value); return false;
} }
return this.value; this.value = this.type.parseString(string);
} return true;
}
public String getConstant() { public Object getValue() {
return this.constant; if (this.value instanceof String[]) {
} return Arrays.asList((String[]) this.value);
}
return this.value;
}
public Object getDefaultValue() { public String getConstant() {
if (this.default_value instanceof String[]) { return this.constant;
return StringUtils.join((String[]) this.default_value, ","); }
}
return this.default_value;
}
public String getDescription() { public Object getDefaultValue() {
return this.description; if (this.default_value instanceof String[]) {
} return StringUtils.join((String[]) this.default_value, ",");
}
return this.default_value;
}
public String getDescription() {
return this.description;
}
} }

View File

@ -7,95 +7,107 @@ import org.bukkit.ChatColor;
*/ */
public class ConsoleColors { public class ConsoleColors {
static enum ConsoleColor { static enum ConsoleColor {
RESET ("\u001B[0m"), RESET("\u001B[0m"), BLACK("\u001B[30m"), RED("\u001B[31m"), GREEN(
BLACK ("\u001B[30m"), "\u001B[32m"), YELLOW("\u001B[33m"), BLUE("\u001B[34m"), PURPLE(
RED ("\u001B[31m"), "\u001B[35m"), CYAN("\u001B[36m"), WHITE("\u001B[37m"), BOLD(
GREEN ("\u001B[32m"), "\033[1m"), UNDERLINE("\033[0m"), ITALIC("\033[3m");
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 win;
private String lin; private String lin;
ConsoleColor(String lin) { ConsoleColor(String lin) {
this.lin = lin; this.lin = lin;
this.win = win; this.win = this.win;
} }
public String getWin() { public String getWin() {
return win; return this.win;
} }
public String getLin(){ public String getLin() {
return lin; return this.lin;
} }
} }
/* public static final String ANSI_RESET = "\u001B[0m"; /*
public static final String ANSI_BLACK = "\u001B[30m"; * public static final String ANSI_RESET = "\u001B[0m"; public static final
public static final String ANSI_RED = "\u001B[31m"; * String ANSI_BLACK = "\u001B[30m"; public static final String ANSI_RED =
public static final String ANSI_GREEN = "\u001B[32m"; * "\u001B[31m"; public static final String ANSI_GREEN = "\u001B[32m";
public static final String ANSI_YELLOW = "\u001B[33m"; * public static final String ANSI_YELLOW = "\u001B[33m"; public static
public static final String ANSI_BLUE = "\u001B[34m"; * final String ANSI_BLUE = "\u001B[34m"; public static final String
public static final String ANSI_PURPLE = "\u001B[35m"; * ANSI_PURPLE = "\u001B[35m"; public static final String ANSI_CYAN =
public static final String ANSI_CYAN = "\u001B[36m"; * "\u001B[36m"; public static final String ANSI_WHITE = "\u001B[37m";
public static final String ANSI_WHITE = "\u001B[37m"; * public static final String ANSI_BOLD = "\033[1m"; public static final
public static final String ANSI_BOLD = "\033[1m"; * String ANSI_UNDERLINE = "\033[0m"; public static final String ANSI_ITALIC
public static final String ANSI_UNDERLINE = "\033[0m"; * = "\033[3m]";
public static final String ANSI_ITALIC = "\033[3m]";*/ */
public static String fromString(String input) { 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)) input = input.replaceAll("&0", fromChatColor(ChatColor.BLACK))
.replaceAll("&n", fromChatColor(ChatColor.UNDERLINE)).replaceAll("&o", fromChatColor(ChatColor.ITALIC)).replaceAll("&r", fromChatColor(ChatColor.RESET)); .replaceAll("&1", fromChatColor(ChatColor.DARK_BLUE))
return input + ConsoleColor.RESET.toString(); .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) { public static String fromChatColor(ChatColor color) {
return chatColor(color).getLin(); return chatColor(color).getLin();
} }
public static ConsoleColor chatColor(ChatColor color) { public static ConsoleColor chatColor(ChatColor color) {
switch (color) { switch (color) {
case RESET: case RESET:
return ConsoleColor.RESET; return ConsoleColor.RESET;
case GRAY: case GRAY:
case DARK_GRAY: case DARK_GRAY:
return ConsoleColor.WHITE; return ConsoleColor.WHITE;
case BLACK: case BLACK:
return ConsoleColor.BLACK; return ConsoleColor.BLACK;
case DARK_RED: case DARK_RED:
case RED: case RED:
return ConsoleColor.RED; return ConsoleColor.RED;
case GOLD: case GOLD:
case YELLOW: case YELLOW:
return ConsoleColor.YELLOW; return ConsoleColor.YELLOW;
case DARK_GREEN: case DARK_GREEN:
case GREEN: case GREEN:
return ConsoleColor.GREEN; return ConsoleColor.GREEN;
case AQUA: case AQUA:
case DARK_AQUA: case DARK_AQUA:
return ConsoleColor.CYAN; return ConsoleColor.CYAN;
case LIGHT_PURPLE: case LIGHT_PURPLE:
case DARK_PURPLE: case DARK_PURPLE:
return ConsoleColor.PURPLE; return ConsoleColor.PURPLE;
case BLUE: case BLUE:
case DARK_BLUE: case DARK_BLUE:
return ConsoleColor.BLUE; return ConsoleColor.BLUE;
case UNDERLINE: case UNDERLINE:
return ConsoleColor.UNDERLINE; return ConsoleColor.UNDERLINE;
case ITALIC: case ITALIC:
return ConsoleColor.ITALIC; return ConsoleColor.ITALIC;
case BOLD: case BOLD:
return ConsoleColor.BOLD; return ConsoleColor.BOLD;
default: default:
return ConsoleColor.RESET; return ConsoleColor.RESET;
} }
} }
} }

View File

@ -4,85 +4,86 @@ import org.apache.commons.lang.StringUtils;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
public class Flag { public class Flag {
private AbstractFlag key; private AbstractFlag key;
private String value; private String value;
/** /**
* Flag object used to store basic information for a Plot. Flags are a * 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 * key/value pair. For a flag to be usable by a player, you need to register
* it with PlotSquared. * it with PlotSquared.
* *
* @param key * @param key
* AbstractFlag * AbstractFlag
* @param value * @param value
* Value must be alphanumerical (can have spaces) and be <= 48 * Value must be alphanumerical (can have spaces) and be <= 48
* characters * characters
* @throws IllegalArgumentException * @throws IllegalArgumentException
* if you provide inadequate inputs * if you provide inadequate inputs
*/ */
public Flag(AbstractFlag key, String value) { public Flag(AbstractFlag key, String value) {
if (!StringUtils.isAlphanumericSpace(ChatColor.stripColor(value))) { if (!StringUtils.isAlphanumericSpace(ChatColor.stripColor(value))) {
throw new IllegalArgumentException("Flag must be alphanumerical"); throw new IllegalArgumentException("Flag must be alphanumerical");
} }
if (value.length() > 48) { if (value.length() > 48) {
throw new IllegalArgumentException("Value must be <= 48 characters"); throw new IllegalArgumentException("Value must be <= 48 characters");
} }
this.key = key; this.key = key;
this.value = value; this.value = value;
} }
/** /**
* Get the AbstractFlag used in creating the flag * Get the AbstractFlag used in creating the flag
* *
* @return AbstractFlag * @return AbstractFlag
*/ */
public AbstractFlag getAbstractFlag() { public AbstractFlag getAbstractFlag() {
return this.key; return this.key;
} }
/** /**
* Get the key for the AbstractFlag * Get the key for the AbstractFlag
* *
* @return String * @return String
*/ */
public String getKey() { public String getKey() {
return this.key.getKey(); return this.key.getKey();
} }
/** /**
* Get the value * Get the value
* *
* @return String * @return String
*/ */
public String getValue() { public String getValue() {
return this.value; return this.value;
} }
@Override @Override
public String toString() { public String toString() {
if (this.value.equals("")) { if (this.value.equals("")) {
return this.key.getKey(); return this.key.getKey();
} }
return this.key + ":" + this.value; return this.key + ":" + this.value;
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (this == obj) { if (this == obj) {
return true; return true;
} }
if (obj == null) { if (obj == null) {
return false; return false;
} }
if (getClass() != obj.getClass()) { if (getClass() != obj.getClass()) {
return false; return false;
} }
Flag other = (Flag) obj; Flag other = (Flag) obj;
return (this.key.getKey().equals(other.key.getKey()) && this.value.equals(other.value)); return (this.key.getKey().equals(other.key.getKey()) && this.value
} .equals(other.value));
}
@Override @Override
public int hashCode() { public int hashCode() {
return this.key.getKey().hashCode(); return this.key.getKey().hashCode();
} }
} }

View File

@ -6,91 +6,104 @@ import java.util.Set;
public class FlagManager { public class FlagManager {
// TODO add some flags // TODO add some flags
// - Plot clear interval // - Plot clear interval
// - Mob cap // - Mob cap
// - customized plot composition // - customized plot composition
// - greeting / leaving message // - greeting / leaving message
// OR in the flag command, allow users to set worldguard flags. // OR in the flag command, allow users to set worldguard flags.
private static ArrayList<AbstractFlag> flags = new ArrayList<AbstractFlag>(); private static ArrayList<AbstractFlag> flags = new ArrayList<AbstractFlag>();
/** /**
* Register an AbstractFlag with PlotSquared * Register an AbstractFlag with PlotSquared
* *
* @param flag * @param flag
* @return * @return
*/ */
public static boolean addFlag(AbstractFlag flag) { public static boolean addFlag(AbstractFlag flag) {
if (getFlag(flag.getKey()) != null) { if (getFlag(flag.getKey()) != null) {
return false; return false;
} }
return flags.add(flag); return flags.add(flag);
} }
/** /**
* Get a list of registered AbstractFlag objects * Get a list of registered AbstractFlag objects
* *
* @return List (AbstractFlag) * @return List (AbstractFlag)
*/ */
public static List<AbstractFlag> getFlags() { public static List<AbstractFlag> getFlags() {
return flags; return flags;
} }
/** /**
* Get an AbstractFlag by a string Returns null if flag does not exist * Get an AbstractFlag by a string Returns null if flag does not exist
* *
* @param string * @param string
* @return AbstractFlag * @return AbstractFlag
*/ */
public static AbstractFlag getFlag(String string) { public static AbstractFlag getFlag(String string) {
for (AbstractFlag flag : flags) { for (AbstractFlag flag : flags) {
if (flag.getKey().equalsIgnoreCase(string)) { if (flag.getKey().equalsIgnoreCase(string)) {
return flag; return flag;
} }
} }
return null; return null;
} }
/** /**
* Get an AbstractFlag by a string * Get an AbstractFlag by a string
* *
* @param string * @param string
* @param create * @param create
* If to create the flag if it does not exist * If to create the flag if it does not exist
* @return AbstractFlag * @return AbstractFlag
*/ */
public static AbstractFlag getFlag(String string, boolean create) { public static AbstractFlag getFlag(String string, boolean create) {
if ((getFlag(string) == null) && create) { if ((getFlag(string) == null) && create) {
AbstractFlag flag = new AbstractFlag(string); AbstractFlag flag = new AbstractFlag(string);
addFlag(flag); addFlag(flag);
return flag; return flag;
} }
return getFlag(string); return getFlag(string);
} }
/** /**
* Remove a registered AbstractFlag * Remove a registered AbstractFlag
* *
* @param flag * @param flag
* @return boolean Result of operation * @return boolean Result of operation
*/ */
public static boolean removeFlag(AbstractFlag flag) { public static boolean removeFlag(AbstractFlag flag) {
return flags.remove(flag); return flags.remove(flag);
} }
/** public static Flag[] parseFlags(List<String> flagstrings) {
* Get the flags for a plot Flag[] flags = new Flag[flagstrings.size()];
* for (int i = 0; i < flagstrings.size(); i++) {
* @param plot String[] split = flagstrings.get(i).split(";");
* @return List (AbstractFlag) if (split.length == 1) {
*/ flags[i] = new Flag(getFlag(split[0], true), "");
public static List<AbstractFlag> getPlotFlags(Plot plot) { } else {
Set<Flag> plotFlags = plot.settings.getFlags(); flags[i] = new Flag(getFlag(split[0], true), split[1]);
List<AbstractFlag> flags = new ArrayList<>(); }
for (Flag flag : plotFlags) { }
flags.add(flag.getAbstractFlag()); return flags;
} }
return flags;
} /**
* Get the flags for a plot
*
* @param plot
* @return List (AbstractFlag)
*/
public static List<AbstractFlag> getPlotFlags(Plot plot) {
Set<Flag> plotFlags = plot.settings.getFlags();
List<AbstractFlag> flags = new ArrayList<>();
for (Flag flag : plotFlags) {
flags.add(flag.getAbstractFlag());
}
return flags;
}
} }

View File

@ -19,111 +19,113 @@ import org.bukkit.Location;
*/ */
public class LSetCube { public class LSetCube {
/** /**
* Base locations * Base locations
*/ */
private Location l1, l2; private Location l1, l2;
/** /**
* Constructor * Constructor
* *
* @param l1 * @param l1
* @param l2 * @param l2
*/ */
public LSetCube(Location l1, Location l2) { public LSetCube(Location l1, Location l2) {
this.l1 = l1; this.l1 = l1;
this.l1 = l2; this.l1 = l2;
} }
/** /**
* Secondary constructor * Secondary constructor
* *
* @param l1 * @param l1
* @param size * @param size
*/ */
public LSetCube(Location l1, int size) { public LSetCube(Location l1, int size) {
this.l1 = l1; this.l1 = l1;
this.l2 = l1.clone().add(size, size, size); this.l2 = l1.clone().add(size, size, size);
} }
/** /**
* Returns the absolute min. of the cube * Returns the absolute min. of the cube
* *
* @return abs. min * @return abs. min
*/ */
public Location minLoc() { public Location minLoc() {
int x = Math.min(this.l1.getBlockX(), this.l2.getBlockX()); int x = Math.min(this.l1.getBlockX(), this.l2.getBlockX());
int y = Math.min(this.l1.getBlockY(), this.l2.getBlockY()); int y = Math.min(this.l1.getBlockY(), this.l2.getBlockY());
int z = Math.min(this.l1.getBlockZ(), this.l2.getBlockZ()); int z = Math.min(this.l1.getBlockZ(), this.l2.getBlockZ());
return new Location(this.l1.getWorld(), x, y, z); return new Location(this.l1.getWorld(), x, y, z);
} }
/** /**
* Returns the absolute max. of the cube * Returns the absolute max. of the cube
* *
* @return abs. max * @return abs. max
*/ */
public Location maxLoc() { public Location maxLoc() {
int x = Math.max(this.l1.getBlockX(), this.l2.getBlockX()); int x = Math.max(this.l1.getBlockX(), this.l2.getBlockX());
int y = Math.max(this.l1.getBlockY(), this.l2.getBlockY()); int y = Math.max(this.l1.getBlockY(), this.l2.getBlockY());
int z = Math.max(this.l1.getBlockZ(), this.l2.getBlockZ()); int z = Math.max(this.l1.getBlockZ(), this.l2.getBlockZ());
return new Location(this.l1.getWorld(), x, y, z); return new Location(this.l1.getWorld(), x, y, z);
} }
/** /**
* Creates a LCycler for the cube. * Creates a LCycler for the cube.
* *
* @return new lcycler * @return new lcycler
*/ */
public LCycler getCycler() { public LCycler getCycler() {
return new LCycler(this); return new LCycler(this);
} }
/** /**
* @author Citymonstret * @author Citymonstret
*/ */
protected class LCycler { protected class LCycler {
/** /**
* *
*/ */
private Location min; private Location min;
/** /**
* *
*/ */
private Location max; private Location max;
/** /**
* *
*/ */
private Location current; private Location current;
/** /**
* *
* @param cube * @param cube
*/ */
public LCycler(LSetCube cube) { public LCycler(LSetCube cube) {
this.min = cube.minLoc(); this.min = cube.minLoc();
this.max = cube.maxLoc(); this.max = cube.maxLoc();
this.current = this.min; this.current = this.min;
} }
/** /**
* *
* @return * @return
*/ */
public boolean hasNext() { 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 ((this.current.getBlockX() + 1) <= this.max.getBlockX())
} && ((this.current.getBlockY() + 1) <= this.max.getBlockY())
&& ((this.current.getBlockZ() + 1) <= this.max.getBlockZ());
}
/** /**
* *
* @return * @return
*/ */
public Location getNext() { public Location getNext() {
if (!hasNext()) { if (!hasNext()) {
return null; return null;
} }
this.current = this.current.add(1, 1, 1); this.current = this.current.add(1, 1, 1);
return this.current; return this.current;
} }
} }
} }

View File

@ -17,79 +17,80 @@ package com.intellectualcrafters.plot;
*/ */
public class Lag implements Runnable { public class Lag implements Runnable {
/** /**
* Tick count * Tick count
*/ */
public static int TC = 0; public static int TC = 0;
/** /**
* Ticks * Ticks
*/ */
public static long[] T = new long[600]; public static long[] T = new long[600];
/** /**
* something :_: * something :_:
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
public static long LT = 0L; public static long LT = 0L;
/** /**
* Get the server TPS * Get the server TPS
* *
* @return server tick per second * @return server tick per second
*/ */
public static double getTPS() { public static double getTPS() {
return Math.round(getTPS(100)) > 20.0D ? 20.0D : Math.round(getTPS(100)); return Math.round(getTPS(100)) > 20.0D ? 20.0D : Math
} .round(getTPS(100));
}
/** /**
* Return the tick per second (measured in $ticks) * Return the tick per second (measured in $ticks)
* *
* @param ticks * @param ticks
* Ticks * Ticks
* @return ticks per second * @return ticks per second
*/ */
public static double getTPS(int ticks) { public static double getTPS(int ticks) {
if (TC < ticks) { if (TC < ticks) {
return 20.0D; return 20.0D;
} }
int t = (TC - 1 - ticks) % T.length; int t = (TC - 1 - ticks) % T.length;
long e = System.currentTimeMillis() - T[t]; long e = System.currentTimeMillis() - T[t];
return ticks / (e / 1000.0D); return ticks / (e / 1000.0D);
} }
/** /**
* Get number of ticks since * Get number of ticks since
* *
* @param tI * @param tI
* Ticks < * Ticks <
* @return number of ticks since $tI * @return number of ticks since $tI
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
public static long getElapsed(int tI) { public static long getElapsed(int tI) {
long t = T[tI % T.length]; long t = T[tI % T.length];
return System.currentTimeMillis() - t; return System.currentTimeMillis() - t;
} }
@Override @Override
public void run() { public void run() {
T[TC % T.length] = System.currentTimeMillis(); T[TC % T.length] = System.currentTimeMillis();
TC++; TC++;
} }
/** /**
* Get lag percentage * Get lag percentage
* *
* @return lag percentage * @return lag percentage
*/ */
public static double getPercentage() { public static double getPercentage() {
return Math.round((1.0D - (Lag.getTPS() / 20.0D)) * 100.0D); return Math.round((1.0D - (Lag.getTPS() / 20.0D)) * 100.0D);
} }
/** /**
* Get TPS percentage (of 20) * Get TPS percentage (of 20)
* *
* @return TPS percentage * @return TPS percentage
*/ */
public static double getFullPercentage() { public static double getFullPercentage() {
return getTPS() * 5.0D; return getTPS() * 5.0D;
} }
} }

View File

@ -25,51 +25,52 @@ import java.util.Date;
*/ */
public class Logger { public class Logger {
private static ArrayList<String> entries; private static ArrayList<String> entries;
private static File log; private static File log;
public static void setup(File file) { public static void setup(File file) {
log = file; log = file;
entries = new ArrayList<>(); entries = new ArrayList<>();
try { try {
BufferedReader reader = new BufferedReader(new FileReader(file)); BufferedReader reader = new BufferedReader(new FileReader(file));
String line; String line;
while ((line = reader.readLine()) != null) { while ((line = reader.readLine()) != null) {
entries.add(line); entries.add(line);
} }
reader.close(); reader.close();
} catch (IOException e) { } catch (IOException e) {
PlotMain.sendConsoleSenderMessage(C.PREFIX.s() + "File setup error Logger#setup"); PlotMain.sendConsoleSenderMessage(C.PREFIX.s()
} + "File setup error Logger#setup");
} }
}
public enum LogLevel { public enum LogLevel {
GENERAL("General"), WARNING("Warning"), DANGER("Danger"); GENERAL("General"), WARNING("Warning"), DANGER("Danger");
private String name; private String name;
LogLevel(String name) { LogLevel(String name) {
this.name = name; this.name = name;
} }
@Override @Override
public String toString() { public String toString() {
return this.name; return this.name;
} }
} }
public static void write() throws IOException { public static void write() throws IOException {
FileWriter writer = new FileWriter(log); FileWriter writer = new FileWriter(log);
for (String string : entries) { for (String string : entries) {
writer.write(string + System.lineSeparator()); writer.write(string + System.lineSeparator());
} }
writer.close(); writer.close();
} }
public static void add(LogLevel level, String string) { public static void add(LogLevel level, String string) {
append("[" + level.toString() + "] " + string); append("[" + level.toString() + "] " + string);
} }
private static void append(String string) { private static void append(String string) {
entries.add("[" + new Date().toString() + "]" + string); entries.add("[" + new Date().toString() + "]" + string);
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -19,86 +19,98 @@ import com.sk89q.worldedit.regions.CuboidRegion;
*/ */
public class PWE { public class PWE {
public static void setMask(Player p, Location l) { public static void setMask(Player p, Location l) {
try { try {
LocalSession s; LocalSession s;
if (PlotMain.worldEdit == null) { if (PlotMain.worldEdit == null) {
s = WorldEdit.getInstance().getSession(p.getName()); s = WorldEdit.getInstance().getSession(p.getName());
} else { } else {
s = PlotMain.worldEdit.getSession(p); s = PlotMain.worldEdit.getSession(p);
} }
PlotId id = PlayerFunctions.getPlot(l); PlotId id = PlayerFunctions.getPlot(l);
if (id != null) { if (id != null) {
Plot plot = PlotMain.getPlots(l.getWorld()).get(id); Plot plot = PlotMain.getPlots(l.getWorld()).get(id);
if (plot != null) { if (plot != null) {
boolean r; boolean r;
r = (plot.getOwner() != null) && plot.getOwner().equals(p.getUniqueId()) || plot.helpers.contains(DBFunc.everyone) || plot.helpers.contains(p.getUniqueId()); r = (plot.getOwner() != null)
if (!r) { && plot.getOwner().equals(p.getUniqueId())
if (p.hasPermission("plots.worldedit.bypass")) { || plot.helpers.contains(DBFunc.everyone)
removeMask(p, s); || plot.helpers.contains(p.getUniqueId());
return; if (!r) {
} if (p.hasPermission("plots.worldedit.bypass")) {
} else { removeMask(p, s);
return;
}
} else {
World w = p.getWorld(); World w = p.getWorld();
Location bloc = PlotHelper.getPlotBottomLoc(w, plot.id); Location bloc = PlotHelper.getPlotBottomLoc(w, plot.id);
Location tloc = PlotHelper.getPlotTopLoc(w, plot.id); Location tloc = PlotHelper.getPlotTopLoc(w, plot.id);
Vector bvec = new Vector(bloc.getBlockX() + 1, bloc.getBlockY() + 1, bloc.getBlockZ() + 1); Vector bvec = new Vector(bloc.getBlockX() + 1,
Vector tvec = new Vector(tloc.getBlockX(), tloc.getBlockY(), tloc.getBlockZ()); 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); CuboidRegion region = new CuboidRegion(lw, bvec, tvec);
com.sk89q.worldedit.masks.RegionMask mask = new com.sk89q.worldedit.masks.RegionMask(region); com.sk89q.worldedit.masks.RegionMask mask = new com.sk89q.worldedit.masks.RegionMask(
region);
s.setMask(mask); s.setMask(mask);
return; return;
} }
} }
} }
if (noMask(s)) { if (noMask(s)) {
BukkitPlayer plr = PlotMain.worldEdit.wrapPlayer(p); BukkitPlayer plr = PlotMain.worldEdit.wrapPlayer(p);
Vector p1 = new Vector(69, 69, 69), p2 = new Vector(69, 69, 69); 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))); 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?"); } catch (Exception e) {
} // throw new
} // PlotSquaredException(PlotSquaredException.PlotError.MISSING_DEPENDENCY,
// "WorldEdit == Null?");
}
}
public static boolean noMask(LocalSession s) { public static boolean noMask(LocalSession s) {
try { try {
com.sk89q.worldedit.masks.Mask mask = s.getMask(); com.sk89q.worldedit.masks.Mask mask = s.getMask();
return mask == null; return mask == null;
} catch (Throwable e) { } catch (Throwable e) {
return true; return true;
} }
} }
public static void removeMask(Player p, LocalSession s) { public static void removeMask(Player p, LocalSession s) {
try { try {
s.setMask(null); s.setMask(null);
} catch (Throwable e) { } catch (Throwable e) {
com.sk89q.worldedit.masks.Mask mask = null; com.sk89q.worldedit.masks.Mask mask = null;
s.setMask(mask); s.setMask(mask);
} }
} }
public static void removeMask(Player p) { public static void removeMask(Player p) {
try { try {
LocalSession s; LocalSession s;
if (PlotMain.worldEdit == null) { if (PlotMain.worldEdit == null) {
s = WorldEdit.getInstance().getSession(p.getName()); s = WorldEdit.getInstance().getSession(p.getName());
} else { } else {
s = PlotMain.worldEdit.getSession(p); s = PlotMain.worldEdit.getSession(p);
} }
removeMask(p, s); removeMask(p, s);
} catch (Exception e) { } catch (Exception e) {
// throw new PlotSquaredException(PlotSquaredException.PlotError.MISSING_DEPENDENCY, "WorldEdit == Null?"); // throw new
} // PlotSquaredException(PlotSquaredException.PlotError.MISSING_DEPENDENCY,
} // "WorldEdit == Null?");
}
}
} }

View File

@ -33,231 +33,247 @@ import org.bukkit.entity.Player;
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
public class PlayerFunctions { public class PlayerFunctions {
/** /**
* *
* @param player * @param player
* player * player
* @return * @return
*/ */
public static boolean isInPlot(Player player) { public static boolean isInPlot(Player player) {
return getCurrentPlot(player) != null; return getCurrentPlot(player) != null;
} }
/** /**
* *
* @param plot * @param plot
* plot * plot
* @return * @return
*/ */
public static boolean hasExpired(Plot plot) { public static boolean hasExpired(Plot plot) {
OfflinePlayer player = Bukkit.getOfflinePlayer(plot.owner); OfflinePlayer player = Bukkit.getOfflinePlayer(plot.owner);
long lp = player.getLastPlayed(); long lp = player.getLastPlayed();
long cu = System.currentTimeMillis(); long cu = System.currentTimeMillis();
return (lp - cu) > 30l; return (lp - cu) > 30l;
} }
public static ArrayList<PlotId> getPlotSelectionIds(World world, PlotId pos1, PlotId pos2) { public static ArrayList<PlotId> getPlotSelectionIds(World world,
ArrayList<PlotId> myplots = new ArrayList<PlotId>(); PlotId pos1, PlotId pos2) {
for (int x = pos1.x; x <= pos2.x; x++) { ArrayList<PlotId> myplots = new ArrayList<PlotId>();
for (int y = pos1.y; y <= pos2.y; y++) { for (int x = pos1.x; x <= pos2.x; x++) {
myplots.add(new PlotId(x, y)); 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) { public static Plot getBottomPlot(World world, Plot plot) {
if (plot.settings.getMerged(0)) { if (plot.settings.getMerged(0)) {
return getBottomPlot(world, PlotMain.getPlots(world).get(new PlotId(plot.id.x, plot.id.y - 1))); return getBottomPlot(
} world,
if (plot.settings.getMerged(3)) { PlotMain.getPlots(world).get(
return getBottomPlot(world, PlotMain.getPlots(world).get(new PlotId(plot.id.x - 1, plot.id.y))); new PlotId(plot.id.x, plot.id.y - 1)));
} }
return plot; 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) { public static Plot getTopPlot(World world, Plot plot) {
if (plot.settings.getMerged(2)) { if (plot.settings.getMerged(2)) {
return getTopPlot(world, PlotMain.getPlots(world).get(new PlotId(plot.id.x, plot.id.y + 1))); return getTopPlot(
} world,
if (plot.settings.getMerged(1)) { PlotMain.getPlots(world).get(
return getTopPlot(world, PlotMain.getPlots(world).get(new PlotId(plot.id.x + 1, plot.id.y))); new PlotId(plot.id.x, plot.id.y + 1)));
} }
return plot; 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 * @param loc
* @return * @return
*/ */
public static PlotId getPlotAbs(Location loc) { public static PlotId getPlotAbs(Location loc) {
String world = loc.getWorld().getName(); String world = loc.getWorld().getName();
PlotManager manager = PlotMain.getPlotManager(world); PlotManager manager = PlotMain.getPlotManager(world);
if (manager == null) { if (manager == null) {
return null; return null;
} }
PlotWorld plotworld = PlotMain.getWorldSettings(world); PlotWorld plotworld = PlotMain.getWorldSettings(world);
return manager.getPlotIdAbs(plotworld, loc); return manager.getPlotIdAbs(plotworld, loc);
} }
public static PlotId getPlot(Location loc) { public static PlotId getPlot(Location loc) {
String world = loc.getWorld().getName(); String world = loc.getWorld().getName();
PlotManager manager = PlotMain.getPlotManager(world); PlotManager manager = PlotMain.getPlotManager(world);
if (manager == null) { if (manager == null) {
return null; return null;
} }
PlotWorld plotworld = PlotMain.getWorldSettings(world); PlotWorld plotworld = PlotMain.getWorldSettings(world);
return manager.getPlotId(plotworld, loc); return manager.getPlotId(plotworld, loc);
} }
/** /**
* *
* @param player * @param player
* @param plot * @param plot
*/ */
public static void togglePlotWeather(Player player, Plot plot) { public static void togglePlotWeather(Player player, Plot plot) {
player.setPlayerWeather(plot.settings.getRain() ? WeatherType.DOWNFALL : WeatherType.CLEAR); player.setPlayerWeather(plot.settings.getRain() ? WeatherType.DOWNFALL
} : WeatherType.CLEAR);
}
/** /**
* *
* @param player * @param player
* @param plot * @param plot
*/ */
public static void togglePlotTime(Player player, Plot plot) { public static void togglePlotTime(Player player, Plot plot) {
player.setPlayerTime(plot.settings.getTime(), false); player.setPlayerTime(plot.settings.getTime(), false);
} }
/** /**
* *
* @param player * @param player
* @return * @return
*/ */
public static Plot getCurrentPlot(Player player) { public static Plot getCurrentPlot(Player player) {
if (!PlotMain.isPlotWorld(player.getWorld())) { if (!PlotMain.isPlotWorld(player.getWorld())) {
return null; return null;
} }
PlotId id = getPlot(player.getLocation()); PlotId id = getPlot(player.getLocation());
World world = player.getWorld(); World world = player.getWorld();
if (id == null) { if (id == null) {
return null; return null;
} }
HashMap<PlotId, Plot> plots = PlotMain.getPlots(world); HashMap<PlotId, Plot> plots = PlotMain.getPlots(world);
if (plots != null) { if (plots != null) {
if (plots.containsKey(id)) { if (plots.containsKey(id)) {
return plots.get(id); return plots.get(id);
} }
} }
return new Plot(id, null, Biome.FOREST, new ArrayList<UUID>(), new ArrayList<UUID>(), world.getName()); return new Plot(id, null, Biome.FOREST, new ArrayList<UUID>(),
new ArrayList<UUID>(), world.getName());
} }
/** /**
* @deprecated * @deprecated
* @param id * @param id
* @param plot * @param plot
*/ */
@Deprecated @Deprecated
public static void set(Integer[] id, Plot plot) { public static void set(Integer[] id, Plot plot) {
PlotMain.updatePlot(plot); PlotMain.updatePlot(plot);
} }
/** /**
* *
* @param plr * @param plr
* @return * @return
*/ */
// public static Set<Plot> getPlayerPlots(Player plr) { // public static Set<Plot> getPlayerPlots(Player plr) {
// return PlotMain.getPlots(plr); // return PlotMain.getPlots(plr);
// } // }
// //
public static Set<Plot> getPlayerPlots(World world, Player plr) { public static Set<Plot> getPlayerPlots(World world, Player plr) {
Set<Plot> p = PlotMain.getPlots(world, plr); Set<Plot> p = PlotMain.getPlots(world, plr);
if (p == null) { if (p == null) {
return new HashSet<Plot>(); return new HashSet<Plot>();
} }
return p; return p;
} }
/** /**
* *
* @param plr * @param plr
* @return * @return
*/ */
// public static int getPlayerPlotCount(Player plr) { // public static int getPlayerPlotCount(Player plr) {
// return getPlayerPlots(plr).size(); // return getPlayerPlots(plr).size();
// } // }
// //
public static int getPlayerPlotCount(World world, Player plr) { public static int getPlayerPlotCount(World world, Player plr) {
return getPlayerPlots(world, plr).size(); return getPlayerPlots(world, plr).size();
} }
/** /**
* *
* @param p * @param p
* @return * @return
*/ */
@SuppressWarnings("SuspiciousNameCombination") @SuppressWarnings("SuspiciousNameCombination")
public static int getAllowedPlots(Player p) { public static int getAllowedPlots(Player p) {
return PlotMain.hasPermissionRange(p, "plots.plot", Settings.MAX_PLOTS); return PlotMain.hasPermissionRange(p, "plots.plot", Settings.MAX_PLOTS);
} }
/** /**
* *
* @return PlotMain.getPlots(); * @return PlotMain.getPlots();
* @deprecated * @deprecated
*/ */
@Deprecated @Deprecated
public static Set<Plot> getPlots() { public static Set<Plot> getPlots() {
return PlotMain.getPlots(); return PlotMain.getPlots();
} }
/** /**
* \\previous\\ * \\previous\\
* *
* @param plr * @param plr
* @param msg * @param msg
* Was used to wrap the chat client length (Packets out--) * Was used to wrap the chat client length (Packets out--)
*/ */
public static void sendMessageWrapped(Player plr, String msg) { public static void sendMessageWrapped(Player plr, String msg) {
plr.sendMessage(msg); plr.sendMessage(msg);
} }
/** /**
* Send a message to the player * Send a message to the player
* *
* @param plr * @param plr
* Player to recieve message * Player to recieve message
* @param msg * @param msg
* Message to send * Message to send
*/ */
public static void sendMessage(Player plr, String msg) { public static void sendMessage(Player plr, String msg) {
if ((msg.length() == 0) || msg.equalsIgnoreCase("")) { if ((msg.length() == 0) || msg.equalsIgnoreCase("")) {
return; return;
} }
sendMessageWrapped(plr, ChatColor.translateAlternateColorCodes('&', C.PREFIX.s() + msg)); sendMessageWrapped(plr,
} ChatColor.translateAlternateColorCodes('&', C.PREFIX.s() + msg));
}
/** /**
* Send a message to the player * Send a message to the player
* *
* @param plr * @param plr
* Player to recieve message * Player to recieve message
* @param c * @param c
* Caption to send * Caption to send
*/ */
public static void sendMessage(Player plr, C c, String... args) { public static void sendMessage(Player plr, C c, String... args) {
if (c.s().length() < 1) { if (c.s().length() < 1) {
return; return;
} }
String msg = c.s(); String msg = c.s();
if ((args != null) && (args.length > 0)) { if ((args != null) && (args.length > 0)) {
for (String str : args) { for (String str : args) {
msg = msg.replaceFirst("%s", str); msg = msg.replaceFirst("%s", str);
} }
} }
sendMessage(plr, msg); sendMessage(plr, msg);
} }
} }

View File

@ -28,261 +28,279 @@ import com.intellectualcrafters.plot.database.DBFunc;
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
public class Plot implements Cloneable { public class Plot implements Cloneable {
/** /**
* plot ID * plot ID
*/ */
public PlotId id; public PlotId id;
/** /**
* plot world * plot world
*/ */
public String world; public String world;
/** /**
* plot owner * plot owner
*/ */
public UUID owner; public UUID owner;
/** /**
* Deny Entry * Deny Entry
*/ */
public boolean deny_entry; public boolean deny_entry;
/** /**
* List of helpers (with plot permissions) * List of helpers (with plot permissions)
*/ */
public ArrayList<UUID> helpers; public ArrayList<UUID> helpers;
/** /**
* List of trusted users (with plot permissions) * List of trusted users (with plot permissions)
*/ */
public ArrayList<UUID> trusted; public ArrayList<UUID> trusted;
/** /**
* List of denied players * List of denied players
*/ */
public ArrayList<UUID> denied; public ArrayList<UUID> denied;
/** /**
* External settings class * External settings class
*/ */
public PlotSettings settings; public PlotSettings settings;
/** /**
* Delete on next save cycle? * Delete on next save cycle?
*/ */
public boolean delete; public boolean delete;
/** /**
* Has the plot changed since the last save cycle? * Has the plot changed since the last save cycle?
*/ */
public boolean hasChanged = false; public boolean hasChanged = false;
/** /**
* Primary constructor * Primary constructor
* *
* @param id * @param id
* @param owner * @param owner
* @param plotBiome * @param plotBiome
* @param helpers * @param helpers
* @param denied * @param denied
*/ */
public Plot(PlotId id, UUID owner, Biome plotBiome, ArrayList<UUID> helpers, ArrayList<UUID> denied, String world) { public Plot(PlotId id, UUID owner, Biome plotBiome,
this.id = id; ArrayList<UUID> helpers, ArrayList<UUID> denied, String world) {
this.settings = new PlotSettings(this); this.id = id;
this.settings.setBiome(plotBiome); this.settings = new PlotSettings(this);
this.owner = owner; this.settings.setBiome(plotBiome);
this.deny_entry = this.owner == null; this.owner = owner;
this.helpers = helpers; this.deny_entry = this.owner == null;
this.denied = denied; this.helpers = helpers;
this.trusted = new ArrayList<UUID>(); this.denied = denied;
this.settings.setTime(8000l); this.trusted = new ArrayList<UUID>();
this.settings.setRain(false); this.settings.setTime(8000l);
this.settings.setTimeChange(false); this.settings.setRain(false);
this.settings.setAlias(""); this.settings.setTimeChange(false);
this.settings.setPosition(PlotHomePosition.DEFAULT); this.settings.setAlias("");
this.delete = false; this.settings.setPosition(PlotHomePosition.DEFAULT);
this.settings.setFlags(new Flag[0]); this.delete = false;
this.world = world; this.settings.setFlags(new Flag[0]);
} this.world = world;
}
/** /**
* Constructor for saved plots * Constructor for saved plots
* *
* @param id * @param id
* @param owner * @param owner
* @param plotBiome * @param plotBiome
* @param helpers * @param helpers
* @param denied * @param denied
* @param changeTime * @param changeTime
* @param time * @param time
* @param merged * @param merged
*/ */
public Plot(PlotId id, UUID owner, Biome plotBiome, ArrayList<UUID> helpers, ArrayList<UUID> trusted, ArrayList<UUID> denied, boolean changeTime, long time, boolean rain, String alias, PlotHomePosition position, Flag[] flags, String world, boolean[] merged) { public Plot(PlotId id, UUID owner, Biome plotBiome,
this.id = id; ArrayList<UUID> helpers, ArrayList<UUID> trusted,
this.settings = new PlotSettings(this); ArrayList<UUID> denied, boolean changeTime, long time,
this.settings.setBiome(plotBiome); boolean rain, String alias, PlotHomePosition position,
this.owner = owner; Flag[] flags, String world, boolean[] merged) {
this.deny_entry = this.owner != null; this.id = id;
this.trusted = trusted; this.settings = new PlotSettings(this);
this.helpers = helpers; this.settings.setBiome(plotBiome);
this.denied = denied; this.owner = owner;
this.settings.setTime(time); this.deny_entry = this.owner != null;
this.settings.setRain(rain); this.trusted = trusted;
this.settings.setTimeChange(changeTime); this.helpers = helpers;
this.settings.setAlias(alias); this.denied = denied;
this.settings.setPosition(position); this.settings.setTime(time);
this.settings.setMerged(merged); this.settings.setRain(rain);
this.delete = false; this.settings.setTimeChange(changeTime);
if (flags != null) { this.settings.setAlias(alias);
this.settings.setFlags(flags); this.settings.setPosition(position);
} else { this.settings.setMerged(merged);
this.settings.setFlags(new Flag[0]); this.delete = false;
} if (flags != null) {
this.world = world; this.settings.setFlags(flags);
} } else {
this.settings.setFlags(new Flag[0]);
}
this.world = world;
}
/** /**
* Check if the plot has a set owner * Check if the plot has a set owner
* *
* @return false if there is no owner * @return false if there is no owner
*/ */
public boolean hasOwner() { public boolean hasOwner() {
return this.owner != null; return this.owner != null;
} }
/** /**
* Set the owner * Set the owner
* *
* @param player * @param player
*/ */
public void setOwner(Player player) { public void setOwner(Player player) {
this.owner = player.getUniqueId(); this.owner = player.getUniqueId();
} }
/** /**
* Check if the player is either the owner or on the helpers list * Check if the player is either the owner or on the helpers list
* *
* @param player * @param player
* @return true if the player is added as a helper or is the owner * @return true if the player is added as a helper or is the owner
*/ */
public boolean hasRights(Player player) { 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))); 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? * Should the player be allowed to enter?
* *
* @param player * @param player
* @return false if the player is allowed to enter * @return false if the player is allowed to enter
*/ */
public boolean deny_entry(Player player) { 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()))); 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 * Get the UUID of the owner
* *
*/ */
public UUID getOwner() { public UUID getOwner() {
return this.owner; return this.owner;
} }
/** /**
* Get the plot ID * Get the plot ID
* *
*/ */
public PlotId getId() { public PlotId getId() {
return this.id; return this.id;
} }
/** /**
* Get the plot World * Get the plot World
* *
*/ */
public World getWorld() { public World getWorld() {
return Bukkit.getWorld(this.world); return Bukkit.getWorld(this.world);
} }
/** /**
* Get a clone of the plot * Get a clone of the plot
* *
* @return * @return
*/ */
@Override @Override
public Object clone() throws CloneNotSupportedException { public Object clone() throws CloneNotSupportedException {
try { try {
return super.clone(); return super.clone();
} catch (CloneNotSupportedException e) { } catch (CloneNotSupportedException e) {
return null; return null;
} }
} }
/** /**
* Deny someone (use DBFunc.addDenied() as well) * Deny someone (use DBFunc.addDenied() as well)
* *
* @param uuid * @param uuid
*/ */
public void addDenied(UUID uuid) { public void addDenied(UUID uuid) {
this.denied.add(uuid); this.denied.add(uuid);
} }
/** /**
* Add someone as a helper (use DBFunc as well) * Add someone as a helper (use DBFunc as well)
* *
* @param uuid * @param uuid
*/ */
public void addHelper(UUID uuid) { public void addHelper(UUID uuid) {
this.helpers.add(uuid); this.helpers.add(uuid);
} }
/** /**
* Add someone as a trusted user (use DBFunc as well) * Add someone as a trusted user (use DBFunc as well)
* *
* @param uuid * @param uuid
*/ */
public void addTrusted(UUID uuid) { public void addTrusted(UUID uuid) {
this.trusted.add(uuid); this.trusted.add(uuid);
} }
/** /**
* Get plot display name * Get plot display name
* *
* @return alias if set, else id * @return alias if set, else id
*/ */
public String getDisplayName() { public String getDisplayName() {
if (this.settings.getAlias().length() > 1) { if (this.settings.getAlias().length() > 1) {
return this.settings.getAlias(); return this.settings.getAlias();
} }
return this.getId().x + ";" + this.getId().y; return this.getId().x + ";" + this.getId().y;
} }
/** /**
* Remove a denied player (use DBFunc as well) * Remove a denied player (use DBFunc as well)
* *
* @param uuid * @param uuid
*/ */
public void removeDenied(UUID uuid) { public void removeDenied(UUID uuid) {
this.denied.remove(uuid); this.denied.remove(uuid);
} }
/** /**
* Remove a helper (use DBFunc as well) * Remove a helper (use DBFunc as well)
* *
* @param uuid * @param uuid
*/ */
public void removeHelper(UUID uuid) { public void removeHelper(UUID uuid) {
this.helpers.remove(uuid); this.helpers.remove(uuid);
} }
/** /**
* Remove a trusted user (use DBFunc as well) * Remove a trusted user (use DBFunc as well)
* *
* @param uuid * @param uuid
*/ */
public void removeTrusted(UUID uuid) { public void removeTrusted(UUID uuid) {
this.trusted.remove(uuid); this.trusted.remove(uuid);
} }
/** /**
* Clear a plot * Clear a plot
* *
* @param plr * @param plr
* initiator * initiator
*/ */
public void clear(Player plr) { public void clear(Player plr) {
PlotHelper.clear(plr, this); PlotHelper.clear(plr, this);
} }
} }

View File

@ -1,10 +1,11 @@
package com.intellectualcrafters.plot; package com.intellectualcrafters.plot;
public class PlotBlock { public class PlotBlock {
public short id; public short id;
public byte data; public byte data;
public PlotBlock(short id, byte data) {
this.id = id; public PlotBlock(short id, byte data) {
this.data = data; this.id = id;
} this.data = data;
}
} }

View File

@ -4,7 +4,7 @@ import org.bukkit.generator.ChunkGenerator;
public abstract class PlotGenerator extends ChunkGenerator { public abstract class PlotGenerator extends ChunkGenerator {
public abstract PlotWorld getPlotWorld(); public abstract PlotWorld getPlotWorld();
public abstract PlotManager getPlotManager(); public abstract PlotManager getPlotManager();
} }

File diff suppressed because it is too large Load Diff

View File

@ -13,24 +13,24 @@ package com.intellectualcrafters.plot;
* Created by Citymonstret on 2014-08-05. * Created by Citymonstret on 2014-08-05.
*/ */
public enum PlotHomePosition { public enum PlotHomePosition {
CENTER("Center", 'c'), DEFAULT("Default", 'd'); CENTER("Center", 'c'), DEFAULT("Default", 'd');
private String string; private String string;
private char ch; private char ch;
PlotHomePosition(String string, char ch) { PlotHomePosition(String string, char ch) {
this.string = string; this.string = string;
this.ch = ch; this.ch = ch;
} }
public boolean isMatching(String string) { public boolean isMatching(String string) {
if ((string.length() < 2) && (string.charAt(0) == this.ch)) { if ((string.length() < 2) && (string.charAt(0) == this.ch)) {
return true; return true;
} }
if (string.equalsIgnoreCase(this.string)) { if (string.equalsIgnoreCase(this.string)) {
return true; return true;
} }
return false; return false;
} }
} }

View File

@ -1,54 +1,54 @@
package com.intellectualcrafters.plot; package com.intellectualcrafters.plot;
public class PlotId { public class PlotId {
/** /**
* x value * x value
*/ */
public Integer x; public Integer x;
/** /**
* y value * y value
*/ */
public Integer y; public Integer y;
/** /**
* PlotId class (PlotId x,y values do not correspond to Block locations) * PlotId class (PlotId x,y values do not correspond to Block locations)
* *
* @param x * @param x
* The plot x coordinate * The plot x coordinate
* @param y * @param y
* The plot y coordinate * The plot y coordinate
*/ */
public PlotId(int x, int y) { public PlotId(int x, int y) {
this.x = x; this.x = x;
this.y = y; this.y = y;
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (this == obj) { if (this == obj) {
return true; return true;
} }
if (obj == null) { if (obj == null) {
return false; return false;
} }
if (getClass() != obj.getClass()) { if (getClass() != obj.getClass()) {
return false; return false;
} }
PlotId other = (PlotId) obj; PlotId other = (PlotId) obj;
return ((this.x == other.x) && (this.y == other.y)); return ((this.x == other.x) && (this.y == other.y));
} }
@Override @Override
public String toString() { public String toString() {
return this.x + ";" + this.y; return this.x + ";" + this.y;
} }
@Override @Override
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = (prime * result) + this.x; result = (prime * result) + this.x;
result = (prime * result) + this.y; result = (prime * result) + this.y;
return result; return result;
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -5,63 +5,68 @@ import java.util.ArrayList;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.block.Biome; import org.bukkit.block.Biome;
import org.bukkit.block.Block;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
public abstract class PlotManager { public abstract class PlotManager {
/* /*
* Plot locations (methods with Abs in them will not need to consider mega * Plot locations (methods with Abs in them will not need to consider mega
* plots) * plots)
*/ */
public abstract PlotId getPlotIdAbs(PlotWorld plotworld, Location loc); public abstract PlotId getPlotIdAbs(PlotWorld plotworld, Location loc);
public abstract PlotId getPlotId(PlotWorld plotworld, Location loc); public abstract PlotId getPlotId(PlotWorld plotworld, Location loc);
public abstract boolean isInPlotAbs(PlotWorld plotworld, Location loc, PlotId plotid); public abstract boolean isInPlotAbs(PlotWorld plotworld, Location loc,
// If you have a circular plot, just return the corner if it were a square PlotId plotid);
public abstract Location getPlotBottomLocAbs(PlotWorld plotworld, PlotId plotid);
// the same applies here
public abstract Location getPlotTopLocAbs(PlotWorld plotworld, PlotId plotid);
/* // If you have a circular plot, just return the corner if it were a square
* Plot clearing (return false if you do not support some method) public abstract Location getPlotBottomLocAbs(PlotWorld plotworld,
* PlotId plotid);
*
*/
public abstract boolean clearPlot(Player player, Plot plot); // the same applies here
public abstract Location getPlotTopLocAbs(PlotWorld plotworld, PlotId plotid);
public abstract Location getSignLoc(Player player, PlotWorld plotworld, Plot plot); /*
* Plot clearing (return false if you do not support some method)
*/
/* public abstract boolean clearPlot(Player player, Plot plot);
* Plot set functions (return false if you do not support the specific set
* method)
*/
public abstract boolean setWall(Player player, PlotWorld plotworld, PlotId plotid, PlotBlock block); public abstract Location getSignLoc(Player player, PlotWorld plotworld,
Plot plot);
public abstract boolean setFloor(Player player, PlotWorld plotworld, PlotId plotid, PlotBlock[] block); /*
* Plot set functions (return false if you do not support the specific set
* method)
*/
public abstract boolean setBiome(Player player, Plot plot, Biome biome); public abstract boolean setWall(Player player, PlotWorld plotworld,
PlotId plotid, PlotBlock block);
/* public abstract boolean setFloor(Player player, PlotWorld plotworld,
* PLOT MERGING (return false if your generator does not support plot PlotId plotid, PlotBlock[] block);
* merging)
*/
public abstract boolean createRoadEast(PlotWorld plotworld, Plot plot);
public abstract boolean createRoadSouth(PlotWorld plotworld, Plot plot); public abstract boolean setBiome(Player player, Plot plot, Biome biome);
public abstract boolean createRoadSouthEast(PlotWorld plotworld, Plot plot); /*
* PLOT MERGING (return false if your generator does not support plot
* merging)
*/
public abstract boolean createRoadEast(PlotWorld plotworld, Plot plot);
public abstract boolean removeRoadEast(PlotWorld plotworld, Plot plot); public abstract boolean createRoadSouth(PlotWorld plotworld, Plot plot);
public abstract boolean removeRoadSouth(PlotWorld plotworld, Plot plot); public abstract boolean createRoadSouthEast(PlotWorld plotworld, Plot plot);
public abstract boolean removeRoadSouthEast(PlotWorld plotworld, Plot plot); public abstract boolean removeRoadEast(PlotWorld plotworld, Plot plot);
public abstract boolean finishPlotMerge(World world, PlotWorld plotworld, ArrayList<PlotId> plotIds); 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<PlotId> plotIds);
} }

View File

@ -22,204 +22,204 @@ import org.bukkit.block.Biome;
* *
*/ */
public class PlotSettings { public class PlotSettings {
/** /**
* merged plots * merged plots
*/ */
private boolean[] merged = new boolean[] { false, false, false, false }; private boolean[] merged = new boolean[] { false, false, false, false };
/** /**
* plot alias * plot alias
*/ */
private String alias; private String alias;
/** /**
* plot biome * plot biome
*/ */
private Biome biome; private Biome biome;
/** /**
* plot rain * plot rain
*/ */
private boolean rain; private boolean rain;
/** /**
* *
*/ */
private Set<Flag> flags; private Set<Flag> flags;
/** /**
* plot time * plot time
*/ */
private Long time; private Long time;
/** /**
* Change time? * Change time?
*/ */
private boolean changeTime; private boolean changeTime;
private PlotHomePosition position; private PlotHomePosition position;
/** /**
* Constructor * Constructor
* *
* @param plot * @param plot
*/ */
public PlotSettings(Plot plot) { public PlotSettings(Plot plot) {
this.alias = ""; this.alias = "";
} }
/** /**
* <b>Check if the plot is merged in a direction</b><br> * <b>Check if the plot is merged in a direction</b><br>
* 0 = North<br> * 0 = North<br>
* 1 = East<br> * 1 = East<br>
* 2 = South<br> * 2 = South<br>
* 3 = West<br> * 3 = West<br>
* *
* @param direction * @param direction
* @return boolean * @return boolean
*/ */
public boolean getMerged(int direction) { public boolean getMerged(int direction) {
return this.merged[direction]; return this.merged[direction];
} }
public boolean isMerged() { public boolean isMerged() {
return (this.merged[0] || this.merged[1] || this.merged[2] || this.merged[3]); return (this.merged[0] || this.merged[1] || this.merged[2] || this.merged[3]);
} }
public boolean[] getMerged() { public boolean[] getMerged() {
return this.merged; return this.merged;
} }
public void setMerged(boolean[] merged) { public void setMerged(boolean[] merged) {
this.merged = merged; this.merged = merged;
} }
public void setMerged(int direction, boolean merged) { public void setMerged(int direction, boolean merged) {
this.merged[direction] = merged; this.merged[direction] = merged;
} }
/** /**
* *
* @param b * @param b
*/ */
public void setBiome(Biome b) { public void setBiome(Biome b) {
this.biome = b; this.biome = b;
} }
/** /**
* *
* @param b * @param b
*/ */
public void setTimeChange(boolean b) { public void setTimeChange(boolean b) {
this.changeTime = b; this.changeTime = b;
} }
/** /**
* *
* @param l * @param l
*/ */
public void setTime(long l) { public void setTime(long l) {
this.time = l; this.time = l;
} }
/** /**
* *
* @return * @return
* @deprecated * @deprecated
*/ */
@Deprecated @Deprecated
public Biome getBiome() { public Biome getBiome() {
return this.biome; return this.biome;
} }
/** /**
* *
* @return * @return
*/ */
public boolean getRain() { public boolean getRain() {
return this.rain; return this.rain;
} }
public void setRain(boolean b) { public void setRain(boolean b) {
this.rain = b; this.rain = b;
} }
/** /**
* *
* @return * @return
*/ */
public long getTime() { public long getTime() {
return this.time; return this.time;
} }
/** /**
* *
* @return * @return
*/ */
public boolean getChangeTime() { public boolean getChangeTime() {
return this.changeTime; return this.changeTime;
} }
/** /**
* *
* @param alias * @param alias
*/ */
public void setAlias(String alias) { public void setAlias(String alias) {
this.alias = alias; this.alias = alias;
} }
/** /**
* *
* @param flag * @param flag
*/ */
public void addFlag(Flag flag) { public void addFlag(Flag flag) {
Flag hasFlag = getFlag(flag.getKey()); Flag hasFlag = getFlag(flag.getKey());
if (hasFlag != null) { if (hasFlag != null) {
this.flags.remove(hasFlag); this.flags.remove(hasFlag);
} }
this.flags.add(flag); this.flags.add(flag);
} }
/** /**
* *
* @param flags * @param flags
*/ */
public void setFlags(Flag[] flags) { public void setFlags(Flag[] flags) {
this.flags = new HashSet<Flag>(Arrays.asList(flags)); this.flags = new HashSet<Flag>(Arrays.asList(flags));
} }
/** /**
* *
* @return * @return
*/ */
public Set<Flag> getFlags() { public Set<Flag> getFlags() {
return this.flags; return this.flags;
} }
/** /**
* *
* @param flag * @param flag
* @return * @return
*/ */
public Flag getFlag(String flag) { public Flag getFlag(String flag) {
for (Flag myflag : this.flags) { for (Flag myflag : this.flags) {
if (myflag.getKey().equals(flag)) { if (myflag.getKey().equals(flag)) {
return myflag; return myflag;
} }
} }
return null; return null;
} }
public PlotHomePosition getPosition() { public PlotHomePosition getPosition() {
return this.position; return this.position;
} }
public void setPosition(PlotHomePosition position) { public void setPosition(PlotHomePosition position) {
this.position = position; this.position = position;
} }
public String getAlias() { public String getAlias() {
return this.alias; return this.alias;
} }
public String getJoinMessage() { public String getJoinMessage() {
return ""; return "";
} }
public String getLeaveMessage() { public String getLeaveMessage() {
return ""; return "";
} }
} }

View File

@ -5,26 +5,27 @@ package com.intellectualcrafters.plot;
*/ */
public class PlotSquaredException extends RuntimeException { public class PlotSquaredException extends RuntimeException {
public PlotSquaredException(PlotError error, String details) { public PlotSquaredException(PlotError error, String details) {
super("PlotError >> " + error.getHeader() + ": " + details); super("PlotError >> " + error.getHeader() + ": " + details);
PlotMain.sendConsoleSenderMessage("&cPlotError &6>> &c" + error.getHeader() + ": &6" + details); PlotMain.sendConsoleSenderMessage("&cPlotError &6>> &c"
} + error.getHeader() + ": &6" + details);
}
public static enum PlotError { public static enum PlotError {
MISSING_DEPENDENCY("Missing Dependency"); MISSING_DEPENDENCY("Missing Dependency");
private String errorHeader; private String errorHeader;
PlotError(String errorHeader) { PlotError(String errorHeader) {
this.errorHeader = errorHeader; this.errorHeader = errorHeader;
} }
public String getHeader() { public String getHeader() {
return this.errorHeader; return this.errorHeader;
} }
@Override @Override
public String toString() { public String toString() {
return this.getHeader(); return this.getHeader();
} }
} }
} }

View File

@ -1,109 +1,229 @@
package com.intellectualcrafters.plot; 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.ArrayList;
import java.util.Arrays;
import java.util.List; import java.util.List;
import org.bukkit.Material;
import org.bukkit.block.Biome; import org.bukkit.block.Biome;
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.ConfigurationSection;
public abstract class PlotWorld { public abstract class PlotWorld {
public boolean AUTO_MERGE; // TODO make this configurable
public static boolean AUTO_MERGE_DEFAULT = false; // make non static and static_default_valu + add config option
public static ArrayList<Material> BLOCKS = new ArrayList<Material>(
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) }));
public boolean MOB_SPAWNING; public boolean AUTO_MERGE;
public static boolean MOB_SPAWNING_DEFAULT = false; public static boolean AUTO_MERGE_DEFAULT = false;
public Biome PLOT_BIOME; public boolean MOB_SPAWNING;
public static Biome PLOT_BIOME_DEFAULT = Biome.FOREST; public static boolean MOB_SPAWNING_DEFAULT = false;
public boolean PLOT_CHAT; public Biome PLOT_BIOME;
public static boolean PLOT_CHAT_DEFAULT = false; public static Biome PLOT_BIOME_DEFAULT = Biome.FOREST;
public boolean SCHEMATIC_CLAIM_SPECIFY = false; public boolean PLOT_CHAT;
public static boolean SCHEMATIC_CLAIM_SPECIFY_DEFAULT = false; public static boolean PLOT_CHAT_DEFAULT = false;
public boolean SCHEMATIC_ON_CLAIM; public boolean SCHEMATIC_CLAIM_SPECIFY = false;
public static boolean SCHEMATIC_ON_CLAIM_DEFAULT = false; public static boolean SCHEMATIC_CLAIM_SPECIFY_DEFAULT = false;
public String SCHEMATIC_FILE; public boolean SCHEMATIC_ON_CLAIM;
public static String SCHEMATIC_FILE_DEFAULT = "null"; public static boolean SCHEMATIC_ON_CLAIM_DEFAULT = false;
public List<String> SCHEMATICS; public String SCHEMATIC_FILE;
public static List<String> SCHEMATICS_DEFAULT = null; public static String SCHEMATIC_FILE_DEFAULT = "null";
public List<String> DEFAULT_FLAGS; public List<String> SCHEMATICS;
public static List<String> DEFAULT_FLAGS_DEFAULT = new ArrayList<String>(); public static List<String> SCHEMATICS_DEFAULT = null;
public boolean USE_ECONOMY; public List<String> DEFAULT_FLAGS;
public static boolean USE_ECONOMY_DEFAULT = false; public static List<String> DEFAULT_FLAGS_DEFAULT = new ArrayList<String>();
public double PLOT_PRICE; public boolean USE_ECONOMY;
public static double PLOT_PRICE_DEFAULT = 100; public static boolean USE_ECONOMY_DEFAULT = false;
public double MERGE_PRICE; public double PLOT_PRICE;
public static double MERGE_PRICE_DEFAULT = 100; public static double PLOT_PRICE_DEFAULT = 100;
public PlotWorld(String worldname) { public double MERGE_PRICE;
this.worldname = worldname; public static double MERGE_PRICE_DEFAULT = 100;
}
/** public double SELL_PRICE;
* When a world is created, the following method will be called for each node set in the configuration public static double SELL_PRICE_DEFAULT = 75;
* - 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) { public PlotWorld(String worldname) {
this.worldname = worldname;
}
/* /**
* Saving core plotworld settings * 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
config.set("natural_mob_spawning",this.MOB_SPAWNING); * not support configuration, or if you want to implement your own methods
config.set("plot.auto_merge",this.AUTO_MERGE); *
config.set("plot.biome",this.PLOT_BIOME.name()); * @param key
config.set("schematic.on_claim",this.SCHEMATIC_ON_CLAIM); * @param value
config.set("schematic.file",this.SCHEMATIC_FILE); */
config.set("schematic.specify_on_claim",this.SCHEMATIC_CLAIM_SPECIFY); public void loadConfiguration(ConfigurationSection config) {
config.set("schematic.schematics",this.SCHEMATICS); this.MOB_SPAWNING = config.getBoolean("natural_mob_spawning");
config.set("economy.use",this.USE_ECONOMY); this.AUTO_MERGE = config.getBoolean("plot.auto_merge");
config.set("economy.prices.claim",this.PLOT_PRICE); this.PLOT_BIOME = (Biome) Configuration.BIOME.parseString(config
config.set("economy.prices.merge",this.MERGE_PRICE); .getString("plot.biome"));
config.set("chat.enabled",this.PLOT_CHAT); this.SCHEMATIC_ON_CLAIM = config.getBoolean("schematic.on_claim");
config.set("flags.default",this.DEFAULT_FLAGS); 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");
}
ConfigurationNode[] settings = getSettingNodes(); public void saveConfiguration(ConfigurationSection config) {
/* /*
* Saving generator specific settings * Saving core plotworld settings
*/ */
for (ConfigurationNode setting:settings) { config.set("natural_mob_spawning", this.MOB_SPAWNING);
config.set(setting.getConstant(), setting.getValue()); 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);
public String worldname; ConfigurationNode[] settings = getSettingNodes();
/** /*
* Used for the <b>/plot setup</b> command * Saving generator specific settings
* Return null if you do not want to support this feature */
* for (ConfigurationNode setting : settings) {
* @return ConfigurationNode[] config.set(setting.getConstant(), setting.getValue());
*/ }
public abstract ConfigurationNode[] getSettingNodes(); }
public String worldname;
/**
* Used for the <b>/plot setup</b> command Return null if you do not want to
* support this feature
*
* @return ConfigurationNode[]
*/
public abstract ConfigurationNode[] getSettingNodes();
} }

View File

@ -20,70 +20,71 @@ import org.bukkit.entity.Player;
*/ */
public class RUtils { public class RUtils {
public static long getTotalRam() { public static long getTotalRam() {
return (Runtime.getRuntime().maxMemory() / 1024) / 1024; return (Runtime.getRuntime().maxMemory() / 1024) / 1024;
} }
public static long getFreeRam() { public static long getFreeRam() {
return (Runtime.getRuntime().freeMemory() / 1024) / 1024; return (Runtime.getRuntime().freeMemory() / 1024) / 1024;
} }
public static long getRamPercentage() { public static long getRamPercentage() {
return (getFreeRam() / getTotalRam()) * 100; return (getFreeRam() / getTotalRam()) * 100;
} }
public static String formatTime(double sec) { public static String formatTime(double sec) {
double h = sec / 3600; double h = sec / 3600;
double m = (sec % 3600) / 60; double m = (sec % 3600) / 60;
double s = sec % 60; double s = sec % 60;
String string = C.TIME_FORMAT.s(); String string = C.TIME_FORMAT.s();
@SuppressWarnings("unused") @SuppressWarnings("unused")
// String s_d = (int) d + " " + (d != 1 ? "days" : "day"); // String s_d = (int) d + " " + (d != 1 ? "days" : "day");
String s_h = (int) h + " " + ((int) h != 1 ? "hours" : "hour"); String s_h = (int) h + " " + ((int) h != 1 ? "hours" : "hour");
String s_m = (int) m + " " + ((int) m != 1 ? "minutes" : "minute"); String s_m = (int) m + " " + ((int) m != 1 ? "minutes" : "minute");
String s_s = (int) s + " " + ((int) s != 1 ? "seconds" : "second"); String s_s = (int) s + " " + ((int) s != 1 ? "seconds" : "second");
return string.replaceAll("%sec%", s_s).replaceAll("%min%", s_m).replaceAll("%hours%", s_h); return string.replaceAll("%sec%", s_s).replaceAll("%min%", s_m)
} .replaceAll("%hours%", s_h);
}
enum Direction { enum Direction {
SOUTH(0), EAST(1), NORTH(2), WEST(3); SOUTH(0), EAST(1), NORTH(2), WEST(3);
private int i; private int i;
Direction(int i) { Direction(int i) {
this.i = i; this.i = i;
} }
public int getInt() { public int getInt() {
return this.i; return this.i;
} }
} }
public void forceTexture(Player p) { public void forceTexture(Player p) {
p.setResourcePack(Settings.PLOT_SPECIFIC_RESOURCE_PACK); p.setResourcePack(Settings.PLOT_SPECIFIC_RESOURCE_PACK);
} }
public Direction getDirection(Location l) { public Direction getDirection(Location l) {
double d = ((l.getYaw() * 4.0F) / 360.0F) + 0.5D; double d = ((l.getYaw() * 4.0F) / 360.0F) + 0.5D;
int i = (int) d; int i = (int) d;
int x = d < i ? i - 1 : i; int x = d < i ? i - 1 : i;
switch (x) { switch (x) {
case 0: case 0:
return Direction.SOUTH; return Direction.SOUTH;
case 1: case 1:
return Direction.EAST; return Direction.EAST;
case 2: case 2:
return Direction.NORTH; return Direction.NORTH;
case 3: case 3:
return Direction.WEST; return Direction.WEST;
default: default:
return null; return null;
} }
} }
public boolean compareDirections(Location l1, Location l2) { public boolean compareDirections(Location l1, Location l2) {
return getDirection(l1) == getDirection(l2); return getDirection(l1) == getDirection(l2);
} }
} }

View File

@ -24,154 +24,166 @@ import com.sk89q.worldedit.bukkit.BukkitWorld;
*/ */
public class SchematicHandler { public class SchematicHandler {
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public boolean paste(Location location, Schematic schematic, Plot plot) { public boolean paste(Location location, Schematic schematic, Plot plot) {
if (schematic == null) { if (schematic == null) {
PlotMain.sendConsoleSenderMessage("Schematic == null :|"); PlotMain.sendConsoleSenderMessage("Schematic == null :|");
return false; return false;
} }
try { try {
EditSession session = new EditSession(new BukkitWorld(location.getWorld()), 999999999); EditSession session = new EditSession(new BukkitWorld(
CuboidClipboard clipboard = CuboidClipboard.loadSchematic(schematic.getFile()); location.getWorld()), 999999999);
Location l1 = PlotHelper.getPlotBottomLoc(plot.getWorld(), plot.getId()); CuboidClipboard clipboard = CuboidClipboard.loadSchematic(schematic
PlotHelper.getPlotTopLoc(plot.getWorld(), plot.getId()); .getFile());
int x = l1.getBlockX() + 1; Location l1 = PlotHelper.getPlotBottomLoc(plot.getWorld(),
int z = l1.getBlockZ() + 1; plot.getId());
int y = location.getWorld().getHighestBlockYAt(x,z); PlotHelper.getPlotTopLoc(plot.getWorld(), plot.getId());
Vector v1 = new Vector(x, y+1, z); int x = l1.getBlockX() + 1;
clipboard.paste(session, v1, true); int z = l1.getBlockZ() + 1;
} catch (Exception e) { int y = location.getWorld().getHighestBlockYAt(x, z);
return false; Vector v1 = new Vector(x, y + 1, z);
} clipboard.paste(session, v1, true);
return true; } catch (Exception e) {
} return false;
}
return true;
}
public Schematic getSchematic(String name) { public Schematic getSchematic(String name) {
{ {
File parent = new File(JavaPlugin.getPlugin(PlotMain.class).getDataFolder() + File.separator + "schematics"); File parent = new File(JavaPlugin.getPlugin(PlotMain.class)
if (!parent.exists()) { .getDataFolder() + File.separator + "schematics");
parent.mkdir(); if (!parent.exists()) {
} parent.mkdir();
} }
File file = new File(JavaPlugin.getPlugin(PlotMain.class).getDataFolder() + File.separator + "schematics" + File.separator + name + ".schematic"); }
if (!file.exists()) { File file = new File(JavaPlugin.getPlugin(PlotMain.class)
PlotMain.sendConsoleSenderMessage(file.toString() + " doesn't exist"); .getDataFolder()
return null; + File.separator
} + "schematics"
+ File.separator + name + ".schematic");
if (!file.exists()) {
PlotMain.sendConsoleSenderMessage(file.toString()
+ " doesn't exist");
return null;
}
Schematic schematic = null; Schematic schematic = null;
try { try {
InputStream iStream = new FileInputStream(file); InputStream iStream = new FileInputStream(file);
NBTInputStream stream = new NBTInputStream(new GZIPInputStream(iStream)); NBTInputStream stream = new NBTInputStream(new GZIPInputStream(
CompoundTag tag = (CompoundTag) stream.readTag(); iStream));
Map<String, Tag> tagMap = tag.getValue(); CompoundTag tag = (CompoundTag) stream.readTag();
Map<String, Tag> tagMap = tag.getValue();
byte[] addId = new byte[0]; byte[] addId = new byte[0];
if (tagMap.containsKey("AddBlocks")) { if (tagMap.containsKey("AddBlocks")) {
addId = ByteArrayTag.class.cast(tagMap.get("AddBlocks")).getValue(); addId = ByteArrayTag.class.cast(tagMap.get("AddBlocks"))
} .getValue();
}
short width = ShortTag.class.cast(tagMap.get("Width")).getValue(); short width = ShortTag.class.cast(tagMap.get("Width")).getValue();
short length = ShortTag.class.cast(tagMap.get("Length")).getValue(); short length = ShortTag.class.cast(tagMap.get("Length")).getValue();
short height = ShortTag.class.cast(tagMap.get("Height")).getValue(); short height = ShortTag.class.cast(tagMap.get("Height")).getValue();
byte[] b = ByteArrayTag.class.cast(tagMap.get("Blocks")).getValue(); byte[] b = ByteArrayTag.class.cast(tagMap.get("Blocks")).getValue();
byte[] d = ByteArrayTag.class.cast(tagMap.get("Data")).getValue(); byte[] d = ByteArrayTag.class.cast(tagMap.get("Data")).getValue();
short[] blocks = new short[b.length]; 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++) { for (int index = 0; index < b.length; index++) {
if ((index >> 1) >= addId.length) { // No corresponding if ((index >> 1) >= addId.length) { // No corresponding
// AddBlocks index // AddBlocks index
blocks[index] = (short) (b[index] & 0xFF); blocks[index] = (short) (b[index] & 0xFF);
} else { } else {
if ((index & 1) == 0) { if ((index & 1) == 0) {
blocks[index] = (short) (((addId[index >> 1] & 0x0F) << 8) + (b[index] & 0xFF)); blocks[index] = (short) (((addId[index >> 1] & 0x0F) << 8) + (b[index] & 0xFF));
} else { } else {
blocks[index] = (short) (((addId[index >> 1] & 0xF0) << 4) + (b[index] & 0xFF)); 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++) { for (int x = 0; x < b.length; x++) {
collection[x] = new DataCollection(blocks[x], d[x]); collection[x] = new DataCollection(blocks[x], d[x]);
} }
schematic = new Schematic(collection, dimension, file); schematic = new Schematic(collection, dimension, file);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;
} finally { } finally {
return schematic; return schematic;
} }
} }
public static class Schematic { public static class Schematic {
private DataCollection[] blockCollection; private DataCollection[] blockCollection;
private Dimension schematicDimension; private Dimension schematicDimension;
private File file; private File file;
public Schematic(DataCollection[] blockCollection, Dimension schematicDimension, File file) { public Schematic(DataCollection[] blockCollection,
this.blockCollection = blockCollection; Dimension schematicDimension, File file) {
this.schematicDimension = schematicDimension; this.blockCollection = blockCollection;
this.file = file; this.schematicDimension = schematicDimension;
} this.file = file;
}
public File getFile() { public File getFile() {
return this.file; return this.file;
} }
public Dimension getSchematicDimension() { public Dimension getSchematicDimension() {
return this.schematicDimension; return this.schematicDimension;
} }
public DataCollection[] getBlockCollection() { public DataCollection[] getBlockCollection() {
return this.blockCollection; return this.blockCollection;
} }
} }
public class Dimension { public class Dimension {
private int x; private int x;
private int y; private int y;
private int z; private int z;
public Dimension(int x, int y, int z) { public Dimension(int x, int y, int z) {
this.x = x; this.x = x;
this.y = y; this.y = y;
this.z = z; this.z = z;
} }
public int getX() { public int getX() {
return this.x; return this.x;
} }
public int getY() { public int getY() {
return this.y; return this.y;
} }
public int getZ() { public int getZ() {
return this.z; return this.z;
} }
} }
public class DataCollection { public class DataCollection {
private short block; private short block;
private byte data; private byte data;
public DataCollection(short block, byte data) { public DataCollection(short block, byte data) {
this.block = block; this.block = block;
this.data = data; this.data = data;
} }
public short getBlock() { public short getBlock() {
return this.block; return this.block;
} }
public byte getData() { public byte getData() {
return this.data; return this.data;
} }
} }
} }

View File

@ -15,38 +15,43 @@ import com.intellectualcrafters.plot.ReflectionUtils.RefMethod;
*/ */
public class SetBlockFast { public class SetBlockFast {
private static final RefClass classBlock = getRefClass("{nms}.Block"); private static final RefClass classBlock = getRefClass("{nms}.Block");
private static final RefClass classChunk = getRefClass("{nms}.Chunk"); private static final RefClass classChunk = getRefClass("{nms}.Chunk");
private static final RefClass classWorld = getRefClass("{nms}.World"); private static final RefClass classWorld = getRefClass("{nms}.World");
private static final RefClass classCraftWorld = getRefClass("{cb}.CraftWorld"); private static final RefClass classCraftWorld = getRefClass("{cb}.CraftWorld");
private static RefMethod methodGetHandle; private static RefMethod methodGetHandle;
private static RefMethod methodGetChunkAt; private static RefMethod methodGetChunkAt;
private static RefMethod methodA; private static RefMethod methodA;
private static RefMethod methodGetById; private static RefMethod methodGetById;
public SetBlockFast() throws NoSuchMethodException { public SetBlockFast() throws NoSuchMethodException {
methodGetHandle = classCraftWorld.getMethod("getHandle"); methodGetHandle = classCraftWorld.getMethod("getHandle");
methodGetChunkAt = classWorld.getMethod("getChunkAt", int.class, int.class); methodGetChunkAt = classWorld.getMethod("getChunkAt", int.class,
methodA = classChunk.getMethod("a", int.class, int.class, int.class, classBlock, int.class); int.class);
methodGetById = classBlock.getMethod("getById", 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 w = methodGetHandle.of(world).call();
Object chunk = methodGetChunkAt.of(w).call(x >> 4, z >> 4); Object chunk = methodGetChunkAt.of(w).call(x >> 4, z >> 4);
Object block = methodGetById.of(null).call(blockId); Object block = methodGetById.of(null).call(blockId);
methodA.of(chunk).call(x & 0x0f, y, z & 0x0f, block, data); methodA.of(chunk).call(x & 0x0f, y, z & 0x0f, block, data);
return true; return true;
} }
public static void update(org.bukkit.entity.Player player) { public static void update(org.bukkit.entity.Player player) {
int distance = Bukkit.getViewDistance() + 1; int distance = Bukkit.getViewDistance() + 1;
for (int cx = -distance; cx < distance; cx++) { for (int cx = -distance; cx < distance; cx++) {
for (int cz = -distance; cz < distance; cz++) { for (int cz = -distance; cz < distance; cz++) {
player.getWorld().refreshChunk(player.getLocation().getChunk().getX() + cx, player.getLocation().getChunk().getZ() + cz); player.getWorld().refreshChunk(
} player.getLocation().getChunk().getX() + cx,
} player.getLocation().getChunk().getZ() + cz);
} }
}
}
} }

View File

@ -17,81 +17,82 @@ package com.intellectualcrafters.plot;
* @author Empire92 * @author Empire92
*/ */
public class Settings { public class Settings {
public static int MAX_PLOTS = 20; public static int MAX_PLOTS = 20;
/** /**
* WorldGuard region on claimed plots * WorldGuard region on claimed plots
*/ */
public static boolean WORLDGUARD = false; public static boolean WORLDGUARD = false;
/** /**
* metrics * metrics
*/ */
public static boolean METRICS = true; public static boolean METRICS = true;
/** /**
* plot specific resource pack * plot specific resource pack
*/ */
public static String PLOT_SPECIFIC_RESOURCE_PACK = ""; public static String PLOT_SPECIFIC_RESOURCE_PACK = "";
/** /**
* Kill road mobs? * Kill road mobs?
*/ */
public static boolean KILL_ROAD_MOBS; public static boolean KILL_ROAD_MOBS;
/** /**
* Default kill road mobs: true * Default kill road mobs: true
*/ */
public static boolean KILL_ROAD_MOBS_DEFAULT = true; public static boolean KILL_ROAD_MOBS_DEFAULT = true;
/** /**
* mob pathfinding? * mob pathfinding?
*/ */
public static boolean MOB_PATHFINDING; public static boolean MOB_PATHFINDING;
/** /**
* Default mob pathfinding: true * Default mob pathfinding: true
*/ */
public static boolean MOB_PATHFINDING_DEFAULT = true; public static boolean MOB_PATHFINDING_DEFAULT = true;
/** /**
* Update settings * Update settings
* *
* @author Citymonstret * @author Citymonstret
* *
*/ */
public static String URL = "http://dev.bukkit.org/bukkit-plugins/plotsquared/"; 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 boolean AUTO_CLEAR = false;
public static int AUTO_CLEAR_DAYS = 365; public static int AUTO_CLEAR_DAYS = 365;
public static class Update { public static class Update {
/** /**
* Update plugin? * Update plugin?
* *
* @deprecated * @deprecated
*/ */
@Deprecated @Deprecated
public static boolean AUTO_UPDATE = false; public static boolean AUTO_UPDATE = false;
} }
public static class Web { public static class Web {
public static boolean ENABLED = false; public static boolean ENABLED = false;
public static int PORT = 9000; public static int PORT = 9000;
} }
/** /**
* Database settings * Database settings
* *
* @author Citymonstret * @author Citymonstret
* *
*/ */
public static class DB { public static class DB {
public static boolean USE_MONGO = false; /* public static boolean USE_MONGO = false; /*
* TODO: Implement Mongo * TODO: Implement Mongo
* @Brandon *
*/; * @Brandon
public static boolean USE_SQLITE = false; */;
public static boolean USE_MYSQL = true; /* NOTE: Fixed connector */ public static boolean USE_SQLITE = false;
public static String SQLITE_DB = "storage"; public static boolean USE_MYSQL = true; /* NOTE: Fixed connector */
public static String HOST_NAME = "localhost"; public static String SQLITE_DB = "storage";
public static String PORT = "3306"; public static String HOST_NAME = "localhost";
public static String DATABASE = "plot_db"; public static String PORT = "3306";
public static String USER = "root"; public static String DATABASE = "plot_db";
public static String PASSWORD = "password"; public static String USER = "root";
} public static String PASSWORD = "password";
}
} }

View File

@ -17,391 +17,431 @@ import org.bukkit.entity.Player;
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
public class Title { public class Title {
/* Title packet */ /* Title packet */
private Class<?> packetTitle; private Class<?> packetTitle;
/* Title packet actions ENUM */ /* Title packet actions ENUM */
private Class<?> packetActions; private Class<?> packetActions;
/* Chat serializer */ /* Chat serializer */
private Class<?> nmsChatSerializer; private Class<?> nmsChatSerializer;
/* Title text and color */ /* Title text and color */
private String title = ""; private String title = "";
private ChatColor titleColor = ChatColor.WHITE; private ChatColor titleColor = ChatColor.WHITE;
/* Subtitle text and color */ /* Subtitle text and color */
private String subtitle = ""; private String subtitle = "";
private ChatColor subtitleColor = ChatColor.WHITE; private ChatColor subtitleColor = ChatColor.WHITE;
/* Title timings */ /* Title timings */
private int fadeInTime = -1; private int fadeInTime = -1;
private int stayTime = -1; private int stayTime = -1;
private int fadeOutTime = -1; private int fadeOutTime = -1;
private boolean ticks = false; private boolean ticks = false;
private static final Map<Class<?>, Class<?>> CORRESPONDING_TYPES; private static final Map<Class<?>, Class<?>> CORRESPONDING_TYPES;
static { static {
CORRESPONDING_TYPES = new HashMap<>(); CORRESPONDING_TYPES = new HashMap<>();
} }
/** /**
* Create a new 1.8 title * Create a new 1.8 title
* *
* @param title * @param title
* Title * Title
*/ */
public Title(String title) { public Title(String title) {
this.title = title; this.title = title;
loadClasses(); loadClasses();
} }
/** /**
* Create a new 1.8 title * Create a new 1.8 title
* *
* @param title * @param title
* Title text * Title text
* @param subtitle * @param subtitle
* Subtitle text * Subtitle text
*/ */
public Title(String title, String subtitle) { public Title(String title, String subtitle) {
this.title = title; this.title = title;
this.subtitle = subtitle; this.subtitle = subtitle;
loadClasses(); loadClasses();
} }
/** /**
* Create a new 1.8 title * Create a new 1.8 title
* *
* @param title * @param title
* Title text * Title text
* @param subtitle * @param subtitle
* Subtitle text * Subtitle text
* @param fadeInTime * @param fadeInTime
* Fade in time * Fade in time
* @param stayTime * @param stayTime
* Stay on screen time * Stay on screen time
* @param fadeOutTime * @param fadeOutTime
* Fade out time * Fade out time
*/ */
public Title(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) { public Title(String title, String subtitle, int fadeInTime, int stayTime,
this.title = title; int fadeOutTime) {
this.subtitle = subtitle; this.title = title;
this.fadeInTime = fadeInTime; this.subtitle = subtitle;
this.stayTime = stayTime; this.fadeInTime = fadeInTime;
this.fadeOutTime = fadeOutTime; this.stayTime = stayTime;
loadClasses(); this.fadeOutTime = fadeOutTime;
} loadClasses();
}
/** /**
* Load spigot and NMS classes * Load spigot and NMS classes
*/ */
private void loadClasses() { private void loadClasses() {
this.packetTitle = getClass("org.spigotmc.ProtocolInjector$PacketTitle"); this.packetTitle = getClass("org.spigotmc.ProtocolInjector$PacketTitle");
this.packetActions = getClass("org.spigotmc.ProtocolInjector$PacketTitle$Action"); this.packetActions = getClass("org.spigotmc.ProtocolInjector$PacketTitle$Action");
this.nmsChatSerializer = getNMSClass("ChatSerializer"); this.nmsChatSerializer = getNMSClass("ChatSerializer");
} }
/** /**
* Set the title color * Set the title color
* *
* @param color * @param color
* Chat color * Chat color
*/ */
public void setTitleColor(ChatColor color) { public void setTitleColor(ChatColor color) {
this.titleColor = color; this.titleColor = color;
} }
/** /**
* Set the subtitle color * Set the subtitle color
* *
* @param color * @param color
* Chat color * Chat color
*/ */
public void setSubtitleColor(ChatColor color) { public void setSubtitleColor(ChatColor color) {
this.subtitleColor = color; this.subtitleColor = color;
} }
/** /**
* Set title fade in time * Set title fade in time
* *
* @param time * @param time
* Time * Time
*/ */
public void setFadeInTime(int time) { public void setFadeInTime(int time) {
this.fadeInTime = time; this.fadeInTime = time;
} }
/** /**
* Set title fade out time * Set title fade out time
* *
* @param time * @param time
* Time * Time
*/ */
public void setFadeOutTime(int time) { public void setFadeOutTime(int time) {
this.fadeOutTime = time; this.fadeOutTime = time;
} }
/** /**
* Set title stay time * Set title stay time
* *
* @param time * @param time
* Time * Time
*/ */
public void setStayTime(int time) { public void setStayTime(int time) {
this.stayTime = time; this.stayTime = time;
} }
/** /**
* Set timings to ticks * Set timings to ticks
*/ */
public void setTimingsToTicks() { public void setTimingsToTicks() {
this.ticks = true; this.ticks = true;
} }
/** /**
* Set timings to seconds * Set timings to seconds
*/ */
public void setTimingsToSeconds() { public void setTimingsToSeconds() {
this.ticks = false; this.ticks = false;
} }
/** /**
* Send the title to a player * Send the title to a player
* *
* @param player * @param player
* Player * Player
*/ */
public void send(Player player) { public void send(Player player) {
if ((getProtocolVersion(player) >= 47) && isSpigot() && (this.packetTitle != null)) { if ((getProtocolVersion(player) >= 47) && isSpigot()
// First reset previous settings && (this.packetTitle != null)) {
resetTitle(player); // First reset previous settings
try { resetTitle(player);
// Send timings first try {
Object handle = getHandle(player); // Send timings first
Object connection = getField(handle.getClass(), "playerConnection").get(handle); Object handle = getHandle(player);
Object[] actions = this.packetActions.getEnumConstants(); Object connection = getField(handle.getClass(),
Method sendPacket = getMethod(connection.getClass(), "sendPacket"); "playerConnection").get(handle);
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)); Object[] actions = this.packetActions.getEnumConstants();
// Send if set Method sendPacket = getMethod(connection.getClass(),
if ((this.fadeInTime != -1) && (this.fadeOutTime != -1) && (this.stayTime != -1)) { "sendPacket");
sendPacket.invoke(connection, packet); 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 // Send title
Object serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.title) + "\",color:" + this.titleColor.name().toLowerCase() + "}"); Object serialized = getMethod(this.nmsChatSerializer, "a",
packet = this.packetTitle.getConstructor(this.packetActions, getNMSClass("IChatBaseComponent")).newInstance(actions[0], serialized); String.class).invoke(
sendPacket.invoke(connection, packet); null,
if (!this.subtitle.equals("")) { "{text:\""
// Send subtitle if present + ChatColor.translateAlternateColorCodes('&',
serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.subtitle) + "\",color:" + this.subtitleColor.name().toLowerCase() + "}"); this.title) + "\",color:"
packet = this.packetTitle.getConstructor(this.packetActions, getNMSClass("IChatBaseComponent")).newInstance(actions[1], serialized); + this.titleColor.name().toLowerCase() + "}");
sendPacket.invoke(connection, packet); packet = this.packetTitle.getConstructor(this.packetActions,
} getNMSClass("IChatBaseComponent")).newInstance(
} catch (Exception e) { actions[0], serialized);
e.printStackTrace(); 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 * Broadcast the title to all players
*/ */
public void broadcast() { public void broadcast() {
for (Player p : Bukkit.getOnlinePlayers()) { for (Player p : Bukkit.getOnlinePlayers()) {
send(p); send(p);
} }
} }
/** /**
* Clear the title * Clear the title
* *
* @param player * @param player
* Player * Player
*/ */
public void clearTitle(Player player) { public void clearTitle(Player player) {
if ((getProtocolVersion(player) >= 47) && isSpigot()) { if ((getProtocolVersion(player) >= 47) && isSpigot()) {
try { try {
// Send timings first // Send timings first
Object handle = getHandle(player); Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle); Object connection = getField(handle.getClass(),
Object[] actions = this.packetActions.getEnumConstants(); "playerConnection").get(handle);
Method sendPacket = getMethod(connection.getClass(), "sendPacket"); Object[] actions = this.packetActions.getEnumConstants();
Object packet = this.packetTitle.getConstructor(this.packetActions).newInstance(actions[3]); Method sendPacket = getMethod(connection.getClass(),
sendPacket.invoke(connection, packet); "sendPacket");
} catch (Exception e) { Object packet = this.packetTitle.getConstructor(
e.printStackTrace(); this.packetActions).newInstance(actions[3]);
} sendPacket.invoke(connection, packet);
} } catch (Exception e) {
} e.printStackTrace();
}
}
}
/** /**
* Reset the title settings * Reset the title settings
* *
* @param player * @param player
* Player * Player
*/ */
public void resetTitle(Player player) { public void resetTitle(Player player) {
if ((getProtocolVersion(player) >= 47) && isSpigot()) { if ((getProtocolVersion(player) >= 47) && isSpigot()) {
try { try {
// Send timings first // Send timings first
Object handle = getHandle(player); Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle); Object connection = getField(handle.getClass(),
Object[] actions = this.packetActions.getEnumConstants(); "playerConnection").get(handle);
Method sendPacket = getMethod(connection.getClass(), "sendPacket"); Object[] actions = this.packetActions.getEnumConstants();
Object packet = this.packetTitle.getConstructor(this.packetActions).newInstance(actions[4]); Method sendPacket = getMethod(connection.getClass(),
sendPacket.invoke(connection, packet); "sendPacket");
} catch (Exception e) { Object packet = this.packetTitle.getConstructor(
e.printStackTrace(); this.packetActions).newInstance(actions[4]);
} sendPacket.invoke(connection, packet);
} } catch (Exception e) {
} e.printStackTrace();
}
}
}
/** /**
* Get the protocol version of the player * Get the protocol version of the player
* *
* @param player * @param player
* Player * Player
* @return Protocol version * @return Protocol version
*/ */
private int getProtocolVersion(Player player) { private int getProtocolVersion(Player player) {
int version = 0; int version = 0;
try { try {
Object handle = getHandle(player); Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle); Object connection = getField(handle.getClass(), "playerConnection")
Object networkManager = getValue("networkManager", connection); .get(handle);
version = (Integer) getMethod("getVersion", networkManager.getClass()).invoke(networkManager); Object networkManager = getValue("networkManager", connection);
version = (Integer) getMethod("getVersion",
networkManager.getClass()).invoke(networkManager);
return version; return version;
} catch (Exception ex) { } catch (Exception ex) {
// ex.printStackTrace(); <-- spammy console // ex.printStackTrace(); <-- spammy console
} }
return version; return version;
} }
/** /**
* Check if running spigot * Check if running spigot
* *
* @return Spigot * @return Spigot
*/ */
private boolean isSpigot() { private boolean isSpigot() {
return Bukkit.getVersion().contains("Spigot"); return Bukkit.getVersion().contains("Spigot");
} }
/** /**
* Get class by url * Get class by url
* *
* @param namespace * @param namespace
* Namespace url * Namespace url
* @return Class * @return Class
*/ */
private Class<?> getClass(String namespace) { private Class<?> getClass(String namespace) {
try { try {
return Class.forName(namespace); return Class.forName(namespace);
} catch (Exception e) { } catch (Exception e) {
return null; return null;
} }
} }
private Field getField(String name, Class<?> clazz) throws Exception { private Field getField(String name, Class<?> clazz) throws Exception {
return clazz.getDeclaredField(name); return clazz.getDeclaredField(name);
} }
private Object getValue(String name, Object obj) throws Exception { private Object getValue(String name, Object obj) throws Exception {
Field f = getField(name, obj.getClass()); Field f = getField(name, obj.getClass());
f.setAccessible(true); f.setAccessible(true);
return f.get(obj); return f.get(obj);
} }
private Class<?> getPrimitiveType(Class<?> clazz) { private Class<?> getPrimitiveType(Class<?> clazz) {
return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES.get(clazz) : clazz; return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES
} .get(clazz) : clazz;
}
private Class<?>[] toPrimitiveTypeArray(Class<?>[] classes) { private Class<?>[] toPrimitiveTypeArray(Class<?>[] classes) {
int a = classes != null ? classes.length : 0; int a = classes != null ? classes.length : 0;
Class<?>[] types = new Class<?>[a]; Class<?>[] types = new Class<?>[a];
for (int i = 0; i < a; i++) { for (int i = 0; i < a; i++) {
types[i] = getPrimitiveType(classes[i]); types[i] = getPrimitiveType(classes[i]);
} }
return types; return types;
} }
private static boolean equalsTypeArray(Class<?>[] a, Class<?>[] o) { private static boolean equalsTypeArray(Class<?>[] a, Class<?>[] o) {
if (a.length != o.length) { if (a.length != o.length) {
return false; return false;
} }
for (int i = 0; i < a.length; i++) { for (int i = 0; i < a.length; i++) {
if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i])) { if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i])) {
return false; return false;
} }
} }
return true; return true;
} }
private Object getHandle(Object obj) { private Object getHandle(Object obj) {
try { try {
return getMethod("getHandle", obj.getClass()).invoke(obj); return getMethod("getHandle", obj.getClass()).invoke(obj);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
} }
private Method getMethod(String name, Class<?> clazz, Class<?>... paramTypes) { private Method getMethod(String name, Class<?> clazz,
Class<?>[] t = toPrimitiveTypeArray(paramTypes); Class<?>... paramTypes) {
for (Method m : clazz.getMethods()) { Class<?>[] t = toPrimitiveTypeArray(paramTypes);
Class<?>[] types = toPrimitiveTypeArray(m.getParameterTypes()); for (Method m : clazz.getMethods()) {
if (m.getName().equals(name) && equalsTypeArray(types, t)) { Class<?>[] types = toPrimitiveTypeArray(m.getParameterTypes());
return m; if (m.getName().equals(name) && equalsTypeArray(types, t)) {
} return m;
} }
return null; }
} return null;
}
private String getVersion() { private String getVersion() {
String name = Bukkit.getServer().getClass().getPackage().getName(); String name = Bukkit.getServer().getClass().getPackage().getName();
return name.substring(name.lastIndexOf('.') + 1) + "."; return name.substring(name.lastIndexOf('.') + 1) + ".";
} }
private Class<?> getNMSClass(String className) { private Class<?> getNMSClass(String className) {
String fullName = "net.minecraft.server." + getVersion() + className; String fullName = "net.minecraft.server." + getVersion() + className;
Class<?> clazz = null; Class<?> clazz = null;
try { try {
clazz = Class.forName(fullName); clazz = Class.forName(fullName);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
return clazz; return clazz;
} }
private Field getField(Class<?> clazz, String name) { private Field getField(Class<?> clazz, String name) {
try { try {
Field field = clazz.getDeclaredField(name); Field field = clazz.getDeclaredField(name);
field.setAccessible(true); field.setAccessible(true);
return field; return field;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
} }
private Method getMethod(Class<?> clazz, String name, Class<?>... args) { private Method getMethod(Class<?> clazz, String name, Class<?>... args) {
for (Method m : clazz.getMethods()) { for (Method m : clazz.getMethods()) {
if (m.getName().equals(name) && ((args.length == 0) || ClassListEqual(args, m.getParameterTypes()))) { if (m.getName().equals(name)
m.setAccessible(true); && ((args.length == 0) || ClassListEqual(args,
return m; m.getParameterTypes()))) {
} m.setAccessible(true);
} return m;
return null; }
} }
return null;
}
private boolean ClassListEqual(Class<?>[] l1, Class<?>[] l2) { private boolean ClassListEqual(Class<?>[] l1, Class<?>[] l2) {
boolean equal = true; boolean equal = true;
if (l1.length != l2.length) { if (l1.length != l2.length) {
return false; return false;
} }
for (int i = 0; i < l1.length; i++) { for (int i = 0; i < l1.length; i++) {
if (l1[i] != l2[i]) { if (l1[i] != l2[i]) {
equal = false; equal = false;
break; break;
} }
} }
return equal; return equal;
} }
} }

View File

@ -1,205 +1,215 @@
package com.intellectualcrafters.plot; 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.Arrays;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap; 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 { public class UUIDHandler {
private static ConcurrentHashMap<String, UUID> uuidMap = new ConcurrentHashMap<>(); private static ConcurrentHashMap<String, UUID> uuidMap = new ConcurrentHashMap<>();
public static boolean uuidExists(UUID uuid) { public static boolean uuidExists(UUID uuid) {
return uuidMap.containsValue(uuid); return uuidMap.containsValue(uuid);
} }
public static boolean nameExists(String name) { public static boolean nameExists(String name) {
return uuidMap.containsKey(name); return uuidMap.containsKey(name);
} }
public static void add(String name, UUID uuid) { public static void add(String name, UUID uuid) {
uuidMap.put(name, uuid); uuidMap.put(name, uuid);
} }
/** /**
* *
* @param plugin * @param plugin
*/ */
public static void startFetch(JavaPlugin plugin) { public static void startFetch(JavaPlugin plugin) {
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() { plugin.getServer().getScheduler()
@Override .runTaskAsynchronously(plugin, new Runnable() {
public void run() { @Override
OfflinePlayer[] offlinePlayers = Bukkit.getOfflinePlayers(); public void run() {
int lenght = offlinePlayers.length; OfflinePlayer[] offlinePlayers = Bukkit
long start = System.currentTimeMillis(); .getOfflinePlayers();
int lenght = offlinePlayers.length;
long start = System.currentTimeMillis();
String name; String name;
UUID uuid; UUID uuid;
for(OfflinePlayer player : offlinePlayers) { for (OfflinePlayer player : offlinePlayers) {
name = player.getName(); name = player.getName();
uuid = player.getUniqueId(); uuid = player.getUniqueId();
if(!uuidExists(uuid)) if (!uuidExists(uuid)) {
add(name, uuid); add(name, uuid);
} }
}
long time = System.currentTimeMillis() - start; long time = System.currentTimeMillis() - start;
PlotMain.sendConsoleSenderMessage("&cFinished caching of offlineplayers! Took &6" + time + "&cms, &6" + lenght + " &cUUID's were cached" + PlotMain.sendConsoleSenderMessage("&cFinished caching of offlineplayers! Took &6"
" and there is now a grand total of &6" + uuidMap.size() + " &ccached."); + time
} + "&cms, &6"
}); + lenght
} + " &cUUID's were cached"
+ " and there is now a grand total of &6"
+ uuidMap.size() + " &ccached.");
}
});
}
/** /**
* *
* @param name * @param name
* @return * @return
*/ */
public static UUID getUUID(String name) { public static UUID getUUID(String name) {
if (nameExists(name)) { if (nameExists(name)) {
return uuidMap.get(name); return uuidMap.get(name);
} }
UUID uuid; UUID uuid;
if ((uuid = getUuidOnlinePlayer(name)) != null) { if ((uuid = getUuidOnlinePlayer(name)) != null) {
return uuid; return uuid;
} }
if ((uuid = getUuidOfflinePlayer(name)) != null) { if ((uuid = getUuidOfflinePlayer(name)) != null) {
return uuid; return uuid;
} }
if(Bukkit.getOnlineMode()) { if (Bukkit.getOnlineMode()) {
try { try {
UUIDFetcher fetcher = new UUIDFetcher(Arrays.asList(name)); UUIDFetcher fetcher = new UUIDFetcher(Arrays.asList(name));
uuid = fetcher.call().get(name); uuid = fetcher.call().get(name);
add(name, uuid); add(name, uuid);
} catch(Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} else { } else {
return getUuidOfflineMode(name); return getUuidOfflineMode(name);
} }
return null; return null;
} }
/** /**
* *
* @param uuid * @param uuid
* @return * @return
*/ */
private static String loopSearch(UUID uuid) { private static String loopSearch(UUID uuid) {
for(Map.Entry<String, UUID> entry : uuidMap.entrySet()) { for (Map.Entry<String, UUID> entry : uuidMap.entrySet()) {
if(entry.getValue().equals(uuid)) { if (entry.getValue().equals(uuid)) {
return entry.getKey(); return entry.getKey();
} }
} }
return ""; return "";
} }
/** /**
* *
* @param uuid * @param uuid
* @return * @return
*/ */
public static String getName(UUID uuid) { public static String getName(UUID uuid) {
if(uuidExists(uuid)) { if (uuidExists(uuid)) {
return loopSearch(uuid); return loopSearch(uuid);
} }
String name; String name;
if ((name = getNameOnlinePlayer(uuid)) != null) { if ((name = getNameOnlinePlayer(uuid)) != null) {
return name; return name;
} }
if ((name = getNameOfflinePlayer(uuid)) != null) { if ((name = getNameOfflinePlayer(uuid)) != null) {
return name; return name;
} }
if (Bukkit.getOnlineMode()) { if (Bukkit.getOnlineMode()) {
try { try {
NameFetcher fetcher = new NameFetcher(Arrays.asList(uuid)); NameFetcher fetcher = new NameFetcher(Arrays.asList(uuid));
name = fetcher.call().get(uuid); name = fetcher.call().get(uuid);
add(name, uuid); add(name, uuid);
return name; return name;
} catch(Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} else { } else {
return "unknown"; return "unknown";
} }
return ""; return "";
} }
/** /**
* *
* @param name * @param name
* @return * @return
*/ */
private static UUID getUuidOfflineMode(String name) { private static UUID getUuidOfflineMode(String name) {
UUID uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8)); UUID uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name)
add(name, uuid); .getBytes(Charsets.UTF_8));
return uuid; add(name, uuid);
} return uuid;
}
/** /**
* *
* @param uuid * @param uuid
* @return * @return
*/ */
private static String getNameOnlinePlayer(UUID uuid) { private static String getNameOnlinePlayer(UUID uuid) {
Player player = Bukkit.getPlayer(uuid); Player player = Bukkit.getPlayer(uuid);
if(player == null || !player.isOnline()) { if (player == null || !player.isOnline()) {
return null; return null;
} }
String name = player.getName(); String name = player.getName();
add(name, uuid); add(name, uuid);
return name; return name;
} }
/** /**
* *
* @param uuid * @param uuid
* @return * @return
*/ */
private static String getNameOfflinePlayer(UUID uuid) { private static String getNameOfflinePlayer(UUID uuid) {
OfflinePlayer player = Bukkit.getOfflinePlayer(uuid); OfflinePlayer player = Bukkit.getOfflinePlayer(uuid);
if (player == null || !player.hasPlayedBefore()) { if (player == null || !player.hasPlayedBefore()) {
return null; return null;
} }
String name = player.getName(); String name = player.getName();
add(name, uuid); add(name, uuid);
return name; return name;
} }
/** /**
* *
* @param name * @param name
* @return * @return
*/ */
private static UUID getUuidOnlinePlayer(String name) { private static UUID getUuidOnlinePlayer(String name) {
Player player = Bukkit.getPlayer(name); Player player = Bukkit.getPlayer(name);
if (player == null || !player.isOnline()) { if (player == null || !player.isOnline()) {
return null; return null;
} }
UUID uuid = player.getUniqueId(); UUID uuid = player.getUniqueId();
add(name, uuid); add(name, uuid);
return uuid; return uuid;
} }
/** /**
* *
* @param name * @param name
* @return * @return
*/ */
private static UUID getUuidOfflinePlayer(String name) { private static UUID getUuidOfflinePlayer(String name) {
OfflinePlayer player = Bukkit.getOfflinePlayer(name); OfflinePlayer player = Bukkit.getOfflinePlayer(name);
if (player == null || !player.hasPlayedBefore()) { if (player == null || !player.hasPlayedBefore()) {
return null; return null;
} }
UUID uuid = player.getUniqueId(); UUID uuid = player.getUniqueId();
add(name, uuid); add(name, uuid);
return uuid; return uuid;
} }
} }

View File

@ -38,285 +38,288 @@ import com.intellectualcrafters.plot.commands.SubCommand;
@SuppressWarnings({ "unused", "javadoc" }) @SuppressWarnings({ "unused", "javadoc" })
public class PlotAPI { public class PlotAPI {
// To access plotMain stuff. // To access plotMain stuff.
private PlotMain plotMain; private PlotMain plotMain;
// Reference // Reference
public static final String ADMIN_PERMISSION = "plots.admin"; public static final String ADMIN_PERMISSION = "plots.admin";
/** /**
* Constructor. Insert any Plugin. * Constructor. Insert any Plugin.
* *
* @param plugin * @param plugin
*/ */
public PlotAPI(JavaPlugin plugin) { public PlotAPI(JavaPlugin plugin) {
this.plotMain = JavaPlugin.getPlugin(PlotMain.class); this.plotMain = JavaPlugin.getPlugin(PlotMain.class);
} }
/** /**
* Send a message to a player. * Send a message to a player.
* *
* @param player * @param player
* @param c * @param c
* (Caption) * (Caption)
*/ */
public void sendMessage(Player player, C c) { public void sendMessage(Player player, C c) {
PlayerFunctions.sendMessage(player, c); PlayerFunctions.sendMessage(player, c);
} }
/** /**
* Send a message to a player. * Send a message to a player.
* *
* @param player * @param player
* @param string * @param string
*/ */
public void sendMessage(Player player, String string) { public void sendMessage(Player player, String string) {
PlayerFunctions.sendMessage(player, string); PlayerFunctions.sendMessage(player, string);
} }
/** /**
* Send a message to the console. * Send a message to the console.
* *
* @param msg * @param msg
*/ */
public void sendConsoleMessage(String msg) { public void sendConsoleMessage(String msg) {
PlotMain.sendConsoleSenderMessage(msg); PlotMain.sendConsoleSenderMessage(msg);
} }
/** /**
* Send a message to the console * Send a message to the console
* *
* @param c * @param c
* (Caption) * (Caption)
*/ */
public void sendConsoleMessage(C c) { public void sendConsoleMessage(C c) {
sendConsoleMessage(c.s()); sendConsoleMessage(c.s());
} }
/** /**
* Register a flag for use in plots * Register a flag for use in plots
* *
* @param flag * @param flag
*/ */
public void addFlag(AbstractFlag flag) { public void addFlag(AbstractFlag flag) {
FlagManager.addFlag(flag); FlagManager.addFlag(flag);
} }
/** /**
* get all the currently registered flags * get all the currently registered flags
* *
* @return array of Flag[] * @return array of Flag[]
*/ */
public AbstractFlag[] getFlags() { public AbstractFlag[] getFlags() {
return FlagManager.getFlags().toArray(new AbstractFlag[0]); return FlagManager.getFlags().toArray(new AbstractFlag[0]);
} }
/** /**
* Get a plot based on the ID * Get a plot based on the ID
* *
* @param world * @param world
* @param x * @param x
* @param z * @param z
* @return plot, null if ID is wrong * @return plot, null if ID is wrong
*/ */
public Plot getPlot(World world, int x, int z) { public Plot getPlot(World world, int x, int z) {
return PlotHelper.getPlot(world, new PlotId(x, z)); return PlotHelper.getPlot(world, new PlotId(x, z));
} }
/** /**
* Get a plot based on the location * Get a plot based on the location
* *
* @param l * @param l
* @return plot if found, otherwise it creates a temporary plot- * @return plot if found, otherwise it creates a temporary plot-
*/ */
public Plot getPlot(Location l) { public Plot getPlot(Location l) {
return PlotHelper.getCurrentPlot(l); return PlotHelper.getCurrentPlot(l);
} }
/** /**
* Get a plot based on the player location * Get a plot based on the player location
* *
* @param player * @param player
* @return plot if found, otherwise it creates a temporary plot * @return plot if found, otherwise it creates a temporary plot
*/ */
public Plot getPlot(Player player) { public Plot getPlot(Player player) {
return this.getPlot(player.getLocation()); return this.getPlot(player.getLocation());
} }
/** /**
* Check whether or not a player has a plot * Check whether or not a player has a plot
* *
* @param player * @param player
* @return true if player has a plot, false if not. * @return true if player has a plot, false if not.
*/ */
public boolean hasPlot(World world, Player player) { public boolean hasPlot(World world, Player player) {
return (getPlots(world, player, true) != null) && (getPlots(world, player, true).length > 0); return (getPlots(world, player, true) != null)
} && (getPlots(world, player, true).length > 0);
}
/** /**
* Get all plots for the player * Get all plots for the player
* *
* @param plr * @param plr
* to search for * to search for
* @param just_owner * @param just_owner
* should we just search for owner? Or with rights? * should we just search for owner? Or with rights?
*/ */
public Plot[] getPlots(World world, Player plr, boolean just_owner) { public Plot[] getPlots(World world, Player plr, boolean just_owner) {
ArrayList<Plot> pPlots = new ArrayList<>(); ArrayList<Plot> pPlots = new ArrayList<>();
for (Plot plot : PlotMain.getPlots(world).values()) { for (Plot plot : PlotMain.getPlots(world).values()) {
if (just_owner) { if (just_owner) {
if ((plot.owner != null) && (plot.owner == plr.getUniqueId())) { if ((plot.owner != null) && (plot.owner == plr.getUniqueId())) {
pPlots.add(plot); pPlots.add(plot);
} }
} else { } else {
if (plot.hasRights(plr)) { if (plot.hasRights(plr)) {
pPlots.add(plot); pPlots.add(plot);
} }
} }
} }
return (Plot[]) pPlots.toArray(); return (Plot[]) pPlots.toArray();
} }
/** /**
* Get all plots for the world * Get all plots for the world
* *
* @param world * @param world
* to get plots of * to get plots of
* @return Plot[] - array of plot objects in world * @return Plot[] - array of plot objects in world
*/ */
public Plot[] getPlots(World world) { public Plot[] getPlots(World world) {
return PlotMain.getWorldPlots(world); return PlotMain.getWorldPlots(world);
} }
/** /**
* Get all plot worlds * Get all plot worlds
* *
* @return World[] - array of plot worlds * @return World[] - array of plot worlds
*/ */
public String[] getPlotWorlds() { public String[] getPlotWorlds() {
return PlotMain.getPlotWorlds(); return PlotMain.getPlotWorlds();
} }
/** /**
* Get if plot world * Get if plot world
* *
* @param world * @param world
* (to check if plot world) * (to check if plot world)
* @return boolean (if plot world or not) * @return boolean (if plot world or not)
*/ */
public boolean isPlotWorld(World world) { public boolean isPlotWorld(World world) {
return PlotMain.isPlotWorld(world); return PlotMain.isPlotWorld(world);
} }
/** /**
* Get the settings for a world (settings bundled in PlotWorld class) * Get the settings for a world (settings bundled in PlotWorld class)
* *
* @param world * @param world
* (to get settings of) * (to get settings of)
* @return PlotWorld class for ther world ! will return null if not a plot * @return PlotWorld class for ther world ! will return null if not a plot
* world * world
*/ */
public PlotWorld getWorldSettings(World world) { public PlotWorld getWorldSettings(World world) {
return PlotMain.getWorldSettings(world); return PlotMain.getWorldSettings(world);
} }
/** /**
* Get plot locations * Get plot locations
* *
* @param p * @param p
* @return [0] = bottomLc, [1] = topLoc, [2] = home * @return [0] = bottomLc, [1] = topLoc, [2] = home
*/ */
public Location[] getLocations(Plot p) { public Location[] getLocations(Plot p) {
World world = Bukkit.getWorld(p.world); World world = Bukkit.getWorld(p.world);
return new Location[] { PlotHelper.getPlotBottomLoc(world, p.id), PlotHelper.getPlotTopLoc(world, p.id), PlotHelper.getPlotHome(world, p.id) }; return new Location[] { PlotHelper.getPlotBottomLoc(world, p.id),
} PlotHelper.getPlotTopLoc(world, p.id),
PlotHelper.getPlotHome(world, p.id) };
}
/** /**
* Get home location * Get home location
* *
* @param p * @param p
* @return plot bottom location * @return plot bottom location
*/ */
public Location getHomeLocation(Plot p) { public Location getHomeLocation(Plot p) {
return PlotHelper.getPlotHome(p.getWorld(), p.id); return PlotHelper.getPlotHome(p.getWorld(), p.id);
} }
/** /**
* Get Bottom Location * Get Bottom Location
* *
* @param p * @param p
* @return plot bottom location * @return plot bottom location
*/ */
public Location getBottomLocation(Plot p) { public Location getBottomLocation(Plot p) {
World world = Bukkit.getWorld(p.world); World world = Bukkit.getWorld(p.world);
return PlotHelper.getPlotBottomLoc(world, p.id); return PlotHelper.getPlotBottomLoc(world, p.id);
} }
/** /**
* Get Top Location * Get Top Location
* *
* @param p * @param p
* @return plot top location * @return plot top location
*/ */
public Location getTopLocation(Plot p) { public Location getTopLocation(Plot p) {
World world = Bukkit.getWorld(p.world); World world = Bukkit.getWorld(p.world);
return PlotHelper.getPlotTopLoc(world, p.id); return PlotHelper.getPlotTopLoc(world, p.id);
} }
/** /**
* Check whether or not a player is in a plot * Check whether or not a player is in a plot
* *
* @param player * @param player
* @return true if the player is in a plot, false if not- * @return true if the player is in a plot, false if not-
*/ */
public boolean isInPlot(Player player) { public boolean isInPlot(Player player) {
return PlayerFunctions.isInPlot(player); return PlayerFunctions.isInPlot(player);
} }
/** /**
* Register a subcommand * Register a subcommand
* *
* @param c * @param c
*/ */
public void registerCommand(SubCommand c) { public void registerCommand(SubCommand c) {
MainCommand.subCommands.add(c); MainCommand.subCommands.add(c);
} }
/** /**
* Get the plotMain class * Get the plotMain class
* *
* @return PlotMain Class * @return PlotMain Class
*/ */
public PlotMain getPlotMain() { public PlotMain getPlotMain() {
return this.plotMain; return this.plotMain;
} }
/** /**
* Get the player plot count * Get the player plot count
* *
* @param player * @param player
* @return * @return
*/ */
public int getPlayerPlotCount(World world, Player player) { public int getPlayerPlotCount(World world, Player player) {
return PlayerFunctions.getPlayerPlotCount(world, player); return PlayerFunctions.getPlayerPlotCount(world, player);
} }
/** /**
* Get a players plots * Get a players plots
* *
* @param player * @param player
* @return a set containing the players plots * @return a set containing the players plots
*/ */
public Set<Plot> getPlayerPlots(World world, Player player) { public Set<Plot> getPlayerPlots(World world, Player player) {
return PlayerFunctions.getPlayerPlots(world, player); return PlayerFunctions.getPlayerPlots(world, player);
} }
/** /**
* Get the allowed plot count for a player * Get the allowed plot count for a player
* *
* @param player * @param player
* @return the number of allowed plots * @return the number of allowed plots
*/ */
public int getAllowedPlots(Player player) { public int getAllowedPlots(Player player) {
return PlayerFunctions.getAllowedPlots(player); return PlayerFunctions.getAllowedPlots(player);
} }
} }

View File

@ -8,156 +8,172 @@
*/ */
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.*;
import net.milkbowl.vault.economy.Economy; import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.entity.Player; 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") @SuppressWarnings("deprecation")
public class Auto extends SubCommand { public class Auto extends SubCommand {
public Auto() { public Auto() {
super("auto", "plots.auto", "Claim the nearest plot", "auto", "a", CommandCategory.CLAIMING); super("auto", "plots.auto", "Claim the nearest plot", "auto", "a",
} CommandCategory.CLAIMING);
}
// TODO auto claim a mega plot!!!!!!!!!!!! // TODO auto claim a mega plot!!!!!!!!!!!!
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(Player plr, String... args) {
World world; World world;
int size_x = 1; int size_x = 1;
int size_z = 1; int size_z = 1;
String schematic = ""; String schematic = "";
if (PlotMain.getPlotWorlds().length == 1) { if (PlotMain.getPlotWorlds().length == 1) {
world = Bukkit.getWorld(PlotMain.getPlotWorlds()[0]); world = Bukkit.getWorld(PlotMain.getPlotWorlds()[0]);
} else { } else {
if (PlotMain.isPlotWorld(plr.getWorld())) { if (PlotMain.isPlotWorld(plr.getWorld())) {
world = plr.getWorld(); world = plr.getWorld();
} else { } else {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD); PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD);
return false; return false;
} }
} }
if (args.length > 0) { if (args.length > 0) {
if (PlotMain.hasPermission(plr, "plots.auto.mega")) { if (PlotMain.hasPermission(plr, "plots.auto.mega")) {
try { try {
String[] split = args[0].split(","); String[] split = args[0].split(",");
size_x = Integer.parseInt(split[0]); size_x = Integer.parseInt(split[0]);
size_z = Integer.parseInt(split[1]); size_z = Integer.parseInt(split[1]);
if ((size_x < 1) || (size_z < 1)) { if ((size_x < 1) || (size_z < 1)) {
PlayerFunctions.sendMessage(plr, "&cError: size<=0"); PlayerFunctions.sendMessage(plr, "&cError: size<=0");
} }
if ((size_x > 4) || (size_z > 4)) { if ((size_x > 4) || (size_z > 4)) {
PlayerFunctions.sendMessage(plr, "&cError: size>4"); PlayerFunctions.sendMessage(plr, "&cError: size>4");
} }
if(args.length > 1) { if (args.length > 1) {
schematic = args[1]; schematic = args[1];
} }
} catch (Exception e) { } catch (Exception e) {
schematic = args[0]; schematic = args[0];
//PlayerFunctions.sendMessage(plr, "&cError: Invalid size (X,Y)"); // PlayerFunctions.sendMessage(plr,
//return false; // "&cError: Invalid size (X,Y)");
} // return false;
} else { }
schematic = args[0]; } else {
//PlayerFunctions.sendMessage(plr, C.NO_PERMISSION); schematic = args[0];
//return false; // PlayerFunctions.sendMessage(plr, C.NO_PERMISSION);
} // return false;
} }
if (PlayerFunctions.getPlayerPlotCount(world, plr) >= PlayerFunctions.getAllowedPlots(plr)) { }
PlayerFunctions.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS); if (PlayerFunctions.getPlayerPlotCount(world, plr) >= PlayerFunctions
return false; .getAllowedPlots(plr)) {
} PlayerFunctions.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS);
PlotWorld pWorld = PlotMain.getWorldSettings(world); return false;
if(PlotMain.useEconomy && pWorld.USE_ECONOMY) { }
double cost = pWorld.PLOT_PRICE; PlotWorld pWorld = PlotMain.getWorldSettings(world);
cost = (size_x * size_z) * cost; if (PlotMain.useEconomy && pWorld.USE_ECONOMY) {
if (cost > 0d) { double cost = pWorld.PLOT_PRICE;
Economy economy = PlotMain.economy; cost = (size_x * size_z) * cost;
if (economy.getBalance(plr) < cost) { if (cost > 0d) {
sendMessage(plr, C.CANNOT_AFFORD_PLOT, "" + cost); Economy economy = PlotMain.economy;
return true; if (economy.getBalance(plr) < cost) {
} sendMessage(plr, C.CANNOT_AFFORD_PLOT, "" + cost);
economy.withdrawPlayer(plr, cost); return true;
sendMessage(plr, C.REMOVED_BALANCE, cost + ""); }
} economy.withdrawPlayer(plr, cost);
} sendMessage(plr, C.REMOVED_BALANCE, cost + "");
if(!schematic.equals("")) { }
if (pWorld.SCHEMATIC_CLAIM_SPECIFY) { }
if(pWorld.SCHEMATICS.contains(schematic.toLowerCase())) { if (!schematic.equals("")) {
sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent: " + schematic); if (pWorld.SCHEMATIC_CLAIM_SPECIFY) {
return true; if (pWorld.SCHEMATICS.contains(schematic.toLowerCase())) {
} sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent: "
if (!plr.hasPermission("plots.claim." + schematic) && !plr.hasPermission("plots.admin")) { + schematic);
PlayerFunctions.sendMessage(plr, C.NO_SCHEMATIC_PERMISSION, schematic); return true;
return true; }
} if (!plr.hasPermission("plots.claim." + schematic)
} && !plr.hasPermission("plots.admin")) {
} PlayerFunctions.sendMessage(plr, C.NO_SCHEMATIC_PERMISSION,
boolean br = false; schematic);
int x = 0, z = 0, q = 100; return true;
PlotId id; }
if ((size_x == 1) && (size_z == 1)) { }
while (!br) { }
id = new PlotId(x, z); boolean br = false;
if (PlotHelper.getPlot(world, id).owner == null) { int x = 0, z = 0, q = 100;
Plot plot = PlotHelper.getPlot(world, id); PlotId id;
boolean result = Claim.claimPlot(plr, plot, true); if ((size_x == 1) && (size_z == 1)) {
br = !result; while (!br) {
} id = new PlotId(x, z);
if ((z < q) && ((z - x) < q)) { if (PlotHelper.getPlot(world, id).owner == null) {
z++; Plot plot = PlotHelper.getPlot(world, id);
} else if (x < q) { boolean result = Claim.claimPlot(plr, plot, true);
x++; br = !result;
z = q - 100; }
} else { if ((z < q) && ((z - x) < q)) {
q += 100; z++;
x = q; } else if (x < q) {
z = q; x++;
} z = q - 100;
} } else {
} else { q += 100;
while (!br) { x = q;
PlotId start = new PlotId(x, z); z = q;
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++) { } else {
for (int j = start.y; j <= end.y; j++) { while (!br) {
Plot plot = PlotHelper.getPlot(world, new PlotId(i, j)); PlotId start = new PlotId(x, z);
boolean teleport = ((i == end.x) && (j == end.y)); PlotId end = new PlotId((x + size_x) - 1, (z + size_z) - 1);
Claim.claimPlot(plr, plot, teleport); if (isUnowned(world, start, end)) {
} for (int i = start.x; i <= end.x; i++) {
} for (int j = start.y; j <= end.y; j++) {
if(!PlotHelper.mergePlots(plr, world, PlayerFunctions.getPlotSelectionIds(world, start, end))) { Plot plot = PlotHelper.getPlot(world, new PlotId(i,
return false; j));
} boolean teleport = ((i == end.x) && (j == end.y));
br = true; Claim.claimPlot(plr, plot, teleport);
} }
if ((z < q) && ((z - x) < q)) { }
z += size_z; if (!PlotHelper.mergePlots(plr, world, PlayerFunctions
} else if (x < q) { .getPlotSelectionIds(world, start, end))) {
x += size_x; return false;
z = q - 100; }
} else { br = true;
q += 100; }
x = q; if ((z < q) && ((z - x) < q)) {
z = q; z += size_z;
} } else if (x < q) {
} x += size_x;
} z = q - 100;
return true; } else {
} q += 100;
x = q;
z = q;
}
}
}
return true;
}
public boolean isUnowned(World world, PlotId pos1, PlotId pos2) { public boolean isUnowned(World world, PlotId pos1, PlotId pos2) {
for (int x = pos1.x; x <= pos2.x; x++) { for (int x = pos1.x; x <= pos2.x; x++) {
for (int y = pos1.y; y <= pos2.y; y++) { for (int y = pos1.y; y <= pos2.y; y++) {
PlotId id = new PlotId(x, y); PlotId id = new PlotId(x, y);
if (PlotMain.getPlots(world).get(id) != null) { if (PlotMain.getPlots(world).get(id) != null) {
if (PlotMain.getPlots(world).get(id).owner != null) { if (PlotMain.getPlots(world).get(id).owner != null) {
return false; return false;
} }
} }
} }
} }
return true; return true;
} }
} }

View File

@ -17,78 +17,78 @@ import com.intellectualcrafters.plot.C;
import com.intellectualcrafters.plot.PlayerFunctions; import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.Plot; import com.intellectualcrafters.plot.Plot;
import com.intellectualcrafters.plot.PlotHelper; import com.intellectualcrafters.plot.PlotHelper;
import com.intellectualcrafters.plot.PlotMain;
import com.intellectualcrafters.plot.PlotWorld;
/** /**
* Created by Citymonstret on 2014-08-15. * Created by Citymonstret on 2014-08-15.
*/ */
public class Camera extends SubCommand implements Listener { public class Camera extends SubCommand implements Listener {
private CameraAPI api; private CameraAPI api;
public Camera() { public Camera() {
super("camera", "plots.camera", "Go into camera mode", "camera", "c", CommandCategory.TELEPORT); super("camera", "plots.camera", "Go into camera mode", "camera", "c",
this.api = CameraAPI.getInstance(); CommandCategory.TELEPORT);
this.travelers = new ArrayList<String>(); this.api = CameraAPI.getInstance();
} this.travelers = new ArrayList<String>();
}
private ArrayList<String> travelers; private ArrayList<String> travelers;
@Override @Override
public boolean execute(Player player, String... args) { public boolean execute(Player player, String... args) {
if (!PlayerFunctions.isInPlot(player)) { if (!PlayerFunctions.isInPlot(player)) {
PlayerFunctions.sendMessage(player, C.NOT_IN_PLOT); PlayerFunctions.sendMessage(player, C.NOT_IN_PLOT);
return false; return false;
} }
this.api = CameraAPI.getInstance(); this.api = CameraAPI.getInstance();
Plot plot = PlotHelper.getCurrentPlot(player.getLocation()); Plot plot = PlotHelper.getCurrentPlot(player.getLocation());
if (this.api.isTravelling(player)) { if (this.api.isTravelling(player)) {
this.api.stopTravel(player); this.api.stopTravel(player);
PlayerFunctions.sendMessage(player, C.CAMERA_STOPPED); PlayerFunctions.sendMessage(player, C.CAMERA_STOPPED);
return true; return true;
} }
this.api.travel(getController(player, plot)); this.api.travel(getController(player, plot));
PlayerFunctions.sendMessage(player, C.CAMERA_STARTED, plot.getId().x + ";" + plot.getId().y); PlayerFunctions.sendMessage(player, C.CAMERA_STARTED, plot.getId().x
this.travelers.add(player.getName()); + ";" + plot.getId().y);
return true; this.travelers.add(player.getName());
} return true;
}
@EventHandler @EventHandler
public void onTravelEnded(TravelEndEvent event) { public void onTravelEnded(TravelEndEvent event) {
if (this.travelers.contains(event.getPlayer().getName())) { if (this.travelers.contains(event.getPlayer().getName())) {
this.travelers.remove(event.getPlayer().getName()); this.travelers.remove(event.getPlayer().getName());
PlayerFunctions.sendMessage(event.getPlayer(), C.CAMERA_STOPPED); PlayerFunctions.sendMessage(event.getPlayer(), C.CAMERA_STOPPED);
} }
if (this.travelers.contains(event.getPlayer().getName())) { if (this.travelers.contains(event.getPlayer().getName())) {
event.getHandlers().bake(); event.getHandlers().bake();
} }
} }
public CameraController getController(Player player, Plot plot) { public CameraController getController(Player player, Plot plot) {
World w = Bukkit.getWorld(plot.world); World w = Bukkit.getWorld(plot.world);
PlotWorld plotworld = PlotMain.getWorldSettings(w); int seconds = PlotHelper.getPlotWidth(w, plot.id) * 5;
int seconds = plotworld.PLOT_WIDTH * 5; Location loc1, loc2, loc3, loc4, loc5;
Location loc1, loc2, loc3, loc4, loc5; double y = player.getLocation().getY();
double y = player.getLocation().getY(); Location bottomLoc = PlotHelper.getPlotBottomLoc(w, plot.id);
Location bottomLoc = PlotHelper.getPlotBottomLoc(w, plot.id); Location topLoc = PlotHelper.getPlotTopLoc(w, plot.id);
Location topLoc = PlotHelper.getPlotTopLoc(w, plot.id); World world = bottomLoc.getWorld();
World world = bottomLoc.getWorld(); int maxX = Math.max(bottomLoc.getBlockX(), topLoc.getBlockX());
int maxX = Math.max(bottomLoc.getBlockX(), topLoc.getBlockX()); int maxZ = Math.max(bottomLoc.getBlockZ(), topLoc.getBlockZ());
int maxZ = Math.max(bottomLoc.getBlockZ(), topLoc.getBlockZ()); int minX = Math.min(bottomLoc.getBlockX(), topLoc.getBlockX());
int minX = Math.min(bottomLoc.getBlockX(), topLoc.getBlockX()); int minZ = Math.min(bottomLoc.getBlockZ(), topLoc.getBlockZ());
int minZ = Math.min(bottomLoc.getBlockZ(), topLoc.getBlockZ()); loc1 = new Location(world, maxX, y, maxZ);
loc1 = new Location(world, maxX, y, maxZ); loc2 = new Location(world, maxX, y, minZ);
loc2 = new Location(world, maxX, y, minZ); loc3 = new Location(world, minX, y, minZ);
loc3 = new Location(world, minX, y, minZ); loc4 = new Location(world, minX, y, maxZ);
loc4 = new Location(world, minX, y, maxZ); loc1.setYaw(((3 / 4.0F) * 360.0F) - 0.5F);
loc1.setYaw(((3 / 4.0F) * 360.0F) - 0.5F); loc3.setYaw(((1 / 4.0F) * 360.0F) - 0.5F);
loc3.setYaw(((1 / 4.0F) * 360.0F) - 0.5F); loc4.setYaw(((2 / 4.0F) * 360.0F) - 0.5F);
loc4.setYaw(((2 / 4.0F) * 360.0F) - 0.5F); loc2.setYaw(((0 / 4.0F) * 360.0F) - 0.5F);
loc2.setYaw(((0 / 4.0F) * 360.0F) - 0.5F); loc5 = loc1.clone();
loc5 = loc1.clone(); CameraController controller = this.api.createController(player,
CameraController controller = this.api.createController(player, seconds, loc1, loc2, loc3, loc4, loc5); seconds, loc1, loc2, loc3, loc4, loc5);
return controller; return controller;
} }
} }

View File

@ -15,6 +15,7 @@ import org.bukkit.Bukkit;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.intellectualcrafters.plot.C; import com.intellectualcrafters.plot.C;
import com.intellectualcrafters.plot.FlagManager;
import com.intellectualcrafters.plot.PlayerFunctions; import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.Plot; import com.intellectualcrafters.plot.Plot;
import com.intellectualcrafters.plot.PlotHelper; import com.intellectualcrafters.plot.PlotHelper;
@ -30,93 +31,100 @@ import com.intellectualcrafters.plot.events.PlayerClaimPlotEvent;
*/ */
public class Claim extends SubCommand { public class Claim extends SubCommand {
public Claim() { public Claim() {
super(Command.CLAIM, "Claim the current plot you're standing on.", "claim", CommandCategory.CLAIMING); super(Command.CLAIM, "Claim the current plot you're standing on.",
} "claim", CommandCategory.CLAIMING);
}
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(Player plr, String... args) {
String schematic = ""; String schematic = "";
if (args.length >= 1) { if (args.length >= 1) {
schematic = args[0]; schematic = args[0];
} }
if (!PlayerFunctions.isInPlot(plr)) { if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
return true; return true;
} }
if (PlayerFunctions.getPlayerPlotCount(plr.getWorld(), plr) >= PlayerFunctions.getAllowedPlots(plr)) { if (PlayerFunctions.getPlayerPlotCount(plr.getWorld(), plr) >= PlayerFunctions
PlayerFunctions.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS); .getAllowedPlots(plr)) {
return true; PlayerFunctions.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS);
} return true;
Plot plot = PlayerFunctions.getCurrentPlot(plr); }
if (plot.hasOwner()) { Plot plot = PlayerFunctions.getCurrentPlot(plr);
PlayerFunctions.sendMessage(plr, C.PLOT_IS_CLAIMED); if (plot.hasOwner()) {
return false; PlayerFunctions.sendMessage(plr, C.PLOT_IS_CLAIMED);
} return false;
PlotWorld world = PlotMain.getWorldSettings(plot.getWorld()); }
if (PlotMain.useEconomy && world.USE_ECONOMY) { PlotWorld world = PlotMain.getWorldSettings(plot.getWorld());
double cost = world.PLOT_PRICE; if (PlotMain.useEconomy && world.USE_ECONOMY) {
if (cost > 0d) { double cost = world.PLOT_PRICE;
Economy economy = PlotMain.economy; if (cost > 0d) {
if (economy.getBalance(plr) < cost) { Economy economy = PlotMain.economy;
sendMessage(plr, C.CANNOT_AFFORD_PLOT, "" + cost); if (economy.getBalance(plr) < cost) {
return true; sendMessage(plr, C.CANNOT_AFFORD_PLOT, "" + cost);
} return true;
economy.withdrawPlayer(plr, cost); }
sendMessage(plr, C.REMOVED_BALANCE, cost + ""); economy.withdrawPlayer(plr, cost);
} sendMessage(plr, C.REMOVED_BALANCE, cost + "");
} }
if (!schematic.equals("")) { }
if (world.SCHEMATIC_CLAIM_SPECIFY) { if (!schematic.equals("")) {
if (!world.SCHEMATICS.contains(schematic.toLowerCase())) { if (world.SCHEMATIC_CLAIM_SPECIFY) {
sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent: " + schematic); if (!world.SCHEMATICS.contains(schematic.toLowerCase())) {
return true; sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent: "
} + schematic);
if (!plr.hasPermission("plots.claim." + schematic) && !plr.hasPermission("plots.admin")) { return true;
PlayerFunctions.sendMessage(plr, C.NO_SCHEMATIC_PERMISSION, schematic); }
return true; if (!plr.hasPermission("plots.claim." + schematic)
} && !plr.hasPermission("plots.admin")) {
} PlayerFunctions.sendMessage(plr, C.NO_SCHEMATIC_PERMISSION,
} schematic);
boolean result = claimPlot(plr, plot, false, schematic); return true;
if (result) { }
PlayerFunctions.sendMessage(plr, C.PLOT_NOT_CLAIMED); }
return false; }
} boolean result = claimPlot(plr, plot, false, schematic);
return true; if (result) {
PlayerFunctions.sendMessage(plr, C.PLOT_NOT_CLAIMED);
return false;
}
return true;
} }
public static boolean claimPlot(Player player, Plot plot, boolean teleport) { public static boolean claimPlot(Player player, Plot plot, boolean teleport) {
return claimPlot(player, plot, teleport, ""); return claimPlot(player, plot, teleport, "");
} }
public static boolean claimPlot(Player player, Plot plot, boolean teleport, String schematic) { public static boolean claimPlot(Player player, Plot plot, boolean teleport,
PlayerClaimPlotEvent event = new PlayerClaimPlotEvent(player, plot); String schematic) {
Bukkit.getPluginManager().callEvent(event); PlayerClaimPlotEvent event = new PlayerClaimPlotEvent(player, plot);
if (!event.isCancelled()) { Bukkit.getPluginManager().callEvent(event);
PlotHelper.createPlot(player, plot); if (!event.isCancelled()) {
PlotHelper.setSign(player, plot); PlotHelper.createPlot(player, plot);
PlayerFunctions.sendMessage(player, C.CLAIMED); PlotHelper.setSign(player, plot);
if (teleport) { PlayerFunctions.sendMessage(player, C.CLAIMED);
PlotMain.teleportPlayer(player, player.getLocation(), plot); if (teleport) {
} PlotMain.teleportPlayer(player, player.getLocation(), plot);
PlotWorld world = PlotMain.getWorldSettings(plot.getWorld()); }
if (world.SCHEMATIC_ON_CLAIM) { PlotWorld world = PlotMain.getWorldSettings(plot.getWorld());
SchematicHandler handler = new SchematicHandler(); if (world.SCHEMATIC_ON_CLAIM) {
SchematicHandler.Schematic sch; SchematicHandler handler = new SchematicHandler();
if (schematic.equals("")) { SchematicHandler.Schematic sch;
sch = handler.getSchematic(world.SCHEMATIC_FILE); if (schematic.equals("")) {
} else { sch = handler.getSchematic(world.SCHEMATIC_FILE);
sch = handler.getSchematic(schematic); } else {
if (sch == null) { sch = handler.getSchematic(schematic);
sch = handler.getSchematic(world.SCHEMATIC_FILE); if (sch == null) {
} sch = handler.getSchematic(world.SCHEMATIC_FILE);
} }
handler.paste(player.getLocation(), sch, plot); }
} handler.paste(player.getLocation(), sch, plot);
plot.settings.setFlags(PlotMain.getWorldSettings(player.getWorld()).DEFAULT_FLAGS); }
} plot.settings.setFlags(FlagManager.parseFlags(PlotMain
return event.isCancelled(); .getWorldSettings(player.getWorld()).DEFAULT_FLAGS));
} }
return event.isCancelled();
}
} }

View File

@ -20,22 +20,24 @@ import com.intellectualcrafters.plot.Plot;
*/ */
public class Clear extends SubCommand { public class Clear extends SubCommand {
public Clear() { public Clear() {
super(Command.CLEAR, "Clear a plot", "clear", CommandCategory.ACTIONS); super(Command.CLEAR, "Clear a plot", "clear", CommandCategory.ACTIONS);
} }
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(Player plr, String... args) {
if (!PlayerFunctions.isInPlot(plr)) { if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, "You're not in a plot."); PlayerFunctions.sendMessage(plr, "You're not in a plot.");
return false; return false;
} }
Plot plot = PlayerFunctions.getCurrentPlot(plr); Plot plot = PlayerFunctions.getCurrentPlot(plr);
if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId())) && !plr.hasPermission("plots.admin")) { if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(
PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); plr.getUniqueId()))
return false; && !plr.hasPermission("plots.admin")) {
} PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
plot.clear(plr); return false;
return true; }
} plot.clear(plr);
return true;
}
} }

View File

@ -16,162 +16,162 @@ package com.intellectualcrafters.plot.commands;
*/ */
public enum Command { public enum Command {
// TODO new commands // TODO new commands
// (allow a plot to be transferred from one plot to another of the same // (allow a plot to be transferred from one plot to another of the same
// size) // size)
// - /plot copy // - /plot copy
// - /plot paste // - /plot paste
// (economy) // (economy)
// - /plot buy // - /plot buy
// - /plot sell <value> // - /plot sell <value>
// (Rating system) (ratings can be stored as the average, and number of // (Rating system) (ratings can be stored as the average, and number of
// ratings) // ratings)
// - /plot rate <number out of 10> // - /plot rate <number out of 10>
// - /plot list <some parameter to list the most popular, and highest rated // - /plot list <some parameter to list the most popular, and highest rated
// plots> // plots>
TRUSTED("trusted", "trust"), TRUSTED("trusted", "trust"),
/** /**
* *
*/ */
COPY("copy"), COPY("copy"),
/** /**
* *
*/ */
KICK("kick", "k"), KICK("kick", "k"),
/** /**
* *
*/ */
HELPERS("helpers", "hp"), HELPERS("helpers", "hp"),
/** /**
* *
*/ */
DENIED("denied", "dn"), DENIED("denied", "dn"),
/** /**
* *
*/ */
CLAIM("claim", "c"), CLAIM("claim", "c"),
/** /**
* *
*/ */
MERGE("merge", "m"), MERGE("merge", "m"),
/** /**
* *
*/ */
UNLINK("unlink", "u"), UNLINK("unlink", "u"),
/** /**
* *
*/ */
CLEAR("clear", "clear", new CommandPermission("plots.clear")), CLEAR("clear", "clear", new CommandPermission("plots.clear")),
/** /**
* *
*/ */
DELETE("delete", "d", new CommandPermission("plots.delete")), DELETE("delete", "d", new CommandPermission("plots.delete")),
/** /**
* *
*/ */
DEBUG("debug", "database", new CommandPermission("plots.admin")), DEBUG("debug", "database", new CommandPermission("plots.admin")),
/** /**
* *
*/ */
HOME("home", "h"), HOME("home", "h"),
/** /**
* *
*/ */
INFO("info", "i"), INFO("info", "i"),
/** /**
* *
*/ */
LIST("list", "l"), LIST("list", "l"),
/** /**
* *
*/ */
SET("set", "s"), SET("set", "s"),
/** /**
* *
*/ */
SETUP("setup"), SETUP("setup"),
/** /**
* *
*/ */
TP("tp", "tp"); TP("tp", "tp");
/** /**
* *
*/ */
private String command; private String command;
/** /**
* *
*/ */
private String alias; private String alias;
/** /**
* *
*/ */
private CommandPermission permission; private CommandPermission permission;
/** /**
* *
* @param command * @param command
*/ */
Command(String command) { Command(String command) {
this.command = command; this.command = command;
this.alias = command; this.alias = command;
this.permission = new CommandPermission("plots." + command); this.permission = new CommandPermission("plots." + command);
} }
/** /**
* *
* @param command * @param command
* @param permission * @param permission
*/ */
Command(String command, CommandPermission permission) { Command(String command, CommandPermission permission) {
this.command = command; this.command = command;
this.permission = permission; this.permission = permission;
this.alias = command; this.alias = command;
} }
/** /**
* *
* @param command * @param command
* @param alias * @param alias
*/ */
Command(String command, String alias) { Command(String command, String alias) {
this.command = command; this.command = command;
this.alias = alias; this.alias = alias;
this.permission = new CommandPermission("plots." + command); this.permission = new CommandPermission("plots." + command);
} }
/** /**
* *
* @param Command * @param Command
* @param alias * @param alias
* @param permission * @param permission
*/ */
Command(String command, String alias, CommandPermission permission) { Command(String command, String alias, CommandPermission permission) {
this.command = command; this.command = command;
this.alias = alias; this.alias = alias;
this.permission = permission; this.permission = permission;
} }
/** /**
* *
* @return * @return
*/ */
public String getCommand() { public String getCommand() {
return this.command; return this.command;
} }
/** /**
* *
* @return * @return
*/ */
public String getAlias() { public String getAlias() {
return this.alias; return this.alias;
} }
/** /**
* *
* @return * @return
*/ */
public CommandPermission getPermission() { public CommandPermission getPermission() {
return this.permission; return this.permission;
} }
} }

View File

@ -18,24 +18,25 @@ import org.bukkit.entity.Player;
*/ */
public class CommandPermission { public class CommandPermission {
/** /**
* *
*/ */
private String permission; private String permission;
/** /**
* @param permission * @param permission
*/ */
public CommandPermission(String permission) { public CommandPermission(String permission) {
this.permission = permission.toLowerCase(); this.permission = permission.toLowerCase();
} }
/** /**
* *
* @param player * @param player
* @return * @return
*/ */
public boolean hasPermission(Player player) { public boolean hasPermission(Player player) {
return player.hasPermission(this.permission) || player.hasPermission("plots.admin"); return player.hasPermission(this.permission)
} || player.hasPermission("plots.admin");
}
} }

View File

@ -20,22 +20,24 @@ import com.intellectualcrafters.plot.Plot;
*/ */
public class Copy extends SubCommand { public class Copy extends SubCommand {
public Copy() { public Copy() {
super(Command.COPY, "Copy a plot", "clear", CommandCategory.ACTIONS); super(Command.COPY, "Copy a plot", "clear", CommandCategory.ACTIONS);
} }
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(Player plr, String... args) {
if (!PlayerFunctions.isInPlot(plr)) { if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, "You're not in a plot."); PlayerFunctions.sendMessage(plr, "You're not in a plot.");
return false; return false;
} }
Plot plot = PlayerFunctions.getCurrentPlot(plr); Plot plot = PlayerFunctions.getCurrentPlot(plr);
if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId())) && !plr.hasPermission("plots.admin")) { if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(
PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); plr.getUniqueId()))
return false; && !plr.hasPermission("plots.admin")) {
} PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
plot.clear(plr); return false;
return true; }
} plot.clear(plr);
return true;
}
} }

View File

@ -31,92 +31,105 @@ import com.intellectualcrafters.plot.RUtils;
*/ */
public class Debug extends SubCommand { public class Debug extends SubCommand {
// private extends SubCommand^Implements {Command, Information} from // private extends SubCommand^Implements {Command, Information} from
// >>\\S.txt6\\ // >>\\S.txt6\\
public Debug() { public Debug() {
super(Command.DEBUG, "Show debug information", "debug [msg]", CommandCategory.INFO); super(Command.DEBUG, "Show debug information", "debug [msg]",
{ CommandCategory.INFO);
/** {
* This. /**
*/ * This.
} */
} }
}
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(Player plr, String... args) {
PlotMain.getWorldSettings(plr.getWorld()); PlotMain.getWorldSettings(plr.getWorld());
if ((args.length > 0) && args[0].equalsIgnoreCase("msg")) { if ((args.length > 0) && args[0].equalsIgnoreCase("msg")) {
StringBuilder msg = new StringBuilder(); StringBuilder msg = new StringBuilder();
for (C c : C.values()) { for (C c : C.values()) {
msg.append(c.s() + "\n"); msg.append(c.s() + "\n");
} }
PlayerFunctions.sendMessage(plr, msg.toString()); PlayerFunctions.sendMessage(plr, msg.toString());
return true; return true;
} }
StringBuilder information; StringBuilder information;
String header, line, section; String header, line, section;
/** /**
* {$notnull || compile:: \\Debug:Captions\\} * {$notnull || compile:: \\Debug:Captions\\}
*/ */
{ {
information = new StringBuilder(); information = new StringBuilder();
header = C.DEUBG_HEADER.s(); header = C.DEUBG_HEADER.s();
line = C.DEBUG_LINE.s(); line = C.DEBUG_LINE.s();
section = C.DEBUG_SECTION.s(); section = C.DEBUG_SECTION.s();
} }
/** /**
* {||direct:: load: debug::I>Captions::trsl} \\ if(missing) * {||direct:: load: debug::I>Captions::trsl} \\ if(missing)
* set(default) -> this->(){} \\ echo line->line(Compiler.cpp -> * set(default) -> this->(){} \\ echo line->line(Compiler.cpp ->
* lineCompiler); when finished: now = this(); * lineCompiler); when finished: now = this();
* now(getter)->setter(this())->{ "string" = getter(this); * now(getter)->setter(this())->{ "string" = getter(this);
* setter(string) = getter(this->setter); } when ^ finished compile; * setter(string) = getter(this->setter); } when ^ finished compile;
* if(^compile failed -> |this->failed.|tests->failed.| ||run test * if(^compile failed -> |this->failed.|tests->failed.| ||run test
* {this->test}|on fail(action(){return FAILED})| * {this->test}|on fail(action(){return FAILED})|
*/ */
{ {
StringBuilder worlds = new StringBuilder(""); StringBuilder worlds = new StringBuilder("");
for (String world : PlotMain.getPlotWorlds()) { for (String world : PlotMain.getPlotWorlds()) {
worlds.append(world + " "); worlds.append(world + " ");
} }
information.append(header); information.append(header);
information.append(getSection(section, "Lag / TPS")); information.append(getSection(section, "Lag / TPS"));
information.append(getLine(line, "Ticks Per Second", Lag.getTPS())); information.append(getLine(line, "Ticks Per Second", Lag.getTPS()));
information.append(getLine(line, "Lag Percentage", (int) Lag.getPercentage() + "%")); information.append(getLine(line, "Lag Percentage",
information.append(getLine(line, "TPS Percentage", (int) Lag.getFullPercentage() + "%")); (int) Lag.getPercentage() + "%"));
information.append(getSection(section, "PlotWorld")); information.append(getLine(line, "TPS Percentage",
information.append(getLine(line, "Plot Worlds", worlds)); (int) Lag.getFullPercentage() + "%"));
information.append(getLine(line, "Owned Plots", PlotMain.getPlots().size())); information.append(getSection(section, "PlotWorld"));
// information.append(getLine(line, "PlotWorld Size", information.append(getLine(line, "Plot Worlds", worlds));
// PlotHelper.getWorldFolderSize() + "MB")); information.append(getLine(line, "Owned Plots", PlotMain.getPlots()
for (String world : PlotMain.getPlotWorlds()) { .size()));
information.append(getLine(line, "World: " + world + " size", PlotHelper.getWorldFolderSize(Bukkit.getWorld(world)))); // information.append(getLine(line, "PlotWorld Size",
} // PlotHelper.getWorldFolderSize() + "MB"));
information.append(getLine(line, "Entities", PlotHelper.getEntities(plr.getWorld()))); for (String world : PlotMain.getPlotWorlds()) {
information.append(getLine(line, "Loaded Tile Entities", PlotHelper.getTileEntities(plr.getWorld()))); information.append(getLine(line, "World: " + world + " size",
information.append(getLine(line, "Loaded Chunks", PlotHelper.getLoadedChunks(plr.getWorld()))); PlotHelper.getWorldFolderSize(Bukkit.getWorld(world))));
information.append(getSection(section, "RAM")); }
information.append(getLine(line, "Free Ram", RUtils.getFreeRam() + "MB")); information.append(getLine(line, "Entities",
information.append(getLine(line, "Total Ram", RUtils.getTotalRam() + "MB")); PlotHelper.getEntities(plr.getWorld())));
information.append(getSection(section, "Messages")); information.append(getLine(line, "Loaded Tile Entities",
information.append(getLine(line, "Total Messages", C.values().length)); PlotHelper.getTileEntities(plr.getWorld())));
information.append(getLine(line, "View all captions", "/plot debug msg")); information.append(getLine(line, "Loaded Chunks",
} PlotHelper.getLoadedChunks(plr.getWorld())));
/** information.append(getSection(section, "RAM"));
* {function:: SEND_MESSAGE |local player -> plr|local string -> information.append(getLine(line, "Free Ram", RUtils.getFreeRam()
* information.toString())} + "MB"));
*/ information.append(getLine(line, "Total Ram", RUtils.getTotalRam()
{ + "MB"));
PlayerFunctions.sendMessage(plr, information.toString()); information.append(getSection(section, "Messages"));
} information.append(getLine(line, "Total Messages",
return true; 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) { private String getSection(String line, String val) {
return line.replaceAll("%val%", val) + "\n"; return line.replaceAll("%val%", val) + "\n";
} }
private String getLine(String line, String var, Object val) { private String getLine(String line, String var, Object val) {
return line.replaceAll("%var%", var).replaceAll("%val%", "" + val) + "\n"; return line.replaceAll("%var%", var).replaceAll("%val%", "" + val)
} + "\n";
}
} }

View File

@ -9,52 +9,64 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.*;
import com.intellectualcrafters.plot.database.DBFunc;
import net.milkbowl.vault.economy.Economy; import net.milkbowl.vault.economy.Economy;
import org.bukkit.entity.Player; 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. * Created by Citymonstret on 2014-08-01.
*/ */
public class Delete extends SubCommand { public class Delete extends SubCommand {
public Delete() { public Delete() {
super(Command.DELETE, "Delete a plot", "delete", CommandCategory.ACTIONS); super(Command.DELETE, "Delete a plot", "delete",
} CommandCategory.ACTIONS);
}
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(Player plr, String... args) {
if (!PlayerFunctions.isInPlot(plr)) { if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, "You're not in a plot."); PlayerFunctions.sendMessage(plr, "You're not in a plot.");
return false; return false;
} }
Plot plot = PlayerFunctions.getCurrentPlot(plr); Plot plot = PlayerFunctions.getCurrentPlot(plr);
if (!PlayerFunctions.getTopPlot(plr.getWorld(), plot).equals(PlayerFunctions.getBottomPlot(plr.getWorld(), plot))) { if (!PlayerFunctions.getTopPlot(plr.getWorld(), plot).equals(
PlayerFunctions.sendMessage(plr, C.UNLINK_REQUIRED); PlayerFunctions.getBottomPlot(plr.getWorld(), plot))) {
return false; 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); if ((((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(
return false; plr.getUniqueId())))
} && !plr.hasPermission("plots.admin")) {
PlotWorld pWorld = PlotMain.getWorldSettings(plot.getWorld()); PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
if(PlotMain.useEconomy && pWorld.USE_ECONOMY) { return false;
double c = pWorld.SELL_PRICE; }
if(c > 0d) { PlotWorld pWorld = PlotMain.getWorldSettings(plot.getWorld());
Economy economy = PlotMain.economy; if (PlotMain.useEconomy && pWorld.USE_ECONOMY) {
economy.depositPlayer(plr, c); double c = pWorld.SELL_PRICE;
sendMessage(plr, C.ADDED_BALANCE, c + ""); if (c > 0d) {
} Economy economy = PlotMain.economy;
} economy.depositPlayer(plr, c);
boolean result = PlotMain.removePlot(plr.getWorld().getName(), plot.id, true); sendMessage(plr, C.ADDED_BALANCE, c + "");
if (result) { }
PlotHelper.removeSign(plr, plot); }
plot.clear(plr); boolean result = PlotMain.removePlot(plr.getWorld().getName(), plot.id,
DBFunc.delete(plr.getWorld().getName(), plot); true);
} else { if (result) {
PlayerFunctions.sendMessage(plr, "Plot clearing has been denied."); PlotHelper.removeSign(plr, plot);
} plot.clear(plr);
return true; DBFunc.delete(plr.getWorld().getName(), plot);
} } else {
PlayerFunctions.sendMessage(plr, "Plot clearing has been denied.");
}
return true;
}
} }

View File

@ -9,17 +9,17 @@
package com.intellectualcrafters.plot.commands; 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.C;
import com.intellectualcrafters.plot.PlayerFunctions; import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.Plot; import com.intellectualcrafters.plot.Plot;
import com.intellectualcrafters.plot.UUIDHandler; import com.intellectualcrafters.plot.UUIDHandler;
import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.events.PlayerPlotDeniedEvent; 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. * Created by Citymonstret on 2014-08-03.
@ -27,118 +27,100 @@ import java.util.UUID;
@SuppressWarnings("deprecated") @SuppressWarnings("deprecated")
public class Denied extends SubCommand { public class Denied extends SubCommand {
public Denied() { public Denied() {
super(Command.DENIED, "Manage plot helpers", "denied {add|remove} {player}", CommandCategory.ACTIONS); super(Command.DENIED, "Manage plot helpers",
} "denied {add|remove} {player}", CommandCategory.ACTIONS);
}
private boolean hasBeenOnServer(String name) { @Override
Player plr = Bukkit.getPlayer(name); public boolean execute(Player plr, String... args) {
if (plr == null) { if (args.length < 2) {
OfflinePlayer oplr = Bukkit.getPlayer(name); PlayerFunctions.sendMessage(plr, C.DENIED_NEED_ARGUMENT);
if (oplr == null) { return true;
return false; }
} else { if (!PlayerFunctions.isInPlot(plr)) {
return oplr.hasPlayedBefore(); PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
} return true;
} else { }
if (plr.isOnline()) { Plot plot = PlayerFunctions.getCurrentPlot(plr);
return true; if ((plot.owner == null) || !plot.hasRights(plr)) {
} else { PlayerFunctions.sendMessage(plr, C.NO_PERMISSION);
return plr.hasPlayedBefore(); return true;
} }
} if (args[0].equalsIgnoreCase("add")) {
} if (args[1].equalsIgnoreCase("*")) {
UUID uuid = DBFunc.everyone;
@Override plot.addDenied(uuid);
public boolean execute(Player plr, String... args) { DBFunc.setDenied(plr.getWorld().getName(), plot,
if (args.length < 2) { Bukkit.getOfflinePlayer(args[1]));
PlayerFunctions.sendMessage(plr, C.DENIED_NEED_ARGUMENT); PlayerFunctions.sendMessage(plr, C.DENIED_ADDED);
return true; return true;
} }
if (!PlayerFunctions.isInPlot(plr)) { /*
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); * if (!hasBeenOnServer(args[1])) { PlayerFunctions.sendMessage(plr,
return true; * C.PLAYER_HAS_NOT_BEEN_ON); return true; } UUID uuid = null; if
} * ((Bukkit.getPlayer(args[1]) != null)) { uuid =
Plot plot = PlayerFunctions.getCurrentPlot(plr); * Bukkit.getPlayer(args[1]).getUniqueId(); } else { uuid =
if ((plot.owner == null) || !plot.hasRights(plr)) { * Bukkit.getOfflinePlayer(args[1]).getUniqueId(); } if (uuid ==
PlayerFunctions.sendMessage(plr, C.NO_PERMISSION); * null) { PlayerFunctions.sendMessage(plr,
return true; * C.PLAYER_HAS_NOT_BEEN_ON); return true; }
} */
if (args[0].equalsIgnoreCase("add")) { UUID uuid = UUIDHandler.getUUID(args[1]);
if (args[1].equalsIgnoreCase("*")) { plot.addDenied(uuid);
UUID uuid = DBFunc.everyone; DBFunc.setDenied(plr.getWorld().getName(), plot,
plot.addDenied(uuid); Bukkit.getOfflinePlayer(args[1]));
DBFunc.setDenied(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); PlayerPlotDeniedEvent event = new PlayerPlotDeniedEvent(plr, plot,
PlayerFunctions.sendMessage(plr, C.DENIED_ADDED); uuid, true);
return true; Bukkit.getPluginManager().callEvent(event);
} PlayerFunctions.sendMessage(plr, C.DENIED_ADDED);
/*if (!hasBeenOnServer(args[1])) { if ((Bukkit.getPlayer(uuid) != null)
PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); && Bukkit.getPlayer(uuid).isOnline()) {
return true; Plot pl = PlayerFunctions.getCurrentPlot(Bukkit
} .getPlayer((uuid)));
UUID uuid = null; if (pl.id == plot.id) {
if ((Bukkit.getPlayer(args[1]) != null)) { PlayerFunctions.sendMessage(Bukkit.getPlayer(uuid),
uuid = Bukkit.getPlayer(args[1]).getUniqueId(); C.YOU_BE_DENIED);
} else { Bukkit.getPlayer(uuid).teleport(
uuid = Bukkit.getOfflinePlayer(args[1]).getUniqueId(); Bukkit.getPlayer(uuid).getWorld()
} .getSpawnLocation());
if (uuid == null) { }
PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); }
return true; } else if (args[0].equalsIgnoreCase("remove")) {
}*/ if (args[1].equalsIgnoreCase("*")) {
UUID uuid = UUIDHandler.getUUID(args[1]); UUID uuid = DBFunc.everyone;
plot.addDenied(uuid); if (!plot.denied.contains(uuid)) {
DBFunc.setDenied(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED);
PlayerPlotDeniedEvent event = new PlayerPlotDeniedEvent(plr, plot, uuid, true); return true;
Bukkit.getPluginManager().callEvent(event); }
PlayerFunctions.sendMessage(plr, C.DENIED_ADDED); plot.removeDenied(uuid);
if ((Bukkit.getPlayer(uuid) != null) && Bukkit.getPlayer(uuid).isOnline()) { DBFunc.removeDenied(plr.getWorld().getName(), plot,
Plot pl = PlayerFunctions.getCurrentPlot(Bukkit.getPlayer((uuid))); Bukkit.getOfflinePlayer(args[1]));
if (pl.id == plot.id) { PlayerFunctions.sendMessage(plr, C.DENIED_REMOVED);
PlayerFunctions.sendMessage(Bukkit.getPlayer(uuid), C.YOU_BE_DENIED); return true;
Bukkit.getPlayer(uuid).teleport(Bukkit.getPlayer(uuid).getWorld().getSpawnLocation()); }
} /*
} * if (!hasBeenOnServer(args[1])) { PlayerFunctions.sendMessage(plr,
} else if (args[0].equalsIgnoreCase("remove")) { * C.PLAYER_HAS_NOT_BEEN_ON); return true; } UUID uuid = null; if
if (args[1].equalsIgnoreCase("*")) { * (Bukkit.getPlayer(args[1])!=null) { uuid =
UUID uuid = DBFunc.everyone; * Bukkit.getPlayer(args[1]).getUniqueId(); } else { uuid =
if (!plot.denied.contains(uuid)) { * Bukkit.getOfflinePlayer(args[1]).getUniqueId(); } if
PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED); * (!plot.denied.contains(uuid)) { PlayerFunctions.sendMessage(plr,
return true; * C.WAS_NOT_ADDED); return true; } if (uuid == null) {
} * PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON);
plot.removeDenied(uuid); * return true; }
DBFunc.removeDenied(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); */
PlayerFunctions.sendMessage(plr, C.DENIED_REMOVED); UUID uuid = UUIDHandler.getUUID(args[1]);
return true; plot.removeDenied(uuid);
} DBFunc.removeDenied(plr.getWorld().getName(), plot,
/*if (!hasBeenOnServer(args[1])) { Bukkit.getOfflinePlayer(args[1]));
PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); PlayerPlotDeniedEvent event = new PlayerPlotDeniedEvent(plr, plot,
return true; uuid, false);
} Bukkit.getPluginManager().callEvent(event);
UUID uuid = null; PlayerFunctions.sendMessage(plr, C.DENIED_REMOVED);
if (Bukkit.getPlayer(args[1])!=null) { } else {
uuid = Bukkit.getPlayer(args[1]).getUniqueId(); PlayerFunctions.sendMessage(plr, C.DENIED_NEED_ARGUMENT);
} else { return true;
uuid = Bukkit.getOfflinePlayer(args[1]).getUniqueId(); }
} return true;
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;
}
} }

View File

@ -15,12 +15,13 @@ import org.bukkit.entity.Player;
* Created by Citymonstret on 2014-08-11. * Created by Citymonstret on 2014-08-11.
*/ */
public class Help extends SubCommand { public class Help extends SubCommand {
public Help() { public Help() {
super("help", "", "Get this help menu", "help", "he", SubCommand.CommandCategory.INFO); super("help", "", "Get this help menu", "help", "he",
} SubCommand.CommandCategory.INFO);
}
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(Player plr, String... args) {
return false; return false;
} }
} }

View File

@ -9,126 +9,103 @@
package com.intellectualcrafters.plot.commands; 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.C;
import com.intellectualcrafters.plot.PlayerFunctions; import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.Plot; import com.intellectualcrafters.plot.Plot;
import com.intellectualcrafters.plot.UUIDHandler; import com.intellectualcrafters.plot.UUIDHandler;
import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.events.PlayerPlotHelperEvent; 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") @SuppressWarnings("deprecation")
public class Helpers extends SubCommand { public class Helpers extends SubCommand {
public Helpers() { public Helpers() {
super(Command.HELPERS, "Manage plot helpers", "helpers {add|remove} {player}", CommandCategory.ACTIONS); super(Command.HELPERS, "Manage plot helpers",
} "helpers {add|remove} {player}", CommandCategory.ACTIONS);
}
private boolean hasBeenOnServer(String name) { @Override
Player plr = Bukkit.getPlayer(name); public boolean execute(Player plr, String... args) {
if (plr == null) { if (args.length < 2) {
OfflinePlayer oplr = Bukkit.getOfflinePlayer(name); PlayerFunctions.sendMessage(plr, C.HELPER_NEED_ARGUMENT);
if (oplr == null) { return true;
return false; }
} else { if (!PlayerFunctions.isInPlot(plr)) {
return oplr.hasPlayedBefore(); PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
} return true;
} else { }
if (plr.isOnline()) { Plot plot = PlayerFunctions.getCurrentPlot(plr);
return true; if ((plot.owner == null) || !plot.hasRights(plr)) {
} else { PlayerFunctions.sendMessage(plr, C.NO_PERMISSION);
return plr.hasPlayedBefore(); return true;
} }
} if (args[0].equalsIgnoreCase("add")) {
} if (args[1].equalsIgnoreCase("*")) {
UUID uuid = DBFunc.everyone;
@Override plot.addHelper(uuid);
public boolean execute(Player plr, String... args) { DBFunc.setHelper(plr.getWorld().getName(), plot,
if (args.length < 2) { Bukkit.getOfflinePlayer(args[1]));
PlayerFunctions.sendMessage(plr, C.HELPER_NEED_ARGUMENT); PlayerFunctions.sendMessage(plr, C.HELPER_ADDED);
return true; return true;
} }
if (!PlayerFunctions.isInPlot(plr)) { /*
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); * if (!hasBeenOnServer(args[1])) { PlayerFunctions.sendMessage(plr,
return true; * C.PLAYER_HAS_NOT_BEEN_ON); return true; } UUID uuid = null; if
} * ((Bukkit.getPlayer(args[1]) != null)) { uuid =
Plot plot = PlayerFunctions.getCurrentPlot(plr); * Bukkit.getPlayer(args[1]).getUniqueId(); } else { uuid =
if ((plot.owner == null) || !plot.hasRights(plr)) { * Bukkit.getOfflinePlayer(args[1]).getUniqueId(); } if (uuid ==
PlayerFunctions.sendMessage(plr, C.NO_PERMISSION); * null) { PlayerFunctions.sendMessage(plr,
return true; * C.PLAYER_HAS_NOT_BEEN_ON); return true; }
} */
if (args[0].equalsIgnoreCase("add")) { UUID uuid = UUIDHandler.getUUID(args[1]);
if (args[1].equalsIgnoreCase("*")) { plot.addHelper(uuid);
UUID uuid = DBFunc.everyone; DBFunc.setHelper(plr.getWorld().getName(), plot,
plot.addHelper(uuid); Bukkit.getOfflinePlayer(args[1]));
DBFunc.setHelper(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); PlayerPlotHelperEvent event = new PlayerPlotHelperEvent(plr, plot,
PlayerFunctions.sendMessage(plr, C.HELPER_ADDED); uuid, true);
return true; Bukkit.getPluginManager().callEvent(event);
} PlayerFunctions.sendMessage(plr, C.HELPER_ADDED);
/*if (!hasBeenOnServer(args[1])) { } else if (args[0].equalsIgnoreCase("remove")) {
PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); if (args[1].equalsIgnoreCase("*")) {
return true; UUID uuid = DBFunc.everyone;
} if (!plot.helpers.contains(uuid)) {
UUID uuid = null; PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED);
if ((Bukkit.getPlayer(args[1]) != null)) { return true;
uuid = Bukkit.getPlayer(args[1]).getUniqueId(); }
} else { plot.removeHelper(uuid);
uuid = Bukkit.getOfflinePlayer(args[1]).getUniqueId(); DBFunc.removeHelper(plr.getWorld().getName(), plot,
} Bukkit.getOfflinePlayer(args[1]));
if (uuid == null) { PlayerFunctions.sendMessage(plr, C.HELPER_REMOVED);
PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); return true;
return true; }
}*/ /*
UUID uuid = UUIDHandler.getUUID(args[1]); * if (!hasBeenOnServer(args[1])) { PlayerFunctions.sendMessage(plr,
plot.addHelper(uuid); * C.PLAYER_HAS_NOT_BEEN_ON); return true; } UUID uuid = null; if
DBFunc.setHelper(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); * (Bukkit.getPlayer(args[1]) != null) { uuid =
PlayerPlotHelperEvent event = new PlayerPlotHelperEvent(plr, plot, uuid, true); * Bukkit.getPlayer(args[1]).getUniqueId(); } else { uuid =
Bukkit.getPluginManager().callEvent(event); * Bukkit.getOfflinePlayer(args[1]).getUniqueId(); } if (uuid ==
PlayerFunctions.sendMessage(plr, C.HELPER_ADDED); * null) { PlayerFunctions.sendMessage(plr,
} else if (args[0].equalsIgnoreCase("remove")) { * C.PLAYER_HAS_NOT_BEEN_ON); return true; } if
if (args[1].equalsIgnoreCase("*")) { * (!plot.helpers.contains(uuid)) { PlayerFunctions.sendMessage(plr,
UUID uuid = DBFunc.everyone; * C.WAS_NOT_ADDED); return true; }
if (!plot.helpers.contains(uuid)) { */
PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED); UUID uuid = UUIDHandler.getUUID(args[1]);
return true; plot.removeHelper(uuid);
} DBFunc.removeHelper(plr.getWorld().getName(), plot,
plot.removeHelper(uuid); Bukkit.getOfflinePlayer(args[1]));
DBFunc.removeHelper(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); PlayerPlotHelperEvent event = new PlayerPlotHelperEvent(plr, plot,
PlayerFunctions.sendMessage(plr, C.HELPER_REMOVED); uuid, false);
return true; Bukkit.getPluginManager().callEvent(event);
} PlayerFunctions.sendMessage(plr, C.HELPER_REMOVED);
/*if (!hasBeenOnServer(args[1])) { } else {
PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); PlayerFunctions.sendMessage(plr, C.HELPER_NEED_ARGUMENT);
return true; return true;
} }
UUID uuid = null; return true;
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;
}
} }

View File

@ -9,8 +9,6 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import java.util.ArrayList;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.intellectualcrafters.plot.C; import com.intellectualcrafters.plot.C;
@ -25,56 +23,59 @@ import com.intellectualcrafters.plot.PlotMain;
*/ */
public class Home extends SubCommand { public class Home extends SubCommand {
public Home() { public Home() {
super(Command.HOME, "Go to your plot", "home {id|alias}", CommandCategory.TELEPORT); super(Command.HOME, "Go to your plot", "home {id|alias}",
} CommandCategory.TELEPORT);
}
private Plot isAlias(String a) { private Plot isAlias(String a) {
for (Plot p : PlotMain.getPlots()) { for (Plot p : PlotMain.getPlots()) {
if ((p.settings.getAlias().length() > 0) && p.settings.getAlias().equalsIgnoreCase(a)) { if ((p.settings.getAlias().length() > 0)
return p; && p.settings.getAlias().equalsIgnoreCase(a)) {
} return p;
} }
return null; }
} return null;
}
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(Player plr, String... args) {
Plot[] plots = PlotMain.getPlots(plr).toArray(new Plot[0]); Plot[] plots = PlotMain.getPlots(plr).toArray(new Plot[0]);
if (plots.length == 1) { if (plots.length == 1) {
PlotMain.teleportPlayer(plr, plr.getLocation(), plots[0]); PlotMain.teleportPlayer(plr, plr.getLocation(), plots[0]);
return true; return true;
} else if (plots.length > 1) { } else if (plots.length > 1) {
if (args.length < 1) { if (args.length < 1) {
args = new String[] {"1"}; args = new String[] { "1" };
} }
int id = 0; int id = 0;
try { try {
id = Integer.parseInt(args[0]); id = Integer.parseInt(args[0]);
} catch (Exception e) { } catch (Exception e) {
Plot temp; Plot temp;
if ((temp = isAlias(args[0])) != null) { if ((temp = isAlias(args[0])) != null) {
if (temp.hasOwner()) { if (temp.hasOwner()) {
if (temp.getOwner().equals(plr.getUniqueId())) { if (temp.getOwner().equals(plr.getUniqueId())) {
PlotMain.teleportPlayer(plr, plr.getLocation(), temp); PlotMain.teleportPlayer(plr, plr.getLocation(),
return true; temp);
} return true;
} }
PlayerFunctions.sendMessage(plr, C.NOT_YOUR_PLOT); }
return false; PlayerFunctions.sendMessage(plr, C.NOT_YOUR_PLOT);
} return false;
PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER); }
return true; PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER);
} return true;
if ((id > (plots.length)) || (id < 1)) { }
PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER); if ((id > (plots.length)) || (id < 1)) {
return false; PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER);
} return false;
PlotMain.teleportPlayer(plr, plr.getLocation(), plots[id - 1]); }
return true; PlotMain.teleportPlayer(plr, plr.getLocation(), plots[id - 1]);
} else { return true;
PlayerFunctions.sendMessage(plr, C.NO_PLOTS); } else {
return true; PlayerFunctions.sendMessage(plr, C.NO_PLOTS);
} return true;
} }
}
} }

View File

@ -9,8 +9,9 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.*; import java.util.ArrayList;
import com.intellectualcrafters.plot.database.DBFunc; import java.util.UUID;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
@ -18,8 +19,12 @@ import org.bukkit.World;
import org.bukkit.block.Biome; import org.bukkit.block.Biome;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import java.util.ArrayList; import com.intellectualcrafters.plot.C;
import java.util.UUID; 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;
/** /**
* *
@ -28,110 +33,121 @@ import java.util.UUID;
*/ */
public class Info extends SubCommand { public class Info extends SubCommand {
public Info() { public Info() {
super(Command.INFO, "Display plot info", "info", CommandCategory.INFO); super(Command.INFO, "Display plot info", "info", CommandCategory.INFO);
} }
@Override @Override
public boolean execute(Player player, String... args) { public boolean execute(Player player, String... args) {
if (!PlayerFunctions.isInPlot(player)) { if (!PlayerFunctions.isInPlot(player)) {
PlayerFunctions.sendMessage(player, C.NOT_IN_PLOT); PlayerFunctions.sendMessage(player, C.NOT_IN_PLOT);
return true; return true;
} }
// || // ||
Plot plot = PlayerFunctions.getCurrentPlot(player); Plot plot = PlayerFunctions.getCurrentPlot(player);
boolean hasOwner = plot.hasOwner(); boolean hasOwner = plot.hasOwner();
boolean containsEveryone; boolean containsEveryone;
boolean trustedEveryone; boolean trustedEveryone;
// Wildcard player {added} // Wildcard player {added}
{ {
if (plot.helpers == null) { if (plot.helpers == null) {
containsEveryone = false; containsEveryone = false;
} else { } else {
containsEveryone = plot.helpers.contains(DBFunc.everyone); containsEveryone = plot.helpers.contains(DBFunc.everyone);
} }
if (plot.trusted == null) { if (plot.trusted == null) {
trustedEveryone = false; trustedEveryone = false;
} else { } else {
trustedEveryone = plot.trusted.contains(DBFunc.everyone); trustedEveryone = plot.trusted.contains(DBFunc.everyone);
} }
} }
// Unclaimed? // Unclaimed?
if (!hasOwner && !containsEveryone && !trustedEveryone) { if (!hasOwner && !containsEveryone && !trustedEveryone) {
PlayerFunctions.sendMessage(player, C.PLOT_INFO_UNCLAIMED, plot.id.x + ";" + plot.id.y); PlayerFunctions.sendMessage(player, C.PLOT_INFO_UNCLAIMED,
return true; plot.id.x + ";" + plot.id.y);
} return true;
}
new StringBuilder(); new StringBuilder();
String owner = "none"; String owner = "none";
if (plot.owner != null) { if (plot.owner != null) {
owner = Bukkit.getOfflinePlayer(plot.owner).getName(); owner = Bukkit.getOfflinePlayer(plot.owner).getName();
} }
if (owner == null) { if (owner == null) {
owner = plot.owner.toString(); owner = plot.owner.toString();
} }
String info = C.PLOT_INFO.s(); String info = C.PLOT_INFO.s();
info = info.replaceAll("%alias%", plot.settings.getAlias().length() > 0 ? plot.settings.getAlias() : "none"); info = info.replaceAll(
info = info.replaceAll("%id%", plot.id.toString()); "%alias%",
info = info.replaceAll("%biome%", getBiomeAt(plot).toString()); plot.settings.getAlias().length() > 0 ? plot.settings
info = info.replaceAll("%owner%", owner); .getAlias() : "none");
info = info.replaceAll("%time%", plot.settings.getChangeTime() ? plot.settings.getTime() + "" : "default"); info = info.replaceAll("%id%", plot.id.toString());
info = info.replaceAll("%weather%", plot.settings.getRain() ? "rain" : "default"); info = info.replaceAll("%biome%", getBiomeAt(plot).toString());
info = info.replaceAll("%helpers%", getPlayerList(plot.helpers)); info = info.replaceAll("%owner%", owner);
info = info.replaceAll("%trusted%", getPlayerList(plot.trusted)); info = info.replaceAll("%time%",
info = info.replaceAll("%denied%", getPlayerList(plot.denied)); plot.settings.getChangeTime() ? plot.settings.getTime() + ""
info = info.replaceAll("%rating%", "" + DBFunc.getRatings(plot)); : "default");
info = info.replaceAll("%flags%", StringUtils.join(plot.settings.getFlags(), "").length() > 0 ? StringUtils.join(plot.settings.getFlags(), ",") : "none"); info = info.replaceAll("%weather%", plot.settings.getRain() ? "rain"
// PlayerFunctions.sendMessage(player, : "default");
// PlayerFunctions.getTopPlot(player.getWorld(), plot).id.toString()); info = info.replaceAll("%helpers%", getPlayerList(plot.helpers));
// PlayerFunctions.sendMessage(player, info = info.replaceAll("%trusted%", getPlayerList(plot.trusted));
// PlayerFunctions.getBottomPlot(player.getWorld(), info = info.replaceAll("%denied%", getPlayerList(plot.denied));
// plot).id.toString()); info = info.replaceAll("%rating%", "" + DBFunc.getRatings(plot));
PlayerFunctions.sendMessage(player, info); info = info
return true; .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<UUID> l) { private String getPlayerList(ArrayList<UUID> l) {
if ((l == null) || (l.size() < 1)) { if ((l == null) || (l.size() < 1)) {
return " none"; return " none";
} }
String c = C.PLOT_USER_LIST.s(); String c = C.PLOT_USER_LIST.s();
StringBuilder list = new StringBuilder(); StringBuilder list = new StringBuilder();
for (int x = 0; x < l.size(); x++) { for (int x = 0; x < l.size(); x++) {
if ((x + 1) == l.size()) { if ((x + 1) == l.size()) {
list.append(c.replace("%user%", getPlayerName(l.get(x))).replace(",", "")); list.append(c.replace("%user%", getPlayerName(l.get(x)))
} else { .replace(",", ""));
list.append(c.replace("%user%", getPlayerName(l.get(x)))); } else {
} list.append(c.replace("%user%", getPlayerName(l.get(x))));
} }
return list.toString(); }
} return list.toString();
}
private String getPlayerName(UUID uuid) { private String getPlayerName(UUID uuid) {
if (uuid == null) { if (uuid == null) {
return "unknown"; return "unknown";
} }
if (uuid.equals(DBFunc.everyone) || uuid.toString().equalsIgnoreCase(DBFunc.everyone.toString())) { if (uuid.equals(DBFunc.everyone)
return "everyone"; || uuid.toString().equalsIgnoreCase(DBFunc.everyone.toString())) {
} return "everyone";
/* }
OfflinePlayer plr = Bukkit.getOfflinePlayer(uuid); /*
if (plr.getName() == null) { * OfflinePlayer plr = Bukkit.getOfflinePlayer(uuid); if (plr.getName()
return "unknown"; * == null) { return "unknown"; } return plr.getName();
} */
return plr.getName();*/ return UUIDHandler.getName(uuid);
return UUIDHandler.getName(uuid); }
}
private Biome getBiomeAt(Plot plot) { private Biome getBiomeAt(Plot plot) {
World w = Bukkit.getWorld(plot.world); World w = Bukkit.getWorld(plot.world);
Location bl = PlotHelper.getPlotTopLoc(w, plot.id); Location bl = PlotHelper.getPlotTopLoc(w, plot.id);
return bl.getBlock().getBiome(); return bl.getBlock().getBiome();
} }
} }

View File

@ -20,41 +20,48 @@ import org.bukkit.inventory.meta.ItemMeta;
public class Inventory extends SubCommand { public class Inventory extends SubCommand {
public Inventory() { public Inventory() {
super("inventory", "plots.inventory", "Open a command inventory", "inventory", "inv", CommandCategory.INFO); super("inventory", "plots.inventory", "Open a command inventory",
} "inventory", "inv", CommandCategory.INFO);
}
@Override @Override
public boolean execute(final Player plr, String... args) { public boolean execute(final Player plr, String... args) {
ArrayList<SubCommand> cmds = new ArrayList<>(); ArrayList<SubCommand> cmds = new ArrayList<>();
for (SubCommand cmd : MainCommand.subCommands) { for (SubCommand cmd : MainCommand.subCommands) {
if (cmd.permission.hasPermission(plr)) { if (cmd.permission.hasPermission(plr)) {
cmds.add(cmd); cmds.add(cmd);
} }
} }
int size = 9 * (int) Math.ceil(cmds.size() / 9.0); int size = 9 * (int) Math.ceil(cmds.size() / 9.0);
org.bukkit.inventory.Inventory inventory = Bukkit.createInventory(null, size, "PlotSquared Commands"); org.bukkit.inventory.Inventory inventory = Bukkit.createInventory(null,
for (SubCommand cmd : cmds) { size, "PlotSquared Commands");
inventory.addItem(getItem(cmd)); for (SubCommand cmd : cmds) {
} inventory.addItem(getItem(cmd));
plr.openInventory(inventory); }
return true; plr.openInventory(inventory);
} return true;
}
private ItemStack getItem(final SubCommand cmd) { private ItemStack getItem(final SubCommand cmd) {
ItemStack stack = new ItemStack(Material.COMMAND); ItemStack stack = new ItemStack(Material.COMMAND);
ItemMeta meta = stack.getItemMeta(); ItemMeta meta = stack.getItemMeta();
{ {
meta.setDisplayName(ChatColor.GREEN + cmd.cmd + ChatColor.DARK_GRAY + " [" + ChatColor.GREEN + cmd.alias + ChatColor.DARK_GRAY + "]"); meta.setDisplayName(ChatColor.GREEN + cmd.cmd + ChatColor.DARK_GRAY
meta.setLore(new ArrayList<String>() { + " [" + ChatColor.GREEN + cmd.alias + ChatColor.DARK_GRAY
{ + "]");
add(ChatColor.RED + "Category: " + ChatColor.GOLD + cmd.category.toString()); meta.setLore(new ArrayList<String>() {
add(ChatColor.RED + "Description: " + ChatColor.GOLD + cmd.description); {
add(ChatColor.RED + "Usage: " + ChatColor.GOLD + "/plot " + cmd.usage); add(ChatColor.RED + "Category: " + ChatColor.GOLD
} + cmd.category.toString());
}); add(ChatColor.RED + "Description: " + ChatColor.GOLD
} + cmd.description);
stack.setItemMeta(meta); add(ChatColor.RED + "Usage: " + ChatColor.GOLD + "/plot "
return stack; + cmd.usage);
} }
});
}
stack.setItemMeta(meta);
return stack;
}
} }

View File

@ -21,35 +21,43 @@ import com.intellectualcrafters.plot.Plot;
*/ */
public class Kick extends SubCommand { public class Kick extends SubCommand {
public Kick() { public Kick() {
super(Command.KICK, "Kick a player from your plot", "kick", CommandCategory.ACTIONS); super(Command.KICK, "Kick a player from your plot", "kick",
} CommandCategory.ACTIONS);
}
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(Player plr, String... args) {
if (!PlayerFunctions.isInPlot(plr)) { if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, "You're not in a plot."); PlayerFunctions.sendMessage(plr, "You're not in a plot.");
return false; return false;
} }
Plot plot = PlayerFunctions.getCurrentPlot(plr); Plot plot = PlayerFunctions.getCurrentPlot(plr);
if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId())) && !plr.hasPermission("plots.admin")) { if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(
PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); plr.getUniqueId()))
return false; && !plr.hasPermission("plots.admin")) {
} PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
if (args.length != 1) { return false;
PlayerFunctions.sendMessage(plr, "&c/plot kick <player>"); }
return false; if (args.length != 1) {
} PlayerFunctions.sendMessage(plr, "&c/plot kick <player>");
if (Bukkit.getPlayer(args[0]) != null) { return false;
PlayerFunctions.sendMessage(plr, C.INVALID_PLAYER.s().replaceAll("%player%", args[0])); }
return false; if (Bukkit.getPlayer(args[0]) != null) {
} PlayerFunctions.sendMessage(plr,
Player player = Bukkit.getPlayer(args[0]); C.INVALID_PLAYER.s().replaceAll("%player%", args[0]));
if (!player.getWorld().equals(plr.getWorld()) || !PlayerFunctions.isInPlot(player) || (PlayerFunctions.getCurrentPlot(player) == null) || !PlayerFunctions.getCurrentPlot(player).equals(plot)) { return false;
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())
player.teleport(player.getWorld().getSpawnLocation()); || !PlayerFunctions.isInPlot(player)
return true; || (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;
}
} }

View File

@ -9,17 +9,18 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.C; import java.util.ArrayList;
import com.intellectualcrafters.plot.PlayerFunctions; import java.util.Arrays;
import com.intellectualcrafters.plot.PlotMain;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import java.util.ArrayList; import com.intellectualcrafters.plot.C;
import java.util.Arrays; import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.PlotMain;
/** /**
* PlotMain command class * PlotMain command class
@ -29,113 +30,143 @@ import java.util.Arrays;
*/ */
public class MainCommand implements CommandExecutor { 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<SubCommand> subCommands = new ArrayList<SubCommand>() { public static ArrayList<SubCommand> subCommands = new ArrayList<SubCommand>() {
{ {
addAll(Arrays.asList(_subCommands)); addAll(Arrays.asList(_subCommands));
} }
}; };
public static boolean no_permission(Player player) { public static boolean no_permission(Player player) {
PlayerFunctions.sendMessage(player, C.NO_PERMISSION); PlayerFunctions.sendMessage(player, C.NO_PERMISSION);
return false; return false;
} }
@Override @Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { public boolean onCommand(CommandSender sender, Command cmd,
if (!(sender instanceof Player)) { String commandLabel, String[] args) {
if (args.length > 0) { if (!(sender instanceof Player)) {
if (args[0].equalsIgnoreCase("reload")) { if (args.length > 0) {
new Reload().executeConsole(args); if (args[0].equalsIgnoreCase("reload")) {
} new Reload().executeConsole(args);
} else { }
PlotMain.sendConsoleSenderMessage(C.PREFIX.s() + C.HELP_HEADER.s()); } else {
PlotMain.sendConsoleSenderMessage("&6/plots reload &c-&6 reloads the plugin"); PlotMain.sendConsoleSenderMessage(C.PREFIX.s()
} + C.HELP_HEADER.s());
return false; PlotMain.sendConsoleSenderMessage("&6/plots reload &c-&6 reloads the plugin");
} }
Player player = (Player) sender; return false;
if (!player.hasPermission("plots.use")) { }
return no_permission(player); Player player = (Player) sender;
} if (!player.hasPermission("plots.use")) {
if ((args.length < 1) || ((args.length >= 1) && (args[0].equalsIgnoreCase("help") || args[0].equalsIgnoreCase("he")))) { return no_permission(player);
if (args.length < 2) { }
StringBuilder builder = new StringBuilder(); if ((args.length < 1)
builder.append(C.HELP_INFO.s()); || ((args.length >= 1) && (args[0].equalsIgnoreCase("help") || args[0]
for (SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) { .equalsIgnoreCase("he")))) {
builder.append("\n" + C.HELP_INFO_ITEM.s().replaceAll("%category%", category.toString().toLowerCase()).replaceAll("%category_desc%", category.toString())); if (args.length < 2) {
} StringBuilder builder = new StringBuilder();
PlayerFunctions.sendMessage(player, builder.toString()); builder.append(C.HELP_INFO.s());
return true; for (SubCommand.CommandCategory category : SubCommand.CommandCategory
} .values()) {
String cat = args[1]; builder.append("\n"
SubCommand.CommandCategory cato = null; + C.HELP_INFO_ITEM
for (SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) { .s()
if (cat.equalsIgnoreCase(category.toString())) { .replaceAll("%category%",
cato = category; category.toString().toLowerCase())
break; .replaceAll("%category_desc%",
} category.toString()));
} }
if (cato == null) { PlayerFunctions.sendMessage(player, builder.toString());
StringBuilder builder = new StringBuilder(); return true;
builder.append(C.HELP_INFO.s()); }
for (SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) { String cat = args[1];
builder.append("\n" + C.HELP_INFO_ITEM.s().replaceAll("%category%", category.toString().toLowerCase()).replaceAll("%category_desc%", category.toString())); SubCommand.CommandCategory cato = null;
} for (SubCommand.CommandCategory category : SubCommand.CommandCategory
PlayerFunctions.sendMessage(player, builder.toString()); .values()) {
return true; if (cat.equalsIgnoreCase(category.toString())) {
} cato = category;
StringBuilder help = new StringBuilder(); break;
for (String string : helpMenu(player, cato)) { }
help.append(string + "\n"); }
} if (cato == null) {
PlayerFunctions.sendMessage(player, help.toString()); StringBuilder builder = new StringBuilder();
return true; builder.append(C.HELP_INFO.s());
} else { for (SubCommand.CommandCategory category : SubCommand.CommandCategory
for (SubCommand command : subCommands) { .values()) {
if (command.cmd.equalsIgnoreCase(args[0]) || command.alias.equalsIgnoreCase(args[0])) { builder.append("\n"
String[] arguments = new String[args.length - 1]; + C.HELP_INFO_ITEM
for (int x = 1; x < args.length; x++) { .s()
arguments[x - 1] = args[x]; .replaceAll("%category%",
} category.toString().toLowerCase())
if (command.permission.hasPermission(player)) { .replaceAll("%category_desc%",
return command.execute(player, arguments); category.toString()));
} else { }
return no_permission(player); PlayerFunctions.sendMessage(player, builder.toString());
} return true;
} }
} StringBuilder help = new StringBuilder();
PlayerFunctions.sendMessage(player, C.NOT_VALID_SUBCOMMAND); for (String string : helpMenu(player, cato)) {
} help.append(string + "\n");
return false; }
} 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<String> helpMenu(Player player, final SubCommand.CommandCategory category) { public static ArrayList<String> helpMenu(Player player,
ArrayList<String> help = new ArrayList<String>() { final SubCommand.CommandCategory category) {
{ ArrayList<String> help = new ArrayList<String>() {
add(t(C.HELP_HEADER.s())); {
add(t(C.HELP_CATEGORY.s().replaceAll("%category%", category.toString()))); 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()); for (SubCommand cmd : subCommands) {
s = s.replaceAll("%alias%", cmd.alias); if (cmd.permission.hasPermission(player)
s = s.replaceAll("%usage%", cmd.usage.contains("plot") ? cmd.usage : "/plot " + cmd.usage); && (cmd.category == category)) {
s = s.replaceAll("%cmd%", cmd.cmd); String s = t(C.HELP_PAGE.s());
s = s.replaceAll("%desc%", cmd.description); s = s.replaceAll("%alias%", cmd.alias);
help.add(s); s = s.replaceAll("%usage%",
} cmd.usage.contains("plot") ? cmd.usage : "/plot "
} + cmd.usage);
if (help.size() < 2) { s = s.replaceAll("%cmd%", cmd.cmd);
help.add(t(C.NO_COMMANDS.s())); s = s.replaceAll("%desc%", cmd.description);
} help.add(s);
return help; }
} }
if (help.size() < 2) {
help.add(t(C.NO_COMMANDS.s()));
}
return help;
}
private static String t(String s) { private static String t(String s) {
return ChatColor.translateAlternateColorCodes('&', s); return ChatColor.translateAlternateColorCodes('&', s);
} }
} }

View File

@ -9,15 +9,24 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.*; import java.util.ArrayList;
import com.intellectualcrafters.plot.events.PlotMergeEvent;
import net.milkbowl.vault.economy.Economy; import net.milkbowl.vault.economy.Economy;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.entity.Player; 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;
/** /**
* *
@ -26,123 +35,147 @@ import java.util.ArrayList;
*/ */
public class Merge extends SubCommand { public class Merge extends SubCommand {
public static String[] values = new String[] { "north", "east", "south", "west" }; public static String[] values = new String[] { "north", "east", "south",
public static String[] aliases = new String[] { "n", "e", "s", "w" }; "west" };
public static String[] aliases = new String[] { "n", "e", "s", "w" };
public Merge() { public Merge() {
super(Command.MERGE, "Merge the plot you are standing on with another plot.", "merge", CommandCategory.ACTIONS); super(Command.MERGE,
} "Merge the plot you are standing on with another plot.",
"merge", CommandCategory.ACTIONS);
}
public static String direction(float yaw) { public static String direction(float yaw) {
yaw = yaw / 90; yaw = yaw / 90;
int i = Math.round(yaw); int i = Math.round(yaw);
switch (i) { switch (i) {
case -4: case -4:
case 0: case 0:
case 4: case 4:
return "SOUTH"; return "SOUTH";
case -1: case -1:
case 3: case 3:
return "EAST"; return "EAST";
case -2: case -2:
case 2: case 2:
return "NORTH"; return "NORTH";
case -3: case -3:
case 1: case 1:
return "WEST"; return "WEST";
default: default:
return ""; return "";
} }
} }
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(Player plr, String... args) {
if (!PlayerFunctions.isInPlot(plr)) { if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
return true; return true;
} }
Plot plot = PlayerFunctions.getCurrentPlot(plr); Plot plot = PlayerFunctions.getCurrentPlot(plr);
if ((plot == null) || !plot.hasOwner()) { if ((plot == null) || !plot.hasOwner()) {
PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
return false; return false;
} }
if (!plot.getOwner().equals(plr.getUniqueId())) { if (!plot.getOwner().equals(plr.getUniqueId())) {
PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
return false; return false;
} }
if (args.length < 1) { if (args.length < 1) {
PlayerFunctions.sendMessage(plr, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + StringUtils.join(values, C.BLOCK_LIST_SEPARATER.s())); PlayerFunctions.sendMessage(
PlayerFunctions.sendMessage(plr, C.DIRECTION.s().replaceAll("%dir%", direction(plr.getLocation().getYaw()))); plr,
return false; C.SUBCOMMAND_SET_OPTIONS_HEADER.s()
} + StringUtils.join(values,
int direction = -1; C.BLOCK_LIST_SEPARATER.s()));
for (int i = 0; i < values.length; i++) { PlayerFunctions.sendMessage(
if (args[0].equalsIgnoreCase(values[i]) || args[0].equalsIgnoreCase(aliases[i])) { plr,
direction = i; C.DIRECTION.s().replaceAll("%dir%",
break; direction(plr.getLocation().getYaw())));
} return false;
} }
if (direction == -1) { int direction = -1;
PlayerFunctions.sendMessage(plr, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + StringUtils.join(values, C.BLOCK_LIST_SEPARATER.s())); for (int i = 0; i < values.length; i++) {
PlayerFunctions.sendMessage(plr, C.DIRECTION.s().replaceAll("%dir%", direction(plr.getLocation().getYaw()))); if (args[0].equalsIgnoreCase(values[i])
return false; || args[0].equalsIgnoreCase(aliases[i])) {
} direction = i;
World world = plr.getWorld(); break;
PlotId bot = PlayerFunctions.getBottomPlot(world, plot).id; }
PlotId top = PlayerFunctions.getTopPlot(world, plot).id; }
ArrayList<PlotId> plots; if (direction == -1) {
switch (direction) { PlayerFunctions.sendMessage(
case 0: // north = -y plr,
plots = PlayerFunctions.getPlotSelectionIds(plr.getWorld(), new PlotId(bot.x, bot.y - 1), new PlotId(top.x, top.y)); C.SUBCOMMAND_SET_OPTIONS_HEADER.s()
break; + StringUtils.join(values,
case 1: // east = +x C.BLOCK_LIST_SEPARATER.s()));
plots = PlayerFunctions.getPlotSelectionIds(plr.getWorld(), new PlotId(bot.x, bot.y), new PlotId(top.x + 1, top.y)); PlayerFunctions.sendMessage(
break; plr,
case 2: // south = +y C.DIRECTION.s().replaceAll("%dir%",
plots = PlayerFunctions.getPlotSelectionIds(plr.getWorld(), new PlotId(bot.x, bot.y), new PlotId(top.x, top.y + 1)); direction(plr.getLocation().getYaw())));
break; return false;
case 3: // west = -x }
plots = PlayerFunctions.getPlotSelectionIds(plr.getWorld(), new PlotId(bot.x - 1, bot.y), new PlotId(top.x, top.y)); World world = plr.getWorld();
break; PlotId bot = PlayerFunctions.getBottomPlot(world, plot).id;
default: PlotId top = PlayerFunctions.getTopPlot(world, plot).id;
return false; ArrayList<PlotId> plots;
} switch (direction) {
for (PlotId myid : plots) { case 0: // north = -y
Plot myplot = PlotMain.getPlots(world).get(myid); plots = PlayerFunctions.getPlotSelectionIds(plr.getWorld(),
if ((myplot == null) || !myplot.hasOwner() || !(myplot.getOwner().equals(plr.getUniqueId()))) { new PlotId(bot.x, bot.y - 1), new PlotId(top.x, top.y));
PlayerFunctions.sendMessage(plr, C.NO_PERM_MERGE.s().replaceAll("%plot%", myid.toString())); break;
return false; 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); PlotWorld plotWorld = PlotMain.getWorldSettings(world);
if (PlotMain.useEconomy && plotWorld.USE_ECONOMY) { if (PlotMain.useEconomy && plotWorld.USE_ECONOMY) {
double cost = plotWorld.MERGE_PRICE; double cost = plotWorld.MERGE_PRICE;
cost = plots.size() * cost; cost = plots.size() * cost;
if (cost > 0d) { if (cost > 0d) {
Economy economy = PlotMain.economy; Economy economy = PlotMain.economy;
if (economy.getBalance(plr) < cost) { if (economy.getBalance(plr) < cost) {
sendMessage(plr, C.CANNOT_AFFORD_MERGE, cost + ""); sendMessage(plr, C.CANNOT_AFFORD_MERGE, cost + "");
return false; return false;
} }
economy.withdrawPlayer(plr, cost); economy.withdrawPlayer(plr, cost);
sendMessage(plr, C.REMOVED_BALANCE, 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); Bukkit.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) { if (event.isCancelled()) {
event.setCancelled(true); event.setCancelled(true);
PlayerFunctions.sendMessage(plr, "&cMerge has been cancelled"); PlayerFunctions.sendMessage(plr, "&cMerge has been cancelled");
return false; return false;
} }
PlayerFunctions.sendMessage(plr, "&cPlots have been merged"); PlayerFunctions.sendMessage(plr, "&cPlots have been merged");
PlotHelper.mergePlots(world, plots); PlotHelper.mergePlots(world, plots);
if (PlotHelper.canSetFast) { if (PlotHelper.canSetFast) {
SetBlockFast.update(plr); SetBlockFast.update(plr);
} }
return true; return true;
} }
} }

View File

@ -11,62 +11,63 @@ import com.intellectualcrafters.plot.Plot;
*/ */
public class Rate extends SubCommand { public class Rate extends SubCommand {
/* /*
* String cmd, String permission, String description, String usage, String * String cmd, String permission, String description, String usage, String
* alias, CommandCategory category * alias, CommandCategory category
*/ */
public Rate() { public Rate() {
super("rate", "plots.rate", "Rate the plot", "rate {0-10}", "rt", CommandCategory.ACTIONS); super("rate", "plots.rate", "Rate the plot", "rate {0-10}", "rt",
} CommandCategory.ACTIONS);
}
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(Player plr, String... args) {
if (args.length < 1) { if (args.length < 1) {
sendMessage(plr, C.RATING_NOT_VALID); sendMessage(plr, C.RATING_NOT_VALID);
return true; return true;
} }
if (!PlayerFunctions.isInPlot(plr)) { if (!PlayerFunctions.isInPlot(plr)) {
sendMessage(plr, C.NOT_IN_PLOT); sendMessage(plr, C.NOT_IN_PLOT);
return true; return true;
} }
Plot plot = PlayerFunctions.getCurrentPlot(plr); Plot plot = PlayerFunctions.getCurrentPlot(plr);
if (!plot.hasOwner()) { if (!plot.hasOwner()) {
sendMessage(plr, C.RATING_NOT_OWNED); sendMessage(plr, C.RATING_NOT_OWNED);
return true; return true;
} }
if (plot.getOwner().equals(plr.getUniqueId())) { if (plot.getOwner().equals(plr.getUniqueId())) {
sendMessage(plr, C.RATING_NOT_YOUR_OWN); sendMessage(plr, C.RATING_NOT_YOUR_OWN);
return true; return true;
} }
String arg = args[0]; String arg = args[0];
boolean o = false; boolean o = false;
for (char c : arg.toCharArray()) { for (char c : arg.toCharArray()) {
if (!Character.isDigit(c)) { if (!Character.isDigit(c)) {
o = true; o = true;
break; break;
} }
} }
int rating = 0; int rating = 0;
if (!o) { if (!o) {
rating = Integer.parseInt(arg); rating = Integer.parseInt(arg);
} }
if (o || ((rating < 0) || (rating > 10))) { if (o || ((rating < 0) || (rating > 10))) {
sendMessage(plr, C.RATING_NOT_VALID); sendMessage(plr, C.RATING_NOT_VALID);
return true; return true;
} }
// TODO implement check for already rated // TODO implement check for already rated
boolean rated = false; boolean rated = false;
if (rated) { if (rated) {
sendMessage(plr, C.RATING_ALREADY_EXISTS, plot.getId().toString()); sendMessage(plr, C.RATING_ALREADY_EXISTS, plot.getId().toString());
} }
// TODO actually do something... // TODO actually do something...
boolean success = false; boolean success = false;
if (success) { if (success) {
sendMessage(plr, C.RATING_APPLIED, plot.getId().toString()); sendMessage(plr, C.RATING_APPLIED, plot.getId().toString());
} else { } else {
sendMessage(plr, C.COMMAND_WENT_WRONG); sendMessage(plr, C.COMMAND_WENT_WRONG);
} }
return true; return true;
} }
} }

View File

@ -20,23 +20,24 @@ import com.intellectualcrafters.plot.PlotMain;
*/ */
public class Reload extends SubCommand { public class Reload extends SubCommand {
public Reload() { public Reload() {
super("reload", "plots.admin", "Reload configurations", "", "reload", CommandCategory.INFO); super("reload", "plots.admin", "Reload configurations", "", "reload",
} CommandCategory.INFO);
}
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(Player plr, String... args) {
try { try {
PlotMain.reloadTranslations(); PlotMain.reloadTranslations();
PlotMain.BroadcastWithPerms(C.RELOADED_CONFIGS); PlotMain.BroadcastWithPerms(C.RELOADED_CONFIGS);
} catch (Exception e) { } catch (Exception e) {
if (plr != null) { if (plr != null) {
PlayerFunctions.sendMessage(plr, C.RELOAD_FAILED); PlayerFunctions.sendMessage(plr, C.RELOAD_FAILED);
} else { } else {
PlotMain.sendConsoleSenderMessage(C.RELOAD_FAILED); PlotMain.sendConsoleSenderMessage(C.RELOAD_FAILED);
} }
} }
return true; return true;
} }
} }

View File

@ -4,67 +4,78 @@ import org.bukkit.entity.Player;
import com.intellectualcrafters.plot.C; import com.intellectualcrafters.plot.C;
import com.intellectualcrafters.plot.PlayerFunctions; 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; import com.intellectualcrafters.plot.SchematicHandler;
public class Schematic extends SubCommand { public class Schematic extends SubCommand {
public Schematic() { public Schematic() {
super("schematic", "plots.admin", "Schematic Command", "schematic {arg}", "sch", CommandCategory.ACTIONS); super("schematic", "plots.admin", "Schematic Command",
} "schematic {arg}", "sch", CommandCategory.ACTIONS);
}
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(Player plr, String... args) {
if (args.length < 1) { if (args.length < 1) {
sendMessage(plr, C.SCHEMATIC_MISSING_ARG); sendMessage(plr, C.SCHEMATIC_MISSING_ARG);
return true; return true;
} }
String arg = args[0]; String arg = args[0];
String file; String file;
SchematicHandler.Schematic schematic; SchematicHandler.Schematic schematic;
switch (arg) { switch (arg) {
case "paste": case "paste":
if (args.length < 2) { if (args.length < 2) {
sendMessage(plr, C.SCHEMATIC_MISSING_ARG); sendMessage(plr, C.SCHEMATIC_MISSING_ARG);
break; break;
} }
if (!PlayerFunctions.isInPlot(plr)) { if (!PlayerFunctions.isInPlot(plr)) {
sendMessage(plr, C.NOT_IN_PLOT); sendMessage(plr, C.NOT_IN_PLOT);
break; break;
} }
file = args[1]; file = args[1];
schematic = new SchematicHandler().getSchematic(file); schematic = new SchematicHandler().getSchematic(file);
boolean s = new SchematicHandler().paste(plr.getLocation(), schematic, PlayerFunctions.getCurrentPlot(plr)); boolean s = new SchematicHandler().paste(plr.getLocation(),
if (s) { schematic, PlayerFunctions.getCurrentPlot(plr));
sendMessage(plr, C.SCHEMATIC_PASTE_SUCCESS); if (s) {
} else { sendMessage(plr, C.SCHEMATIC_PASTE_SUCCESS);
sendMessage(plr, C.SCHEMATIC_PASTE_FAILED); } else {
} sendMessage(plr, C.SCHEMATIC_PASTE_FAILED);
break; }
case "test": break;
if (args.length < 2) { case "test":
sendMessage(plr, C.SCHEMATIC_MISSING_ARG); if (args.length < 2) {
break; sendMessage(plr, C.SCHEMATIC_MISSING_ARG);
} break;
file = args[1]; }
schematic = new SchematicHandler().getSchematic(file); file = args[1];
if (schematic == null) { schematic = new SchematicHandler().getSchematic(file);
sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent"); if (schematic == null) {
break; sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent");
} break;
int l1 = schematic.getSchematicDimension().getX(); }
int l2 = schematic.getSchematicDimension().getZ(); if (!PlayerFunctions.isInPlot(plr)) {
int length = PlotMain.getWorldSettings(plr.getWorld()).PLOT_WIDTH; sendMessage(plr, C.NOT_IN_PLOT);
if ((l1 != length) || (l2 != length)) { break;
sendMessage(plr, C.SCHEMATIC_INVALID, String.format("Wrong size (x: %s, z: %d) vs %d ", l1, l2, length)); }
break; int l1 = schematic.getSchematicDimension().getX();
} int l2 = schematic.getSchematicDimension().getZ();
sendMessage(plr, C.SCHEMATIC_VALID);
break; Plot plot = PlayerFunctions.getCurrentPlot(plr);
default: int length = PlotHelper.getPlotWidth(plr.getWorld(), plot.id);
sendMessage(plr, C.SCHEMATIC_MISSING_ARG);
break; if ((l1 != length) || (l2 != length)) {
} sendMessage(plr, C.SCHEMATIC_INVALID, String.format(
return true; "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;
}
} }

View File

@ -26,6 +26,7 @@ import com.intellectualcrafters.plot.Flag;
import com.intellectualcrafters.plot.FlagManager; import com.intellectualcrafters.plot.FlagManager;
import com.intellectualcrafters.plot.PlayerFunctions; import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.Plot; import com.intellectualcrafters.plot.Plot;
import com.intellectualcrafters.plot.PlotBlock;
import com.intellectualcrafters.plot.PlotHelper; import com.intellectualcrafters.plot.PlotHelper;
import com.intellectualcrafters.plot.PlotHomePosition; import com.intellectualcrafters.plot.PlotHomePosition;
import com.intellectualcrafters.plot.PlotMain; import com.intellectualcrafters.plot.PlotMain;
@ -41,374 +42,407 @@ import com.intellectualcrafters.plot.events.PlotFlagRemoveEvent;
*/ */
public class Set extends SubCommand { public class Set extends SubCommand {
public Set() { public Set() {
super(Command.SET, "Set a plot value", "set {arg} {value...}", CommandCategory.ACTIONS); 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[] values = new String[] { "biome", "wall",
public static String[] aliases = new String[] { "b", "w", "wf", "f", "a", "h", "r", "fl" }; "wall_filling", "floor", "alias", "home", "rain", "flag" };
public static String[] aliases = new String[] { "b", "w", "wf", "f", "a",
"h", "r", "fl" };
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(Player plr, String... args) {
if (!PlayerFunctions.isInPlot(plr)) { if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
return false; return false;
} }
Plot plot = PlayerFunctions.getCurrentPlot(plr); Plot plot = PlayerFunctions.getCurrentPlot(plr);
if (!plot.hasRights(plr) && !plr.hasPermission("plots.admin")) { if (!plot.hasRights(plr) && !plr.hasPermission("plots.admin")) {
PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
return false; return false;
} }
if (args.length < 1) { if (args.length < 1) {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
builder.append(C.SUBCOMMAND_SET_OPTIONS_HEADER.s()); builder.append(C.SUBCOMMAND_SET_OPTIONS_HEADER.s());
builder.append(getArgumentList(values)); builder.append(getArgumentList(values));
PlayerFunctions.sendMessage(plr, builder.toString()); PlayerFunctions.sendMessage(plr, builder.toString());
return false; return false;
} }
for (int i = 0; i < aliases.length; i++) { for (int i = 0; i < aliases.length; i++) {
if (aliases[i].equalsIgnoreCase(args[0])) { if (aliases[i].equalsIgnoreCase(args[0])) {
args[0] = values[i]; args[0] = values[i];
break; break;
} }
} }
/* TODO: Implement option */ /* TODO: Implement option */
boolean advanced_permissions = true; boolean advanced_permissions = true;
if (advanced_permissions) { if (advanced_permissions) {
if (!plr.hasPermission("plots.set." + args[0].toLowerCase())) { if (!plr.hasPermission("plots.set." + args[0].toLowerCase())) {
PlayerFunctions.sendMessage(plr, C.NO_PERMISSION); PlayerFunctions.sendMessage(plr, C.NO_PERMISSION);
return false; return false;
} }
} }
if (args[0].equalsIgnoreCase("flag")) { if (args[0].equalsIgnoreCase("flag")) {
if (args.length < 2) { if (args.length < 2) {
String message = StringUtils.join(FlagManager.getFlags(), "&c, &6"); String message = StringUtils.join(FlagManager.getFlags(),
if (PlotMain.worldGuardListener != null) { "&c, &6");
if (message.equals("")) { if (PlotMain.worldGuardListener != null) {
message = StringUtils.join(PlotMain.worldGuardListener.str_flags, "&c, &6"); if (message.equals("")) {
} else { message = StringUtils
message += "," + StringUtils.join(PlotMain.worldGuardListener.str_flags, "&c, &6"); .join(PlotMain.worldGuardListener.str_flags,
} "&c, &6");
} } else {
PlayerFunctions.sendMessage(plr, C.NEED_KEY.s().replaceAll("%values%", message)); message += ","
return false; + StringUtils.join(
} PlotMain.worldGuardListener.str_flags,
if (!FlagManager.getFlags().contains(args[1].toLowerCase()) && (PlotMain.worldGuardListener != null) && !PlotMain.worldGuardListener.str_flags.contains(args[1].toLowerCase())) { "&c, &6");
PlayerFunctions.sendMessage(plr, C.NOT_VALID_FLAG); }
return false; }
} PlayerFunctions.sendMessage(plr,
if (!plr.hasPermission("plots.set.flag" + args[1].toLowerCase())) { C.NEED_KEY.s().replaceAll("%values%", message));
PlayerFunctions.sendMessage(plr, C.NO_PERMISSION); return false;
return false; }
} if (!FlagManager.getFlags().contains(args[1].toLowerCase())
if (args.length == 2) { && (PlotMain.worldGuardListener != null)
if (plot.settings.getFlag(args[1].toLowerCase()) == null) { && !PlotMain.worldGuardListener.str_flags.contains(args[1]
if (PlotMain.worldGuardListener != null) { .toLowerCase())) {
if (PlotMain.worldGuardListener.str_flags.contains(args[1].toLowerCase())) { PlayerFunctions.sendMessage(plr, C.NOT_VALID_FLAG);
PlotMain.worldGuardListener.removeFlag(plr, plr.getWorld(), plot, args[1]); return false;
return false; }
} if (!plr.hasPermission("plots.set.flag" + args[1].toLowerCase())) {
} PlayerFunctions.sendMessage(plr, C.NO_PERMISSION);
PlayerFunctions.sendMessage(plr, C.FLAG_NOT_IN_PLOT); return false;
return false; }
} if (args.length == 2) {
Flag flag = plot.settings.getFlag(args[1].toLowerCase()); if (plot.settings.getFlag(args[1].toLowerCase()) == null) {
PlotFlagRemoveEvent event = new PlotFlagRemoveEvent(flag, plot); if (PlotMain.worldGuardListener != null) {
Bukkit.getServer().getPluginManager().callEvent(event); if (PlotMain.worldGuardListener.str_flags
if (event.isCancelled()) { .contains(args[1].toLowerCase())) {
PlayerFunctions.sendMessage(plr, C.FLAG_NOT_REMOVED); PlotMain.worldGuardListener.removeFlag(plr,
event.setCancelled(true); plr.getWorld(), plot, args[1]);
return false; return false;
} }
java.util.Set<Flag> newflags = plot.settings.getFlags(); }
Flag oldFlag = plot.settings.getFlag(args[1].toLowerCase()); PlayerFunctions.sendMessage(plr, C.FLAG_NOT_IN_PLOT);
if (oldFlag != null) { return false;
newflags.remove(oldFlag); }
} Flag flag = plot.settings.getFlag(args[1].toLowerCase());
plot.settings.setFlags(newflags.toArray(new Flag[0])); PlotFlagRemoveEvent event = new PlotFlagRemoveEvent(flag, plot);
DBFunc.setFlags(plr.getWorld().getName(), plot, newflags.toArray(new Flag[0])); Bukkit.getServer().getPluginManager().callEvent(event);
PlayerFunctions.sendMessage(plr, C.FLAG_REMOVED); if (event.isCancelled()) {
return true; PlayerFunctions.sendMessage(plr, C.FLAG_NOT_REMOVED);
} event.setCancelled(true);
try { return false;
String value = StringUtils.join(Arrays.copyOfRange(args, 2, args.length), " "); }
if ((FlagManager.getFlag(args[1].toLowerCase()) == null) && (PlotMain.worldGuardListener != null)) { java.util.Set<Flag> newflags = plot.settings.getFlags();
PlotMain.worldGuardListener.addFlag(plr, plr.getWorld(), plot, args[1], value); Flag oldFlag = plot.settings.getFlag(args[1].toLowerCase());
return false; if (oldFlag != null) {
} newflags.remove(oldFlag);
Flag flag = new Flag(FlagManager.getFlag(args[1].toLowerCase(), true), value); }
PlotFlagAddEvent event = new PlotFlagAddEvent(flag, plot); plot.settings.setFlags(newflags.toArray(new Flag[0]));
Bukkit.getServer().getPluginManager().callEvent(event); DBFunc.setFlags(plr.getWorld().getName(), plot,
if (event.isCancelled()) { newflags.toArray(new Flag[0]));
PlayerFunctions.sendMessage(plr, C.FLAG_NOT_ADDED); PlayerFunctions.sendMessage(plr, C.FLAG_REMOVED);
event.setCancelled(true); return true;
return false; }
} try {
plot.settings.addFlag(flag); String value = StringUtils.join(
DBFunc.setFlags(plr.getWorld().getName(), plot, plot.settings.getFlags().toArray(new Flag[0])); Arrays.copyOfRange(args, 2, args.length), " ");
PlayerFunctions.sendMessage(plr, C.FLAG_ADDED); if ((FlagManager.getFlag(args[1].toLowerCase()) == null)
return true; && (PlotMain.worldGuardListener != null)) {
} catch (Exception e) { PlotMain.worldGuardListener.addFlag(plr, plr.getWorld(),
PlayerFunctions.sendMessage(plr, "&c" + e.getMessage()); plot, args[1], value);
return false; return false;
} }
} Flag flag = new Flag(FlagManager.getFlag(args[1].toLowerCase(),
if (args[0].equalsIgnoreCase("rain")) { true), value);
if (args.length < 2) { PlotFlagAddEvent event = new PlotFlagAddEvent(flag, plot);
PlayerFunctions.sendMessage(plr, C.NEED_ON_OFF); Bukkit.getServer().getPluginManager().callEvent(event);
return false; if (event.isCancelled()) {
} PlayerFunctions.sendMessage(plr, C.FLAG_NOT_ADDED);
String word = args[1]; event.setCancelled(true);
if (!word.equalsIgnoreCase("on") && !word.equalsIgnoreCase("off")) { return false;
PlayerFunctions.sendMessage(plr, C.NEED_ON_OFF); }
return true; plot.settings.addFlag(flag);
} DBFunc.setFlags(plr.getWorld().getName(), plot, plot.settings
boolean b = word.equalsIgnoreCase("on"); .getFlags().toArray(new Flag[0]));
DBFunc.setWeather(plr.getWorld().getName(), plot, b); PlayerFunctions.sendMessage(plr, C.FLAG_ADDED);
PlayerFunctions.sendMessage(plr, C.SETTING_UPDATED); return true;
for (Player p : Bukkit.getOnlinePlayers()) { } catch (Exception e) {
if (PlayerFunctions.getCurrentPlot(plr).id == plot.id) { PlayerFunctions.sendMessage(plr, "&c" + e.getMessage());
if (b) { return false;
p.setPlayerWeather(WeatherType.DOWNFALL); }
} else { }
p.resetPlayerWeather(); if (args[0].equalsIgnoreCase("rain")) {
} if (args.length < 2) {
} PlayerFunctions.sendMessage(plr, C.NEED_ON_OFF);
} return false;
return true; }
} 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[0].equalsIgnoreCase("home")) {
if (args.length < 2) { if (args.length < 2) {
PlayerFunctions.sendMessage(plr, C.MISSING_POSITION); PlayerFunctions.sendMessage(plr, C.MISSING_POSITION);
return false; return false;
} }
PlotHomePosition position = null; PlotHomePosition position = null;
for (PlotHomePosition p : PlotHomePosition.values()) { for (PlotHomePosition p : PlotHomePosition.values()) {
if (p.isMatching(args[1])) { if (p.isMatching(args[1])) {
position = p; position = p;
} }
} }
if (position == null) { if (position == null) {
PlayerFunctions.sendMessage(plr, C.INVALID_POSITION); PlayerFunctions.sendMessage(plr, C.INVALID_POSITION);
return false; return false;
} }
DBFunc.setPosition(plr.getWorld().getName(), plot, position.toString()); DBFunc.setPosition(plr.getWorld().getName(), plot,
PlayerFunctions.sendMessage(plr, C.POSITION_SET); position.toString());
return true; PlayerFunctions.sendMessage(plr, C.POSITION_SET);
} return true;
}
if (args[0].equalsIgnoreCase("alias")) { if (args[0].equalsIgnoreCase("alias")) {
if (args.length < 2) { if (args.length < 2) {
PlayerFunctions.sendMessage(plr, C.MISSING_ALIAS); PlayerFunctions.sendMessage(plr, C.MISSING_ALIAS);
return false; return false;
} }
String alias = args[1]; String alias = args[1];
for (Plot p : PlotMain.getPlots(plr.getWorld()).values()) { for (Plot p : PlotMain.getPlots(plr.getWorld()).values()) {
if (p.settings.getAlias().equalsIgnoreCase(alias)) { if (p.settings.getAlias().equalsIgnoreCase(alias)) {
PlayerFunctions.sendMessage(plr, C.ALIAS_IS_TAKEN); PlayerFunctions.sendMessage(plr, C.ALIAS_IS_TAKEN);
return false; return false;
} }
if (Bukkit.getOfflinePlayer(alias).hasPlayedBefore()) { if (Bukkit.getOfflinePlayer(alias).hasPlayedBefore()) {
PlayerFunctions.sendMessage(plr, C.ALIAS_IS_TAKEN); PlayerFunctions.sendMessage(plr, C.ALIAS_IS_TAKEN);
return false; return false;
} }
} }
DBFunc.setAlias(plr.getWorld().getName(), plot, alias); DBFunc.setAlias(plr.getWorld().getName(), plot, alias);
PlayerFunctions.sendMessage(plr, C.ALIAS_SET_TO.s().replaceAll("%alias%", alias)); PlayerFunctions.sendMessage(plr,
return true; C.ALIAS_SET_TO.s().replaceAll("%alias%", alias));
} return true;
if (args[0].equalsIgnoreCase("biome")) { }
if (args.length < 2) { if (args[0].equalsIgnoreCase("biome")) {
PlayerFunctions.sendMessage(plr, C.NEED_BIOME); if (args.length < 2) {
return true; PlayerFunctions.sendMessage(plr, C.NEED_BIOME);
} return true;
Biome biome = null; }
for (Biome b : Biome.values()) { Biome biome = null;
if (b.toString().equalsIgnoreCase(args[1])) { for (Biome b : Biome.values()) {
biome = b; if (b.toString().equalsIgnoreCase(args[1])) {
break; biome = b;
} break;
} }
if (biome == null) { }
PlayerFunctions.sendMessage(plr, getBiomeList(Arrays.asList(Biome.values()))); if (biome == null) {
return true; PlayerFunctions.sendMessage(plr,
} getBiomeList(Arrays.asList(Biome.values())));
PlotHelper.setBiome(plr.getWorld(), plot, biome); return true;
PlayerFunctions.sendMessage(plr, C.BIOME_SET_TO.s() + biome.toString().toLowerCase()); }
return true; PlotHelper.setBiome(plr.getWorld(), plot, biome);
} PlayerFunctions.sendMessage(plr, C.BIOME_SET_TO.s()
if (args[0].equalsIgnoreCase("wall")) { + biome.toString().toLowerCase());
PlotWorld plotworld = PlotMain.getWorldSettings(plr.getWorld()); return true;
if (plotworld == null) { }
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD); if (args[0].equalsIgnoreCase("wall")) {
return true; PlotWorld plotworld = PlotMain.getWorldSettings(plr.getWorld());
} if (plotworld == null) {
if (args.length < 2) { PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD);
PlayerFunctions.sendMessage(plr, C.NEED_BLOCK); return true;
return true; }
} if (args.length < 2) {
Material material = null; PlayerFunctions.sendMessage(plr, C.NEED_BLOCK);
for (Material m : PlotWorld.BLOCKS) { return true;
if (m.toString().equalsIgnoreCase(args[1])) { }
material = m; Material material = null;
break; for (Material m : PlotWorld.BLOCKS) {
} if (m.toString().equalsIgnoreCase(args[1])) {
} material = m;
if (material == null) { break;
PlayerFunctions.sendMessage(plr, getBlockList(PlotWorld.BLOCKS)); }
return true; }
} if (material == null) {
byte data = 0; PlayerFunctions
.sendMessage(plr, getBlockList(PlotWorld.BLOCKS));
return true;
}
byte data = 0;
if (args.length > 2) { if (args.length > 2) {
try { try {
data = (byte) Integer.parseInt(args[2]); data = (byte) Integer.parseInt(args[2]);
} catch (Exception e) { } catch (Exception e) {
PlayerFunctions.sendMessage(plr, C.NOT_VALID_DATA); PlayerFunctions.sendMessage(plr, C.NOT_VALID_DATA);
return true; return true;
} }
} }
PlayerFunctions.sendMessage(plr, C.GENERATING_WALL); PlayerFunctions.sendMessage(plr, C.GENERATING_WALL);
PlotHelper.adjustWall(plr.getWorld(), plot, (short) material.getId(), data); PlotHelper.adjustWall(plr, plot,
return true; new PlotBlock((short) material.getId(), data));
} return true;
if (args[0].equalsIgnoreCase("floor")) { }
if (args.length < 2) { if (args[0].equalsIgnoreCase("floor")) {
PlayerFunctions.sendMessage(plr, C.NEED_BLOCK); if (args.length < 2) {
return true; PlayerFunctions.sendMessage(plr, C.NEED_BLOCK);
} return true;
PlotWorld plotworld = PlotMain.getWorldSettings(plr.getWorld()); }
if (plotworld == null) { PlotWorld plotworld = PlotMain.getWorldSettings(plr.getWorld());
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD); if (plotworld == null) {
return true; PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD);
} return true;
// }
@SuppressWarnings("unchecked") //
ArrayList<Material> materials = (ArrayList<Material>) PlotWorld.BLOCKS.clone(); @SuppressWarnings("unchecked")
materials.add(Material.AIR); ArrayList<Material> materials = (ArrayList<Material>) PlotWorld.BLOCKS
// .clone();
String[] strings = args[1].split(","); materials.add(Material.AIR);
// //
Material[] material = new Material[strings.length]; String[] strings = args[1].split(",");
byte[] data = new byte[strings.length]; //
// int index = 0;
int index = 0; //
// byte b = (byte) 0;
byte b = (byte) 0; Material m = null;
Material m = null; //
// PlotBlock[] blocks = new PlotBlock[strings.length];
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) { for (String s : strings) {
try { s = s.replaceAll(",", "");
data = (byte) Integer.parseInt(args[2]); String[] ss = s.split(";");
} catch (Exception e) { ss[0] = ss[0].replaceAll(";", "");
PlayerFunctions.sendMessage(plr, C.NOT_VALID_DATA); for (Material ma : materials) {
return true; if (ma.toString().equalsIgnoreCase(ss[0])) {
} m = ma;
} }
PlotHelper.adjustWallFilling(plr, plr.getWorld(), plot, (short) material.getId(), data); }
return true; if (m == null) {
} PlayerFunctions.sendMessage(plr, C.NOT_VALID_BLOCK);
StringBuilder builder = new StringBuilder(); return true;
builder.append(C.SUBCOMMAND_SET_OPTIONS_HEADER.s()); }
builder.append(getArgumentList(values)); if (ss.length == 1) {
PlayerFunctions.sendMessage(plr, builder.toString());
return false;
}
private String getMaterial(Material m) { blocks[index] = new PlotBlock((short) m.getId(), (byte) 0);
return ChatColor.translateAlternateColorCodes('&', C.BLOCK_LIST_ITEM.s().replaceAll("%mat%", m.toString().toLowerCase())); } 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) { if (args.length > 2) {
return ChatColor.translateAlternateColorCodes('&', C.BLOCK_LIST_ITEM.s().replaceAll("%mat%", b.toString().toLowerCase())); 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) { private String getMaterial(Material m) {
return ChatColor.translateAlternateColorCodes('&', C.BLOCK_LIST_ITEM.s().replaceAll("%mat%", s)); return ChatColor.translateAlternateColorCodes('&', C.BLOCK_LIST_ITEM
} .s().replaceAll("%mat%", m.toString().toLowerCase()));
}
private String getArgumentList(String[] strings) { private String getBiome(Biome b) {
StringBuilder builder = new StringBuilder(); return ChatColor.translateAlternateColorCodes('&', C.BLOCK_LIST_ITEM
for (String s : strings) { .s().replaceAll("%mat%", b.toString().toLowerCase()));
builder.append(getString(s)); }
}
return builder.toString().substring(1, builder.toString().length() - 1);
}
private String getBiomeList(List<Biome> biomes) { private String getString(String s) {
StringBuilder builder = new StringBuilder(); return ChatColor.translateAlternateColorCodes('&', C.BLOCK_LIST_ITEM
builder.append(ChatColor.translateAlternateColorCodes('&', C.NOT_VALID_BLOCK_LIST_HEADER.s())); .s().replaceAll("%mat%", s));
for (Biome b : biomes) { }
builder.append(getBiome(b));
}
return builder.toString().substring(1, builder.toString().length() - 1);
}
private String getBlockList(List<Material> blocks) { private String getArgumentList(String[] strings) {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
builder.append(ChatColor.translateAlternateColorCodes('&', C.NOT_VALID_BLOCK_LIST_HEADER.s())); for (String s : strings) {
for (Material b : blocks) { builder.append(getString(s));
builder.append(getMaterial(b)); }
} return builder.toString().substring(1, builder.toString().length() - 1);
return builder.toString().substring(1, builder.toString().length() - 1); }
}
private String getBiomeList(List<Biome> 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<Material> 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);
}
} }

View File

@ -9,44 +9,50 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.*; import java.util.UUID;
import com.intellectualcrafters.plot.database.DBFunc;
import org.bukkit.entity.Player; 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") @SuppressWarnings("deprecation")
public class SetOwner extends SubCommand { public class SetOwner extends SubCommand {
public SetOwner() { public SetOwner() {
super("setowner", "plots.admin", "Set the plot owner", "setowner {player}", "so", CommandCategory.ACTIONS); super("setowner", "plots.admin", "Set the plot owner",
} "setowner {player}", "so", CommandCategory.ACTIONS);
}
/* /*
private UUID getUUID(String string) { * private UUID getUUID(String string) { OfflinePlayer player =
OfflinePlayer player = Bukkit.getOfflinePlayer(string); * Bukkit.getOfflinePlayer(string); return ((player != null) &&
return ((player != null) && player.hasPlayedBefore()) ? player.getUniqueId() : null; * player.hasPlayedBefore()) ? player.getUniqueId() : null; }
}*/ */
private UUID getUUID(String string) { private UUID getUUID(String string) {
return UUIDHandler.getUUID(string); return UUIDHandler.getUUID(string);
} }
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(Player plr, String... args) {
if (!PlayerFunctions.isInPlot(plr)) { if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
return true; return true;
} }
Plot plot = PlayerFunctions.getCurrentPlot(plr); Plot plot = PlayerFunctions.getCurrentPlot(plr);
if (args.length < 1) { if (args.length < 1) {
PlayerFunctions.sendMessage(plr, C.NEED_USER); PlayerFunctions.sendMessage(plr, C.NEED_USER);
return true; return true;
} }
plot.owner = getUUID(args[0]); plot.owner = getUUID(args[0]);
PlotMain.updatePlot(plot); PlotMain.updatePlot(plot);
DBFunc.setOwner(plot, plot.owner); DBFunc.setOwner(plot, plot.owner);
PlayerFunctions.sendMessage(plr, C.SET_OWNER); PlayerFunctions.sendMessage(plr, C.SET_OWNER);
return true; return true;
} }
} }

View File

@ -1,16 +1,15 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import java.io.IOException; import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.bukkit.block.Biome;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import com.intellectualcrafters.plot.C; import com.intellectualcrafters.plot.C;
import com.intellectualcrafters.plot.ConfigurationNode;
import com.intellectualcrafters.plot.PlayerFunctions; import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.PlotMain; import com.intellectualcrafters.plot.PlotMain;
import com.intellectualcrafters.plot.PlotWorld; import com.intellectualcrafters.plot.PlotWorld;
@ -20,244 +19,148 @@ import com.intellectualcrafters.plot.PlotWorld;
*/ */
public class Setup extends SubCommand implements Listener { public class Setup extends SubCommand implements Listener {
public static Map<String, SetupObject> setupMap = new HashMap<>(); public static Map<String, SetupObject> setupMap = new HashMap<>();
private static class SetupStep { private class SetupObject {
private String constant; String world;
private Object default_value; int current = 0;
private String description;
private Object value = 0;
private String type;
public SetupStep(String constant, Object default_value, String description, String type, boolean require_previous) { ConfigurationNode[] step;
this.constant = constant;
this.default_value = default_value;
this.description = description;
this.type = type;
}
public String getType() { public SetupObject(String world, PlotWorld plotworld) {
return this.type; this.world = world;
} this.step = plotworld.getSettingNodes();
}
public boolean setValue(String string) { public int getCurrent() {
if (!validValue(string)) { return this.current;
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 boolean validValue(String string) { public int getMax() {
try { return this.step.length;
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 Object getValue() { public Setup() {
if (this.value instanceof String[]) { super("setup", "plots.admin", "Setup a PlotWorld", "setup {world}",
return Arrays.asList((String[]) this.value); "setup", CommandCategory.ACTIONS);
} }
return this.value;
}
public String getConstant() { @Override
return this.constant; public boolean execute(Player plr, String... args) {
} boolean finished = false;
public Object getDefaultValue() { if (!finished) {
if (this.default_value instanceof String[]) { // TODO recode this to work with the multiple generators
return StringUtils.join((String[]) this.default_value, ","); PlayerFunctions
} .sendMessage(plr, "&4CURRENTLY NOT IMPLEMENTED YET!");
return this.default_value;
}
public String getDescription() { return false;
return this.description; }
}
}
private class SetupObject { if (setupMap.containsKey(plr.getName())) {
String world; SetupObject object = setupMap.get(plr.getName());
int current = 0; 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), ConfigurationNode[] steps = object.step;
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), }; 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) { // World newWorld = WorldCreator.name(world).generator(new
this.world = world; // WorldGenerator(world)).createWorld();
} // plr.teleport(newWorld.getSpawnLocation());
public int getCurrent() { setupMap.remove(plr.getName());
return this.current;
}
public int getMax() { return true;
return this.step.length; }
} 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() { PlotWorld plotworld = PlotMain.getWorldSettings("//TODO"); // TODO
super("setup", "plots.admin", "Setup a PlotWorld", "setup {world}", "setup", CommandCategory.ACTIONS);
}
@Override setupMap.put(plr.getName(), new SetupObject(world, plotworld));
public boolean execute(Player plr, String... args) { sendMessage(plr, C.SETUP_INIT);
if (setupMap.containsKey(plr.getName())) { SetupObject object = setupMap.get(plr.getName());
SetupObject object = setupMap.get(plr.getName()); ConfigurationNode step = object.step[object.current];
if (object.getCurrent() == object.getMax()) { sendMessage(plr, C.SETUP_STEP, object.current + 1 + "",
sendMessage(plr, C.SETUP_FINISHED, object.world); step.getDescription(), step.getType(),
step.getDefaultValue() + "");
SetupStep[] steps = object.step; return true;
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;
}
}
} }

View File

@ -22,111 +22,114 @@ import com.intellectualcrafters.plot.PlayerFunctions;
*/ */
public abstract class SubCommand { public abstract class SubCommand {
/** /**
* Command * Command
*/ */
public String cmd; public String cmd;
/** /**
* Permission node * Permission node
*/ */
public CommandPermission permission; public CommandPermission permission;
/** /**
* Simple description * Simple description
*/ */
public String description; public String description;
/** /**
* Alias * Alias
*/ */
public String alias; public String alias;
/** /**
* Command usage * Command usage
*/ */
public String usage; public String usage;
public CommandCategory category; public CommandCategory category;
/** /**
* *
* @param cmd * @param cmd
* Command /plot {cmd} <-- That! * Command /plot {cmd} <-- That!
* @param permission * @param permission
* Permission Node * Permission Node
* @param description * @param description
* Simple description * Simple description
* @param usage * @param usage
* Usage description: /plot command {args...} * Usage description: /plot command {args...}
* @param alias * @param alias
* Command alias * Command alias
* @param category * @param category
* CommandCategory. Pick whichever closests to what you want. * CommandCategory. Pick whichever closests to what you want.
*/ */
public SubCommand(String cmd, String permission, String description, String usage, String alias, CommandCategory category) { public SubCommand(String cmd, String permission, String description,
this.cmd = cmd; String usage, String alias, CommandCategory category) {
this.permission = new CommandPermission(permission); this.cmd = cmd;
this.description = description; this.permission = new CommandPermission(permission);
this.alias = alias; this.description = description;
this.usage = usage; this.alias = alias;
this.category = category; this.usage = usage;
} this.category = category;
}
/** /**
* *
* @param command * @param command
* Command /plot {cmd} <-- That! * Command /plot {cmd} <-- That!
* @param description * @param description
* Simple description * Simple description
* @param usage * @param usage
* Usage description: /plot command {args...} * Usage description: /plot command {args...}
* @param category * @param category
* CommandCategory. Pick whichever closests to what you want. * CommandCategory. Pick whichever closests to what you want.
*/ */
public SubCommand(Command command, String description, String usage, CommandCategory category) { public SubCommand(Command command, String description, String usage,
this.cmd = command.getCommand(); CommandCategory category) {
this.permission = command.getPermission(); this.cmd = command.getCommand();
this.alias = command.getAlias(); this.permission = command.getPermission();
this.description = description; this.alias = command.getAlias();
this.usage = usage; this.description = description;
this.category = category; this.usage = usage;
} this.category = category;
}
/** /**
* Execute. * Execute.
* *
* @param plr * @param plr
* executor * executor
* @param args * @param args
* arguments * arguments
* @return true on success, false on failure * @return true on success, false on failure
*/ */
public abstract boolean execute(Player plr, String... args); public abstract boolean execute(Player plr, String... args);
public void executeConsole(String... args) { public void executeConsole(String... args) {
this.execute(null, args); this.execute(null, args);
} }
/** /**
* Send a message * Send a message
* *
* @param plr * @param plr
* @param c * @param c
* @param args * @param args
*/ */
public void sendMessage(Player plr, C c, String... args) { public void sendMessage(Player plr, C c, String... args) {
PlayerFunctions.sendMessage(plr, c, args); PlayerFunctions.sendMessage(plr, c, args);
} }
public enum CommandCategory { public enum CommandCategory {
CLAIMING("Claiming"), TELEPORT("Teleportation"), ACTIONS("Actions"), INFO("Information"); CLAIMING("Claiming"), TELEPORT("Teleportation"), ACTIONS("Actions"), INFO(
private String name; "Information");
private String name;
CommandCategory(String name) { CommandCategory(String name) {
this.name = name; this.name = name;
} }
@Override @Override
public String toString() { public String toString() {
return this.name; return this.name;
} }
} }
} }

View File

@ -28,65 +28,70 @@ import com.intellectualcrafters.plot.PlotMain;
*/ */
public class TP extends SubCommand { public class TP extends SubCommand {
public TP() { public TP() {
super(Command.TP, "Teleport to a plot", "tp {alias|id}", CommandCategory.TELEPORT); super(Command.TP, "Teleport to a plot", "tp {alias|id}",
} CommandCategory.TELEPORT);
}
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(Player plr, String... args) {
if (args.length < 1) { if (args.length < 1) {
PlayerFunctions.sendMessage(plr, C.NEED_PLOT_ID); PlayerFunctions.sendMessage(plr, C.NEED_PLOT_ID);
return false; return false;
} }
String id = args[0]; String id = args[0];
PlotId plotid; PlotId plotid;
World world = plr.getWorld(); World world = plr.getWorld();
if (args.length == 2) { if (args.length == 2) {
if (Bukkit.getWorld(args[1]) != null) { if (Bukkit.getWorld(args[1]) != null) {
world = Bukkit.getWorld(args[1]); world = Bukkit.getWorld(args[1]);
} }
} }
if (!PlotMain.isPlotWorld(world)) { if (!PlotMain.isPlotWorld(world)) {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD); PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD);
return false; return false;
} }
Plot temp; Plot temp;
if ((temp = isAlias(world, id)) != null) { if ((temp = isAlias(world, id)) != null) {
PlotMain.teleportPlayer(plr, plr.getLocation(), temp); PlotMain.teleportPlayer(plr, plr.getLocation(), temp);
return true; return true;
} }
try { try {
plotid = new PlotId(Integer.parseInt(id.split(";")[0]), Integer.parseInt(id.split(";")[1])); plotid = new PlotId(Integer.parseInt(id.split(";")[0]),
PlotMain.teleportPlayer(plr, plr.getLocation(), PlotHelper.getPlot(world, plotid)); Integer.parseInt(id.split(";")[1]));
return true; PlotMain.teleportPlayer(plr, plr.getLocation(),
} catch (Exception e) { PlotHelper.getPlot(world, plotid));
PlayerFunctions.sendMessage(plr, C.NOT_VALID_PLOT_ID); return true;
} } catch (Exception e) {
return false; PlayerFunctions.sendMessage(plr, C.NOT_VALID_PLOT_ID);
} }
return false;
}
private Plot isAlias(World world, String a) { private Plot isAlias(World world, String a) {
int index = 0; int index = 0;
if (a.contains(";")) { if (a.contains(";")) {
String[] split = a.split(";"); String[] split = a.split(";");
if ((split[1].length() > 0) && StringUtils.isNumeric(split[1])) { if ((split[1].length() > 0) && StringUtils.isNumeric(split[1])) {
index = Integer.parseInt(split[1]); index = Integer.parseInt(split[1]);
} }
a = split[0]; a = split[0];
} }
Player player = Bukkit.getPlayer(a); Player player = Bukkit.getPlayer(a);
if (player != null) { if (player != null) {
Plot[] plots = PlotMain.getPlots(world, player).toArray(new Plot[0]); Plot[] plots = PlotMain.getPlots(world, player)
if (plots.length > index) { .toArray(new Plot[0]);
return plots[index]; if (plots.length > index) {
} return plots[index];
return null; }
} return null;
for (Plot p : PlotMain.getPlots(world).values()) { }
if ((p.settings.getAlias().length() > 0) && p.settings.getAlias().equalsIgnoreCase(a)) { for (Plot p : PlotMain.getPlots(world).values()) {
return p; if ((p.settings.getAlias().length() > 0)
} && p.settings.getAlias().equalsIgnoreCase(a)) {
} return p;
return null; }
} }
return null;
}
} }

View File

@ -9,127 +9,103 @@
package com.intellectualcrafters.plot.commands; 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.C;
import com.intellectualcrafters.plot.PlayerFunctions; import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.Plot; import com.intellectualcrafters.plot.Plot;
import com.intellectualcrafters.plot.UUIDHandler; import com.intellectualcrafters.plot.UUIDHandler;
import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.events.PlayerPlotTrustedEvent; 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") @SuppressWarnings("deprecation")
public class Trusted extends SubCommand { public class Trusted extends SubCommand {
public Trusted() { public Trusted() {
super(Command.TRUSTED, "Manage trusted users for a plot", "trusted {add|remove} {player}", CommandCategory.ACTIONS); super(Command.TRUSTED, "Manage trusted users for a plot",
} "trusted {add|remove} {player}", CommandCategory.ACTIONS);
}
private boolean hasBeenOnServer(String name) { @Override
Player plr = Bukkit.getPlayer(name); public boolean execute(Player plr, String... args) {
if (plr == null) { if (args.length < 2) {
OfflinePlayer oplr = Bukkit.getOfflinePlayer(name); PlayerFunctions.sendMessage(plr, C.TRUSTED_NEED_ARGUMENT);
if (oplr == null) { return true;
return false; }
} else { if (!PlayerFunctions.isInPlot(plr)) {
return oplr.hasPlayedBefore(); PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
} return true;
} else { }
if (plr.isOnline()) { Plot plot = PlayerFunctions.getCurrentPlot(plr);
return true; if ((plot.owner == null) || !plot.hasRights(plr)) {
} else { PlayerFunctions.sendMessage(plr, C.NO_PERMISSION);
return plr.hasPlayedBefore(); return true;
} }
} if (args[0].equalsIgnoreCase("add")) {
} if (args[1].equalsIgnoreCase("*")) {
UUID uuid = DBFunc.everyone;
@Override plot.addTrusted(uuid);
public boolean execute(Player plr, String... args) { DBFunc.setTrusted(plr.getWorld().getName(), plot,
if (args.length < 2) { Bukkit.getOfflinePlayer(args[1]));
PlayerFunctions.sendMessage(plr, C.TRUSTED_NEED_ARGUMENT); PlayerFunctions.sendMessage(plr, C.TRUSTED_ADDED);
return true; return true;
} }
if (!PlayerFunctions.isInPlot(plr)) { /*
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT); * if (!hasBeenOnServer(args[1])) { PlayerFunctions.sendMessage(plr,
return true; * C.PLAYER_HAS_NOT_BEEN_ON); return true; } UUID uuid = null; if
} * ((Bukkit.getPlayer(args[1]) != null)) { uuid =
Plot plot = PlayerFunctions.getCurrentPlot(plr); * Bukkit.getPlayer(args[1]).getUniqueId(); } else { uuid =
if ((plot.owner == null) || !plot.hasRights(plr)) { * Bukkit.getOfflinePlayer(args[1]).getUniqueId(); } if (uuid ==
PlayerFunctions.sendMessage(plr, C.NO_PERMISSION); * null) { PlayerFunctions.sendMessage(plr,
return true; * C.PLAYER_HAS_NOT_BEEN_ON); return true; }
} */
if (args[0].equalsIgnoreCase("add")) { UUID uuid = UUIDHandler.getUUID(args[1]);
if (args[1].equalsIgnoreCase("*")) { plot.addTrusted(uuid);
UUID uuid = DBFunc.everyone; DBFunc.setTrusted(plr.getWorld().getName(), plot,
plot.addTrusted(uuid); Bukkit.getOfflinePlayer(args[1]));
DBFunc.setTrusted(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); PlayerPlotTrustedEvent event = new PlayerPlotTrustedEvent(plr,
PlayerFunctions.sendMessage(plr, C.TRUSTED_ADDED); plot, uuid, true);
return true; Bukkit.getPluginManager().callEvent(event);
} PlayerFunctions.sendMessage(plr, C.TRUSTED_ADDED);
/*if (!hasBeenOnServer(args[1])) { } else if (args[0].equalsIgnoreCase("remove")) {
PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); if (args[1].equalsIgnoreCase("*")) {
return true; UUID uuid = DBFunc.everyone;
} if (!plot.trusted.contains(uuid)) {
UUID uuid = null; PlayerFunctions.sendMessage(plr, C.T_WAS_NOT_ADDED);
if ((Bukkit.getPlayer(args[1]) != null)) { return true;
uuid = Bukkit.getPlayer(args[1]).getUniqueId(); }
} else { plot.removeTrusted(uuid);
uuid = Bukkit.getOfflinePlayer(args[1]).getUniqueId(); DBFunc.removeTrusted(plr.getWorld().getName(), plot,
} Bukkit.getOfflinePlayer(args[1]));
if (uuid == null) { PlayerFunctions.sendMessage(plr, C.TRUSTED_REMOVED);
PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); return true;
return true; }
}*/ /*
UUID uuid = UUIDHandler.getUUID(args[1]); * if (!hasBeenOnServer(args[1])) { PlayerFunctions.sendMessage(plr,
plot.addTrusted(uuid); * C.PLAYER_HAS_NOT_BEEN_ON); return true; } UUID uuid = null; if
DBFunc.setTrusted(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); * (Bukkit.getPlayer(args[1]) != null) { uuid =
PlayerPlotTrustedEvent event = new PlayerPlotTrustedEvent(plr, plot, uuid, true); * Bukkit.getPlayer(args[1]).getUniqueId(); } else { uuid =
Bukkit.getPluginManager().callEvent(event); * Bukkit.getOfflinePlayer(args[1]).getUniqueId(); } if (uuid ==
PlayerFunctions.sendMessage(plr, C.TRUSTED_ADDED); * null) { PlayerFunctions.sendMessage(plr,
} else if (args[0].equalsIgnoreCase("remove")) { * C.PLAYER_HAS_NOT_BEEN_ON); return true; } if
if (args[1].equalsIgnoreCase("*")) { * (!plot.trusted.contains(uuid)) { PlayerFunctions.sendMessage(plr,
UUID uuid = DBFunc.everyone; * C.T_WAS_NOT_ADDED); return true; }
if (!plot.trusted.contains(uuid)) { */
PlayerFunctions.sendMessage(plr, C.T_WAS_NOT_ADDED); UUID uuid = UUIDHandler.getUUID(args[1]);
return true; plot.removeTrusted(uuid);
} DBFunc.removeTrusted(plr.getWorld().getName(), plot,
plot.removeTrusted(uuid); Bukkit.getOfflinePlayer(args[1]));
DBFunc.removeTrusted(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); PlayerPlotTrustedEvent event = new PlayerPlotTrustedEvent(plr,
PlayerFunctions.sendMessage(plr, C.TRUSTED_REMOVED); plot, uuid, false);
return true; Bukkit.getPluginManager().callEvent(event);
} PlayerFunctions.sendMessage(plr, C.TRUSTED_REMOVED);
/* } else {
if (!hasBeenOnServer(args[1])) { PlayerFunctions.sendMessage(plr, C.TRUSTED_NEED_ARGUMENT);
PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); return true;
return true; }
} 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;
}
} }

View File

@ -12,16 +12,15 @@ package com.intellectualcrafters.plot.commands;
import java.util.ArrayList; import java.util.ArrayList;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.intellectualcrafters.plot.C; import com.intellectualcrafters.plot.C;
import com.intellectualcrafters.plot.PlayerFunctions; import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.Plot; import com.intellectualcrafters.plot.Plot;
import com.intellectualcrafters.plot.PlotHelper;
import com.intellectualcrafters.plot.PlotId; import com.intellectualcrafters.plot.PlotId;
import com.intellectualcrafters.plot.PlotMain; import com.intellectualcrafters.plot.PlotMain;
import com.intellectualcrafters.plot.PlotManager;
import com.intellectualcrafters.plot.PlotWorld; import com.intellectualcrafters.plot.PlotWorld;
import com.intellectualcrafters.plot.SetBlockFast; import com.intellectualcrafters.plot.SetBlockFast;
import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.database.DBFunc;
@ -32,186 +31,91 @@ import com.intellectualcrafters.plot.events.PlotUnlinkEvent;
*/ */
public class Unlink extends SubCommand { public class Unlink extends SubCommand {
private short w_id; public Unlink() {
private byte w_v; super(Command.UNLINK, "Unlink a mega-plot", "unlink",
private short wf_id; CommandCategory.ACTIONS);
private byte wf_v; }
private short f1_id;
private byte f1_v;
private int pathsize;
private int wallheight;
private int roadheight;
public Unlink() { @Override
super(Command.UNLINK, "Unlink a mega-plot", "unlink", CommandCategory.ACTIONS); 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<PlotId> ids = PlayerFunctions.getPlotSelectionIds(world,
pos1, pos2);
@Override PlotUnlinkEvent event = new PlotUnlinkEvent(world, ids);
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<PlotId> ids = PlayerFunctions.getPlotSelectionIds(world, pos1, pos2);
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); for (PlotId id : ids) {
if (event.isCancelled()) { Plot myplot = PlotMain.getPlots(world).get(id);
event.setCancelled(true);
PlayerFunctions.sendMessage(plr, "&cUnlink has been cancelled");
return false;
}
for (PlotId id : ids) { if (plot.helpers != null) {
Plot myplot = PlotMain.getPlots(world).get(id); 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) { new PlotId(x, y);
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());
}
PlotWorld plotworld = PlotMain.getWorldSettings(world); if (lx) {
this.pathsize = plotworld.ROAD_WIDTH; manager.removeRoadEast(plotworld, plot);
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];
// WALL FILLING if (ly) {
short[] result_wf = PlotHelper.getBlock(plotworld.WALL_FILLING); manager.removeRoadSouthEast(plotworld, plot);
this.wf_id = result_wf[0]; }
this.wf_v = (byte) result_wf[1];
// 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); if (ly) {
for (int x = pos1.x; x <= pos2.x; x++) { manager.removeRoadSouth(plotworld, plot);
for (int y = pos1.y; y <= pos2.y; y++) { }
boolean lx = x < pos2.x;
boolean ly = y < pos2.y;
PlotId id = new PlotId(x, y); }
}
if (lx) { try {
setRoadX(world, id); SetBlockFast.update(plr);
} catch (Exception e) {
if (ly) { }
setRoadXY(world, id);
}
} PlayerFunctions.sendMessage(plr, "&6Plots unlinked successfully!");
return true;
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 });
}
} }

View File

@ -22,51 +22,53 @@ import com.intellectualcrafters.plot.Plot;
import com.intellectualcrafters.plot.PlotMain; import com.intellectualcrafters.plot.PlotMain;
public class Visit extends SubCommand { public class Visit extends SubCommand {
public Visit() { public Visit() {
super("visit", "plots.visit", "Visit someones plot", "visit {player} [#]", "v", CommandCategory.TELEPORT); super("visit", "plots.visit", "Visit someones plot",
} "visit {player} [#]", "v", CommandCategory.TELEPORT);
}
public List<Plot> getPlots(UUID uuid) { public List<Plot> getPlots(UUID uuid) {
List<Plot> plots = new ArrayList<>(); List<Plot> plots = new ArrayList<>();
for (Plot p : PlotMain.getPlots()) { for (Plot p : PlotMain.getPlots()) {
if (p.owner.equals(uuid)) { if (p.owner.equals(uuid)) {
plots.add(p); plots.add(p);
} }
} }
return plots; return plots;
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(Player plr, String... args) {
if (args.length < 1) { if (args.length < 1) {
PlayerFunctions.sendMessage(plr, C.NEED_USER); PlayerFunctions.sendMessage(plr, C.NEED_USER);
return true; return true;
} }
String username = args[0]; String username = args[0];
List<Plot> plots = getPlots(Bukkit.getOfflinePlayer(username).getUniqueId()); List<Plot> plots = getPlots(Bukkit.getOfflinePlayer(username)
if (plots.isEmpty()) { .getUniqueId());
PlayerFunctions.sendMessage(plr, C.FOUND_NO_PLOTS); if (plots.isEmpty()) {
return true; PlayerFunctions.sendMessage(plr, C.FOUND_NO_PLOTS);
} return true;
if (args.length < 2) { }
Plot plot = plots.get(0); if (args.length < 2) {
PlotMain.teleportPlayer(plr, plr.getLocation(), plot); Plot plot = plots.get(0);
return true; PlotMain.teleportPlayer(plr, plr.getLocation(), plot);
} return true;
int i; }
try { int i;
i = Integer.parseInt(args[1]); try {
} catch (Exception e) { i = Integer.parseInt(args[1]);
PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER); } catch (Exception e) {
return true; PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER);
} return true;
if ((i < 0) || (i > plots.size())) { }
PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER); if ((i < 0) || (i > plots.size())) {
return true; PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER);
} return true;
Plot plot = plots.get(i); }
PlotMain.teleportPlayer(plr, plr.getLocation(), plot); Plot plot = plots.get(i);
return true; PlotMain.teleportPlayer(plr, plr.getLocation(), plot);
} return true;
}
} }

View File

@ -9,12 +9,18 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.*; import java.util.HashMap;
import java.util.UUID;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import java.util.HashMap; import com.intellectualcrafters.plot.C;
import java.util.UUID; 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;
/** /**
* *
@ -23,92 +29,136 @@ import java.util.UUID;
*/ */
public class list extends SubCommand { public class list extends SubCommand {
public list() { public list() {
super(Command.LIST, "List all plots", "list {mine|all|world}", CommandCategory.INFO); super(Command.LIST, "List all plots", "list {mine|all|world}",
} CommandCategory.INFO);
}
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(Player plr, String... args) {
if (args.length < 1) { if (args.length < 1) {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
builder.append(C.SUBCOMMAND_SET_OPTIONS_HEADER.s()); builder.append(C.SUBCOMMAND_SET_OPTIONS_HEADER.s());
builder.append(getArgumentList(new String[] { "mine", "shared", "world", "all" })); builder.append(getArgumentList(new String[] { "mine", "shared",
PlayerFunctions.sendMessage(plr, builder.toString()); "world", "all" }));
return true; PlayerFunctions.sendMessage(plr, builder.toString());
} return true;
if (args[0].equalsIgnoreCase("mine")) { }
StringBuilder string = new StringBuilder(); if (args[0].equalsIgnoreCase("mine")) {
string.append(C.PLOT_LIST_HEADER.s().replaceAll("%word%", "your") + "\n"); StringBuilder string = new StringBuilder();
int idx = 0; string.append(C.PLOT_LIST_HEADER.s().replaceAll("%word%", "your")
for (Plot p : PlotMain.getPlots(plr)) { + "\n");
string.append(C.PLOT_LIST_ITEM.s().replaceAll("%id%", p.id.x + ";" + p.id.y + ";" + p.world).replaceAll("%owner%", getName(p.owner)) + "\n"); int idx = 0;
idx++; for (Plot p : PlotMain.getPlots(plr)) {
} string.append(C.PLOT_LIST_ITEM
if (idx == 0) { .s()
PlayerFunctions.sendMessage(plr, C.NO_PLOTS); .replaceAll("%id%",
return true; p.id.x + ";" + p.id.y + ";" + p.world)
} .replaceAll("%owner%", getName(p.owner))
string.append(C.PLOT_LIST_FOOTER.s().replaceAll("%word%", "You have").replaceAll("%num%", idx + "").replaceAll("%plot%", idx == 1 ? "plot" : "plots")); + "\n");
PlayerFunctions.sendMessage(plr, string.toString()); idx++;
return true; }
} else if (args[0].equalsIgnoreCase("shared")) { if (idx == 0) {
StringBuilder string = new StringBuilder(); PlayerFunctions.sendMessage(plr, C.NO_PLOTS);
string.append(C.PLOT_LIST_HEADER.s().replaceAll("%word%", "all") + "\n"); return true;
for (Plot p : PlotMain.getPlots()) { }
if (p.helpers.contains(plr.getUniqueId())) { string.append(C.PLOT_LIST_FOOTER.s()
string.append(C.PLOT_LIST_ITEM.s().replaceAll("%id%", p.id.x + ";" + p.id.y + ";" + p.world).replaceAll("%owner%", getName(p.owner)) + "\n"); .replaceAll("%word%", "You have")
} .replaceAll("%num%", idx + "")
} .replaceAll("%plot%", idx == 1 ? "plot" : "plots"));
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());
PlayerFunctions.sendMessage(plr, string.toString()); return true;
return true; } else if (args[0].equalsIgnoreCase("shared")) {
} else if (args[0].equalsIgnoreCase("all")) { StringBuilder string = new StringBuilder();
StringBuilder string = new StringBuilder(); string.append(C.PLOT_LIST_HEADER.s().replaceAll("%word%", "all")
string.append(C.PLOT_LIST_HEADER.s().replaceAll("%word%", "all") + "\n"); + "\n");
for (Plot p : PlotMain.getPlots()) { 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"); if (p.helpers.contains(plr.getUniqueId())) {
} string.append(C.PLOT_LIST_ITEM
string.append(C.PLOT_LIST_FOOTER.s().replaceAll("%word%", "There is").replaceAll("%num%", PlotMain.getPlots().size() + "").replaceAll("%plot%", PlotMain.getPlots().size() == 1 ? "plot" : "plots")); .s()
PlayerFunctions.sendMessage(plr, string.toString()); .replaceAll("%id%",
return true; p.id.x + ";" + p.id.y + ";" + p.world)
} else if (args[0].equalsIgnoreCase("world")) { .replaceAll("%owner%", getName(p.owner))
StringBuilder string = new StringBuilder(); + "\n");
string.append(C.PLOT_LIST_HEADER.s().replaceAll("%word%", "all") + "\n"); }
HashMap<PlotId, Plot> plots = PlotMain.getPlots(plr.getWorld()); }
for (Plot p : plots.values()) { string.append(C.PLOT_LIST_FOOTER
string.append(C.PLOT_LIST_ITEM.s().replaceAll("%id%", p.id.x + ";" + p.id.y + ";" + p.world).replaceAll("%owner%", getName(p.owner)) + "\n"); .s()
} .replaceAll("%word%", "There is")
string.append(C.PLOT_LIST_FOOTER.s().replaceAll("%word%", "There is").replaceAll("%num%", plots.values().size() + "").replaceAll("%plot%", plots.values().size() == 1 ? "plot" : "plots")); .replaceAll("%num%", PlotMain.getPlots().size() + "")
PlayerFunctions.sendMessage(plr, string.toString()); .replaceAll("%plot%",
return true; PlotMain.getPlots().size() == 1 ? "plot" : "plots"));
} else { PlayerFunctions.sendMessage(plr, string.toString());
execute(plr); return true;
return false; } 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<PlotId, Plot> 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) { private static String getName(UUID id) {
if (id == null) { if (id == null) {
return "none"; return "none";
} }
/*String name = Bukkit.getOfflinePlayer(id).getName(); /*
if (name == null) { * String name = Bukkit.getOfflinePlayer(id).getName(); if (name ==
return "none"; * null) { return "none"; } return name;
} */
return name;*/ return UUIDHandler.getName(id);
return UUIDHandler.getName(id); }
}
private String getArgumentList(String[] strings) { private String getArgumentList(String[] strings) {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
for (String s : strings) { for (String s : strings) {
builder.append(getString(s)); builder.append(getString(s));
} }
return builder.toString().substring(1, builder.toString().length() - 1); return builder.toString().substring(1, builder.toString().length() - 1);
} }
private String getString(String s) { private String getString(String s) {
return ChatColor.translateAlternateColorCodes('&', C.BLOCK_LIST_ITEM.s().replaceAll("%mat%", s)); return ChatColor.translateAlternateColorCodes('&', C.BLOCK_LIST_ITEM
} .s().replaceAll("%mat%", s));
}
} }

View File

@ -9,69 +9,80 @@
package com.intellectualcrafters.plot.commands; 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.BufferedReader;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.net.URL; import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
import java.util.ArrayList; 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 class plugin extends SubCommand {
public plugin() { public plugin() {
super("plugin", "plots.use", "Show plugin information", "plugin", "pl", CommandCategory.INFO); super("plugin", "plots.use", "Show plugin information", "plugin", "pl",
} CommandCategory.INFO);
}
@Override @Override
public boolean execute(final Player plr, String... args) { public boolean execute(final Player plr, String... args) {
Bukkit.getScheduler().runTaskAsynchronously(JavaPlugin.getPlugin(PlotMain.class), new Runnable() { Bukkit.getScheduler().runTaskAsynchronously(
@Override JavaPlugin.getPlugin(PlotMain.class), new Runnable() {
public void run() { @Override
ArrayList<String> strings = new ArrayList<String>() { public void run() {
{ ArrayList<String> strings = new ArrayList<String>() {
String {
downloads = getInfo("https://intellectualsites.com/spigot_api.php?method=downloads&url=http://www.spigotmc.org/resources/plotsquared.1177/"), 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");
version = getInfo("https://intellectualsites.com/spigot_api.php?method=version&resource=1177"); add(String.format(
add(String.format("&c>> &6PlotSquared (Version: %s)", PlotMain.getMain().getDescription().getVersion())); "&c>> &6PlotSquared (Version: %s)",
add(String.format("&c>> &6Made by Citymonstret and Empire92")); PlotMain.getMain().getDescription()
add(String.format("&c>> &6Download at &lhttp://i-s.link/ps")); .getVersion()));
add(String.format("&c>> &cNewest Version (Spigot): %s", version)); add(String
add(String.format("&c>> &cTotal Downloads (Spigot): %s", downloads)); .format("&c>> &6Made by Citymonstret and Empire92"));
} add(String
}; .format("&c>> &6Download at &lhttp://i-s.link/ps"));
for (String s : strings) { add(String.format(
PlayerFunctions.sendMessage(plr, s); "&c>> &cNewest Version (Spigot): %s",
} version));
} add(String.format(
}); "&c>> &cTotal Downloads (Spigot): %s",
return true; downloads));
} }
};
for (String s : strings) {
PlayerFunctions.sendMessage(plr, s);
}
}
});
return true;
}
/** /**
* *
* @param link * @param link
* @return * @return
*/ */
private String getInfo(String link) { private String getInfo(String link) {
try { try {
URLConnection connection = new URL(link).openConnection(); URLConnection connection = new URL(link).openConnection();
connection.addRequestProperty("User-Agent", "Mozilla/4.0"); connection.addRequestProperty("User-Agent", "Mozilla/4.0");
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); BufferedReader reader = new BufferedReader(new InputStreamReader(
String document = "", line; connection.getInputStream()));
while ((line = reader.readLine()) != null) { String document = "", line;
document += (line + "\n"); while ((line = reader.readLine()) != null) {
} document += (line + "\n");
reader.close(); }
return document; reader.close();
} catch(Exception e) { return document;
e.printStackTrace(); } catch (Exception e) {
return ""; e.printStackTrace();
} return "";
} }
}
} }

View File

@ -15,84 +15,87 @@ import org.bukkit.plugin.Plugin;
*/ */
public abstract class Database { public abstract class Database {
/** /**
* Plugin instance, use for plugin.getDataFolder() * Plugin instance, use for plugin.getDataFolder()
*/ */
protected Plugin plugin; protected Plugin plugin;
/** /**
* Creates a new Database * Creates a new Database
* *
* @param plugin * @param plugin
* Plugin instance * Plugin instance
*/ */
protected Database(Plugin plugin) { protected Database(Plugin plugin) {
this.plugin = plugin; this.plugin = plugin;
} }
/** /**
* Opens a connection with the database * Opens a connection with the database
* *
* @return Opened connection * @return Opened connection
* @throws SQLException * @throws SQLException
* if the connection can not be opened * if the connection can not be opened
* @throws ClassNotFoundException * @throws ClassNotFoundException
* if the driver cannot be found * if the driver cannot be found
*/ */
public abstract Connection openConnection() throws SQLException, ClassNotFoundException; public abstract Connection openConnection() throws SQLException,
ClassNotFoundException;
/** /**
* Checks if a connection is open with the database * Checks if a connection is open with the database
* *
* @return true if the connection is open * @return true if the connection is open
* @throws SQLException * @throws SQLException
* if the connection cannot be checked * if the connection cannot be checked
*/ */
public abstract boolean checkConnection() throws SQLException; public abstract boolean checkConnection() throws SQLException;
/** /**
* Gets the connection with the database * Gets the connection with the database
* *
* @return Connection with the database, null if none * @return Connection with the database, null if none
*/ */
public abstract Connection getConnection(); public abstract Connection getConnection();
/** /**
* Closes the connection with the database * Closes the connection with the database
* *
* @return true if successful * @return true if successful
* @throws SQLException * @throws SQLException
* if the connection cannot be closed * if the connection cannot be closed
*/ */
public abstract boolean closeConnection() throws SQLException; public abstract boolean closeConnection() throws SQLException;
/** /**
* Executes a SQL Query<br> * Executes a SQL Query<br>
* *
* If the connection is closed, it will be opened * If the connection is closed, it will be opened
* *
* @param query * @param query
* Query to be run * Query to be run
* @return the results of the query * @return the results of the query
* @throws SQLException * @throws SQLException
* If the query cannot be executed * If the query cannot be executed
* @throws ClassNotFoundException * @throws ClassNotFoundException
* If the driver cannot be found; see {@link #openConnection()} * If the driver cannot be found; see {@link #openConnection()}
*/ */
public abstract ResultSet querySQL(String query) throws SQLException, ClassNotFoundException; public abstract ResultSet querySQL(String query) throws SQLException,
ClassNotFoundException;
/** /**
* Executes an Update SQL Query<br> * Executes an Update SQL Query<br>
* See {@link java.sql.Statement#executeUpdate(String)}<br> * See {@link java.sql.Statement#executeUpdate(String)}<br>
* If the connection is closed, it will be opened * If the connection is closed, it will be opened
* *
* @param query * @param query
* Query to be run * Query to be run
* @return Result Code, see {@link java.sql.Statement#executeUpdate(String)} * @return Result Code, see {@link java.sql.Statement#executeUpdate(String)}
* @throws SQLException * @throws SQLException
* If the query cannot be executed * If the query cannot be executed
* @throws ClassNotFoundException * @throws ClassNotFoundException
* If the driver cannot be found; see {@link #openConnection()} * If the driver cannot be found; see {@link #openConnection()}
*/ */
public abstract int updateSQL(String query) throws SQLException, ClassNotFoundException; public abstract int updateSQL(String query) throws SQLException,
ClassNotFoundException;
} }

View File

@ -15,93 +15,99 @@ import org.bukkit.plugin.Plugin;
* @author tips48 * @author tips48
*/ */
public class MySQL extends Database { public class MySQL extends Database {
private final String user; private final String user;
private final String database; private final String database;
private final String password; private final String password;
private final String port; private final String port;
private final String hostname; private final String hostname;
private Connection connection; private Connection connection;
/** /**
* Creates a new MySQL instance * Creates a new MySQL instance
* *
* @param plugin * @param plugin
* Plugin instance * Plugin instance
* @param hostname * @param hostname
* Name of the host * Name of the host
* @param port * @param port
* Port number * Port number
* @param database * @param database
* Database name * Database name
* @param username * @param username
* Username * Username
* @param password * @param password
* Password * Password
*/ */
public MySQL(Plugin plugin, String hostname, String port, String database, String username, String password) { public MySQL(Plugin plugin, String hostname, String port, String database,
super(plugin); String username, String password) {
this.hostname = hostname; super(plugin);
this.port = port; this.hostname = hostname;
this.database = database; this.port = port;
this.user = username; this.database = database;
this.password = password; this.user = username;
this.connection = null; this.password = password;
} this.connection = null;
}
@Override @Override
public Connection openConnection() throws SQLException, ClassNotFoundException { public Connection openConnection() throws SQLException,
if (checkConnection()) { ClassNotFoundException {
return this.connection; 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); Class.forName("com.mysql.jdbc.Driver");
return this.connection; this.connection = DriverManager.getConnection("jdbc:mysql://"
} + this.hostname + ":" + this.port + "/" + this.database,
this.user, this.password);
return this.connection;
}
@Override @Override
public boolean checkConnection() throws SQLException { public boolean checkConnection() throws SQLException {
return (this.connection != null) && !this.connection.isClosed(); return (this.connection != null) && !this.connection.isClosed();
} }
@Override @Override
public Connection getConnection() { public Connection getConnection() {
return this.connection; return this.connection;
} }
@Override @Override
public boolean closeConnection() throws SQLException { public boolean closeConnection() throws SQLException {
if (this.connection == null) { if (this.connection == null) {
return false; return false;
} }
this.connection.close(); this.connection.close();
return true; return true;
} }
@Override @Override
public ResultSet querySQL(String query) throws SQLException, ClassNotFoundException { public ResultSet querySQL(String query) throws SQLException,
if (checkConnection()) { ClassNotFoundException {
openConnection(); 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 @Override
public int updateSQL(String query) throws SQLException, ClassNotFoundException { public int updateSQL(String query) throws SQLException,
if (checkConnection()) { ClassNotFoundException {
openConnection(); 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;
} }
} }

View File

@ -1,7 +1,5 @@
package com.intellectualcrafters.plot.database; package com.intellectualcrafters.plot.database;
import java.io.File;
import java.io.FilenameFilter;
import java.io.PrintStream; import java.io.PrintStream;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.ArrayList; import java.util.ArrayList;
@ -25,130 +23,190 @@ import com.worldcretornica.plotme.PlotManager;
*/ */
public class PlotMeConverter { public class PlotMeConverter {
private PlotMain plugin; private PlotMain plugin;
public PlotMeConverter(PlotMain plugin) { public PlotMeConverter(PlotMain plugin) {
this.plugin = 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() { Bukkit.getScheduler().runTaskAsynchronously(this.plugin,
@Override new Runnable() {
public void run() { @Override
PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Conversion has started"); public void run() {
PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Caching playerdata..."); PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Conversion has started");
ArrayList<com.intellectualcrafters.plot.Plot> createdPlots = new ArrayList<com.intellectualcrafters.plot.Plot>(); PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Caching playerdata...");
boolean online = Bukkit.getServer().getOnlineMode(); ArrayList<com.intellectualcrafters.plot.Plot> createdPlots = new ArrayList<com.intellectualcrafters.plot.Plot>();
for (World world : Bukkit.getWorlds()) { boolean online = Bukkit.getServer().getOnlineMode();
HashMap<String, Plot> plots = PlotManager.getPlots(world); for (World world : Bukkit.getWorlds()) {
if (plots != null) { HashMap<String, Plot> plots = PlotManager
PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Processing '" + plots.size() + "' plots for world '" + world.getName() + "'"); .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() + "'..."); PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Converting "
for (Plot plot : plots.values()) { + plots.size()
ArrayList<UUID> psAdded = new ArrayList<>(); + " plots for '"
ArrayList<UUID> psTrusted = new ArrayList<>(); + world.toString() + "'...");
ArrayList<UUID> psDenied = new ArrayList<>(); for (Plot plot : plots.values()) {
if (world == null) { ArrayList<UUID> psAdded = new ArrayList<>();
world = Bukkit.getWorld("world"); ArrayList<UUID> psTrusted = new ArrayList<>();
} ArrayList<UUID> psDenied = new ArrayList<>();
long eR3040bl230 = 22392948l; if (world == null) {
try { world = Bukkit.getWorld("world");
if (online) { }
PlayerList denied = null; long eR3040bl230 = 22392948l;
PlayerList added = null; try {
Field fAdded = plot.getClass().getDeclaredField("allowed"); if (online) {
Field fDenied = plot.getClass().getDeclaredField("denied"); PlayerList denied = null;
fAdded.setAccessible(true); PlayerList added = null;
fDenied.setAccessible(true); Field fAdded = plot
added = (PlayerList) fAdded.get(plot); .getClass()
denied = (PlayerList) fDenied.get(plot); .getDeclaredField("allowed");
for (Map.Entry<String, UUID> set : added.getAllPlayers().entrySet()) { Field fDenied = plot.getClass()
if ((set.getValue() != null) || set.getKey().equals("*")) { .getDeclaredField("denied");
if (set.getKey().equalsIgnoreCase("*") || set.getValue().toString().equals("*")) { fAdded.setAccessible(true);
psAdded.add(DBFunc.everyone); fDenied.setAccessible(true);
continue; added = (PlayerList) fAdded
} .get(plot);
} denied = (PlayerList) fDenied
if (set.getValue() != null) { .get(plot);
psAdded.add(set.getValue()); for (Map.Entry<String, UUID> set : added
} .getAllPlayers().entrySet()) {
} if ((set.getValue() != null)
for (Map.Entry<String, UUID> set : denied.getAllPlayers().entrySet()) { || set.getKey().equals(
if ((set.getValue() != null) || set.getKey().equals("*")) { "*")) {
if (set.getKey().equals("*") || set.getValue().toString().equals("*")) { if (set.getKey()
psDenied.add(DBFunc.everyone); .equalsIgnoreCase(
continue; "*")
} || set.getValue()
} .toString()
if (set.getValue() != null) { .equals("*")) {
psDenied.add(set.getValue()); psAdded.add(DBFunc.everyone);
} continue;
} }
} else { }
for (String user : plot.getAllowed().split(",")) { if (set.getValue() != null) {
if (user.equals("*")) { psAdded.add(set.getValue());
psAdded.add(DBFunc.everyone); }
} else { }
UUID uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + user).getBytes(Charsets.UTF_8)); for (Map.Entry<String, UUID> set : denied
psAdded.add(uuid); .getAllPlayers().entrySet()) {
} if ((set.getValue() != null)
} || set.getKey().equals(
try { "*")) {
for (String user : plot.getDenied().split(",")) { if (set.getKey()
if (user.equals("*")) { .equals("*")
psDenied.add(DBFunc.everyone); || set.getValue()
} else { .toString()
UUID uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + user).getBytes(Charsets.UTF_8)); .equals("*")) {
psDenied.add(uuid); psDenied.add(DBFunc.everyone);
} continue;
} }
} catch (Throwable e) { }
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) { } catch (Throwable e) {
e.printStackTrace(); e.printStackTrace();
eR3040bl230 = 232000499888388747l; eR3040bl230 = 232000499888388747l;
} finally { } finally {
eR3040bl230 = 232999304998392004l; eR3040bl230 = 232999304998392004l;
} }
stream.println(eR3040bl230); stream.println(eR3040bl230);
PlotId id = new PlotId(Integer.parseInt(plot.id.split(";")[0]), Integer.parseInt(plot.id.split(";")[1])); PlotId id = new PlotId(
com.intellectualcrafters.plot.Plot pl = null; Integer.parseInt(plot.id.split(";")[0]),
if (online) { Integer.parseInt(plot.id.split(";")[1]));
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 }); com.intellectualcrafters.plot.Plot pl = null;
} else { if (online) {
String owner = plot.getOwner(); pl = new com.intellectualcrafters.plot.Plot(
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 }); 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 // TODO createPlot doesn't add helpers /
// users // denied
if (pl != null) { // users
createdPlots.add(pl); 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 plot DB");
PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Creating settings/helpers DB"); DBFunc.createPlots(createdPlots);
DBFunc.createAllSettingsAndHelpers(createdPlots); PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Creating settings/helpers DB");
stream.close(); DBFunc.createAllSettingsAndHelpers(createdPlots);
PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Conversion has finished"); stream.close();
// TODO disable PlotMe -> Unload all plot worlds, change the PlotMain.sendConsoleSenderMessage("&3PlotMe&8->&3PlotSquared&8: &7Conversion has finished");
// generator, restart the server automatically // TODO disable PlotMe -> Unload all plot worlds, change
// Possibly use multiverse / multiworld if it's to difficult // the
// modifying a world's generator while the server is running // generator, restart the server automatically
// Should really do that? Would seem pretty bad from our side + // Possibly use multiverse / multiworld if it's to
// bukkit wouldn't approve // 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);
}); }
} });
}
} }

View File

@ -19,85 +19,91 @@ import org.bukkit.plugin.Plugin;
*/ */
public class SQLite extends Database { public class SQLite extends Database {
private Connection connection; private Connection connection;
private final String dbLocation; private final String dbLocation;
/** /**
* Creates a new SQLite instance * Creates a new SQLite instance
* *
* @param plugin * @param plugin
* Plugin instance * Plugin instance
* @param dbLocation * @param dbLocation
* Location of the Database (Must end in .db) * Location of the Database (Must end in .db)
*/ */
public SQLite(Plugin plugin, String dbLocation) { public SQLite(Plugin plugin, String dbLocation) {
super(plugin); super(plugin);
this.dbLocation = dbLocation; this.dbLocation = dbLocation;
} }
@Override @Override
public Connection openConnection() throws SQLException, ClassNotFoundException { public Connection openConnection() throws SQLException,
if (checkConnection()) { ClassNotFoundException {
return this.connection; if (checkConnection()) {
} return this.connection;
if (!this.plugin.getDataFolder().exists()) { }
this.plugin.getDataFolder().mkdirs(); if (!this.plugin.getDataFolder().exists()) {
} this.plugin.getDataFolder().mkdirs();
File file = new File(this.plugin.getDataFolder(), this.dbLocation); }
if (!(file.exists())) { File file = new File(this.plugin.getDataFolder(), this.dbLocation);
try { if (!(file.exists())) {
file.createNewFile(); try {
} catch (IOException e) { file.createNewFile();
this.plugin.getLogger().log(Level.SEVERE, "Unable to create database!"); } 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; Class.forName("org.sqlite.JDBC");
} this.connection = DriverManager.getConnection("jdbc:sqlite:"
+ this.plugin.getDataFolder().toPath().toString() + "/"
+ this.dbLocation);
return this.connection;
}
@Override @Override
public boolean checkConnection() throws SQLException { public boolean checkConnection() throws SQLException {
return (this.connection != null) && !this.connection.isClosed(); return (this.connection != null) && !this.connection.isClosed();
} }
@Override @Override
public Connection getConnection() { public Connection getConnection() {
return this.connection; return this.connection;
} }
@Override @Override
public boolean closeConnection() throws SQLException { public boolean closeConnection() throws SQLException {
if (this.connection == null) { if (this.connection == null) {
return false; return false;
} }
this.connection.close(); this.connection.close();
return true; return true;
} }
@Override @Override
public ResultSet querySQL(String query) throws SQLException, ClassNotFoundException { public ResultSet querySQL(String query) throws SQLException,
if (checkConnection()) { ClassNotFoundException {
openConnection(); 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 @Override
public int updateSQL(String query) throws SQLException, ClassNotFoundException { public int updateSQL(String query) throws SQLException,
if (checkConnection()) { ClassNotFoundException {
openConnection(); 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;
} }
} }

View File

@ -20,47 +20,47 @@ import com.intellectualcrafters.plot.Plot;
* Created by Citymonstret on 2014-08-09. * Created by Citymonstret on 2014-08-09.
*/ */
public class PlayerClaimPlotEvent extends PlayerEvent implements Cancellable { public class PlayerClaimPlotEvent extends PlayerEvent implements Cancellable {
private static HandlerList handlers = new HandlerList(); private static HandlerList handlers = new HandlerList();
private boolean cancelled; private boolean cancelled;
private Plot plot; private Plot plot;
/** /**
* PlayerClaimPlotEvent: Called when a plot is claimed * PlayerClaimPlotEvent: Called when a plot is claimed
* *
* @param player * @param player
* @param plot * @param plot
*/ */
public PlayerClaimPlotEvent(Player player, Plot plot) { public PlayerClaimPlotEvent(Player player, Plot plot) {
super(player); super(player);
this.plot = plot; this.plot = plot;
} }
/** /**
* Get the plot involved * Get the plot involved
* *
* @return Plot * @return Plot
*/ */
public Plot getPlot() { public Plot getPlot() {
return this.plot; return this.plot;
} }
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
@Override @Override
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
@Override @Override
public boolean isCancelled() { public boolean isCancelled() {
return this.cancelled; return this.cancelled;
} }
@Override @Override
public void setCancelled(boolean b) { public void setCancelled(boolean b) {
this.cancelled = b; this.cancelled = b;
} }
} }

View File

@ -11,33 +11,33 @@ import com.intellectualcrafters.plot.Plot;
*/ */
public class PlayerEnterPlotEvent extends PlayerEvent { 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 * PlayerEnterPlotEvent: Called when a player leaves a plot
* *
* @param player * @param player
* @param plot * @param plot
*/ */
public PlayerEnterPlotEvent(Player player, Plot plot) { public PlayerEnterPlotEvent(Player player, Plot plot) {
super(player); super(player);
this.plot = plot; this.plot = plot;
} }
/** /**
* Get the plot involved * Get the plot involved
* *
* @return Plot * @return Plot
*/ */
public Plot getPlot() { public Plot getPlot() {
return this.plot; return this.plot;
} }
@Override @Override
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
} }

View File

@ -10,32 +10,32 @@ import com.intellectualcrafters.plot.Plot;
* Created by Citymonstret on 2014-08-16. * Created by Citymonstret on 2014-08-16.
*/ */
public class PlayerLeavePlotEvent extends PlayerEvent { 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 * PlayerLeavePlotEvent: Called when a player leaves a plot
* *
* @param player * @param player
* @param plot * @param plot
*/ */
public PlayerLeavePlotEvent(Player player, Plot plot) { public PlayerLeavePlotEvent(Player player, Plot plot) {
super(player); super(player);
this.plot = plot; this.plot = plot;
} }
/** /**
* Get the plot involved * Get the plot involved
* *
* @return Plot * @return Plot
*/ */
public Plot getPlot() { public Plot getPlot() {
return this.plot; return this.plot;
} }
@Override @Override
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
} }

View File

@ -12,67 +12,68 @@ import com.intellectualcrafters.plot.Plot;
* Created by Citymonstret on 2014-08-16. * Created by Citymonstret on 2014-08-16.
*/ */
public class PlayerPlotDeniedEvent extends Event { public class PlayerPlotDeniedEvent extends Event {
private static HandlerList handlers = new HandlerList(); private static HandlerList handlers = new HandlerList();
private Plot plot; private Plot plot;
private Player initiator; private Player initiator;
private boolean added; private boolean added;
private UUID player; private UUID player;
/** /**
* PlayerPlotDeniedEvent: Called when the denied UUID list is modified for a * PlayerPlotDeniedEvent: Called when the denied UUID list is modified for a
* plot * plot
* *
* @param initiator * @param initiator
* @param plot * @param plot
* @param player * @param player
* @param added * @param added
*/ */
public PlayerPlotDeniedEvent(Player initiator, Plot plot, UUID player, boolean added) { public PlayerPlotDeniedEvent(Player initiator, Plot plot, UUID player,
this.initiator = initiator; boolean added) {
this.plot = plot; this.initiator = initiator;
this.added = added; this.plot = plot;
this.player = player; this.added = added;
} this.player = player;
}
/** /**
* If a user was added * If a user was added
* *
* @return boolean * @return boolean
*/ */
public boolean wasAdded() { public boolean wasAdded() {
return this.added; return this.added;
} }
/** /**
* The player added/removed * The player added/removed
* *
* @return UUID * @return UUID
*/ */
public UUID getPlayer() { public UUID getPlayer() {
return this.player; return this.player;
} }
/** /**
* The plot involved * The plot involved
* *
* @return Plot * @return Plot
*/ */
public Plot getPlot() { public Plot getPlot() {
return this.plot; return this.plot;
} }
/** /**
* The player initiating the action * The player initiating the action
* *
* @return Player * @return Player
*/ */
public Player getInitiator() { public Player getInitiator() {
return this.initiator; return this.initiator;
} }
@Override @Override
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
} }

View File

@ -12,66 +12,67 @@ import com.intellectualcrafters.plot.Plot;
* Created by Citymonstret on 2014-08-16. * Created by Citymonstret on 2014-08-16.
*/ */
public class PlayerPlotHelperEvent extends Event { public class PlayerPlotHelperEvent extends Event {
private static HandlerList handlers = new HandlerList(); private static HandlerList handlers = new HandlerList();
private Plot plot; private Plot plot;
private Player initiator; private Player initiator;
private boolean added; private boolean added;
private UUID player; private UUID player;
/** /**
* PlayerPlotHelperEvent: Called when a plot helper is added/removed * PlayerPlotHelperEvent: Called when a plot helper is added/removed
* *
* @param initiator * @param initiator
* @param plot * @param plot
* @param player * @param player
* @param added * @param added
*/ */
public PlayerPlotHelperEvent(Player initiator, Plot plot, UUID player, boolean added) { public PlayerPlotHelperEvent(Player initiator, Plot plot, UUID player,
this.initiator = initiator; boolean added) {
this.plot = plot; this.initiator = initiator;
this.added = added; this.plot = plot;
this.player = player; this.added = added;
} this.player = player;
}
/** /**
* If a player was added * If a player was added
* *
* @return boolean * @return boolean
*/ */
public boolean wasAdded() { public boolean wasAdded() {
return this.added; return this.added;
} }
/** /**
* The UUID added/removed * The UUID added/removed
* *
* @return UUID * @return UUID
*/ */
public UUID getPlayer() { public UUID getPlayer() {
return this.player; return this.player;
} }
/** /**
* The plot involved * The plot involved
* *
* @return Plot * @return Plot
*/ */
public Plot getPlot() { public Plot getPlot() {
return this.plot; return this.plot;
} }
/** /**
* The player initiating the action * The player initiating the action
* *
* @return Player * @return Player
*/ */
public Player getInitiator() { public Player getInitiator() {
return this.initiator; return this.initiator;
} }
@Override @Override
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
} }

View File

@ -12,66 +12,67 @@ import com.intellectualcrafters.plot.Plot;
* Created by Citymonstret on 2014-08-16. * Created by Citymonstret on 2014-08-16.
*/ */
public class PlayerPlotTrustedEvent extends Event { public class PlayerPlotTrustedEvent extends Event {
private static HandlerList handlers = new HandlerList(); private static HandlerList handlers = new HandlerList();
private Plot plot; private Plot plot;
private Player initiator; private Player initiator;
private boolean added; private boolean added;
private UUID player; private UUID player;
/** /**
* PlayerPlotTrustedEvent: Called when a plot trusted user is added/removed * PlayerPlotTrustedEvent: Called when a plot trusted user is added/removed
* *
* @param initiator * @param initiator
* @param plot * @param plot
* @param player * @param player
* @param added * @param added
*/ */
public PlayerPlotTrustedEvent(Player initiator, Plot plot, UUID player, boolean added) { public PlayerPlotTrustedEvent(Player initiator, Plot plot, UUID player,
this.initiator = initiator; boolean added) {
this.plot = plot; this.initiator = initiator;
this.added = added; this.plot = plot;
this.player = player; this.added = added;
} this.player = player;
}
/** /**
* If a player was added * If a player was added
* *
* @return boolean * @return boolean
*/ */
public boolean wasAdded() { public boolean wasAdded() {
return this.added; return this.added;
} }
/** /**
* The UUID added/removed * The UUID added/removed
* *
* @return UUID * @return UUID
*/ */
public UUID getPlayer() { public UUID getPlayer() {
return this.player; return this.player;
} }
/** /**
* The plot involved * The plot involved
* *
* @return Plot * @return Plot
*/ */
public Plot getPlot() { public Plot getPlot() {
return this.plot; return this.plot;
} }
/** /**
* The player initiating the action * The player initiating the action
* *
* @return Player * @return Player
*/ */
public Player getInitiator() { public Player getInitiator() {
return this.initiator; return this.initiator;
} }
@Override @Override
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
} }

View File

@ -20,61 +20,62 @@ import com.intellectualcrafters.plot.Plot;
/** /**
* Called when a player teleports to a plot * Called when a player teleports to a plot
*/ */
public class PlayerTeleportToPlotEvent extends PlayerEvent implements Cancellable { public class PlayerTeleportToPlotEvent extends PlayerEvent implements
private static final HandlerList handlers = new HandlerList(); Cancellable {
private static final HandlerList handlers = new HandlerList();
private Location from; private Location from;
private Plot plot; private Plot plot;
private boolean cancelled; private boolean cancelled;
/** /**
* PlayerTeleportToPlotEvent: Called when a player teleports to a plot * PlayerTeleportToPlotEvent: Called when a player teleports to a plot
* *
* @param player * @param player
* @param from * @param from
* @param plot * @param plot
*/ */
public PlayerTeleportToPlotEvent(Player player, Location from, Plot plot) { public PlayerTeleportToPlotEvent(Player player, Location from, Plot plot) {
super(player); super(player);
this.from = from; this.from = from;
this.plot = plot; this.plot = plot;
} }
@Override @Override
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
/** /**
* Get the from location * Get the from location
* *
* @return Location * @return Location
*/ */
public Location getFrom() { public Location getFrom() {
return this.from; return this.from;
} }
/** /**
* Get the plot involved * Get the plot involved
* *
* @return Plot * @return Plot
*/ */
public Plot getPlot() { public Plot getPlot() {
return this.plot; return this.plot;
} }
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
@Override @Override
public boolean isCancelled() { public boolean isCancelled() {
return this.cancelled; return this.cancelled;
} }
@Override @Override
public void setCancelled(boolean cancelled) { public void setCancelled(boolean cancelled) {
this.cancelled = cancelled; this.cancelled = cancelled;
} }
} }

View File

@ -19,57 +19,57 @@ import com.intellectualcrafters.plot.PlotId;
* Called when a plot is cleared * Called when a plot is cleared
*/ */
public class PlotClearEvent extends Event implements Cancellable { public class PlotClearEvent extends Event implements Cancellable {
private static HandlerList handlers = new HandlerList(); private static HandlerList handlers = new HandlerList();
private boolean cancelled; private boolean cancelled;
private PlotId id; private PlotId id;
private String world; private String world;
/** /**
* PlotDeleteEvent: Called when a plot is cleared * PlotDeleteEvent: Called when a plot is cleared
* *
* @param world * @param world
* @param id * @param id
*/ */
public PlotClearEvent(String world, PlotId id) { public PlotClearEvent(String world, PlotId id) {
this.id = id; this.id = id;
this.world = world; this.world = world;
} }
/** /**
* Get the PlotId * Get the PlotId
* *
* @return PlotId * @return PlotId
*/ */
public PlotId getPlotId() { public PlotId getPlotId() {
return this.id; return this.id;
} }
/** /**
* Get the world name * Get the world name
* *
* @return String * @return String
*/ */
public String getWorld() { public String getWorld() {
return this.world; return this.world;
} }
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
@Override @Override
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
@Override @Override
public boolean isCancelled() { public boolean isCancelled() {
return this.cancelled; return this.cancelled;
} }
@Override @Override
public void setCancelled(boolean b) { public void setCancelled(boolean b) {
this.cancelled = b; this.cancelled = b;
} }
} }

View File

@ -19,57 +19,57 @@ import com.intellectualcrafters.plot.PlotId;
* Called when a plot is deleted * Called when a plot is deleted
*/ */
public class PlotDeleteEvent extends Event implements Cancellable { public class PlotDeleteEvent extends Event implements Cancellable {
private static HandlerList handlers = new HandlerList(); private static HandlerList handlers = new HandlerList();
private boolean cancelled; private boolean cancelled;
private PlotId id; private PlotId id;
private String world; private String world;
/** /**
* PlotDeleteEvent: Called when a plot is deleted * PlotDeleteEvent: Called when a plot is deleted
* *
* @param world * @param world
* @param id * @param id
*/ */
public PlotDeleteEvent(String world, PlotId id) { public PlotDeleteEvent(String world, PlotId id) {
this.id = id; this.id = id;
this.world = world; this.world = world;
} }
/** /**
* Get the PlotId * Get the PlotId
* *
* @return PlotId * @return PlotId
*/ */
public PlotId getPlotId() { public PlotId getPlotId() {
return this.id; return this.id;
} }
/** /**
* Get the world name * Get the world name
* *
* @return String * @return String
*/ */
public String getWorld() { public String getWorld() {
return this.world; return this.world;
} }
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
@Override @Override
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
@Override @Override
public boolean isCancelled() { public boolean isCancelled() {
return this.cancelled; return this.cancelled;
} }
@Override @Override
public void setCancelled(boolean b) { public void setCancelled(boolean b) {
this.cancelled = b; this.cancelled = b;
} }
} }

View File

@ -20,57 +20,57 @@ import com.intellectualcrafters.plot.Plot;
* Called when a Flag is added to a plot * Called when a Flag is added to a plot
*/ */
public class PlotFlagAddEvent extends Event implements Cancellable { public class PlotFlagAddEvent extends Event implements Cancellable {
private static HandlerList handlers = new HandlerList(); private static HandlerList handlers = new HandlerList();
private boolean cancelled; private boolean cancelled;
private Plot plot; private Plot plot;
private Flag flag; private Flag flag;
/** /**
* PlotFlagAddEvent: Called when a Flag is added to a plot * PlotFlagAddEvent: Called when a Flag is added to a plot
* *
* @param flag * @param flag
* @param plot * @param plot
*/ */
public PlotFlagAddEvent(Flag flag, Plot plot) { public PlotFlagAddEvent(Flag flag, Plot plot) {
this.plot = plot; this.plot = plot;
this.flag = flag; this.flag = flag;
} }
/** /**
* Get the plot involved * Get the plot involved
* *
* @return Plot * @return Plot
*/ */
public Plot getPlot() { public Plot getPlot() {
return this.plot; return this.plot;
} }
/** /**
* Get the flag involved * Get the flag involved
* *
* @return Flag * @return Flag
*/ */
public Flag getFlag() { public Flag getFlag() {
return this.flag; return this.flag;
} }
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
@Override @Override
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
@Override @Override
public boolean isCancelled() { public boolean isCancelled() {
return this.cancelled; return this.cancelled;
} }
@Override @Override
public void setCancelled(boolean b) { public void setCancelled(boolean b) {
this.cancelled = b; this.cancelled = b;
} }
} }

View File

@ -20,57 +20,57 @@ import com.intellectualcrafters.plot.Plot;
* Called when a flag is removed from a plot * Called when a flag is removed from a plot
*/ */
public class PlotFlagRemoveEvent extends Event implements Cancellable { public class PlotFlagRemoveEvent extends Event implements Cancellable {
private static HandlerList handlers = new HandlerList(); private static HandlerList handlers = new HandlerList();
private boolean cancelled; private boolean cancelled;
private Plot plot; private Plot plot;
private Flag flag; private Flag flag;
/** /**
* PlotFlagRemoveEvent: Called when a flag is removed from a plot * PlotFlagRemoveEvent: Called when a flag is removed from a plot
* *
* @param flag * @param flag
* @param plot * @param plot
*/ */
public PlotFlagRemoveEvent(Flag flag, Plot plot) { public PlotFlagRemoveEvent(Flag flag, Plot plot) {
this.plot = plot; this.plot = plot;
this.flag = flag; this.flag = flag;
} }
/** /**
* Get the plot involved * Get the plot involved
* *
* @return Plot * @return Plot
*/ */
public Plot getPlot() { public Plot getPlot() {
return this.plot; return this.plot;
} }
/** /**
* Get the flag involved * Get the flag involved
* *
* @return Flag * @return Flag
*/ */
public Flag getFlag() { public Flag getFlag() {
return this.flag; return this.flag;
} }
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
@Override @Override
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
@Override @Override
public boolean isCancelled() { public boolean isCancelled() {
return this.cancelled; return this.cancelled;
} }
@Override @Override
public void setCancelled(boolean b) { public void setCancelled(boolean b) {
this.cancelled = b; this.cancelled = b;
} }
} }

View File

@ -23,61 +23,61 @@ import com.intellectualcrafters.plot.PlotId;
* Created by Citymonstret on 2014-08-09. * Created by Citymonstret on 2014-08-09.
*/ */
public class PlotMergeEvent extends Event implements Cancellable { public class PlotMergeEvent extends Event implements Cancellable {
private static HandlerList handlers = new HandlerList(); private static HandlerList handlers = new HandlerList();
private boolean cancelled; private boolean cancelled;
private ArrayList<PlotId> plots; private ArrayList<PlotId> plots;
private Plot plot; private Plot plot;
private World world; private World world;
/** /**
* PlotMergeEvent: Called when plots are merged * PlotMergeEvent: Called when plots are merged
* *
* @param player * @param player
* @param plot * @param plot
*/ */
public PlotMergeEvent(World world, Plot plot, ArrayList<PlotId> plots) { public PlotMergeEvent(World world, Plot plot, ArrayList<PlotId> plots) {
this.plots = plots; this.plots = plots;
} }
/** /**
* Get the plots being added; * Get the plots being added;
* *
* @return Plot * @return Plot
*/ */
public ArrayList<PlotId> getPlots() { public ArrayList<PlotId> getPlots() {
return this.plots; return this.plots;
} }
/** /**
* Get the main plot * Get the main plot
* *
* @return Plot * @return Plot
*/ */
public Plot getPlot() { public Plot getPlot() {
return this.plot; return this.plot;
} }
public World getWorld() { public World getWorld() {
return this.world; return this.world;
} }
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
@Override @Override
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
@Override @Override
public boolean isCancelled() { public boolean isCancelled() {
return this.cancelled; return this.cancelled;
} }
@Override @Override
public void setCancelled(boolean b) { public void setCancelled(boolean b) {
this.cancelled = b; this.cancelled = b;
} }
} }

View File

@ -22,52 +22,52 @@ import com.intellectualcrafters.plot.PlotId;
* Created by Citymonstret on 2014-08-09. * Created by Citymonstret on 2014-08-09.
*/ */
public class PlotUnlinkEvent extends Event implements Cancellable { public class PlotUnlinkEvent extends Event implements Cancellable {
private static HandlerList handlers = new HandlerList(); private static HandlerList handlers = new HandlerList();
private boolean cancelled; private boolean cancelled;
private ArrayList<PlotId> plots; private ArrayList<PlotId> plots;
private World world; private World world;
/** /**
* Called when a mega-plot is unlinked. * Called when a mega-plot is unlinked.
* *
* @param world * @param world
* @param plots * @param plots
*/ */
public PlotUnlinkEvent(World world, ArrayList<PlotId> plots) { public PlotUnlinkEvent(World world, ArrayList<PlotId> plots) {
this.plots = plots; this.plots = plots;
this.world = world; this.world = world;
} }
/** /**
* Get the plots involved * Get the plots involved
* *
* @return PlotId * @return PlotId
*/ */
public ArrayList<PlotId> getPlots() { public ArrayList<PlotId> getPlots() {
return this.plots; return this.plots;
} }
public World getWorld() { public World getWorld() {
return this.world; return this.world;
} }
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
@Override @Override
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
@Override @Override
public boolean isCancelled() { public boolean isCancelled() {
return this.cancelled; return this.cancelled;
} }
@Override @Override
public void setCancelled(boolean b) { public void setCancelled(boolean b) {
this.cancelled = b; this.cancelled = b;
} }
} }

View File

@ -10,170 +10,194 @@ import com.intellectualcrafters.plot.PlotWorld;
public class DefaultPlotWorld extends PlotWorld { public class DefaultPlotWorld extends PlotWorld {
/* /*
* These variables are set to ensure fast access to config settings * These variables are set to ensure fast access to config settings Strings
* Strings are used as little as possible to optimize math performance in many of the functions/algorithms * 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;
/** /**
* Road Height * plot height
*/ */
public int ROAD_HEIGHT; public int PLOT_HEIGHT;
/** /**
* Default Road Height: 64 * Default plot height: 64
*/ */
public static int ROAD_HEIGHT_DEFAULT = 64; public static int PLOT_HEIGHT_DEFAULT = 64;
/** /**
* plot height * Wall height
*/ */
public int PLOT_HEIGHT; public int WALL_HEIGHT;
/** /**
* Default plot height: 64 * Default Wall Height: 64
*/ */
public static int PLOT_HEIGHT_DEFAULT = 64; public static int WALL_HEIGHT_DEFAULT = 64;
/** /**
* Wall height * plot width
*/ */
public int WALL_HEIGHT; public int PLOT_WIDTH;
/** /**
* Default Wall Height: 64 * Default plot width: 32
*/ */
public static int WALL_HEIGHT_DEFAULT = 64; public static int PLOT_WIDTH_DEFAULT = 32;
/** /**
* plot width * Road width
*/ */
public int PLOT_WIDTH; public int ROAD_WIDTH;
/** /**
* Default plot width: 32 * Default road width: 7
*/ */
public static int PLOT_WIDTH_DEFAULT = 32; public static int ROAD_WIDTH_DEFAULT = 7;
/** /**
* Road width * Plot biome
*/ */
public int ROAD_WIDTH; public PlotBlock[] MAIN_BLOCK;
/** /**
* Default road width: 7 * Default main block: 1
*/ */
public static int ROAD_WIDTH_DEFAULT = 7; 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) };
/** /**
* Plot biome * Wall block
*/ */
public PlotBlock[] MAIN_BLOCK; public PlotBlock WALL_BLOCK;
/** /**
* Default main block: 1 * Default wall block: 44
*/ */
public static PlotBlock[] MAIN_BLOCK_DEFAULT = new PlotBlock[] { new PlotBlock((short) 1, (byte) 0) }; public static String WALL_BLOCK_DEFAULT = "44: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 block * Wall filling
*/ */
public PlotBlock WALL_BLOCK; public PlotBlock WALL_FILLING;
/** /**
* Default wall block: 44 * Default wall filling: 1
*/ */
public static String WALL_BLOCK_DEFAULT = "44:0"; public static PlotBlock WALL_FILLING_DEFAULT = new PlotBlock((short) 1,
(byte) 0);
/** /**
* Wall filling * Road stripes
*/ */
public PlotBlock WALL_FILLING; public PlotBlock ROAD_STRIPES;
/** /**
* Default wall filling: 1 * Default road stripes: 35
*/ */
public static PlotBlock WALL_FILLING_DEFAULT = new PlotBlock((short) 1, (byte) 0); 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);
/** /*
* Road stripes * Here we are just calling the super method, nothing special
*/ */
public PlotBlock ROAD_STRIPES; public DefaultPlotWorld(String worldname) {
/** super(worldname);
* 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);
/*
* 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), };
}
/* /*
* Here we are just calling the super method, nothing special * 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
public DefaultPlotWorld(String worldname) { * specific world.
super(worldname); */
} @Override
public void loadConfiguration(ConfigurationSection config) {
/* this.PLOT_HEIGHT = config.getInt("plot.height");
* CONFIG NODE | DEFAULT VALUE | DESCRIPTION | CONFIGURATION TYPE | REQUIRED FOR INITIAL SETUP this.PLOT_WIDTH = config.getInt("plot.width");
* this.MAIN_BLOCK = (PlotBlock[]) Configuration.BLOCKLIST
* Set the last boolean to false if you do not require a specific config node to be set while using the setup command .parseString(StringUtils.join(
* - this may be useful if a config value can be changed at a later date, and has no impact on the actual world generation config.getStringList("plot.filling"), ','));
* this.TOP_BLOCK = (PlotBlock[]) Configuration.BLOCKLIST
*/ .parseString(StringUtils.join(
@Override config.getStringList("plot.floor"), ','));
public ConfigurationNode[] getSettingNodes() { this.WALL_BLOCK = (PlotBlock) Configuration.BLOCK.parseString(config
// TODO return a set of configuration nodes (used for setup command) .getString("wall.block"));
return this.ROAD_WIDTH = config.getInt("road.width");
new ConfigurationNode[] { this.ROAD_HEIGHT = config.getInt("road.height");
new ConfigurationNode("plot.height", PLOT_HEIGHT, "Plot height", Configuration.INTEGER, true), this.ROAD_STRIPES_ENABLED = config.getBoolean("road.enable_stripes");
new ConfigurationNode("plot.width", PLOT_WIDTH, "Plot width", Configuration.INTEGER, true), this.ROAD_BLOCK = (PlotBlock) Configuration.BLOCK.parseString(config
new ConfigurationNode("plot.filling", MAIN_BLOCK, "Plot block", Configuration.BLOCKLIST, true), .getString("road.block"));
new ConfigurationNode("plot.floor", TOP_BLOCK, "Plot floor block", Configuration.BLOCKLIST, true), this.ROAD_STRIPES = (PlotBlock) Configuration.BLOCK.parseString(config
new ConfigurationNode("wall.block", WALL_BLOCK, "Top wall block", Configuration.BLOCK, true), .getString("road.stripes"));
new ConfigurationNode("road.width", ROAD_WIDTH, "Road width", Configuration.INTEGER, true), this.WALL_FILLING = (PlotBlock) Configuration.BLOCK.parseString(config
new ConfigurationNode("road.height", ROAD_HEIGHT, "Road height", Configuration.INTEGER, true), .getString("wall.filling"));
new ConfigurationNode("road.enable_stripes", ROAD_STRIPES_ENABLED, "Enable road stripes", Configuration.BOOLEAN, true), this.WALL_HEIGHT = config.getInt("wall.height");
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),
};
}
/* }
* 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");
}
} }

View File

@ -17,436 +17,529 @@ import com.intellectualcrafters.plot.PlotWorld;
*/ */
public class XPopulator extends BlockPopulator { public class XPopulator extends BlockPopulator {
/* /*
* Sorry, this isn't well documented at the moment. * 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. * We advise you to take a look at a world generation tutorial for
* * information about how a BlockPopulator works.
*/ */
private int X; private int X;
private int Z; private int Z;
private long state; private long state;
public final long nextLong() { public final long nextLong() {
long a = this.state; long a = this.state;
this.state = xorShift64(a); this.state = xorShift64(a);
return a; return a;
} }
public final long xorShift64(long a) { public final long xorShift64(long a) {
a ^= (a << 21); a ^= (a << 21);
a ^= (a >>> 35); a ^= (a >>> 35);
a ^= (a << 4); a ^= (a << 4);
return a; return a;
} }
public final int random(int n) { public final int random(int n) {
long result = ((nextLong() >>> 32) * n) >> 32; long result = ((nextLong() >>> 32) * n) >> 32;
return (int) result; return (int) result;
} }
public void setCuboidRegion(int x1, int x2, int y1, int y2, int z1, int z2, PlotBlock block, World w) { public void setCuboidRegion(int x1, int x2, int y1, int y2, int z1, int z2,
if (block.data == 0) { PlotBlock block, World w) {
return; if (block.data == 0) {
} return;
for (int x = x1; x < x2; x++) { }
for (int z = z1; z < z2; z++) { for (int x = x1; x < x2; x++) {
for (int y = y1; y < y2; y++) { for (int z = z1; z < z2; z++) {
setBlock(w, x, y, z, block.id, block.data); for (int y = y1; y < y2; y++) {
} setBlock(w, x, y, z, block.id, block.data);
} }
} }
} }
}
private void setCuboidRegion(int x1, int x2, int y1, int y2, int z1, int z2, PlotBlock[] blocks, World w) { private void setCuboidRegion(int x1, int x2, int y1, int y2, int z1,
if (blocks.length == 1) { int z2, PlotBlock[] blocks, World w) {
setCuboidRegion(x1, x2, y1, y2, z1, z2, blocks[0], w); if (blocks.length == 1) {
} else { setCuboidRegion(x1, x2, y1, y2, z1, z2, blocks[0], w);
for (int x = x1; x < x2; x++) { } else {
for (int z = z1; z < z2; z++) { for (int x = x1; x < x2; x++) {
for (int y = y1; y < y2; y++) { for (int z = z1; z < z2; z++) {
int i = random(blocks.length); for (int y = y1; y < y2; y++) {
if (blocks[i].data != 0) { int i = random(blocks.length);
setBlock(w, x, y, z, blocks[i].id, blocks[i].data); if (blocks[i].data != 0) {
} setBlock(w, x, y, z, blocks[i].id, blocks[i].data);
} }
} }
} }
} }
}
} }
public short[] getBlock(String block) { public short[] getBlock(String block) {
if (block.contains(":")) { if (block.contains(":")) {
String[] split = block.split(":"); String[] split = block.split(":");
return new short[] { Short.parseShort(split[0]), Short.parseShort(split[1]) }; return new short[] { Short.parseShort(split[0]),
} Short.parseShort(split[1]) };
return new short[] { Short.parseShort(block), 0 }; }
} return new short[] { Short.parseShort(block), 0 };
}
int plotsize; int plotsize;
int pathsize; int pathsize;
PlotBlock wall; PlotBlock wall;
PlotBlock wallfilling; PlotBlock wallfilling;
PlotBlock floor1; PlotBlock floor1;
PlotBlock floor2; PlotBlock floor2;
int size; int size;
Biome biome; Biome biome;
int roadheight; int roadheight;
int wallheight; int wallheight;
int plotheight; int plotheight;
PlotBlock[] plotfloors; PlotBlock[] plotfloors;
PlotBlock[] filling; PlotBlock[] filling;
private double pathWidthLower; private double pathWidthLower;
private DefaultPlotWorld plotworld; private DefaultPlotWorld plotworld;
public XPopulator(PlotWorld pw) { public XPopulator(PlotWorld pw) {
this.plotworld = (DefaultPlotWorld) pw; this.plotworld = (DefaultPlotWorld) pw;
// save configuration // save configuration
plotsize = plotworld.PLOT_WIDTH; this.plotsize = this.plotworld.PLOT_WIDTH;
pathsize = plotworld.ROAD_WIDTH; this.pathsize = this.plotworld.ROAD_WIDTH;
floor1 = plotworld.ROAD_BLOCK; this.floor1 = this.plotworld.ROAD_BLOCK;
floor2 = plotworld.ROAD_STRIPES; this.floor2 = this.plotworld.ROAD_STRIPES;
wallfilling = plotworld.WALL_FILLING; this.wallfilling = this.plotworld.WALL_FILLING;
size = pathsize + plotsize; this.size = this.pathsize + this.plotsize;
wall = plotworld.WALL_BLOCK; this.wall = this.plotworld.WALL_BLOCK;
plotfloors = plotworld.TOP_BLOCK; this.plotfloors = this.plotworld.TOP_BLOCK;
filling = plotworld.MAIN_BLOCK; this.filling = this.plotworld.MAIN_BLOCK;
wallheight = plotworld.WALL_HEIGHT; this.wallheight = this.plotworld.WALL_HEIGHT;
roadheight = plotworld.ROAD_HEIGHT; this.roadheight = this.plotworld.ROAD_HEIGHT;
plotheight = plotworld.PLOT_HEIGHT; this.plotheight = this.plotworld.PLOT_HEIGHT;
if ((this.pathsize % 2) == 0) { if ((this.pathsize % 2) == 0) {
this.pathWidthLower = Math.floor(this.pathsize / 2) - 1; this.pathWidthLower = Math.floor(this.pathsize / 2) - 1;
} else { } else {
this.pathWidthLower = Math.floor(this.pathsize / 2); this.pathWidthLower = Math.floor(this.pathsize / 2);
} }
} }
@Override @Override
public void populate(World w, Random r, Chunk c) { public void populate(World w, Random r, Chunk c) {
int cx = c.getX(), cz = c.getZ(); int cx = c.getX(), cz = c.getZ();
final int prime = 31; final int prime = 31;
int h = 1; int h = 1;
h = (prime * h) + cx; h = (prime * h) + cx;
h = (prime * h) + cz; h = (prime * h) + cz;
this.state = h; this.state = h;
this.X = cx << 4; this.X = cx << 4;
this.Z = cz << 4; this.Z = cz << 4;
cx = (cx % this.size) + (8 * this.size); cx = (cx % this.size) + (8 * this.size);
cz = (cz % 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)); double absX = ((((cx * 16) + 16) - this.pathWidthLower - 1) + (8 * this.size)), absZ = ((((cz * 16) + 16)
int plotMinX = (int) (((absX) % this.size)); - this.pathWidthLower - 1) + (8 * this.size));
int plotMinZ = (int) (((absZ) % this.size)); int plotMinX = (int) (((absX) % this.size));
int roadStartX = (plotMinX + this.pathsize); int plotMinZ = (int) (((absZ) % this.size));
int roadStartZ = (plotMinZ + this.pathsize); int roadStartX = (plotMinX + this.pathsize);
if (roadStartX >= this.size) { int roadStartZ = (plotMinZ + this.pathsize);
roadStartX -= this.size; if (roadStartX >= this.size) {
} roadStartX -= this.size;
if (roadStartZ >= this.size) { }
roadStartZ -= this.size; if (roadStartZ >= this.size) {
} roadStartZ -= this.size;
}
// ROADS // ROADS
if ((this.pathsize > 16) && ((plotMinX > roadStartX) || (plotMinZ > roadStartZ)) && !((roadStartX < 16) && (roadStartZ < 16)) && (((roadStartX > 16) && (roadStartZ > 16)) || ((plotMinX > roadStartX) && (plotMinZ > roadStartZ)))) { if ((this.pathsize > 16)
setCuboidRegion(0, 16, 1, this.roadheight + 1, 0, 16, this.floor1, w); && ((plotMinX > roadStartX) || (plotMinZ > roadStartZ))
return; && !((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;
}
if (((plotMinZ + 1) <= 16) || ((roadStartZ <= 16) && (roadStartZ > 0))) { if (((plotMinZ + 1) <= 16) || ((roadStartZ <= 16) && (roadStartZ > 0))) {
int start = Math.max((16 - plotMinZ - this.pathsize) + 1, (16 - roadStartZ) + 1); int start = Math.max((16 - plotMinZ - this.pathsize) + 1,
int end = Math.min(16 - plotMinZ - 1, (16 - roadStartZ) + this.pathsize); (16 - roadStartZ) + 1);
if ((start >= 0) && (start <= 16) && (end < 0)) { int end = Math.min(16 - plotMinZ - 1, (16 - roadStartZ)
end = 16; + this.pathsize);
} if ((start >= 0) && (start <= 16) && (end < 0)) {
setCuboidRegion(0, 16, 1, this.roadheight + 1, Math.max(start, 0), Math.min(16, end), this.floor1, w); end = 16;
} }
if (((plotMinX + 1) <= 16) || ((roadStartX <= 16) && (roadStartX > 0))) { setCuboidRegion(0, 16, 1, this.roadheight + 1, Math.max(start, 0),
int start = Math.max((16 - plotMinX - this.pathsize) + 1, (16 - roadStartX) + 1); Math.min(16, end), this.floor1, w);
int end = Math.min(16 - plotMinX - 1, (16 - roadStartX) + this.pathsize); }
if ((start >= 0) && (start <= 16) && (end < 0)) { if (((plotMinX + 1) <= 16) || ((roadStartX <= 16) && (roadStartX > 0))) {
end = 16; int start = Math.max((16 - plotMinX - this.pathsize) + 1,
} (16 - roadStartX) + 1);
setCuboidRegion(Math.max(start, 0), Math.min(16, end), 1, this.roadheight + 1, 0, 16, this.floor1, w); 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 // STRIPES
if ((this.pathsize > 4) && this.plotworld.ROAD_STRIPES_ENABLED) { if ((this.pathsize > 4) && this.plotworld.ROAD_STRIPES_ENABLED) {
if ((plotMinZ + 2) <= 16) { if ((plotMinZ + 2) <= 16) {
int value = (plotMinZ + 2); int value = (plotMinZ + 2);
int start, end; int start, end;
if ((plotMinX + 2) <= 16) { if ((plotMinX + 2) <= 16) {
start = 16 - plotMinX - 1; start = 16 - plotMinX - 1;
} else { } else {
start = 16; start = 16;
} }
if ((roadStartX - 1) <= 16) { if ((roadStartX - 1) <= 16) {
end = (16 - roadStartX) + 1; end = (16 - roadStartX) + 1;
} else { } else {
end = 0; end = 0;
} }
if (!(((plotMinX + 2) <= 16) || ((roadStartX - 1) <= 16))) { if (!(((plotMinX + 2) <= 16) || ((roadStartX - 1) <= 16))) {
start = 0; start = 0;
} }
setCuboidRegion(0, end, this.roadheight, this.roadheight + 1, 16 - value, (16 - value) + 1, this.floor2, w); // setCuboidRegion(0, end, this.roadheight, this.roadheight + 1,
setCuboidRegion(start, 16, this.roadheight, this.roadheight + 1, 16 - value, (16 - value) + 1, this.floor2, w); // 16 - value, (16 - value) + 1, this.floor2, w); //
} setCuboidRegion(start, 16, this.roadheight,
if ((plotMinX + 2) <= 16) { this.roadheight + 1, 16 - value, (16 - value) + 1,
int value = (plotMinX + 2); this.floor2, w); //
int start, end; }
if ((plotMinZ + 2) <= 16) { if ((plotMinX + 2) <= 16) {
start = 16 - plotMinZ - 1; int value = (plotMinX + 2);
} else { int start, end;
start = 16; if ((plotMinZ + 2) <= 16) {
} start = 16 - plotMinZ - 1;
if ((roadStartZ - 1) <= 16) { } else {
end = (16 - roadStartZ) + 1; start = 16;
} else { }
end = 0; if ((roadStartZ - 1) <= 16) {
} end = (16 - roadStartZ) + 1;
if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) { } else {
start = 0; end = 0;
} }
setCuboidRegion(16 - value, (16 - value) + 1, this.roadheight, this.roadheight + 1, 0, end, this.floor2, w); // if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) {
setCuboidRegion(16 - value, (16 - value) + 1, this.roadheight, this.roadheight + 1, start, 16, this.floor2, w); // start = 0;
} }
if ((roadStartZ <= 16) && (roadStartZ > 1)) { setCuboidRegion(16 - value, (16 - value) + 1, this.roadheight,
int val = roadStartZ; this.roadheight + 1, 0, end, this.floor2, w); //
int start, end; setCuboidRegion(16 - value, (16 - value) + 1, this.roadheight,
if ((plotMinX + 2) <= 16) { this.roadheight + 1, start, 16, this.floor2, w); //
start = 16 - plotMinX - 1; }
} else { if ((roadStartZ <= 16) && (roadStartZ > 1)) {
start = 16; int val = roadStartZ;
} int start, end;
if ((roadStartX - 1) <= 16) { if ((plotMinX + 2) <= 16) {
end = (16 - roadStartX) + 1; start = 16 - plotMinX - 1;
} else { } else {
end = 0; start = 16;
} }
if (!(((plotMinX + 2) <= 16) || ((roadStartX - 1) <= 16))) { if ((roadStartX - 1) <= 16) {
start = 0; end = (16 - roadStartX) + 1;
} } else {
setCuboidRegion(0, end, this.roadheight, this.roadheight + 1, (16 - val) + 1, (16 - val) + 2, this.floor2, w); end = 0;
setCuboidRegion(start, 16, this.roadheight, this.roadheight + 1, (16 - val) + 1, (16 - val) + 2, this.floor2, w); }
} if (!(((plotMinX + 2) <= 16) || ((roadStartX - 1) <= 16))) {
if ((roadStartX <= 16) && (roadStartX > 1)) { start = 0;
int val = roadStartX; }
int start, end; setCuboidRegion(0, end, this.roadheight, this.roadheight + 1,
if ((plotMinZ + 2) <= 16) { (16 - val) + 1, (16 - val) + 2, this.floor2, w);
start = 16 - plotMinZ - 1; setCuboidRegion(start, 16, this.roadheight,
} else { this.roadheight + 1, (16 - val) + 1, (16 - val) + 2,
start = 16; this.floor2, w);
} }
if ((roadStartZ - 1) <= 16) { if ((roadStartX <= 16) && (roadStartX > 1)) {
end = (16 - roadStartZ) + 1; int val = roadStartX;
} else { int start, end;
end = 0; if ((plotMinZ + 2) <= 16) {
} start = 16 - plotMinZ - 1;
if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) { } else {
start = 0; start = 16;
} }
setCuboidRegion((16 - val) + 1, (16 - val) + 2, this.roadheight, this.roadheight + 1, 0, end, this.floor2, w); // if ((roadStartZ - 1) <= 16) {
setCuboidRegion((16 - val) + 1, (16 - val) + 2, this.roadheight, this.roadheight + 1, start, 16, this.floor2, w); // end = (16 - roadStartZ) + 1;
} } else {
} end = 0;
// WALLS }
if (this.pathsize > 0) { if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) {
if ((plotMinZ + 1) <= 16) { start = 0;
int start, end; }
if ((plotMinX + 2) <= 16) { setCuboidRegion((16 - val) + 1, (16 - val) + 2,
start = 16 - plotMinX - 1; this.roadheight, this.roadheight + 1, 0, end,
} else { this.floor2, w); //
start = 16; setCuboidRegion((16 - val) + 1, (16 - val) + 2,
} this.roadheight, this.roadheight + 1, start, 16,
if ((roadStartX - 1) <= 16) { this.floor2, w); //
end = (16 - roadStartX) + 1; }
} else { }
end = 0; // WALLS
} if (this.pathsize > 0) {
if (!(((plotMinX + 2) <= 16) || ((roadStartX - 1) <= 16))) { if ((plotMinZ + 1) <= 16) {
start = 0; int start, end;
} if ((plotMinX + 2) <= 16) {
setCuboidRegion(0, end, 1, this.wallheight + 1, 16 - plotMinZ - 1, 16 - plotMinZ, this.wallfilling, w); start = 16 - plotMinX - 1;
setCuboidRegion(0, end, this.wallheight + 1, this.wallheight + 2, 16 - plotMinZ - 1, 16 - plotMinZ, this.wall, w); } else {
setCuboidRegion(start, 16, 1, this.wallheight + 1, 16 - plotMinZ - 1, 16 - plotMinZ, this.wallfilling, w); start = 16;
setCuboidRegion(start, 16, this.wallheight + 1, this.wallheight + 2, 16 - plotMinZ - 1, 16 - plotMinZ, this.wall, w); }
} if ((roadStartX - 1) <= 16) {
if ((plotMinX + 1) <= 16) { end = (16 - roadStartX) + 1;
int start, end; } else {
if ((plotMinZ + 2) <= 16) { end = 0;
start = 16 - plotMinZ - 1; }
} else { if (!(((plotMinX + 2) <= 16) || ((roadStartX - 1) <= 16))) {
start = 16; start = 0;
} }
if ((roadStartZ - 1) <= 16) { setCuboidRegion(0, end, 1, this.wallheight + 1,
end = (16 - roadStartZ) + 1; 16 - plotMinZ - 1, 16 - plotMinZ, this.wallfilling, w);
} else { setCuboidRegion(0, end, this.wallheight + 1,
end = 0; this.wallheight + 2, 16 - plotMinZ - 1, 16 - plotMinZ,
} this.wall, w);
if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) { setCuboidRegion(start, 16, 1, this.wallheight + 1,
start = 0; 16 - plotMinZ - 1, 16 - plotMinZ, this.wallfilling, w);
} setCuboidRegion(start, 16, this.wallheight + 1,
setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, 1, this.wallheight + 1, 0, end, this.wallfilling, w); this.wallheight + 2, 16 - plotMinZ - 1, 16 - plotMinZ,
setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, this.wallheight + 1, this.wallheight + 2, 0, end, this.wall, w); 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 ((plotMinX + 1) <= 16) {
} int start, end;
if ((roadStartZ <= 16) && (roadStartZ > 0)) { if ((plotMinZ + 2) <= 16) {
int start, end; start = 16 - plotMinZ - 1;
if ((plotMinX + 1) <= 16) { } else {
start = 16 - plotMinX; start = 16;
} else { }
start = 16; if ((roadStartZ - 1) <= 16) {
} end = (16 - roadStartZ) + 1;
if ((roadStartX + 1) <= 16) { } else {
end = (16 - roadStartX) + 1; end = 0;
} else { }
end = 0; if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) {
} start = 0;
if (!(((plotMinX + 1) <= 16) || (roadStartX <= 16))) { }
start = 0; setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, 1,
} this.wallheight + 1, 0, end, this.wallfilling, w);
setCuboidRegion(0, end, 1, this.wallheight + 1, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wallfilling, w); setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX,
setCuboidRegion(0, end, this.wallheight + 1, this.wallheight + 2, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wall, w); this.wallheight + 1, this.wallheight + 2, 0, end,
setCuboidRegion(start, 16, 1, this.wallheight + 1, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wallfilling, w); this.wall, w);
setCuboidRegion(start, 16, this.wallheight + 1, this.wallheight + 2, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wall, w); setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, 1,
} this.wallheight + 1, start, 16, this.wallfilling, w);
if ((roadStartX <= 16) && (roadStartX > 0)) { setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX,
int start, end; this.wallheight + 1, this.wallheight + 2, start, 16,
if ((plotMinZ + 1) <= 16) { this.wall, w);
start = 16 - plotMinZ; }
} else { if ((roadStartZ <= 16) && (roadStartZ > 0)) {
start = 16; int start, end;
} if ((plotMinX + 1) <= 16) {
if ((roadStartZ + 1) <= 16) { start = 16 - plotMinX;
end = (16 - roadStartZ) + 1; } else {
} else { start = 16;
end = 0; }
} if ((roadStartX + 1) <= 16) {
if (!(((plotMinZ + 1) <= 16) || ((roadStartZ + 1) <= 16))) { end = (16 - roadStartX) + 1;
start = 0; } else {
} end = 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); if (!(((plotMinX + 1) <= 16) || (roadStartX <= 16))) {
setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, 1, this.wallheight + 1, start, 16, this.wallfilling, w); start = 0;
setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, this.wallheight + 1, this.wallheight + 2, start, 16, this.wall, w); }
} 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 // PLOT
if (this.plotsize > 16) { if (this.plotsize > 16) {
if (roadStartX <= 16) { if (roadStartX <= 16) {
if (roadStartZ <= 16) { if (roadStartZ <= 16) {
setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 0, 16 - roadStartZ, this.filling, w); setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 0,
setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors, w); 16 - roadStartZ, this.filling, w);
} setCuboidRegion(0, 16 - roadStartX, this.plotheight,
if (plotMinZ <= 16) { this.plotheight + 1, 0, 16 - roadStartZ,
setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 16 - plotMinZ, 16, this.filling, w); this.plotfloors, w);
setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors, w); }
} if (plotMinZ <= 16) {
} else { setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight,
if (roadStartZ <= 16) { 16 - plotMinZ, 16, this.filling, w);
if (plotMinX > 16) { setCuboidRegion(0, 16 - roadStartX, this.plotheight,
setCuboidRegion(0, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.filling, w); this.plotheight + 1, 16 - plotMinZ, 16,
setCuboidRegion(0, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors, w); this.plotfloors, w);
} }
} } else {
} if (roadStartZ <= 16) {
if (plotMinX <= 16) { if (plotMinX > 16) {
if (plotMinZ <= 16) { setCuboidRegion(0, 16, 1, this.plotheight, 0,
setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 16 - plotMinZ, 16, this.filling, w); 16 - roadStartZ, this.filling, w);
setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors, w); setCuboidRegion(0, 16, this.plotheight,
} else { this.plotheight + 1, 0, 16 - roadStartZ,
int z = 16 - roadStartZ; this.plotfloors, w);
if (z < 0) { }
z = 16; }
} }
setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, z, this.filling, w); if (plotMinX <= 16) {
setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, z, this.plotfloors, w); if (plotMinZ <= 16) {
} setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight,
if (roadStartZ <= 16) { 16 - plotMinZ, 16, this.filling, w);
setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.filling, w); setCuboidRegion(16 - plotMinX, 16, this.plotheight,
setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors, w); this.plotheight + 1, 16 - plotMinZ, 16,
} else { this.plotfloors, w);
if (roadStartX <= 16) { } else {
if (plotMinZ > 16) { int z = 16 - roadStartZ;
int x = 16 - roadStartX; if (z < 0) {
if (x < 0) { z = 16;
x = 16; }
} setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0,
setCuboidRegion(0, x, 1, this.plotheight, 0, 16, this.filling, w); z, this.filling, w);
setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, 16, this.plotfloors, w); setCuboidRegion(16 - plotMinX, 16, this.plotheight,
} this.plotheight + 1, 0, z, this.plotfloors, w);
} }
} if (roadStartZ <= 16) {
} else { setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0,
if (plotMinZ <= 16) { 16 - roadStartZ, this.filling, w);
if (roadStartX > 16) { setCuboidRegion(16 - plotMinX, 16, this.plotheight,
int x = 16 - roadStartX; this.plotheight + 1, 0, 16 - roadStartZ,
if (x < 0) { this.plotfloors, w);
x = 16; } else {
} if (roadStartX <= 16) {
setCuboidRegion(0, x, 1, this.plotheight, 16 - plotMinZ, 16, this.filling, w); if (plotMinZ > 16) {
setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors, w); int x = 16 - roadStartX;
} if (x < 0) {
} else { x = 16;
if (roadStartZ > 16) { }
int x = 16 - roadStartX; setCuboidRegion(0, x, 1, this.plotheight, 0, 16,
if (x < 0) { this.filling, w);
x = 16; setCuboidRegion(0, x, this.plotheight,
} this.plotheight + 1, 0, 16,
int z = 16 - roadStartZ; this.plotfloors, w);
if (z < 0) { }
z = 16; }
} }
if (roadStartX > 16) { } else {
setCuboidRegion(0, x, 1, this.plotheight, 0, z, this.filling, w); if (plotMinZ <= 16) {
setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, z, this.plotfloors, w); if (roadStartX > 16) {
} else { int x = 16 - roadStartX;
setCuboidRegion(0, x, 1, this.plotheight, 0, z, this.filling, w); if (x < 0) {
setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, z, this.plotfloors, w); x = 16;
} }
} setCuboidRegion(0, x, 1, this.plotheight,
} 16 - plotMinZ, 16, this.filling, w);
} setCuboidRegion(0, x, this.plotheight,
} else { this.plotheight + 1, 16 - plotMinZ, 16,
if (roadStartX <= 16) { this.plotfloors, w);
if (roadStartZ <= 16) { }
setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 0, 16 - roadStartZ, this.filling, w); } else {
setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors, w); if (roadStartZ > 16) {
} int x = 16 - roadStartX;
if (plotMinZ <= 16) { if (x < 0) {
setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 16 - plotMinZ, 16, this.filling, w); x = 16;
setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors, w); }
} int z = 16 - roadStartZ;
} if (z < 0) {
if (plotMinX <= 16) { z = 16;
if (plotMinZ <= 16) { }
setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 16 - plotMinZ, 16, this.filling, w); if (roadStartX > 16) {
setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors, w); setCuboidRegion(0, x, 1, this.plotheight, 0, z,
} this.filling, w);
if (roadStartZ <= 16) { setCuboidRegion(0, x, this.plotheight,
setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.filling, w); this.plotheight + 1, 0, z, this.plotfloors,
setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors, w); 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) { 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); w.getBlockAt(this.X + x, y, this.Z + z).setData(val, false);
} }
} }

View File

@ -33,129 +33,140 @@ import com.intellectualcrafters.plot.database.DBFunc;
*/ */
public class WorldEditListener implements Listener { public class WorldEditListener implements Listener {
public final Set<String> blockedcmds = new HashSet<String>(Arrays.asList("/gmask", "//gmask", "/worldedit:gmask")); public final Set<String> blockedcmds = new HashSet<String>(Arrays.asList(
public final Set<String> restrictedcmds = new HashSet<String>(Arrays.asList("/up", "//up", "/worldedit:up")); "/gmask", "//gmask", "/worldedit:gmask"));
public final Set<String> restrictedcmds = new HashSet<String>(
Arrays.asList("/up", "//up", "/worldedit:up"));
private boolean isPlotWorld(Location l) { private boolean isPlotWorld(Location l) {
return (PlotMain.isPlotWorld(l.getWorld())); return (PlotMain.isPlotWorld(l.getWorld()));
} }
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onInteract(PlayerInteractEvent e) { public void onInteract(PlayerInteractEvent e) {
Block b = e.getClickedBlock(); Block b = e.getClickedBlock();
if (b == null) { if (b == null) {
return; return;
} }
Player p = e.getPlayer(); Player p = e.getPlayer();
Location l = b.getLocation(); Location l = b.getLocation();
if (!isPlotWorld(l)) { if (!isPlotWorld(l)) {
return; return;
} }
p.getItemInHand(); p.getItemInHand();
if ((p.getItemInHand() == null) || (p.getItemInHand().getType() == Material.AIR)) { if ((p.getItemInHand() == null)
return; || (p.getItemInHand().getType() == Material.AIR)) {
} return;
Plot plot = PlotHelper.getCurrentPlot(b.getLocation()); }
if (plot != null) { Plot plot = PlotHelper.getCurrentPlot(b.getLocation());
if ((plot != null) && plot.hasOwner() && (plot.helpers != null) && (plot.helpers.contains(DBFunc.everyone) || plot.helpers.contains(p.getUniqueId()))) { if (plot != null) {
PWE.setMask(p, l); 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) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPlayerCommand(PlayerCommandPreprocessEvent e) { public void onPlayerCommand(PlayerCommandPreprocessEvent e) {
Player p = e.getPlayer(); Player p = e.getPlayer();
if (PlotMain.hasPermission(p, "plots.worldedit.bypass") || !PlotMain.isPlotWorld(p.getWorld())) { if (PlotMain.hasPermission(p, "plots.worldedit.bypass")
return; || !PlotMain.isPlotWorld(p.getWorld())) {
} return;
String cmd = e.getMessage().toLowerCase(); }
String cmd = e.getMessage().toLowerCase();
if (cmd.contains(" ")) { if (cmd.contains(" ")) {
cmd = cmd.substring(0, cmd.indexOf(" ")); cmd = cmd.substring(0, cmd.indexOf(" "));
} }
if (this.restrictedcmds.contains(cmd)) { if (this.restrictedcmds.contains(cmd)) {
Plot plot = PlayerFunctions.getCurrentPlot(p); Plot plot = PlayerFunctions.getCurrentPlot(p);
if ((plot == null) || !(plot.helpers.contains(DBFunc.everyone) || plot.helpers.contains(p.getUniqueId()))) { if ((plot == null)
e.setCancelled(true); || !(plot.helpers.contains(DBFunc.everyone) || plot.helpers
} .contains(p.getUniqueId()))) {
} else if (this.blockedcmds.contains(cmd)) { e.setCancelled(true);
e.setCancelled(true); }
} } else if (this.blockedcmds.contains(cmd)) {
} e.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPlayerJoin(final PlayerJoinEvent e) { public void onPlayerJoin(final PlayerJoinEvent e) {
Player p = e.getPlayer(); Player p = e.getPlayer();
if (PlotMain.hasPermission(p, "plots.worldedit.bypass")) { if (PlotMain.hasPermission(p, "plots.worldedit.bypass")) {
return; return;
} }
Location l = p.getLocation(); Location l = p.getLocation();
if (isPlotWorld(l)) { if (isPlotWorld(l)) {
PWE.setMask(p, l); PWE.setMask(p, l);
} else { } else {
PWE.removeMask(p); PWE.removeMask(p);
} }
} }
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerMove(final PlayerMoveEvent e) { public void onPlayerMove(final PlayerMoveEvent e) {
Location t = e.getTo(); Location t = e.getTo();
if (!isPlotWorld(t)) { if (!isPlotWorld(t)) {
return; return;
} }
Location f = e.getFrom(); Location f = e.getFrom();
Player p = e.getPlayer(); Player p = e.getPlayer();
if ((f.getBlockX() != t.getBlockX()) || (f.getBlockZ() != t.getBlockZ())) { if ((f.getBlockX() != t.getBlockX())
PlotId idF = PlayerFunctions.getPlot(f); || (f.getBlockZ() != t.getBlockZ())) {
PlotId idT = PlayerFunctions.getPlot(t); PlotId idF = PlayerFunctions.getPlot(f);
if (PlotMain.hasPermission(e.getPlayer(), "plots.worldedit.bypass")) { PlotId idT = PlayerFunctions.getPlot(t);
return; if (PlotMain.hasPermission(e.getPlayer(), "plots.worldedit.bypass")) {
} return;
if ((idT != null) && !(idF == idT)) { }
PWE.setMask(p, t); if ((idT != null) && !(idF == idT)) {
} PWE.setMask(p, t);
} }
} }
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPortal(PlayerPortalEvent e) { public void onPortal(PlayerPortalEvent e) {
if (PlotMain.hasPermission(e.getPlayer(), "plots.worldedit.bypass")) { if (PlotMain.hasPermission(e.getPlayer(), "plots.worldedit.bypass")) {
return; return;
} }
Player p = e.getPlayer(); Player p = e.getPlayer();
Location t = e.getTo(); Location t = e.getTo();
Location f = e.getFrom(); Location f = e.getFrom();
if (t==null) { if (t == null) {
PWE.removeMask(p); PWE.removeMask(p);
return; return;
} }
if (isPlotWorld(t)) { if (isPlotWorld(t)) {
PWE.setMask(p, t); PWE.setMask(p, t);
return; return;
} }
if (f!=null && isPlotWorld(f)) { if (f != null && isPlotWorld(f)) {
PWE.removeMask(p); PWE.removeMask(p);
return; return;
} }
} }
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onTeleport(final PlayerTeleportEvent e) { public void onTeleport(final PlayerTeleportEvent e) {
if (PlotMain.hasPermission(e.getPlayer(), "plots.worldedit.bypass")) { if (PlotMain.hasPermission(e.getPlayer(), "plots.worldedit.bypass")) {
return; return;
} }
Player p = e.getPlayer(); Player p = e.getPlayer();
Location t = e.getTo(); Location t = e.getTo();
Location f = e.getFrom(); Location f = e.getFrom();
if (!isPlotWorld(t)) { if (!isPlotWorld(t)) {
if (isPlotWorld(f)) { if (isPlotWorld(f)) {
PWE.removeMask(p); PWE.removeMask(p);
} else { } else {
return; return;
} }
} }
PWE.setMask(p, t); PWE.setMask(p, t);
} }
} }

View File

@ -31,147 +31,165 @@ import com.sk89q.worldguard.protection.regions.ProtectedRegion;
* Created by Citymonstret on 2014-09-24. * Created by Citymonstret on 2014-09-24.
*/ */
public class WorldGuardListener implements Listener { public class WorldGuardListener implements Listener {
public ArrayList<String> str_flags = new ArrayList<String>(); public ArrayList<String> str_flags = new ArrayList<String>();
public ArrayList<Flag<?>> flags = new ArrayList<Flag<?>>(); public ArrayList<Flag<?>> flags = new ArrayList<Flag<?>>();
public WorldGuardListener(PlotMain plugin) { public WorldGuardListener(PlotMain plugin) {
plugin.getServer().getPluginManager().registerEvents(this, plugin); plugin.getServer().getPluginManager().registerEvents(this, plugin);
for (Flag<?> flag : DefaultFlag.getFlags()) { for (Flag<?> flag : DefaultFlag.getFlags()) {
this.str_flags.add(flag.getName()); this.str_flags.add(flag.getName());
this.flags.add(flag); this.flags.add(flag);
} }
} }
public void removeFlag(Player requester, World world, Plot plot, String key) { public void removeFlag(Player requester, World world, Plot plot, String key) {
boolean op = requester.isOp(); boolean op = requester.isOp();
requester.setOp(true); requester.setOp(true);
try { try {
RegionManager manager = PlotMain.worldGuard.getRegionManager(world); RegionManager manager = PlotMain.worldGuard.getRegionManager(world);
manager.getRegion(plot.id.x + "-" + plot.id.y); manager.getRegion(plot.id.x + "-" + plot.id.y);
for (Flag flag : this.flags) { for (Flag flag : this.flags) {
if (flag.getName().equalsIgnoreCase(key)) { if (flag.getName().equalsIgnoreCase(key)) {
requester.performCommand("region flag " + (plot.id.x + "-" + plot.id.y) + " " + key); requester.performCommand("region flag "
} + (plot.id.x + "-" + plot.id.y) + " " + key);
} }
} catch (Exception e) { }
requester.setOp(op); } catch (Exception e) {
} finally { requester.setOp(op);
requester.setOp(op); } finally {
} requester.setOp(op);
} }
}
public void addFlag(Player requester, World world, Plot plot, String key, String value) { public void addFlag(Player requester, World world, Plot plot, String key,
boolean op = requester.isOp(); String value) {
requester.setOp(true); boolean op = requester.isOp();
try { requester.setOp(true);
RegionManager manager = PlotMain.worldGuard.getRegionManager(world); try {
manager.getRegion(plot.id.x + "-" + plot.id.y); RegionManager manager = PlotMain.worldGuard.getRegionManager(world);
for (Flag flag : this.flags) { manager.getRegion(plot.id.x + "-" + plot.id.y);
if (flag.getName().equalsIgnoreCase(key)) { for (Flag flag : this.flags) {
requester.performCommand("region flag " + (plot.id.x + "-" + plot.id.y) + " " + key + " " + value); if (flag.getName().equalsIgnoreCase(key)) {
} requester.performCommand("region flag "
} + (plot.id.x + "-" + plot.id.y) + " " + key + " "
} catch (Exception e) { + value);
requester.setOp(op); }
} finally { }
requester.setOp(op); } catch (Exception e) {
} requester.setOp(op);
} } finally {
requester.setOp(op);
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onMerge(PlotMergeEvent event) { public void onMerge(PlotMergeEvent event) {
Plot main = event.getPlot(); Plot main = event.getPlot();
ArrayList<PlotId> plots = event.getPlots(); ArrayList<PlotId> plots = event.getPlots();
World world = event.getWorld(); World world = event.getWorld();
RegionManager manager = PlotMain.worldGuard.getRegionManager(world); RegionManager manager = PlotMain.worldGuard.getRegionManager(world);
for (PlotId plot : plots) { for (PlotId plot : plots) {
if (!plot.equals(main)) { if (!plot.equals(main)) {
manager.removeRegion(plot.x + "-" + plot.y); manager.removeRegion(plot.x + "-" + plot.y);
} }
} }
ProtectedRegion region = manager.getRegion(main.id.x + "-" + main.id.y); ProtectedRegion region = manager.getRegion(main.id.x + "-" + main.id.y);
DefaultDomain owner = region.getOwners(); DefaultDomain owner = region.getOwners();
Map<Flag<?>, Object> flags = region.getFlags(); Map<Flag<?>, Object> flags = region.getFlags();
DefaultDomain members = region.getMembers(); DefaultDomain members = region.getMembers();
manager.removeRegion(main.id.x + "-" + main.id.y); manager.removeRegion(main.id.x + "-" + main.id.y);
Location location1 = PlotHelper.getPlotBottomLocAbs(world, plots.get(0)); Location location1 = PlotHelper
Location location2 = PlotHelper.getPlotTopLocAbs(world, plots.get(plots.size() - 1)); .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 vector1 = new BlockVector(location1.getBlockX(), 1,
BlockVector vector2 = new BlockVector(location2.getBlockX(), world.getMaxHeight(), location2.getBlockZ()); location1.getBlockZ());
ProtectedRegion rg = new ProtectedCuboidRegion(main.id.x + "-" + main.id.y, vector1, vector2); 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) @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onUnlink(PlotUnlinkEvent event) { public void onUnlink(PlotUnlinkEvent event) {
World w = event.getWorld(); World w = event.getWorld();
ArrayList<PlotId> plots = event.getPlots(); ArrayList<PlotId> plots = event.getPlots();
Plot main = PlotMain.getPlots(w).get(plots.get(0)); Plot main = PlotMain.getPlots(w).get(plots.get(0));
RegionManager manager = PlotMain.worldGuard.getRegionManager(w); RegionManager manager = PlotMain.worldGuard.getRegionManager(w);
ProtectedRegion region = manager.getRegion(main.id.x + "-" + main.id.y); ProtectedRegion region = manager.getRegion(main.id.x + "-" + main.id.y);
DefaultDomain owner = region.getOwners(); DefaultDomain owner = region.getOwners();
Map<Flag<?>, Object> flags = region.getFlags(); Map<Flag<?>, Object> flags = region.getFlags();
DefaultDomain members = region.getMembers(); DefaultDomain members = region.getMembers();
manager.removeRegion(main.id.x + "-" + main.id.y); manager.removeRegion(main.id.x + "-" + main.id.y);
for (int i = 1; i < plots.size(); i++) { for (int i = 1; i < plots.size(); i++) {
PlotId id = plots.get(i); PlotId id = plots.get(i);
Location location1 = PlotHelper.getPlotBottomLocAbs(w, id); Location location1 = PlotHelper.getPlotBottomLocAbs(w, id);
Location location2 = PlotHelper.getPlotTopLocAbs(w, id); Location location2 = PlotHelper.getPlotTopLocAbs(w, id);
BlockVector vector1 = new BlockVector(location1.getBlockX(), 1, location1.getBlockZ()); BlockVector vector1 = new BlockVector(location1.getBlockX(), 1,
BlockVector vector2 = new BlockVector(location2.getBlockX(), w.getMaxHeight(), location2.getBlockZ()); location1.getBlockZ());
ProtectedRegion rg = new ProtectedCuboidRegion(id.x + "-" + id.y, vector1, vector2); 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 @EventHandler
public void onPlotClaim(PlayerClaimPlotEvent event) { public void onPlotClaim(PlayerClaimPlotEvent event) {
Player player = event.getPlayer(); Player player = event.getPlayer();
Plot plot = event.getPlot(); Plot plot = event.getPlot();
RegionManager manager = PlotMain.worldGuard.getRegionManager(plot.getWorld()); RegionManager manager = PlotMain.worldGuard.getRegionManager(plot
.getWorld());
Location location1 = PlotHelper.getPlotBottomLoc(plot.getWorld(), plot.getId()); Location location1 = PlotHelper.getPlotBottomLoc(plot.getWorld(),
Location location2 = PlotHelper.getPlotTopLoc(plot.getWorld(), plot.getId()); plot.getId());
Location location2 = PlotHelper.getPlotTopLoc(plot.getWorld(),
plot.getId());
BlockVector vector1 = new BlockVector(location1.getBlockX(), 1, location1.getBlockZ()); BlockVector vector1 = new BlockVector(location1.getBlockX(), 1,
BlockVector vector2 = new BlockVector(location2.getBlockX(), plot.getWorld().getMaxHeight(), location2.getBlockZ()); 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(); DefaultDomain owner = new DefaultDomain();
owner.addPlayer(PlotMain.worldGuard.wrapPlayer(player)); owner.addPlayer(PlotMain.worldGuard.wrapPlayer(player));
region.setOwners(owner); region.setOwners(owner);
manager.addRegion(region); manager.addRegion(region);
} }
@EventHandler @EventHandler
public void onPlotDelete(PlotDeleteEvent event) { public void onPlotDelete(PlotDeleteEvent event) {
PlotId plot = event.getPlotId(); PlotId plot = event.getPlotId();
World world = Bukkit.getWorld(event.getWorld()); World world = Bukkit.getWorld(event.getWorld());
RegionManager manager = PlotMain.worldGuard.getRegionManager(world); RegionManager manager = PlotMain.worldGuard.getRegionManager(world);
manager.removeRegion(plot.x + "-" + plot.y); manager.removeRegion(plot.x + "-" + plot.y);
} }
} }

View File

@ -20,34 +20,37 @@ import com.google.common.collect.ImmutableList;
* *
*/ */
public class NameFetcher implements Callable<Map<UUID, String>> { public class NameFetcher implements Callable<Map<UUID, String>> {
private static final String PROFILE_URL = "https://sessionserver.mojang.com/session/minecraft/profile/"; private static final String PROFILE_URL = "https://sessionserver.mojang.com/session/minecraft/profile/";
private final JSONParser jsonParser = new JSONParser(); private final JSONParser jsonParser = new JSONParser();
private final List<UUID> uuids; private final List<UUID> uuids;
public NameFetcher(List<UUID> uuids) { public NameFetcher(List<UUID> uuids) {
this.uuids = ImmutableList.copyOf(uuids); this.uuids = ImmutableList.copyOf(uuids);
} }
@Override @Override
public Map<UUID, String> call() throws Exception { public Map<UUID, String> call() throws Exception {
Map<UUID, String> uuidStringMap = new HashMap<UUID, String>(); Map<UUID, String> uuidStringMap = new HashMap<UUID, String>();
for (UUID uuid : this.uuids) { for (UUID uuid : this.uuids) {
if (uuidStringMap.containsKey(uuid)) { if (uuidStringMap.containsKey(uuid)) {
continue; continue;
} }
HttpURLConnection connection = (HttpURLConnection) new URL(PROFILE_URL + uuid.toString().replace("-", "")).openConnection(); HttpURLConnection connection = (HttpURLConnection) new URL(
JSONObject response = (JSONObject) this.jsonParser.parse(new InputStreamReader(connection.getInputStream())); PROFILE_URL + uuid.toString().replace("-", ""))
String name = (String) response.get("name"); .openConnection();
if (name == null) { JSONObject response = (JSONObject) this.jsonParser
continue; .parse(new InputStreamReader(connection.getInputStream()));
} String name = (String) response.get("name");
String cause = (String) response.get("cause"); if (name == null) {
String errorMessage = (String) response.get("errorMessage"); continue;
if ((cause != null) && (cause.length() > 0)) { }
throw new IllegalStateException(errorMessage); String cause = (String) response.get("cause");
} String errorMessage = (String) response.get("errorMessage");
uuidStringMap.put(uuid, name); if ((cause != null) && (cause.length() > 0)) {
} throw new IllegalStateException(errorMessage);
return uuidStringMap; }
} uuidStringMap.put(uuid, name);
}
return uuidStringMap;
}
} }

View File

@ -22,84 +22,91 @@ import com.google.common.collect.ImmutableList;
* @author * @author
*/ */
public class UUIDFetcher implements Callable<Map<String, UUID>> { public class UUIDFetcher implements Callable<Map<String, UUID>> {
private static final double PROFILES_PER_REQUEST = 100; private static final double PROFILES_PER_REQUEST = 100;
private static final String PROFILE_URL = "https://api.mojang.com/profiles/minecraft"; private static final String PROFILE_URL = "https://api.mojang.com/profiles/minecraft";
private final JSONParser jsonParser = new JSONParser(); private final JSONParser jsonParser = new JSONParser();
private final List<String> names; private final List<String> names;
private final boolean rateLimiting; private final boolean rateLimiting;
public UUIDFetcher(List<String> names, boolean rateLimiting) { public UUIDFetcher(List<String> names, boolean rateLimiting) {
this.names = ImmutableList.copyOf(names); this.names = ImmutableList.copyOf(names);
this.rateLimiting = rateLimiting; this.rateLimiting = rateLimiting;
} }
public UUIDFetcher(List<String> names) { public UUIDFetcher(List<String> names) {
this(names, true); this(names, true);
} }
@Override @Override
public Map<String, UUID> call() throws Exception { public Map<String, UUID> call() throws Exception {
Map<String, UUID> uuidMap = new HashMap<String, UUID>(); Map<String, UUID> uuidMap = new HashMap<String, UUID>();
int requests = (int) Math.ceil(this.names.size() / PROFILES_PER_REQUEST); int requests = (int) Math
for (int i = 0; i < requests; i++) { .ceil(this.names.size() / PROFILES_PER_REQUEST);
HttpURLConnection connection = createConnection(); for (int i = 0; i < requests; i++) {
String body = JSONArray.toJSONString(this.names.subList(i * 100, Math.min((i + 1) * 100, this.names.size()))); HttpURLConnection connection = createConnection();
writeBody(connection, body); String body = JSONArray.toJSONString(this.names.subList(i * 100,
JSONArray array = (JSONArray) this.jsonParser.parse(new InputStreamReader(connection.getInputStream())); Math.min((i + 1) * 100, this.names.size())));
for (Object profile : array) { writeBody(connection, body);
JSONObject jsonProfile = (JSONObject) profile; JSONArray array = (JSONArray) this.jsonParser
String id = (String) jsonProfile.get("id"); .parse(new InputStreamReader(connection.getInputStream()));
String name = (String) jsonProfile.get("name"); for (Object profile : array) {
UUID uuid = UUIDFetcher.getUUID(id); JSONObject jsonProfile = (JSONObject) profile;
uuidMap.put(name, uuid); String id = (String) jsonProfile.get("id");
} String name = (String) jsonProfile.get("name");
if (this.rateLimiting && (i != (requests - 1))) { UUID uuid = UUIDFetcher.getUUID(id);
Thread.sleep(100L); uuidMap.put(name, uuid);
} }
} if (this.rateLimiting && (i != (requests - 1))) {
return uuidMap; Thread.sleep(100L);
} }
}
return uuidMap;
}
private static void writeBody(HttpURLConnection connection, String body) throws Exception { private static void writeBody(HttpURLConnection connection, String body)
OutputStream stream = connection.getOutputStream(); throws Exception {
stream.write(body.getBytes()); OutputStream stream = connection.getOutputStream();
stream.flush(); stream.write(body.getBytes());
stream.close(); stream.flush();
} stream.close();
}
private static HttpURLConnection createConnection() throws Exception { private static HttpURLConnection createConnection() throws Exception {
URL url = new URL(PROFILE_URL); URL url = new URL(PROFILE_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST"); connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Content-Type", "application/json");
connection.setUseCaches(false); connection.setUseCaches(false);
connection.setDoInput(true); connection.setDoInput(true);
connection.setDoOutput(true); connection.setDoOutput(true);
return connection; return connection;
} }
public static UUID getUUID(String id) { 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)); 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) { public static byte[] toBytes(UUID uuid) {
ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]); ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]);
byteBuffer.putLong(uuid.getMostSignificantBits()); byteBuffer.putLong(uuid.getMostSignificantBits());
byteBuffer.putLong(uuid.getLeastSignificantBits()); byteBuffer.putLong(uuid.getLeastSignificantBits());
return byteBuffer.array(); return byteBuffer.array();
} }
public static UUID fromBytes(byte[] array) { public static UUID fromBytes(byte[] array) {
if (array.length != 16) { if (array.length != 16) {
throw new IllegalArgumentException("Illegal byte array length: " + array.length); throw new IllegalArgumentException("Illegal byte array length: "
} + array.length);
ByteBuffer byteBuffer = ByteBuffer.wrap(array); }
long mostSignificant = byteBuffer.getLong(); ByteBuffer byteBuffer = ByteBuffer.wrap(array);
long leastSignificant = byteBuffer.getLong(); long mostSignificant = byteBuffer.getLong();
return new UUID(mostSignificant, leastSignificant); long leastSignificant = byteBuffer.getLong();
} return new UUID(mostSignificant, leastSignificant);
}
public static UUID getUUIDOf(String name) throws Exception { public static UUID getUUIDOf(String name) throws Exception {
return new UUIDFetcher(Arrays.asList(name)).call().get(name); return new UUIDFetcher(Arrays.asList(name)).call().get(name);
} }
} }

View File

@ -15,78 +15,89 @@ import org.simpleframework.http.core.Container;
*/ */
public class IndexHandler implements Container { public class IndexHandler implements Container {
private JavaPlugin plugin; private JavaPlugin plugin;
private String title; private String title;
public IndexHandler(JavaPlugin plugin, String title) { public IndexHandler(JavaPlugin plugin, String title) {
this.plugin = plugin; this.plugin = plugin;
this.title = title; this.title = title;
} }
@Override @Override
public void handle(Request request, Response response) { public void handle(Request request, Response response) {
try { try {
PrintStream body; PrintStream body;
long time; long time;
String coverage; String coverage;
body = response.getPrintStream(); body = response.getPrintStream();
time = System.currentTimeMillis(); time = System.currentTimeMillis();
request.getQuery(); request.getQuery();
request.getPath(); request.getPath();
if ((request.getInteger("page")) < 0) { if ((request.getInteger("page")) < 0) {
} }
if (((coverage = request.getTarget()) == null) || coverage.equals("/")) { if (((coverage = request.getTarget()) == null)
coverage = "index"; || coverage.equals("/")) {
} coverage = "index";
}
coverage = coverage.toLowerCase(); coverage = coverage.toLowerCase();
List<String> list = new ArrayList<>(Arrays.asList(new String[] { "install", "index", "stylesheet" })); List<String> list = new ArrayList<>(Arrays.asList(new String[] {
"install", "index", "stylesheet" }));
if (!list.contains(coverage)) { if (!list.contains(coverage)) {
coverage = "index"; coverage = "index";
} }
if (coverage.equals("stylesheet")) { if (coverage.equals("stylesheet")) {
response.setValue("Content-Type", "text/css"); response.setValue("Content-Type", "text/css");
response.setValue("Server", "PlotWeb/1.0 (Simple 5.0)"); response.setValue("Server", "PlotWeb/1.0 (Simple 5.0)");
response.setDate("Date", time); response.setDate("Date", time);
response.setDate("Last-Modified", 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); body.print(stylesheetHTML);
} else { } else {
response.setValue("Content-Type", "html"); response.setValue("Content-Type", "html");
response.setValue("Server", "PlotWeb/1.0 (Simple 5.0)"); response.setValue("Server", "PlotWeb/1.0 (Simple 5.0)");
response.setDate("Date", time); response.setDate("Date", time);
response.setDate("Last-Modified", time); response.setDate("Last-Modified", time);
ResourceHandler header = new ResourceHandler("header", ResourceHandler.FileType.HTML, this.plugin.getDataFolder()); ResourceHandler header = new ResourceHandler("header",
ResourceHandler footer = new ResourceHandler("footer", ResourceHandler.FileType.HTML, this.plugin.getDataFolder()); ResourceHandler.FileType.HTML,
ResourceHandler cPage = new ResourceHandler(coverage, ResourceHandler.FileType.HTML, this.plugin.getDataFolder()); 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 headerHTML = header.getHTML().replace("@title",
String footerHTML = footer.getHTML(); this.title);
String cPageHTML = cPage.getHTML(); String footerHTML = footer.getHTML();
String cPageHTML = cPage.getHTML();
header.done(); header.done();
footer.done(); footer.done();
cPage.done(); cPage.done();
body.print(headerHTML); body.print(headerHTML);
body.print(cPageHTML); body.print(cPageHTML);
body.print(footerHTML); body.print(footerHTML);
} }
body.close(); body.close();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }

View File

@ -17,34 +17,35 @@ import com.intellectualcrafters.plot.PlotMain;
*/ */
public class PlotWeb { 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 String title;
private int port; private int port;
private Server server; private Server server;
private Connection connection; private Connection connection;
private Container container; private Container container;
private SocketAddress address; private SocketAddress address;
public PlotWeb(String title, int port) { public PlotWeb(String title, int port) {
this.title = title; this.title = title;
this.port = port; this.port = port;
} }
public void start() throws Exception { public void start() throws Exception {
this.container = new IndexHandler(JavaPlugin.getPlugin(PlotMain.class), this.title); this.container = new IndexHandler(JavaPlugin.getPlugin(PlotMain.class),
this.server = new ContainerServer(this.container); this.title);
this.connection = new SocketConnection(this.server); this.server = new ContainerServer(this.container);
this.address = new InetSocketAddress(this.port); this.connection = new SocketConnection(this.server);
this.address = new InetSocketAddress(this.port);
this.connection.connect(this.address); this.connection.connect(this.address);
PLOTWEB = this; PLOTWEB = this;
} }
public void stop() throws Exception { public void stop() throws Exception {
this.connection.close(); this.connection.close();
PLOTWEB = null; PLOTWEB = null;
} }
} }

View File

@ -10,43 +10,49 @@ import java.io.InputStreamReader;
*/ */
public class ResourceHandler { public class ResourceHandler {
private File file; private File file;
private BufferedReader reader; private BufferedReader reader;
public ResourceHandler(String filePath, FileType fileType, File folder) throws Exception { public ResourceHandler(String filePath, FileType fileType, File folder)
if (fileType == FileType.CSS) { throws Exception {
this.file = new File(folder.toPath().toString() + File.separator + "web" + File.separator + "css" + File.separator + filePath + "." + fileType.toString()); if (fileType == FileType.CSS) {
} else { this.file = new File(folder.toPath().toString() + File.separator
this.file = new File(folder.toPath().toString() + File.separator + "web" + File.separator + filePath + "." + fileType.toString()); + "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 { public String getHTML() throws Exception {
StringBuilder html = new StringBuilder(); StringBuilder html = new StringBuilder();
this.reader = new BufferedReader(new InputStreamReader(new FileInputStream(this.file))); this.reader = new BufferedReader(new InputStreamReader(
String line = ""; new FileInputStream(this.file)));
while ((line = this.reader.readLine()) != null) { String line = "";
html.append(line); while ((line = this.reader.readLine()) != null) {
} html.append(line);
return html.toString(); }
} return html.toString();
}
public void done() throws Exception { public void done() throws Exception {
this.reader.close(); this.reader.close();
} }
public static enum FileType { public static enum FileType {
CSS("css"), HTML("html"), JS("js"); CSS("css"), HTML("html"), JS("js");
private String ext; private String ext;
FileType(String ext) { FileType(String ext) {
this.ext = ext; this.ext = ext;
} }
@Override @Override
public String toString() { public String toString() {
return this.ext; return this.ext;
} }
} }
} }

View File

@ -5,12 +5,12 @@ package com.intellectualsites.web;
*/ */
public class Test { public class Test {
public static void main(String[] args) { public static void main(String[] args) {
try { try {
new PlotWeb("Test", 9000).start(); new PlotWeb("Test", 9000).start();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
} }