Added plot clear on claim. AND A LOT OF OTHER MORE IMPORTANT THINGS

Like... I added that space there, between that equals sign and the word
'this'
- Re-added old plot clear algorithm (in case SetBlockFast fails)
- Made some performance improvements with plot clear
- Used built in code cleaning in eclipse to make everything look nicer
- Bug fixes
This commit is contained in:
boy0001 2014-09-24 22:21:43 +10:00
parent 874f7575c1
commit d7bd7ba093
73 changed files with 5197 additions and 4756 deletions

View File

@ -3,11 +3,11 @@
<classpathentry kind="src" path="PlotSquared/src"/> <classpathentry kind="src" path="PlotSquared/src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="lib" path="C:/Users/Jesse Boyd/Desktop/plugins/plot_lib/lib/BarAPI.jar"/> <classpathentry kind="lib" path="C:/Users/Jesse Boyd/Desktop/plugins/plot_lib/lib/BarAPI.jar"/>
<classpathentry kind="lib" path="C:/Users/Jesse Boyd/Desktop/plugins/plot_lib/lib/bukkit-1.7.9-R0.2.jar"/>
<classpathentry kind="lib" path="C:/Users/Jesse Boyd/Desktop/plugins/plot_lib/lib/CameraAPI.jar"/> <classpathentry kind="lib" path="C:/Users/Jesse Boyd/Desktop/plugins/plot_lib/lib/CameraAPI.jar"/>
<classpathentry kind="lib" path="C:/Users/Jesse Boyd/Desktop/plugins/plot_lib/lib/PlotMe.jar"/> <classpathentry kind="lib" path="C:/Users/Jesse Boyd/Desktop/plugins/plot_lib/lib/PlotMe.jar"/>
<classpathentry kind="lib" path="C:/Users/Jesse Boyd/Desktop/plugins/plot_lib/lib/simple-5.1.6.jar"/> <classpathentry kind="lib" path="C:/Users/Jesse Boyd/Desktop/plugins/plot_lib/lib/simple-5.1.6.jar"/>
<classpathentry kind="lib" path="C:/Users/Jesse Boyd/Desktop/plugins/plot_lib/lib/simple-xml.jar"/> <classpathentry kind="lib" path="C:/Users/Jesse Boyd/Desktop/plugins/plot_lib/lib/simple-xml.jar"/>
<classpathentry kind="lib" path="C:/Users/Jesse Boyd/Desktop/plugins/plot_lib/lib/WorldEdit.jar"/> <classpathentry kind="lib" path="C:/Users/Jesse Boyd/Desktop/plugins/plot_lib/lib/WorldEdit.jar"/>
<classpathentry kind="lib" path="C:/Users/Jesse Boyd/Desktop/plugins/bukkit-1.7.9-R0.3.jar"/>
<classpathentry kind="output" path="bin"/> <classpathentry kind="output" path="bin"/>
</classpath> </classpath>

View File

@ -10,10 +10,12 @@ public class AbstractFlag {
private final String key; private final String key;
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) }
if (key.length() > 16) {
throw new IllegalArgumentException("Key must be <= 16 characters"); throw new IllegalArgumentException("Key must be <= 16 characters");
}
this.key = key.toLowerCase(); this.key = key.toLowerCase();
} }

View File

@ -13,232 +13,159 @@ import org.bukkit.ChatColor;
/** /**
* Captions class. * Captions class.
*
* @author Citymonstret * @author Citymonstret
* *
*/ */
public enum C { public enum C {
/* /*
Schematic Stuff * Schematic Stuff
*/ */
SCHEMATIC_MISSING_ARG("&cYou need to specify an argument. Possible values: &6test {name}"), 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"),
SCHEMATIC_INVALID("&cThat is not a valid schematic. Reason: &c%s"),
SCHEMATIC_VALID("&cThat's a valid schematic"),
SCHEMATIC_PASTE_FAILED("&cFailed to paste schematic"),
SCHEMATIC_PASTE_SUCCESS("&cSchematic pasted successfully"),
/* /*
Title Stuff * Title Stuff
*/ */
TITLE_ENTERED_PLOT("You entered plot %s"), 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"),
TITLE_ENTERED_PLOT_COLOR("GOLD"),
TITLE_ENTERED_PLOT_SUB("Owned by %s"),
TITLE_ENTERED_PLOT_SUB_COLOR("RED"),
TITLE_LEFT_PLOT("You entered plot %s"),
TITLE_LEFT_PLOT_COLOR("GOLD"),
TITLE_LEFT_PLOT_SUB("Owned by %s"),
TITLE_LEFT_PLOT_SUB_COLOR("RED"),
/* /*
Core Stuff * Core Stuff
*/ */
PREFIX("&c[&6&lPlot&c] "), PREFIX("&c[&6&lPlot&c] "), ENABLED("&6Plots are now enabled"), EXAMPLE_MESSAGE("&cThis is an example message &k!!!"),
ENABLED("&6Plots are now enabled"),
EXAMPLE_MESSAGE("&cThis is an example message &k!!!"),
/* /*
Reload * Reload
*/ */
RELOADED_CONFIGS("&6The translation files has been reloaded"), RELOADED_CONFIGS("&6The translation files has been reloaded"), RELOAD_FAILED("&cFailed to reload the translations file"),
RELOAD_FAILED("&cFailed to reload the translations file"), /*
/* * BarAPI
BarAPI
*/ */
BOSSBAR_CLEARING("&cClearing plot: &6%id%"), BOSSBAR_CLEARING("&cClearing plot: &6%id%"),
/* /*
Alias * Alias
*/ */
ALIAS_SET_TO("&cPlot alias set to &6%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"),
MISSING_ALIAS("&cYou need to specify the alias"),
ALIAS_IS_TAKEN("&cThat alias is already taken"),
/* /*
Position * Position
*/ */
MISSING_POSITION("&cYou need to specify a position. Possible values: &6default&c, &6center"), 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"),
POSITION_SET("&cPlot home position set"),
INVALID_POSITION("&cThat is not a valid position value"),
/* /*
Time * Time
*/ */
TIME_FORMAT("&6%hours%, %min%, %sec%"), TIME_FORMAT("&6%hours%, %min%, %sec%"),
/* /*
Permission * Permission
*/ */
NO_PERMISSION("&cYou don't have the permissions required to use this command."), 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_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"),
/* /*
Commands * Commands
*/ */
NOT_VALID_SUBCOMMAND("&cThat is not a valid subcommand."), 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: "),
NO_COMMANDS("&cI'm sorry, but you're not permitted to use any subcommands."),
SUBCOMMAND_SET_OPTIONS_HEADER("&cPossible Values: "),
/* /*
No {plot} * No {plot}
*/ */
NOT_IN_PLOT("&cYou're not in a 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"),
NOT_IN_PLOT_WORLD("&cYou're not in a plot world"),
NOT_VALID_WORLD("&cThat is not a valid world (case sensitive)"),
NOT_VALID_PLOT_WORLD("&cThat is not a valid plot world (case sensitive)"),
NO_PLOTS("&cYou don't have any plots"),
/* /*
Block List * Block List
*/ */
NOT_VALID_BLOCK_LIST_HEADER("&cThat's not a valid block. Valid blocks are:\\n"), NOT_VALID_BLOCK_LIST_HEADER("&cThat's not a valid block. Valid blocks are:\\n"), BLOCK_LIST_ITEM(" &6%mat%&c,"),
BLOCK_LIST_ITEM(" &6%mat%&c,"),
/* /*
Biome * Biome
*/ */
NEED_BIOME("&cYou've got to specify a biome"), NEED_BIOME("&cYou've got to specify a biome"), BIOME_SET_TO("&cPlot biome set to &c"),
BIOME_SET_TO("&cPlot biome set to &c"),
/* /*
Teleport / Entry * Teleport / Entry
*/ */
TELEPORTED_TO_PLOT("&6You have been teleported"), TELEPORTED_TO_PLOT("&6You have been teleported"),
/* /*
Set Block * Set Block
*/ */
SET_BLOCK_ACTION_FINISHED("&6The last setblock action is now finished."), SET_BLOCK_ACTION_FINISHED("&6The last setblock action is now finished."),
/* /*
Debug * Debug
*/ */
DEUBG_HEADER("&6Debug Information\\n"), DEUBG_HEADER("&6Debug Information\\n"), DEBUG_SECTION("&c>> &6&l%val%"), DEBUG_LINE("&c>> &6%var%&c:&6 %val%\\n"),
DEBUG_SECTION("&c>> &6&l%val%"),
DEBUG_LINE("&c>> &6%var%&c:&6 %val%\\n"),
/* /*
Invalid * Invalid
*/ */
NOT_VALID_DATA("&cThat's not a valid data id."), 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"),
NOT_VALID_BLOCK("&cThat's not a valid block."),
NOT_VALID_NUMBER("&cThat's not a valid number"),
NOT_VALID_PLOT_ID("&cThat's not a valid plot id."),
NOT_YOUR_PLOT("&cThat is not your plot."),
NO_SUCH_PLOT("&cThere is no such plot"),
PLAYER_HAS_NOT_BEEN_ON("&cThat player hasn't been in the plotworld"),
FOUND_NO_PLOTS("&cFound no plots with your search query"),
/* /*
Camera * Camera
*/ */
CAMERA_STARTED("&cYou have entered camera mode for plot &6%s"), CAMERA_STARTED("&cYou have entered camera mode for plot &6%s"), CAMERA_STOPPED("&cYou are no longer in camera mode"),
CAMERA_STOPPED("&cYou are no longer in camera mode"),
/* /*
Need * Need
*/ */
NEED_PLOT_NUMBER("&cYou've got to specify a plot number or alias"), 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"),
NEED_BLOCK("&cYou've got to specify a block"),
NEED_PLOT_ID("&cYou've got to specify a plot id."),
NEED_USER("&cYou need to specify a username"),
/* /*
Info * Info
*/ */
PLOT_INFO_UNCLAIMED("&cPlot &6%s&c is not yet claimed"), 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 Denied:&6%denied%&c, plot flags: &6%flags%"), PLOT_USER_LIST(" &6%user%&c,"),
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 Denied:&6%denied%&c, plot flags: &6%flags%"),
PLOT_USER_LIST(" &6%user%&c,"),
/* /*
Generating * Generating
*/ */
GENERATING_FLOOR("&6Started generating floor from your settings. It will take %time%"), 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."),
GENERATING_WALL("&6Started generating wall from your settings"),
GENERATING_WALL_FILLING("&cStarted generating wall filling from your settings."),
/* /*
Clearing * Clearing
*/ */
CLEARING_PLOT("&cClearing plot."), CLEARING_PLOT("&cClearing plot."), CLEARING_DONE("&6Done, took &a%time%&6 ms!"), CLEARING_DONE_PACKETS("&6(&a%time% &6ms for packets)"),
CLEARING_DONE("&6Done, took &a%time%&6 ms!"),
CLEARING_DONE_PACKETS("&6(&a%time% &6ms for packets)"),
/* /*
Claiming * Claiming
*/ */
PLOT_NOT_CLAIMED("&cCannot claim plot"), PLOT_NOT_CLAIMED("&cCannot claim plot"), PLOT_IS_CLAIMED("&cThis plot is already claimed"), CLAIMED("&6You successfully claimed the plot"),
PLOT_IS_CLAIMED("&cThis plot is already claimed"),
CLAIMED("&6You successfully claimed the plot"),
/* /*
List * List
*/ */
PLOT_LIST_HEADER("&6List of %word% plots"), 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%."),
PLOT_LIST_ITEM("&c>> &6%id% &c- &6%owner%"),
PLOT_LIST_FOOTER("&c>> &6%word% a total of &c%num% &6claimed %plot%."),
/* /*
Left * Left
*/ */
LEFT_PLOT("&cYou left a plot"), LEFT_PLOT("&cYou left a plot"),
/* /*
Wait * Wait
*/ */
WAIT_FOR_TIMER("&cA setblock timer is bound to either the current plot or you. Please wait for it to finish"), WAIT_FOR_TIMER("&cA setblock timer is bound to either the current plot or you. Please wait for it to finish"),
/* /*
Chat * Chat
*/ */
PLOT_CHAT_FORMAT("&c[&6Plot Chat&c][&6%plot_id%&c] &6%sender%&c: &6%msg%"), PLOT_CHAT_FORMAT("&c[&6Plot Chat&c][&6%plot_id%&c] &6%sender%&c: &6%msg%"),
/* /*
Denied * Denied
*/ */
DENIED_REMOVED("&cYou successfully undenied the player from this plot"), 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"),
DENIED_ADDED("&cYou successfully denied the player from this plot"),
DENIED_NEED_ARGUMENT("&cArguments are missing. &6/plot denied add {name} &cor &6/plot helpers remove {name}"),
WAS_NOT_DENIED("&cThat player was not denied on this plot"),
/* /*
Rain * Rain
*/ */
NEED_ON_OFF("&cYou need to specify a value. Possible values: &6on&c, &6off"), NEED_ON_OFF("&cYou need to specify a value. Possible values: &6on&c, &6off"), SETTING_UPDATED("&cYou successfully updated the setting"),
SETTING_UPDATED("&cYou successfully updated the setting"),
/* /*
* Flag * Flag
*/ */
NEED_KEY("&cPossible values: &6%values%"), 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"),
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
*/ */
HELPER_ADDED("&6You successfully added a helper to the plot"), 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"),
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"),
/* /*
Set Owner * Set Owner
*/ */
SET_OWNER("&6You successfully set the plot owner"), SET_OWNER("&6You successfully set the plot owner"),
/* /*
Signs * 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%"), OWNER_SIGN_LINE_1("&cID: &6%id%"), OWNER_SIGN_LINE_2("&cOwner:"), OWNER_SIGN_LINE_3("&6%plr%"), OWNER_SIGN_LINE_4("&2Claimed"),
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"),
/* /*
Custom * Help
*/ */
CUSTOM_STRING("-") 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"),
; /*
/** * Custom
* Default */
*/ CUSTOM_STRING("-");
private String d; /**
/** * Default
* Translated */
*/ private String d;
private String s; /**
* Translated
*/
private String s;
/** /**
* Constructor for custom strings. * Constructor for custom strings.
@ -246,48 +173,52 @@ public enum C {
@SuppressWarnings("unused") @SuppressWarnings("unused")
C() { C() {
/* /*
use setCustomString(); * use setCustomString();
*/ */
} }
/** /**
* Constructor * Constructor
* @param d default *
*/ * @param d
C(String d) { * default
this.d = d; */
this.s = PlotMain.translations.getString(this.toString()); C(String d) {
if (this.s==null) { this.d = d;
this.s = ""; this.s = PlotMain.translations.getString(this.toString());
} if (this.s == null) {
} 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() { */
if(this.s.length() < 1) public String s() {
return this.d.replace("\\n", "\n"); if (this.s.length() < 1) {
return this.s.replace("\\n", "\n"); return this.d.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

@ -21,68 +21,46 @@ public class ConsoleColors {
public static final String ANSI_ITALIC = "\033[3m]"; public static final String ANSI_ITALIC = "\033[3m]";
public static String fromString(String input) { public static String fromString(String input) {
input = input input = input.replaceAll("&0", fromChatColor(ChatColor.BLACK)).replaceAll("&1", fromChatColor(ChatColor.DARK_BLUE)).replaceAll("&2", fromChatColor(ChatColor.DARK_GREEN)).replaceAll("&3", fromChatColor(ChatColor.DARK_AQUA)).replaceAll("&4", fromChatColor(ChatColor.DARK_RED)).replaceAll("&5", fromChatColor(ChatColor.DARK_PURPLE)).replaceAll("&6", fromChatColor(ChatColor.GOLD)).replaceAll("&7", fromChatColor(ChatColor.GRAY)).replaceAll("&8", fromChatColor(ChatColor.DARK_GRAY)).replaceAll("&9", fromChatColor(ChatColor.BLUE)).replaceAll("&a", fromChatColor(ChatColor.GREEN)).replaceAll("&b", fromChatColor(ChatColor.AQUA)).replaceAll("&c", fromChatColor(ChatColor.RED)).replaceAll("&d", fromChatColor(ChatColor.LIGHT_PURPLE)).replaceAll("&e", fromChatColor(ChatColor.YELLOW)).replaceAll("&f", fromChatColor(ChatColor.WHITE)).replaceAll("&k", fromChatColor(ChatColor.MAGIC)).replaceAll("&l", fromChatColor(ChatColor.BOLD)).replaceAll("&m", fromChatColor(ChatColor.STRIKETHROUGH))
.replaceAll("&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))
.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 + ANSI_RESET; return input + ANSI_RESET;
} }
public static String fromChatColor(ChatColor color) { public static String fromChatColor(ChatColor color) {
switch(color) { switch (color) {
case RESET: case RESET:
return ANSI_RESET; return ANSI_RESET;
case GRAY: case GRAY:
case DARK_GRAY: case DARK_GRAY:
return ANSI_WHITE; return ANSI_WHITE;
case BLACK: case BLACK:
return ANSI_BLACK; return ANSI_BLACK;
case DARK_RED: case DARK_RED:
case RED: case RED:
return ANSI_RED; return ANSI_RED;
case GOLD: case GOLD:
case YELLOW: case YELLOW:
return ANSI_YELLOW; return ANSI_YELLOW;
case DARK_GREEN: case DARK_GREEN:
case GREEN: case GREEN:
return ANSI_GREEN; return ANSI_GREEN;
case AQUA: case AQUA:
case DARK_AQUA: case DARK_AQUA:
return ANSI_CYAN; return ANSI_CYAN;
case LIGHT_PURPLE: case LIGHT_PURPLE:
case DARK_PURPLE: case DARK_PURPLE:
return ANSI_PURPLE; return ANSI_PURPLE;
case BLUE: case BLUE:
case DARK_BLUE: case DARK_BLUE:
return ANSI_BLUE; return ANSI_BLUE;
case UNDERLINE: case UNDERLINE:
return ANSI_UNDERLINE; return ANSI_UNDERLINE;
case ITALIC: case ITALIC:
return ANSI_ITALIC; return ANSI_ITALIC;
case BOLD: case BOLD:
return ANSI_BOLD; return ANSI_BOLD;
default: default:
return ""; return "";
} }
} }
} }

View File

@ -6,41 +6,55 @@ import org.bukkit.ChatColor;
public class Flag { public class Flag {
private AbstractFlag key; private AbstractFlag key;
private String value; private String value;
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;
} }
public AbstractFlag getAbstractFlag() { return this.key; }
public AbstractFlag getAbstractFlag() {
return this.key;
}
public String getKey() { public String getKey() {
return this.key.getKey(); return this.key.getKey();
} }
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 key.getKey().hashCode(); return this.key.getKey().hashCode();
} }
} }

View File

@ -9,7 +9,7 @@ public class FlagManager {
private static ArrayList<AbstractFlag> flags; private static ArrayList<AbstractFlag> flags;
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);
@ -20,8 +20,8 @@ public class FlagManager {
} }
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;
} }
} }
@ -29,7 +29,7 @@ public class FlagManager {
} }
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);
return flag; return flag;
} }
@ -39,7 +39,9 @@ public class FlagManager {
public static List<AbstractFlag> getPlotFlags(Plot plot) { public static List<AbstractFlag> getPlotFlags(Plot plot) {
Set<Flag> plotFlags = plot.settings.getFlags(); Set<Flag> plotFlags = plot.settings.getFlags();
List<AbstractFlag> flags = new ArrayList<>(); List<AbstractFlag> flags = new ArrayList<>();
for(Flag flag : plotFlags) flags.add(flag.getAbstractFlag()); for (Flag flag : plotFlags) {
flags.add(flag.getAbstractFlag());
}
return flags; return flags;
} }
} }

View File

@ -13,6 +13,7 @@ import org.bukkit.Location;
/** /**
* Cube utilities * Cube utilities
*
* @author Citymonstret * @author Citymonstret
* *
*/ */
@ -21,101 +22,108 @@ 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(l1.getBlockX(), l2.getBlockX()); int x = Math.min(this.l1.getBlockX(), this.l2.getBlockX());
int y = Math.min(l1.getBlockY(), l2.getBlockY()); int y = Math.min(this.l1.getBlockY(), this.l2.getBlockY());
int z = Math.min(l1.getBlockZ(), l2.getBlockZ()); int z = Math.min(this.l1.getBlockZ(), this.l2.getBlockZ());
return new Location(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(l1.getBlockX(), l2.getBlockX()); int x = Math.max(this.l1.getBlockX(), this.l2.getBlockX());
int y = Math.max(l1.getBlockY(), l2.getBlockY()); int y = Math.max(this.l1.getBlockY(), this.l2.getBlockY());
int z = Math.max(l1.getBlockZ(), l2.getBlockZ()); int z = Math.max(this.l1.getBlockZ(), this.l2.getBlockZ());
return new Location(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()) return null; if (!hasNext()) {
this.current = this.current.add(1,1,1); return null;
return this.current; }
} this.current = this.current.add(1, 1, 1);
} return this.current;
}
}
} }

View File

@ -11,76 +11,85 @@ package com.intellectualcrafters.plot;
/** /**
* TPS and Lag Checker. * TPS and Lag Checker.
*
* @author Citymonstret * @author Citymonstret
* *
*/ */
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 Ticks *
* @param 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; }
long e = System.currentTimeMillis() - T[t]; int t = (TC - 1 - ticks) % T.length;
return ticks / (e / 1000.0D); long e = System.currentTimeMillis() - T[t];
} return ticks / (e / 1000.0D);
}
/** /**
* Get number of ticks since * Get number of ticks since
* @param tI Ticks < *
* @param tI
* 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

@ -9,62 +9,67 @@
package com.intellectualcrafters.plot; package com.intellectualcrafters.plot;
import java.io.*; import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
/** /**
* Logging of errors and debug messages. * Logging of errors and debug messages.
*
* @author Citymonstret * @author Citymonstret
* *
*/ */
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"), GENERAL("General"), WARNING("Warning"), DANGER("Danger");
WARNING("Warning"), private String name;
DANGER("Danger");
private String name;
LogLevel(String name) {
this.name = name;
}
@Override
public String toString() {
return this.name;
}
}
public static void write() throws IOException { LogLevel(String name) {
FileWriter writer = new FileWriter(log); this.name = name;
for(String string : entries) { }
writer.write(string + System.lineSeparator());
}
writer.close();
}
public static void add(LogLevel level, String string) { @Override
append("[" + level.toString() + "] " + string); public String toString() {
} return this.name;
}
}
private static void append(String string) { public static void write() throws IOException {
entries.add("[" + new Date().toString() + "]" + string); FileWriter writer = new FileWriter(log);
} for (String string : entries) {
writer.write(string + System.lineSeparator());
}
writer.close();
}
public static void add(LogLevel level, String string) {
append("[" + level.toString() + "] " + string);
}
private static void append(String string) {
entries.add("[" + new Date().toString() + "]" + string);
}
} }

View File

@ -1,32 +1,52 @@
package com.intellectualcrafters.plot; package com.intellectualcrafters.plot;
/* /*
* Copyright 2011-2013 Tyler Blair. All rights reserved. * Copyright 2011-2013 Tyler Blair. All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without modification, are * Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met: * permitted provided that the following conditions are met:
* *
* 1. Redistributions of source code must retain the above copyright notice, this list of * 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer. * conditions and the following disclaimer.
* *
* 2. Redistributions in binary form must reproduce the above copyright notice, this list * 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials * of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution. * provided with the distribution.
* *
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
* The views and conclusions contained in the software and documentation are those of the * The views and conclusions contained in the software and documentation are those of the
* authors and contributors and should not be interpreted as representing official policies, * authors and contributors and should not be interpreted as representing official policies,
* either expressed or implied, of anybody else. * either expressed or implied, of anybody else.
*/ */
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Level;
import java.util.zip.GZIPOutputStream;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.InvalidConfigurationException;
@ -35,15 +55,6 @@ import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.scheduler.BukkitTask; import org.bukkit.scheduler.BukkitTask;
import java.io.*;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.*;
import java.util.logging.Level;
import java.util.zip.GZIPOutputStream;
public class Metrics { public class Metrics {
/** /**
* The current revision number * The current revision number
@ -99,98 +110,110 @@ public class Metrics {
throw new IllegalArgumentException("Plugin cannot be null"); throw new IllegalArgumentException("Plugin cannot be null");
} }
this.plugin = plugin; this.plugin = plugin;
// load the config // load the config
configurationFile = getConfigFile(); this.configurationFile = getConfigFile();
configuration = YamlConfiguration.loadConfiguration(configurationFile); this.configuration = YamlConfiguration.loadConfiguration(this.configurationFile);
// add some defaults // add some defaults
configuration.addDefault("opt-out", false); this.configuration.addDefault("opt-out", false);
configuration.addDefault("guid", UUID.randomUUID().toString()); this.configuration.addDefault("guid", UUID.randomUUID().toString());
configuration.addDefault("debug", false); this.configuration.addDefault("debug", false);
// Do we need to create the file? // Do we need to create the file?
if (configuration.get("guid", null) == null) { if (this.configuration.get("guid", null) == null) {
configuration.options().header("http://mcstats.org").copyDefaults(true); this.configuration.options().header("http://mcstats.org").copyDefaults(true);
configuration.save(configurationFile); this.configuration.save(this.configurationFile);
} }
// Load the guid then // Load the guid then
guid = configuration.getString("guid"); this.guid = this.configuration.getString("guid");
debug = configuration.getBoolean("debug", false); this.debug = this.configuration.getBoolean("debug", false);
} }
/** /**
* Construct and create a Graph that can be used to separate specific plotters to their own graphs on the metrics * Construct and create a Graph that can be used to separate specific
* website. Plotters can be added to the graph object returned. * plotters to their own graphs on the metrics website. Plotters can be
* added to the graph object returned.
* *
* @param name The name of the graph * @param name
* @return Graph object created. Will never return NULL under normal circumstances unless bad parameters are given * The name of the graph
* @return Graph object created. Will never return NULL under normal
* circumstances unless bad parameters are given
*/ */
public Graph createGraph(final String name) { public Graph createGraph(final String name) {
if (name == null) { if (name == null) {
throw new IllegalArgumentException("Graph name cannot be null"); throw new IllegalArgumentException("Graph name cannot be null");
} }
// Construct the graph object // Construct the graph object
final Graph graph = new Graph(name); final Graph graph = new Graph(name);
// Now we can add our graph // Now we can add our graph
graphs.add(graph); this.graphs.add(graph);
// and return back // and return back
return graph; return graph;
} }
/** /**
* Add a Graph object to BukkitMetrics that represents data for the plugin that should be sent to the backend * Add a Graph object to BukkitMetrics that represents data for the plugin
* that should be sent to the backend
* *
* @param graph The name of the graph * @param graph
* The name of the graph
*/ */
public void addGraph(final Graph graph) { public void addGraph(final Graph graph) {
if (graph == null) { if (graph == null) {
throw new IllegalArgumentException("Graph cannot be null"); throw new IllegalArgumentException("Graph cannot be null");
} }
graphs.add(graph); this.graphs.add(graph);
} }
/** /**
* Start measuring statistics. This will immediately create an async repeating task as the plugin and send the * Start measuring statistics. This will immediately create an async
* initial data to the metrics backend, and then after that it will post in increments of PING_INTERVAL * 1200 * repeating task as the plugin and send the initial data to the metrics
* ticks. * backend, and then after that it will post in increments of PING_INTERVAL
* * 1200 ticks.
* *
* @return True if statistics measuring is running, otherwise false. * @return True if statistics measuring is running, otherwise false.
*/ */
public boolean start() { public boolean start() {
synchronized (optOutLock) { synchronized (this.optOutLock) {
// Did we opt out? // Did we opt out?
if (isOptOut()) { if (isOptOut()) {
return false; return false;
} }
// Is metrics already running? // Is metrics already running?
if (task != null) { if (this.task != null) {
return true; return true;
} }
// Begin hitting the server with glorious data // Begin hitting the server with glorious data
task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() { this.task = this.plugin.getServer().getScheduler().runTaskTimerAsynchronously(this.plugin, new Runnable() {
private boolean firstPost = true; private boolean firstPost = true;
@Override
public void run() { public void run() {
try { try {
// This has to be synchronized or it can collide with the disable method. // This has to be synchronized or it can collide with
synchronized (optOutLock) { // the disable method.
// Disable Task, if it is running and the server owner decided to opt-out synchronized (Metrics.this.optOutLock) {
if (isOptOut() && task != null) { // Disable Task, if it is running and the server
task.cancel(); // owner decided to opt-out
task = null; if (isOptOut() && (Metrics.this.task != null)) {
// Tell all plotters to stop gathering information. Metrics.this.task.cancel();
for (Graph graph : graphs) { Metrics.this.task = null;
// Tell all plotters to stop gathering
// information.
for (Graph graph : Metrics.this.graphs) {
graph.onOptOut(); graph.onOptOut();
} }
} }
} }
// We use the inverse of firstPost because if it is the first time we are posting, // We use the inverse of firstPost because if it is the
// it is not a interval ping, so it evaluates to FALSE // first time we are posting,
// Each time thereafter it will evaluate to TRUE, i.e PING! // it is not a interval ping, so it evaluates to FALSE
postPlugin(!firstPost); // Each time thereafter it will evaluate to TRUE, i.e
// After the first post we set firstPost to false // PING!
// Each post thereafter will be a ping postPlugin(!this.firstPost);
firstPost = false; // After the first post we set firstPost to false
// Each post thereafter will be a ping
this.firstPost = false;
} catch (IOException e) { } catch (IOException e) {
if (debug) { if (Metrics.this.debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage()); Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage());
} }
} }
@ -206,79 +229,87 @@ public class Metrics {
* @return true if metrics should be opted out of it * @return true if metrics should be opted out of it
*/ */
public boolean isOptOut() { public boolean isOptOut() {
synchronized (optOutLock) { synchronized (this.optOutLock) {
try { try {
// Reload the metrics file // Reload the metrics file
configuration.load(getConfigFile()); this.configuration.load(getConfigFile());
} catch (IOException ex) { } catch (IOException ex) {
if (debug) { if (this.debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
} }
return true; return true;
} catch (InvalidConfigurationException ex) { } catch (InvalidConfigurationException ex) {
if (debug) { if (this.debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage()); Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
} }
return true; return true;
} }
return configuration.getBoolean("opt-out", false); return this.configuration.getBoolean("opt-out", false);
} }
} }
/** /**
* Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task. * Enables metrics for the server by setting "opt-out" to false in the
* config file and starting the metrics task.
* *
* @throws java.io.IOException * @throws java.io.IOException
*/ */
public void enable() throws IOException { public void enable() throws IOException {
// This has to be synchronized or it can collide with the check in the task. // This has to be synchronized or it can collide with the check in the
synchronized (optOutLock) { // task.
// Check if the server owner has already set opt-out, if not, set it. synchronized (this.optOutLock) {
// Check if the server owner has already set opt-out, if not, set
// it.
if (isOptOut()) { if (isOptOut()) {
configuration.set("opt-out", false); this.configuration.set("opt-out", false);
configuration.save(configurationFile); this.configuration.save(this.configurationFile);
} }
// Enable Task, if it is not running // Enable Task, if it is not running
if (task == null) { if (this.task == null) {
start(); start();
} }
} }
} }
/** /**
* Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task. * Disables metrics for the server by setting "opt-out" to true in the
* config file and canceling the metrics task.
* *
* @throws java.io.IOException * @throws java.io.IOException
*/ */
public void disable() throws IOException { public void disable() throws IOException {
// This has to be synchronized or it can collide with the check in the task. // This has to be synchronized or it can collide with the check in the
synchronized (optOutLock) { // task.
// Check if the server owner has already set opt-out, if not, set it. synchronized (this.optOutLock) {
// Check if the server owner has already set opt-out, if not, set
// it.
if (!isOptOut()) { if (!isOptOut()) {
configuration.set("opt-out", true); this.configuration.set("opt-out", true);
configuration.save(configurationFile); this.configuration.save(this.configurationFile);
} }
// Disable Task, if it is running // Disable Task, if it is running
if (task != null) { if (this.task != null) {
task.cancel(); this.task.cancel();
task = null; this.task = null;
} }
} }
} }
/** /**
* Gets the File object of the config file that should be used to store data such as the GUID and opt-out status * Gets the File object of the config file that should be used to store data
* such as the GUID and opt-out status
* *
* @return the File object for the config file * @return the File object for the config file
*/ */
public File getConfigFile() { public File getConfigFile() {
// I believe the easiest way to get the base folder (e.g craftbukkit set via -P) for plugins to use // I believe the easiest way to get the base folder (e.g craftbukkit set
// is to abuse the plugin object we already have // via -P) for plugins to use
// plugin.getDataFolder() => base/plugins/PluginA/ // is to abuse the plugin object we already have
// pluginsFolder => base/plugins/ // plugin.getDataFolder() => base/plugins/PluginA/
// The base is not necessarily relative to the startup directory. // pluginsFolder => base/plugins/
File pluginsFolder = plugin.getDataFolder().getParentFile(); // The base is not necessarily relative to the startup directory.
// return => base/plugins/PluginMetrics/config.yml File pluginsFolder = this.plugin.getDataFolder().getParentFile();
// return => base/plugins/PluginMetrics/config.yml
return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml"); return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml");
} }
@ -286,29 +317,33 @@ public class Metrics {
* Generic method that posts a plugin to the metrics website * Generic method that posts a plugin to the metrics website
*/ */
private void postPlugin(final boolean isPing) throws IOException { private void postPlugin(final boolean isPing) throws IOException {
// Server software specific section // Server software specific section
PluginDescriptionFile description = plugin.getDescription(); PluginDescriptionFile description = this.plugin.getDescription();
String pluginName = description.getName(); String pluginName = description.getName();
boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE if online mode is enabled boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE if
// online mode
// is enabled
String pluginVersion = description.getVersion(); String pluginVersion = description.getVersion();
String serverVersion = Bukkit.getVersion(); String serverVersion = Bukkit.getVersion();
int playersOnline = Bukkit.getServer().getOnlinePlayers().length; int playersOnline = Bukkit.getServer().getOnlinePlayers().length;
// END server software specific section -- all code below does not use any code outside of this class / Java // END server software specific section -- all code below does not use
// Construct the post data // any code outside of this class / Java
// Construct the post data
StringBuilder json = new StringBuilder(1024); StringBuilder json = new StringBuilder(1024);
json.append('{'); json.append('{');
// The plugin's description file containg all of the plugin data such as name, version, author, etc // The plugin's description file containg all of the plugin data such as
appendJSONPair(json, "guid", guid); // name, version, author, etc
appendJSONPair(json, "guid", this.guid);
appendJSONPair(json, "plugin_version", pluginVersion); appendJSONPair(json, "plugin_version", pluginVersion);
appendJSONPair(json, "server_version", serverVersion); appendJSONPair(json, "server_version", serverVersion);
appendJSONPair(json, "players_online", Integer.toString(playersOnline)); appendJSONPair(json, "players_online", Integer.toString(playersOnline));
// New data as of R6 // New data as of R6
String osname = System.getProperty("os.name"); String osname = System.getProperty("os.name");
String osarch = System.getProperty("os.arch"); String osarch = System.getProperty("os.arch");
String osversion = System.getProperty("os.version"); String osversion = System.getProperty("os.version");
String java_version = System.getProperty("java.version"); String java_version = System.getProperty("java.version");
int coreCount = Runtime.getRuntime().availableProcessors(); int coreCount = Runtime.getRuntime().availableProcessors();
// normalize os arch .. amd64 -> x86_64 // normalize os arch .. amd64 -> x86_64
if (osarch.equals("amd64")) { if (osarch.equals("amd64")) {
osarch = "x86_64"; osarch = "x86_64";
} }
@ -318,12 +353,12 @@ public class Metrics {
appendJSONPair(json, "cores", Integer.toString(coreCount)); appendJSONPair(json, "cores", Integer.toString(coreCount));
appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0"); appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0");
appendJSONPair(json, "java_version", java_version); appendJSONPair(json, "java_version", java_version);
// If we're pinging, append it // If we're pinging, append it
if (isPing) { if (isPing) {
appendJSONPair(json, "ping", "1"); appendJSONPair(json, "ping", "1");
} }
if (graphs.size() > 0) { if (this.graphs.size() > 0) {
synchronized (graphs) { synchronized (this.graphs) {
json.append(','); json.append(',');
json.append('"'); json.append('"');
json.append("graphs"); json.append("graphs");
@ -331,7 +366,7 @@ public class Metrics {
json.append(':'); json.append(':');
json.append('{'); json.append('{');
boolean firstGraph = true; boolean firstGraph = true;
final Iterator<Graph> iter = graphs.iterator(); final Iterator<Graph> iter = this.graphs.iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
Graph graph = iter.next(); Graph graph = iter.next();
StringBuilder graphJson = new StringBuilder(); StringBuilder graphJson = new StringBuilder();
@ -351,14 +386,14 @@ public class Metrics {
json.append('}'); json.append('}');
} }
} }
// close json // close json
json.append('}'); json.append('}');
// Create the url // Create the url
URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName))); URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName)));
// Connect to the website // Connect to the website
URLConnection connection; URLConnection connection;
// Mineshafter creates a socks proxy, so we can safely bypass it // Mineshafter creates a socks proxy, so we can safely bypass it
// It does not reroute POST requests so we need to go around it // It does not reroute POST requests so we need to go around it
if (isMineshafterPresent()) { if (isMineshafterPresent()) {
connection = url.openConnection(Proxy.NO_PROXY); connection = url.openConnection(Proxy.NO_PROXY);
} else { } else {
@ -366,7 +401,7 @@ public class Metrics {
} }
byte[] uncompressed = json.toString().getBytes(); byte[] uncompressed = json.toString().getBytes();
byte[] compressed = gzip(json.toString()); byte[] compressed = gzip(json.toString());
// Headers // Headers
connection.addRequestProperty("User-Agent", "MCStats/" + REVISION); connection.addRequestProperty("User-Agent", "MCStats/" + REVISION);
connection.addRequestProperty("Content-Type", "application/json"); connection.addRequestProperty("Content-Type", "application/json");
connection.addRequestProperty("Content-Encoding", "gzip"); connection.addRequestProperty("Content-Encoding", "gzip");
@ -374,20 +409,20 @@ public class Metrics {
connection.addRequestProperty("Accept", "application/json"); connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close"); connection.addRequestProperty("Connection", "close");
connection.setDoOutput(true); connection.setDoOutput(true);
if (debug) { if (this.debug) {
System.out.println("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" + compressed.length); System.out.println("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" + compressed.length);
} }
// Write the data // Write the data
OutputStream os = connection.getOutputStream(); OutputStream os = connection.getOutputStream();
os.write(compressed); os.write(compressed);
os.flush(); os.flush();
// Now read the response // Now read the response
final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String response = reader.readLine(); String response = reader.readLine();
// close resources // close resources
os.close(); os.close();
reader.close(); reader.close();
if (response == null || response.startsWith("ERR") || response.startsWith("7")) { if ((response == null) || response.startsWith("ERR") || response.startsWith("7")) {
if (response == null) { if (response == null) {
response = "null"; response = "null";
} else if (response.startsWith("7")) { } else if (response.startsWith("7")) {
@ -395,10 +430,10 @@ public class Metrics {
} }
throw new IOException(response); throw new IOException(response);
} else { } else {
// Is this the first update this hour? // Is this the first update this hour?
if (response.equals("1") || response.contains("This is your first update this hour")) { if (response.equals("1") || response.contains("This is your first update this hour")) {
synchronized (graphs) { synchronized (this.graphs) {
final Iterator<Graph> iter = graphs.iterator(); final Iterator<Graph> iter = this.graphs.iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
final Graph graph = iter.next(); final Graph graph = iter.next();
for (Plotter plotter : graph.getPlotters()) { for (Plotter plotter : graph.getPlotters()) {
@ -425,16 +460,19 @@ public class Metrics {
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
if (gzos != null) try { if (gzos != null) {
gzos.close(); try {
} catch (IOException ignore) { gzos.close();
} catch (IOException ignore) {
}
} }
} }
return baos.toByteArray(); return baos.toByteArray();
} }
/** /**
* Check if mineshafter is present. If it is, we need to bypass it to send POST requests * Check if mineshafter is present. If it is, we need to bypass it to send
* POST requests
* *
* @return true if mineshafter is installed on the server * @return true if mineshafter is installed on the server
*/ */
@ -489,31 +527,31 @@ public class Metrics {
for (int index = 0; index < text.length(); index++) { for (int index = 0; index < text.length(); index++) {
char chr = text.charAt(index); char chr = text.charAt(index);
switch (chr) { switch (chr) {
case '"': case '"':
case '\\': case '\\':
builder.append('\\'); builder.append('\\');
builder.append(chr);
break;
case '\b':
builder.append("\\b");
break;
case '\t':
builder.append("\\t");
break;
case '\n':
builder.append("\\n");
break;
case '\r':
builder.append("\\r");
break;
default:
if (chr < ' ') {
String t = "000" + Integer.toHexString(chr);
builder.append("\\u" + t.substring(t.length() - 4));
} else {
builder.append(chr); builder.append(chr);
break; }
case '\b': break;
builder.append("\\b");
break;
case '\t':
builder.append("\\t");
break;
case '\n':
builder.append("\\n");
break;
case '\r':
builder.append("\\r");
break;
default:
if (chr < ' ') {
String t = "000" + Integer.toHexString(chr);
builder.append("\\u" + t.substring(t.length() - 4));
} else {
builder.append(chr);
}
break;
} }
} }
builder.append('"'); builder.append('"');
@ -523,7 +561,8 @@ public class Metrics {
/** /**
* Encode text as UTF-8 * Encode text as UTF-8
* *
* @param text the text to encode * @param text
* the text to encode
* @return the encoded text, as UTF-8 * @return the encoded text, as UTF-8
*/ */
private static String urlEncode(final String text) throws UnsupportedEncodingException { private static String urlEncode(final String text) throws UnsupportedEncodingException {
@ -535,8 +574,8 @@ public class Metrics {
*/ */
public static class Graph { public static class Graph {
/** /**
* The graph's name, alphanumeric and spaces only :) If it does not comply to the above when submitted, it is * The graph's name, alphanumeric and spaces only :) If it does not
* rejected * comply to the above when submitted, it is rejected
*/ */
private final String name; private final String name;
/** /**
@ -554,25 +593,27 @@ public class Metrics {
* @return the Graph's name * @return the Graph's name
*/ */
public String getName() { public String getName() {
return name; return this.name;
} }
/** /**
* Add a plotter to the graph, which will be used to plot entries * Add a plotter to the graph, which will be used to plot entries
* *
* @param plotter the plotter to add to the graph * @param plotter
* the plotter to add to the graph
*/ */
public void addPlotter(final Plotter plotter) { public void addPlotter(final Plotter plotter) {
plotters.add(plotter); this.plotters.add(plotter);
} }
/** /**
* Remove a plotter from the graph * Remove a plotter from the graph
* *
* @param plotter the plotter to remove from the graph * @param plotter
* the plotter to remove from the graph
*/ */
public void removePlotter(final Plotter plotter) { public void removePlotter(final Plotter plotter) {
plotters.remove(plotter); this.plotters.remove(plotter);
} }
/** /**
@ -581,12 +622,12 @@ public class Metrics {
* @return an unmodifiable {@link java.util.Set} of the plotter objects * @return an unmodifiable {@link java.util.Set} of the plotter objects
*/ */
public Set<Plotter> getPlotters() { public Set<Plotter> getPlotters() {
return Collections.unmodifiableSet(plotters); return Collections.unmodifiableSet(this.plotters);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return name.hashCode(); return this.name.hashCode();
} }
@Override @Override
@ -595,11 +636,12 @@ public class Metrics {
return false; return false;
} }
final Graph graph = (Graph) object; final Graph graph = (Graph) object;
return graph.name.equals(name); return graph.name.equals(this.name);
} }
/** /**
* Called when the server owner decides to opt-out of BukkitMetrics while the server is running. * Called when the server owner decides to opt-out of BukkitMetrics
* while the server is running.
*/ */
protected void onOptOut() { protected void onOptOut() {
} }
@ -624,16 +666,20 @@ public class Metrics {
/** /**
* Construct a plotter with a specific plot name * Construct a plotter with a specific plot name
* *
* @param name the name of the plotter to use, which will show up on the website * @param name
* the name of the plotter to use, which will show up on the
* website
*/ */
public Plotter(final String name) { public Plotter(final String name) {
this.name = name; this.name = name;
} }
/** /**
* Get the current value for the plotted point. Since this function defers to an external function it may or may * Get the current value for the plotted point. Since this function
* not return immediately thus cannot be guaranteed to be thread friendly or safe. This function can be called * defers to an external function it may or may not return immediately
* from any thread so care should be taken when accessing resources that need to be synchronized. * thus cannot be guaranteed to be thread friendly or safe. This
* function can be called from any thread so care should be taken when
* accessing resources that need to be synchronized.
* *
* @return the current value for the point to be plotted. * @return the current value for the point to be plotted.
*/ */
@ -645,7 +691,7 @@ public class Metrics {
* @return the plotted point's column name * @return the plotted point's column name
*/ */
public String getColumnName() { public String getColumnName() {
return name; return this.name;
} }
/** /**
@ -665,7 +711,7 @@ public class Metrics {
return false; return false;
} }
final Plotter plotter = (Plotter) object; final Plotter plotter = (Plotter) object;
return plotter.name.equals(name) && plotter.getValue() == getValue(); return plotter.name.equals(this.name) && (plotter.getValue() == getValue());
} }
} }
} }

View File

@ -11,7 +11,6 @@ import com.sk89q.worldedit.bukkit.BukkitPlayer;
import com.sk89q.worldedit.masks.RegionMask; import com.sk89q.worldedit.masks.RegionMask;
import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.CuboidRegion;
/** /**
* *
* @author Citymonstret * @author Citymonstret
@ -19,46 +18,47 @@ 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) {
LocalSession s = PlotMain.worldEdit.getSession(p); LocalSession s = PlotMain.worldEdit.getSession(p);
Plot plot = PlayerFunctions.getCurrentPlot(p); Plot plot = PlayerFunctions.getCurrentPlot(p);
if (plot!=null) { if (plot != null) {
boolean r; boolean r;
if (plot.getOwner()!=null) if (plot.getOwner() != null) {
r = plot.getOwner().equals(p.getUniqueId()); r = plot.getOwner().equals(p.getUniqueId());
else } else {
r = false; r = false;
if (!r) { }
if (p.hasPermission("plots.we.member") && plot.hasRights(p)) if (!r) {
r = true; if (p.hasPermission("plots.we.member") && plot.hasRights(p)) {
else if (p.hasPermission("plots.we.bypass")) { r = true;
s.setMask(null); } else if (p.hasPermission("plots.we.bypass")) {
return; s.setMask(null);
} return;
} }
if (r) { }
World w = p.getWorld(); if (r) {
Location b = PlotHelper.getPlotBottomLoc(w, plot.id); World w = p.getWorld();
Location t = PlotHelper.getPlotTopLoc(w, plot.id); Location b = PlotHelper.getPlotBottomLoc(w, plot.id);
Vector p1 = new Vector(b.getBlockX(),b.getBlockY(),b.getBlockZ()); Location t = PlotHelper.getPlotTopLoc(w, plot.id);
Vector p2 = new Vector(t.getBlockX(),t.getBlockY(),t.getBlockZ()); Vector p1 = new Vector(b.getBlockX(), b.getBlockY(), b.getBlockZ());
Vector p2 = new Vector(t.getBlockX(), t.getBlockY(), t.getBlockZ());
LocalWorld world = PlotMain.worldEdit.wrapPlayer(p).getWorld(); LocalWorld world = PlotMain.worldEdit.wrapPlayer(p).getWorld();
CuboidRegion cr = new CuboidRegion(world, p1, p2); CuboidRegion cr = new CuboidRegion(world, p1, p2);
RegionMask rm = new RegionMask(cr); RegionMask rm = new RegionMask(cr);
s.setMask(rm); s.setMask(rm);
return; return;
} }
} }
if(s.getMask() == null) { if (s.getMask() == null) {
BukkitPlayer plr = PlotMain.worldEdit.wrapPlayer(p); BukkitPlayer plr = PlotMain.worldEdit.wrapPlayer(p);
LocalWorld world = plr.getWorld(); LocalWorld world = plr.getWorld();
Vector p1 = new Vector(0,0,0), p2 = new Vector(0,0,0); Vector p1 = new Vector(0, 0, 0), p2 = new Vector(0, 0, 0);
s.setMask(new RegionMask(new CuboidRegion(world, p1, p2))); s.setMask(new RegionMask(new CuboidRegion(world, p1, p2)));
} }
} }
public static void removeMask(Player p) { public static void removeMask(Player p) {
LocalSession s = PlotMain.worldEdit.getSession(p); LocalSession s = PlotMain.worldEdit.getSession(p);
s.setMask(null); s.setMask(null);
} }
} }

View File

@ -9,15 +9,25 @@
package com.intellectualcrafters.plot; package com.intellectualcrafters.plot;
import org.bukkit.*; import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.WeatherType;
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.*;
/** /**
* Functions involving players, plots and locations. * Functions involving players, plots and locations.
* @author Citymonstret *
* @author Citymonstret
* *
*/ */
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
@ -25,88 +35,90 @@ public class PlayerFunctions {
/** /**
* *
* @param player player * @param 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 plot * @param 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;
} }
/** /**
* *
* @param loc * @param loc
* @return * @return
*/ */
public static PlotId getPlot(Location loc) { public static PlotId getPlot(Location loc) {
int valx = loc.getBlockX(); int valx = loc.getBlockX();
int valz = loc.getBlockZ(); int valz = loc.getBlockZ();
PlotWorld plotworld = PlotMain.getWorldSettings(loc.getWorld()); PlotWorld plotworld = PlotMain.getWorldSettings(loc.getWorld());
int size = plotworld.PLOT_WIDTH + plotworld.ROAD_WIDTH; int size = plotworld.PLOT_WIDTH + plotworld.ROAD_WIDTH;
int pathsize = plotworld.ROAD_WIDTH; int pathsize = plotworld.ROAD_WIDTH;
boolean road = false; boolean road = false;
double n3; double n3;
int mod2 = 0; int mod2 = 0;
int mod1 = 1; int mod1 = 1;
int x = (int) Math.ceil((double) valx / size); int x = (int) Math.ceil((double) valx / size);
int z = (int) Math.ceil((double) valz / size); int z = (int) Math.ceil((double) valz / size);
if(pathsize % 2 == 1) { if ((pathsize % 2) == 1) {
n3 = Math.ceil(((double) pathsize) / 2); n3 = Math.ceil(((double) pathsize) / 2);
mod2 = -1; mod2 = -1;
} else { } else {
n3 = Math.floor(((double) pathsize) / 2); n3 = Math.floor(((double) pathsize) / 2);
} }
for(double i = n3; i >= 0; i--) { for (double i = n3; i >= 0; i--) {
if((valx - i + mod1) % size == 0 || (valx + i + mod2) % size == 0) { if (((((valx - i) + mod1) % size) == 0) || (((valx + i + mod2) % size) == 0)) {
road = true; road = true;
x = (int) Math.ceil((valx - n3) / size); x = (int) Math.ceil((valx - n3) / size);
} }
if((valz - i + mod1) % size == 0 || (valz + i + mod2) % size == 0) { if (((((valz - i) + mod1) % size) == 0) || (((valz + i + mod2) % size) == 0)) {
road = true; road = true;
z = (int) Math.ceil((valz - n3) / size); z = (int) Math.ceil((valz - n3) / size);
} }
} }
if(road) { if (road) {
return null; return null;
} else { } else {
return new PlotId(x,z); return new PlotId(x, z);
} }
} }
/** /**
* *
* @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);
} }
/** /**
* *
@ -114,47 +126,50 @@ public class PlayerFunctions {
* @return * @return
*/ */
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
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()); }
World world = player.getWorld(); PlotId id = getPlot(player.getLocation());
if(id==null) { World world = player.getWorld();
return null; if (id == 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
*/ */
public static void set(Integer[] id, Plot plot) { @Deprecated
PlotMain.updatePlot(plot); public static void set(Integer[] id, Plot 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;
} }
@ -163,11 +178,11 @@ public class PlayerFunctions {
* @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();
} }
@ -178,11 +193,14 @@ public class PlayerFunctions {
*/ */
@SuppressWarnings("SuspiciousNameCombination") @SuppressWarnings("SuspiciousNameCombination")
public static int getAllowedPlots(Player p) { public static int getAllowedPlots(Player p) {
if(p.hasPermission("plots.admin")) return Integer.MAX_VALUE; if (p.hasPermission("plots.admin")) {
return Integer.MAX_VALUE;
}
int y = 0; int y = 0;
for(int x = 1; x <= 100; x++) { for (int x = 1; x <= 100; x++) {
if(p.hasPermission("plots.plot." + x)) y = x; if (p.hasPermission("plots.plot." + x)) {
else { y = x;
} else {
break; break;
} }
} }
@ -194,42 +212,55 @@ public class PlayerFunctions {
* @return PlotMain.getPlots(); * @return PlotMain.getPlots();
* @deprecated * @deprecated
*/ */
public static Set<Plot> getPlots() { @Deprecated
return PlotMain.getPlots(); public static Set<Plot> 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 Player to recieve message *
* @param msg Message to send * @param plr
* Player to recieve message
* @param msg
* 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("")) return; if ((msg.length() == 0) || msg.equalsIgnoreCase("")) {
sendMessageWrapped(plr, ChatColor.translateAlternateColorCodes('&', C.PREFIX.s() + msg)); return;
}
/**
* Send a message to the player
* @param plr Player to recieve message
* @param c Caption to send
*/
public static void sendMessage(Player plr, C c, String ... args) {
if(c.s().length() < 1) return;
String msg = c.s();
if(args != null && args.length > 0) {
for(String str : args)
msg = msg.replaceFirst("%s", str);
} }
sendMessage(plr, msg); sendMessageWrapped(plr, ChatColor.translateAlternateColorCodes('&', C.PREFIX.s() + msg));
} }
/**
* Send a message to the player
*
* @param plr
* Player to recieve message
* @param c
* Caption to send
*/
public static void sendMessage(Player plr, C c, String... args) {
if (c.s().length() < 1) {
return;
}
String msg = c.s();
if ((args != null) && (args.length > 0)) {
for (String str : args) {
msg = msg.replaceFirst("%s", str);
}
}
sendMessage(plr, msg);
}
} }

View File

@ -9,151 +9,158 @@
package com.intellectualcrafters.plot; package com.intellectualcrafters.plot;
import com.intellectualcrafters.plot.database.DBFunc; import java.util.ArrayList;
import java.util.UUID;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.World; 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.database.DBFunc;
import java.util.Set;
import java.util.UUID;
/** /**
* The plot class * The plot class
*
* @author Citymonstret * @author Citymonstret
* *
*/ */
@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 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 owner * @param id
* @param plotBiome * @param owner
* @param helpers * @param plotBiome
* @param denied * @param helpers
*/ * @param denied
public Plot(PlotId id, UUID owner, Biome plotBiome, ArrayList<UUID> helpers, ArrayList<UUID> denied, String world) { */
this.id = id; public Plot(PlotId id, UUID owner, Biome plotBiome, 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.settings.setTime(8000l); this.denied = denied;
this.settings.setRain(false); this.settings.setTime(8000l);
this.settings.setTimeChange(false); this.settings.setRain(false);
this.settings.setTimeChange(false);
this.settings.setAlias(""); this.settings.setAlias("");
this.settings.setPosition(PlotHomePosition.DEFAULT); this.settings.setPosition(PlotHomePosition.DEFAULT);
this.delete = false; this.delete = false;
this.settings.setFlags(new Flag[0]); this.settings.setFlags(new Flag[0]);
this.world = world; this.world = world;
}
/**
* Constructor for saved plots
* @param id
* @param owner
* @param plotBiome
* @param helpers
* @param denied
* @param changeTime
* @param time
*/
public Plot(PlotId id, UUID owner, Biome plotBiome, ArrayList<UUID> helpers, ArrayList<UUID> denied, boolean changeTime, long time, boolean rain, String alias, PlotHomePosition position, Flag[] flags, String world) {
this.id = id;
this.settings = new PlotSettings(this);
this.settings.setBiome(plotBiome);
this.owner = owner;
this.deny_entry = this.owner != null;
this.helpers = helpers;
this.denied = denied;
this.settings.setTime(time);
this.settings.setRain(rain);
this.settings.setTimeChange(changeTime);
this.settings.setAlias(alias);
this.settings.setPosition(position);
this.delete = false;
if (flags!=null)
this.settings.setFlags(flags);
else
this.settings.setFlags(new Flag[0]);
this.world = world;
}
/**
* Check if the plot has a set owner
* @return false if there is no owner
*/
public boolean hasOwner() {
return this.owner != null;
}
/**
* Set the owner
* @param player
*/
public void setOwner(Player player) {
this.owner = player.getUniqueId();
}
/**
* Check if the player is either the owner or on the helpers list
* @param player
* @return true if the player is added as a helper or is the owner
*/
public boolean hasRights(Player player) {
return player.hasPermission("plots.admin") || this.helpers != null && this.helpers.contains(DBFunc.everyone) || this.helpers != null && this.helpers.contains(player.getUniqueId()) || this.owner != null && this.owner.equals(player.getUniqueId());
} }
/** /**
* Should the player be allowed to enter? * Constructor for saved plots
* @param player *
* @return false if the player is allowed to enter * @param id
*/ * @param owner
public boolean deny_entry(Player player) { * @param plotBiome
return this.denied != null && (this.denied.contains(DBFunc.everyone) && !this.hasRights(player) || !this.hasRights(player) && this.denied.contains(player.getUniqueId())); * @param helpers
* @param denied
* @param changeTime
* @param time
*/
public Plot(PlotId id, UUID owner, Biome plotBiome, ArrayList<UUID> helpers, ArrayList<UUID> denied, boolean changeTime, long time, boolean rain, String alias, PlotHomePosition position, Flag[] flags, String world) {
this.id = id;
this.settings = new PlotSettings(this);
this.settings.setBiome(plotBiome);
this.owner = owner;
this.deny_entry = this.owner != null;
this.helpers = helpers;
this.denied = denied;
this.settings.setTime(time);
this.settings.setRain(rain);
this.settings.setTimeChange(changeTime);
this.settings.setAlias(alias);
this.settings.setPosition(position);
this.delete = false;
if (flags != null) {
this.settings.setFlags(flags);
} else {
this.settings.setFlags(new Flag[0]);
}
this.world = world;
}
/**
* Check if the plot has a set owner
*
* @return false if there is no owner
*/
public boolean hasOwner() {
return this.owner != null;
}
/**
* Set the owner
*
* @param player
*/
public void setOwner(Player player) {
this.owner = player.getUniqueId();
}
/**
* Check if the player is either the owner or on the helpers list
*
* @param player
* @return true if the player is added as a helper or is the owner
*/
public boolean hasRights(Player player) {
return player.hasPermission("plots.admin") || ((this.helpers != null) && this.helpers.contains(DBFunc.everyone)) || ((this.helpers != null) && this.helpers.contains(player.getUniqueId())) || ((this.owner != null) && this.owner.equals(player.getUniqueId()));
}
/**
* Should the player be allowed to enter?
*
* @param player
* @return false if the player is allowed to enter
*/
public boolean deny_entry(Player player) {
return (this.denied != null) && ((this.denied.contains(DBFunc.everyone) && !this.hasRights(player)) || (!this.hasRights(player) && this.denied.contains(player.getUniqueId())));
} }
/** /**
@ -172,7 +179,6 @@ public class Plot implements Cloneable{
return this.id; return this.id;
} }
/** /**
* Get the plot World * Get the plot World
* *
@ -183,55 +189,71 @@ public class Plot implements Cloneable{
/** /**
* 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) { this.denied.add(uuid); } public void addDenied(UUID 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) { this.helpers.add(uuid); } public void addHelper(UUID uuid) {
this.helpers.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) { this.denied.remove(uuid); } public void removeDenied(UUID 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) { this.helpers.remove(uuid); } public void removeHelper(UUID uuid) {
this.helpers.remove(uuid);
}
/** /**
* Clear a plot * Clear a plot
* @param plr initiator *
* @param plr
* initiator
*/ */
public void clear(Player plr) { public void clear(Player plr) {
PlotHelper.clear(plr, this); PlotHelper.clear(plr, this);
@ -239,8 +261,12 @@ public class Plot implements Cloneable{
/** /**
* Delete a plot * Delete a plot
* @param plr initiator *
* @param plr
* initiator
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
public void delete(Player plr) { this.clear(plr); } public void delete(Player plr) {
this.clear(plr);
}
} }

View File

@ -9,35 +9,47 @@
package com.intellectualcrafters.plot; package com.intellectualcrafters.plot;
import com.intellectualcrafters.plot.Logger.LogLevel; import java.util.ArrayList;
import com.intellectualcrafters.plot.database.DBFunc; import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import org.bukkit.*; import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.block.Biome; import org.bukkit.block.Biome;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.block.Sign; import org.bukkit.block.Sign;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import java.sql.PreparedStatement; import com.intellectualcrafters.plot.database.DBFunc;
import java.sql.SQLException;
import java.util.*;
import static com.intellectualcrafters.plot.PlotMain.connection;
import static com.intellectualcrafters.plot.Settings.*;
/** /**
* plot functions * plot functions
*
* @author Citymonstret * @author Citymonstret
* *
*/ */
public class PlotHelper { public class PlotHelper {
static long state;
/**
*
* @param blocks
* @param blocks_per_second
* @return
*/
private static double calculateNeededTime(double blocks, double blocks_per_second) { private static double calculateNeededTime(double blocks, double blocks_per_second) {
return (blocks / blocks_per_second); return (blocks / blocks_per_second);
} }
static long state;
public static final long nextLong() { public static final long nextLong() {
long a=state; long a = state;
state = xorShift64(a); state = xorShift64(a);
return a; return a;
} }
@ -48,15 +60,19 @@ public class PlotHelper {
a ^= (a << 4); a ^= (a << 4);
return a; return a;
} }
public static final int random(int n) { public static final int random(int n) {
long r = ((nextLong()>>>32)*n)>>32; if (n == 1) {
return 0;
}
long r = ((nextLong() >>> 32) * n) >> 32;
return (int) r; return (int) r;
} }
public static void removeSign(Player plr, Plot p) { public static void removeSign(Player plr, Plot p) {
PlotWorld plotworld = PlotMain.getWorldSettings(Bukkit.getWorld(p.world)); PlotWorld plotworld = PlotMain.getWorldSettings(Bukkit.getWorld(p.world));
Location pl = new Location(plr.getWorld(), getPlotBottomLoc(plr.getWorld(), p.id).getBlockX() , plotworld.ROAD_HEIGHT + 1, getPlotBottomLoc(plr.getWorld(), p.id).getBlockZ()); Location pl = new Location(plr.getWorld(), getPlotBottomLoc(plr.getWorld(), p.id).getBlockX(), plotworld.ROAD_HEIGHT + 1, getPlotBottomLoc(plr.getWorld(), p.id).getBlockZ());
Block bs = pl.add(0,0,-1).getBlock(); Block bs = pl.add(0, 0, -1).getBlock();
bs.setType(Material.AIR); bs.setType(Material.AIR);
} }
@ -64,11 +80,11 @@ public class PlotHelper {
public static void setSign(Player plr, Plot p) { public static void setSign(Player plr, Plot p) {
World world = Bukkit.getWorld(p.world); World world = Bukkit.getWorld(p.world);
PlotWorld plotworld = PlotMain.getWorldSettings(world); PlotWorld plotworld = PlotMain.getWorldSettings(world);
Location pl = new Location(world, getPlotBottomLoc(world, p.id).getBlockX() , plotworld.ROAD_HEIGHT + 1, getPlotBottomLoc(world, p.id).getBlockZ()); Location pl = new Location(world, getPlotBottomLoc(world, p.id).getBlockX(), plotworld.ROAD_HEIGHT + 1, getPlotBottomLoc(world, p.id).getBlockZ());
Block bs = pl.add(0,0,-1).getBlock(); Block bs = pl.add(0, 0, -1).getBlock();
bs.setType(Material.AIR); bs.setType(Material.AIR);
bs.setTypeIdAndData(Material.WALL_SIGN.getId(), (byte) 2, false); bs.setTypeIdAndData(Material.WALL_SIGN.getId(), (byte) 2, false);
String id = p.id.y+";"+p.id.x; String id = p.id.y + ";" + p.id.x;
Sign sign = (Sign) bs.getState(); Sign sign = (Sign) bs.getState();
sign.setLine(0, C.OWNER_SIGN_LINE_1.translated().replaceAll("%id%", id)); sign.setLine(0, C.OWNER_SIGN_LINE_1.translated().replaceAll("%id%", id));
sign.setLine(1, C.OWNER_SIGN_LINE_2.translated().replaceAll("%id%", id).replaceAll("%plr%", plr.getName())); sign.setLine(1, C.OWNER_SIGN_LINE_2.translated().replaceAll("%id%", id).replaceAll("%plr%", plr.getName()));
@ -78,14 +94,20 @@ public class PlotHelper {
} }
public static String getPlayerName(UUID uuid) { public static String getPlayerName(UUID uuid) {
if(uuid == null) return "unknown"; if (uuid == null) {
return "unknown";
}
OfflinePlayer plr = Bukkit.getOfflinePlayer(uuid); OfflinePlayer plr = Bukkit.getOfflinePlayer(uuid);
if(plr == null) return "unknown"; if (plr == null) {
return "unknown";
}
return plr.getName(); return plr.getName();
} }
public static String getStringSized(int max, String string) { public static String getStringSized(int max, String string) {
if(string.length() > max) return string.substring(0,max); if (string.length() > max) {
return string.substring(0, max);
}
return string; return string;
} }
@ -104,41 +126,41 @@ public class PlotHelper {
Block block; Block block;
for (x = bottom.getBlockX(); x < top.getBlockX() + 1; x++) { for (x = bottom.getBlockX(); x < (top.getBlockX() + 1); x++) {
z = bottom.getBlockZ(); z = bottom.getBlockZ();
block = w.getBlockAt(x, plotworld.ROAD_HEIGHT + 1, z); block = w.getBlockAt(x, plotworld.ROAD_HEIGHT + 1, z);
setWall(block, "" + id + ":" + data); setWall(block, "" + id + ":" + data);
} }
for (z = bottom.getBlockZ(); z < top.getBlockZ() + 1; z++) { for (z = bottom.getBlockZ(); z < (top.getBlockZ() + 1); z++) {
x = top.getBlockX() + 1; x = top.getBlockX() + 1;
block = w.getBlockAt(x, plotworld.ROAD_HEIGHT + 1, z); block = w.getBlockAt(x, plotworld.ROAD_HEIGHT + 1, z);
setWall(block, "" + id + ":" + data); setWall(block, "" + id + ":" + data);
} }
for (x = top.getBlockX() + 1; x > bottom.getBlockX() - 1; x--) { for (x = top.getBlockX() + 1; x > (bottom.getBlockX() - 1); x--) {
z = top.getBlockZ() + 1; z = top.getBlockZ() + 1;
block = w.getBlockAt(x, plotworld.ROAD_HEIGHT + 1, z); block = w.getBlockAt(x, plotworld.ROAD_HEIGHT + 1, z);
setWall(block, "" + id + ":" + data); setWall(block, "" + id + ":" + data);
} }
for (z = top.getBlockZ() + 1; z > bottom.getBlockZ() - 1; z--) { for (z = top.getBlockZ() + 1; z > (bottom.getBlockZ() - 1); z--) {
x = bottom.getBlockX(); x = bottom.getBlockX();
block = w.getBlockAt(x, plotworld.ROAD_HEIGHT + 1, z); block = w.getBlockAt(x, plotworld.ROAD_HEIGHT + 1, z);
setWall(block, "" + id + ":" + data); setWall(block, "" + id + ":" + data);
} }
} }
public static boolean createPlot(Player player, Plot plot) { public static boolean createPlot(Player player, Plot plot) {
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
World w = plot.getWorld(); World w = plot.getWorld();
Plot p = new Plot(plot.id, player.getUniqueId(), plot.settings.getBiome(), null, null, w.getName()); Plot p = new Plot(plot.id, player.getUniqueId(), plot.settings.getBiome(), null, null, w.getName());
PlotMain.updatePlot(p); PlotMain.updatePlot(p);
DBFunc.createPlot(p); DBFunc.createPlot(p);
DBFunc.createPlotSettings(DBFunc.getId(w.getName(),p.id), p); DBFunc.createPlotSettings(DBFunc.getId(w.getName(), p.id), p);
return true; return true;
} }
@ -151,171 +173,176 @@ public class PlotHelper {
} }
public static int getTileEntities(World world) { public static int getTileEntities(World world) {
PlotWorld plotworld = PlotMain.getWorldSettings(world); PlotMain.getWorldSettings(world);
int x = 0; int x = 0;
for(Chunk chunk : world.getLoadedChunks()) { for (Chunk chunk : world.getLoadedChunks()) {
x += chunk.getTileEntities().length; x += chunk.getTileEntities().length;
} }
return x; return x;
} }
public static double getWorldFolderSize(){ public static double getWorldFolderSize() {
//long size = FileUtils.sizeOfDirectory(Bukkit.getWorld(Settings.PLOT_WORLD).getWorldFolder()); // long size =
// FileUtils.sizeOfDirectory(Bukkit.getWorld(Settings.PLOT_WORLD).getWorldFolder());
long size = 10; long size = 10;
return (((size) / 1024) / 1024); return (((size) / 1024) / 1024);
} }
// public static void adjustLinkedPlots(String id) { // public static void adjustLinkedPlots(String id) {
// World world = Bukkit.getWorld(Settings.PLOT_WORLD); // World world = Bukkit.getWorld(Settings.PLOT_WORLD);
// int x = getIdX(id); // int x = getIdX(id);
// int z = getIdZ(id); // int z = getIdZ(id);
// //
// plot p11 = getPlot(id); // plot p11 = getPlot(id);
// if (p11 != null) { // if (p11 != null) {
// plot p01, p10, p12, p21, p00, p02, p20, p22; // plot p01, p10, p12, p21, p00, p02, p20, p22;
// p01 = getPlot(x - 1, z); // p01 = getPlot(x - 1, z);
// p10 = getPlot(x, z - 1); // p10 = getPlot(x, z - 1);
// p12 = getPlot(x, z + 1); // p12 = getPlot(x, z + 1);
// p21 = getPlot(x + 1, z); // p21 = getPlot(x + 1, z);
// p00 = getPlot(x - 1, z - 1); // p00 = getPlot(x - 1, z - 1);
// p02 = getPlot(x - 1, z + 1); // p02 = getPlot(x - 1, z + 1);
// p20 = getPlot(x + 1, z - 1); // p20 = getPlot(x + 1, z - 1);
// p22 = getPlot(x + 1, z + 1); // p22 = getPlot(x + 1, z + 1);
// if (p01 != null && p01.owner.equals(p11.owner)) { // if (p01 != null && p01.owner.equals(p11.owner)) {
// fillroad(p01, p11, world); // fillroad(p01, p11, world);
// } // }
// //
// if (p10 != null && p10.owner.equals(p11.owner)) { // if (p10 != null && p10.owner.equals(p11.owner)) {
// fillroad(p10, p11, world); // fillroad(p10, p11, world);
// } // }
// //
// if (p12 != null && p12.owner.equals(p11.owner)) { // if (p12 != null && p12.owner.equals(p11.owner)) {
// fillroad(p12, p11, world); // fillroad(p12, p11, world);
// } // }
// //
// if (p21 != null && p21.owner.equals(p11.owner)) { // if (p21 != null && p21.owner.equals(p11.owner)) {
// fillroad(p21, p11, world); // fillroad(p21, p11, world);
// } // }
// //
// if (p00 != null && p10 != null && p01 != null // if (p00 != null && p10 != null && p01 != null
// && p00.owner.equals(p11.owner) // && p00.owner.equals(p11.owner)
// && p11.owner.equals(p10.owner) // && p11.owner.equals(p10.owner)
// && p10.owner.equals(p01.owner)) { // && p10.owner.equals(p01.owner)) {
// fillmiddleroad(p00, p11, world); // fillmiddleroad(p00, p11, world);
// } // }
// //
// if (p10 != null && p20 != null && p21 != null // if (p10 != null && p20 != null && p21 != null
// && p10.owner.equals(p11.owner) // && p10.owner.equals(p11.owner)
// && p11.owner.equals(p20.owner) // && p11.owner.equals(p20.owner)
// && p20.owner.equals(p21.owner)) { // && p20.owner.equals(p21.owner)) {
// fillmiddleroad(p20, p11, world); // fillmiddleroad(p20, p11, world);
// } // }
// //
// if (p01 != null && p02 != null && p12 != null // if (p01 != null && p02 != null && p12 != null
// && p01.owner.equals(p11.owner) // && p01.owner.equals(p11.owner)
// && p11.owner.equals(p02.owner) // && p11.owner.equals(p02.owner)
// && p02.owner.equals(p12.owner)) { // && p02.owner.equals(p12.owner)) {
// fillmiddleroad(p02, p11, world); // fillmiddleroad(p02, p11, world);
// } // }
// //
// if (p12 != null && p21 != null && p22 != null // if (p12 != null && p21 != null && p22 != null
// && p12.owner.equals(p11.owner) // && p12.owner.equals(p11.owner)
// && p11.owner.equals(p21.owner) // && p11.owner.equals(p21.owner)
// && p21.owner.equals(p22.owner)) { // && p21.owner.equals(p22.owner)) {
// fillmiddleroad(p22, p11, world); // fillmiddleroad(p22, p11, world);
// } // }
// } // }
// } // }
// //
// public static void fillroad(plot plot1, plot plot2, World w) { // public static void fillroad(plot plot1, plot plot2, World w) {
// Location bottomPlot1, topPlot1, bottomPlot2, topPlot2; // Location bottomPlot1, topPlot1, bottomPlot2, topPlot2;
// bottomPlot1 = getPlotBottomLoc(w, plot1.id); // bottomPlot1 = getPlotBottomLoc(w, plot1.id);
// topPlot1 = getPlotTopLoc(w, plot1.id); // topPlot1 = getPlotTopLoc(w, plot1.id);
// bottomPlot2 = getPlotBottomLoc(w, plot2.id); // bottomPlot2 = getPlotBottomLoc(w, plot2.id);
// topPlot2 = getPlotTopLoc(w, plot2.id); // topPlot2 = getPlotTopLoc(w, plot2.id);
// //
// int minX, maxX, minZ, maxZ; // int minX, maxX, minZ, maxZ;
// //
// boolean isWallX; // boolean isWallX;
// //
// int h = Settings.ROAD_HEIGHT; // int h = Settings.ROAD_HEIGHT;
// int wallId = Settings.WALL_BLOCK; // int wallId = Settings.WALL_BLOCK;
// int fillId = Settings.TOP_BLOCK; // int fillId = Settings.TOP_BLOCK;
// //
// if(bottomPlot1.getBlockX() == bottomPlot2.getBlockX()) { // if(bottomPlot1.getBlockX() == bottomPlot2.getBlockX()) {
// minX = bottomPlot1.getBlockX(); // minX = bottomPlot1.getBlockX();
// maxX = topPlot1.getBlockX(); // maxX = topPlot1.getBlockX();
// //
// minZ = Math.min(bottomPlot1.getBlockZ(), bottomPlot2.getBlockZ()) + Settings.PLOT_WIDTH; // minZ = Math.min(bottomPlot1.getBlockZ(), bottomPlot2.getBlockZ()) +
// maxZ = Math.min(topPlot1.getBlockZ(), topPlot2.getBlockZ()) - Settings.PLOT_WIDTH; // Settings.PLOT_WIDTH;
// } else { // maxZ = Math.min(topPlot1.getBlockZ(), topPlot2.getBlockZ()) -
// minZ = bottomPlot1.getBlockZ(); // Settings.PLOT_WIDTH;
// maxZ = topPlot1.getBlockZ(); // } else {
// // minZ = bottomPlot1.getBlockZ();
// minX = Math.min(bottomPlot1.getBlockX(), bottomPlot2.getBlockX()) + Settings.PLOT_WIDTH; // maxZ = topPlot1.getBlockZ();
// maxX = Math.max(topPlot1.getBlockX(), topPlot2.getBlockX()) - Settings.PLOT_WIDTH; //
// } // minX = Math.min(bottomPlot1.getBlockX(), bottomPlot2.getBlockX()) +
// // Settings.PLOT_WIDTH;
// isWallX = (maxX - minX) > (maxZ - minZ); // maxX = Math.max(topPlot1.getBlockX(), topPlot2.getBlockX()) -
// // Settings.PLOT_WIDTH;
// if(isWallX) { // }
// minX--; //
// maxX++; // isWallX = (maxX - minX) > (maxZ - minZ);
// } else { //
// minZ--; // if(isWallX) {
// maxZ++; // minX--;
// } // maxX++;
// // } else {
// for(int x = minX; x <= maxX; x++) { // minZ--;
// for(int z = minZ; x <= maxZ; z++) { // maxZ++;
// for(int y = h; y < h + 3; y++) { // }
// if(y >= (h + 2)) { //
// w.getBlockAt(x,y,z).setType(Material.AIR); // for(int x = minX; x <= maxX; x++) {
// } else if(y == (h + 1)) { // for(int z = minZ; x <= maxZ; z++) {
// if(isWallX && (x == minX || x == maxX)) { // for(int y = h; y < h + 3; y++) {
// w.getBlockAt(x,y,z).setTypeIdAndData(wallId, (byte) 0, true); // if(y >= (h + 2)) {
// } else if(!isWallX && (z == minZ || z == maxZ)) { // w.getBlockAt(x,y,z).setType(Material.AIR);
// w.getBlockAt(x,y,z).setTypeIdAndData(wallId, (byte) 0, true); // } else if(y == (h + 1)) {
// } else { // if(isWallX && (x == minX || x == maxX)) {
// w.getBlockAt(x,y,z).setType(Material.AIR); // w.getBlockAt(x,y,z).setTypeIdAndData(wallId, (byte) 0, true);
// } // } else if(!isWallX && (z == minZ || z == maxZ)) {
// } else { // w.getBlockAt(x,y,z).setTypeIdAndData(wallId, (byte) 0, true);
// w.getBlockAt(x,y,z).setTypeIdAndData(fillId, (byte) 0, true); // } else {
// } // w.getBlockAt(x,y,z).setType(Material.AIR);
// } // }
// } // } else {
// } // w.getBlockAt(x,y,z).setTypeIdAndData(fillId, (byte) 0, true);
// } // }
// // }
// public static void fillmiddleroad(plot p1, plot p2, World w) { // }
// Location b1 = getPlotBottomLoc(w, p1.id); // }
// Location t1 = getPlotTopLoc(w, p1.id); // }
// Location b2 = getPlotBottomLoc(w, p2.id); //
// Location t2 = getPlotTopLoc(w, p2.id); // public static void fillmiddleroad(plot p1, plot p2, World w) {
// // Location b1 = getPlotBottomLoc(w, p1.id);
// int minX, maxX, minZ, maxZ; // Location t1 = getPlotTopLoc(w, p1.id);
// // Location b2 = getPlotBottomLoc(w, p2.id);
// int h = Settings.ROAD_HEIGHT; // Location t2 = getPlotTopLoc(w, p2.id);
// int fillID = Settings.TOP_BLOCK; //
// // int minX, maxX, minZ, maxZ;
// minX = Math.min(t1.getBlockX(), t2.getBlockX()); //
// maxX = Math.max(b1.getBlockX(), b2.getBlockX()); // int h = Settings.ROAD_HEIGHT;
// // int fillID = Settings.TOP_BLOCK;
// minZ = Math.min(t1.getBlockZ(), t2.getBlockZ()); //
// maxZ = Math.max(b1.getBlockZ(), b2.getBlockZ()); // minX = Math.min(t1.getBlockX(), t2.getBlockX());
// // maxX = Math.max(b1.getBlockX(), b2.getBlockX());
// for(int x = minX; x <= maxX; x++) { //
// for(int z = minZ; z <= maxZ; z++) { // minZ = Math.min(t1.getBlockZ(), t2.getBlockZ());
// for(int y = h; y < h + 3; y++) { // maxZ = Math.max(b1.getBlockZ(), b2.getBlockZ());
// if(y >= (h + 1)) { //
// w.getBlockAt(x,y,z).setType(Material.AIR); // for(int x = minX; x <= maxX; x++) {
// } else { // for(int z = minZ; z <= maxZ; z++) {
// w.getBlockAt(x,y,z).setTypeId(fillID); // for(int y = h; y < h + 3; y++) {
// } // if(y >= (h + 1)) {
// } // w.getBlockAt(x,y,z).setType(Material.AIR);
// } // } else {
// } // w.getBlockAt(x,y,z).setTypeId(fillID);
// } // }
// }
// }
// }
// }
public static String createId(int x, int z) { public static String createId(int x, int z) {
return x + ";" + z; return x + ";" + z;
@ -324,67 +351,55 @@ public class PlotHelper {
public static ArrayList<String> runners_p = new ArrayList<String>(); public static ArrayList<String> runners_p = new ArrayList<String>();
public static HashMap<Plot, Integer> runners = new HashMap<Plot, Integer>(); public static HashMap<Plot, Integer> runners = new HashMap<Plot, Integer>();
public static void adjustWallFilling(final Player requester, final World w, final Plot plot, public static void adjustWallFilling(final Player requester, final World w, final Plot plot, final short id, final byte data) {
final short id, final byte data) { if (runners.containsKey(plot)) {
if(runners.containsKey(plot)) {
PlayerFunctions.sendMessage(requester, C.WAIT_FOR_TIMER); PlayerFunctions.sendMessage(requester, C.WAIT_FOR_TIMER);
return; return;
} }
PlayerFunctions.sendMessage(requester, C.GENERATING_WALL_FILLING); PlayerFunctions.sendMessage(requester, C.GENERATING_WALL_FILLING);
final PlotWorld plotworld = PlotMain.getWorldSettings(w); final PlotWorld plotworld = PlotMain.getWorldSettings(w);
runners.put( runners.put(plot, Bukkit.getScheduler().scheduleSyncRepeatingTask(PlotMain.getMain(), new Runnable() {
plot, Location bottom = getPlotBottomLoc(w, plot.id);
Bukkit.getScheduler().scheduleSyncRepeatingTask(PlotMain.getMain(), Location top = getPlotTopLoc(w, plot.id);
new Runnable() { int y = plotworld.ROAD_HEIGHT;
Location bottom = getPlotBottomLoc(w, plot.id); int x, z;
Location top = getPlotTopLoc(w, plot.id);
int y = plotworld.ROAD_HEIGHT;
int x, z;
@Override @Override
public void run() { public void run() {
for (x = bottom.getBlockX(); x < top for (this.x = this.bottom.getBlockX(); this.x < (this.top.getBlockX() + 1); this.x++) {
.getBlockX() + 1; x++) { this.z = this.bottom.getBlockZ();
z = bottom.getBlockZ(); setWall(w.getBlockAt(this.x, this.y, this.z), "" + id + ":" + data);
setWall(w.getBlockAt(x, y, z), "" + id }
+ ":" + data);
}
for (z = bottom.getBlockZ(); z < top for (this.z = this.bottom.getBlockZ(); this.z < (this.top.getBlockZ() + 1); this.z++) {
.getBlockZ() + 1; z++) { this.x = this.top.getBlockX() + 1;
x = top.getBlockX() + 1; setWall(w.getBlockAt(this.x, this.y, this.z), "" + id + ":" + data);
setWall(w.getBlockAt(x, y, z), "" + id }
+ ":" + data);
}
for (x = top.getBlockX() + 1; x > bottom for (this.x = this.top.getBlockX() + 1; this.x > (this.bottom.getBlockX() - 1); this.x--) {
.getBlockX() - 1; x--) { this.z = this.top.getBlockZ() + 1;
z = top.getBlockZ() + 1; setWall(w.getBlockAt(this.x, this.y, this.z), "" + id + ":" + data);
setWall(w.getBlockAt(x, y, z), "" + id }
+ ":" + data);
}
for (z = top.getBlockZ() + 1; z > bottom for (this.z = this.top.getBlockZ() + 1; this.z > (this.bottom.getBlockZ() - 1); this.z--) {
.getBlockZ() - 1; z--) { this.x = this.bottom.getBlockX();
x = bottom.getBlockX(); setWall(w.getBlockAt(this.x, this.y, this.z), "" + id + ":" + data);
setWall(w.getBlockAt(x, y, z), "" + id }
+ ":" + data);
}
y--; this.y--;
if (y < 1) { if (this.y < 1) {
int runner = runners.get(plot); int runner = runners.get(plot);
runners.remove(plot); runners.remove(plot);
PlayerFunctions.sendMessage(requester, C.SET_BLOCK_ACTION_FINISHED); PlayerFunctions.sendMessage(requester, C.SET_BLOCK_ACTION_FINISHED);
Bukkit.getScheduler().cancelTask(runner); Bukkit.getScheduler().cancelTask(runner);
} }
} }
}, 0l, 5l)); }, 0l, 5l));
} }
public static void setFloor(final Player requester, final Plot plot, final Material material[], final byte data[]) { public static void setFloor(final Player requester, final Plot plot, final Material material[], final byte data[]) {
final PlotWorld plotworld = PlotMain.getWorldSettings(Bukkit.getWorld(plot.world)); final PlotWorld plotworld = PlotMain.getWorldSettings(Bukkit.getWorld(plot.world));
if(runners.containsKey(plot)) { if (runners.containsKey(plot)) {
PlayerFunctions.sendMessage(requester, C.WAIT_FOR_TIMER); PlayerFunctions.sendMessage(requester, C.WAIT_FOR_TIMER);
return; return;
} }
@ -393,37 +408,38 @@ public class PlotHelper {
PlayerFunctions.sendMessage(requester, send); PlayerFunctions.sendMessage(requester, send);
runners.put(plot, Bukkit.getScheduler().scheduleSyncRepeatingTask(PlotMain.getMain(), new Runnable() { runners.put(plot, Bukkit.getScheduler().scheduleSyncRepeatingTask(PlotMain.getMain(), new Runnable() {
World world = Bukkit.getWorld(plot.world); World world = Bukkit.getWorld(plot.world);
int x1 = getPlotBottomLoc(world, plot.id).getBlockX(); int x1 = getPlotBottomLoc(this.world, plot.id).getBlockX();
int x2 = x1 + plotworld.PLOT_WIDTH; int x2 = this.x1 + plotworld.PLOT_WIDTH;
int z1 = getPlotBottomLoc(world, plot.id).getBlockZ(); int z1 = getPlotBottomLoc(this.world, plot.id).getBlockZ();
int z2 = z1 + plotworld.PLOT_WIDTH; int z2 = this.z1 + plotworld.PLOT_WIDTH;
int xMin = Math.min(x1, x2) + 1; int xMin = Math.min(this.x1, this.x2) + 1;
int xMax = Math.max(x1, x2); int xMax = Math.max(this.x1, this.x2);
int zMin = Math.min(z1, z2) + 1; int zMin = Math.min(this.z1, this.z2) + 1;
int zMax = Math.max(z1, z2); int zMax = Math.max(this.z1, this.z2);
Random random = new Random(); Random random = new Random();
int x = xMin; int x = this.xMin;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@Override @Override
public void run() { public void run() {
for(int z = zMin; z <= zMax; z++) { for (int z = this.zMin; z <= this.zMax; z++) {
int y = plotworld.PLOT_HEIGHT; int y = plotworld.PLOT_HEIGHT;
byte d; byte d;
short id; short id;
if(material.length > 1) { if (material.length > 1) {
int index = random.nextInt(material.length); int index = this.random.nextInt(material.length);
d = data[index]; d = data[index];
id = (short) material[index].getId(); id = (short) material[index].getId();
} else { } else {
d = data[0]; d = data[0];
id = (short)material[0].getId(); id = (short) material[0].getId();
} }
world.getBlockAt(x, y, z).setTypeIdAndData(id,d, true); this.world.getBlockAt(this.x, y, z).setTypeIdAndData(id, d, true);
} }
x++; this.x++;
if(x > xMax) { if (this.x > this.xMax) {
int runner = runners.get(plot); int runner = runners.get(plot);
runners.remove(plot); runners.remove(plot);
PlayerFunctions.sendMessage(requester, C.SET_BLOCK_ACTION_FINISHED); PlayerFunctions.sendMessage(requester, C.SET_BLOCK_ACTION_FINISHED);
@ -431,10 +447,9 @@ public class PlotHelper {
} }
} }
},0l, 10l)); }, 0l, 10l));
} }
public static int square(int x) { public static int square(int x) {
return x * x; return x * x;
} }
@ -443,12 +458,13 @@ public class PlotHelper {
PlotWorld plotworld = PlotMain.getWorldSettings(world); PlotWorld plotworld = PlotMain.getWorldSettings(world);
return (square(plotworld.PLOT_WIDTH)) * (world.getMaxHeight()); return (square(plotworld.PLOT_WIDTH)) * (world.getMaxHeight());
} }
public static Short[] getBlock(String block) { public static 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 };
} }
public static void clear(final Player requester, final Plot plot) { public static void clear(final Player requester, final Plot plot) {
@ -458,7 +474,7 @@ public class PlotHelper {
PlotHelper.removeSign(requester, plot); PlotHelper.removeSign(requester, plot);
PlayerFunctions.sendMessage(requester, C.CLEARING_PLOT); PlayerFunctions.sendMessage(requester, C.CLEARING_PLOT);
final World world = requester.getWorld(); final World world = requester.getWorld();
final Location pos1 = getPlotBottomLoc(world, plot.id).add(1,0,1); final Location pos1 = getPlotBottomLoc(world, plot.id).add(1, 0, 1);
final Location pos2 = getPlotTopLoc(world, plot.id); final Location pos2 = getPlotTopLoc(world, plot.id);
final short[] plotfloors = new short[plotworld.TOP_BLOCK.length]; final short[] plotfloors = new short[plotworld.TOP_BLOCK.length];
@ -478,44 +494,185 @@ public class PlotHelper {
filling_data[i] = result[1]; filling_data[i] = result[1];
} }
final int prime = 31;
int h = 1;
h = (prime * h) + pos1.getBlockX();
h = (prime * h) + pos1.getBlockZ();
state = h;
boolean canSetFast;
try { try {
final int prime = 31; new SetBlockFast();
int h = 1; canSetFast = true;
h = prime * h + pos1.getBlockX(); } catch (Exception e) {
h = prime * h + pos1.getBlockZ(); canSetFast = false;
state = h; }
if (canSetFast) {
PlotMain.getMain().getServer().getScheduler().runTaskAsynchronously(PlotMain.getMain(), (new Runnable() { PlotMain.getMain().getServer().getScheduler().runTaskAsynchronously(PlotMain.getMain(), (new Runnable() {
@Override @Override
public void run() { public void run() {
for (int y = 0; y<plotworld.PLOT_HEIGHT; y++) { try {
for (int x = pos1.getBlockX(); x<=pos2.getBlockX(); x++) { for (int y = 0; y < 1; y++) {
for(int z = pos1.getBlockZ(); z <= pos2.getBlockZ(); z++) { for (int x = pos1.getBlockX(); x <= pos2.getBlockX(); x++) {
int i = random(filling.length); for (int z = pos1.getBlockZ(); z <= pos2.getBlockZ(); z++) {
short id = filling[i]; SetBlockFast.set(world, x, y, z, 7, (byte) 0);
byte d = (byte) filling_data[i]; }
SetBlockFast.set(world, x, y, z, id, d);
} }
} }
} for (int y = 1; y < plotworld.PLOT_HEIGHT; y++) {
for (int y = plotworld.PLOT_HEIGHT; y<plotworld.PLOT_HEIGHT+1; y++) { for (int x = pos1.getBlockX(); x <= pos2.getBlockX(); x++) {
for (int x = pos1.getBlockX(); x<=pos2.getBlockX(); x++) { for (int z = pos1.getBlockZ(); z <= pos2.getBlockZ(); z++) {
for(int z = pos1.getBlockZ(); z <= pos2.getBlockZ(); z++) { int i = random(filling.length);
int i = random(plotfloors.length); short id = filling[i];
short id = plotfloors[i]; byte d = (byte) filling_data[i];
byte d = (byte) plotfloors_data[i]; SetBlockFast.set(world, x, y, z, id, d);
SetBlockFast.set(world, x, y, z, id, d); }
} }
} }
for (int y = plotworld.PLOT_HEIGHT; y < (plotworld.PLOT_HEIGHT + 1); y++) {
for (int x = pos1.getBlockX(); x <= pos2.getBlockX(); x++) {
for (int z = pos1.getBlockZ(); z <= pos2.getBlockZ(); z++) {
int i = random(plotfloors.length);
short id = plotfloors[i];
byte d = (byte) plotfloors_data[i];
SetBlockFast.set(world, x, y, z, id, d);
}
}
}
for (int y = plotworld.PLOT_HEIGHT + 1; y < (world.getMaxHeight() + 1); y++) {
for (int x = pos1.getBlockX(); x <= pos2.getBlockX(); x++) {
for (int z = pos1.getBlockZ(); z <= pos2.getBlockZ(); z++) {
SetBlockFast.set(world, x, y, z, 0, (byte) 0);
}
}
}
PlayerFunctions.sendMessage(requester, C.CLEARING_DONE.s().replaceAll("%time%", "" + ((System.nanoTime() - start) / 1000000.0)));
SetBlockFast.update(requester);
return;
} catch (Exception e) {
PlayerFunctions.sendMessage(requester, C.PREFIX.s() + "&cPlot clear failed... Trying again...");
} }
PlayerFunctions.sendMessage(requester, C.CLEARING_DONE.s().replaceAll("%time%", ""+((System.nanoTime()-start)/1000000.0)));
SetBlockFast.update(requester);
} }
})); }));
}
if ((pos2.getBlockX() - pos1.getBlockX()) < 16) {
setSimpleCuboid(world, new Location(world, pos1.getBlockX(), 0, pos1.getBlockZ()), new Location(world, pos2.getBlockX(), 1, pos2.getBlockZ()), (short) 7);
setSimpleCuboid(world, new Location(world, pos1.getBlockX(), plotworld.PLOT_HEIGHT, pos1.getBlockZ()), new Location(world, pos2.getBlockX(), world.getMaxHeight(), pos2.getBlockZ()), (short) 0);
setCuboid(world, new Location(world, pos1.getBlockX(), 1, pos1.getBlockZ()), new Location(world, pos2.getBlockX(), plotworld.PLOT_HEIGHT, pos2.getBlockZ()), filling, filling_data);
setCuboid(world, new Location(world, pos1.getBlockX(), plotworld.PLOT_HEIGHT, pos1.getBlockZ()), new Location(world, pos2.getBlockX(), plotworld.PLOT_HEIGHT + 1, pos2.getBlockZ()), plotfloors, plotfloors_data);
PlayerFunctions.sendMessage(requester, "&c(depreciated) &r" + C.CLEARING_DONE.s().replaceAll("%time%", "" + ((System.nanoTime() - start) / 1000000.0)));
return; return;
} }
catch (NoClassDefFoundError e) { int startX = (pos1.getBlockX() / 16) * 16;
PlayerFunctions.sendMessage(requester, C.PREFIX.s() + "&cFast plot clearing is currently not enabled."); int startZ = (pos1.getBlockZ() / 16) * 16;
int chunkX = 16 + pos2.getBlockX();
int chunkZ = 16 + pos2.getBlockZ();
int plotMinX = getPlotBottomLoc(world, plot.id).getBlockX() + 1;
int plotMinZ = getPlotBottomLoc(world, plot.id).getBlockZ() + 1;
int plotMaxX = getPlotTopLoc(world, plot.id).getBlockX();
int plotMaxZ = getPlotTopLoc(world, plot.id).getBlockZ();
Location min = null;
Location max = null;
for (int i = startX; i < chunkX; i += 16) {
for (int j = startZ; j < chunkZ; j += 16) {
Plot plot1 = getCurrentPlot(new Location(world, i, 0, j));
if ((plot1 != null) && (plot1.getId() != plot.getId()) && plot1.hasOwner()) {
break;
}
Plot plot2 = getCurrentPlot(new Location(world, i + 15, 0, j));
if ((plot2 != null) && (plot2.getId() != plot.getId()) && plot2.hasOwner()) {
break;
}
Plot plot3 = getCurrentPlot(new Location(world, i + 15, 0, j + 15));
if ((plot3 != null) && (plot3.getId() != plot.getId()) && plot3.hasOwner()) {
break;
}
Plot plot4 = getCurrentPlot(new Location(world, i, 0, j + 15));
if ((plot4 != null) && (plot4.getId() != plot.getId()) && plot4.hasOwner()) {
break;
}
Plot plot5 = getCurrentPlot(new Location(world, i + 15, 0, j + 15));
if ((plot5 != null) && (plot5.getId() != plot.getId()) && plot5.hasOwner()) {
break;
}
if (min == null) {
min = new Location(world, Math.max(i - 1, plotMinX), 0, Math.max(j - 1, plotMinZ));
max = new Location(world, Math.min(i + 16, plotMaxX), 0, Math.min(j + 16, plotMaxZ));
} else if ((max.getBlockZ() < (j + 15)) || (max.getBlockX() < (i + 15))) {
max = new Location(world, Math.min(i + 16, plotMaxX), 0, Math.min(j + 16, plotMaxZ));
}
world.regenerateChunk(i / 16, j / 16);
}
}
if (min == null) {
setSimpleCuboid(world, new Location(world, pos1.getBlockX(), 0, pos1.getBlockZ()), new Location(world, pos2.getBlockX(), 1, pos2.getBlockZ()), (short) 7);
setSimpleCuboid(world, new Location(world, pos1.getBlockX(), plotworld.PLOT_HEIGHT, pos1.getBlockZ()), new Location(world, pos2.getBlockX(), world.getMaxHeight(), pos2.getBlockZ()), (short) 0);
setCuboid(world, new Location(world, pos1.getBlockX(), 1, pos1.getBlockZ()), new Location(world, pos2.getBlockX(), plotworld.PLOT_HEIGHT, pos2.getBlockZ()), filling, filling_data);
setCuboid(world, new Location(world, pos1.getBlockX(), plotworld.PLOT_HEIGHT, pos1.getBlockZ()), new Location(world, pos2.getBlockX(), plotworld.PLOT_HEIGHT + 1, pos2.getBlockZ()), plotfloors, plotfloors_data);
} else {
setSimpleCuboid(world, new Location(world, plotMinX, 0, plotMinZ), new Location(world, min.getBlockX(), 1, min.getBlockZ()), (short) 7);
setSimpleCuboid(world, new Location(world, plotMinX, plotworld.PLOT_HEIGHT + 1, plotMinZ), new Location(world, min.getBlockX(), world.getMaxHeight(), min.getBlockZ()), (short) 0);
setCuboid(world, new Location(world, plotMinX, 1, plotMinZ), new Location(world, min.getBlockX(), plotworld.PLOT_HEIGHT, min.getBlockZ()), filling, filling_data);
setCuboid(world, new Location(world, plotMinX, plotworld.PLOT_HEIGHT, plotMinZ), new Location(world, min.getBlockX(), plotworld.PLOT_HEIGHT + 1, min.getBlockZ()), plotfloors, plotfloors_data);
setSimpleCuboid(world, new Location(world, min.getBlockX(), 0, plotMinZ), new Location(world, max.getBlockX(), 1, min.getBlockZ()), (short) 7);
setSimpleCuboid(world, new Location(world, min.getBlockX(), plotworld.PLOT_HEIGHT + 1, plotMinZ), new Location(world, max.getBlockX(), world.getMaxHeight(), min.getBlockZ()), (short) 0);
setCuboid(world, new Location(world, min.getBlockX(), 1, plotMinZ), new Location(world, max.getBlockX(), plotworld.PLOT_HEIGHT, min.getBlockZ()), filling, filling_data);
setCuboid(world, new Location(world, min.getBlockX(), plotworld.PLOT_HEIGHT, plotMinZ), new Location(world, max.getBlockX(), plotworld.PLOT_HEIGHT + 1, min.getBlockZ()), plotfloors, plotfloors_data);
setSimpleCuboid(world, new Location(world, max.getBlockX(), 0, plotMinZ), new Location(world, plotMaxX, 1, min.getBlockZ()), (short) 7);
setSimpleCuboid(world, new Location(world, max.getBlockX(), plotworld.PLOT_HEIGHT + 1, plotMinZ), new Location(world, plotMaxX, world.getMaxHeight(), min.getBlockZ()), (short) 0);
setCuboid(world, new Location(world, max.getBlockX(), 1, plotMinZ), new Location(world, plotMaxX, plotworld.PLOT_HEIGHT, min.getBlockZ()), filling, filling_data);
setCuboid(world, new Location(world, max.getBlockX(), plotworld.PLOT_HEIGHT, plotMinZ), new Location(world, plotMaxX, plotworld.PLOT_HEIGHT + 1, min.getBlockZ()), plotfloors, plotfloors_data);
setSimpleCuboid(world, new Location(world, plotMinX, 0, min.getBlockZ()), new Location(world, min.getBlockX(), 1, max.getBlockZ()), (short) 7);
setSimpleCuboid(world, new Location(world, plotMinX, plotworld.PLOT_HEIGHT + 1, min.getBlockZ()), new Location(world, min.getBlockX(), world.getMaxHeight(), max.getBlockZ()), (short) 0);
setCuboid(world, new Location(world, plotMinX, 1, min.getBlockZ()), new Location(world, min.getBlockX(), plotworld.PLOT_HEIGHT, max.getBlockZ()), filling, filling_data);
setCuboid(world, new Location(world, plotMinX, plotworld.PLOT_HEIGHT, min.getBlockZ()), new Location(world, min.getBlockX(), plotworld.PLOT_HEIGHT + 1, max.getBlockZ()), plotfloors, plotfloors_data);
setSimpleCuboid(world, new Location(world, plotMinX, 0, max.getBlockZ()), new Location(world, min.getBlockX(), 1, plotMaxZ), (short) 7);
setSimpleCuboid(world, new Location(world, plotMinX, plotworld.PLOT_HEIGHT + 1, max.getBlockZ()), new Location(world, min.getBlockX(), world.getMaxHeight(), plotMaxZ), (short) 0);
setCuboid(world, new Location(world, plotMinX, 1, max.getBlockZ()), new Location(world, min.getBlockX(), plotworld.PLOT_HEIGHT, plotMaxZ), filling, filling_data);
setCuboid(world, new Location(world, plotMinX, plotworld.PLOT_HEIGHT, max.getBlockZ()), new Location(world, min.getBlockX(), plotworld.PLOT_HEIGHT + 1, plotMaxZ), plotfloors, plotfloors_data);
setSimpleCuboid(world, new Location(world, min.getBlockX(), 0, max.getBlockZ()), new Location(world, max.getBlockX(), 1, plotMaxZ), (short) 7);
setSimpleCuboid(world, new Location(world, min.getBlockX(), plotworld.PLOT_HEIGHT + 1, max.getBlockZ()), new Location(world, max.getBlockX(), world.getMaxHeight(), plotMaxZ), (short) 0);
setCuboid(world, new Location(world, min.getBlockX(), 1, max.getBlockZ()), new Location(world, max.getBlockX(), plotworld.PLOT_HEIGHT, plotMaxZ), filling, filling_data);
setCuboid(world, new Location(world, min.getBlockX(), plotworld.PLOT_HEIGHT, max.getBlockZ()), new Location(world, max.getBlockX(), plotworld.PLOT_HEIGHT + 1, plotMaxZ), plotfloors, plotfloors_data);
setSimpleCuboid(world, new Location(world, max.getBlockX(), 0, min.getBlockZ()), new Location(world, plotMaxX, 1, max.getBlockZ()), (short) 7);
setSimpleCuboid(world, new Location(world, max.getBlockX(), plotworld.PLOT_HEIGHT + 1, max.getBlockZ()), new Location(world, plotMaxX, world.getMaxHeight(), plotMaxZ), (short) 0);
setCuboid(world, new Location(world, max.getBlockX(), 1, min.getBlockZ()), new Location(world, plotMaxX, plotworld.PLOT_HEIGHT, max.getBlockZ()), filling, filling_data);
setCuboid(world, new Location(world, max.getBlockX(), plotworld.PLOT_HEIGHT, min.getBlockZ()), new Location(world, plotMaxX, plotworld.PLOT_HEIGHT + 1, max.getBlockZ()), plotfloors, plotfloors_data);
setSimpleCuboid(world, new Location(world, max.getBlockX(), 0, max.getBlockZ()), new Location(world, plotMaxX, 1, plotMaxZ), (short) 7);
setSimpleCuboid(world, new Location(world, max.getBlockX(), plotworld.PLOT_HEIGHT + 1, max.getBlockZ()), new Location(world, plotMaxX, world.getMaxHeight(), plotMaxZ), (short) 0);
setCuboid(world, new Location(world, max.getBlockX(), 1, max.getBlockZ()), new Location(world, plotMaxX, plotworld.PLOT_HEIGHT, plotMaxZ), filling, filling_data);
setCuboid(world, new Location(world, max.getBlockX(), plotworld.PLOT_HEIGHT, max.getBlockZ()), new Location(world, plotMaxX, plotworld.PLOT_HEIGHT + 1, plotMaxZ), plotfloors, plotfloors_data);
}
PlayerFunctions.sendMessage(requester, "&c(depreciated) &r" + C.CLEARING_DONE.s().replaceAll("%time%", "" + ((System.nanoTime() - start) / 1000000.0)));
return;
}
public static void setCuboid(World world, Location pos1, Location pos2, short[] id_l, short[] d_l) {
for (int y = pos1.getBlockY(); y < pos2.getBlockY(); y++) {
for (int x = pos1.getBlockX(); x < pos2.getBlockX(); x++) {
for (int z = pos1.getBlockZ(); z < pos2.getBlockZ(); z++) {
int i = random(id_l.length);
short id = id_l[i];
byte d = (byte) d_l[i];
Block block = world.getBlockAt(x, y, z);
if (!((block.getTypeId() == id) && (block.getData() == d))) {
block.setTypeIdAndData(id, d, false);
}
}
}
}
}
public static void setSimpleCuboid(World world, Location pos1, Location pos2, short id) {
for (int y = pos1.getBlockY(); y < pos2.getBlockY(); y++) {
for (int x = pos1.getBlockX(); x < pos2.getBlockX(); x++) {
for (int z = pos1.getBlockZ(); z < pos2.getBlockZ(); z++) {
Block block = world.getBlockAt(x, y, z);
if (!((block.getTypeId() == id))) {
block.setTypeId(id, false);
}
}
}
} }
} }
@ -538,10 +695,8 @@ public class PlotHelper {
public static Location getPlotHome(World w, Plot plot) { public static Location getPlotHome(World w, Plot plot) {
PlotWorld plotworld = PlotMain.getWorldSettings(w); PlotWorld plotworld = PlotMain.getWorldSettings(w);
if(plot.settings.getPosition() == PlotHomePosition.DEFAULT) { if (plot.settings.getPosition() == PlotHomePosition.DEFAULT) {
int x = getPlotBottomLoc(w, plot.id).getBlockX() int x = getPlotBottomLoc(w, plot.id).getBlockX() + (getPlotTopLoc(w, plot.id).getBlockX() - getPlotBottomLoc(w, plot.id).getBlockX());
+ (getPlotTopLoc(w, plot.id).getBlockX() - getPlotBottomLoc(w,
plot.id).getBlockX());
int z = getPlotBottomLoc(w, plot.id).getBlockZ() - 2; int z = getPlotBottomLoc(w, plot.id).getBlockZ() - 2;
return new Location(w, x, plotworld.ROAD_HEIGHT + 2, z); return new Location(w, x, plotworld.ROAD_HEIGHT + 2, z);
} else { } else {
@ -552,10 +707,10 @@ public class PlotHelper {
int z2 = z1 + plotworld.PLOT_WIDTH; int z2 = z1 + plotworld.PLOT_WIDTH;
int xMin = Math.min(x1, x2) + 1; int xMin = Math.min(x1, x2) + 1;
// int xMax = Math.max(x1, x2); // int xMax = Math.max(x1, x2);
int zMin = Math.min(z1, z2) + 1; int zMin = Math.min(z1, z2) + 1;
// int zMax = Math.max(z1, z2); // int zMax = Math.max(z1, z2);
double adder = (plotworld.PLOT_WIDTH / 2); double adder = (plotworld.PLOT_WIDTH / 2);
double x = (xMin + adder), y = plotworld.ROAD_HEIGHT + 3, z = (zMin + adder); double x = (xMin + adder), y = plotworld.ROAD_HEIGHT + 3, z = (zMin + adder);
@ -565,10 +720,8 @@ public class PlotHelper {
public static Location getPlotHome(World w, PlotId id) { public static Location getPlotHome(World w, PlotId id) {
PlotWorld plotworld = PlotMain.getWorldSettings(w); PlotWorld plotworld = PlotMain.getWorldSettings(w);
if(getPlot(w,id).settings.getPosition() == PlotHomePosition.DEFAULT) { if (getPlot(w, id).settings.getPosition() == PlotHomePosition.DEFAULT) {
int x = getPlotBottomLoc(w, id).getBlockX() int x = getPlotBottomLoc(w, id).getBlockX() + (getPlotTopLoc(w, id).getBlockX() - getPlotBottomLoc(w, id).getBlockX());
+ (getPlotTopLoc(w, id).getBlockX() - getPlotBottomLoc(w, id)
.getBlockX());
int z = getPlotBottomLoc(w, id).getBlockZ() - 2; int z = getPlotBottomLoc(w, id).getBlockZ() - 2;
return new Location(w, x, plotworld.ROAD_HEIGHT + 2, z); return new Location(w, x, plotworld.ROAD_HEIGHT + 2, z);
} else { } else {
@ -579,10 +732,10 @@ public class PlotHelper {
int z2 = z1 + plotworld.PLOT_WIDTH; int z2 = z1 + plotworld.PLOT_WIDTH;
int xMin = Math.min(x1, x2) + 1; int xMin = Math.min(x1, x2) + 1;
int xMax = Math.max(x1, x2); Math.max(x1, x2);
int zMin = Math.min(z1, z2) + 1; int zMin = Math.min(z1, z2) + 1;
int zMax = Math.max(z1, z2); Math.max(z1, z2);
double adder = (plotworld.PLOT_WIDTH / 2); double adder = (plotworld.PLOT_WIDTH / 2);
double x = (xMin + adder), y = plotworld.ROAD_HEIGHT + 3, z = (zMin + adder); double x = (xMin + adder), y = plotworld.ROAD_HEIGHT + 3, z = (zMin + adder);
@ -613,10 +766,8 @@ public class PlotHelper {
int px = id.x; int px = id.x;
int pz = id.y; int pz = id.y;
int x = px * (plotworld.ROAD_WIDTH + plotworld.PLOT_WIDTH) int x = (px * (plotworld.ROAD_WIDTH + plotworld.PLOT_WIDTH)) - ((int) Math.floor(plotworld.ROAD_WIDTH / 2)) - 1;
- ((int) Math.floor(plotworld.ROAD_WIDTH / 2)) - 1; int z = (pz * (plotworld.ROAD_WIDTH + plotworld.PLOT_WIDTH)) - ((int) Math.floor(plotworld.ROAD_WIDTH / 2)) - 1;
int z = pz * (plotworld.ROAD_WIDTH + plotworld.PLOT_WIDTH)
- ((int) Math.floor(plotworld.ROAD_WIDTH / 2)) - 1;
return new Location(world, x, 255, z); return new Location(world, x, 255, z);
} }
@ -626,10 +777,8 @@ public class PlotHelper {
int px = id.x; int px = id.x;
int pz = id.y; int pz = id.y;
int x = px * (plotworld.ROAD_WIDTH + plotworld.PLOT_WIDTH) - plotworld.PLOT_WIDTH int x = (px * (plotworld.ROAD_WIDTH + plotworld.PLOT_WIDTH)) - plotworld.PLOT_WIDTH - ((int) Math.floor(plotworld.ROAD_WIDTH / 2)) - 1;
- ((int) Math.floor(plotworld.ROAD_WIDTH / 2)) - 1; int z = (pz * (plotworld.ROAD_WIDTH + plotworld.PLOT_WIDTH)) - plotworld.PLOT_WIDTH - ((int) Math.floor(plotworld.ROAD_WIDTH / 2)) - 1;
int z = pz * (plotworld.ROAD_WIDTH + plotworld.PLOT_WIDTH) - plotworld.PLOT_WIDTH
- ((int) Math.floor(plotworld.ROAD_WIDTH / 2)) - 1;
return new Location(world, x, 1, z); return new Location(world, x, 1, z);
} }
@ -645,13 +794,13 @@ public class PlotHelper {
} }
public static Plot getCurrentPlot(Location loc) { public static Plot getCurrentPlot(Location loc) {
/* /*
* Vector vector = player.getLocation().toVector(); for(plot plot : * Vector vector = player.getLocation().toVector(); for(plot plot :
* getPlots()) if(vector.isInAABB(plot.l1.toVector(), * getPlots()) if(vector.isInAABB(plot.l1.toVector(),
* plot.l2.toVector())) return plot; return null; * plot.l2.toVector())) return plot; return null;
*/ */
PlotId id = PlayerFunctions.getPlot(loc); PlotId id = PlayerFunctions.getPlot(loc);
if (id.equals("...") || id.equals("road")) { if (id == null) {
return null; return null;
} }
if (PlotMain.getPlots(loc.getWorld()).containsKey(id)) { if (PlotMain.getPlots(loc.getWorld()).containsKey(id)) {
@ -666,10 +815,8 @@ public class PlotHelper {
byte blockData = 0; byte blockData = 0;
if (currentBlockId.contains(":")) { if (currentBlockId.contains(":")) {
try { try {
blockId = Integer.parseInt(currentBlockId.substring(0, blockId = Integer.parseInt(currentBlockId.substring(0, currentBlockId.indexOf(":")));
currentBlockId.indexOf(":"))); blockData = Byte.parseByte(currentBlockId.substring(currentBlockId.indexOf(":") + 1));
blockData = Byte.parseByte(currentBlockId
.substring(currentBlockId.indexOf(":") + 1));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
blockId = 1; blockId = 1;
blockData = (byte) 0; blockData = (byte) 0;

View File

@ -13,20 +13,23 @@ 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'), CENTER("Center", 'c'), DEFAULT("Default", 'd');
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) return true; if ((string.length() < 2) && (string.charAt(0) == this.ch)) {
if(string.equalsIgnoreCase(this.string)) return true; return true;
}
if (string.equalsIgnoreCase(this.string)) {
return true;
}
return false; return false;
} }

View File

@ -1,31 +1,35 @@
package com.intellectualcrafters.plot; package com.intellectualcrafters.plot;
import java.util.Arrays;
public class PlotId { public class PlotId {
public int x; public int x;
public int y; public int y;
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 int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result + x; result = (prime * result) + this.x;
result = prime * result + y; result = (prime * result) + this.y;
return result; return result;
} }
} }

View File

@ -9,6 +9,124 @@
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.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import me.confuser.barapi.BarAPI;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Tameable;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.plugin.java.JavaPlugin;
import ca.mera.CameraAPI; import ca.mera.CameraAPI;
import com.intellectualcrafters.plot.Logger.LogLevel; import com.intellectualcrafters.plot.Logger.LogLevel;
@ -25,34 +143,8 @@ import com.intellectualcrafters.plot.listeners.PlayerEvents;
import com.intellectualcrafters.plot.listeners.WorldEditListener; import com.intellectualcrafters.plot.listeners.WorldEditListener;
import com.sk89q.worldedit.bukkit.WorldEditPlugin; import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import me.confuser.barapi.BarAPI;
import org.bukkit.*;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Tameable;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.Vector;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.Map.Entry;
import static org.bukkit.Material.*;
/** /**
* @awesome @author Citymonstret, Empire92 * @awesome @author Citymonstret, Empire92 PlotMain class.
* PlotMain class.
*/ */
public class PlotMain extends JavaPlugin { public class PlotMain extends JavaPlugin {
@ -110,17 +202,16 @@ public class PlotMain extends JavaPlugin {
/** /**
* TODO: Implement better system * TODO: Implement better system
* *
*/ */
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public static void checkForExpiredPlots() { public static void checkForExpiredPlots() {
final JavaPlugin plugin = PlotMain.getMain(); final JavaPlugin plugin = PlotMain.getMain();
Bukkit.getScheduler().scheduleAsyncRepeatingTask(plugin, Bukkit.getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable() {
new Runnable() { @Override
@Override public void run() {
public void run() { checkExpired(plugin, true);
checkExpired(plugin, true); }
} }, 0l, 12 * 60 * 60 * 20l);
}, 0l, 12 * 60 * 60 * 20l);
} }
/** /**
@ -137,9 +228,10 @@ public class PlotMain extends JavaPlugin {
} }
public static boolean isRegisteredFlag(String arg) { public static boolean isRegisteredFlag(String arg) {
for (Flag flag:registeredFlags) { for (Flag flag : registeredFlags) {
if (flag.getKey().equalsIgnoreCase(arg)) if (flag.getKey().equalsIgnoreCase(arg)) {
return true; return true;
}
} }
return false; return false;
} }
@ -159,11 +251,12 @@ public class PlotMain extends JavaPlugin {
*/ */
public static Set<Plot> getPlots() { public static Set<Plot> getPlots() {
ArrayList<Plot> myplots = new ArrayList<Plot>(); ArrayList<Plot> myplots = new ArrayList<Plot>();
for (HashMap<PlotId, Plot> world:plots.values()) { for (HashMap<PlotId, Plot> world : plots.values()) {
myplots.addAll(world.values()); myplots.addAll(world.values());
} }
return new HashSet<Plot>(myplots); return new HashSet<Plot>(myplots);
} }
/** /**
* *
* @param player * @param player
@ -172,8 +265,8 @@ public class PlotMain extends JavaPlugin {
public static Set<Plot> getPlots(Player player) { public static Set<Plot> getPlots(Player player) {
UUID uuid = player.getUniqueId(); UUID uuid = player.getUniqueId();
ArrayList<Plot> myplots = new ArrayList<Plot>(); ArrayList<Plot> myplots = new ArrayList<Plot>();
for (HashMap<PlotId, Plot> world:plots.values()) { for (HashMap<PlotId, Plot> world : plots.values()) {
for (Plot plot:world.values()) { for (Plot plot : world.values()) {
if (plot.hasOwner()) { if (plot.hasOwner()) {
if (plot.getOwner().equals(uuid)) { if (plot.getOwner().equals(uuid)) {
myplots.add(plot); myplots.add(plot);
@ -183,6 +276,7 @@ public class PlotMain extends JavaPlugin {
} }
return new HashSet<Plot>(myplots); return new HashSet<Plot>(myplots);
} }
/** /**
* *
* @param world * @param world
@ -192,7 +286,7 @@ public class PlotMain extends JavaPlugin {
public static Set<Plot> getPlots(World world, Player player) { public static Set<Plot> getPlots(World world, Player player) {
UUID uuid = player.getUniqueId(); UUID uuid = player.getUniqueId();
ArrayList<Plot> myplots = new ArrayList<Plot>(); ArrayList<Plot> myplots = new ArrayList<Plot>();
for (Plot plot:getPlots(world).values()) { for (Plot plot : getPlots(world).values()) {
if (plot.hasOwner()) { if (plot.hasOwner()) {
if (plot.getOwner().equals(uuid)) { if (plot.getOwner().equals(uuid)) {
myplots.add(plot); myplots.add(plot);
@ -201,6 +295,7 @@ public class PlotMain extends JavaPlugin {
} }
return new HashSet<Plot>(myplots); return new HashSet<Plot>(myplots);
} }
/** /**
* *
* @param world * @param world
@ -212,12 +307,14 @@ public class PlotMain extends JavaPlugin {
} }
return new HashMap<PlotId, Plot>(); return new HashMap<PlotId, Plot>();
} }
/** /**
* get all plot worlds * get all plot worlds
*/ */
public static String[] getPlotWorlds() { public static String[] getPlotWorlds() {
return (worlds.keySet().toArray(new String[0])); return (worlds.keySet().toArray(new String[0]));
} }
/** /**
* *
* @return * @return
@ -225,6 +322,7 @@ public class PlotMain extends JavaPlugin {
public static String[] getPlotWorldsString() { public static String[] getPlotWorldsString() {
return plots.keySet().toArray(new String[0]); return plots.keySet().toArray(new String[0]);
} }
/** /**
* *
* @param world * @param world
@ -233,54 +331,62 @@ public class PlotMain extends JavaPlugin {
public static boolean isPlotWorld(World world) { public static boolean isPlotWorld(World world) {
return (worlds.containsKey(world.getName())); return (worlds.containsKey(world.getName()));
} }
/** /**
* *
* @param world * @param world
* @return * @return
*/ */
public static PlotWorld getWorldSettings(World world) { public static PlotWorld getWorldSettings(World world) {
if (worlds.containsKey(world.getName())) if (worlds.containsKey(world.getName())) {
return worlds.get(world.getName()); return worlds.get(world.getName());
}
return null; return null;
} }
/** /**
* *
* @param world * @param world
* @return * @return
*/ */
public static PlotWorld getWorldSettings(String world) { public static PlotWorld getWorldSettings(String world) {
if (worlds.containsKey(world)) if (worlds.containsKey(world)) {
return worlds.get(world); return worlds.get(world);
}
return null; return null;
} }
/** /**
* *
* @param world * @param world
* @return set containing the plots for a world * @return set containing the plots for a world
*/ */
public static Plot[] getWorldPlots(World world) { public static Plot[] getWorldPlots(World world) {
return (Plot[])(plots.get(world.getName()).values().toArray(new Plot[0])); return (plots.get(world.getName()).values().toArray(new Plot[0]));
} }
public static boolean removePlot(String world, PlotId id) { public static boolean removePlot(String world, PlotId id) {
PlotDeleteEvent event = new PlotDeleteEvent(world,id); PlotDeleteEvent event = new PlotDeleteEvent(world, id);
Bukkit.getServer().getPluginManager().callEvent(event); Bukkit.getServer().getPluginManager().callEvent(event);
if(event.isCancelled()) { if (event.isCancelled()) {
event.setCancelled(true); event.setCancelled(true);
return false; return false;
} }
plots.get(world).remove(id); plots.get(world).remove(id);
return true; return true;
} }
/** /**
* Replace the plot object with an updated version * Replace the plot object with an updated version
* *
* @param plot plot object * @param plot
* plot object
*/ */
public static void updatePlot(Plot plot) { public static void updatePlot(Plot plot) {
String world = plot.world; String world = plot.world;
if (!plots.containsKey(world)) if (!plots.containsKey(world)) {
plots.put(world,new HashMap<PlotId, Plot>()); plots.put(world, new HashMap<PlotId, Plot>());
}
plot.hasChanged = true; plot.hasChanged = true;
plots.get(world).put(plot.id, plot); plots.get(world).put(plot.id, plot);
} }
@ -288,27 +394,28 @@ public class PlotMain extends JavaPlugin {
/** /**
* TODO: Implement better system * TODO: Implement better system
* *
* @param plugin Plugin * @param plugin
* @param async Call async? * Plugin
* @param async
* Call async?
*/ */
private static void checkExpired(JavaPlugin plugin, boolean async) { private static void checkExpired(JavaPlugin plugin, boolean async) {
if (async) { if (async) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override @Override
public void run() { public void run() {
for (String world:getPlotWorldsString()) { for (String world : getPlotWorldsString()) {
if (plots.containsKey(world)) { if (plots.containsKey(world)) {
for (Plot plot : plots.get(world).values()) { for (Plot plot : plots.get(world).values()) {
if (plot.owner == null) { if (plot.owner == null) {
continue; continue;
} }
if (PlayerFunctions.hasExpired(plot)) { if (PlayerFunctions.hasExpired(plot)) {
PlotDeleteEvent event = new PlotDeleteEvent(world,plot.id); PlotDeleteEvent event = new PlotDeleteEvent(world, plot.id);
Bukkit.getServer().getPluginManager().callEvent(event); Bukkit.getServer().getPluginManager().callEvent(event);
if(event.isCancelled()) { if (event.isCancelled()) {
event.setCancelled(true); event.setCancelled(true);
} } else {
else {
DBFunc.delete(world, plot); DBFunc.delete(world, plot);
} }
} }
@ -318,16 +425,15 @@ public class PlotMain extends JavaPlugin {
} }
}); });
} else { } else {
for (String world:getPlotWorldsString()) { for (String world : getPlotWorldsString()) {
if (PlotMain.plots.containsKey(world)) { if (PlotMain.plots.containsKey(world)) {
for (Plot plot : PlotMain.plots.get(world).values()) { for (Plot plot : PlotMain.plots.get(world).values()) {
if (PlayerFunctions.hasExpired(plot)) { if (PlayerFunctions.hasExpired(plot)) {
PlotDeleteEvent event = new PlotDeleteEvent(world,plot.id); PlotDeleteEvent event = new PlotDeleteEvent(world, plot.id);
Bukkit.getServer().getPluginManager().callEvent(event); Bukkit.getServer().getPluginManager().callEvent(event);
if(event.isCancelled()) { if (event.isCancelled()) {
event.setCancelled(true); event.setCancelled(true);
} } else {
else {
DBFunc.delete(world, plot); DBFunc.delete(world, plot);
} }
} }
@ -337,7 +443,6 @@ public class PlotMain extends JavaPlugin {
} }
} }
private void setupLogger() { private void setupLogger() {
File log = new File(getMain().getDataFolder() + File.separator + "logs" + File.separator + "plots.log"); File log = new File(getMain().getDataFolder() + File.separator + "logs" + File.separator + "plots.log");
if (!log.exists()) { if (!log.exists()) {
@ -371,8 +476,8 @@ public class PlotMain extends JavaPlugin {
public void onEnable() { public void onEnable() {
setupLogger(); setupLogger();
//Check for outdated java version. // Check for outdated java version.
if(getJavaVersion() < 1.7) { if (getJavaVersion() < 1.7) {
sendConsoleSenderMessage(C.PREFIX.s() + "&cYour java version is outdated. Please update to at least 1.7."); sendConsoleSenderMessage(C.PREFIX.s() + "&cYour java version is outdated. Please update to at least 1.7.");
sendConsoleSenderMessage(C.PREFIX.s() + "&cURL: &6https://java.com/en/download/index.jsp"); sendConsoleSenderMessage(C.PREFIX.s() + "&cURL: &6https://java.com/en/download/index.jsp");
Bukkit.getPluginManager().disablePlugin(this); Bukkit.getPluginManager().disablePlugin(this);
@ -381,68 +486,36 @@ public class PlotMain extends JavaPlugin {
configs(); configs();
if(Settings.METRICS) { if (Settings.METRICS) {
try { try {
Metrics metrics = new Metrics(this); Metrics metrics = new Metrics(this);
metrics.start(); metrics.start();
sendConsoleSenderMessage(C.PREFIX.s() + "&6Metrics enabled."); sendConsoleSenderMessage(C.PREFIX.s() + "&6Metrics enabled.");
} catch(Exception e) { } catch (Exception e) {
sendConsoleSenderMessage(C.PREFIX.s() + "&cFailed to load up metrics."); sendConsoleSenderMessage(C.PREFIX.s() + "&cFailed to load up metrics.");
} }
} }
// TODO make this configurable // TODO make this configurable
PlotWorld.BLOCKS = new ArrayList<>(Arrays.asList(new Material[]{ PlotWorld.BLOCKS = new ArrayList<>(Arrays.asList(new Material[] { ACACIA_STAIRS, BEACON, BEDROCK, BIRCH_WOOD_STAIRS, BOOKSHELF, BREWING_STAND, BRICK, BRICK_STAIRS, BURNING_FURNACE, CAKE_BLOCK, CAULDRON, CLAY_BRICK, CLAY, COAL_BLOCK, COAL_ORE, COBBLE_WALL, COBBLESTONE, COBBLESTONE_STAIRS, COMMAND, DARK_OAK_STAIRS, DAYLIGHT_DETECTOR, DIAMOND_ORE, DIAMOND_BLOCK, DIRT, DISPENSER, DROPPER, EMERALD_BLOCK, EMERALD_ORE, ENCHANTMENT_TABLE, ENDER_PORTAL_FRAME, ENDER_STONE, FURNACE, GLOWSTONE, GOLD_ORE, GOLD_BLOCK, GRASS, GRAVEL, GLASS, HARD_CLAY, HAY_BLOCK, HUGE_MUSHROOM_1, HUGE_MUSHROOM_2, IRON_BLOCK, IRON_ORE, JACK_O_LANTERN, JUKEBOX, JUNGLE_WOOD_STAIRS, LAPIS_BLOCK, LAPIS_ORE, LEAVES, LEAVES_2, LOG, LOG_2, MELON_BLOCK, MOB_SPAWNER, MOSSY_COBBLESTONE, MYCEL, NETHER_BRICK, NETHER_BRICK_STAIRS, NETHERRACK, NOTE_BLOCK, OBSIDIAN, PACKED_ICE, PUMPKIN, QUARTZ_BLOCK, QUARTZ_ORE, QUARTZ_STAIRS, REDSTONE_BLOCK, SANDSTONE, SAND, SANDSTONE_STAIRS, SMOOTH_BRICK, SMOOTH_STAIRS, SNOW_BLOCK,
ACACIA_STAIRS, BEACON, BEDROCK, SOUL_SAND, SPONGE, SPRUCE_WOOD_STAIRS, STONE, WOOD, WOOD_STAIRS, WORKBENCH, WOOL, getMaterial(44), getMaterial(126) }));
BIRCH_WOOD_STAIRS, BOOKSHELF, if (Settings.KILL_ROAD_MOBS) {
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)}));
if (Settings.KILL_ROAD_MOBS)
killAllEntities(); killAllEntities();
}
if (C.ENABLED.s().length() > 0) { if (C.ENABLED.s().length() > 0) {
Broadcast(C.ENABLED); Broadcast(C.ENABLED);
} }
if (Settings.DB.USE_MYSQL) { if (Settings.DB.USE_MYSQL) {
try { try {
mySQL = new MySQL(this, Settings.DB.HOST_NAME, Settings.DB.PORT, mySQL = new MySQL(this, Settings.DB.HOST_NAME, Settings.DB.PORT, Settings.DB.DATABASE, Settings.DB.USER, Settings.DB.PASSWORD);
Settings.DB.DATABASE, Settings.DB.USER,
Settings.DB.PASSWORD);
connection = mySQL.openConnection(); connection = mySQL.openConnection();
{ {
DatabaseMetaData meta = connection.getMetaData(); DatabaseMetaData meta = connection.getMetaData();
ResultSet res = meta.getTables(null, null, "plot", null); ResultSet res = meta.getTables(null, null, "plot", null);
if(!res.next()) if (!res.next()) {
DBFunc.createTables("mysql"); DBFunc.createTables("mysql");
}
} }
} catch (ClassNotFoundException | SQLException e) { } catch (ClassNotFoundException | SQLException e) {
Logger.add(LogLevel.DANGER, "MySQL connection failed."); Logger.add(LogLevel.DANGER, "MySQL connection failed.");
@ -462,8 +535,9 @@ public class PlotMain extends JavaPlugin {
{ {
DatabaseMetaData meta = connection.getMetaData(); DatabaseMetaData meta = connection.getMetaData();
ResultSet res = meta.getTables(null, null, "plot", null); ResultSet res = meta.getTables(null, null, "plot", null);
if(!res.next()) if (!res.next()) {
DBFunc.createTables("sqlite"); DBFunc.createTables("sqlite");
}
} }
} catch (ClassNotFoundException | SQLException e) { } catch (ClassNotFoundException | SQLException e) {
Logger.add(LogLevel.DANGER, "SQLite connection failed"); Logger.add(LogLevel.DANGER, "SQLite connection failed");
@ -480,25 +554,24 @@ public class PlotMain extends JavaPlugin {
getServer().getPluginManager().disablePlugin(this); getServer().getPluginManager().disablePlugin(this);
return; return;
} }
if (getServer().getPluginManager().getPlugin("PlotMe") != null ) { if (getServer().getPluginManager().getPlugin("PlotMe") != null) {
try { try {
new PlotMeConverter(this).runAsync(); new PlotMeConverter(this).runAsync();
} catch(Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
getCommand("plots").setExecutor(new MainCommand()); getCommand("plots").setExecutor(new MainCommand());
getCommand("plots").setAliases( getCommand("plots").setAliases(new ArrayList<String>() {
new ArrayList<String>() { {
{ add("p");
add("p"); add("plotme");
add("plotme"); add("plot");
add("plot"); }
} });
});
getServer().getPluginManager().registerEvents(new PlayerEvents(), this); getServer().getPluginManager().registerEvents(new PlayerEvents(), this);
if (getServer().getPluginManager().getPlugin("CameraAPI") != null ){ if (getServer().getPluginManager().getPlugin("CameraAPI") != null) {
cameraAPI = CameraAPI.getInstance(); cameraAPI = CameraAPI.getInstance();
Camera camera = new Camera(); Camera camera = new Camera();
MainCommand.subCommands.add(camera); MainCommand.subCommands.add(camera);
@ -508,27 +581,19 @@ public class PlotMain extends JavaPlugin {
barAPI = (BarAPI) getServer().getPluginManager().getPlugin("BarAPI"); barAPI = (BarAPI) getServer().getPluginManager().getPlugin("BarAPI");
} }
if (getServer().getPluginManager().getPlugin("WorldEdit") != null) { if (getServer().getPluginManager().getPlugin("WorldEdit") != null) {
worldEdit = (WorldEditPlugin) getServer().getPluginManager() worldEdit = (WorldEditPlugin) getServer().getPluginManager().getPlugin("WorldEdit");
.getPlugin("WorldEdit"); getServer().getPluginManager().registerEvents(new WorldEditListener(), this);
getServer().getPluginManager().registerEvents(
new WorldEditListener(), this);
} }
checkExpired(PlotMain.getMain(), true); checkExpired(PlotMain.getMain(), true);
checkForExpiredPlots(); checkForExpiredPlots();
getServer().getScheduler().scheduleSyncRepeatingTask(this, new Lag(), getServer().getScheduler().scheduleSyncRepeatingTask(this, new Lag(), 100L, 1L);
100L, 1L);
if(Web.ENABLED) { if (Web.ENABLED) {
sendConsoleSenderMessage(C.PREFIX.s() + "This is not yet implemented..."); sendConsoleSenderMessage(C.PREFIX.s() + "This is not yet implemented...");
} }
} }
private void options(boolean verbose) {
}
/** /**
* Get MySQL Connection * Get MySQL Connection
* *
@ -541,35 +606,32 @@ public class PlotMain extends JavaPlugin {
/** .. */ /** .. */
//Old Stuff // Old Stuff
/*private static boolean checkForUpdate() throws IOException { /*
URL call = new URL(Settings.Update.VERSION_URL); * private static boolean checkForUpdate() throws IOException { URL call =
InputStream stream = call.openStream(); * new URL(Settings.Update.VERSION_URL); InputStream stream =
BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); * call.openStream(); BufferedReader reader = new BufferedReader(new
String latest = reader.readLine(); * InputStreamReader(stream)); String latest = reader.readLine();
reader.close(); * reader.close(); return
return !getPlotMain().getDescription().getVersion().equalsIgnoreCase(latest); * !getPlotMain().getDescription().getVersion().equalsIgnoreCase(latest); }
} * private static String getNextUpdateString() throws IOException { URL call
* = new URL(Settings.Update.VERSION_URL); InputStream stream =
private static String getNextUpdateString() throws IOException { * call.openStream(); BufferedReader reader = new BufferedReader(new
URL call = new URL(Settings.Update.VERSION_URL); * InputStreamReader(stream)); return reader.readLine(); } private static
InputStream stream = call.openStream(); * void update() throws IOException { sendConsoleSenderMessage(C.PREFIX.s()
BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); * + "&c&lThere is an update! New Update: &6&l" + getNextUpdateString() +
return reader.readLine(); * "&c&l, Current Update: &6&l" +
} * getPlotMain().getDescription().getVersion()); }
*/
private static void update() throws IOException {
sendConsoleSenderMessage(C.PREFIX.s() + "&c&lThere is an update! New Update: &6&l" + getNextUpdateString() + "&c&l, Current Update: &6&l" + getPlotMain().getDescription().getVersion());
}
*/
/** /**
* Send a message to the console. * Send a message to the console.
* *
* @param string message * @param string
* message
*/ */
public static void sendConsoleSenderMessage(String string) { public static void sendConsoleSenderMessage(String string) {
if(getMain().getServer().getConsoleSender() == null) { if (getMain().getServer().getConsoleSender() == null) {
System.out.println(ChatColor.stripColor(ConsoleColors.fromString(string))); System.out.println(ChatColor.stripColor(ConsoleColors.fromString(string)));
} else { } else {
getMain().getServer().getConsoleSender().sendMessage(ChatColor.translateAlternateColorCodes('&', string)); getMain().getServer().getConsoleSender().sendMessage(ChatColor.translateAlternateColorCodes('&', string));
@ -579,10 +641,9 @@ public class PlotMain extends JavaPlugin {
public static boolean teleportPlayer(Player player, Location from, Plot plot) { public static boolean teleportPlayer(Player player, Location from, Plot plot) {
PlayerTeleportToPlotEvent event = new PlayerTeleportToPlotEvent(player, from, plot); PlayerTeleportToPlotEvent event = new PlayerTeleportToPlotEvent(player, from, plot);
Bukkit.getServer().getPluginManager().callEvent(event); Bukkit.getServer().getPluginManager().callEvent(event);
if(!event.isCancelled()) { if (!event.isCancelled()) {
Location location = PlotHelper.getPlotHome(Bukkit.getWorld(plot.world), plot); Location location = PlotHelper.getPlotHome(Bukkit.getWorld(plot.world), plot);
if(location.getBlockX() >= 29999999 || location.getBlockX() <= -29999999 || if ((location.getBlockX() >= 29999999) || (location.getBlockX() <= -29999999) || (location.getBlockZ() >= 299999999) || (location.getBlockZ() <= -29999999)) {
location.getBlockZ() >= 299999999 ||location.getBlockZ() <= -29999999) {
event.setCancelled(true); event.setCancelled(true);
return false; return false;
} }
@ -595,7 +656,8 @@ public class PlotMain extends JavaPlugin {
/** /**
* Send a message to the console * Send a message to the console
* *
* @param c message * @param c
* message
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
public static void sendConsoleSenderMessage(C c) { public static void sendConsoleSenderMessage(C c) {
@ -605,11 +667,11 @@ public class PlotMain extends JavaPlugin {
/** /**
* Broadcast publicly * Broadcast publicly
* *
* @param c message * @param c
* message
*/ */
public static void Broadcast(C c) { public static void Broadcast(C c) {
Bukkit.broadcastMessage(ChatColor.translateAlternateColorCodes('&', Bukkit.broadcastMessage(ChatColor.translateAlternateColorCodes('&', C.PREFIX.s() + c.s()));
C.PREFIX.s() + c.s()));
} }
/** /**
@ -624,21 +686,22 @@ public class PlotMain extends JavaPlugin {
/** /**
* Broadcast a message to all admins * Broadcast a message to all admins
* *
* @param c message * @param c
* message
*/ */
public static void BroadcastWithPerms(C c) { public static void BroadcastWithPerms(C c) {
for (Player player : Bukkit.getOnlinePlayers()) { for (Player player : Bukkit.getOnlinePlayers()) {
if (player.hasPermission("plots.admin")) if (player.hasPermission("plots.admin")) {
PlayerFunctions.sendMessage(player, c); PlayerFunctions.sendMessage(player, c);
}
} }
System.out.println(ChatColor.stripColor(ChatColor System.out.println(ChatColor.stripColor(ChatColor.translateAlternateColorCodes('&', C.PREFIX.s() + c.s())));
.translateAlternateColorCodes('&', C.PREFIX.s() + c.s())));
} }
public static void reloadTranslations() throws IOException { public static void reloadTranslations() throws IOException {
translations = YamlConfiguration.loadConfiguration(translationsFile); translations = YamlConfiguration.loadConfiguration(translationsFile);
} }
/** /**
* Load configuration files * Load configuration files
*/ */
@ -649,43 +712,39 @@ public class PlotMain extends JavaPlugin {
sendConsoleSenderMessage(C.PREFIX.s() + "&cFailed to create the /plugins/config folder. Please create it manually."); sendConsoleSenderMessage(C.PREFIX.s() + "&cFailed to create the /plugins/config folder. Please create it manually.");
} }
try { try {
configFile = new File(getMain().getDataFolder() + File.separator + "config" + File.separator +"settings.yml"); configFile = new File(getMain().getDataFolder() + File.separator + "config" + File.separator + "settings.yml");
if (!configFile.exists()) { if (!configFile.exists()) {
configFile.createNewFile(); configFile.createNewFile();
} }
config = YamlConfiguration.loadConfiguration(configFile); config = YamlConfiguration.loadConfiguration(configFile);
setupConfig(); setupConfig();
} } catch (Exception err_trans) {
catch (Exception err_trans) {
Logger.add(LogLevel.DANGER, "Failed to save settings.yml"); Logger.add(LogLevel.DANGER, "Failed to save settings.yml");
System.out.println("Failed to save settings.yml"); System.out.println("Failed to save settings.yml");
} }
try { try {
storageFile = new File(getMain().getDataFolder() + File.separator + "config" + File.separator +"storage.yml"); storageFile = new File(getMain().getDataFolder() + File.separator + "config" + File.separator + "storage.yml");
if (!storageFile.exists()) { if (!storageFile.exists()) {
storageFile.createNewFile(); storageFile.createNewFile();
} }
storage = YamlConfiguration.loadConfiguration(storageFile); storage = YamlConfiguration.loadConfiguration(storageFile);
setupStorage(); setupStorage();
} } catch (Exception err_trans) {
catch (Exception err_trans) {
Logger.add(LogLevel.DANGER, "Failed to save storage.yml"); Logger.add(LogLevel.DANGER, "Failed to save storage.yml");
System.out.println("Failed to save storage.yml"); System.out.println("Failed to save storage.yml");
} }
try { try {
translationsFile = new File(getMain().getDataFolder() + File.separator + "config" + File.separator +"translations.yml"); translationsFile = new File(getMain().getDataFolder() + File.separator + "config" + File.separator + "translations.yml");
if (!translationsFile.exists()) { if (!translationsFile.exists()) {
translationsFile.createNewFile(); translationsFile.createNewFile();
} }
translations = YamlConfiguration.loadConfiguration(translationsFile); translations = YamlConfiguration.loadConfiguration(translationsFile);
setupTranslations(); setupTranslations();
} } catch (Exception err_trans) {
catch (Exception err_trans) {
Logger.add(LogLevel.DANGER, "Failed to save translations.yml"); Logger.add(LogLevel.DANGER, "Failed to save translations.yml");
System.out.println("Failed to save translations.yml"); System.out.println("Failed to save translations.yml");
} }
try { try {
config.save(configFile); config.save(configFile);
storage.save(storageFile); storage.save(storageFile);
@ -706,9 +765,9 @@ public class PlotMain extends JavaPlugin {
} }
{ {
Settings.METRICS = config.getBoolean("metrics"); Settings.METRICS = config.getBoolean("metrics");
//Web // Web
//Web.ENABLED = config.getBoolean("web.enabled"); // Web.ENABLED = config.getBoolean("web.enabled");
//Web.PORT = config.getInt("web.port"); // Web.PORT = config.getInt("web.port");
} }
} }
@ -717,106 +776,104 @@ public class PlotMain extends JavaPlugin {
*/ */
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public static void killAllEntities() { public static void killAllEntities() {
Bukkit.getScheduler().scheduleAsyncRepeatingTask(getMain(), Bukkit.getScheduler().scheduleAsyncRepeatingTask(getMain(), new Runnable() {
new Runnable() { Location location;
World world; long ticked = 0l;
Location location; long error = 0l;
long ticked = 0l; {
long error = 0l; sendConsoleSenderMessage(C.PREFIX.s() + "KillAllEntities started.");
{ }
sendConsoleSenderMessage(C.PREFIX.s() + "KillAllEntities started.");
} @Override
@Override public void run() {
public void run() { if (this.ticked > 36000l) {
if(ticked > 36000l) { this.ticked = 0l;
ticked = 0l; sendConsoleSenderMessage(C.PREFIX.s() + "KillAllEntities has been running for 60 minutes. Errors: " + this.error);
sendConsoleSenderMessage(C.PREFIX.s() + "KillAllEntities has been running for 60 minutes. Errors: " + error); this.error = 0l;
error = 0l; }
for (String w : getPlotWorlds()) {
getWorldSettings(w);
World world = Bukkit.getServer().getWorld(w);
try {
if (world.getLoadedChunks().length < 1) {
continue;
} }
for (String w: getPlotWorlds()) { for (Chunk chunk : world.getLoadedChunks()) {
PlotWorld plotworld = getWorldSettings(w); Entity[] entities = chunk.getEntities();
World world = Bukkit.getServer().getWorld(w); for (int i = entities.length - 1; i >= 0; i--) {
try { Entity entity = entities[i];
if(world.getLoadedChunks().length < 1) { if (entity.getType() == EntityType.PLAYER) {
continue; continue;
} }
for (Chunk chunk : world.getLoadedChunks()) { this.location = entity.getLocation();
Entity[] entities = chunk.getEntities(); if (!PlayerEvents.isInPlot(this.location)) {
for (int i = entities.length-1; i>=0;i--){ boolean tamed = false;
Entity entity = entities[i]; if (Settings.MOB_PATHFINDING) {
if (entity.getType() == EntityType.PLAYER) if (entity instanceof Tameable) {
continue; Tameable tameable = (Tameable) entity;
location = entity.getLocation(); if (tameable.isTamed()) {
if (!PlayerEvents.isInPlot(location)) { tamed = true;
boolean tamed = false;
if (Settings.MOB_PATHFINDING) {
if (entity instanceof Tameable) {
Tameable tameable = (Tameable) entity;
if (tameable.isTamed()) {
tamed = true;
}
}
else if (entity instanceof LivingEntity) {
LivingEntity livingEntity = ((LivingEntity) entity);
if (livingEntity.getCustomName()!=null) {
tamed = true;
}
}
if (tamed) {
boolean found = false;
int radius = 1;
int dir = 0;
int x = location.getBlockX();
int y = location.getBlockY();
int z = location.getBlockZ();
while (!found || radius > PlotWorld.ROAD_WIDTH_DEFAULT) {
Location pos;
switch (dir) {
case 0:
pos = new Location(world, x+radius, y, z);
dir++;
break;
case 1:
pos = new Location(world, x, y, z+radius);
dir++;
break;
case 2:
pos = new Location(world, x-radius, y, z);
dir++;
break;
case 3:
pos = new Location(world, x, y, z-radius);
dir = 0;
radius++;
break;
default:
pos = location;
break;
}
if (PlayerEvents.isInPlot(pos)) {
entity.teleport(pos.add(0.5,0,0.5));
found = true;
break;
}
}
}
} }
if (!tamed) { } else if (entity instanceof LivingEntity) {
entity.remove(); LivingEntity livingEntity = ((LivingEntity) entity);
if (livingEntity.getCustomName() != null) {
tamed = true;
}
}
if (tamed) {
boolean found = false;
int radius = 1;
int dir = 0;
int x = this.location.getBlockX();
int y = this.location.getBlockY();
int z = this.location.getBlockZ();
while (!found || (radius > PlotWorld.ROAD_WIDTH_DEFAULT)) {
Location pos;
switch (dir) {
case 0:
pos = new Location(world, x + radius, y, z);
dir++;
break;
case 1:
pos = new Location(world, x, y, z + radius);
dir++;
break;
case 2:
pos = new Location(world, x - radius, y, z);
dir++;
break;
case 3:
pos = new Location(world, x, y, z - radius);
dir = 0;
radius++;
break;
default:
pos = this.location;
break;
}
if (PlayerEvents.isInPlot(pos)) {
entity.teleport(pos.add(0.5, 0, 0.5));
found = true;
break;
}
} }
} }
} }
if (!tamed) {
entity.remove();
}
} }
} catch (Exception e) {
++error;
}
finally {
++ticked;
} }
} }
} catch (Exception e) {
++this.error;
} finally {
++this.ticked;
} }
}, 0l, 2l); }
}
}, 0l, 2l);
} }
/** /**
@ -825,7 +882,7 @@ public class PlotMain extends JavaPlugin {
private static void setupConfig() { private static void setupConfig() {
config.set("version", config_ver); config.set("version", config_ver);
Map<String, Object> options = new HashMap<String, Object>(); Map<String, Object> options = new HashMap<String, Object>();
//options.put("auto_update", false); // options.put("auto_update", false);
options.put("kill_road_mobs", Settings.KILL_ROAD_MOBS_DEFAULT); options.put("kill_road_mobs", Settings.KILL_ROAD_MOBS_DEFAULT);
options.put("mob_pathfinding", Settings.MOB_PATHFINDING_DEFAULT); options.put("mob_pathfinding", Settings.MOB_PATHFINDING_DEFAULT);
options.put("web.enabled", Web.ENABLED); options.put("web.enabled", Web.ENABLED);
@ -842,15 +899,14 @@ public class PlotMain extends JavaPlugin {
Settings.MOB_PATHFINDING = config.getBoolean("mob_pathfinding"); Settings.MOB_PATHFINDING = config.getBoolean("mob_pathfinding");
Settings.METRICS = config.getBoolean("metrics"); Settings.METRICS = config.getBoolean("metrics");
for (String node:config.getConfigurationSection("worlds").getKeys(false)) { for (String node : config.getConfigurationSection("worlds").getKeys(false)) {
World world = Bukkit.getWorld(node); World world = Bukkit.getWorld(node);
if (world==null) { if (world == null) {
Logger.add(LogLevel.WARNING, "World '"+node+"' in settings.yml does not exist (case sensitive)"); Logger.add(LogLevel.WARNING, "World '" + node + "' in settings.yml does not exist (case sensitive)");
} } else {
else {
ChunkGenerator gen = world.getGenerator(); ChunkGenerator gen = world.getGenerator();
if (gen==null || !gen.toString().equals("PlotSquared")) { if ((gen == null) || !gen.toString().equals("PlotSquared")) {
Logger.add(LogLevel.WARNING, "World '"+node+"' in settings.yml is not using PlotSquared generator"); Logger.add(LogLevel.WARNING, "World '" + node + "' in settings.yml is not using PlotSquared generator");
} }
} }
} }
@ -904,24 +960,21 @@ public class PlotMain extends JavaPlugin {
try { try {
connection.close(); connection.close();
mySQL.closeConnection(); mySQL.closeConnection();
} } catch (NullPointerException | SQLException e) {
catch (NullPointerException | SQLException e) { if (connection != null) {
if (connection!=null) {
Logger.add(LogLevel.DANGER, "Could not close mysql connection"); Logger.add(LogLevel.DANGER, "Could not close mysql connection");
} }
} }
/* /*
if(PlotWeb.PLOTWEB != null) { * if(PlotWeb.PLOTWEB != null) { try { PlotWeb.PLOTWEB.stop(); } catch
try { * (Exception e) { e.printStackTrace(); } }
PlotWeb.PLOTWEB.stop(); */
} catch (Exception e) {
e.printStackTrace();
}
}*/
} }
public static void addPlotWorld(String world,PlotWorld plotworld) {
PlotMain.worlds.put(world,plotworld); public static void addPlotWorld(String world, PlotWorld plotworld) {
if(!plots.containsKey(world)) PlotMain.worlds.put(world, plotworld);
if (!plots.containsKey(world)) {
plots.put(world, new HashMap<PlotId, Plot>()); plots.put(world, new HashMap<PlotId, Plot>());
}
} }
} }

View File

@ -13,26 +13,21 @@ import java.util.Arrays;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.bukkit.block.Biome; import org.bukkit.block.Biome;
/** /**
* plot settings * plot settings
*
* @author Citymonstret * @author Citymonstret
* *
*/ */
public class PlotSettings { public class PlotSettings {
private String alias; private String alias;
/** /**
* plot object * plot biome
*/ */
@SuppressWarnings("unused") private Biome biome;
private Plot plot;
/**
* plot biome
*/
private Biome biome;
/** /**
* plot rain * plot rain
*/ */
@ -41,90 +36,92 @@ public class PlotSettings {
* *
*/ */
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 /**
* @param plot * Constructor
*/ *
public PlotSettings(Plot plot) { * @param plot
this.plot = plot; */
public PlotSettings(Plot plot) {
this.alias = ""; this.alias = "";
} }
/** /**
* *
* @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
*/ */
public Biome getBiome() { @Deprecated
return this.biome; public Biome getBiome() {
} 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;
} }
@ -134,10 +131,12 @@ public class PlotSettings {
*/ */
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) {
flags.remove(hasFlag); this.flags.remove(hasFlag);
}
this.flags.add(flag); this.flags.add(flag);
} }
/** /**
* *
* @param flags * @param flags
@ -145,6 +144,7 @@ public class PlotSettings {
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
@ -152,23 +152,38 @@ public class PlotSettings {
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: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() { return this.position; } public PlotHomePosition getPosition() {
public void setPosition(PlotHomePosition position) { this.position = position; } return this.position;
public String getAlias() { return this.alias; } }
public String getJoinMessage() { return ""; }
public String getLeaveMessage() { return ""; } public void setPosition(PlotHomePosition position) {
this.position = position;
}
public String getAlias() {
return this.alias;
}
public String getJoinMessage() {
return "";
}
public String getLeaveMessage() {
return "";
}
} }

View File

@ -1,29 +1,27 @@
package com.intellectualcrafters.plot; package com.intellectualcrafters.plot;
import org.bukkit.Material;
import java.util.ArrayList; import java.util.ArrayList;
import org.bukkit.Material;
public class PlotWorld { public class PlotWorld {
/* /*
* This is the PlotWorld class (obviously) * This is the PlotWorld class (obviously) - All existing PlotWorld
* - All existing PlotWorld instances should be kept in PlotMain (worlds variable) * instances should be kept in PlotMain (worlds variable) - The accessors
* - The accessors and mutators are: * and mutators are: PlotMain.isPlotWorld(world) PlotMain.getPlotWorlds() or
* PlotMain.isPlotWorld(world) * PlotMain.getPlotWorldsString() <- use this if you don't need to get world
* PlotMain.getPlotWorlds() or PlotMain.getPlotWorldsString() <- use this if you don't need to get world objects * objects PlotMain.getWorldSettings(World) - get the PlotWorld class for a
* PlotMain.getWorldSettings(World) - get the PlotWorld class for a world * world Also added is getWorldPlots(World) as the plots are now sorted per
* * world To get the world of a plot, you can use plot.world - (string) or
* Also added is getWorldPlots(World) as the plots are now sorted per world * plot.getWorld() (world object) All PlotWorld settings are per world in
* * the settings.yml (these settings are automatically added when a world is
* To get the world of a plot, you can use plot.world - (string) or plot.getWorld() (world object) * loaded, either at startup or if a new world is created): - You can find
* * this in the WorldGenerator class (yeah, it's possibly not the best place,
* All PlotWorld settings are per world in the settings.yml (these settings are automatically added when a world is loaded, either at startup or if a new world is created): * but it makes sure worlds are added to the settings.yml) All new DEFAULT
* - You can find this in the WorldGenerator class (yeah, it's possibly not the best place, but it makes sure worlds are added to the settings.yml) * CONSTANTS should be static and be given a value All new variables should
* * not be static and should not be given any values here, but rather in the
* All new DEFAULT CONSTANTS should be static and be given a value * WorldGenerator class
* All new variables should not be static and should not be given any values here, but rather in the WorldGenerator class
*
*/ */
/** /**
@ -86,7 +84,7 @@ public class PlotWorld {
/** /**
* Default main block: 1 * Default main block: 1
*/ */
public static String[] MAIN_BLOCK_DEFAULT = new String[] {"1:0"}; public static String[] MAIN_BLOCK_DEFAULT = new String[] { "1:0" };
/** /**
* Top blocks * Top blocks
*/ */
@ -94,7 +92,7 @@ public class PlotWorld {
/** /**
* Default top blocks: {"2"} * Default top blocks: {"2"}
*/ */
public static String[] TOP_BLOCK_DEFAULT = new String[] {"2:0"}; public static String[] TOP_BLOCK_DEFAULT = new String[] { "2:0" };
/** /**
* Wall block * Wall block
@ -124,33 +122,33 @@ public class PlotWorld {
* Default road stripes: 35 * Default road stripes: 35
*/ */
public static String ROAD_STRIPES_DEFAULT = "98:0"; public static String ROAD_STRIPES_DEFAULT = "98:0";
// //
// /** // /**
// * Road stripes data value (byte) // * Road stripes data value (byte)
// */ // */
// public int ROAD_STRIPES_DATA; // public int ROAD_STRIPES_DATA;
// /** // /**
// * Default road stripes data value: (byte) 0 // * Default road stripes data value: (byte) 0
// */ // */
// public static int ROAD_STRIPES_DATA_DEFAULT = 0; // public static int ROAD_STRIPES_DATA_DEFAULT = 0;
// //
// /** // /**
// * Wall block data value (byte) // * Wall block data value (byte)
// */ // */
// public int WALL_BLOCK_DATA; // public int WALL_BLOCK_DATA;
// /** // /**
// * Default wall block data value: (byte) 0 // * Default wall block data value: (byte) 0
// */ // */
// public static int WALL_BLOCK_DATA_DEFAULT = 0; // public static int WALL_BLOCK_DATA_DEFAULT = 0;
// //
// /** // /**
// * Wall filling data value (byte) // * Wall filling data value (byte)
// */ // */
// public int WALL_FILLING_DATA; // public int WALL_FILLING_DATA;
// /** // /**
// * Default wall filling data value: (byte) 0 // * Default wall filling data value: (byte) 0
// */ // */
// public static int WALL_FILLING_DATA_DEFAULT = 0; // public static int WALL_FILLING_DATA_DEFAULT = 0;
/** /**
* Road block * Road block
*/ */
@ -159,15 +157,15 @@ public class PlotWorld {
* Default road block: 155 * Default road block: 155
*/ */
public static String ROAD_BLOCK_DEFAULT = "155:0"; public static String ROAD_BLOCK_DEFAULT = "155:0";
// //
// /** // /**
// * Road block data value (byte) // * Road block data value (byte)
// */ // */
// public int ROAD_BLOCK_DATA; // public int ROAD_BLOCK_DATA;
// /** // /**
// * Default road block data value: (byte) 0 // * Default road block data value: (byte) 0
// */ // */
// public static int ROAD_BLOCK_DATA_DEFAULT = 0; // public static int ROAD_BLOCK_DATA_DEFAULT = 0;
/** /**
* plot chat? * plot chat?

View File

@ -14,101 +14,76 @@ import org.bukkit.entity.Player;
/** /**
* Random utilities * Random utilities
*
* @author Citymonstret * @author Citymonstret
* *
*/ */
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), SOUTH(0), EAST(1), NORTH(2), WEST(3);
EAST(1), private int i;
NORTH(2),
WEST(3) Direction(int i) {
; this.i = i;
private int i; }
Direction(int i) {
this.i = i; public int getInt() {
} return this.i;
public int getInt() { }
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;
float yaw; switch (x) {
case 0:
return Direction.SOUTH;
case 1:
switch(x) { return Direction.EAST;
case 0: case 2:
return Direction.SOUTH; return Direction.NORTH;
case 1: case 3:
return Direction.EAST; return Direction.WEST;
case 2: default:
return Direction.NORTH; return null;
case 3: }
return Direction.WEST; }
default:
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);
} }
private boolean AND(boolean b1, boolean b2) {
return b1 && b2;
}
private boolean OR(boolean b1, boolean b2) {
return b1 || b2;
}
private boolean XOR(boolean b1, boolean b2) {
return b1 ^ b2;
}
private boolean NAND(boolean b1, boolean b2) {
return !b1 && !b2;
}
private boolean NOR(boolean b1, boolean b2) {
return !b1 || !b2;
}
} }

View File

@ -1,8 +1,5 @@
package com.intellectualcrafters.plot; package com.intellectualcrafters.plot;
import org.bukkit.Bukkit;
import org.bukkit.Server;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.Method; import java.lang.reflect.Method;
@ -10,6 +7,9 @@ import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Server;
/** /**
* @author DPOH-VAR * @author DPOH-VAR
* @version 1.0 * @version 1.0
@ -17,7 +17,7 @@ import java.util.List;
@SuppressWarnings({ "UnusedDeclaration", "rawtypes" }) @SuppressWarnings({ "UnusedDeclaration", "rawtypes" })
public class ReflectionUtils { public class ReflectionUtils {
/** prefix of bukkit classes */ /** prefix of bukkit classes */
private static String preClassB = "org.bukkit.craftbukkit"; private static String preClassB = "org.bukkit.craftbukkit";
/** prefix of minecraft classes */ /** prefix of minecraft classes */
private static String preClassM = "net.minecraft.server"; private static String preClassM = "net.minecraft.server";
@ -26,14 +26,16 @@ public class ReflectionUtils {
/** check server version and class names */ /** check server version and class names */
static { static {
if(Bukkit.getServer()!=null) { if (Bukkit.getServer() != null) {
if(Bukkit.getVersion().contains("MCPC")||Bukkit.getVersion().contains("Forge")) forge = true; if (Bukkit.getVersion().contains("MCPC") || Bukkit.getVersion().contains("Forge")) {
forge = true;
}
Server server = Bukkit.getServer(); Server server = Bukkit.getServer();
Class<?> bukkitServerClass = server.getClass(); Class<?> bukkitServerClass = server.getClass();
String[] pas = bukkitServerClass.getName().split("\\."); String[] pas = bukkitServerClass.getName().split("\\.");
if (pas.length == 5) { if (pas.length == 5) {
String verB = pas[3]; String verB = pas[3];
preClassB += "."+verB; preClassB += "." + verB;
} }
try { try {
Method getHandle = bukkitServerClass.getDeclaredMethod("getHandle"); Method getHandle = bukkitServerClass.getDeclaredMethod("getHandle");
@ -42,7 +44,7 @@ public class ReflectionUtils {
pas = handleServerClass.getName().split("\\."); pas = handleServerClass.getName().split("\\.");
if (pas.length == 5) { if (pas.length == 5) {
String verM = pas[3]; String verM = pas[3];
preClassM += "."+verM; preClassM += "." + verM;
} }
} catch (Exception ignored) { } catch (Exception ignored) {
} }
@ -52,34 +54,36 @@ public class ReflectionUtils {
/** /**
* @return true if server has forge classes * @return true if server has forge classes
*/ */
public static boolean isForge(){ public static boolean isForge() {
return forge; return forge;
} }
/** /**
* Get class for name. * Get class for name. Replace {nms} to net.minecraft.server.V*. Replace
* Replace {nms} to net.minecraft.server.V*. * {cb} to org.bukkit.craftbukkit.V*. Replace {nm} to net.minecraft
* Replace {cb} to org.bukkit.craftbukkit.V*. *
* Replace {nm} to net.minecraft * @param classes
* @param classes possible class paths * possible class paths
* @return RefClass object * @return RefClass object
* @throws RuntimeException if no class found * @throws RuntimeException
* if no class found
*/ */
public static RefClass getRefClass(String... classes){ public static RefClass getRefClass(String... classes) {
for (String className: classes) try { for (String className : classes) {
className = className try {
.replace("{cb}", preClassB) className = className.replace("{cb}", preClassB).replace("{nms}", preClassM).replace("{nm}", "net.minecraft");
.replace("{nms}", preClassM) return getRefClass(Class.forName(className));
.replace("{nm}", "net.minecraft"); } catch (ClassNotFoundException ignored) {
return getRefClass(Class.forName(className)); }
} catch (ClassNotFoundException ignored) {
} }
throw new RuntimeException("no class found"); throw new RuntimeException("no class found");
} }
/** /**
* get RefClass object by real class * get RefClass object by real class
* @param clazz class *
* @param clazz
* class
* @return RefClass based on passed class * @return RefClass based on passed class
*/ */
public static RefClass getRefClass(Class clazz) { public static RefClass getRefClass(Class clazz) {
@ -94,43 +98,56 @@ public class ReflectionUtils {
/** /**
* get passed class * get passed class
*
* @return class * @return class
*/ */
public Class<?> getRealClass() { public Class<?> getRealClass() {
return clazz; return this.clazz;
} }
private RefClass(Class<?> clazz) { private RefClass(Class<?> clazz) {
this.clazz = clazz; this.clazz = clazz;
} }
/** /**
* see {@link Class#isInstance(Object)} * see {@link Class#isInstance(Object)}
* @param object the object to check *
* @param object
* the object to check
* @return true if object is an instance of this class * @return true if object is an instance of this class
*/ */
public boolean isInstance(Object object){ public boolean isInstance(Object object) {
return clazz.isInstance(object); return this.clazz.isInstance(object);
} }
/** /**
* get existing method by name and types * get existing method by name and types
* @param name name *
* @param types method parameters. can be Class or RefClass * @param name
* name
* @param types
* method parameters. can be Class or RefClass
* @return RefMethod object * @return RefMethod object
* @throws RuntimeException if method not found * @throws RuntimeException
* if method not found
*/ */
public RefMethod getMethod(String name, Object... types) { public RefMethod getMethod(String name, Object... types) throws NoSuchMethodException {
try { try {
Class[] classes = new Class[types.length]; Class[] classes = new Class[types.length];
int i=0; for (Object e: types) { int i = 0;
if (e instanceof Class) classes[i++] = (Class)e; for (Object e : types) {
else if (e instanceof RefClass) classes[i++] = ((RefClass) e).getRealClass(); if (e instanceof Class) {
else classes[i++] = e.getClass(); classes[i++] = (Class) e;
} else if (e instanceof RefClass) {
classes[i++] = ((RefClass) e).getRealClass();
} else {
classes[i++] = e.getClass();
}
} }
try { try {
return new RefMethod(clazz.getMethod(name, classes)); return new RefMethod(this.clazz.getMethod(name, classes));
} catch (NoSuchMethodException ignored) { } catch (NoSuchMethodException ignored) {
return new RefMethod(clazz.getDeclaredMethod(name, classes)); return new RefMethod(this.clazz.getDeclaredMethod(name, classes));
} }
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
@ -139,22 +156,30 @@ public class ReflectionUtils {
/** /**
* get existing constructor by types * get existing constructor by types
* @param types parameters. can be Class or RefClass *
* @param types
* parameters. can be Class or RefClass
* @return RefMethod object * @return RefMethod object
* @throws RuntimeException if constructor not found * @throws RuntimeException
* if constructor not found
*/ */
public RefConstructor getConstructor(Object... types) { public RefConstructor getConstructor(Object... types) {
try { try {
Class[] classes = new Class[types.length]; Class[] classes = new Class[types.length];
int i=0; for (Object e: types) { int i = 0;
if (e instanceof Class) classes[i++] = (Class)e; for (Object e : types) {
else if (e instanceof RefClass) classes[i++] = ((RefClass) e).getRealClass(); if (e instanceof Class) {
else classes[i++] = e.getClass(); classes[i++] = (Class) e;
} else if (e instanceof RefClass) {
classes[i++] = ((RefClass) e).getRealClass();
} else {
classes[i++] = e.getClass();
}
} }
try { try {
return new RefConstructor(clazz.getConstructor(classes)); return new RefConstructor(this.clazz.getConstructor(classes));
} catch (NoSuchMethodException ignored) { } catch (NoSuchMethodException ignored) {
return new RefConstructor(clazz.getDeclaredConstructor(classes)); return new RefConstructor(this.clazz.getDeclaredConstructor(classes));
} }
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
@ -163,25 +188,37 @@ public class ReflectionUtils {
/** /**
* find method by type parameters * find method by type parameters
* @param types parameters. can be Class or RefClass *
* @param types
* parameters. can be Class or RefClass
* @return RefMethod object * @return RefMethod object
* @throws RuntimeException if method not found * @throws RuntimeException
* if method not found
*/ */
public RefMethod findMethod(Object... types) { public RefMethod findMethod(Object... types) {
Class[] classes = new Class[types.length]; Class[] classes = new Class[types.length];
int t=0; for (Object e: types) { int t = 0;
if (e instanceof Class) classes[t++] = (Class)e; for (Object e : types) {
else if (e instanceof RefClass) classes[t++] = ((RefClass) e).getRealClass(); if (e instanceof Class) {
else classes[t++] = e.getClass(); classes[t++] = (Class) e;
} else if (e instanceof RefClass) {
classes[t++] = ((RefClass) e).getRealClass();
} else {
classes[t++] = e.getClass();
}
} }
List<Method> methods = new ArrayList<>(); List<Method> methods = new ArrayList<>();
Collections.addAll(methods, clazz.getMethods()); Collections.addAll(methods, this.clazz.getMethods());
Collections.addAll(methods, clazz.getDeclaredMethods()); Collections.addAll(methods, this.clazz.getDeclaredMethods());
findMethod: for (Method m: methods) { findMethod: for (Method m : methods) {
Class<?>[] methodTypes = m.getParameterTypes(); Class<?>[] methodTypes = m.getParameterTypes();
if (methodTypes.length != classes.length) continue; if (methodTypes.length != classes.length) {
for (int i=0; i<classes.length; i++) { continue;
if (!classes.equals(methodTypes)) continue findMethod; }
for (int i = 0; i < classes.length; i++) {
if (!classes.equals(methodTypes)) {
continue findMethod;
}
return new RefMethod(m); return new RefMethod(m);
} }
} }
@ -190,16 +227,19 @@ public class ReflectionUtils {
/** /**
* find method by name * find method by name
* @param names possible names of method *
* @param names
* possible names of method
* @return RefMethod object * @return RefMethod object
* @throws RuntimeException if method not found * @throws RuntimeException
* if method not found
*/ */
public RefMethod findMethodByName(String... names) { public RefMethod findMethodByName(String... names) {
List<Method> methods = new ArrayList<>(); List<Method> methods = new ArrayList<>();
Collections.addAll(methods, clazz.getMethods()); Collections.addAll(methods, this.clazz.getMethods());
Collections.addAll(methods, clazz.getDeclaredMethods()); Collections.addAll(methods, this.clazz.getDeclaredMethods());
for (Method m: methods) { for (Method m : methods) {
for (String name: names) { for (String name : names) {
if (m.getName().equals(name)) { if (m.getName().equals(name)) {
return new RefMethod(m); return new RefMethod(m);
} }
@ -210,8 +250,11 @@ public class ReflectionUtils {
/** /**
* find method by return value * find method by return value
* @param type type of returned value *
* @throws RuntimeException if method not found * @param type
* type of returned value
* @throws RuntimeException
* if method not found
* @return RefMethod * @return RefMethod
*/ */
public RefMethod findMethodByReturnType(RefClass type) { public RefMethod findMethodByReturnType(RefClass type) {
@ -220,16 +263,21 @@ public class ReflectionUtils {
/** /**
* find method by return value * find method by return value
* @param type type of returned value *
* @param type
* type of returned value
* @return RefMethod * @return RefMethod
* @throws RuntimeException if method not found * @throws RuntimeException
* if method not found
*/ */
public RefMethod findMethodByReturnType(Class type) { public RefMethod findMethodByReturnType(Class type) {
if (type==null) type = void.class; if (type == null) {
type = void.class;
}
List<Method> methods = new ArrayList<>(); List<Method> methods = new ArrayList<>();
Collections.addAll(methods, clazz.getMethods()); Collections.addAll(methods, this.clazz.getMethods());
Collections.addAll(methods, clazz.getDeclaredMethods()); Collections.addAll(methods, this.clazz.getDeclaredMethods());
for (Method m: methods) { for (Method m : methods) {
if (type.equals(m.getReturnType())) { if (type.equals(m.getReturnType())) {
return new RefMethod(m); return new RefMethod(m);
} }
@ -239,32 +287,40 @@ public class ReflectionUtils {
/** /**
* find constructor by number of arguments * find constructor by number of arguments
* @param number number of arguments *
* @param number
* number of arguments
* @return RefConstructor * @return RefConstructor
* @throws RuntimeException if constructor not found * @throws RuntimeException
* if constructor not found
*/ */
public RefConstructor findConstructor(int number) { public RefConstructor findConstructor(int number) {
List<Constructor> constructors = new ArrayList<>(); List<Constructor> constructors = new ArrayList<>();
Collections.addAll(constructors, clazz.getConstructors()); Collections.addAll(constructors, this.clazz.getConstructors());
Collections.addAll(constructors, clazz.getDeclaredConstructors()); Collections.addAll(constructors, this.clazz.getDeclaredConstructors());
for (Constructor m: constructors) { for (Constructor m : constructors) {
if (m.getParameterTypes().length == number) return new RefConstructor(m); if (m.getParameterTypes().length == number) {
return new RefConstructor(m);
}
} }
throw new RuntimeException("no such constructor"); throw new RuntimeException("no such constructor");
} }
/** /**
* get field by name * get field by name
* @param name field name *
* @param name
* field name
* @return RefField * @return RefField
* @throws RuntimeException if field not found * @throws RuntimeException
* if field not found
*/ */
public RefField getField(String name) { public RefField getField(String name) {
try { try {
try { try {
return new RefField(clazz.getField(name)); return new RefField(this.clazz.getField(name));
} catch (NoSuchFieldException ignored) { } catch (NoSuchFieldException ignored) {
return new RefField(clazz.getDeclaredField(name)); return new RefField(this.clazz.getDeclaredField(name));
} }
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
@ -273,9 +329,12 @@ public class ReflectionUtils {
/** /**
* find field by type * find field by type
* @param type field type *
* @param type
* field type
* @return RefField * @return RefField
* @throws RuntimeException if field not found * @throws RuntimeException
* if field not found
*/ */
public RefField findField(RefClass type) { public RefField findField(RefClass type) {
return findField(type.clazz); return findField(type.clazz);
@ -283,16 +342,21 @@ public class ReflectionUtils {
/** /**
* find field by type * find field by type
* @param type field type *
* @param type
* field type
* @return RefField * @return RefField
* @throws RuntimeException if field not found * @throws RuntimeException
* if field not found
*/ */
public RefField findField(Class type) { public RefField findField(Class type) {
if (type==null) type = void.class; if (type == null) {
type = void.class;
}
List<Field> fields = new ArrayList<>(); List<Field> fields = new ArrayList<>();
Collections.addAll(fields, clazz.getFields()); Collections.addAll(fields, this.clazz.getFields());
Collections.addAll(fields, clazz.getDeclaredFields()); Collections.addAll(fields, this.clazz.getDeclaredFields());
for (Field f: fields) { for (Field f : fields) {
if (type.equals(f.getType())) { if (type.equals(f.getType())) {
return new RefField(f); return new RefField(f);
} }
@ -310,28 +374,34 @@ public class ReflectionUtils {
/** /**
* @return passed method * @return passed method
*/ */
public Method getRealMethod(){ public Method getRealMethod() {
return method; return this.method;
} }
/** /**
* @return owner class of method * @return owner class of method
*/ */
public RefClass getRefClass(){ public RefClass getRefClass() {
return new RefClass(method.getDeclaringClass()); return new RefClass(this.method.getDeclaringClass());
} }
/** /**
* @return class of method return type * @return class of method return type
*/ */
public RefClass getReturnRefClass(){ public RefClass getReturnRefClass() {
return new RefClass(method.getReturnType()); return new RefClass(this.method.getReturnType());
} }
private RefMethod (Method method) {
private RefMethod(Method method) {
this.method = method; this.method = method;
method.setAccessible(true); method.setAccessible(true);
} }
/** /**
* apply method to object * apply method to object
* @param e object to which the method is applied *
* @param e
* object to which the method is applied
* @return RefExecutor with method call(...) * @return RefExecutor with method call(...)
*/ */
public RefExecutor of(Object e) { public RefExecutor of(Object e) {
@ -340,12 +410,14 @@ public class ReflectionUtils {
/** /**
* call static method * call static method
* @param params sent parameters *
* @param params
* sent parameters
* @return return value * @return return value
*/ */
public Object call(Object... params) { public Object call(Object... params) {
try{ try {
return method.invoke(null,params); return this.method.invoke(null, params);
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@ -353,19 +425,23 @@ public class ReflectionUtils {
public class RefExecutor { public class RefExecutor {
Object e; Object e;
public RefExecutor(Object e) { public RefExecutor(Object e) {
this.e = e; this.e = e;
} }
/** /**
* apply method for selected object * apply method for selected object
* @param params sent parameters *
* @param params
* sent parameters
* @return return value * @return return value
* @throws RuntimeException if something went wrong * @throws RuntimeException
* if something went wrong
*/ */
public Object call(Object... params) { public Object call(Object... params) {
try{ try {
return method.invoke(e,params); return RefMethod.this.method.invoke(this.e, params);
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@ -382,30 +458,34 @@ public class ReflectionUtils {
/** /**
* @return passed constructor * @return passed constructor
*/ */
public Constructor getRealConstructor(){ public Constructor getRealConstructor() {
return constructor; return this.constructor;
} }
/** /**
* @return owner class of method * @return owner class of method
*/ */
public RefClass getRefClass(){ public RefClass getRefClass() {
return new RefClass(constructor.getDeclaringClass()); return new RefClass(this.constructor.getDeclaringClass());
} }
private RefConstructor (Constructor constructor) {
private RefConstructor(Constructor constructor) {
this.constructor = constructor; this.constructor = constructor;
constructor.setAccessible(true); constructor.setAccessible(true);
} }
/** /**
* create new instance with constructor * create new instance with constructor
* @param params parameters for constructor *
* @param params
* parameters for constructor
* @return new object * @return new object
* @throws RuntimeException if something went wrong * @throws RuntimeException
* if something went wrong
*/ */
public Object create(Object... params) { public Object create(Object... params) {
try{ try {
return constructor.newInstance(params); return this.constructor.newInstance(params);
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@ -418,49 +498,56 @@ public class ReflectionUtils {
/** /**
* @return passed field * @return passed field
*/ */
public Field getRealField(){ public Field getRealField() {
return field; return this.field;
} }
/** /**
* @return owner class of field * @return owner class of field
*/ */
public RefClass getRefClass(){ public RefClass getRefClass() {
return new RefClass(field.getDeclaringClass()); return new RefClass(this.field.getDeclaringClass());
} }
/** /**
* @return type of field * @return type of field
*/ */
public RefClass getFieldRefClass(){ public RefClass getFieldRefClass() {
return new RefClass(field.getType()); return new RefClass(this.field.getType());
} }
private RefField (Field field) {
private RefField(Field field) {
this.field = field; this.field = field;
field.setAccessible(true); field.setAccessible(true);
} }
/** /**
* apply fiend for object * apply fiend for object
* @param e applied object *
* @param e
* applied object
* @return RefExecutor with getter and setter * @return RefExecutor with getter and setter
*/ */
public RefExecutor of(Object e) { public RefExecutor of(Object e) {
return new RefExecutor(e); return new RefExecutor(e);
} }
public class RefExecutor { public class RefExecutor {
Object e; Object e;
public RefExecutor(Object e) { public RefExecutor(Object e) {
this.e = e; this.e = e;
} }
/** /**
* set field value for applied object * set field value for applied object
* @param param value *
* @param param
* value
*/ */
public void set(Object param) { public void set(Object param) {
try{ try {
field.set(e,param); RefField.this.field.set(this.e, param);
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@ -468,11 +555,12 @@ public class ReflectionUtils {
/** /**
* get field value for applied object * get field value for applied object
*
* @return value of field * @return value of field
*/ */
public Object get() { public Object get() {
try{ try {
return field.get(e); return RefField.this.field.get(this.e);
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }

View File

@ -1,26 +1,32 @@
package com.intellectualcrafters.plot; package com.intellectualcrafters.plot;
import com.sk89q.jnbt.*;
import com.sk89q.worldedit.CuboidClipboard;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.bukkit.BukkitWorld;
import org.bukkit.Location;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.InputStream; import java.io.InputStream;
import java.util.Map; import java.util.Map;
import java.util.zip.GZIPInputStream; import java.util.zip.GZIPInputStream;
import org.bukkit.Location;
import org.bukkit.plugin.java.JavaPlugin;
import com.sk89q.jnbt.ByteArrayTag;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.jnbt.NBTInputStream;
import com.sk89q.jnbt.ShortTag;
import com.sk89q.jnbt.Tag;
import com.sk89q.worldedit.CuboidClipboard;
import com.sk89q.worldedit.EditSession;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.bukkit.BukkitWorld;
/** /**
* Created by Citymonstret on 2014-09-15. * Created by Citymonstret on 2014-09-15.
*/ */
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;
} }
@ -28,11 +34,11 @@ public class SchematicHandler {
EditSession session = new EditSession(new BukkitWorld(location.getWorld()), 999999999); EditSession session = new EditSession(new BukkitWorld(location.getWorld()), 999999999);
CuboidClipboard clipboard = CuboidClipboard.loadSchematic(schematic.getFile()); CuboidClipboard clipboard = CuboidClipboard.loadSchematic(schematic.getFile());
Location l1 = PlotHelper.getPlotBottomLoc(plot.getWorld(), plot.getId()); Location l1 = PlotHelper.getPlotBottomLoc(plot.getWorld(), plot.getId());
Location l2 = PlotHelper.getPlotTopLoc(plot.getWorld(), plot.getId()); PlotHelper.getPlotTopLoc(plot.getWorld(), plot.getId());
PlotWorld plotWorld = PlotMain.getWorldSettings(plot.getWorld()); PlotWorld plotWorld = PlotMain.getWorldSettings(plot.getWorld());
Vector v1 = new Vector(l1.getBlockX() + 1, plotWorld.PLOT_HEIGHT + 2, l1.getBlockZ() + 1); Vector v1 = new Vector(l1.getBlockX() + 1, plotWorld.PLOT_HEIGHT + 2, l1.getBlockZ() + 1);
clipboard.paste(session, v1, true); clipboard.paste(session, v1, true);
} catch(Exception e) { } catch (Exception e) {
return false; return false;
} }
return true; return true;
@ -40,13 +46,13 @@ public class SchematicHandler {
public Schematic getSchematic(String name) { public Schematic getSchematic(String name) {
{ {
File parent = new File(PlotMain.getPlugin(PlotMain.class).getDataFolder() + File.separator + "schematics"); File parent = new File(JavaPlugin.getPlugin(PlotMain.class).getDataFolder() + File.separator + "schematics");
if(!parent.exists()) { if (!parent.exists()) {
parent.mkdir(); parent.mkdir();
} }
} }
File file = new File(PlotMain.getPlugin(PlotMain.class).getDataFolder() + File.separator + "schematics" + File.separator + name + ".schematic"); File file = new File(JavaPlugin.getPlugin(PlotMain.class).getDataFolder() + File.separator + "schematics" + File.separator + name + ".schematic");
if(!file.exists()) { if (!file.exists()) {
PlotMain.sendConsoleSenderMessage(file.toString() + " doesn't exist"); PlotMain.sendConsoleSenderMessage(file.toString() + " doesn't exist");
return null; return null;
} }
@ -74,7 +80,8 @@ public class SchematicHandler {
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 AddBlocks index if ((index >> 1) >= addId.length) { // No corresponding
// AddBlocks index
blocks[index] = (short) (b[index] & 0xFF); blocks[index] = (short) (b[index] & 0xFF);
} else { } else {
if ((index & 1) == 0) { if ((index & 1) == 0) {
@ -87,12 +94,12 @@ public class SchematicHandler {
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 {
@ -100,10 +107,6 @@ public class SchematicHandler {
} }
} }
private int getCurrent(int x, int y, int z, Dimension dimension) {
return (x * dimension.getX()) + (y * dimension.getY()) + (z * dimension.getZ());
}
public static class Schematic { public static class Schematic {
private DataCollection[] blockCollection; private DataCollection[] blockCollection;
private Dimension schematicDimension; private Dimension schematicDimension;

View File

@ -1,8 +1,9 @@
package com.intellectualcrafters.plot; package com.intellectualcrafters.plot;
import org.bukkit.entity.Player; import static com.intellectualcrafters.plot.ReflectionUtils.getRefClass;
import static com.intellectualcrafters.plot.ReflectionUtils.*; import com.intellectualcrafters.plot.ReflectionUtils.RefClass;
import com.intellectualcrafters.plot.ReflectionUtils.RefMethod;
public class SetBlockFast { public class SetBlockFast {
@ -11,24 +12,28 @@ public class SetBlockFast {
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 final RefMethod methodGetHandle = classCraftWorld.getMethod("getHandle"); private static RefMethod methodGetHandle;
private static final RefMethod methodGetChunkAt = classWorld.getMethod("getChunkAt",int.class,int.class); private static RefMethod methodGetChunkAt;
private static final RefMethod methodA = classChunk.getMethod("a",int.class,int.class,int.class,classBlock,int.class); private static RefMethod methodA;
private static final RefMethod methodGetById = classBlock.getMethod("getById", int.class); private static RefMethod methodGetById;
public SetBlockFast() {
public SetBlockFast() throws NoSuchMethodException {
methodGetHandle = classCraftWorld.getMethod("getHandle");
methodGetChunkAt = classWorld.getMethod("getChunkAt", int.class, int.class);
methodA = classChunk.getMethod("a", int.class, int.class, int.class, classBlock, int.class);
methodGetById = classBlock.getMethod("getById", int.class);
} }
public static boolean set(org.bukkit.World world, int x, int y, int z, int blockId, byte data) { 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(Player player) { public static void update(org.bukkit.entity.Player player) {
for (int cx = -8; cx < 8; cx++) { for (int cx = -8; cx < 8; cx++) {
for (int cz = -8; cz < 8; cz++) { for (int cz = -8; cz < 8; 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

@ -11,6 +11,7 @@ package com.intellectualcrafters.plot;
/** /**
* Updater and DB settings * Updater and DB settings
*
* @author Citymonstret * @author Citymonstret
* *
* @author Empire92 * @author Empire92
@ -37,39 +38,44 @@ public class Settings {
* 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 class Update {
/**
* Update plugin?
* @deprecated
*/
public static boolean AUTO_UPDATE = false;
}
public static class Web { public static class Update {
public static boolean ENABLED = false; /**
public static int PORT = 9000; * Update plugin?
*
* @deprecated
*/
@Deprecated
public static boolean AUTO_UPDATE = false;
} }
/** public static class Web {
* Database settings public static boolean ENABLED = false;
* @author Citymonstret public static int PORT = 9000;
* }
*/
public static class DB { /**
public static boolean USE_MONGO = false; /* TODO: Implement Mongo */; * Database settings
public static boolean USE_SQLITE = false; *
public static boolean USE_MYSQL = true; /* NOTE: Fixed connector */ * @author Citymonstret
public static String SQLITE_DB = "storage"; *
public static String HOST_NAME = "localhost"; */
public static String PORT = "3306"; public static class DB {
public static String DATABASE = "plot_db"; public static boolean USE_MONGO = false; /* TODO: Implement Mongo */;
public static String USER = "root"; public static boolean USE_SQLITE = false;
public static String PASSWORD = "password"; public static boolean USE_MYSQL = true; /* NOTE: Fixed connector */
} public static String SQLITE_DB = "storage";
public static String HOST_NAME = "localhost";
public static String PORT = "3306";
public static String DATABASE = "plot_db";
public static String USER = "root";
public static String PASSWORD = "password";
}
} }

View File

@ -1,14 +1,14 @@
package com.intellectualcrafters.plot; package com.intellectualcrafters.plot;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
/** /**
* Minecraft 1.8 Title * Minecraft 1.8 Title
* *
@ -80,8 +80,7 @@ public class Title {
* @param fadeOutTime * @param fadeOutTime
* Fade out time * Fade out time
*/ */
public Title(String title, String subtitle, int fadeInTime, int stayTime, public Title(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) {
int fadeOutTime) {
this.title = title; this.title = title;
this.subtitle = subtitle; this.subtitle = subtitle;
this.fadeInTime = fadeInTime; this.fadeInTime = fadeInTime;
@ -94,9 +93,9 @@ public class Title {
* Load spigot and NMS classes * Load spigot and NMS classes
*/ */
private void loadClasses() { private void loadClasses() {
packetTitle = getClass("org.spigotmc.ProtocolInjector$PacketTitle"); this.packetTitle = getClass("org.spigotmc.ProtocolInjector$PacketTitle");
packetActions = getClass("org.spigotmc.ProtocolInjector$PacketTitle$Action"); this.packetActions = getClass("org.spigotmc.ProtocolInjector$PacketTitle$Action");
nmsChatSerializer = getNMSClass("ChatSerializer"); this.nmsChatSerializer = getNMSClass("ChatSerializer");
} }
/** /**
@ -153,14 +152,14 @@ public class Title {
* Set timings to ticks * Set timings to ticks
*/ */
public void setTimingsToTicks() { public void setTimingsToTicks() {
ticks = true; this.ticks = true;
} }
/** /**
* Set timings to seconds * Set timings to seconds
*/ */
public void setTimingsToSeconds() { public void setTimingsToSeconds() {
ticks = false; this.ticks = false;
} }
/** /**
@ -170,53 +169,29 @@ public class Title {
* Player * Player
*/ */
public void send(Player player) { public void send(Player player) {
if (getProtocolVersion(player) >= 47 && isSpigot() if ((getProtocolVersion(player) >= 47) && isSpigot() && (this.packetTitle != null)) {
&& packetTitle != null) {
// First reset previous settings // First reset previous settings
resetTitle(player); resetTitle(player);
try { try {
// Send timings first // Send timings first
Object handle = getHandle(player); Object handle = getHandle(player);
Object connection = getField(handle.getClass(), Object connection = getField(handle.getClass(), "playerConnection").get(handle);
"playerConnection").get(handle); Object[] actions = this.packetActions.getEnumConstants();
Object[] actions = packetActions.getEnumConstants(); Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Method sendPacket = getMethod(connection.getClass(), 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));
"sendPacket");
Object packet = packetTitle.getConstructor(packetActions,
Integer.TYPE, Integer.TYPE, Integer.TYPE).newInstance(
actions[2], fadeInTime * (ticks ? 1 : 20),
stayTime * (ticks ? 1 : 20),
fadeOutTime * (ticks ? 1 : 20));
// Send if set // Send if set
if (fadeInTime != -1 && fadeOutTime != -1 && stayTime != -1) if ((this.fadeInTime != -1) && (this.fadeOutTime != -1) && (this.stayTime != -1)) {
sendPacket.invoke(connection, packet); sendPacket.invoke(connection, packet);
}
// Send title // Send title
Object serialized = getMethod(nmsChatSerializer, "a", Object serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.title) + "\",color:" + this.titleColor.name().toLowerCase() + "}");
String.class).invoke( packet = this.packetTitle.getConstructor(this.packetActions, getNMSClass("IChatBaseComponent")).newInstance(actions[0], serialized);
null,
"{text:\""
+ ChatColor.translateAlternateColorCodes('&',
title) + "\",color:"
+ titleColor.name().toLowerCase() + "}");
packet = packetTitle.getConstructor(packetActions,
getNMSClass("IChatBaseComponent")).newInstance(
actions[0], serialized);
sendPacket.invoke(connection, packet); sendPacket.invoke(connection, packet);
if (!subtitle.equals("")) { if (!this.subtitle.equals("")) {
// Send subtitle if present // Send subtitle if present
serialized = getMethod(nmsChatSerializer, "a", String.class) serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.subtitle) + "\",color:" + this.subtitleColor.name().toLowerCase() + "}");
.invoke(null, packet = this.packetTitle.getConstructor(this.packetActions, getNMSClass("IChatBaseComponent")).newInstance(actions[1], serialized);
"{text:\""
+ ChatColor
.translateAlternateColorCodes(
'&', subtitle)
+ "\",color:"
+ subtitleColor.name()
.toLowerCase() + "}");
packet = packetTitle.getConstructor(packetActions,
getNMSClass("IChatBaseComponent")).newInstance(
actions[1], serialized);
sendPacket.invoke(connection, packet); sendPacket.invoke(connection, packet);
} }
} catch (Exception e) { } catch (Exception e) {
@ -241,17 +216,14 @@ public class Title {
* 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(), Object connection = getField(handle.getClass(), "playerConnection").get(handle);
"playerConnection").get(handle); Object[] actions = this.packetActions.getEnumConstants();
Object[] actions = packetActions.getEnumConstants(); Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Method sendPacket = getMethod(connection.getClass(), Object packet = this.packetTitle.getConstructor(this.packetActions).newInstance(actions[3]);
"sendPacket");
Object packet = packetTitle.getConstructor(packetActions)
.newInstance(actions[3]);
sendPacket.invoke(connection, packet); sendPacket.invoke(connection, packet);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@ -266,17 +238,14 @@ public class Title {
* 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(), Object connection = getField(handle.getClass(), "playerConnection").get(handle);
"playerConnection").get(handle); Object[] actions = this.packetActions.getEnumConstants();
Object[] actions = packetActions.getEnumConstants(); Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Method sendPacket = getMethod(connection.getClass(), Object packet = this.packetTitle.getConstructor(this.packetActions).newInstance(actions[4]);
"sendPacket");
Object packet = packetTitle.getConstructor(packetActions)
.newInstance(actions[4]);
sendPacket.invoke(connection, packet); sendPacket.invoke(connection, packet);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@ -295,15 +264,13 @@ public class Title {
int version = 0; int version = 0;
try { try {
Object handle = getHandle(player); Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection") Object connection = getField(handle.getClass(), "playerConnection").get(handle);
.get(handle);
Object networkManager = getValue("networkManager", connection); Object networkManager = getValue("networkManager", connection);
version = (Integer) getMethod("getVersion", version = (Integer) getMethod("getVersion", networkManager.getClass()).invoke(networkManager);
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;
} }
@ -343,24 +310,27 @@ public class Title {
} }
private Class<?> getPrimitiveType(Class<?> clazz) { private Class<?> getPrimitiveType(Class<?> clazz) {
return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES.get(clazz) : clazz;
.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++) }
if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i])) for (int i = 0; i < a.length; i++) {
if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i])) {
return false; return false;
}
}
return true; return true;
} }
@ -373,13 +343,13 @@ public class Title {
} }
} }
private Method getMethod(String name, Class<?> clazz, private Method getMethod(String name, Class<?> clazz, Class<?>... paramTypes) {
Class<?>... paramTypes) {
Class<?>[] t = toPrimitiveTypeArray(paramTypes); Class<?>[] t = toPrimitiveTypeArray(paramTypes);
for (Method m : clazz.getMethods()) { for (Method m : clazz.getMethods()) {
Class<?>[] types = toPrimitiveTypeArray(m.getParameterTypes()); Class<?>[] types = toPrimitiveTypeArray(m.getParameterTypes());
if (m.getName().equals(name) && equalsTypeArray(types, t)) if (m.getName().equals(name) && equalsTypeArray(types, t)) {
return m; return m;
}
} }
return null; return null;
} }
@ -412,25 +382,26 @@ public class Title {
} }
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) if (m.getName().equals(name) && ((args.length == 0) || ClassListEqual(args, m.getParameterTypes()))) {
&& (args.length == 0 || ClassListEqual(args,
m.getParameterTypes()))) {
m.setAccessible(true); m.setAccessible(true);
return m; 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,5 +1,30 @@
package com.intellectualcrafters.plot; package com.intellectualcrafters.plot;
import static com.intellectualcrafters.plot.PlotWorld.DEFAULT_FLAGS_DEFAULT;
import static com.intellectualcrafters.plot.PlotWorld.MAIN_BLOCK_DEFAULT;
import static com.intellectualcrafters.plot.PlotWorld.PLOT_BIOME_DEFAULT;
import static com.intellectualcrafters.plot.PlotWorld.PLOT_HEIGHT_DEFAULT;
import static com.intellectualcrafters.plot.PlotWorld.PLOT_WIDTH_DEFAULT;
import static com.intellectualcrafters.plot.PlotWorld.ROAD_BLOCK_DEFAULT;
import static com.intellectualcrafters.plot.PlotWorld.ROAD_HEIGHT_DEFAULT;
import static com.intellectualcrafters.plot.PlotWorld.ROAD_STRIPES_DEFAULT;
import static com.intellectualcrafters.plot.PlotWorld.ROAD_STRIPES_ENABLED_DEFAULT;
import static com.intellectualcrafters.plot.PlotWorld.ROAD_WIDTH_DEFAULT;
import static com.intellectualcrafters.plot.PlotWorld.SCHEMATIC_FILE_DEFAULT;
import static com.intellectualcrafters.plot.PlotWorld.SCHEMATIC_ON_CLAIM_DEFAULT;
import static com.intellectualcrafters.plot.PlotWorld.TOP_BLOCK_DEFAULT;
import static com.intellectualcrafters.plot.PlotWorld.WALL_BLOCK_DEFAULT;
import static com.intellectualcrafters.plot.PlotWorld.WALL_FILLING_DEFAULT;
import static com.intellectualcrafters.plot.PlotWorld.WALL_HEIGHT_DEFAULT;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.World; import org.bukkit.World;
@ -8,24 +33,19 @@ import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.generator.BlockPopulator; import org.bukkit.generator.BlockPopulator;
import org.bukkit.generator.ChunkGenerator; import org.bukkit.generator.ChunkGenerator;
import java.io.IOException;
import java.util.*;
import java.util.Map.Entry;
import static com.intellectualcrafters.plot.PlotWorld.*;
/** /**
* TODO finish recoding this class * TODO finish recoding this class
*
* @auther Empire92 * @auther Empire92
* @author Citymonstret * @author Citymonstret
* *
*/ */
public class WorldGenerator extends ChunkGenerator { public class WorldGenerator extends ChunkGenerator {
private long state; private long state;
public final long nextLong() { public final long nextLong() {
long a=state; long a = this.state;
state = xorShift64(a); this.state = xorShift64(a);
return a; return a;
} }
@ -35,8 +55,9 @@ public class WorldGenerator extends ChunkGenerator {
a ^= (a << 4); a ^= (a << 4);
return a; return a;
} }
public final int random(int n) { public final int random(int n) {
long r = ((nextLong()>>>32)*n)>>32; long r = ((nextLong() >>> 32) * n) >> 32;
return (int) r; return (int) r;
} }
@ -68,25 +89,25 @@ public class WorldGenerator extends ChunkGenerator {
public WorldGenerator(String world) { public WorldGenerator(String world) {
YamlConfiguration config = PlotMain.config; YamlConfiguration config = PlotMain.config;
plotworld = new PlotWorld(); this.plotworld = new PlotWorld();
Map<String, Object> options = new HashMap<String, Object>(); Map<String, Object> options = new HashMap<String, Object>();
options.put("worlds."+world+".plot_height", PLOT_HEIGHT_DEFAULT); options.put("worlds." + world + ".plot_height", PLOT_HEIGHT_DEFAULT);
options.put("worlds."+world+".plot_size", PLOT_WIDTH_DEFAULT); options.put("worlds." + world + ".plot_size", PLOT_WIDTH_DEFAULT);
options.put("worlds."+world+".plot_biome", PLOT_BIOME_DEFAULT); options.put("worlds." + world + ".plot_biome", PLOT_BIOME_DEFAULT);
options.put("worlds."+world+".plot_filling", Arrays.asList(MAIN_BLOCK_DEFAULT)); options.put("worlds." + world + ".plot_filling", Arrays.asList(MAIN_BLOCK_DEFAULT));
options.put("worlds."+world+".top_floor", Arrays.asList(TOP_BLOCK_DEFAULT)); options.put("worlds." + world + ".top_floor", Arrays.asList(TOP_BLOCK_DEFAULT));
options.put("worlds."+world+".wall.block", WALL_BLOCK_DEFAULT); options.put("worlds." + world + ".wall.block", WALL_BLOCK_DEFAULT);
options.put("worlds."+world+".road.width", ROAD_WIDTH_DEFAULT); options.put("worlds." + world + ".road.width", ROAD_WIDTH_DEFAULT);
options.put("worlds."+world+".road.height", ROAD_HEIGHT_DEFAULT); options.put("worlds." + world + ".road.height", ROAD_HEIGHT_DEFAULT);
options.put("worlds."+world+".road.block", ROAD_BLOCK_DEFAULT); options.put("worlds." + world + ".road.block", ROAD_BLOCK_DEFAULT);
options.put("worlds."+world+".road.stripes", ROAD_STRIPES_DEFAULT); options.put("worlds." + world + ".road.stripes", ROAD_STRIPES_DEFAULT);
options.put("worlds."+world+".road.enable_stripes", ROAD_STRIPES_ENABLED_DEFAULT); options.put("worlds." + world + ".road.enable_stripes", ROAD_STRIPES_ENABLED_DEFAULT);
options.put("worlds."+world+".wall.filling", WALL_FILLING_DEFAULT); options.put("worlds." + world + ".wall.filling", WALL_FILLING_DEFAULT);
options.put("worlds."+world+".wall.height", WALL_HEIGHT_DEFAULT); options.put("worlds." + world + ".wall.height", WALL_HEIGHT_DEFAULT);
options.put("worlds."+world+".schematic.on_claim", SCHEMATIC_ON_CLAIM_DEFAULT); options.put("worlds." + world + ".schematic.on_claim", SCHEMATIC_ON_CLAIM_DEFAULT);
options.put("worlds."+world+".schematic.file", SCHEMATIC_FILE_DEFAULT); options.put("worlds." + world + ".schematic.file", SCHEMATIC_FILE_DEFAULT);
options.put("worlds."+world+".default_flags", DEFAULT_FLAGS_DEFAULT); options.put("worlds." + world + ".default_flags", DEFAULT_FLAGS_DEFAULT);
for (Entry<String, Object> node : options.entrySet()) { for (Entry<String, Object> node : options.entrySet()) {
if (!config.contains(node.getKey())) { if (!config.contains(node.getKey())) {
@ -98,64 +119,65 @@ public class WorldGenerator extends ChunkGenerator {
} catch (IOException e) { } catch (IOException e) {
PlotMain.sendConsoleSenderMessage("&c[Warning] PlotSquared failed to save the configuration&7 (settings.yml may differ from the one in memory)\n - To force a save from console use /plots save"); PlotMain.sendConsoleSenderMessage("&c[Warning] PlotSquared failed to save the configuration&7 (settings.yml may differ from the one in memory)\n - To force a save from console use /plots save");
} }
plotworld.PLOT_HEIGHT = config.getInt("worlds."+world+".plot_height"); this.plotworld.PLOT_HEIGHT = config.getInt("worlds." + world + ".plot_height");
plotworld.PLOT_WIDTH = config.getInt("worlds."+world+".plot_size"); this.plotworld.PLOT_WIDTH = config.getInt("worlds." + world + ".plot_size");
plotworld.PLOT_BIOME = config.getString("worlds."+world+".plot_biome"); this.plotworld.PLOT_BIOME = config.getString("worlds." + world + ".plot_biome");
plotworld.MAIN_BLOCK = config.getStringList("worlds."+world+".plot_filling").toArray(new String[0]); this.plotworld.MAIN_BLOCK = config.getStringList("worlds." + world + ".plot_filling").toArray(new String[0]);
plotworld.TOP_BLOCK = config.getStringList("worlds."+world+".top_floor").toArray(new String[0]); this.plotworld.TOP_BLOCK = config.getStringList("worlds." + world + ".top_floor").toArray(new String[0]);
plotworld.WALL_BLOCK = config.getString("worlds."+world+".wall.block"); this.plotworld.WALL_BLOCK = config.getString("worlds." + world + ".wall.block");
plotworld.ROAD_WIDTH = config.getInt("worlds."+world+".road.width"); this.plotworld.ROAD_WIDTH = config.getInt("worlds." + world + ".road.width");
plotworld.ROAD_HEIGHT = config.getInt("worlds."+world+".road.height"); this.plotworld.ROAD_HEIGHT = config.getInt("worlds." + world + ".road.height");
plotworld.ROAD_STRIPES_ENABLED = config.getBoolean("worlds."+world+".road.enable_stripes"); this.plotworld.ROAD_STRIPES_ENABLED = config.getBoolean("worlds." + world + ".road.enable_stripes");
plotworld.ROAD_BLOCK = config.getString("worlds."+world+".road.block"); this.plotworld.ROAD_BLOCK = config.getString("worlds." + world + ".road.block");
plotworld.ROAD_STRIPES = config.getString("worlds."+world+".road.stripes"); this.plotworld.ROAD_STRIPES = config.getString("worlds." + world + ".road.stripes");
plotworld.WALL_FILLING = config.getString("worlds."+world+".wall.filling"); this.plotworld.WALL_FILLING = config.getString("worlds." + world + ".wall.filling");
plotworld.WALL_HEIGHT = config.getInt("worlds."+world+".wall.height"); this.plotworld.WALL_HEIGHT = config.getInt("worlds." + world + ".wall.height");
plotworld.PLOT_CHAT = config.getBoolean("worlds."+world+".plot_chat"); this.plotworld.PLOT_CHAT = config.getBoolean("worlds." + world + ".plot_chat");
plotworld.SCHEMATIC_ON_CLAIM = config.getBoolean("worlds."+world+".schematic.on_claim"); this.plotworld.SCHEMATIC_ON_CLAIM = config.getBoolean("worlds." + world + ".schematic.on_claim");
plotworld.SCHEMATIC_FILE = config.getString("worlds."+world+".schematic.file"); this.plotworld.SCHEMATIC_FILE = config.getString("worlds." + world + ".schematic.file");
String[] default_flags_string = config.getStringList("worlds."+world+".default_flags").toArray(new String[0]); String[] default_flags_string = config.getStringList("worlds." + world + ".default_flags").toArray(new String[0]);
Flag[] default_flags = new Flag[default_flags_string.length]; Flag[] default_flags = new Flag[default_flags_string.length];
for (int i = 0; i < default_flags.length; i++) { for (int i = 0; i < default_flags.length; i++) {
String current = default_flags_string[i]; String current = default_flags_string[i];
if (current.contains(",")) if (current.contains(",")) {
default_flags[i] = new Flag(FlagManager.getFlag(current.split(",")[0], true), current.split(",")[1]); default_flags[i] = new Flag(FlagManager.getFlag(current.split(",")[0], true), current.split(",")[1]);
else } else {
default_flags[i] = new Flag(FlagManager.getFlag(current, true), ""); default_flags[i] = new Flag(FlagManager.getFlag(current, true), "");
}
} }
plotworld.DEFAULT_FLAGS = default_flags; this.plotworld.DEFAULT_FLAGS = default_flags;
PlotMain.addPlotWorld(world, plotworld); PlotMain.addPlotWorld(world, this.plotworld);
plotsize = plotworld.PLOT_WIDTH; this.plotsize = this.plotworld.PLOT_WIDTH;
pathsize = plotworld.ROAD_WIDTH; this.pathsize = this.plotworld.ROAD_WIDTH;
bottom = (short) Material.BEDROCK.getId(); this.bottom = (short) Material.BEDROCK.getId();
floor1 = getBlock(plotworld.ROAD_BLOCK); this.floor1 = getBlock(this.plotworld.ROAD_BLOCK);
floor2 = getBlock(plotworld.ROAD_STRIPES); this.floor2 = getBlock(this.plotworld.ROAD_STRIPES);
wallfilling = getBlock(plotworld.WALL_FILLING); this.wallfilling = getBlock(this.plotworld.WALL_FILLING);
size = pathsize + plotsize; this.size = this.pathsize + this.plotsize;
wall = getBlock(plotworld.WALL_BLOCK); this.wall = getBlock(this.plotworld.WALL_BLOCK);
plotfloors = new short[plotworld.TOP_BLOCK.length]; this.plotfloors = new short[this.plotworld.TOP_BLOCK.length];
filling = new short[plotworld.MAIN_BLOCK.length]; this.filling = new short[this.plotworld.MAIN_BLOCK.length];
for (int i = 0; i < plotworld.TOP_BLOCK.length; i++) { for (int i = 0; i < this.plotworld.TOP_BLOCK.length; i++) {
plotfloors[i] = getBlock(plotworld.TOP_BLOCK[i]); this.plotfloors[i] = getBlock(this.plotworld.TOP_BLOCK[i]);
} }
for (int i = 0; i < plotworld.MAIN_BLOCK.length; i++) { for (int i = 0; i < this.plotworld.MAIN_BLOCK.length; i++) {
filling[i] = getBlock(plotworld.MAIN_BLOCK[i]); this.filling[i] = getBlock(this.plotworld.MAIN_BLOCK[i]);
} }
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;
biome = Biome.FOREST; this.biome = Biome.FOREST;
for (Biome myBiome:Biome.values()) { for (Biome myBiome : Biome.values()) {
if (myBiome.name().equalsIgnoreCase(plotworld.PLOT_BIOME)) { if (myBiome.name().equalsIgnoreCase(this.plotworld.PLOT_BIOME)) {
biome = myBiome; this.biome = myBiome;
break; break;
} }
} }
@ -171,343 +193,351 @@ public class WorldGenerator extends ChunkGenerator {
return new Location(world, 0, PlotMain.getWorldSettings(world).ROAD_HEIGHT + 2, 0); return new Location(world, 0, PlotMain.getWorldSettings(world).ROAD_HEIGHT + 2, 0);
} }
public void setCuboidRegion(int x1,int x2, int y1, int y2, int z1, int z2, short id) { public void setCuboidRegion(int x1, int x2, int y1, int y2, int z1, int z2, short id) {
for (int x = x1; x < x2; x++) { for (int x = x1; x < x2; x++) {
for (int z = z1; z < z2; z++) { for (int z = z1; z < z2; z++) {
for (int y = y1; y < y2; y++) { for (int y = y1; y < y2; y++) {
setBlock(result, x, y, z, id); setBlock(this.result, x, y, z, id);
} }
} }
} }
} }
private void setCuboidRegion(int x1, int x2, int y1, int y2, int z1, int z2, short[] id) { private void setCuboidRegion(int x1, int x2, int y1, int y2, int z1, int z2, short[] id) {
if (id.length==1) { if (id.length == 1) {
setCuboidRegion(x1,x2,y1,y2,z1,z2,id[0]); setCuboidRegion(x1, x2, y1, y2, z1, z2, id[0]);
} } else {
else {
for (int x = x1; x < x2; x++) { for (int x = x1; x < x2; x++) {
for (int z = z1; z < z2; z++) { for (int z = z1; z < z2; z++) {
for (int y = y1; y < y2; y++) { for (int y = y1; y < y2; y++) {
int i = random(id.length); int i = random(id.length);
setBlock(result, x, y, z, id[i]); setBlock(this.result, x, y, z, id[i]);
} }
} }
} }
} }
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@Override @Override
public short[][] generateExtBlockSections(World world, Random random, public short[][] generateExtBlockSections(World world, Random random, int cx, int cz, BiomeGrid biomes) {
int cx, int cz, BiomeGrid biomes) {
int maxY = world.getMaxHeight(); int maxY = world.getMaxHeight();
result = new short[maxY / 16][]; this.result = new short[maxY / 16][];
double pathWidthLower; double pathWidthLower;
pathWidthLower = Math.floor(pathsize/2); pathWidthLower = Math.floor(this.pathsize / 2);
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;
state = h; this.state = h;
cx=cx%size+8*size; cx = (cx % this.size) + (8 * this.size);
cz=cz%size+8*size; cz = (cz % this.size) + (8 * this.size);
int absX = (int) (cx*16+16-pathWidthLower-1+8*size); int absX = (int) ((((cx * 16) + 16) - pathWidthLower - 1) + (8 * this.size));
int absZ = (int) (cz*16+16-pathWidthLower-1+8*size); int absZ = (int) ((((cz * 16) + 16) - pathWidthLower - 1) + (8 * this.size));
int plotMinX = (((absX)%size)); int plotMinX = (((absX) % this.size));
int plotMinZ = (((absZ)%size)); int plotMinZ = (((absZ) % this.size));
int roadStartX = (plotMinX + pathsize); int roadStartX = (plotMinX + this.pathsize);
int roadStartZ = (plotMinZ + pathsize); int roadStartZ = (plotMinZ + this.pathsize);
if (roadStartX>=size) if (roadStartX >= this.size) {
roadStartX-=size; roadStartX -= this.size;
if (roadStartZ>=size) }
roadStartZ-=size; if (roadStartZ >= this.size) {
roadStartZ -= this.size;
}
// BOTTOM (1/1 cuboids) // BOTTOM (1/1 cuboids)
for (int x = 0; x < 16; x++) { for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) { for (int z = 0; z < 16; z++) {
setBlock(result, x, 0, z, bottom); setBlock(this.result, x, 0, z, this.bottom);
biomes.setBiome(x, z, biome); biomes.setBiome(x, z, this.biome);
} }
} }
// ROAD (0/24) The following is an inefficient placeholder as it is too much work to finish it // ROAD (0/24) The following is an inefficient placeholder as it is too
// much work to finish it
if (plotMinZ+1<=16||roadStartZ<=16&&roadStartZ>0) { if (((plotMinZ + 1) <= 16) || ((roadStartZ <= 16) && (roadStartZ > 0))) {
int start = (int) Math.max(16-plotMinZ-pathsize+1,16-roadStartZ+1); int start = Math.max((16 - plotMinZ - this.pathsize) + 1, (16 - roadStartZ) + 1);
int end = (int) Math.min(16-plotMinZ-1,16-roadStartZ+pathsize); int end = Math.min(16 - plotMinZ - 1, (16 - roadStartZ) + this.pathsize);
if (start>=0 && start<=16 && end <0) if ((start >= 0) && (start <= 16) && (end < 0)) {
end = 16; end = 16;
setCuboidRegion(0, 16, 1, roadheight+1, Math.max(start,0),Math.min(16,end), floor1); }
setCuboidRegion(0, 16, 1, this.roadheight + 1, Math.max(start, 0), Math.min(16, end), this.floor1);
} }
if (plotMinX+1<=16||roadStartX<=16&&roadStartX>0) { if (((plotMinX + 1) <= 16) || ((roadStartX <= 16) && (roadStartX > 0))) {
int start = (int) Math.max(16-plotMinX-pathsize+1,16-roadStartX+1); int start = Math.max((16 - plotMinX - this.pathsize) + 1, (16 - roadStartX) + 1);
int end = (int) Math.min(16-plotMinX-1,16-roadStartX+pathsize); int end = Math.min(16 - plotMinX - 1, (16 - roadStartX) + this.pathsize);
if (start>=0 && start<=16 && end <0) if ((start >= 0) && (start <= 16) && (end < 0)) {
end = 16; end = 16;
setCuboidRegion(Math.max(start,0), Math.min(16,end), 1, roadheight+1, 0, 16, floor1); }
setCuboidRegion(Math.max(start, 0), Math.min(16, end), 1, this.roadheight + 1, 0, 16, this.floor1);
} }
// ROAD STRIPES // ROAD STRIPES
if (pathsize>4&&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) }
end = 16-roadStartX+1; if ((roadStartX - 1) <= 16) {
else end = (16 - roadStartX) + 1;
} 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, wallheight, wallheight+1, 16-value, 16-value+1, floor2); // setCuboidRegion(0, end, this.wallheight, this.wallheight + 1, 16 - value, (16 - value) + 1, this.floor2); //
setCuboidRegion(start, 16, wallheight, wallheight+1, 16-value, 16-value+1, floor2); // setCuboidRegion(start, 16, this.wallheight, this.wallheight + 1, 16 - value, (16 - value) + 1, this.floor2); //
} }
if ((plotMinX+2)<=16) { if ((plotMinX + 2) <= 16) {
int value = (plotMinX+2); int value = (plotMinX + 2);
int start,end; int start, end;
if (plotMinZ+2<=16) if ((plotMinZ + 2) <= 16) {
start = 16-plotMinZ-1; start = 16 - plotMinZ - 1;
else } else {
start = 16; start = 16;
if (roadStartZ-1<=16) }
end = 16-roadStartZ+1; if ((roadStartZ - 1) <= 16) {
else end = (16 - roadStartZ) + 1;
} else {
end = 0; end = 0;
if (!(plotMinZ+2<=16||roadStartZ-1<=16)) { }
if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) {
start = 0; start = 0;
} }
setCuboidRegion( 16-value, 16-value+1,wallheight, wallheight+1, 0, end, floor2); // setCuboidRegion(16 - value, (16 - value) + 1, this.wallheight, this.wallheight + 1, 0, end, this.floor2); //
setCuboidRegion( 16-value, 16-value+1, wallheight, wallheight+1,start, 16, floor2); // setCuboidRegion(16 - value, (16 - value) + 1, this.wallheight, this.wallheight + 1, start, 16, this.floor2); //
} }
if (roadStartZ<=16&&roadStartZ>1) { if ((roadStartZ <= 16) && (roadStartZ > 1)) {
int val = roadStartZ; int val = roadStartZ;
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) }
end = 16-roadStartX+1; if ((roadStartX - 1) <= 16) {
else end = (16 - roadStartX) + 1;
} 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, wallheight, wallheight+1, 16-val+1, 16-val+2, floor2); setCuboidRegion(0, end, this.wallheight, this.wallheight + 1, (16 - val) + 1, (16 - val) + 2, this.floor2);
setCuboidRegion(start, 16, wallheight, wallheight+1, 16-val+1, 16-val+2, floor2); setCuboidRegion(start, 16, this.wallheight, this.wallheight + 1, (16 - val) + 1, (16 - val) + 2, this.floor2);
} }
if (roadStartX<=16&&roadStartX>1) { if ((roadStartX <= 16) && (roadStartX > 1)) {
int val = roadStartX; int val = roadStartX;
int start,end; int start, end;
if (plotMinZ+2<=16) if ((plotMinZ + 2) <= 16) {
start = 16-plotMinZ-1; start = 16 - plotMinZ - 1;
else } else {
start = 16; start = 16;
if (roadStartZ-1<=16) }
end = 16-roadStartZ+1; if ((roadStartZ - 1) <= 16) {
else end = (16 - roadStartZ) + 1;
} else {
end = 0; end = 0;
if (!(plotMinZ+2<=16||roadStartZ-1<=16)) { }
if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) {
start = 0; start = 0;
} }
setCuboidRegion(16-val+1, 16-val+2, wallheight, wallheight+1, 0, end, floor2); // setCuboidRegion((16 - val) + 1, (16 - val) + 2, this.wallheight, this.wallheight + 1, 0, end, this.floor2); //
setCuboidRegion(16-val+1, 16-val+2, wallheight, wallheight+1, start, 16, floor2); // setCuboidRegion((16 - val) + 1, (16 - val) + 2, this.wallheight, this.wallheight + 1, start, 16, this.floor2); //
} }
} }
// Plot filling (28/28 cuboids) (10x2 + 4x2) // Plot filling (28/28 cuboids) (10x2 + 4x2)
if (plotsize>16) { if (this.plotsize > 16) {
if (roadStartX<=16) { if (roadStartX <= 16) {
if (roadStartZ<=16) { if (roadStartZ <= 16) {
setCuboidRegion(0, 16-roadStartX, 1, plotheight, 0, 16-roadStartZ, filling); setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 0, 16 - roadStartZ, this.filling);
setCuboidRegion(0, 16-roadStartX, plotheight, plotheight+1, 0, 16-roadStartZ, plotfloors); setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors);
} }
if (plotMinZ<=16) { if (plotMinZ <= 16) {
setCuboidRegion(0, 16-roadStartX, 1, plotheight, 16-plotMinZ, 16, filling); setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 16 - plotMinZ, 16, this.filling);
setCuboidRegion(0, 16-roadStartX, plotheight, plotheight+1, 16-plotMinZ, 16, plotfloors); setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors);
} }
} } else {
else { if (roadStartZ <= 16) {
if (roadStartZ<=16) { if (plotMinX > 16) {
if (plotMinX>16) { setCuboidRegion(0, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.filling);
setCuboidRegion(0, 16, 1, plotheight, 0, 16-roadStartZ, filling); setCuboidRegion(0, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors);
setCuboidRegion(0, 16, plotheight, plotheight+1, 0, 16-roadStartZ, plotfloors);
} }
} }
} }
if (plotMinX<=16) { if (plotMinX <= 16) {
if (plotMinZ<=16) { if (plotMinZ <= 16) {
setCuboidRegion(16-plotMinX, 16, 1, plotheight, 16-plotMinZ, 16, filling); setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 16 - plotMinZ, 16, this.filling);
setCuboidRegion(16-plotMinX, 16, plotheight, plotheight+1, 16-plotMinZ, 16, plotfloors); setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors);
} else {
int z = 16 - roadStartZ;
if (z < 0) {
z = 16;
}
setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, z, this.filling);
setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, z, this.plotfloors);
} }
else { if (roadStartZ <= 16) {
int z = (int) (16-roadStartZ); setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.filling);
if (z<0) setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors);
z=16; } else {
setCuboidRegion(16-plotMinX, 16, 1, plotheight, 0, z, filling); if (roadStartX <= 16) {
setCuboidRegion(16-plotMinX, 16, plotheight, plotheight+1, 0, z, plotfloors); if (plotMinZ > 16) {
int x = 16 - roadStartX;
if (x < 0) {
x = 16;
}
setCuboidRegion(0, x, 1, this.plotheight, 0, 16, this.filling);
setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, 16, this.plotfloors);
}
}
} }
if (roadStartZ<=16) { } else {
setCuboidRegion(16-plotMinX, 16, 1, plotheight, 0, 16-roadStartZ, filling); if (plotMinZ <= 16) {
setCuboidRegion(16-plotMinX, 16, plotheight, plotheight+1, 0, 16-roadStartZ, plotfloors); if (roadStartX > 16) {
} int x = 16 - roadStartX;
else { if (x < 0) {
if (roadStartX<=16) { x = 16;
if (plotMinZ>16) { }
int x = (int) (16-roadStartX); setCuboidRegion(0, x, 1, this.plotheight, 16 - plotMinZ, 16, this.filling);
if (x<0) setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors);
x=16; }
setCuboidRegion(0, x, 1, plotheight, 0, 16, filling); } else {
setCuboidRegion(0, x, plotheight,plotheight+1, 0, 16, plotfloors); if (roadStartZ > 16) {
int x = 16 - roadStartX;
if (x < 0) {
x = 16;
}
int z = 16 - roadStartZ;
if (z < 0) {
z = 16;
}
if (roadStartX > 16) {
setCuboidRegion(0, x, 1, this.plotheight, 0, z, this.filling);
setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, z, this.plotfloors);
} else {
setCuboidRegion(0, x, 1, this.plotheight, 0, z, this.filling);
setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, z, this.plotfloors);
} }
} }
} }
} }
else { } else {
if (plotMinZ<=16) { if (roadStartX <= 16) {
if (roadStartX>16) { if (roadStartZ <= 16) {
int x = (int) (16-roadStartX); setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 0, 16 - roadStartZ, this.filling);
if (x<0) setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors);
x=16;
setCuboidRegion(0, x, 1, plotheight, 16-plotMinZ, 16, filling);
setCuboidRegion(0, x, plotheight, plotheight+1, 16-plotMinZ, 16, plotfloors);
}
} }
else { if (plotMinZ <= 16) {
if (roadStartZ>16) { setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 16 - plotMinZ, 16, this.filling);
int x = (int) (16-roadStartX); setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors);
if (x<0)
x=16;
int z = (int) (16-roadStartZ);
if (z<0)
z=16;
if (roadStartX>16) {
setCuboidRegion(0, x, 1, plotheight, 0, z, filling);
setCuboidRegion(0, x, plotheight, plotheight+1, 0, z, plotfloors);
}
else {
setCuboidRegion(0, x, 1, plotheight, 0, z, filling);
setCuboidRegion(0, x, plotheight, plotheight+1, 0, z, plotfloors);
}
}
} }
} }
} if (plotMinX <= 16) {
else { if (plotMinZ <= 16) {
if (roadStartX<=16) { setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 16 - plotMinZ, 16, this.filling);
if (roadStartZ<=16) { setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors);
setCuboidRegion(0, 16-roadStartX, 1, plotheight, 0, 16-roadStartZ, filling);
setCuboidRegion(0, 16-roadStartX, plotheight, plotheight+1, 0, 16-roadStartZ, plotfloors);
} }
if (plotMinZ<=16) { if (roadStartZ <= 16) {
setCuboidRegion(0, 16-roadStartX, 1, plotheight, 16-plotMinZ, 16, filling); setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.filling);
setCuboidRegion(0, 16-roadStartX, plotheight, plotheight+1, 16-plotMinZ, 16, plotfloors); setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors);
}
}
if (plotMinX<=16) {
if (plotMinZ<=16) {
setCuboidRegion(16-plotMinX, 16, 1, plotheight, 16-plotMinZ, 16, filling);
setCuboidRegion(16-plotMinX, 16, plotheight, plotheight+1, 16-plotMinZ, 16, plotfloors);
}
if (roadStartZ<=16) {
setCuboidRegion(16-plotMinX, 16, 1, plotheight, 0, 16-roadStartZ, filling);
setCuboidRegion(16-plotMinX, 16, plotheight, plotheight+1, 0, 16-roadStartZ, plotfloors);
} }
} }
} }
// WALLS (16/16 cuboids) // WALLS (16/16 cuboids)
if (pathsize>0) { if (this.pathsize > 0) {
if (plotMinZ+1<=16) { if ((plotMinZ + 1) <= 16) {
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) }
end = 16-roadStartX+1; if ((roadStartX - 1) <= 16) {
else end = (16 - roadStartX) + 1;
} 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, 1, wallheight+1, 16-plotMinZ-1, 16-plotMinZ, wallfilling); setCuboidRegion(0, end, 1, this.wallheight + 1, 16 - plotMinZ - 1, 16 - plotMinZ, this.wallfilling);
setCuboidRegion(0, end, wallheight+1, wallheight+2, 16-plotMinZ-1, 16-plotMinZ, wall); setCuboidRegion(0, end, this.wallheight + 1, this.wallheight + 2, 16 - plotMinZ - 1, 16 - plotMinZ, this.wall);
setCuboidRegion(start, 16, 1, wallheight+1, 16-plotMinZ-1, 16-plotMinZ, wallfilling); setCuboidRegion(start, 16, 1, this.wallheight + 1, 16 - plotMinZ - 1, 16 - plotMinZ, this.wallfilling);
setCuboidRegion(start, 16, wallheight+1, wallheight+2, 16-plotMinZ-1, 16-plotMinZ, wall); setCuboidRegion(start, 16, this.wallheight + 1, this.wallheight + 2, 16 - plotMinZ - 1, 16 - plotMinZ, this.wall);
} }
if (plotMinX+1<=16) { if ((plotMinX + 1) <= 16) {
int start,end; int start, end;
if (plotMinZ+2<=16) if ((plotMinZ + 2) <= 16) {
start = 16-plotMinZ-1; start = 16 - plotMinZ - 1;
else } else {
start = 16; start = 16;
if (roadStartZ-1<=16) }
end = 16-roadStartZ+1; if ((roadStartZ - 1) <= 16) {
else end = (16 - roadStartZ) + 1;
} else {
end = 0; end = 0;
if (!(plotMinZ+2<=16||roadStartZ-1<=16)) { }
if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) {
start = 0; start = 0;
} }
setCuboidRegion( 16-plotMinX-1, 16-plotMinX, 1, wallheight+1,0, end, wallfilling); setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, 1, this.wallheight + 1, 0, end, this.wallfilling);
setCuboidRegion( 16-plotMinX-1, 16-plotMinX,wallheight+1, wallheight+2, 0, end, wall); setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, this.wallheight + 1, this.wallheight + 2, 0, end, this.wall);
setCuboidRegion(16-plotMinX-1, 16-plotMinX, 1, wallheight+1, start, 16, wallfilling); setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, 1, this.wallheight + 1, start, 16, this.wallfilling);
setCuboidRegion( 16-plotMinX-1, 16-plotMinX, wallheight+1, wallheight+2,start, 16, wall); setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, this.wallheight + 1, this.wallheight + 2, start, 16, this.wall);
} }
if (roadStartZ<=16&&roadStartZ>0) { if ((roadStartZ <= 16) && (roadStartZ > 0)) {
int start,end; int start, end;
if (plotMinX+1<=16) if ((plotMinX + 1) <= 16) {
start = 16-plotMinX; start = 16 - plotMinX;
else } else {
start = 16; start = 16;
if (roadStartX+1<=16) }
end = 16-roadStartX+1; if ((roadStartX + 1) <= 16) {
else end = (16 - roadStartX) + 1;
} else {
end = 0; end = 0;
if (!(plotMinX+1<=16||roadStartX<=16)) { }
if (!(((plotMinX + 1) <= 16) || (roadStartX <= 16))) {
start = 0; start = 0;
} }
setCuboidRegion(0, end, 1, wallheight+1, 16-roadStartZ, 16-roadStartZ+1, wallfilling); setCuboidRegion(0, end, 1, this.wallheight + 1, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wallfilling);
setCuboidRegion(0, end, wallheight+1, wallheight+2, 16-roadStartZ, 16-roadStartZ+1, wall); setCuboidRegion(0, end, this.wallheight + 1, this.wallheight + 2, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wall);
setCuboidRegion(start, 16, 1, wallheight+1, 16-roadStartZ, 16-roadStartZ+1, wallfilling); setCuboidRegion(start, 16, 1, this.wallheight + 1, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wallfilling);
setCuboidRegion(start, 16, wallheight+1, wallheight+2, 16-roadStartZ, 16-roadStartZ+1, wall); setCuboidRegion(start, 16, this.wallheight + 1, this.wallheight + 2, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wall);
} }
if (roadStartX<=16&&roadStartX>0) { if ((roadStartX <= 16) && (roadStartX > 0)) {
int start,end; int start, end;
if (plotMinZ+1<=16) if ((plotMinZ + 1) <= 16) {
start = 16-plotMinZ; start = 16 - plotMinZ;
else } else {
start = 16; start = 16;
if (roadStartZ+1<=16) }
end = 16-roadStartZ+1; if ((roadStartZ + 1) <= 16) {
else end = (16 - roadStartZ) + 1;
} else {
end = 0; end = 0;
if (!(plotMinZ+1<=16||roadStartZ+1<=16)) { }
if (!(((plotMinZ + 1) <= 16) || ((roadStartZ + 1) <= 16))) {
start = 0; start = 0;
} }
setCuboidRegion( 16-roadStartX, 16-roadStartX+1, 1, wallheight+1,0, end, wallfilling); setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, 1, this.wallheight + 1, 0, end, this.wallfilling);
setCuboidRegion( 16-roadStartX, 16-roadStartX+1,wallheight+1, roadheight+2,0, end, wall); setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, this.wallheight + 1, this.roadheight + 2, 0, end, this.wall);
setCuboidRegion( 16-roadStartX, 16-roadStartX+1, 1, wallheight+1, start, 16,wallfilling); setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, 1, this.wallheight + 1, start, 16, this.wallfilling);
setCuboidRegion( 16-roadStartX, 16-roadStartX+1,wallheight+1, wallheight+2, start, 16, wall); setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, this.wallheight + 1, this.wallheight + 2, start, 16, this.wall);
} }
} }
return result; return this.result;
}
@SuppressWarnings({ "deprecation", "unused" })
private void setBlock(short[][] result, int x, int y, int z,
Material material) {
setBlock(result, x, y, z, (short) material.getId());
} }
private void setBlock(short[][] result, int x, int y, int z, short blkid) { private void setBlock(short[][] result, int x, int y, int z, short blkid) {

View File

@ -1,15 +1,14 @@
package com.intellectualcrafters.plot; package com.intellectualcrafters.plot;
import org.bukkit.Bukkit; import java.util.Random;
import org.bukkit.Chunk; import org.bukkit.Chunk;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.generator.BlockPopulator; import org.bukkit.generator.BlockPopulator;
import java.util.Random;
/** /**
* TODO recode this class * TODO recode this class Fuck you PlotMe!
* Fuck you PlotMe! *
* @author Citymonstret * @author Citymonstret
* *
*/ */
@ -17,9 +16,10 @@ public class XPopulator extends BlockPopulator {
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=state; long a = this.state;
state = xorShift64(a); this.state = xorShift64(a);
return a; return a;
} }
@ -31,13 +31,14 @@ public class XPopulator extends BlockPopulator {
} }
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, short id, byte data, World w) { public void setCuboidRegion(int x1, int x2, int y1, int y2, int z1, int z2, short id, byte data, World w) {
if (data==0) if (data == 0) {
return; return;
}
for (int x = x1; x < x2; x++) { for (int x = x1; x < x2; x++) {
for (int z = z1; z < z2; z++) { for (int z = z1; z < z2; z++) {
for (int y = y1; y < y2; y++) { for (int y = y1; y < y2; y++) {
@ -46,29 +47,31 @@ public class XPopulator extends BlockPopulator {
} }
} }
} }
private void setCuboidRegion(int x1, int x2, int y1, int y2, int z1, int z2, short[] id, short[] v, World w) { private void setCuboidRegion(int x1, int x2, int y1, int y2, int z1, int z2, short[] id, short[] v, World w) {
if (id.length==1) { if (id.length == 1) {
setCuboidRegion(x1,x2,y1,y2,z1,z2,id[0],(byte) v[0],w); setCuboidRegion(x1, x2, y1, y2, z1, z2, id[0], (byte) v[0], w);
} } else {
else {
for (int x = x1; x < x2; x++) { for (int x = x1; x < x2; x++) {
for (int z = z1; z < z2; z++) { for (int z = z1; z < z2; z++) {
for (int y = y1; y < y2; y++) { for (int y = y1; y < y2; y++) {
int i = random(id.length); int i = random(id.length);
if (v[i]!=0) if (v[i] != 0) {
setBlock(w, x, y, z, id[i], (byte) v[i]); setBlock(w, x, y, z, id[i], (byte) v[i]);
}
} }
} }
} }
} }
} }
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 };
} }
private int plotsize, pathsize, plotheight, wallheight, roadheight, size; private int plotsize, pathsize, plotheight, wallheight, roadheight, size;
@ -77,347 +80,365 @@ public class XPopulator extends BlockPopulator {
private short[] p_id, p_v, f_id, f_v; private short[] p_id, p_v, f_id, f_v;
private double pathWidthLower; private double pathWidthLower;
private PlotWorld plotworld; private PlotWorld plotworld;
public XPopulator(PlotWorld plotworld) { public XPopulator(PlotWorld plotworld) {
this.plotworld = plotworld; this.plotworld = plotworld;
plotsize = plotworld.PLOT_WIDTH; this.plotsize = plotworld.PLOT_WIDTH;
pathsize = plotworld.ROAD_WIDTH; this.pathsize = plotworld.ROAD_WIDTH;
plotheight = plotworld.PLOT_HEIGHT; this.plotheight = plotworld.PLOT_HEIGHT;
wallheight = plotworld.WALL_HEIGHT; this.wallheight = plotworld.WALL_HEIGHT;
roadheight = plotworld.ROAD_HEIGHT; this.roadheight = plotworld.ROAD_HEIGHT;
size = pathsize + plotsize; this.size = this.pathsize + this.plotsize;
// WALL // WALL
short[] result_w = getBlock(plotworld.WALL_BLOCK); short[] result_w = getBlock(plotworld.WALL_BLOCK);
w_id = result_w[0]; this.w_id = result_w[0];
w_v = (byte) result_w[1]; this.w_v = (byte) result_w[1];
// WALL FILLING // WALL FILLING
short[] result_wf = getBlock(plotworld.WALL_FILLING); short[] result_wf = getBlock(plotworld.WALL_FILLING);
wf_id = result_wf[0]; this.wf_id = result_wf[0];
wf_v = (byte) result_wf[1]; this.wf_v = (byte) result_wf[1];
// ROAD // ROAD
short[] result_f1 = getBlock(plotworld.ROAD_BLOCK); short[] result_f1 = getBlock(plotworld.ROAD_BLOCK);
f1_id = result_f1[0]; this.f1_id = result_f1[0];
f1_v = (byte) result_f1[1]; this.f1_v = (byte) result_f1[1];
// //
// Floor 2 // Floor 2
short[] result_f2 = getBlock(plotworld.ROAD_STRIPES); short[] result_f2 = getBlock(plotworld.ROAD_STRIPES);
f2_id = result_f2[0]; this.f2_id = result_f2[0];
f2_v = (byte) result_f2[1]; this.f2_v = (byte) result_f2[1];
// //
p_id = new short[plotworld.MAIN_BLOCK.length]; this.p_id = new short[plotworld.MAIN_BLOCK.length];
p_v = new short[plotworld.MAIN_BLOCK.length]; this.p_v = new short[plotworld.MAIN_BLOCK.length];
f_id = new short[plotworld.TOP_BLOCK.length]; this.f_id = new short[plotworld.TOP_BLOCK.length];
f_v = new short[plotworld.TOP_BLOCK.length]; this.f_v = new short[plotworld.TOP_BLOCK.length];
for (int i = 0; i < plotworld.MAIN_BLOCK.length; i++) { for (int i = 0; i < plotworld.MAIN_BLOCK.length; i++) {
short[] result = getBlock(plotworld.MAIN_BLOCK[i]); short[] result = getBlock(plotworld.MAIN_BLOCK[i]);
p_id[i] = result[0]; this.p_id[i] = result[0];
p_v[i] = result[1]; this.p_v[i] = result[1];
} }
for (int i = 0; i < plotworld.TOP_BLOCK.length; i++) { for (int i = 0; i < plotworld.TOP_BLOCK.length; i++) {
short[] result = getBlock(plotworld.TOP_BLOCK[i]); short[] result = getBlock(plotworld.TOP_BLOCK[i]);
f_id[i] = result[0]; this.f_id[i] = result[0];
f_v[i] = result[1]; this.f_v[i] = result[1];
} }
pathWidthLower = Math.floor(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;
state = h; this.state = h;
this.X = cx << 4;
X = cx << 4; this.Z = cz << 4;
Z = cz << 4; cx = (cx % this.size) + (8 * this.size);
cx=cx%size+8*size; cz = (cz % this.size) + (8 * this.size);
cz=cz%size+8*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-pathWidthLower-1+8*size), absZ = (cz*16+16-pathWidthLower-1+8*size); int plotMinX = (int) (((absX) % this.size));
int plotMinX = (int) (((absX)%size)); int plotMinZ = (int) (((absZ) % this.size));
int plotMinZ = (int) (((absZ)%size)); int roadStartX = (plotMinX + this.pathsize);
int roadStartX = (plotMinX + pathsize); int roadStartZ = (plotMinZ + this.pathsize);
int roadStartZ = (plotMinZ + pathsize); if (roadStartX >= this.size) {
if (roadStartX>=size) roadStartX -= this.size;
roadStartX-=size; }
if (roadStartZ>=size) if (roadStartZ >= this.size) {
roadStartZ-=size; roadStartZ -= this.size;
}
// ROADS // ROADS
if (plotMinZ+1<=16||roadStartZ<=16&&roadStartZ>0) { if (((plotMinZ + 1) <= 16) || ((roadStartZ <= 16) && (roadStartZ > 0))) {
int start = (int) Math.max(16-plotMinZ-pathsize+1,16-roadStartZ+1); int start = Math.max((16 - plotMinZ - this.pathsize) + 1, (16 - roadStartZ) + 1);
int end = (int) Math.min(16-plotMinZ-1,16-roadStartZ+pathsize); int end = Math.min(16 - plotMinZ - 1, (16 - roadStartZ) + this.pathsize);
if (start>=0 && start<=16 && end <0) if ((start >= 0) && (start <= 16) && (end < 0)) {
end = 16; end = 16;
setCuboidRegion(0, 16, 1, roadheight+1, Math.max(start,0),Math.min(16,end), f1_id, f1_v, w); }
setCuboidRegion(0, 16, 1, this.roadheight + 1, Math.max(start, 0), Math.min(16, end), this.f1_id, this.f1_v, w);
} }
if (plotMinX+1<=16||roadStartX<=16&&roadStartX>0) { if (((plotMinX + 1) <= 16) || ((roadStartX <= 16) && (roadStartX > 0))) {
int start = (int) Math.max(16-plotMinX-pathsize+1,16-roadStartX+1); int start = Math.max((16 - plotMinX - this.pathsize) + 1, (16 - roadStartX) + 1);
int end = (int) Math.min(16-plotMinX-1,16-roadStartX+pathsize); int end = Math.min(16 - plotMinX - 1, (16 - roadStartX) + this.pathsize);
if (start>=0 && start<=16 && end <0) if ((start >= 0) && (start <= 16) && (end < 0)) {
end = 16; end = 16;
setCuboidRegion(Math.max(start,0), Math.min(16,end), 1, roadheight+1, 0, 16, f1_id, f1_v, w); }
setCuboidRegion(Math.max(start, 0), Math.min(16, end), 1, this.roadheight + 1, 0, 16, this.f1_id, this.f1_v, w);
} }
// STRIPES // STRIPES
if (pathsize>4&&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) }
end = 16-roadStartX+1; if ((roadStartX - 1) <= 16) {
else end = (16 - roadStartX) + 1;
} 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, roadheight, roadheight+1, 16-value, 16-value+1, f2_id, f2_v, w); // setCuboidRegion(0, end, this.roadheight, this.roadheight + 1, 16 - value, (16 - value) + 1, this.f2_id, this.f2_v, w); //
setCuboidRegion(start, 16, roadheight, roadheight+1, 16-value, 16-value+1, f2_id, f2_v, w); // setCuboidRegion(start, 16, this.roadheight, this.roadheight + 1, 16 - value, (16 - value) + 1, this.f2_id, this.f2_v, w); //
} }
if ((plotMinX+2)<=16) { if ((plotMinX + 2) <= 16) {
int value = (plotMinX+2); int value = (plotMinX + 2);
int start,end; int start, end;
if (plotMinZ+2<=16) if ((plotMinZ + 2) <= 16) {
start = 16-plotMinZ-1; start = 16 - plotMinZ - 1;
else } else {
start = 16; start = 16;
if (roadStartZ-1<=16) }
end = 16-roadStartZ+1; if ((roadStartZ - 1) <= 16) {
else end = (16 - roadStartZ) + 1;
} else {
end = 0; end = 0;
if (!(plotMinZ+2<=16||roadStartZ-1<=16)) { }
if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) {
start = 0; start = 0;
} }
setCuboidRegion( 16-value, 16-value+1,roadheight, roadheight+1, 0, end, f2_id, f2_v, w); // setCuboidRegion(16 - value, (16 - value) + 1, this.roadheight, this.roadheight + 1, 0, end, this.f2_id, this.f2_v, w); //
setCuboidRegion( 16-value, 16-value+1, roadheight, roadheight+1,start, 16, f2_id, f2_v, w); // setCuboidRegion(16 - value, (16 - value) + 1, this.roadheight, this.roadheight + 1, start, 16, this.f2_id, this.f2_v, w); //
} }
if (roadStartZ<=16&&roadStartZ>1) { if ((roadStartZ <= 16) && (roadStartZ > 1)) {
int val = roadStartZ; int val = roadStartZ;
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) }
end = 16-roadStartX+1; if ((roadStartX - 1) <= 16) {
else end = (16 - roadStartX) + 1;
} 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, roadheight, roadheight+1, 16-val+1, 16-val+2, f2_id, f2_v, w); setCuboidRegion(0, end, this.roadheight, this.roadheight + 1, (16 - val) + 1, (16 - val) + 2, this.f2_id, this.f2_v, w);
setCuboidRegion(start, 16, roadheight, roadheight+1, 16-val+1, 16-val+2, f2_id, f2_v, w); setCuboidRegion(start, 16, this.roadheight, this.roadheight + 1, (16 - val) + 1, (16 - val) + 2, this.f2_id, this.f2_v, w);
} }
if (roadStartX<=16&&roadStartX>1) { if ((roadStartX <= 16) && (roadStartX > 1)) {
int val = roadStartX; int val = roadStartX;
int start,end; int start, end;
if (plotMinZ+2<=16) if ((plotMinZ + 2) <= 16) {
start = 16-plotMinZ-1; start = 16 - plotMinZ - 1;
else } else {
start = 16; start = 16;
if (roadStartZ-1<=16) }
end = 16-roadStartZ+1; if ((roadStartZ - 1) <= 16) {
else end = (16 - roadStartZ) + 1;
} else {
end = 0; end = 0;
if (!(plotMinZ+2<=16||roadStartZ-1<=16)) { }
if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) {
start = 0; start = 0;
} }
setCuboidRegion(16-val+1, 16-val+2, roadheight, roadheight+1, 0, end, f2_id, f2_v, w); // setCuboidRegion((16 - val) + 1, (16 - val) + 2, this.roadheight, this.roadheight + 1, 0, end, this.f2_id, this.f2_v, w); //
setCuboidRegion(16-val+1, 16-val+2, roadheight, roadheight+1, start, 16, f2_id, f2_v, w); // setCuboidRegion((16 - val) + 1, (16 - val) + 2, this.roadheight, this.roadheight + 1, start, 16, this.f2_id, this.f2_v, w); //
} }
} }
// WALLS // WALLS
if (pathsize>0) { if (this.pathsize > 0) {
if (plotMinZ+1<=16) { if ((plotMinZ + 1) <= 16) {
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) }
end = 16-roadStartX+1; if ((roadStartX - 1) <= 16) {
else end = (16 - roadStartX) + 1;
} 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, 1, wallheight+1, 16-plotMinZ-1, 16-plotMinZ, wf_id, wf_v, w); setCuboidRegion(0, end, 1, this.wallheight + 1, 16 - plotMinZ - 1, 16 - plotMinZ, this.wf_id, this.wf_v, w);
setCuboidRegion(0, end, wallheight+1, wallheight+2, 16-plotMinZ-1, 16-plotMinZ, w_id, w_v, w); setCuboidRegion(0, end, this.wallheight + 1, this.wallheight + 2, 16 - plotMinZ - 1, 16 - plotMinZ, this.w_id, this.w_v, w);
setCuboidRegion(start, 16, 1, wallheight+1, 16-plotMinZ-1, 16-plotMinZ, wf_id, wf_v, w); setCuboidRegion(start, 16, 1, this.wallheight + 1, 16 - plotMinZ - 1, 16 - plotMinZ, this.wf_id, this.wf_v, w);
setCuboidRegion(start, 16, wallheight+1, wallheight+2, 16-plotMinZ-1, 16-plotMinZ, w_id, w_v, w); setCuboidRegion(start, 16, this.wallheight + 1, this.wallheight + 2, 16 - plotMinZ - 1, 16 - plotMinZ, this.w_id, this.w_v, w);
} }
if (plotMinX+1<=16) { if ((plotMinX + 1) <= 16) {
int start,end; int start, end;
if (plotMinZ+2<=16) if ((plotMinZ + 2) <= 16) {
start = 16-plotMinZ-1; start = 16 - plotMinZ - 1;
else } else {
start = 16; start = 16;
if (roadStartZ-1<=16) }
end = 16-roadStartZ+1; if ((roadStartZ - 1) <= 16) {
else end = (16 - roadStartZ) + 1;
} else {
end = 0; end = 0;
if (!(plotMinZ+2<=16||roadStartZ-1<=16)) { }
if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) {
start = 0; start = 0;
} }
setCuboidRegion( 16-plotMinX-1, 16-plotMinX, 1, wallheight+1,0, end, wf_id, wf_v, w); setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, 1, this.wallheight + 1, 0, end, this.wf_id, this.wf_v, w);
setCuboidRegion( 16-plotMinX-1, 16-plotMinX,wallheight+1, wallheight+2, 0, end, w_id, w_v, w); setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, this.wallheight + 1, this.wallheight + 2, 0, end, this.w_id, this.w_v, w);
setCuboidRegion(16-plotMinX-1, 16-plotMinX, 1, wallheight+1, start, 16, wf_id, wf_v, w); setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, 1, this.wallheight + 1, start, 16, this.wf_id, this.wf_v, w);
setCuboidRegion( 16-plotMinX-1, 16-plotMinX, wallheight+1, wallheight+2,start, 16, w_id, w_v, w); setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, this.wallheight + 1, this.wallheight + 2, start, 16, this.w_id, this.w_v, w);
} }
if (roadStartZ<=16&&roadStartZ>0) { if ((roadStartZ <= 16) && (roadStartZ > 0)) {
int start,end; int start, end;
if (plotMinX+1<=16) if ((plotMinX + 1) <= 16) {
start = 16-plotMinX; start = 16 - plotMinX;
else } else {
start = 16; start = 16;
if (roadStartX+1<=16) }
end = 16-roadStartX+1; if ((roadStartX + 1) <= 16) {
else end = (16 - roadStartX) + 1;
} else {
end = 0; end = 0;
if (!(plotMinX+1<=16||roadStartX<=16)) { }
if (!(((plotMinX + 1) <= 16) || (roadStartX <= 16))) {
start = 0; start = 0;
} }
setCuboidRegion(0, end, 1, wallheight+1, 16-roadStartZ, 16-roadStartZ+1, wf_id, wf_v, w); setCuboidRegion(0, end, 1, this.wallheight + 1, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wf_id, this.wf_v, w);
setCuboidRegion(0, end, wallheight+1, wallheight+2, 16-roadStartZ, 16-roadStartZ+1, w_id, w_v, w); setCuboidRegion(0, end, this.wallheight + 1, this.wallheight + 2, 16 - roadStartZ, (16 - roadStartZ) + 1, this.w_id, this.w_v, w);
setCuboidRegion(start, 16, 1, wallheight+1, 16-roadStartZ, 16-roadStartZ+1, wf_id, wf_v, w); setCuboidRegion(start, 16, 1, this.wallheight + 1, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wf_id, this.wf_v, w);
setCuboidRegion(start, 16, wallheight+1, wallheight+2, 16-roadStartZ, 16-roadStartZ+1, w_id, w_v, w); setCuboidRegion(start, 16, this.wallheight + 1, this.wallheight + 2, 16 - roadStartZ, (16 - roadStartZ) + 1, this.w_id, this.w_v, w);
} }
if (roadStartX<=16&&roadStartX>0) { if ((roadStartX <= 16) && (roadStartX > 0)) {
int start,end; int start, end;
if (plotMinZ+1<=16) if ((plotMinZ + 1) <= 16) {
start = 16-plotMinZ; start = 16 - plotMinZ;
else } else {
start = 16; start = 16;
if (roadStartZ+1<=16) }
end = 16-roadStartZ+1; if ((roadStartZ + 1) <= 16) {
else end = (16 - roadStartZ) + 1;
} else {
end = 0; end = 0;
if (!(plotMinZ+1<=16||roadStartZ+1<=16)) { }
if (!(((plotMinZ + 1) <= 16) || ((roadStartZ + 1) <= 16))) {
start = 0; start = 0;
} }
setCuboidRegion( 16-roadStartX, 16-roadStartX+1, 1, wallheight+1,0, end, wf_id, wf_v, w); setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, 1, this.wallheight + 1, 0, end, this.wf_id, this.wf_v, w);
setCuboidRegion( 16-roadStartX, 16-roadStartX+1,wallheight+1, roadheight+2,0, end, w_id, w_v, w); setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, this.wallheight + 1, this.roadheight + 2, 0, end, this.w_id, this.w_v, w);
setCuboidRegion( 16-roadStartX, 16-roadStartX+1, 1, wallheight+1, start, 16,wf_id, wf_v, w); setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, 1, this.wallheight + 1, start, 16, this.wf_id, this.wf_v, w);
setCuboidRegion( 16-roadStartX, 16-roadStartX+1,wallheight+1, wallheight+2, start, 16, w_id, w_v, w); setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, this.wallheight + 1, this.wallheight + 2, start, 16, this.w_id, this.w_v, w);
} }
} }
// PLOT // PLOT
if (plotsize>16) { if (this.plotsize > 16) {
if (roadStartX<=16) { if (roadStartX <= 16) {
if (roadStartZ<=16) { if (roadStartZ <= 16) {
setCuboidRegion(0, 16-roadStartX, 1, plotheight, 0, 16-roadStartZ, p_id, p_v, w); setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 0, 16 - roadStartZ, this.p_id, this.p_v, w);
setCuboidRegion(0, 16-roadStartX, plotheight, plotheight+1, 0, 16-roadStartZ, f_id, f_v, w); setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.f_id, this.f_v, w);
} }
if (plotMinZ<=16) { if (plotMinZ <= 16) {
setCuboidRegion(0, 16-roadStartX, 1, plotheight, 16-plotMinZ, 16, p_id, p_v, w); setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 16 - plotMinZ, 16, this.p_id, this.p_v, w);
setCuboidRegion(0, 16-roadStartX, plotheight, plotheight+1, 16-plotMinZ, 16, f_id, f_v, w); setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.f_id, this.f_v, w);
} }
} } else {
else { if (roadStartZ <= 16) {
if (roadStartZ<=16) { if (plotMinX > 16) {
if (plotMinX>16) { setCuboidRegion(0, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.p_id, this.p_v, w);
setCuboidRegion(0, 16, 1, plotheight, 0, 16-roadStartZ, p_id, p_v, w); setCuboidRegion(0, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.f_id, this.f_v, w);
setCuboidRegion(0, 16, plotheight, plotheight+1, 0, 16-roadStartZ, f_id, f_v, w);
} }
} }
} }
if (plotMinX<=16) { if (plotMinX <= 16) {
if (plotMinZ<=16) { if (plotMinZ <= 16) {
setCuboidRegion(16-plotMinX, 16, 1, plotheight, 16-plotMinZ, 16, p_id, p_v, w); setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 16 - plotMinZ, 16, this.p_id, this.p_v, w);
setCuboidRegion(16-plotMinX, 16, plotheight, plotheight+1, 16-plotMinZ, 16, f_id, f_v, w); setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.f_id, this.f_v, w);
} else {
int z = 16 - roadStartZ;
if (z < 0) {
z = 16;
}
setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, z, this.p_id, this.p_v, w);
setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, z, this.f_id, this.f_v, w);
} }
else { if (roadStartZ <= 16) {
int z = (int) (16-roadStartZ); setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.p_id, this.p_v, w);
if (z<0) setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.f_id, this.f_v, w);
z=16; } else {
setCuboidRegion(16-plotMinX, 16, 1, plotheight, 0, z, p_id, p_v, w); if (roadStartX <= 16) {
setCuboidRegion(16-plotMinX, 16, plotheight, plotheight+1, 0, z, f_id, f_v, w); if (plotMinZ > 16) {
int x = 16 - roadStartX;
if (x < 0) {
x = 16;
}
setCuboidRegion(0, x, 1, this.plotheight, 0, 16, this.p_id, this.p_v, w);
setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, 16, this.f_id, this.f_v, w);
}
}
} }
if (roadStartZ<=16) { } else {
setCuboidRegion(16-plotMinX, 16, 1, plotheight, 0, 16-roadStartZ, p_id, p_v, w); if (plotMinZ <= 16) {
setCuboidRegion(16-plotMinX, 16, plotheight, plotheight+1, 0, 16-roadStartZ, f_id, f_v, w); if (roadStartX > 16) {
} int x = 16 - roadStartX;
else { if (x < 0) {
if (roadStartX<=16) { x = 16;
if (plotMinZ>16) { }
int x = (int) (16-roadStartX); setCuboidRegion(0, x, 1, this.plotheight, 16 - plotMinZ, 16, this.p_id, this.p_v, w);
if (x<0) setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.f_id, this.f_v, w);
x=16; }
setCuboidRegion(0, x, 1, plotheight, 0, 16, p_id, p_v, w); } else {
setCuboidRegion(0, x, plotheight,plotheight+1, 0, 16, f_id, f_v, w); if (roadStartZ > 16) {
int x = 16 - roadStartX;
if (x < 0) {
x = 16;
}
int z = 16 - roadStartZ;
if (z < 0) {
z = 16;
}
if (roadStartX > 16) {
setCuboidRegion(0, x, 1, this.plotheight, 0, z, this.p_id, this.p_v, w);
setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, z, this.f_id, this.f_v, w);
} else {
setCuboidRegion(0, x, 1, this.plotheight, 0, z, this.p_id, this.p_v, w);
setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, z, this.f_id, this.f_v, w);
} }
} }
} }
} }
else { } else {
if (plotMinZ<=16) { if (roadStartX <= 16) {
if (roadStartX>16) { if (roadStartZ <= 16) {
int x = (int) (16-roadStartX); setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 0, 16 - roadStartZ, this.p_id, this.p_v, w);
if (x<0) setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.f_id, this.f_v, w);
x=16;
setCuboidRegion(0, x, 1, plotheight, 16-plotMinZ, 16, p_id, p_v, w);
setCuboidRegion(0, x, plotheight, plotheight+1, 16-plotMinZ, 16, f_id, f_v, w);
}
} }
else { if (plotMinZ <= 16) {
if (roadStartZ>16) { setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 16 - plotMinZ, 16, this.p_id, this.p_v, w);
int x = (int) (16-roadStartX); setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.f_id, this.f_v, w);
if (x<0) }
x=16; }
int z = (int) (16-roadStartZ); if (plotMinX <= 16) {
if (z<0) if (plotMinZ <= 16) {
z=16; setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 16 - plotMinZ, 16, this.p_id, this.p_v, w);
if (roadStartX>16) { setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.f_id, this.f_v, w);
setCuboidRegion(0, x, 1, plotheight, 0, z, p_id, p_v, w); }
setCuboidRegion(0, x, plotheight, plotheight+1, 0, z, f_id, f_v, w); if (roadStartZ <= 16) {
} setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.p_id, this.p_v, w);
else { setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.f_id, this.f_v, w);
setCuboidRegion(0, x, 1, plotheight, 0, z, p_id, p_v, w);
setCuboidRegion(0, x, plotheight, plotheight+1, 0, z, f_id, f_v, w);
}
}
} }
} }
} }
else { }
if (roadStartX<=16) {
if (roadStartZ<=16) {
setCuboidRegion(0, 16-roadStartX, 1, plotheight, 0, 16-roadStartZ, p_id, p_v, w);
setCuboidRegion(0, 16-roadStartX, plotheight, plotheight+1, 0, 16-roadStartZ, f_id, f_v, w);
}
if (plotMinZ<=16) {
setCuboidRegion(0, 16-roadStartX, 1, plotheight, 16-plotMinZ, 16, p_id, p_v, w);
setCuboidRegion(0, 16-roadStartX, plotheight, plotheight+1, 16-plotMinZ, 16, f_id, f_v, w);
}
}
if (plotMinX<=16) {
if (plotMinZ<=16) {
setCuboidRegion(16-plotMinX, 16, 1, plotheight, 16-plotMinZ, 16, p_id, p_v, w);
setCuboidRegion(16-plotMinX, 16, plotheight, plotheight+1, 16-plotMinZ, 16, f_id, f_v, w);
}
if (roadStartZ<=16) {
setCuboidRegion(16-plotMinX, 16, 1, plotheight, 0, 16-roadStartZ, p_id, p_v, w);
setCuboidRegion(16-plotMinX, 16, plotheight, plotheight+1, 0, 16-roadStartZ, f_id, f_v, 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(X+x, y, Z+z).setData(val, false); w.getBlockAt(this.X + x, y, this.Z + z).setData(val, false);
} }
} }

View File

@ -9,93 +9,109 @@
package com.intellectualcrafters.plot.api; package com.intellectualcrafters.plot.api;
import com.intellectualcrafters.plot.*; import java.util.ArrayList;
import java.util.Set;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import com.intellectualcrafters.plot.C;
import com.intellectualcrafters.plot.Flag;
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.PlotMain;
import com.intellectualcrafters.plot.PlotWorld;
import com.intellectualcrafters.plot.commands.MainCommand; import com.intellectualcrafters.plot.commands.MainCommand;
import com.intellectualcrafters.plot.commands.SubCommand; import com.intellectualcrafters.plot.commands.SubCommand;
import java.util.ArrayList;
import java.util.Set;
/** /**
* The plotMain api class. * The plotMain api class.
*
* @author Citymonstret * @author Citymonstret
*/ */
@SuppressWarnings({"unused", "javadoc"}) @SuppressWarnings({ "unused", "javadoc" })
public class PlotAPI { public class PlotAPI {
//To perform bukkit operations correctly. // To access plotMain stuffz.
private JavaPlugin plugin; private PlotMain plotMain;
//To access plotMain stuffz. // Reference
private PlotMain plotMain; public static final String ADMIN_PERMISSION = "plots.admin";
//Reference
public static final String ADMIN_PERMISSION = "plots.admin";
/**
* Constructor. Insert any Plugin.
*
* @param plugin
*/
public PlotAPI(JavaPlugin plugin) {
this.plotMain = JavaPlugin.getPlugin(PlotMain.class);
}
/** /**
* Constructor. Insert any Plugin. * Send a message to a player.
* @param plugin *
*/ * @param player
public PlotAPI(JavaPlugin plugin) { * @param c
this.plugin = plugin; * (Caption)
this.plotMain = JavaPlugin.getPlugin(PlotMain.class); */
} public void sendMessage(Player player, C c) {
/**
* Send a message to a player.
* @param player
* @param c (Caption)
*/
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 string * @param player
*/ * @param string
public void sendMessage(Player player, String string) { */
PlayerFunctions.sendMessage(player, string); public void sendMessage(Player player, String 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) { */
PlotMain.sendConsoleSenderMessage(msg); public void sendConsoleMessage(String msg) {
} PlotMain.sendConsoleSenderMessage(msg);
}
/**
* Send a message to the console
*
* @param c
* (Caption)
*/
public void sendConsoleMessage(C c) {
sendConsoleMessage(c.s());
}
/**
* Register a flag for use in plots
*
* @param flag
*/
public void registerFlag(Flag flag) {
PlotMain.registerFlag(flag);
}
/**
* get all the currently registered flags
*
* @return array of Flag[]
*/
public Flag[] getRegisteredFlags() {
return PlotMain.getFlags().toArray(new Flag[0]);
}
/**
* Send a message to the console
* @param c (Caption)
*/
public void sendConsoleMessage(C c) {
sendConsoleMessage(c.s());
}
/**
* Register a flag for use in plots
* @param flag
*/
public void registerFlag(Flag flag) {
PlotMain.registerFlag(flag);
}
/**
* get all the currently registered flags
* @return array of Flag[]
*/
public Flag[] getRegisteredFlags() {
return PlotMain.getFlags().toArray(new Flag[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
@ -105,81 +121,98 @@ public class PlotAPI {
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 *
* @return plot if found, otherwise it creates a temporary plot- * @param l
*/ * @return plot if found, otherwise it creates a temporary plot-
public Plot getPlot(Location l) { */
return PlotHelper.getCurrentPlot(l); public Plot getPlot(Location l) {
} return PlotHelper.getCurrentPlot(l);
}
/** /**
* Get a plot based on the player location * Get a plot based on the player location
* @param player *
* @return plot if found, otherwise it creates a temporary plot * @param player
*/ * @return plot if found, otherwise it creates a temporary plot
public Plot getPlot(Player player) { */
return this.getPlot(player.getLocation()); public Plot getPlot(Player player) {
} 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 *
* @return true if player has a plot, false if not. * @param player
*/ * @return true if player has a plot, false if not.
public boolean hasPlot(World world, Player player) { */
return getPlots(world, player, true) != null && getPlots(world, player, true).length > 0; public boolean hasPlot(World world, Player player) {
} return (getPlots(world, player, true) != null) && (getPlots(world, player, true).length > 0);
}
/** /**
* Get all plots for the player * Get all plots for the player
* @param plr to search for *
* @param just_owner should we just search for owner? Or with rights? * @param plr
* to search for
* @param just_owner
* should we just search for owner? Or with rights?
*/ */
public Plot[] getPlots(World world, Player plr, boolean just_owner) { 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 to get plots of *
* @param world
* 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 (to check if plot world) *
* @param 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 (to get settings of) *
* @return PlotWorld class for ther world * @param world
* ! will return null if not a plot world * (to get settings of)
* @return PlotWorld class for ther world ! will return null if not a plot
* world
*/ */
public PlotWorld getWorldSettings(World world) { public PlotWorld getWorldSettings(World world) {
return PlotMain.getWorldSettings(world); return PlotMain.getWorldSettings(world);
@ -187,20 +220,18 @@ public class PlotAPI {
/** /**
* 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[] { return new Location[] { PlotHelper.getPlotBottomLoc(world, p.id), PlotHelper.getPlotTopLoc(world, p.id), PlotHelper.getPlotHome(world, p.id) };
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
*/ */
@ -210,61 +241,57 @@ public class PlotAPI {
/** /**
* 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 *
* @return true if the player is in a plot, false if not- * @param player
*/ * @return true if the player is in a plot, false if not-
public boolean isInPlot(Player player) { */
return PlayerFunctions.isInPlot(player); public boolean isInPlot(Player player) {
} return PlayerFunctions.isInPlot(player);
}
/** /**
* Register a subcommand * Register a subcommand
* @param c *
*/ * @param c
public void registerCommand(SubCommand c) { */
MainCommand.subCommands.add(c); public void registerCommand(SubCommand c) {
} MainCommand.subCommands.add(c);
}
/** /**
* Get the plotMain class * Get the plotMain class
* @return PlotMain Class *
*/ * @return PlotMain Class
public PlotMain getPlotMain() { */
return this.plotMain; public PlotMain getPlotMain() {
} return this.plotMain;
}
/**
* Get the inserted plugin
* @return Plugin.
* @deprecated
*/
@SuppressWarnings("unused")
private JavaPlugin getPlugin() {
return this.plugin;
}
/** /**
* Get the player plot count * Get the player plot count
*
* @param player * @param player
* @return * @return
*/ */
@ -274,6 +301,7 @@ public class PlotAPI {
/** /**
* 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
*/ */
@ -283,6 +311,7 @@ public class PlotAPI {
/** /**
* 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
*/ */

View File

@ -9,6 +9,10 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import org.bukkit.Bukkit;
import org.bukkit.World;
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;
@ -16,10 +20,6 @@ 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 org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.entity.Player;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public class Auto extends SubCommand { public class Auto extends SubCommand {
@ -27,62 +27,60 @@ public class Auto extends SubCommand {
super("auto", "plots.auto", "Claim the nearest plot", "auto", "a", CommandCategory.CLAIMING); super("auto", "plots.auto", "Claim the nearest plot", "auto", "a", CommandCategory.CLAIMING);
} }
public boolean execute(Player plr, String ... args) { @Override
public boolean execute(Player plr, String... args) {
World world; World world;
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 {
if (args.length==1) { if (args.length == 1) {
world = Bukkit.getWorld(args[0]); world = Bukkit.getWorld(args[0]);
if (world!=null) { if (world != null) {
if (!PlotMain.isPlotWorld(world)) { if (!PlotMain.isPlotWorld(world)) {
PlayerFunctions.sendMessage(plr, C.NOT_VALID_PLOT_WORLD); PlayerFunctions.sendMessage(plr, C.NOT_VALID_PLOT_WORLD);
return true; return true;
} }
} } else {
else {
PlayerFunctions.sendMessage(plr, C.NOT_VALID_WORLD); PlayerFunctions.sendMessage(plr, C.NOT_VALID_WORLD);
return true; return true;
} }
} } else {
else {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD); PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD);
return true; return true;
} }
} }
} }
if(PlayerFunctions.getPlayerPlotCount(world, plr) >= PlayerFunctions.getAllowedPlots(plr)) { if (PlayerFunctions.getPlayerPlotCount(world, plr) >= PlayerFunctions.getAllowedPlots(plr)) {
PlayerFunctions.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS); PlayerFunctions.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS);
return true; return true;
} }
boolean br = false; boolean br = false;
int x = 0, z = 0, q = 100; int x = 0, z = 0, q = 100;
PlotId id; PlotId id;
while(!br) { while (!br) {
id = new PlotId(x,z); id = new PlotId(x, z);
if(PlotHelper.getPlot(world, id).owner == null) { if (PlotHelper.getPlot(world, id).owner == null) {
Plot plot = PlotHelper.getPlot(world, id); Plot plot = PlotHelper.getPlot(world, id);
boolean result = Claim.claimPlot(plr, plot, true); boolean result = Claim.claimPlot(plr, plot, true);
br = !result; br = !result;
} }
if(z < q && (z - x) < q) { if ((z < q) && ((z - x) < q)) {
z++; z++;
} else if(x < q) { } else if (x < q) {
x++; x++;
z = q - 100; z = q - 100;
} else { } else {
q += 100; q += 100;
x = q; x = q;
z = q; z = q;
} }
} }
return true; return true;
} }
} }

View File

@ -1,9 +1,7 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import ca.mera.CameraAPI; import java.util.ArrayList;
import ca.mera.CameraController;
import ca.mera.events.TravelEndEvent;
import com.intellectualcrafters.plot.*;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.World; import org.bukkit.World;
@ -11,7 +9,16 @@ import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import java.util.ArrayList; import ca.mera.CameraAPI;
import ca.mera.CameraController;
import ca.mera.events.TravelEndEvent;
import com.intellectualcrafters.plot.C;
import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.Plot;
import com.intellectualcrafters.plot.PlotHelper;
import com.intellectualcrafters.plot.PlotMain;
import com.intellectualcrafters.plot.PlotWorld;
/** /**
* Created by Citymonstret on 2014-08-15. * Created by Citymonstret on 2014-08-15.
@ -19,41 +26,42 @@ import java.util.ArrayList;
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", CommandCategory.TELEPORT);
api = CameraAPI.getInstance(); this.api = CameraAPI.getInstance();
travelers = new ArrayList<String>(); 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;
} }
api = CameraAPI.getInstance(); this.api = CameraAPI.getInstance();
Plot plot = PlotHelper.getCurrentPlot(player.getLocation()); Plot plot = PlotHelper.getCurrentPlot(player.getLocation());
if(api.isTravelling(player)) { if (this.api.isTravelling(player)) {
api.stopTravel(player); this.api.stopTravel(player);
PlayerFunctions.sendMessage(player, C.CAMERA_STOPPED); PlayerFunctions.sendMessage(player, C.CAMERA_STOPPED);
return true; return true;
} }
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 + ";" + plot.getId().y);
travelers.add(player.getName()); this.travelers.add(player.getName());
return true; return true;
} }
@EventHandler @EventHandler
public void onTravelEnded(TravelEndEvent event) { public void onTravelEnded(TravelEndEvent event) {
if(travelers.contains(event.getPlayer().getName())) { if (this.travelers.contains(event.getPlayer().getName())) {
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(travelers.contains(event.getPlayer().getName())) { if (this.travelers.contains(event.getPlayer().getName())) {
event.getHandlers().bake(); event.getHandlers().bake();
} }
} }
@ -65,7 +73,7 @@ public class Camera extends SubCommand implements Listener {
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());
@ -75,12 +83,12 @@ public class Camera extends SubCommand implements Listener {
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 = api.createController(player, seconds, loc1, loc2, loc3, loc4, loc5); CameraController controller = this.api.createController(player, seconds, loc1, loc2, loc3, loc4, loc5);
return controller; return controller;
} }
} }

View File

@ -9,35 +9,41 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.*;
import com.intellectualcrafters.plot.events.PlayerClaimPlotEvent;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
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.SchematicHandler;
import com.intellectualcrafters.plot.events.PlayerClaimPlotEvent;
/** /**
* *
* @author Citymonstret * @author Citymonstret
* *
*/ */
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) {
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.getAllowedPlots(plr)) {
PlayerFunctions.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS); PlayerFunctions.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS);
return true; return true;
} }
Plot plot = PlayerFunctions.getCurrentPlot(plr); Plot plot = PlayerFunctions.getCurrentPlot(plr);
if(plot.hasOwner()) { if (plot.hasOwner()) {
PlayerFunctions.sendMessage(plr, C.PLOT_IS_CLAIMED); PlayerFunctions.sendMessage(plr, C.PLOT_IS_CLAIMED);
return false; return false;
} }
@ -48,21 +54,21 @@ public class Claim extends SubCommand{
} }
return true; return true;
} }
public static boolean claimPlot(Player player, Plot plot, boolean teleport) { public static boolean claimPlot(Player player, Plot plot, boolean teleport) {
plot.clear(player);
PlayerClaimPlotEvent event = new PlayerClaimPlotEvent(player, plot); PlayerClaimPlotEvent event = new PlayerClaimPlotEvent(player, plot);
Bukkit.getPluginManager().callEvent(event); Bukkit.getPluginManager().callEvent(event);
if(!event.isCancelled()) { if (!event.isCancelled()) {
PlotHelper.createPlot(player, plot); PlotHelper.createPlot(player, plot);
PlotHelper.setSign(player, plot); PlotHelper.setSign(player, plot);
PlayerFunctions.sendMessage(player, C.CLAIMED); PlayerFunctions.sendMessage(player, C.CLAIMED);
if(teleport) { if (teleport) {
PlotMain.teleportPlayer(player, player.getLocation(), plot); PlotMain.teleportPlayer(player, player.getLocation(), plot);
} }
PlotWorld world = PlotMain.getWorldSettings(plot.getWorld()); PlotWorld world = PlotMain.getWorldSettings(plot.getWorld());
if(world.SCHEMATIC_ON_CLAIM) { if (world.SCHEMATIC_ON_CLAIM) {
SchematicHandler handler = new SchematicHandler(); SchematicHandler handler = new SchematicHandler();
SchematicHandler.Schematic schematic = handler.getSchematic(world.SCHEMATIC_FILE); SchematicHandler.Schematic schematic = handler.getSchematic(world.SCHEMATIC_FILE);
handler.paste(player.getLocation(), schematic, plot); handler.paste(player.getLocation(), schematic, plot);

View File

@ -9,11 +9,12 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.database.DBFunc; import org.bukkit.entity.Player;
import com.intellectualcrafters.plot.PlotMain;
import com.intellectualcrafters.plot.PlayerFunctions; import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.Plot; import com.intellectualcrafters.plot.Plot;
import org.bukkit.entity.Player; import com.intellectualcrafters.plot.PlotMain;
import com.intellectualcrafters.plot.database.DBFunc;
/** /**
* Created by Citymonstret on 2014-08-01. * Created by Citymonstret on 2014-08-01.
@ -23,9 +24,10 @@ 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 true; return true;
} }
@ -34,8 +36,7 @@ public class Clear extends SubCommand {
if (result) { if (result) {
DBFunc.delete(plr.getWorld().getName(), plot); DBFunc.delete(plr.getWorld().getName(), plot);
plot.clear(plr); plot.clear(plr);
} } else {
else {
PlayerFunctions.sendMessage(plr, "Plot clearing has been denied."); PlayerFunctions.sendMessage(plr, "Plot clearing has been denied.");
} }
return true; return true;

View File

@ -11,6 +11,7 @@ package com.intellectualcrafters.plot.commands;
/** /**
* Created by Citymonstret on 2014-08-03. * Created by Citymonstret on 2014-08-03.
*
* @author Citymonstret * @author Citymonstret
*/ */
public enum Command { public enum Command {
@ -131,7 +132,7 @@ public enum Command {
* *
* @return * @return
*/ */
public CommandPermission getPermission(){ public CommandPermission getPermission() {
return this.permission; return this.permission;
} }
} }

View File

@ -13,6 +13,7 @@ import org.bukkit.entity.Player;
/** /**
* Created by Citymonstret on 2014-08-03. * Created by Citymonstret on 2014-08-03.
*
* @author Citymonstret * @author Citymonstret
*/ */
public class CommandPermission { public class CommandPermission {

View File

@ -9,40 +9,44 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.*;
import org.bukkit.World;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
/** import com.intellectualcrafters.plot.C;
* @author Citymonstret import com.intellectualcrafters.plot.Lag;
* \\SuperCharged Compiler made by Citymonstret\\ import com.intellectualcrafters.plot.PlayerFunctions;
* ||#Compiler:ALPHA-1.0######################### import com.intellectualcrafters.plot.PlotHelper;
* ||#ST:Java(1.7.*)\impl(bukkit)->api(s[])###### import com.intellectualcrafters.plot.PlotMain;
* ||#Section:\Debug\############################ import com.intellectualcrafters.plot.RUtils;
* ||##Debug->Debug.properties|Debug.txt#########
* ||############################################
* ||#Signed By:Citymonstret@IC##################
* \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
*/
public class Debug extends SubCommand{
//private extends SubCommand^Implements {Command, Information} from >>\\S.txt6\\ /**
public Debug() { * @author Citymonstret \\SuperCharged Compiler made by Citymonstret\\
super(Command.DEBUG, "Show debug information", "debug [msg]", CommandCategory.INFO); * ||#Compiler:ALPHA-1.0#########################
* ||#ST:Java(1.7.*)\impl(bukkit)->api(s[])######
* ||#Section:\Debug\############################
* ||##Debug->Debug.properties|Debug.txt#########
* ||############################################ ||#Signed
* By:Citymonstret@IC##################
* \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
*/
public class Debug extends SubCommand {
// private extends SubCommand^Implements {Command, Information} from
// >>\\S.txt6\\
public Debug() {
super(Command.DEBUG, "Show debug information", "debug [msg]", CommandCategory.INFO);
{ {
/** /**
* This. * This.
*/ */
} }
} }
@Override @Override
public boolean execute(Player plr, String ... args) { public boolean execute(Player plr, String... args) {
PlotWorld plotworld = 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());
@ -60,24 +64,19 @@ public class Debug extends SubCommand{
section = C.DEBUG_SECTION.s(); section = C.DEBUG_SECTION.s();
} }
/** /**
* {||direct:: load: debug::I>Captions::trsl} * {||direct:: load: debug::I>Captions::trsl} \\ if(missing)
* \\ * set(default) -> this->(){} \\ echo line->line(Compiler.cpp ->
* if(missing) set(default) -> this->(){} * lineCompiler); when finished: now = this();
* \\ * now(getter)->setter(this())->{ "string" = getter(this);
* echo line->line(Compiler.cpp -> lineCompiler); * setter(string) = getter(this->setter); } when ^ finished compile;
* when finished: now = this(); * if(^compile failed -> |this->failed.|tests->failed.| ||run test
* now(getter)->setter(this())->{ * {this->test}|on fail(action(){return FAILED})|
* "string" = getter(this);
* setter(string) = getter(this->setter);
* }
* when ^ finished compile;
* if(^compile failed -> |this->failed.|tests->failed.|
* ||run test {this->test}|on fail(action(){return FAILED})|
*/ */
{ {
StringBuilder worlds = new StringBuilder(""); 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()));
@ -98,20 +97,21 @@ public class Debug extends SubCommand{
information.append(getLine(line, "View all captions", "/plot debug msg")); information.append(getLine(line, "View all captions", "/plot debug msg"));
} }
/** /**
* {function:: SEND_MESSAGE |local player -> plr|local string -> information.toString())} * {function:: SEND_MESSAGE |local player -> plr|local string ->
* information.toString())}
*/ */
{ {
PlayerFunctions.sendMessage(plr, information.toString()); PlayerFunctions.sendMessage(plr, information.toString());
} }
return true; 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,22 +9,23 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
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.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.
*/ */
@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);
@ -33,63 +34,71 @@ public class Denied extends SubCommand{
@SuppressWarnings("deprecated") @SuppressWarnings("deprecated")
private boolean hasBeenOnServer(String name) { private boolean hasBeenOnServer(String name) {
Player plr; Player plr;
if((plr = Bukkit.getPlayer(name)) == null) { if ((plr = Bukkit.getPlayer(name)) == null) {
OfflinePlayer oplr = Bukkit.getOfflinePlayer(name); OfflinePlayer oplr = Bukkit.getOfflinePlayer(name);
if(oplr == null) return false; if (oplr == null) {
else return oplr.hasPlayedBefore(); return false;
} else {
return oplr.hasPlayedBefore();
}
} else { } else {
if(plr.isOnline()) return true; if (plr.isOnline()) {
else return plr.hasPlayedBefore(); return true;
} else {
return plr.hasPlayedBefore();
}
} }
} }
public boolean execute(Player plr, String ... args) { @Override
if(args.length < 2) { public boolean execute(Player plr, String... args) {
if (args.length < 2) {
PlayerFunctions.sendMessage(plr, C.DENIED_NEED_ARGUMENT); PlayerFunctions.sendMessage(plr, C.DENIED_NEED_ARGUMENT);
return true; return true;
} }
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.owner == null || !plot.hasRights(plr)) { if ((plot.owner == null) || !plot.hasRights(plr)) {
PlayerFunctions.sendMessage(plr, C.NO_PERMISSION); PlayerFunctions.sendMessage(plr, C.NO_PERMISSION);
return true; return true;
} }
if(args[0].equalsIgnoreCase("add")) { if (args[0].equalsIgnoreCase("add")) {
if(args[1].equalsIgnoreCase("*")) { if (args[1].equalsIgnoreCase("*")) {
UUID uuid = DBFunc.everyone; UUID uuid = DBFunc.everyone;
plot.addDenied(uuid); plot.addDenied(uuid);
DBFunc.setDenied(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); DBFunc.setDenied(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1]));
PlayerFunctions.sendMessage(plr, C.DENIED_ADDED); PlayerFunctions.sendMessage(plr, C.DENIED_ADDED);
return true; return true;
} }
if(!hasBeenOnServer(args[1])) { if (!hasBeenOnServer(args[1])) {
PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON);
return true; return true;
} }
UUID uuid = null; UUID uuid = null;
if(Bukkit.getPlayer(args[1]) != null && Bukkit.getPlayer(args[1]).isOnline()) if ((Bukkit.getPlayer(args[1]) != null) && Bukkit.getPlayer(args[1]).isOnline()) {
uuid = Bukkit.getPlayer(args[1]).getUniqueId(); uuid = Bukkit.getPlayer(args[1]).getUniqueId();
else } else {
uuid = Bukkit.getOfflinePlayer(args[1]).getUniqueId(); uuid = Bukkit.getOfflinePlayer(args[1]).getUniqueId();
}
plot.addDenied(uuid); plot.addDenied(uuid);
DBFunc.setDenied(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); DBFunc.setDenied(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1]));
PlayerPlotDeniedEvent event = new PlayerPlotDeniedEvent(plr, plot, uuid, true); PlayerPlotDeniedEvent event = new PlayerPlotDeniedEvent(plr, plot, uuid, true);
Bukkit.getPluginManager().callEvent(event); Bukkit.getPluginManager().callEvent(event);
PlayerFunctions.sendMessage(plr, C.DENIED_ADDED); PlayerFunctions.sendMessage(plr, C.DENIED_ADDED);
if(Bukkit.getPlayer(uuid) != null && Bukkit.getPlayer(uuid).isOnline()) { if ((Bukkit.getPlayer(uuid) != null) && Bukkit.getPlayer(uuid).isOnline()) {
Plot pl = PlayerFunctions.getCurrentPlot(Bukkit.getPlayer((uuid))); Plot pl = PlayerFunctions.getCurrentPlot(Bukkit.getPlayer((uuid)));
if(pl.id == plot.id) { if (pl.id == plot.id) {
PlayerFunctions.sendMessage(Bukkit.getPlayer(uuid), C.YOU_BE_DENIED); PlayerFunctions.sendMessage(Bukkit.getPlayer(uuid), C.YOU_BE_DENIED);
Bukkit.getPlayer(uuid).teleport(Bukkit.getPlayer(uuid).getWorld().getSpawnLocation()); Bukkit.getPlayer(uuid).teleport(Bukkit.getPlayer(uuid).getWorld().getSpawnLocation());
} }
} }
} else if(args[0].equalsIgnoreCase("remove")) { } else if (args[0].equalsIgnoreCase("remove")) {
if(args[1].equalsIgnoreCase("*")) { if (args[1].equalsIgnoreCase("*")) {
UUID uuid = DBFunc.everyone; UUID uuid = DBFunc.everyone;
if(!plot.denied.contains(uuid)) { if (!plot.denied.contains(uuid)) {
PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED); PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED);
return true; return true;
} }
@ -98,16 +107,17 @@ public class Denied extends SubCommand{
PlayerFunctions.sendMessage(plr, C.DENIED_REMOVED); PlayerFunctions.sendMessage(plr, C.DENIED_REMOVED);
return true; return true;
} }
if(!hasBeenOnServer(args[1])) { if (!hasBeenOnServer(args[1])) {
PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON);
return true; return true;
} }
UUID uuid = null; UUID uuid = null;
if(Bukkit.getPlayer(args[1]).isOnline()) if (Bukkit.getPlayer(args[1]).isOnline()) {
uuid = Bukkit.getPlayer(args[1]).getUniqueId(); uuid = Bukkit.getPlayer(args[1]).getUniqueId();
else } else {
uuid = Bukkit.getOfflinePlayer(args[1]).getUniqueId(); uuid = Bukkit.getOfflinePlayer(args[1]).getUniqueId();
if(!plot.denied.contains(uuid)) { }
if (!plot.denied.contains(uuid)) {
PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED); PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED);
return true; return true;
} }

View File

@ -18,5 +18,9 @@ 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);
} }
public boolean execute(Player plr, String ... args) { return false; }
@Override
public boolean execute(Player plr, String... args) {
return false;
}
} }

View File

@ -9,77 +9,85 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
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.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) { private boolean hasBeenOnServer(String name) {
Player plr; Player plr;
if((plr = Bukkit.getPlayer(name)) == null) { if ((plr = Bukkit.getPlayer(name)) == null) {
OfflinePlayer oplr = Bukkit.getOfflinePlayer(name); OfflinePlayer oplr = Bukkit.getOfflinePlayer(name);
if(oplr == null) return false; if (oplr == null) {
else return oplr.hasPlayedBefore(); return false;
} else {
return oplr.hasPlayedBefore();
}
} else { } else {
if(plr.isOnline()) return true; if (plr.isOnline()) {
else return plr.hasPlayedBefore(); return true;
} else {
return plr.hasPlayedBefore();
}
} }
} }
public boolean execute(Player plr, String ... args) { @Override
if(args.length < 2) { public boolean execute(Player plr, String... args) {
if (args.length < 2) {
PlayerFunctions.sendMessage(plr, C.HELPER_NEED_ARGUMENT); PlayerFunctions.sendMessage(plr, C.HELPER_NEED_ARGUMENT);
return true; return true;
} }
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.owner == null || !plot.hasRights(plr)) { if ((plot.owner == null) || !plot.hasRights(plr)) {
PlayerFunctions.sendMessage(plr, C.NO_PERMISSION); PlayerFunctions.sendMessage(plr, C.NO_PERMISSION);
return true; return true;
} }
if(args[0].equalsIgnoreCase("add")) { if (args[0].equalsIgnoreCase("add")) {
if(args[1].equalsIgnoreCase("*")) { if (args[1].equalsIgnoreCase("*")) {
UUID uuid = DBFunc.everyone; UUID uuid = DBFunc.everyone;
plot.addHelper(uuid); plot.addHelper(uuid);
DBFunc.setHelper(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); DBFunc.setHelper(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1]));
PlayerFunctions.sendMessage(plr, C.HELPER_ADDED); PlayerFunctions.sendMessage(plr, C.HELPER_ADDED);
return true; return true;
} }
if(!hasBeenOnServer(args[1])) { if (!hasBeenOnServer(args[1])) {
PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON);
return true; return true;
} }
UUID uuid = null; UUID uuid = null;
if(Bukkit.getPlayer(args[1]) != null && Bukkit.getPlayer(args[1]).isOnline()) if ((Bukkit.getPlayer(args[1]) != null) && Bukkit.getPlayer(args[1]).isOnline()) {
uuid = Bukkit.getPlayer(args[1]).getUniqueId(); uuid = Bukkit.getPlayer(args[1]).getUniqueId();
else } else {
uuid = Bukkit.getOfflinePlayer(args[1]).getUniqueId(); uuid = Bukkit.getOfflinePlayer(args[1]).getUniqueId();
}
plot.addHelper(uuid); plot.addHelper(uuid);
DBFunc.setHelper(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1])); DBFunc.setHelper(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1]));
PlayerPlotHelperEvent event = new PlayerPlotHelperEvent(plr, plot, uuid, true); PlayerPlotHelperEvent event = new PlayerPlotHelperEvent(plr, plot, uuid, true);
Bukkit.getPluginManager().callEvent(event); Bukkit.getPluginManager().callEvent(event);
PlayerFunctions.sendMessage(plr, C.HELPER_ADDED); PlayerFunctions.sendMessage(plr, C.HELPER_ADDED);
} else if(args[0].equalsIgnoreCase("remove")) { } else if (args[0].equalsIgnoreCase("remove")) {
if(args[1].equalsIgnoreCase("*")) { if (args[1].equalsIgnoreCase("*")) {
UUID uuid = DBFunc.everyone; UUID uuid = DBFunc.everyone;
if(!plot.helpers.contains(uuid)) { if (!plot.helpers.contains(uuid)) {
PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED); PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED);
return true; return true;
} }
@ -88,16 +96,17 @@ public class Helpers extends SubCommand{
PlayerFunctions.sendMessage(plr, C.HELPER_REMOVED); PlayerFunctions.sendMessage(plr, C.HELPER_REMOVED);
return true; return true;
} }
if(!hasBeenOnServer(args[1])) { if (!hasBeenOnServer(args[1])) {
PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON);
return true; return true;
} }
UUID uuid = null; UUID uuid = null;
if(Bukkit.getPlayer(args[1]).isOnline()) if (Bukkit.getPlayer(args[1]).isOnline()) {
uuid = Bukkit.getPlayer(args[1]).getUniqueId(); uuid = Bukkit.getPlayer(args[1]).getUniqueId();
else } else {
uuid = Bukkit.getOfflinePlayer(args[1]).getUniqueId(); uuid = Bukkit.getOfflinePlayer(args[1]).getUniqueId();
if(!plot.helpers.contains(uuid)) { }
if (!plot.helpers.contains(uuid)) {
PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED); PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED);
return true; return true;
} }

View File

@ -9,41 +9,44 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.*;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import java.util.ArrayList; import com.intellectualcrafters.plot.C;
import java.util.Set; import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.Plot;
import com.intellectualcrafters.plot.PlotMain;
/** /**
* *
* @author Citymonstret * @author Citymonstret
* *
*/ */
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) {
for(Plot p : PlotMain.getPlots()) { private Plot isAlias(String a) {
if(p.settings.getAlias().length() > 0 && p.settings.getAlias().equalsIgnoreCase(a)) for (Plot p : PlotMain.getPlots()) {
if ((p.settings.getAlias().length() > 0) && p.settings.getAlias().equalsIgnoreCase(a)) {
return p; return p;
}
} }
return null; return null;
} }
@Override
public boolean execute(Player plr, String ... args) {
// TODO plot names / alias @Override
public boolean execute(Player plr, String... args) {
Plot[] plots = PlotMain.getPlots(plr).toArray(new Plot[0]); // TODO plot names / alias
if(plots.length == 1) {
Plot[] plots = PlotMain.getPlots(plr).toArray(new Plot[0]);
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) {
PlayerFunctions.sendMessage(plr, C.NEED_PLOT_NUMBER); PlayerFunctions.sendMessage(plr, C.NEED_PLOT_NUMBER);
return true; return true;
} }
@ -53,7 +56,7 @@ public class Home extends SubCommand{
} 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(), temp);
@ -66,7 +69,7 @@ public class Home extends SubCommand{
PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER); PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER);
return true; return true;
} }
if(id > (plots.length) || id < 1) { if ((id > (plots.length)) || (id < 1)) {
PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER); PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER);
return false; return false;
} }
@ -76,5 +79,5 @@ public class Home extends SubCommand{
PlayerFunctions.sendMessage(plr, C.NO_PLOTS); PlayerFunctions.sendMessage(plr, C.NO_PLOTS);
return true; return true;
} }
} }
} }

View File

@ -9,8 +9,8 @@
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;
@ -20,36 +20,39 @@ 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.database.DBFunc;
/** /**
* *
* @author Citymonstret * @author Citymonstret
* *
*/ */
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;
// 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);
@ -57,57 +60,65 @@ public class Info extends SubCommand{
} }
// Unclaimed? // Unclaimed?
if(!hasOwner && !containsEveryone) { if (!hasOwner && !containsEveryone) {
PlayerFunctions.sendMessage(player, C.PLOT_INFO_UNCLAIMED, plot.id.x+";"+plot.id.y); PlayerFunctions.sendMessage(player, C.PLOT_INFO_UNCLAIMED, plot.id.x + ";" + plot.id.y);
return true; return true;
} }
// Helpers :D new StringBuilder();
StringBuilder helpers = 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();
}
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("%alias%", plot.settings.getAlias().length() > 0 ? plot.settings.getAlias() : "none");
info = info.replaceAll("%id%", plot.id.x+";"+plot.id.y); info = info.replaceAll("%id%", plot.id.x + ";" + plot.id.y);
info = info.replaceAll("%biome%", getBiomeAt(plot).toString()); info = info.replaceAll("%biome%", getBiomeAt(plot).toString());
info = info.replaceAll("%owner%", owner); info = info.replaceAll("%owner%", owner);
info = info.replaceAll("%time%", plot.settings.getChangeTime() ? plot.settings.getTime() + "" : "default"); info = info.replaceAll("%time%", plot.settings.getChangeTime() ? plot.settings.getTime() + "" : "default");
info = info.replaceAll("%weather%", plot.settings.getRain() ? "rain" : "default"); info = info.replaceAll("%weather%", plot.settings.getRain() ? "rain" : "default");
info = info.replaceAll("%helpers%", getPlayerList(plot.helpers)); info = info.replaceAll("%helpers%", getPlayerList(plot.helpers));
info = info.replaceAll("%denied%", getPlayerList(plot.denied)); info = info.replaceAll("%denied%", getPlayerList(plot.denied));
info = info.replaceAll("%flags%", StringUtils.join(plot.settings.getFlags(),"").length() > 0 ? StringUtils.join(plot.settings.getFlags(),",") : "none"); info = info.replaceAll("%flags%", StringUtils.join(plot.settings.getFlags(), "").length() > 0 ? StringUtils.join(plot.settings.getFlags(), ",") : "none");
PlayerFunctions.sendMessage(player, info); PlayerFunctions.sendMessage(player, info);
return true; return true;
} }
private String getPlayerList(ArrayList<UUID> l) { private String getPlayerList(ArrayList<UUID> l) {
if(l == null || l.size() < 1) return " none"; if ((l == null) || (l.size() < 1)) {
String c = C.PLOT_USER_LIST.s(); return " none";
StringBuilder list = new StringBuilder(); }
for(int x = 0; x < l.size(); x++) { String c = C.PLOT_USER_LIST.s();
if(x + 1 == l.size()) StringBuilder list = new StringBuilder();
list.append(c.replace("%user%", getPlayerName(l.get(x))).replace(",", "")); for (int x = 0; x < l.size(); x++) {
else if ((x + 1) == l.size()) {
list.append(c.replace("%user%", getPlayerName(l.get(x)))); list.append(c.replace("%user%", getPlayerName(l.get(x))).replace(",", ""));
} } else {
return list.toString(); list.append(c.replace("%user%", getPlayerName(l.get(x))));
} }
}
return list.toString();
}
private String getPlayerName(UUID uuid) { private String getPlayerName(UUID uuid) {
if(uuid == null) return "unknown"; if (uuid == null) {
if(uuid.equals(DBFunc.everyone) || uuid.toString().equalsIgnoreCase(DBFunc.everyone.toString())) return "unknown";
}
if (uuid.equals(DBFunc.everyone) || uuid.toString().equalsIgnoreCase(DBFunc.everyone.toString())) {
return "everyone"; return "everyone";
OfflinePlayer plr = Bukkit.getOfflinePlayer(uuid); }
if(plr == null) return "unknown"; OfflinePlayer plr = Bukkit.getOfflinePlayer(uuid);
return plr.getName(); if (plr == null) {
} return "unknown";
}
return plr.getName();
}
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

@ -9,6 +9,8 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import java.util.ArrayList;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.Material; import org.bukkit.Material;
@ -16,8 +18,6 @@ import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList;
public class Inventory extends SubCommand { public class Inventory extends SubCommand {
public Inventory() { public Inventory() {
@ -25,19 +25,20 @@ public class Inventory extends SubCommand {
} }
@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); }
org.bukkit.inventory.Inventory inventory = Bukkit.createInventory(null, size, "PlotSquared Commands"); int size = 9 * (int) Math.ceil(cmds.size() / 9.0);
for(SubCommand cmd : cmds) { org.bukkit.inventory.Inventory inventory = Bukkit.createInventory(null, 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) {
@ -46,12 +47,12 @@ public class Inventory extends SubCommand {
{ {
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 + " [" + ChatColor.GREEN + cmd.alias + ChatColor.DARK_GRAY + "]");
meta.setLore(new ArrayList<String>() { meta.setLore(new ArrayList<String>() {
{ {
add(ChatColor.RED + "Category: " + ChatColor.GOLD + cmd.category.toString()); add(ChatColor.RED + "Category: " + ChatColor.GOLD + cmd.category.toString());
add(ChatColor.RED + "Description: " + ChatColor.GOLD + cmd.description); add(ChatColor.RED + "Description: " + ChatColor.GOLD + cmd.description);
add(ChatColor.RED + "Usage: " + ChatColor.GOLD + "/plot " + cmd.usage); add(ChatColor.RED + "Usage: " + ChatColor.GOLD + "/plot " + cmd.usage);
} }
}); });
} }
stack.setItemMeta(meta); stack.setItemMeta(meta);
return stack; return stack;

View File

@ -9,9 +9,8 @@
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;
@ -19,71 +18,53 @@ 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
*
* @author Citymonstret * @author Citymonstret
* *
*/ */
public class MainCommand implements CommandExecutor{ public class MainCommand implements CommandExecutor {
private static SubCommand[] _subCommands = new SubCommand[] { private static SubCommand[] _subCommands = new SubCommand[] { new Claim(), new Auto(), new Home(), new Visit(), new TP(), new Set(), new Clear(), new SetOwner(), new Denied(), new Helpers(), new Info(), new list(), new Help(), new Debug(), new Schematic(), new plugin(), new Inventory(), new Reload() };
new Claim(),
new Auto(),
new Home(),
new Visit(),
new TP(),
new Set(),
new Clear(),
new SetOwner(),
new Denied(),
new Helpers(),
new Info(),
new list(),
new Help(),
new Debug(),
new Schematic(),
new plugin(),
new Inventory(),
new Reload()
};
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, public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
String[] args) { if (!(sender instanceof Player)) {
if(!(sender instanceof Player)) { if (args.length > 0) {
if (args.length>0) { if (args[0].equalsIgnoreCase("reload")) {
if (args[0].equalsIgnoreCase("reload")) { new Reload().executeConsole(args);
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()); }
PlotMain.sendConsoleSenderMessage("&6/plots reload &c-&6 reloads the plugin");
}
return false; return false;
} }
Player player = (Player) sender; Player player = (Player) sender;
if(!player.hasPermission("plots.use")) { if (!player.hasPermission("plots.use")) {
return no_permission(player); return no_permission(player);
} }
if(args.length < 1 || (args.length >= 1 && (args[0].equalsIgnoreCase("help") || args[0].equalsIgnoreCase("he"))) ) if ((args.length < 1) || ((args.length >= 1) && (args[0].equalsIgnoreCase("help") || args[0].equalsIgnoreCase("he")))) {
{ if (args.length < 2) {
if(args.length < 2) {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
builder.append(C.HELP_INFO.s()); builder.append(C.HELP_INFO.s());
for(SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) { for (SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) {
builder.append("\n" + C.HELP_INFO_ITEM.s().replaceAll("%category%", category.toString().toLowerCase()).replaceAll("%category_desc%", category.toString())); builder.append("\n" + C.HELP_INFO_ITEM.s().replaceAll("%category%", category.toString().toLowerCase()).replaceAll("%category_desc%", category.toString()));
} }
PlayerFunctions.sendMessage(player, builder.toString()); PlayerFunctions.sendMessage(player, builder.toString());
@ -91,52 +72,55 @@ public class MainCommand implements CommandExecutor{
} }
String cat = args[1]; String cat = args[1];
SubCommand.CommandCategory cato = null; SubCommand.CommandCategory cato = null;
for(SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) { for (SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) {
if(cat.equalsIgnoreCase(category.toString())){ if (cat.equalsIgnoreCase(category.toString())) {
cato = category; cato = category;
break; break;
} }
} }
if(cato == null) { if (cato == null) {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
builder.append(C.HELP_INFO.s()); builder.append(C.HELP_INFO.s());
for(SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) { for (SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) {
builder.append("\n" + C.HELP_INFO_ITEM.s().replaceAll("%category%", category.toString().toLowerCase()).replaceAll("%category_desc%", category.toString())); builder.append("\n" + C.HELP_INFO_ITEM.s().replaceAll("%category%", category.toString().toLowerCase()).replaceAll("%category_desc%", category.toString()));
} }
PlayerFunctions.sendMessage(player, builder.toString()); PlayerFunctions.sendMessage(player, builder.toString());
return true; return true;
} }
StringBuilder help = new StringBuilder(); StringBuilder help = new StringBuilder();
for(String string : helpMenu(player, cato)) for (String string : helpMenu(player, cato)) {
help.append(string + "\n"); help.append(string + "\n");
PlayerFunctions.sendMessage(player, help.toString()); }
return true; PlayerFunctions.sendMessage(player, help.toString());
} return true;
else { } else {
for(SubCommand command : subCommands) { for (SubCommand command : subCommands) {
if(command.cmd.equalsIgnoreCase(args[0]) || command.alias.equalsIgnoreCase(args[0])) { if (command.cmd.equalsIgnoreCase(args[0]) || command.alias.equalsIgnoreCase(args[0])) {
String[] arguments = new String[args.length - 1]; String[] arguments = new String[args.length - 1];
for(int x = 1; x < args.length; x++) for (int x = 1; x < args.length; x++) {
arguments[x - 1] = args[x]; arguments[x - 1] = args[x];
if(command.permission.hasPermission(player)) }
return command.execute(player, arguments); if (command.permission.hasPermission(player)) {
else return no_permission(player); return command.execute(player, arguments);
} } else {
} return no_permission(player);
PlayerFunctions.sendMessage(player, C.NOT_VALID_SUBCOMMAND); }
} }
return false; }
} 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, final SubCommand.CommandCategory category) {
ArrayList<String> help = new ArrayList<String>(){ ArrayList<String> help = new ArrayList<String>() {
{ {
add(t(C.HELP_HEADER.s())); add(t(C.HELP_HEADER.s()));
add(t(C.HELP_CATEGORY.s().replaceAll("%category%", category.toString()))); add(t(C.HELP_CATEGORY.s().replaceAll("%category%", category.toString())));
} }
}; };
for (SubCommand cmd : subCommands) { for (SubCommand cmd : subCommands) {
if (cmd.permission.hasPermission(player) && cmd.category == category) { if (cmd.permission.hasPermission(player) && (cmd.category == category)) {
String s = t(C.HELP_PAGE.s()); String s = t(C.HELP_PAGE.s());
s = s.replaceAll("%alias%", cmd.alias); s = s.replaceAll("%alias%", cmd.alias);
s = s.replaceAll("%usage%", "/plot " + cmd.usage); s = s.replaceAll("%usage%", "/plot " + cmd.usage);
@ -151,8 +135,8 @@ public class MainCommand implements CommandExecutor{
return help; 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,35 +9,34 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.PlotMain;
import org.bukkit.ChatColor;
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.PlotMain;
/** /**
* @Deprecated * @Deprecated
*/ */
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

@ -1,10 +1,11 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
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.PlotMain;
import com.intellectualcrafters.plot.SchematicHandler; import com.intellectualcrafters.plot.SchematicHandler;
import org.bukkit.entity.Player;
public class Schematic extends SubCommand { public class Schematic extends SubCommand {
@ -12,58 +13,57 @@ public class Schematic extends SubCommand {
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);
break;
}
if(!PlayerFunctions.isInPlot(plr)) {
sendMessage(plr, C.NOT_IN_PLOT);
break;
}
file = args[1];
schematic = new SchematicHandler().getSchematic(file);
boolean s = new SchematicHandler().paste(plr.getLocation(), schematic, PlayerFunctions.getCurrentPlot(plr));
if(s) {
sendMessage(plr, C.SCHEMATIC_PASTE_SUCCESS);
} else {
sendMessage(plr, C.SCHEMATIC_PASTE_FAILED);
}
break;
case "test":
if(args.length < 2) {
sendMessage(plr, C.SCHEMATIC_MISSING_ARG);
break;
}
file = args[1];
schematic = new SchematicHandler().getSchematic(file);
if(schematic == null) {
sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent");
break;
}
int l1 = schematic.getSchematicDimension().getX();
int l2 = schematic.getSchematicDimension().getZ();
int length = PlotMain.getWorldSettings(plr.getWorld()).PLOT_WIDTH;
if(l1 != length || l2 != length) {
sendMessage(plr, C.SCHEMATIC_INVALID, String.format("Wrong size (x: %s, z: %d) vs %d ", l1, l2, length));
break;
}
sendMessage(plr, C.SCHEMATIC_VALID);
break;
default:
sendMessage(plr, C.SCHEMATIC_MISSING_ARG); sendMessage(plr, C.SCHEMATIC_MISSING_ARG);
break; break;
}
if (!PlayerFunctions.isInPlot(plr)) {
sendMessage(plr, C.NOT_IN_PLOT);
break;
}
file = args[1];
schematic = new SchematicHandler().getSchematic(file);
boolean s = new SchematicHandler().paste(plr.getLocation(), schematic, PlayerFunctions.getCurrentPlot(plr));
if (s) {
sendMessage(plr, C.SCHEMATIC_PASTE_SUCCESS);
} else {
sendMessage(plr, C.SCHEMATIC_PASTE_FAILED);
}
break;
case "test":
if (args.length < 2) {
sendMessage(plr, C.SCHEMATIC_MISSING_ARG);
break;
}
file = args[1];
schematic = new SchematicHandler().getSchematic(file);
if (schematic == null) {
sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent");
break;
}
int l1 = schematic.getSchematicDimension().getX();
int l2 = schematic.getSchematicDimension().getZ();
int length = PlotMain.getWorldSettings(plr.getWorld()).PLOT_WIDTH;
if ((l1 != length) || (l2 != length)) {
sendMessage(plr, C.SCHEMATIC_INVALID, String.format("Wrong size (x: %s, z: %d) vs %d ", l1, l2, length));
break;
}
sendMessage(plr, C.SCHEMATIC_VALID);
break;
default:
sendMessage(plr, C.SCHEMATIC_MISSING_ARG);
break;
} }
return true; return true;
} }

View File

@ -9,11 +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.Arrays;
import com.intellectualcrafters.plot.events.PlotDeleteEvent; import java.util.List;
import com.intellectualcrafters.plot.events.PlotFlagAddEvent;
import com.intellectualcrafters.plot.events.PlotFlagRemoveEvent;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@ -23,68 +21,73 @@ import org.bukkit.WeatherType;
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.AbstractFlag;
import java.util.Arrays; import com.intellectualcrafters.plot.C;
import java.util.List; import com.intellectualcrafters.plot.Flag;
import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.Plot;
import com.intellectualcrafters.plot.PlotHelper;
import com.intellectualcrafters.plot.PlotHomePosition;
import com.intellectualcrafters.plot.PlotMain;
import com.intellectualcrafters.plot.PlotWorld;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.events.PlotFlagAddEvent;
import com.intellectualcrafters.plot.events.PlotFlagRemoveEvent;
/** /**
* *
* @author Citymonstret * @author Citymonstret
* *
*/ */
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[] { public static String[] values = new String[] { "biome", "wall", "wall_filling", "floor", "alias", "home", "rain", "flag" };
"biome", "wall", "wall_filling", "floor", "alias", "home", "rain", "flag" public static String[] aliases = new String[] { "b", "w", "wf", "f", "a", "h", "r", "fl" };
};
public static String[] 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 true; return true;
} }
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 = false; boolean advanced_permissions = false;
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) {
PlayerFunctions.sendMessage(plr, C.NEED_KEY.s().replaceAll("%values%", StringUtils.join(PlotMain.getFlags(),"&c, &6"))); PlayerFunctions.sendMessage(plr, C.NEED_KEY.s().replaceAll("%values%", StringUtils.join(PlotMain.getFlags(), "&c, &6")));
return false; return false;
} }
if (!PlotMain.isRegisteredFlag(args[1])) { if (!PlotMain.isRegisteredFlag(args[1])) {
@ -95,34 +98,35 @@ public class Set extends SubCommand{
PlayerFunctions.sendMessage(plr, C.NO_PERMISSION); PlayerFunctions.sendMessage(plr, C.NO_PERMISSION);
return false; return false;
} }
if (args.length==2) { if (args.length == 2) {
if (plot.settings.getFlag(args[1].toLowerCase())==null) { if (plot.settings.getFlag(args[1].toLowerCase()) == null) {
PlayerFunctions.sendMessage(plr, C.FLAG_NOT_IN_PLOT); PlayerFunctions.sendMessage(plr, C.FLAG_NOT_IN_PLOT);
return false; return false;
} }
Flag flag = plot.settings.getFlag(args[1].toLowerCase()); Flag flag = plot.settings.getFlag(args[1].toLowerCase());
PlotFlagRemoveEvent event = new PlotFlagRemoveEvent(flag,plot); PlotFlagRemoveEvent event = new PlotFlagRemoveEvent(flag, plot);
Bukkit.getServer().getPluginManager().callEvent(event); Bukkit.getServer().getPluginManager().callEvent(event);
if(event.isCancelled()) { if (event.isCancelled()) {
PlayerFunctions.sendMessage(plr, C.FLAG_NOT_REMOVED); PlayerFunctions.sendMessage(plr, C.FLAG_NOT_REMOVED);
event.setCancelled(true); event.setCancelled(true);
return false; return false;
} }
java.util.Set<Flag> newflags = plot.settings.getFlags(); java.util.Set<Flag> newflags = plot.settings.getFlags();
Flag oldFlag = plot.settings.getFlag(args[1].toLowerCase()); Flag oldFlag = plot.settings.getFlag(args[1].toLowerCase());
if (oldFlag!=null) if (oldFlag != null) {
newflags.remove(oldFlag); newflags.remove(oldFlag);
}
plot.settings.setFlags(newflags.toArray(new Flag[0])); plot.settings.setFlags(newflags.toArray(new Flag[0]));
DBFunc.setFlags(plr.getWorld().getName(), plot, newflags.toArray(new Flag[0])); DBFunc.setFlags(plr.getWorld().getName(), plot, newflags.toArray(new Flag[0]));
PlayerFunctions.sendMessage(plr, C.FLAG_REMOVED); PlayerFunctions.sendMessage(plr, C.FLAG_REMOVED);
return true; return true;
} }
try { try {
String value = StringUtils.join(Arrays.copyOfRange(args, 2, args.length)," "); String value = StringUtils.join(Arrays.copyOfRange(args, 2, args.length), " ");
Flag flag = new Flag(new AbstractFlag(args[1]), value); Flag flag = new Flag(new AbstractFlag(args[1]), value);
PlotFlagAddEvent event = new PlotFlagAddEvent(flag,plot); PlotFlagAddEvent event = new PlotFlagAddEvent(flag, plot);
Bukkit.getServer().getPluginManager().callEvent(event); Bukkit.getServer().getPluginManager().callEvent(event);
if(event.isCancelled()) { if (event.isCancelled()) {
PlayerFunctions.sendMessage(plr, C.FLAG_NOT_ADDED); PlayerFunctions.sendMessage(plr, C.FLAG_NOT_ADDED);
event.setCancelled(true); event.setCancelled(true);
return false; return false;
@ -131,44 +135,48 @@ public class Set extends SubCommand{
DBFunc.setFlags(plr.getWorld().getName(), plot, plot.settings.getFlags().toArray(new Flag[0])); DBFunc.setFlags(plr.getWorld().getName(), plot, plot.settings.getFlags().toArray(new Flag[0]));
PlayerFunctions.sendMessage(plr, C.FLAG_ADDED); PlayerFunctions.sendMessage(plr, C.FLAG_ADDED);
return true; return true;
} } catch (Exception e) {
catch (Exception e) { PlayerFunctions.sendMessage(plr, "&c" + e.getMessage());
PlayerFunctions.sendMessage(plr, "&c"+e.getMessage());
return false; return false;
} }
} }
if(args[0].equalsIgnoreCase("rain")) { if (args[0].equalsIgnoreCase("rain")) {
if(args.length < 2) { if (args.length < 2) {
PlayerFunctions.sendMessage(plr, C.NEED_ON_OFF); PlayerFunctions.sendMessage(plr, C.NEED_ON_OFF);
return false; return false;
} }
String word = args[1]; String word = args[1];
if(!word.equalsIgnoreCase("on") && !word.equalsIgnoreCase("off")) { if (!word.equalsIgnoreCase("on") && !word.equalsIgnoreCase("off")) {
PlayerFunctions.sendMessage(plr, C.NEED_ON_OFF); PlayerFunctions.sendMessage(plr, C.NEED_ON_OFF);
return true; return true;
} }
boolean b = word.equalsIgnoreCase("on"); boolean b = word.equalsIgnoreCase("on");
DBFunc.setWeather(plr.getWorld().getName(), plot, b); DBFunc.setWeather(plr.getWorld().getName(), plot, b);
PlayerFunctions.sendMessage(plr, C.SETTING_UPDATED); PlayerFunctions.sendMessage(plr, C.SETTING_UPDATED);
for(Player p : Bukkit.getOnlinePlayers()) { for (Player p : Bukkit.getOnlinePlayers()) {
if(PlayerFunctions.getCurrentPlot(plr).id == plot.id) { if (PlayerFunctions.getCurrentPlot(plr).id == plot.id) {
if(b) p.setPlayerWeather(WeatherType.DOWNFALL); if (b) {
else p.resetPlayerWeather(); p.setPlayerWeather(WeatherType.DOWNFALL);
} else {
p.resetPlayerWeather();
}
} }
} }
return true; 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])) position = p; if (p.isMatching(args[1])) {
position = p;
}
} }
if(position == null) { if (position == null) {
PlayerFunctions.sendMessage(plr, C.INVALID_POSITION); PlayerFunctions.sendMessage(plr, C.INVALID_POSITION);
return false; return false;
} }
@ -177,14 +185,14 @@ public class Set extends SubCommand{
return true; 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()) { for (Plot p : PlotMain.getPlots()) {
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;
} }
@ -193,162 +201,162 @@ public class Set extends SubCommand{
PlayerFunctions.sendMessage(plr, C.ALIAS_SET_TO.s().replaceAll("%alias%", alias)); PlayerFunctions.sendMessage(plr, C.ALIAS_SET_TO.s().replaceAll("%alias%", alias));
return true; return true;
} }
if(args[0].equalsIgnoreCase("biome")) { if (args[0].equalsIgnoreCase("biome")) {
if(args.length < 2) { if (args.length < 2) {
PlayerFunctions.sendMessage(plr, C.NEED_BIOME); PlayerFunctions.sendMessage(plr, C.NEED_BIOME);
return true; return true;
} }
Biome biome = null; Biome biome = null;
for(Biome b : Biome.values()) { for (Biome b : Biome.values()) {
if(b.toString().equalsIgnoreCase(args[1])) { if (b.toString().equalsIgnoreCase(args[1])) {
biome = b; biome = b;
break; break;
} }
} }
if(biome == null) { if (biome == null) {
PlayerFunctions.sendMessage(plr, getBiomeList(Arrays.asList(Biome.values()))); PlayerFunctions.sendMessage(plr, getBiomeList(Arrays.asList(Biome.values())));
return true; return true;
} }
PlotHelper.setBiome(plr.getWorld(), plot, biome); PlotHelper.setBiome(plr.getWorld(), plot, biome);
PlayerFunctions.sendMessage(plr, C.BIOME_SET_TO.s() + biome.toString().toLowerCase()); PlayerFunctions.sendMessage(plr, C.BIOME_SET_TO.s() + biome.toString().toLowerCase());
return true; return true;
} }
if(args[0].equalsIgnoreCase("wall")) { if (args[0].equalsIgnoreCase("wall")) {
PlotWorld plotworld = PlotMain.getWorldSettings(plr.getWorld()); PlotWorld plotworld = PlotMain.getWorldSettings(plr.getWorld());
if (plotworld==null) { if (plotworld == null) {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD);
return true;
}
if(args.length < 2) {
PlayerFunctions.sendMessage(plr, C.NEED_BLOCK);
return true;
}
Material material = null;
for(Material m : plotworld.BLOCKS) {
if(m.toString().equalsIgnoreCase(args[1])) {
material = m;
break;
}
}
if(material == null) {
PlayerFunctions.sendMessage(plr, getBlockList(plotworld.BLOCKS));
return true;
}
byte data = 0;
if(args.length > 2) {
try {
data = (byte) Integer.parseInt(args[2]);
} catch(Exception e) {
PlayerFunctions.sendMessage(plr, C.NOT_VALID_DATA);
return true;
}
}
PlayerFunctions.sendMessage(plr, C.GENERATING_WALL);
PlotHelper.adjustWall(plr.getWorld(), plot, (short)material.getId(), data);
return true;
}
if(args[0].equalsIgnoreCase("floor")) {
if(args.length < 2) {
PlayerFunctions.sendMessage(plr, C.NEED_BLOCK);
return true;
}
PlotWorld plotworld = PlotMain.getWorldSettings(plr.getWorld());
if (plotworld==null) {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD); PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD);
return true; return true;
} }
// if (args.length < 2) {
@SuppressWarnings("unchecked") PlayerFunctions.sendMessage(plr, C.NEED_BLOCK);
ArrayList<Material> materials = (ArrayList<Material>) plotworld.BLOCKS.clone(); return true;
materials.add(Material.AIR); }
// Material material = null;
String[] strings = args[1].split(","); for (Material m : PlotWorld.BLOCKS) {
// if (m.toString().equalsIgnoreCase(args[1])) {
Material[] material = new Material[strings.length]; material = m;
byte[] data = new byte[strings.length]; break;
// }
int index = 0; }
// if (material == null) {
byte b = (byte) 0; PlayerFunctions.sendMessage(plr, getBlockList(PlotWorld.BLOCKS));
Material m = null; return true;
// }
for(String s : strings) { byte data = 0;
s = s.replaceAll(",", "");
String[] ss = s.split(";"); if (args.length > 2) {
ss[0] = ss[0].replaceAll(";", ""); try {
for(Material ma : materials) { data = (byte) Integer.parseInt(args[2]);
if(ma.toString().equalsIgnoreCase(ss[0])) { } catch (Exception e) {
m = ma; PlayerFunctions.sendMessage(plr, C.NOT_VALID_DATA);
} return true;
} }
if(m == null) { }
PlayerFunctions.sendMessage(plr, C.NOT_VALID_BLOCK); PlayerFunctions.sendMessage(plr, C.GENERATING_WALL);
return true; PlotHelper.adjustWall(plr.getWorld(), plot, (short) material.getId(), data);
} return true;
if(ss.length == 1) { }
data[index] = (byte) 0; if (args[0].equalsIgnoreCase("floor")) {
material[index] = m; if (args.length < 2) {
} else { PlayerFunctions.sendMessage(plr, C.NEED_BLOCK);
try { return true;
b = (byte) Integer.parseInt(ss[1]); }
} catch(Exception e) { PlotWorld plotworld = PlotMain.getWorldSettings(plr.getWorld());
PlayerFunctions.sendMessage(plr, C.NOT_VALID_DATA); if (plotworld == null) {
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); PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD);
return true; return true;
} }
Material material = null; //
for(Material m : plotworld.BLOCKS) { @SuppressWarnings("unchecked")
if(m.toString().equalsIgnoreCase(args[1])) { ArrayList<Material> materials = (ArrayList<Material>) PlotWorld.BLOCKS.clone();
material = m; materials.add(Material.AIR);
break; //
} String[] strings = args[1].split(",");
} //
if(material == null) { Material[] material = new Material[strings.length];
PlayerFunctions.sendMessage(plr, getBlockList(plotworld.BLOCKS)); byte[] data = new byte[strings.length];
return true; //
} int index = 0;
byte data = 0; //
byte b = (byte) 0;
Material m = null;
//
for (String s : strings) {
s = s.replaceAll(",", "");
String[] ss = s.split(";");
ss[0] = ss[0].replaceAll(";", "");
for (Material ma : materials) {
if (ma.toString().equalsIgnoreCase(ss[0])) {
m = ma;
}
}
if (m == null) {
PlayerFunctions.sendMessage(plr, C.NOT_VALID_BLOCK);
return true;
}
if (ss.length == 1) {
data[index] = (byte) 0;
material[index] = m;
} else {
try {
b = (byte) Integer.parseInt(ss[1]);
} catch (Exception e) {
PlayerFunctions.sendMessage(plr, C.NOT_VALID_DATA);
return true;
}
data[index] = b;
material[index] = m;
}
index++;
}
PlotHelper.setFloor(plr, plot, material, data);
return true;
}
if (args[0].equalsIgnoreCase("wall_filling")) {
if (args.length < 2) {
PlayerFunctions.sendMessage(plr, C.NEED_BLOCK);
return true;
}
PlotWorld plotworld = PlotMain.getWorldSettings(plr.getWorld());
if (plotworld == null) {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD);
return true;
}
Material material = null;
for (Material m : PlotWorld.BLOCKS) {
if (m.toString().equalsIgnoreCase(args[1])) {
material = m;
break;
}
}
if (material == null) {
PlayerFunctions.sendMessage(plr, getBlockList(PlotWorld.BLOCKS));
return true;
}
byte data = 0;
if(args.length > 2) { 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;
} }
} }
PlotHelper.adjustWallFilling(plr, plr.getWorld(), plot, (short)material.getId(), data); PlotHelper.adjustWallFilling(plr, plr.getWorld(), plot, (short) material.getId(), data);
return true; return true;
} }
PlayerFunctions.sendMessage(plr, "Not a valid option. Use {TODO: Insert list.}"); PlayerFunctions.sendMessage(plr, "Not a valid option. Use {TODO: Insert list.}");
return true; return true;
} }
private String getMaterial(Material m) { private String getMaterial(Material m) {
return ChatColor.translateAlternateColorCodes('&', C.BLOCK_LIST_ITEM.s().replaceAll("%mat%", m.toString().toLowerCase())); return ChatColor.translateAlternateColorCodes('&', C.BLOCK_LIST_ITEM.s().replaceAll("%mat%", m.toString().toLowerCase()));
} }
private String getBiome(Biome b) { private String getBiome(Biome b) {
return ChatColor.translateAlternateColorCodes('&', C.BLOCK_LIST_ITEM.s().replaceAll("%mat%", b.toString().toLowerCase())); return ChatColor.translateAlternateColorCodes('&', C.BLOCK_LIST_ITEM.s().replaceAll("%mat%", b.toString().toLowerCase()));
} }
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));
@ -356,29 +364,28 @@ public class Set extends SubCommand{
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 getBiomeList(List<Biome> biomes) { private String getBiomeList(List<Biome> biomes) {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
builder.append(ChatColor.translateAlternateColorCodes('&', C.NOT_VALID_BLOCK_LIST_HEADER.s())); builder.append(ChatColor.translateAlternateColorCodes('&', C.NOT_VALID_BLOCK_LIST_HEADER.s()));
for(Biome b : biomes) { for (Biome b : biomes) {
builder.append(getBiome(b)); builder.append(getBiome(b));
} }
return builder.toString().substring(1,builder.toString().length() - 1); 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);
}
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,19 +9,20 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.C; import java.util.UUID;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.PlotMain;
import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.Plot;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer; import org.bukkit.OfflinePlayer;
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.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);
@ -29,16 +30,17 @@ public class SetOwner extends SubCommand{
private UUID getUUID(String string) { private UUID getUUID(String string) {
OfflinePlayer player = Bukkit.getOfflinePlayer(string); OfflinePlayer player = Bukkit.getOfflinePlayer(string);
return (player != null && player.hasPlayedBefore()) ? player.getUniqueId() : null; return ((player != null) && player.hasPlayedBefore()) ? player.getUniqueId() : null;
} }
@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;
} }

View File

@ -9,33 +9,35 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
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 org.bukkit.entity.Player;
/** /**
* SubCommand class * SubCommand class
*
* @author Citymonstret * @author Citymonstret
* *
*/ */
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
@ -46,30 +48,40 @@ public abstract class SubCommand {
/** /**
* *
* @param cmd Command /plot {cmd} <-- That! * @param cmd
* @param permission Permission Node * Command /plot {cmd} <-- That!
* @param description Simple description * @param permission
* @param usage Usage description: /plot command {args...} * Permission Node
* @param alias Command alias * @param description
* @param category CommandCategory. Pick whichever closests to what you want. * Simple description
* @param usage
* Usage description: /plot command {args...}
* @param alias
* Command alias
* @param category
* CommandCategory. Pick whichever closests to what you want.
*/ */
public SubCommand(String cmd, String permission, String description, String usage, String alias, CommandCategory category) { public SubCommand(String cmd, String permission, String description, String usage, String alias, CommandCategory category) {
this.cmd = cmd; this.cmd = cmd;
this.permission = new CommandPermission(permission); this.permission = new CommandPermission(permission);
this.description = description; this.description = description;
this.alias = alias; this.alias = alias;
this.usage = usage; this.usage = usage;
this.category = category; this.category = category;
} }
/** /**
* *
* @param command Command /plot {cmd} <-- That! * @param command
* @param description Simple description * Command /plot {cmd} <-- That!
* @param usage Usage description: /plot command {args...} * @param description
* @param category CommandCategory. Pick whichever closests to what you want. * Simple description
* @param usage
* Usage description: /plot command {args...}
* @param category
* CommandCategory. Pick whichever closests to what you want.
*/ */
public SubCommand(Command command, String description, String usage, CommandCategory category) { public SubCommand(Command command, String description, String usage, CommandCategory category) {
this.cmd = command.getCommand(); this.cmd = command.getCommand();
this.permission = command.getPermission(); this.permission = command.getPermission();
this.alias = command.getAlias(); this.alias = command.getAlias();
@ -77,29 +89,34 @@ public abstract class SubCommand {
this.usage = usage; this.usage = usage;
this.category = category; this.category = category;
} }
/**
* Execute.
* @param plr executor
* @param args arguments
* @return true on success, false on failure
*/
public abstract boolean execute(Player plr, String ... args);
public void executeConsole(String ... args) { this.execute(null, args); }
public void sendMessage(Player plr, C c, String ... args) { /**
* Execute.
*
* @param plr
* executor
* @param args
* arguments
* @return true on success, false on failure
*/
public abstract boolean execute(Player plr, String... args);
public void executeConsole(String... args) {
this.execute(null, args);
}
public void 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"), CLAIMING("Claiming"), TELEPORT("Teleportation"), ACTIONS("Actions"), INFO("Information");
TELEPORT("Teleportation"),
ACTIONS("Actions"),
INFO("Information");
private String name; 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

@ -9,12 +9,17 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.*;
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;
/** /**
* *
* @author Citymonstret * @author Citymonstret
@ -22,47 +27,48 @@ import org.bukkit.entity.Player;
*/ */
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)) { }
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD); if (!PlotMain.isPlotWorld(world)) {
return false; PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD);
} return false;
}
Plot temp; Plot temp;
if((temp = isAlias(id)) != null) { if ((temp = isAlias(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]), Integer.parseInt(id.split(";")[1]));
PlotMain.teleportPlayer(plr, plr.getLocation(), PlotHelper.getPlot(world, plotid)); PlotMain.teleportPlayer(plr, plr.getLocation(), PlotHelper.getPlot(world, plotid));
return true; return true;
} } catch (Exception e) {
catch (Exception e) { PlayerFunctions.sendMessage(plr, C.NOT_VALID_PLOT_ID);
PlayerFunctions.sendMessage(plr, C.NOT_VALID_PLOT_ID); }
} return false;
return false; }
}
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) && p.settings.getAlias().equalsIgnoreCase(a)) {
return p; return p;
}
} }
return null; return null;
} }

View File

@ -9,42 +9,46 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.*;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
public class Visit extends SubCommand{ import com.intellectualcrafters.plot.C;
import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.Plot;
import com.intellectualcrafters.plot.PlotMain;
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<Plot>(); List<Plot> plots = new ArrayList<Plot>();
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;
} }
@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).getUniqueId());
if(plots.isEmpty()) { if (plots.isEmpty()) {
PlayerFunctions.sendMessage(plr, C.FOUND_NO_PLOTS); PlayerFunctions.sendMessage(plr, C.FOUND_NO_PLOTS);
return true; return true;
} }
if(args.length < 2){ if (args.length < 2) {
Plot plot = plots.get(0); Plot plot = plots.get(0);
PlotMain.teleportPlayer(plr, plr.getLocation(), plot); PlotMain.teleportPlayer(plr, plr.getLocation(), plot);
return true; return true;
@ -52,11 +56,11 @@ public class Visit extends SubCommand{
int i; int i;
try { try {
i = Integer.parseInt(args[1]); i = Integer.parseInt(args[1]);
} catch(Exception e) { } catch (Exception e) {
PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER); PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER);
return true; return true;
} }
if(i < 0 || i > plots.size()) { if ((i < 0) || (i > plots.size())) {
PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER); PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER);
return true; return true;
} }

View File

@ -9,94 +9,94 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import java.util.HashMap;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
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.PlotId; import com.intellectualcrafters.plot.PlotId;
import com.intellectualcrafters.plot.PlotMain; import com.intellectualcrafters.plot.PlotMain;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import java.util.HashMap;
import java.util.UUID;
/** /**
* *
* @author Citymonstret * @author Citymonstret
* *
*/ */
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", "all", "world"})); builder.append(getArgumentList(new String[] { "mine", "all", "world" }));
PlayerFunctions.sendMessage(plr, builder.toString()); PlayerFunctions.sendMessage(plr, builder.toString());
return true; return true;
} }
if(args[0].equalsIgnoreCase("mine")) { if (args[0].equalsIgnoreCase("mine")) {
StringBuilder string = new StringBuilder(); StringBuilder string = new StringBuilder();
string.append(C.PLOT_LIST_HEADER.s().replaceAll("%word%", "your") + "\n"); string.append(C.PLOT_LIST_HEADER.s().replaceAll("%word%", "your") + "\n");
int idx = 0; int idx = 0;
for(Plot p : PlotMain.getPlots(plr)) { for (Plot p : PlotMain.getPlots(plr)) {
string.append(C.PLOT_LIST_ITEM.s().replaceAll("%id%", p.id.x+";"+p.id.y+";"+p.world).replaceAll("%owner%", getName(p.owner)) + "\n"); string.append(C.PLOT_LIST_ITEM.s().replaceAll("%id%", p.id.x + ";" + p.id.y + ";" + p.world).replaceAll("%owner%", getName(p.owner)) + "\n");
idx++; idx++;
} }
if(idx == 0) { if (idx == 0) {
PlayerFunctions.sendMessage(plr, C.NO_PLOTS); PlayerFunctions.sendMessage(plr, C.NO_PLOTS);
return true; return true;
} }
string.append(C.PLOT_LIST_FOOTER.s().replaceAll("%word%", "You have").replaceAll("%num%", idx + "").replaceAll("%plot%", idx == 1 ? "plot" : "plots")); string.append(C.PLOT_LIST_FOOTER.s().replaceAll("%word%", "You have").replaceAll("%num%", idx + "").replaceAll("%plot%", idx == 1 ? "plot" : "plots"));
PlayerFunctions.sendMessage(plr, string.toString()); PlayerFunctions.sendMessage(plr, string.toString());
return true; return true;
} else if(args[0].equalsIgnoreCase("all")) { } else if (args[0].equalsIgnoreCase("all")) {
StringBuilder string = new StringBuilder(); StringBuilder string = new StringBuilder();
string.append(C.PLOT_LIST_HEADER.s().replaceAll("%word%", "all") + "\n"); string.append(C.PLOT_LIST_HEADER.s().replaceAll("%word%", "all") + "\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"); 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")); 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("world")) { } else if (args[0].equalsIgnoreCase("world")) {
StringBuilder string = new StringBuilder(); StringBuilder string = new StringBuilder();
string.append(C.PLOT_LIST_HEADER.s().replaceAll("%word%", "all") + "\n"); string.append(C.PLOT_LIST_HEADER.s().replaceAll("%word%", "all") + "\n");
HashMap<PlotId, Plot> plots = PlotMain.getPlots(plr.getWorld()); HashMap<PlotId, Plot> plots = PlotMain.getPlots(plr.getWorld());
for(Plot p : plots.values()) { 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_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")); 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()); PlayerFunctions.sendMessage(plr, string.toString());
return true; return true;
} } else {
else {
execute(plr); execute(plr);
return false; return false;
} }
} }
private static String getName(UUID id) {
if (id == null) {
return "none";
}
return Bukkit.getOfflinePlayer(id).getName();
}
private static String getName(UUID id) {
if(id == null)
return "none";
return Bukkit.getOfflinePlayer(id).getName();
}
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,12 +9,13 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.PlotMain; import java.util.ArrayList;
import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.Settings;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import java.util.ArrayList; import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.PlotMain;
import com.intellectualcrafters.plot.Settings;
public class plugin extends SubCommand { public class plugin extends SubCommand {
@ -23,7 +24,7 @@ public class plugin extends SubCommand {
} }
@Override @Override
public boolean execute(Player plr, String ... args) { public boolean execute(Player plr, String... args) {
ArrayList<String> strings = new ArrayList<String>() { ArrayList<String> strings = new ArrayList<String>() {
{ {
add(String.format("&c>> &6PlotSquared (Version: %s)", PlotMain.getMain().getDescription().getVersion())); add(String.format("&c>> &6PlotSquared (Version: %s)", PlotMain.getMain().getDescription().getVersion()));
@ -31,10 +32,10 @@ public class plugin extends SubCommand {
add(String.format("&c>> &6Download at %s", Settings.URL)); add(String.format("&c>> &6Download at %s", Settings.URL));
} }
}; };
for(String s : strings) for (String s : strings) {
PlayerFunctions.sendMessage(plr, s); PlayerFunctions.sendMessage(plr, s);
}
return true; return true;
} }
} }

View File

@ -9,18 +9,29 @@
package com.intellectualcrafters.plot.database; package com.intellectualcrafters.plot.database;
import com.intellectualcrafters.plot.*; import static com.intellectualcrafters.plot.PlotMain.connection;
import com.intellectualcrafters.plot.Logger.LogLevel;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.block.Biome;
import java.sql.*; import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.UUID; import java.util.UUID;
import static com.intellectualcrafters.plot.PlotMain.connection; import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.block.Biome;
import com.intellectualcrafters.plot.Flag;
import com.intellectualcrafters.plot.FlagManager;
import com.intellectualcrafters.plot.Logger;
import com.intellectualcrafters.plot.Logger.LogLevel;
import com.intellectualcrafters.plot.Plot;
import com.intellectualcrafters.plot.PlotHomePosition;
import com.intellectualcrafters.plot.PlotId;
import com.intellectualcrafters.plot.PlotMain;
/** /**
* @author Citymonstret * @author Citymonstret
@ -84,83 +95,17 @@ public class DBFunc {
Statement stmt = connection.createStatement(); Statement stmt = connection.createStatement();
if (mysql) { if (mysql) {
stmt.addBatch( stmt.addBatch("CREATE TABLE IF NOT EXISTS `plot` (" + "`id` INT(11) NOT NULL AUTO_INCREMENT," + "`plot_id_x` INT(11) NOT NULL," + "`plot_id_z` INT(11) NOT NULL," + "`owner` VARCHAR(45) NOT NULL," + "`world` VARCHAR(45) NOT NULL," + "`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP," + "PRIMARY KEY (`id`)" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=0");
"CREATE TABLE IF NOT EXISTS `plot` (" + stmt.addBatch("CREATE TABLE IF NOT EXISTS `plot_denied` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8");
"`id` INT(11) NOT NULL AUTO_INCREMENT," + stmt.addBatch("CREATE TABLE IF NOT EXISTS `plot_helpers` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8");
"`plot_id_x` INT(11) NOT NULL," + stmt.addBatch("CREATE TABLE IF NOT EXISTS `plot_settings` (" + " `plot_plot_id` INT(11) NOT NULL," + " `biome` VARCHAR(45) DEFAULT 'FOREST'," + " `rain` INT(1) DEFAULT 0," + " `custom_time` TINYINT(1) DEFAULT '0'," + " `time` INT(11) DEFAULT '8000'," + " `deny_entry` TINYINT(1) DEFAULT '0'," + " `alias` VARCHAR(50) DEFAULT NULL," + " `flags` VARCHAR(512) DEFAULT NULL," + " `position` VARCHAR(50) NOT NULL DEFAULT 'DEFAULT'," + " PRIMARY KEY (`plot_plot_id`)," + " UNIQUE KEY `unique_alias` (`alias`)" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8");
"`plot_id_z` INT(11) NOT NULL," + stmt.addBatch("ALTER TABLE `plot_settings` ADD CONSTRAINT `plot_settings_ibfk_1` FOREIGN KEY (`plot_plot_id`) REFERENCES `plot` (`id`) ON DELETE CASCADE");
"`owner` VARCHAR(45) NOT NULL," +
"`world` VARCHAR(45) NOT NULL," +
"`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP," +
"PRIMARY KEY (`id`)" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=0");
stmt.addBatch(
"CREATE TABLE IF NOT EXISTS `plot_denied` (" +
"`plot_plot_id` INT(11) NOT NULL," +
"`user_uuid` VARCHAR(40) NOT NULL" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8"
);
stmt.addBatch(
"CREATE TABLE IF NOT EXISTS `plot_helpers` (" +
"`plot_plot_id` INT(11) NOT NULL," +
"`user_uuid` VARCHAR(40) NOT NULL" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8"
);
stmt.addBatch(
"CREATE TABLE IF NOT EXISTS `plot_settings` (" +
" `plot_plot_id` INT(11) NOT NULL," +
" `biome` VARCHAR(45) DEFAULT 'FOREST'," +
" `rain` INT(1) DEFAULT 0," +
" `custom_time` TINYINT(1) DEFAULT '0'," +
" `time` INT(11) DEFAULT '8000'," +
" `deny_entry` TINYINT(1) DEFAULT '0'," +
" `alias` VARCHAR(50) DEFAULT NULL," +
" `flags` VARCHAR(512) DEFAULT NULL," +
" `position` VARCHAR(50) NOT NULL DEFAULT 'DEFAULT'," +
" PRIMARY KEY (`plot_plot_id`)," +
" UNIQUE KEY `unique_alias` (`alias`)" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8"
);
stmt.addBatch(
"ALTER TABLE `plot_settings` ADD CONSTRAINT `plot_settings_ibfk_1` FOREIGN KEY (`plot_plot_id`) REFERENCES `plot` (`id`) ON DELETE CASCADE"
);
} else { } else {
stmt.addBatch( stmt.addBatch("CREATE TABLE IF NOT EXISTS `plot` (" + "`id` INTEGER(11) PRIMARY KEY," + "`plot_id_x` INT(11) NOT NULL," + "`plot_id_z` INT(11) NOT NULL," + "`owner` VARCHAR(45) NOT NULL," + "`world` VARCHAR(45) NOT NULL," + "`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP)");
"CREATE TABLE IF NOT EXISTS `plot` (" + stmt.addBatch("CREATE TABLE IF NOT EXISTS `plot_denied` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ")");
"`id` INTEGER(11) PRIMARY KEY," + stmt.addBatch("CREATE TABLE IF NOT EXISTS `plot_helpers` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ")");
"`plot_id_x` INT(11) NOT NULL," + stmt.addBatch("CREATE TABLE IF NOT EXISTS `plot_settings` (" + " `plot_plot_id` INT(11) NOT NULL," + " `biome` VARCHAR(45) DEFAULT 'FOREST'," + " `rain` INT(1) DEFAULT 0," + " `custom_time` TINYINT(1) DEFAULT '0'," + " `time` INT(11) DEFAULT '8000'," + " `deny_entry` TINYINT(1) DEFAULT '0'," + " `alias` VARCHAR(50) DEFAULT NULL," + " `flags` VARCHAR(512) DEFAULT NULL," + " `position` VARCHAR(50) NOT NULL DEFAULT 'DEFAULT'," + " PRIMARY KEY (`plot_plot_id`)" + ")");
"`plot_id_z` INT(11) NOT NULL," +
"`owner` VARCHAR(45) NOT NULL," +
"`world` VARCHAR(45) NOT NULL," +
"`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP)"
);
stmt.addBatch(
"CREATE TABLE IF NOT EXISTS `plot_denied` (" +
"`plot_plot_id` INT(11) NOT NULL," +
"`user_uuid` VARCHAR(40) NOT NULL" +
")"
);
stmt.addBatch(
"CREATE TABLE IF NOT EXISTS `plot_helpers` (" +
"`plot_plot_id` INT(11) NOT NULL," +
"`user_uuid` VARCHAR(40) NOT NULL" +
")"
);
stmt.addBatch(
"CREATE TABLE IF NOT EXISTS `plot_settings` (" +
" `plot_plot_id` INT(11) NOT NULL," +
" `biome` VARCHAR(45) DEFAULT 'FOREST'," +
" `rain` INT(1) DEFAULT 0," +
" `custom_time` TINYINT(1) DEFAULT '0'," +
" `time` INT(11) DEFAULT '8000'," +
" `deny_entry` TINYINT(1) DEFAULT '0'," +
" `alias` VARCHAR(50) DEFAULT NULL," +
" `flags` VARCHAR(512) DEFAULT NULL," +
" `position` VARCHAR(50) NOT NULL DEFAULT 'DEFAULT'," +
" PRIMARY KEY (`plot_plot_id`)" +
")"
);
} }
stmt.executeBatch(); stmt.executeBatch();
@ -168,34 +113,34 @@ public class DBFunc {
stmt.close(); stmt.close();
/** /**
* Adding missing columns (for older versions) * Adding missing columns (for older versions) + get current columns
* + get current columns (continue if they do not match the current number of columns) * (continue if they do not match the current number of columns) + get
* + get data from plot_id column * data from plot_id column - create column (plot_id_x,plot_id_z,world)
* - create column (plot_id_x,plot_id_z,world) * - populate plot_id_x, plot_id_z with data from plot_id - populate
* - populate plot_id_x, plot_id_z with data from plot_id * world column with PlotMain.config.getString("plot_world") - which
* - populate world column with PlotMain.config.getString("plot_world") - which will be set from previous release; * will be set from previous release;
*/ */
/** /**
* `plot` * `plot`
*/ */
// int target_len = 6; // int target_len = 6;
// ArrayList<String> ids = new ArrayList<String>(); // ArrayList<String> ids = new ArrayList<String>();
// stmt = connection.createStatement(); // stmt = connection.createStatement();
// String table = "plot"; // String table = "plot";
// ResultSet rs = stmt.executeQuery("SELECT * FROM `"+table+"`"); // ResultSet rs = stmt.executeQuery("SELECT * FROM `"+table+"`");
// ResultSetMetaData md = rs.getMetaData(); // ResultSetMetaData md = rs.getMetaData();
// int len = md.getColumnCount(); // int len = md.getColumnCount();
// if (len<target_len) { // if (len<target_len) {
// HashSet<String> cols = new HashSet<String>(); // HashSet<String> cols = new HashSet<String>();
// for (int i = 1; i <= len; i++) { // for (int i = 1; i <= len; i++) {
// cols.add(md.getColumnName(i)); // cols.add(md.getColumnName(i));
// } // }
// while (rs.next()) { // while (rs.next()) {
// ids.add(rs.getString("plot_id")); // ids.add(rs.getString("plot_id"));
// } // }
// } // }
// stmt.close(); // stmt.close();
} }
/** /**
@ -245,8 +190,7 @@ public class DBFunc {
public void run() { public void run() {
PreparedStatement stmt = null; PreparedStatement stmt = null;
try { try {
stmt = connection.prepareStatement("INSERT INTO `plot_settings`(`plot_plot_id`) VALUES(" + stmt = connection.prepareStatement("INSERT INTO `plot_settings`(`plot_plot_id`) VALUES(" + "?)");
"?)");
stmt.setInt(1, id); stmt.setInt(1, id);
stmt.executeUpdate(); stmt.executeUpdate();
stmt.close(); stmt.close();
@ -278,28 +222,22 @@ public class DBFunc {
return Integer.MAX_VALUE; return Integer.MAX_VALUE;
} }
/** /**
* Get a plot id * Get a plot id
*
* @param plot_id * @param plot_id
* @return * @return
*/ */
/*public static int getId(String world, PlotId id2) { /*
Statement stmt = null; * public static int getId(String world, PlotId id2) { Statement stmt =
try { * null; try { stmt = connection.createStatement(); ResultSet r =
stmt = connection.createStatement(); * stmt.executeQuery("SELECT `id` FROM `plot` WHERE `plot_id_x` = '" + id2.x
ResultSet r = stmt.executeQuery("SELECT `id` FROM `plot` WHERE `plot_id_x` = '" + id2.x + "' AND `plot_id_z` = '" + id2.y + "' AND `world` = '" + world + "' ORDER BY `timestamp` ASC"); * + "' AND `plot_id_z` = '" + id2.y + "' AND `world` = '" + world +
int id = Integer.MAX_VALUE; * "' ORDER BY `timestamp` ASC"); int id = Integer.MAX_VALUE;
while(r.next()) { * while(r.next()) { id = r.getInt("id"); } stmt.close(); return id; }
id = r.getInt("id"); * catch(SQLException e) { e.printStackTrace(); } return Integer.MAX_VALUE;
} * }
stmt.close(); */
return id;
} catch(SQLException e) {
e.printStackTrace();
}
return Integer.MAX_VALUE;
}*/
/** /**
* @return * @return
@ -311,31 +249,11 @@ public class DBFunc {
boolean execute = rs.next(); boolean execute = rs.next();
if (execute) { if (execute) {
Statement statement = connection.createStatement(); Statement statement = connection.createStatement();
statement.addBatch( statement.addBatch("ALTER IGNORE TABLE `plot` ADD `plot_id_x` int(11) DEFAULT 0");
"ALTER IGNORE TABLE `plot` ADD `plot_id_x` int(11) DEFAULT 0" statement.addBatch("ALTER IGNORE TABLE `plot` ADD `plot_id_z` int(11) DEFAULT 0");
); statement.addBatch("UPDATE `plot` SET\n" + " `plot_id_x` = IF(" + " LOCATE(';', `plot_id`) > 0," + " SUBSTRING(`plot_id`, 1, LOCATE(';', `plot_id`) - 1)," + " `plot_id`" + " )," + " `plot_id_z` = IF(" + " LOCATE(';', `plot_id`) > 0," + " SUBSTRING(`plot_id`, LOCATE(';', `plot_id`) + 1)," + " NULL" + " )");
statement.addBatch( statement.addBatch("ALTER TABLE `plot` DROP `plot_id`");
"ALTER IGNORE TABLE `plot` ADD `plot_id_z` int(11) DEFAULT 0" statement.addBatch("ALTER IGNORE TABLE `plot_settings` ADD `flags` VARCHAR(512) DEFAULT NULL");
);
statement.addBatch(
"UPDATE `plot` SET\n" +
" `plot_id_x` = IF(" +
" LOCATE(';', `plot_id`) > 0," +
" SUBSTRING(`plot_id`, 1, LOCATE(';', `plot_id`) - 1)," +
" `plot_id`" +
" )," +
" `plot_id_z` = IF(" +
" LOCATE(';', `plot_id`) > 0," +
" SUBSTRING(`plot_id`, LOCATE(';', `plot_id`) + 1)," +
" NULL" +
" )"
);
statement.addBatch(
"ALTER TABLE `plot` DROP `plot_id`"
);
statement.addBatch(
"ALTER IGNORE TABLE `plot_settings` ADD `flags` VARCHAR(512) DEFAULT NULL"
);
statement.executeBatch(); statement.executeBatch();
statement.close(); statement.close();
} }
@ -343,7 +261,7 @@ public class DBFunc {
e.printStackTrace(); e.printStackTrace();
} }
HashMap<String, HashMap<PlotId, Plot>> plots = new HashMap<String, HashMap<PlotId, Plot>>(); HashMap<String, HashMap<PlotId, Plot>> plots = new HashMap<String, HashMap<PlotId, Plot>>();
HashMap<String, World> worldMap = new HashMap<String, World>(); new HashMap<String, World>();
Statement stmt = null; Statement stmt = null;
try { try {
stmt = connection.createStatement(); stmt = connection.createStatement();
@ -351,21 +269,24 @@ public class DBFunc {
PlotId plot_id; PlotId plot_id;
int id; int id;
Plot p; Plot p;
World w;
while (r.next()) { while (r.next()) {
plot_id = new PlotId(r.getInt("plot_id_x"), r.getInt("plot_id_z")); plot_id = new PlotId(r.getInt("plot_id_x"), r.getInt("plot_id_z"));
id = r.getInt("id"); id = r.getInt("id");
String worldname = r.getString("world"); String worldname = r.getString("world");
// Quicker to get cache the UUID to the World than to convert each time. // Quicker to get cache the UUID to the World than to convert
// each time.
HashMap<String, Object> settings = getSettings(id); HashMap<String, Object> settings = getSettings(id);
UUID owner = UUID.fromString(r.getString("owner")); UUID owner = UUID.fromString(r.getString("owner"));
Biome plotBiome = Biome.valueOf((String) settings.get("biome")); Biome plotBiome = Biome.valueOf((String) settings.get("biome"));
if (plotBiome == null) plotBiome = Biome.FOREST; if (plotBiome == null) {
plotBiome = Biome.FOREST;
}
String[] flags_string; String[] flags_string;
if (settings.get("flags") == null) if (settings.get("flags") == null) {
flags_string = new String[]{}; flags_string = new String[] {};
else } else {
flags_string = ((String) settings.get("flags")).split(","); flags_string = ((String) settings.get("flags")).split(",");
}
Flag[] flags = new Flag[flags_string.length]; Flag[] flags = new Flag[flags_string.length];
for (int i = 0; i < flags.length; i++) { for (int i = 0; i < flags.length; i++) {
if (flags_string[i].contains(":")) { if (flags_string[i].contains(":")) {
@ -378,21 +299,31 @@ public class DBFunc {
ArrayList<UUID> helpers = plotHelpers(id); ArrayList<UUID> helpers = plotHelpers(id);
ArrayList<UUID> denied = plotDenied(id); ArrayList<UUID> denied = plotDenied(id);
//boolean changeTime = ((Short) settings.get("custom_time") == 0) ? false : true; // boolean changeTime = ((Short) settings.get("custom_time") ==
// 0) ? false : true;
long time = 8000l; long time = 8000l;
//if(changeTime) { // if(changeTime) {
// time = Long.parseLong(settings.get("time").toString()); // time = Long.parseLong(settings.get("time").toString());
//} // }
//boolean rain = Integer.parseInt(settings.get("rain").toString()) == 1 ? true : false; // boolean rain =
// Integer.parseInt(settings.get("rain").toString()) == 1 ? true
// : false;
boolean rain = false; boolean rain = false;
String alias = (String) settings.get("alias"); String alias = (String) settings.get("alias");
if (alias == null || alias.equalsIgnoreCase("NEW")) alias = ""; if ((alias == null) || alias.equalsIgnoreCase("NEW")) {
alias = "";
}
PlotHomePosition position = null; PlotHomePosition position = null;
for (PlotHomePosition plotHomePosition : PlotHomePosition.values()) for (PlotHomePosition plotHomePosition : PlotHomePosition.values()) {
if (plotHomePosition.isMatching((String) settings.get("position"))) position = plotHomePosition; if (plotHomePosition.isMatching((String) settings.get("position"))) {
if (position == null) position = PlotHomePosition.DEFAULT; position = plotHomePosition;
}
}
if (position == null) {
position = PlotHomePosition.DEFAULT;
}
p = new Plot(plot_id, owner, plotBiome, helpers, denied, /*changeTime*/ false, time, rain, alias, position, flags, worldname); p = new Plot(plot_id, owner, plotBiome, helpers, denied, /* changeTime */false, time, rain, alias, position, flags, worldname);
if (plots.containsKey(worldname)) { if (plots.containsKey(worldname)) {
plots.get(worldname).put((plot_id), p); plots.get(worldname).put((plot_id), p);
} else { } else {
@ -438,8 +369,9 @@ public class DBFunc {
final StringBuilder flag_string = new StringBuilder(); final StringBuilder flag_string = new StringBuilder();
int i = 0; int i = 0;
for (Flag flag : flags) { for (Flag flag : flags) {
if (i != 0) if (i != 0) {
flag_string.append(","); flag_string.append(",");
}
flag_string.append(flag.getKey() + ":" + flag.getValue()); flag_string.append(flag.getKey() + ":" + flag.getValue());
i++; i++;
} }

View File

@ -7,95 +7,92 @@ import java.sql.SQLException;
import org.bukkit.plugin.Plugin; import org.bukkit.plugin.Plugin;
/** /**
* Abstract Database class, serves as a base for any connection method (MySQL, * Abstract Database class, serves as a base for any connection method (MySQL,
* SQLite, etc.) * SQLite, etc.)
* *
* @author -_Husky_- * @author -_Husky_-
* @author tips48 * @author tips48
*/ */
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, public abstract Connection openConnection() throws SQLException, ClassNotFoundException;
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>
/** * See {@link java.sql.Statement#executeUpdate(String)}<br>
* Executes an Update SQL Query<br> * If the connection is closed, it will be opened
* See {@link java.sql.Statement#executeUpdate(String)}<br> *
* If the connection is closed, it will be opened * @param query
* * Query to be run
* @param query * @return Result Code, see {@link java.sql.Statement#executeUpdate(String)}
* Query to be run * @throws SQLException
* @return Result Code, see {@link java.sql.Statement#executeUpdate(String)} * If the query cannot be executed
* @throws SQLException * @throws ClassNotFoundException
* If the query cannot be executed * If the driver cannot be found; see {@link #openConnection()}
* @throws ClassNotFoundException */
* 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

@ -1,13 +1,13 @@
package com.intellectualcrafters.plot.database; package com.intellectualcrafters.plot.database;
import org.bukkit.plugin.Plugin;
import java.sql.Connection; import java.sql.Connection;
import java.sql.DriverManager; import java.sql.DriverManager;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import org.bukkit.plugin.Plugin;
/** /**
* Connects to and uses a MySQL database * Connects to and uses a MySQL database
* *
@ -15,99 +15,93 @@ import java.sql.Statement;
* @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, public MySQL(Plugin plugin, String hostname, String port, String database, String username, String password) {
String username, String password) { super(plugin);
super(plugin); this.hostname = hostname;
this.hostname = hostname; this.port = port;
this.port = port; this.database = database;
this.database = database; this.user = username;
this.user = username; this.password = password;
this.password = password; this.connection = null;
this.connection = null; }
}
@Override @Override
public Connection openConnection() throws SQLException, public Connection openConnection() throws SQLException, ClassNotFoundException {
ClassNotFoundException { if (checkConnection()) {
if (checkConnection()) { return this.connection;
return connection; }
} Class.forName("com.mysql.jdbc.Driver");
Class.forName("com.mysql.jdbc.Driver"); this.connection = DriverManager.getConnection("jdbc:mysql://" + this.hostname + ":" + this.port + "/" + this.database, this.user, this.password);
connection = DriverManager.getConnection("jdbc:mysql://" return this.connection;
+ this.hostname + ":" + this.port + "/" + this.database, }
this.user, this.password);
return connection;
}
@Override @Override
public boolean checkConnection() throws SQLException { public boolean checkConnection() throws SQLException {
return connection != null && !connection.isClosed(); return (this.connection != null) && !this.connection.isClosed();
} }
@Override @Override
public Connection getConnection() { public Connection getConnection() {
return connection; return this.connection;
} }
@Override @Override
public boolean closeConnection() throws SQLException { public boolean closeConnection() throws SQLException {
if (connection == null) { if (this.connection == null) {
return false; return false;
} }
connection.close(); this.connection.close();
return true; return true;
} }
@Override @Override
public ResultSet querySQL(String query) throws SQLException, public ResultSet querySQL(String query) throws SQLException, ClassNotFoundException {
ClassNotFoundException { if (checkConnection()) {
if (checkConnection()) { openConnection();
openConnection(); }
}
Statement statement = 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, public int updateSQL(String query) throws SQLException, ClassNotFoundException {
ClassNotFoundException { if (checkConnection()) {
if (checkConnection()) { openConnection();
openConnection(); }
}
Statement statement = connection.createStatement(); Statement statement = this.connection.createStatement();
int result = statement.executeUpdate(query); int result = statement.executeUpdate(query);
return result; return result;
} }
} }

View File

@ -1,14 +1,5 @@
package com.intellectualcrafters.plot.database; package com.intellectualcrafters.plot.database;
import com.intellectualcrafters.plot.PlotHomePosition;
import com.intellectualcrafters.plot.PlotId;
import com.intellectualcrafters.plot.PlotMain;
import com.worldcretornica.plotme.PlayerList;
import com.worldcretornica.plotme.Plot;
import com.worldcretornica.plotme.PlotManager;
import org.bukkit.Bukkit;
import org.bukkit.World;
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;
@ -16,6 +7,16 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.World;
import com.intellectualcrafters.plot.PlotHomePosition;
import com.intellectualcrafters.plot.PlotId;
import com.intellectualcrafters.plot.PlotMain;
import com.worldcretornica.plotme.PlayerList;
import com.worldcretornica.plotme.Plot;
import com.worldcretornica.plotme.PlotManager;
/** /**
* Created by Citymonstret on 2014-08-17. * Created by Citymonstret on 2014-08-17.
*/ */
@ -31,18 +32,18 @@ public class PlotMeConverter {
final PrintStream stream = new PrintStream("converter_log.txt"); final PrintStream stream = new PrintStream("converter_log.txt");
PlotMain.sendConsoleSenderMessage("PlotMe->PlotSquared Conversion has started"); PlotMain.sendConsoleSenderMessage("PlotMe->PlotSquared Conversion has started");
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { Bukkit.getScheduler().runTaskAsynchronously(this.plugin, new Runnable() {
@Override @Override
public void run() { public void run() {
for (World world:Bukkit.getWorlds()) { for (World world : Bukkit.getWorlds()) {
HashMap<String, Plot> plots = PlotManager.getPlots(world); HashMap<String, Plot> plots = PlotManager.getPlots(world);
PlotMain.sendConsoleSenderMessage("Converting "+plots.size()+" plots for '"+world.toString()+"'..."); PlotMain.sendConsoleSenderMessage("Converting " + plots.size() + " plots for '" + world.toString() + "'...");
for (Plot plot : plots.values()) { for (Plot plot : plots.values()) {
PlayerList denied = null; PlayerList denied = null;
PlayerList added = null; PlayerList added = null;
ArrayList<UUID> psAdded = new ArrayList<>(); ArrayList<UUID> psAdded = new ArrayList<>();
ArrayList<UUID> psDenied = new ArrayList<>(); ArrayList<UUID> psDenied = new ArrayList<>();
if (world==null) { if (world == null) {
world = Bukkit.getWorld("world"); world = Bukkit.getWorld("world");
} }
long eR3040bl230 = 22392948l; long eR3040bl230 = 22392948l;
@ -54,49 +55,36 @@ public class PlotMeConverter {
added = (PlayerList) fAdded.get(plot); added = (PlayerList) fAdded.get(plot);
denied = (PlayerList) fDenied.get(plot); denied = (PlayerList) fDenied.get(plot);
for(Map.Entry<String, UUID> set : added.getAllPlayers().entrySet()) { for (Map.Entry<String, UUID> set : added.getAllPlayers().entrySet()) {
if(set.getKey().equalsIgnoreCase("*") || set.getValue().toString().equalsIgnoreCase("*")) { if (set.getKey().equalsIgnoreCase("*") || set.getValue().toString().equalsIgnoreCase("*")) {
psAdded.add(com.intellectualcrafters.plot.database.DBFunc.everyone); psAdded.add(com.intellectualcrafters.plot.database.DBFunc.everyone);
continue; continue;
} }
psAdded.add(set.getValue()); psAdded.add(set.getValue());
} }
for(Map.Entry<String, UUID> set : denied.getAllPlayers().entrySet()) { for (Map.Entry<String, UUID> set : denied.getAllPlayers().entrySet()) {
if(set.getKey().equalsIgnoreCase("*") || set.getValue().toString().equalsIgnoreCase("*")) { if (set.getKey().equalsIgnoreCase("*") || set.getValue().toString().equalsIgnoreCase("*")) {
psDenied.add(com.intellectualcrafters.plot.database.DBFunc.everyone); psDenied.add(com.intellectualcrafters.plot.database.DBFunc.everyone);
continue; continue;
} }
psDenied.add(set.getValue()); psDenied.add(set.getValue());
} }
} catch(NoSuchFieldException | IllegalAccessException e) { } catch (NoSuchFieldException | IllegalAccessException e) {
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(Integer.parseInt(plot.id.split(";")[0]), Integer.parseInt(plot.id.split(";")[1]));
com.intellectualcrafters.plot.Plot pl = new com.intellectualcrafters.plot.Plot( com.intellectualcrafters.plot.Plot pl = new com.intellectualcrafters.plot.Plot(id, plot.getOwnerId(), plot.getBiome(), psAdded, psDenied, false, 8000l, false, "", PlotHomePosition.DEFAULT, null, world.getName());
id,
plot.getOwnerId(),
plot.getBiome(),
psAdded,
psDenied,
false,
8000l,
false,
"",
PlotHomePosition.DEFAULT,
null,
world.getName()
);
DBFunc.createPlot(pl); DBFunc.createPlot(pl);
DBFunc.createPlotSettings(DBFunc.getId(world.getName(),pl.id), pl); DBFunc.createPlotSettings(DBFunc.getId(world.getName(), pl.id), pl);
} }
} }
PlotMain.sendConsoleSenderMessage("PlotMe->PlotSquared Conversion has finished"); PlotMain.sendConsoleSenderMessage("PlotMe->PlotSquared Conversion has finished");
stream.close(); stream.close();
Bukkit.getPluginManager().disablePlugin(plugin); Bukkit.getPluginManager().disablePlugin(PlotMeConverter.this.plugin);
} }
}); });
} }

View File

@ -1,14 +1,19 @@
package com.intellectualcrafters.plot.database; package com.intellectualcrafters.plot.database;
import org.bukkit.plugin.Plugin;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.sql.*; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level; import java.util.logging.Level;
import org.bukkit.plugin.Plugin;
/** /**
* Connects to and uses a SQLite database * Connects to and uses a SQLite database
*
* @author Citymonstret * @author Citymonstret
* @author tips48 * @author tips48
*/ */
@ -16,71 +21,67 @@ 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, public Connection openConnection() throws SQLException, ClassNotFoundException {
ClassNotFoundException {
if (checkConnection()) { if (checkConnection()) {
return connection; return this.connection;
} }
if (!plugin.getDataFolder().exists()) { if (!this.plugin.getDataFolder().exists()) {
plugin.getDataFolder().mkdirs(); this.plugin.getDataFolder().mkdirs();
} }
File file = new File(plugin.getDataFolder(), dbLocation); File file = new File(this.plugin.getDataFolder(), this.dbLocation);
if (!(file.exists())) { if (!(file.exists())) {
try { try {
file.createNewFile(); file.createNewFile();
} catch (IOException e) { } catch (IOException e) {
plugin.getLogger().log(Level.SEVERE, this.plugin.getLogger().log(Level.SEVERE, "Unable to create database!");
"Unable to create database!");
} }
} }
Class.forName("org.sqlite.JDBC"); Class.forName("org.sqlite.JDBC");
connection = DriverManager this.connection = DriverManager.getConnection("jdbc:sqlite:" + this.plugin.getDataFolder().toPath().toString() + "/" + this.dbLocation);
.getConnection("jdbc:sqlite:" return this.connection;
+ plugin.getDataFolder().toPath().toString() + "/"
+ dbLocation);
return connection;
} }
@Override @Override
public boolean checkConnection() throws SQLException { public boolean checkConnection() throws SQLException {
return connection != null && !connection.isClosed(); return (this.connection != null) && !this.connection.isClosed();
} }
@Override @Override
public Connection getConnection() { public Connection getConnection() {
return connection; return this.connection;
} }
@Override @Override
public boolean closeConnection() throws SQLException { public boolean closeConnection() throws SQLException {
if (connection == null) { if (this.connection == null) {
return false; return false;
} }
connection.close(); this.connection.close();
return true; return true;
} }
@Override @Override
public ResultSet querySQL(String query) throws SQLException, public ResultSet querySQL(String query) throws SQLException, ClassNotFoundException {
ClassNotFoundException {
if (checkConnection()) { if (checkConnection()) {
openConnection(); openConnection();
} }
Statement statement = connection.createStatement(); Statement statement = this.connection.createStatement();
ResultSet result = statement.executeQuery(query); ResultSet result = statement.executeQuery(query);
@ -88,13 +89,12 @@ public class SQLite extends Database {
} }
@Override @Override
public int updateSQL(String query) throws SQLException, public int updateSQL(String query) throws SQLException, ClassNotFoundException {
ClassNotFoundException {
if (checkConnection()) { if (checkConnection()) {
openConnection(); openConnection();
} }
Statement statement = connection.createStatement(); Statement statement = this.connection.createStatement();
int result = statement.executeUpdate(query); int result = statement.executeUpdate(query);

View File

@ -9,16 +9,17 @@
package com.intellectualcrafters.plot.events; package com.intellectualcrafters.plot.events;
import com.intellectualcrafters.plot.Plot;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable; import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerEvent; import org.bukkit.event.player.PlayerEvent;
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;
@ -37,6 +38,7 @@ public class PlayerClaimPlotEvent extends PlayerEvent implements Cancellable{
return handlers; return handlers;
} }
@Override
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }

View File

@ -1,10 +1,11 @@
package com.intellectualcrafters.plot.events; package com.intellectualcrafters.plot.events;
import com.intellectualcrafters.plot.Plot;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerEvent; import org.bukkit.event.player.PlayerEvent;
import com.intellectualcrafters.plot.Plot;
/** /**
* Created by Citymonstret on 2014-08-16. * Created by Citymonstret on 2014-08-16.
*/ */
@ -29,4 +30,3 @@ public class PlayerEnterPlotEvent extends PlayerEvent {
} }
} }

View File

@ -1,10 +1,11 @@
package com.intellectualcrafters.plot.events; package com.intellectualcrafters.plot.events;
import com.intellectualcrafters.plot.Plot;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerEvent; import org.bukkit.event.player.PlayerEvent;
import com.intellectualcrafters.plot.Plot;
/** /**
* Created by Citymonstret on 2014-08-16. * Created by Citymonstret on 2014-08-16.
*/ */
@ -12,13 +13,14 @@ public class PlayerLeavePlotEvent extends PlayerEvent {
private static HandlerList handlers = new HandlerList(); private static HandlerList handlers = new HandlerList();
private Plot plot; private Plot plot;
public PlayerLeavePlotEvent(Player player, Plot plot) { public PlayerLeavePlotEvent(Player player, Plot plot) {
super(player); super(player);
this.plot = plot; this.plot = plot;
} }
public Plot getPlot() { public Plot getPlot() {
return this.plot; return this.plot;
} }
@Override @Override

View File

@ -1,11 +1,12 @@
package com.intellectualcrafters.plot.events; package com.intellectualcrafters.plot.events;
import com.intellectualcrafters.plot.Plot; import java.util.UUID;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.Event; import org.bukkit.event.Event;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
import java.util.UUID; import com.intellectualcrafters.plot.Plot;
/** /**
* Created by Citymonstret on 2014-08-16. * Created by Citymonstret on 2014-08-16.

View File

@ -1,11 +1,12 @@
package com.intellectualcrafters.plot.events; package com.intellectualcrafters.plot.events;
import com.intellectualcrafters.plot.Plot; import java.util.UUID;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.Event; import org.bukkit.event.Event;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
import java.util.UUID; import com.intellectualcrafters.plot.Plot;
/** /**
* Created by Citymonstret on 2014-08-16. * Created by Citymonstret on 2014-08-16.

View File

@ -9,15 +9,15 @@
package com.intellectualcrafters.plot.events; package com.intellectualcrafters.plot.events;
import com.intellectualcrafters.plot.Plot;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable; import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerEvent; import org.bukkit.event.player.PlayerEvent;
import com.intellectualcrafters.plot.Plot;
public class PlayerTeleportToPlotEvent extends PlayerEvent implements Cancellable{ public class PlayerTeleportToPlotEvent extends PlayerEvent implements Cancellable {
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
private Location from; private Location from;
@ -31,6 +31,7 @@ public class PlayerTeleportToPlotEvent extends PlayerEvent implements Cancellabl
this.plot = plot; this.plot = plot;
} }
@Override
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
@ -47,10 +48,12 @@ public class PlayerTeleportToPlotEvent extends PlayerEvent implements Cancellabl
return handlers; return handlers;
} }
@Override
public boolean isCancelled() { public boolean isCancelled() {
return this.cancelled; return this.cancelled;
} }
@Override
public void setCancelled(boolean cancelled) { public void setCancelled(boolean cancelled) {
this.cancelled = cancelled; this.cancelled = cancelled;
} }

View File

@ -9,19 +9,16 @@
package com.intellectualcrafters.plot.events; package com.intellectualcrafters.plot.events;
import com.intellectualcrafters.plot.Plot;
import com.intellectualcrafters.plot.PlotId;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable; import org.bukkit.event.Cancellable;
import org.bukkit.event.Event; import org.bukkit.event.Event;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerEvent;
import com.intellectualcrafters.plot.PlotId;
/** /**
* Created by Citymonstret on 2014-08-09. * Created by Citymonstret on 2014-08-09.
*/ */
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;
@ -45,6 +42,7 @@ public class PlotDeleteEvent extends Event implements Cancellable{
return handlers; return handlers;
} }
@Override
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }

View File

@ -9,18 +9,17 @@
package com.intellectualcrafters.plot.events; package com.intellectualcrafters.plot.events;
import com.intellectualcrafters.plot.Flag;
import com.intellectualcrafters.plot.Plot;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable; import org.bukkit.event.Cancellable;
import org.bukkit.event.Event; import org.bukkit.event.Event;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
import com.intellectualcrafters.plot.Flag;
import com.intellectualcrafters.plot.Plot;
/** /**
* Created by Citymonstret on 2014-08-09. * Created by Citymonstret on 2014-08-09.
*/ */
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;
@ -44,6 +43,7 @@ public class PlotFlagAddEvent extends Event implements Cancellable{
return handlers; return handlers;
} }
@Override
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }

View File

@ -9,18 +9,17 @@
package com.intellectualcrafters.plot.events; package com.intellectualcrafters.plot.events;
import com.intellectualcrafters.plot.Flag;
import com.intellectualcrafters.plot.Plot;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable; import org.bukkit.event.Cancellable;
import org.bukkit.event.Event; import org.bukkit.event.Event;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
import com.intellectualcrafters.plot.Flag;
import com.intellectualcrafters.plot.Plot;
/** /**
* Created by Citymonstret on 2014-08-09. * Created by Citymonstret on 2014-08-09.
*/ */
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;
@ -44,6 +43,7 @@ public class PlotFlagRemoveEvent extends Event implements Cancellable{
return handlers; return handlers;
} }
@Override
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }

View File

@ -9,9 +9,11 @@
package com.intellectualcrafters.plot.listeners; package com.intellectualcrafters.plot.listeners;
import com.intellectualcrafters.plot.*; import java.util.ArrayList;
import com.intellectualcrafters.plot.events.PlayerEnterPlotEvent; import java.util.Arrays;
import com.intellectualcrafters.plot.events.PlayerLeavePlotEvent; import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
@ -28,7 +30,18 @@ import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.block.*; import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockDamageEvent;
import org.bukkit.event.block.BlockFadeEvent;
import org.bukkit.event.block.BlockFormEvent;
import org.bukkit.event.block.BlockFromToEvent;
import org.bukkit.event.block.BlockGrowEvent;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.block.BlockPistonExtendEvent;
import org.bukkit.event.block.BlockPistonRetractEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.block.BlockSpreadEvent;
import org.bukkit.event.block.EntityBlockFormEvent;
import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import org.bukkit.event.entity.EntityChangeBlockEvent; import org.bukkit.event.entity.EntityChangeBlockEvent;
@ -37,91 +50,113 @@ import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.hanging.HangingBreakByEntityEvent; import org.bukkit.event.hanging.HangingBreakByEntityEvent;
import org.bukkit.event.hanging.HangingPlaceEvent; import org.bukkit.event.hanging.HangingPlaceEvent;
import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.*; import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerBucketEmptyEvent;
import org.bukkit.event.player.PlayerBucketFillEvent;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerEggThrowEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.world.StructureGrowEvent; import org.bukkit.event.world.StructureGrowEvent;
import org.bukkit.event.world.WorldInitEvent;
import org.bukkit.event.world.WorldLoadEvent;
import java.util.*; import com.intellectualcrafters.plot.C;
import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.Plot;
import com.intellectualcrafters.plot.PlotId;
import com.intellectualcrafters.plot.PlotMain;
import com.intellectualcrafters.plot.PlotWorld;
import com.intellectualcrafters.plot.Settings;
import com.intellectualcrafters.plot.Title;
import com.intellectualcrafters.plot.events.PlayerEnterPlotEvent;
import com.intellectualcrafters.plot.events.PlayerLeavePlotEvent;
/** /**
* Player Events involving plots * Player Events involving plots
*
* @author Citymonstret * @author Citymonstret
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
public class PlayerEvents implements Listener { public class PlayerEvents implements Listener {
private String replaceColours(String string) { private String getName(UUID uuid) {
return ChatColor.translateAlternateColorCodes('&', string);
}
private String getName(UUID uuid){
OfflinePlayer player = Bukkit.getOfflinePlayer(uuid); OfflinePlayer player = Bukkit.getOfflinePlayer(uuid);
if(player != null) { if (player != null) {
return player.getName(); return player.getName();
} }
return "unknown"; return "unknown";
} }
public boolean enteredPlot(Location l1, Location l2) { public boolean enteredPlot(Location l1, Location l2) {
return !isInPlot(l1) && isInPlot(l2); return !isInPlot(l1) && isInPlot(l2);
} }
public boolean leftPlot(Location l1, Location l2){ public boolean leftPlot(Location l1, Location l2) {
return isInPlot(l1) && !isInPlot(l2); return isInPlot(l1) && !isInPlot(l2);
} }
private boolean isPlotWorld(Location l) { return PlotMain.isPlotWorld(l.getWorld());} private boolean isPlotWorld(Location l) {
private boolean isPlotWorld(World w) { return PlotMain.isPlotWorld(w);} return PlotMain.isPlotWorld(l.getWorld());
}
public static boolean isInPlot(Location loc) { private boolean isPlotWorld(World w) {
return getCurrentPlot(loc) != null; return PlotMain.isPlotWorld(w);
} }
public static Plot getCurrentPlot(Location loc) { public static boolean isInPlot(Location loc) {
PlotId id = PlayerFunctions.getPlot(loc); return getCurrentPlot(loc) != null;
if (id == null) { }
return null;
}
World world = loc.getWorld();
if (PlotMain.getPlots(world).containsKey(id)) {
return PlotMain.getPlots(world).get(id);
}
return new Plot(id, null, Biome.FOREST, new ArrayList<UUID>(), new ArrayList<UUID>(), loc.getWorld().getName());
}
@EventHandler public static Plot getCurrentPlot(Location loc) {
public void onJoin(PlayerJoinEvent event) { PlotId id = PlayerFunctions.getPlot(loc);
if (!event.getPlayer().hasPlayedBefore()) if (id == null) {
event.getPlayer().saveData(); return null;
}
World world = loc.getWorld();
if (PlotMain.getPlots(world).containsKey(id)) {
return PlotMain.getPlots(world).get(id);
}
return new Plot(id, null, Biome.FOREST, new ArrayList<UUID>(), new ArrayList<UUID>(), loc.getWorld().getName());
}
@EventHandler
public void onJoin(PlayerJoinEvent event) {
if (!event.getPlayer().hasPlayedBefore()) {
event.getPlayer().saveData();
}
textures(event.getPlayer()); textures(event.getPlayer());
} }
private void textures(Player p) { private void textures(Player p) {
if(Settings.PLOT_SPECIFIC_RESOURCE_PACK.length() > 1 && isPlotWorld(p.getWorld())) if ((Settings.PLOT_SPECIFIC_RESOURCE_PACK.length() > 1) && isPlotWorld(p.getWorld())) {
p.setResourcePack(Settings.PLOT_SPECIFIC_RESOURCE_PACK); p.setResourcePack(Settings.PLOT_SPECIFIC_RESOURCE_PACK);
}
} }
@EventHandler @EventHandler
public void onChangeWorld(PlayerChangedWorldEvent event) { public void onChangeWorld(PlayerChangedWorldEvent event) {
if (isPlotWorld(event.getFrom())) if (isPlotWorld(event.getFrom())) {
event.getPlayer().setResourcePack(""); event.getPlayer().setResourcePack("");
else } else {
textures(event.getPlayer()); textures(event.getPlayer());
}
} }
@EventHandler @EventHandler
public void PlayerMove(PlayerMoveEvent event) { public void PlayerMove(PlayerMoveEvent event) {
Player player = event.getPlayer(); Player player = event.getPlayer();
Location from = event.getFrom(); Location from = event.getFrom();
Location to = event.getTo(); Location to = event.getTo();
if (from.getBlockX()!=to.getBlockX() || from.getBlockZ()!=to.getBlockZ()) { if ((from.getBlockX() != to.getBlockX()) || (from.getBlockZ() != to.getBlockZ())) {
if (!isPlotWorld(player.getWorld())) if (!isPlotWorld(player.getWorld())) {
return; return;
if (enteredPlot(event.getFrom(), event.getTo())) { }
if (enteredPlot(event.getFrom(), event.getTo())) {
Plot plot = getCurrentPlot(event.getTo()); Plot plot = getCurrentPlot(event.getTo());
if(plot.hasOwner()) { if (plot.hasOwner()) {
if(C.TITLE_ENTERED_PLOT.s().length() > 2) { if (C.TITLE_ENTERED_PLOT.s().length() > 2) {
String sTitleMain = C.TITLE_ENTERED_PLOT.s().replaceFirst("%s", plot.getDisplayName()); String sTitleMain = C.TITLE_ENTERED_PLOT.s().replaceFirst("%s", plot.getDisplayName());
String sTitleSub = C.TITLE_ENTERED_PLOT_SUB.s().replaceFirst("%s", getName(plot.owner)); String sTitleSub = C.TITLE_ENTERED_PLOT_SUB.s().replaceFirst("%s", getName(plot.owner));
ChatColor sTitleMainColor = ChatColor.valueOf(C.TITLE_ENTERED_PLOT_COLOR.s()); ChatColor sTitleMainColor = ChatColor.valueOf(C.TITLE_ENTERED_PLOT_COLOR.s());
@ -132,252 +167,265 @@ public class PlayerEvents implements Listener {
title.setTimingsToTicks(); title.setTimingsToTicks();
title.send(player); title.send(player);
} }
{ {
PlayerEnterPlotEvent callEvent = new PlayerEnterPlotEvent(player, plot); PlayerEnterPlotEvent callEvent = new PlayerEnterPlotEvent(player, plot);
Bukkit.getPluginManager().callEvent(callEvent); Bukkit.getPluginManager().callEvent(callEvent);
} }
boolean admin = player.hasPermission("plots.admin"); boolean admin = player.hasPermission("plots.admin");
PlayerFunctions.sendMessage(player, plot.settings.getJoinMessage()); PlayerFunctions.sendMessage(player, plot.settings.getJoinMessage());
if (plot.deny_entry(player) && !admin) { if (plot.deny_entry(player) && !admin) {
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
if (plot.settings.getRain()) if (plot.settings.getRain()) {
PlayerFunctions.togglePlotWeather(player, plot); PlayerFunctions.togglePlotWeather(player, plot);
if (plot.settings.getChangeTime()) }
PlayerFunctions.togglePlotTime(player, plot); if (plot.settings.getChangeTime()) {
PlayerFunctions.togglePlotTime(player, plot);
}
} }
} else if (leftPlot(event.getFrom(), event.getTo())) { } else if (leftPlot(event.getFrom(), event.getTo())) {
Plot plot = getCurrentPlot(event.getFrom()); Plot plot = getCurrentPlot(event.getFrom());
{ {
PlayerLeavePlotEvent callEvent = new PlayerLeavePlotEvent(player, plot); PlayerLeavePlotEvent callEvent = new PlayerLeavePlotEvent(player, plot);
Bukkit.getPluginManager().callEvent(callEvent); Bukkit.getPluginManager().callEvent(callEvent);
} }
event.getPlayer().resetPlayerTime(); event.getPlayer().resetPlayerTime();
event.getPlayer().resetPlayerWeather(); event.getPlayer().resetPlayerWeather();
PlayerFunctions.sendMessage(player, plot.settings.getLeaveMessage()); PlayerFunctions.sendMessage(player, plot.settings.getLeaveMessage());
} }
} }
} }
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
public void onChat(AsyncPlayerChatEvent event) { public void onChat(AsyncPlayerChatEvent event) {
World world = event.getPlayer().getWorld(); World world = event.getPlayer().getWorld();
if (!isPlotWorld(world)) if (!isPlotWorld(world)) {
return;
PlotWorld plotworld = PlotMain.getWorldSettings(world);
if (!plotworld.PLOT_CHAT)
return;
if (getCurrentPlot(event.getPlayer().getLocation()) == null)
return;
String message = event.getMessage();
String format = C.PLOT_CHAT_FORMAT.s();
String sender = event.getPlayer().getDisplayName();
Plot plot = getCurrentPlot(event.getPlayer().getLocation());
PlotId id = plot.id;
Set<Player> recipients = event.getRecipients();
recipients.clear();
for (Player p : Bukkit.getOnlinePlayers()) {
if (p.getLocation()
.distanceSquared(event.getPlayer().getLocation()) <= Math
.pow((double) plotworld.PLOT_WIDTH, 2d)) {
if (getCurrentPlot(p.getLocation()) == plot) {
recipients.add(p);
}
}
}
format = format.replaceAll("%plot_id%", id.x+";"+id.y)
.replaceAll("%sender%", sender).replaceAll("%msg%", message);
format = ChatColor.translateAlternateColorCodes('&', format);
event.setFormat(format);
}
@EventHandler(priority = EventPriority.HIGH)
public void BlockDestroy(BlockBreakEvent event) {
World world = event.getPlayer().getWorld();
if (!isPlotWorld(world))
return;
if (event.getPlayer().hasPermission("plots.admin")) {
return; return;
} }
if (isInPlot(event.getBlock().getLocation())) { PlotWorld plotworld = PlotMain.getWorldSettings(world);
Plot plot = getCurrentPlot(event.getBlock().getLocation()); if (!plotworld.PLOT_CHAT) {
if (!plot.hasRights(event.getPlayer())) return;
event.setCancelled(true); }
if (getCurrentPlot(event.getPlayer().getLocation()) == null) {
return;
}
String message = event.getMessage();
String format = C.PLOT_CHAT_FORMAT.s();
String sender = event.getPlayer().getDisplayName();
Plot plot = getCurrentPlot(event.getPlayer().getLocation());
PlotId id = plot.id;
Set<Player> recipients = event.getRecipients();
recipients.clear();
for (Player p : Bukkit.getOnlinePlayers()) {
if (p.getLocation().distanceSquared(event.getPlayer().getLocation()) <= Math.pow(plotworld.PLOT_WIDTH, 2d)) {
if (getCurrentPlot(p.getLocation()) == plot) {
recipients.add(p);
}
} }
if (PlayerFunctions.getPlot(event.getBlock().getLocation()).equals( }
"road")) { format = format.replaceAll("%plot_id%", id.x + ";" + id.y).replaceAll("%sender%", sender).replaceAll("%msg%", message);
event.setCancelled(true); format = ChatColor.translateAlternateColorCodes('&', format);
} event.setFormat(format);
} }
@EventHandler(priority = EventPriority.HIGH) @EventHandler(priority = EventPriority.HIGH)
public void BlockCreate(BlockPlaceEvent event) { public void BlockDestroy(BlockBreakEvent event) {
World world = event.getPlayer().getWorld(); World world = event.getPlayer().getWorld();
if (!isPlotWorld(world)) if (!isPlotWorld(world)) {
return; return;
if (event.getPlayer().hasPermission("plots.admin")) { }
return; if (event.getPlayer().hasPermission("plots.admin")) {
}
if (isInPlot(event.getBlock().getLocation())) {
Plot plot = getCurrentPlot(event.getBlockPlaced().getLocation());
if (!plot.hasRights(event.getPlayer()))
event.setCancelled(true);
}
if (PlayerFunctions.getPlot(event.getBlockPlaced().getLocation()).equals(
"road")) {
event.setCancelled(true);
}
}
@EventHandler
public void onBigBoom(EntityExplodeEvent event) {
World world = event.getLocation().getWorld();
if (!isPlotWorld(world))
return;
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPeskyMobsChangeTheWorldLikeWTFEvent( // LOL!
EntityChangeBlockEvent event) {
World world = event.getBlock().getWorld();
if (!isPlotWorld(world))
return; return;
Entity e = event.getEntity(); }
if (!(e instanceof Player)) { if (isInPlot(event.getBlock().getLocation())) {
if (!(e instanceof org.bukkit.entity.FallingBlock)) { Plot plot = getCurrentPlot(event.getBlock().getLocation());
event.setCancelled(true); if (!plot.hasRights(event.getPlayer())) {
} event.setCancelled(true);
} else { }
}
if (PlayerFunctions.getPlot(event.getBlock().getLocation()).equals("road")) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGH)
public void BlockCreate(BlockPlaceEvent event) {
World world = event.getPlayer().getWorld();
if (!isPlotWorld(world)) {
return;
}
if (event.getPlayer().hasPermission("plots.admin")) {
return;
}
if (isInPlot(event.getBlock().getLocation())) {
Plot plot = getCurrentPlot(event.getBlockPlaced().getLocation());
if (!plot.hasRights(event.getPlayer())) {
event.setCancelled(true);
}
}
if (PlayerFunctions.getPlot(event.getBlockPlaced().getLocation()).equals("road")) {
event.setCancelled(true);
}
}
@EventHandler
public void onBigBoom(EntityExplodeEvent event) {
World world = event.getLocation().getWorld();
if (!isPlotWorld(world)) {
return;
}
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPeskyMobsChangeTheWorldLikeWTFEvent( // LOL!
EntityChangeBlockEvent event) {
World world = event.getBlock().getWorld();
if (!isPlotWorld(world)) {
return;
}
Entity e = event.getEntity();
if (!(e instanceof Player)) {
if (!(e instanceof org.bukkit.entity.FallingBlock)) {
event.setCancelled(true);
}
} else {
Block b = event.getBlock(); Block b = event.getBlock();
Player p = (Player) e; Player p = (Player) e;
if(!isInPlot(b.getLocation())) { if (!isInPlot(b.getLocation())) {
if(!p.hasPermission("plots.admin")) { if (!p.hasPermission("plots.admin")) {
event.setCancelled(true); event.setCancelled(true);
} }
} else{ } else {
Plot plot = getCurrentPlot(b.getLocation()); Plot plot = getCurrentPlot(b.getLocation());
if(plot == null) { if (plot == null) {
if(!p.hasPermission("plots.admin")) { if (!p.hasPermission("plots.admin")) {
event.setCancelled(true); event.setCancelled(true);
} }
} else if(!plot.hasRights(p)) { } else if (!plot.hasRights(p)) {
if(!p.hasPermission("plots.admin")) { if (!p.hasPermission("plots.admin")) {
event.setCancelled(true); event.setCancelled(true);
} }
} }
} }
} }
} }
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityBlockForm(final EntityBlockFormEvent event) { public void onEntityBlockForm(final EntityBlockFormEvent event) {
World world = event.getBlock().getWorld(); World world = event.getBlock().getWorld();
if (!isPlotWorld(world)) if (!isPlotWorld(world)) {
return; return;
if ((!(event.getEntity() instanceof Player))) }
event.setCancelled(true); if ((!(event.getEntity() instanceof Player))) {
} event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBS(final BlockSpreadEvent e) { public void onBS(final BlockSpreadEvent e) {
Block b = e.getBlock(); Block b = e.getBlock();
if(isPlotWorld(b.getLocation())) { if (isPlotWorld(b.getLocation())) {
if(!isInPlot(b.getLocation())) if (!isInPlot(b.getLocation())) {
e.setCancelled(true); e.setCancelled(true);
}
} }
} }
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBF(final BlockFormEvent e) { public void onBF(final BlockFormEvent e) {
Block b = e.getBlock(); Block b = e.getBlock();
if(isPlotWorld(b.getLocation())) { if (isPlotWorld(b.getLocation())) {
if(!isInPlot(b.getLocation())) if (!isInPlot(b.getLocation())) {
e.setCancelled(true); e.setCancelled(true);
}
} }
} }
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBD(final BlockDamageEvent e) { public void onBD(final BlockDamageEvent e) {
Block b = e.getBlock(); Block b = e.getBlock();
if(isPlotWorld(b.getLocation())) { if (isPlotWorld(b.getLocation())) {
if(!isInPlot(b.getLocation())) if (!isInPlot(b.getLocation())) {
e.setCancelled(true); e.setCancelled(true);
}
} }
} }
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onFade(final BlockFadeEvent e) { public void onFade(final BlockFadeEvent e) {
Block b = e.getBlock(); Block b = e.getBlock();
if(isPlotWorld(b.getLocation())) { if (isPlotWorld(b.getLocation())) {
if(!isInPlot(b.getLocation())) if (!isInPlot(b.getLocation())) {
e.setCancelled(true); e.setCancelled(true);
}
} }
} }
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onChange(final BlockFromToEvent e) { public void onChange(final BlockFromToEvent e) {
Block b = e.getToBlock(); Block b = e.getToBlock();
if(isPlotWorld(b.getLocation())) { if (isPlotWorld(b.getLocation())) {
if(!isInPlot(b.getLocation())) if (!isInPlot(b.getLocation())) {
e.setCancelled(true); e.setCancelled(true);
}
} }
} }
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onGrow(final BlockGrowEvent e) { public void onGrow(final BlockGrowEvent e) {
Block b = e.getBlock(); Block b = e.getBlock();
if(isPlotWorld(b.getLocation())) { if (isPlotWorld(b.getLocation())) {
if(!isInPlot(b.getLocation())) if (!isInPlot(b.getLocation())) {
e.setCancelled(true); e.setCancelled(true);
}
} }
} }
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockPistonExtend(final BlockPistonExtendEvent e) { public void onBlockPistonExtend(final BlockPistonExtendEvent e) {
if(isInPlot(e.getBlock().getLocation())) { if (isInPlot(e.getBlock().getLocation())) {
BlockFace face = e.getDirection(); e.getDirection();
int modifier = e.getBlocks().size(); int modifier = e.getBlocks().size();
Location l = e.getBlock().getLocation(); Location l = e.getBlock().getLocation();
{ {
if(e.getDirection() == BlockFace.EAST) { if (e.getDirection() == BlockFace.EAST) {
l = e.getBlock().getLocation().subtract(modifier, 0, 0); l = e.getBlock().getLocation().subtract(modifier, 0, 0);
} else if(e.getDirection() == BlockFace.NORTH) { } else if (e.getDirection() == BlockFace.NORTH) {
l = e.getBlock().getLocation().subtract(0, 0, modifier); l = e.getBlock().getLocation().subtract(0, 0, modifier);
} else if(e.getDirection() == BlockFace.SOUTH) { } else if (e.getDirection() == BlockFace.SOUTH) {
l = e.getBlock().getLocation().add(0, 0, modifier); l = e.getBlock().getLocation().add(0, 0, modifier);
} else if(e.getDirection() == BlockFace.WEST) { } else if (e.getDirection() == BlockFace.WEST) {
l = e.getBlock().getLocation().add(modifier, 0, 0); l = e.getBlock().getLocation().add(modifier, 0, 0);
} }
if(!isInPlot(l)) { if (!isInPlot(l)) {
e.setCancelled(true); e.setCancelled(true);
return; return;
} }
} }
for(Block b : e.getBlocks()) { for (Block b : e.getBlocks()) {
if(!isInPlot(b.getLocation())) return; if (!isInPlot(b.getLocation())) {
return;
}
{ {
if(e.getDirection() == BlockFace.EAST) { if (e.getDirection() == BlockFace.EAST) {
if(!isInPlot(b.getLocation().subtract(1, 0, 0))) { if (!isInPlot(b.getLocation().subtract(1, 0, 0))) {
e.setCancelled(true); e.setCancelled(true);
} }
} else if(e.getDirection() == BlockFace.NORTH) { } else if (e.getDirection() == BlockFace.NORTH) {
if(!isInPlot(b.getLocation().subtract(0, 0, 1))) { if (!isInPlot(b.getLocation().subtract(0, 0, 1))) {
e.setCancelled(true); e.setCancelled(true);
} }
} else if(e.getDirection() == BlockFace.SOUTH) { } else if (e.getDirection() == BlockFace.SOUTH) {
if(!isInPlot(b.getLocation().add(0, 0, 1))) { if (!isInPlot(b.getLocation().add(0, 0, 1))) {
e.setCancelled(true); e.setCancelled(true);
} }
} else if(e.getDirection() == BlockFace.WEST) { } else if (e.getDirection() == BlockFace.WEST) {
if(!isInPlot(b.getLocation().add(1, 0, 0))) { if (!isInPlot(b.getLocation().add(1, 0, 0))) {
e.setCancelled(true); e.setCancelled(true);
} }
} }
@ -389,9 +437,10 @@ public class PlayerEvents implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockPistonRetract(final BlockPistonRetractEvent e) { public void onBlockPistonRetract(final BlockPistonRetractEvent e) {
Block b = e.getRetractLocation().getBlock(); Block b = e.getRetractLocation().getBlock();
if(isPlotWorld(b.getLocation()) && e.getBlock().getType() == Material.PISTON_STICKY_BASE) { if (isPlotWorld(b.getLocation()) && (e.getBlock().getType() == Material.PISTON_STICKY_BASE)) {
if(!isInPlot(b.getLocation())) if (!isInPlot(b.getLocation())) {
e.setCancelled(true); e.setCancelled(true);
}
} }
} }
@ -399,10 +448,10 @@ public class PlayerEvents implements Listener {
public void onStructureGrow(final StructureGrowEvent e) { public void onStructureGrow(final StructureGrowEvent e) {
List<BlockState> blocks = e.getBlocks(); List<BlockState> blocks = e.getBlocks();
boolean f = false; boolean f = false;
for(int i = 0; i < blocks.size(); i++) { for (int i = 0; i < blocks.size(); i++) {
if(f || isPlotWorld(blocks.get(i).getLocation())) { if (f || isPlotWorld(blocks.get(i).getLocation())) {
f = true; f = true;
if(!isInPlot(blocks.get(i).getLocation())) { if (!isInPlot(blocks.get(i).getLocation())) {
e.getBlocks().remove(i); e.getBlocks().remove(i);
i--; i--;
} }
@ -410,99 +459,88 @@ public class PlayerEvents implements Listener {
} }
} }
@EventHandler @EventHandler
public void onInteract(PlayerInteractEvent event) { public void onInteract(PlayerInteractEvent event) {
if (event.getClickedBlock() == null) if (event.getClickedBlock() == null) {
return;
World world = event.getPlayer().getWorld();
if (!isPlotWorld(world))
return; return;
if (event.getPlayer().hasPermission("plots.admin")) { }
return; World world = event.getPlayer().getWorld();
} if (!isPlotWorld(world)) {
if (isInPlot(event.getClickedBlock().getLocation())) { return;
Plot plot = getCurrentPlot(event.getClickedBlock().getLocation()); }
if (new ArrayList<>(Arrays.asList(new Material[]{ if (event.getPlayer().hasPermission("plots.admin")) {
Material.STONE_BUTTON, return;
Material.WOOD_BUTTON, }
Material.LEVER, if (isInPlot(event.getClickedBlock().getLocation())) {
Material.STONE_PLATE, Plot plot = getCurrentPlot(event.getClickedBlock().getLocation());
Material.WOOD_PLATE, if (new ArrayList<>(Arrays.asList(new Material[] { Material.STONE_BUTTON, Material.WOOD_BUTTON, Material.LEVER, Material.STONE_PLATE, Material.WOOD_PLATE, Material.CHEST, Material.TRAPPED_CHEST, Material.TRAP_DOOR, Material.WOOD_DOOR, Material.WOODEN_DOOR, Material.DISPENSER, Material.DROPPER
Material.CHEST,
Material.TRAPPED_CHEST,
Material.TRAP_DOOR,
Material.WOOD_DOOR,
Material.WOODEN_DOOR,
Material.DISPENSER,
Material.DROPPER
})).contains(event.getClickedBlock().getType())) { })).contains(event.getClickedBlock().getType())) {
return; return;
} }
if (!plot.hasRights(event.getPlayer())) if (!plot.hasRights(event.getPlayer())) {
event.setCancelled(true); event.setCancelled(true);
} }
if (PlayerFunctions.getPlot(event.getClickedBlock().getLocation()) }
.equals("road")) { if (PlayerFunctions.getPlot(event.getClickedBlock().getLocation()).equals("road")) {
event.setCancelled(true); event.setCancelled(true);
} }
} }
@EventHandler
@EventHandler public void MobSpawn(CreatureSpawnEvent event) {
public void MobSpawn(CreatureSpawnEvent event) { World world = event.getLocation().getWorld();
World world = event.getLocation().getWorld(); if (!isPlotWorld(world)) {
if (!isPlotWorld(world))
return; return;
if ((isInPlot(event.getLocation()) && event.getSpawnReason() != SpawnReason.SPAWNER_EGG) }
|| !isInPlot(event.getLocation())) if ((isInPlot(event.getLocation()) && (event.getSpawnReason() != SpawnReason.SPAWNER_EGG)) || !isInPlot(event.getLocation())) {
event.setCancelled(true); event.setCancelled(true);
} }
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBlockIgnite(final BlockIgniteEvent e) { public void onBlockIgnite(final BlockIgniteEvent e) {
if(e.getCause() == BlockIgniteEvent.IgniteCause.LIGHTNING) { if (e.getCause() == BlockIgniteEvent.IgniteCause.LIGHTNING) {
e.setCancelled(true); e.setCancelled(true);
return; return;
} }
Block b = e.getBlock(); Block b = e.getBlock();
if(b != null) { if (b != null) {
if (e.getPlayer()!=null) { if (e.getPlayer() != null) {
Player p = e.getPlayer(); Player p = e.getPlayer();
if(!isInPlot(b.getLocation())) { if (!isInPlot(b.getLocation())) {
if (!p.hasPermission("plots.admin")) { if (!p.hasPermission("plots.admin")) {
e.setCancelled(true); e.setCancelled(true);
} }
} else { } else {
Plot plot = getCurrentPlot(b.getLocation()); Plot plot = getCurrentPlot(b.getLocation());
if(plot == null) { if (plot == null) {
if (!p.hasPermission("plots.admin")) { if (!p.hasPermission("plots.admin")) {
e.setCancelled(true); e.setCancelled(true);
} }
} else if(!plot.hasRights(p)) { } else if (!plot.hasRights(p)) {
if (!p.hasPermission("plots.admin")) { if (!p.hasPermission("plots.admin")) {
e.setCancelled(true); e.setCancelled(true);
} }
} }
} }
} } else {
else
e.setCancelled(true); e.setCancelled(true);
}
} }
} }
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onTeleport(PlayerTeleportEvent event) { public void onTeleport(PlayerTeleportEvent event) {
if(isPlotWorld(event.getTo())) { if (isPlotWorld(event.getTo())) {
if(isInPlot(event.getTo())) { if (isInPlot(event.getTo())) {
Plot plot = getCurrentPlot(event.getTo()); Plot plot = getCurrentPlot(event.getTo());
if(plot.deny_entry(event.getPlayer())) { if (plot.deny_entry(event.getPlayer())) {
PlayerFunctions.sendMessage(event.getPlayer(), C.YOU_BE_DENIED); PlayerFunctions.sendMessage(event.getPlayer(), C.YOU_BE_DENIED);
event.setCancelled(true); event.setCancelled(true);
} }
} }
if(event.getTo().getBlockX() >= 29999999 || event.getTo().getBlockX() <= -29999999 || if ((event.getTo().getBlockX() >= 29999999) || (event.getTo().getBlockX() <= -29999999) || (event.getTo().getBlockZ() >= 29999999) || (event.getTo().getBlockZ() <= -29999999)) {
event.getTo().getBlockZ() >= 29999999 ||event.getTo().getBlockZ() <= -29999999) {
event.setCancelled(true); event.setCancelled(true);
} }
} }
@ -510,19 +548,19 @@ public class PlayerEvents implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBucketEmpty(PlayerBucketEmptyEvent e) { public void onBucketEmpty(PlayerBucketEmptyEvent e) {
if(!e.getPlayer().hasPermission("plots.admin")) { if (!e.getPlayer().hasPermission("plots.admin")) {
BlockFace bf = e.getBlockFace(); BlockFace bf = e.getBlockFace();
Block b = e.getBlockClicked().getLocation().add(bf.getModX(), bf.getModY(), bf.getModZ()).getBlock(); Block b = e.getBlockClicked().getLocation().add(bf.getModX(), bf.getModY(), bf.getModZ()).getBlock();
if(isPlotWorld(b.getLocation())) { if (isPlotWorld(b.getLocation())) {
if(!isInPlot(b.getLocation())) { if (!isInPlot(b.getLocation())) {
PlayerFunctions.sendMessage(e.getPlayer(), C.NO_PERMISSION); PlayerFunctions.sendMessage(e.getPlayer(), C.NO_PERMISSION);
e.setCancelled(true); e.setCancelled(true);
} else { } else {
Plot plot = getCurrentPlot(b.getLocation()); Plot plot = getCurrentPlot(b.getLocation());
if(plot == null) { if (plot == null) {
PlayerFunctions.sendMessage(e.getPlayer(), C.NO_PERMISSION); PlayerFunctions.sendMessage(e.getPlayer(), C.NO_PERMISSION);
e.setCancelled(true); e.setCancelled(true);
} else if(!plot.hasRights(e.getPlayer())) { } else if (!plot.hasRights(e.getPlayer())) {
PlayerFunctions.sendMessage(e.getPlayer(), C.NO_PERMISSION); PlayerFunctions.sendMessage(e.getPlayer(), C.NO_PERMISSION);
e.setCancelled(true); e.setCancelled(true);
} }
@ -533,24 +571,25 @@ public class PlayerEvents implements Listener {
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
public void onInventoryClick(InventoryClickEvent event) { public void onInventoryClick(InventoryClickEvent event) {
if(event.getInventory().getName().equalsIgnoreCase("PlotSquared Commands")) if (event.getInventory().getName().equalsIgnoreCase("PlotSquared Commands")) {
event.setCancelled(true); event.setCancelled(true);
}
} }
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onBucketFill(PlayerBucketFillEvent e) { public void onBucketFill(PlayerBucketFillEvent e) {
if(!e.getPlayer().hasPermission("plots.admin")) { if (!e.getPlayer().hasPermission("plots.admin")) {
Block b = e.getBlockClicked(); Block b = e.getBlockClicked();
if(isPlotWorld(b.getLocation())) { if (isPlotWorld(b.getLocation())) {
if(!isInPlot(b.getLocation())) { if (!isInPlot(b.getLocation())) {
PlayerFunctions.sendMessage(e.getPlayer(), C.NO_PERMISSION); PlayerFunctions.sendMessage(e.getPlayer(), C.NO_PERMISSION);
e.setCancelled(true); e.setCancelled(true);
} else { } else {
Plot plot = getCurrentPlot(b.getLocation()); Plot plot = getCurrentPlot(b.getLocation());
if(plot == null) { if (plot == null) {
PlayerFunctions.sendMessage(e.getPlayer(), C.NO_PERMISSION); PlayerFunctions.sendMessage(e.getPlayer(), C.NO_PERMISSION);
e.setCancelled(true); e.setCancelled(true);
} else if(!plot.hasRights(e.getPlayer())) { } else if (!plot.hasRights(e.getPlayer())) {
PlayerFunctions.sendMessage(e.getPlayer(), C.NO_PERMISSION); PlayerFunctions.sendMessage(e.getPlayer(), C.NO_PERMISSION);
e.setCancelled(true); e.setCancelled(true);
} }
@ -559,25 +598,24 @@ public class PlayerEvents implements Listener {
} }
} }
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onHangingPlace(final HangingPlaceEvent e) { public void onHangingPlace(final HangingPlaceEvent e) {
Block b = e.getBlock(); Block b = e.getBlock();
if(isPlotWorld(b.getLocation())) { if (isPlotWorld(b.getLocation())) {
Player p = e.getPlayer(); Player p = e.getPlayer();
if(isInPlot(b.getLocation())) { if (isInPlot(b.getLocation())) {
if (!p.hasPermission("plots.admin")) { if (!p.hasPermission("plots.admin")) {
PlayerFunctions.sendMessage(p, C.NO_PERMISSION); PlayerFunctions.sendMessage(p, C.NO_PERMISSION);
e.setCancelled(true); e.setCancelled(true);
} }
} else { } else {
Plot plot = getCurrentPlot(b.getLocation()); Plot plot = getCurrentPlot(b.getLocation());
if(plot == null) { if (plot == null) {
if (!p.hasPermission("plots.admin")) { if (!p.hasPermission("plots.admin")) {
PlayerFunctions.sendMessage(p, C.NO_PERMISSION); PlayerFunctions.sendMessage(p, C.NO_PERMISSION);
e.setCancelled(true); e.setCancelled(true);
} }
} else if(!plot.hasRights(p)) { } else if (!plot.hasRights(p)) {
if (!p.hasPermission("plots.admin")) { if (!p.hasPermission("plots.admin")) {
PlayerFunctions.sendMessage(p, C.NO_PERMISSION); PlayerFunctions.sendMessage(p, C.NO_PERMISSION);
e.setCancelled(true); e.setCancelled(true);
@ -590,7 +628,7 @@ public class PlayerEvents implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onHangingBreakByEntity(final HangingBreakByEntityEvent e) { public void onHangingBreakByEntity(final HangingBreakByEntityEvent e) {
Entity r = e.getRemover(); Entity r = e.getRemover();
if(r instanceof Player) { if (r instanceof Player) {
Player p = (Player) r; Player p = (Player) r;
Location l = e.getEntity().getLocation(); Location l = e.getEntity().getLocation();
if (isPlotWorld(l)) { if (isPlotWorld(l)) {
@ -620,22 +658,22 @@ public class PlayerEvents implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerInteractEntity(final PlayerInteractEntityEvent e) { public void onPlayerInteractEntity(final PlayerInteractEntityEvent e) {
Location l = e.getRightClicked().getLocation(); Location l = e.getRightClicked().getLocation();
if(isPlotWorld(l)) { if (isPlotWorld(l)) {
Player p = e.getPlayer(); Player p = e.getPlayer();
if(!isInPlot(l)) { if (!isInPlot(l)) {
if(!p.hasPermission("plots.admin")) { if (!p.hasPermission("plots.admin")) {
PlayerFunctions.sendMessage(p, C.NO_PERMISSION); PlayerFunctions.sendMessage(p, C.NO_PERMISSION);
e.setCancelled(true); e.setCancelled(true);
} }
} else { } else {
Plot plot = getCurrentPlot(l); Plot plot = getCurrentPlot(l);
if(plot == null) { if (plot == null) {
if(!p.hasPermission("plots.admin")) { if (!p.hasPermission("plots.admin")) {
PlayerFunctions.sendMessage(p, C.NO_PERMISSION); PlayerFunctions.sendMessage(p, C.NO_PERMISSION);
e.setCancelled(true); e.setCancelled(true);
} }
} else if(!plot.hasRights(p)) { } else if (!plot.hasRights(p)) {
if(!p.hasPermission("plots.admin")) { if (!p.hasPermission("plots.admin")) {
PlayerFunctions.sendMessage(p, C.NO_PERMISSION); PlayerFunctions.sendMessage(p, C.NO_PERMISSION);
e.setCancelled(true); e.setCancelled(true);
} }
@ -648,23 +686,23 @@ public class PlayerEvents implements Listener {
public void onEntityDamageByEntityEvent(final EntityDamageByEntityEvent e) { public void onEntityDamageByEntityEvent(final EntityDamageByEntityEvent e) {
Location l = e.getEntity().getLocation(); Location l = e.getEntity().getLocation();
Entity d = e.getDamager(); Entity d = e.getDamager();
if(isPlotWorld(l)) { if (isPlotWorld(l)) {
if(d instanceof Player) { if (d instanceof Player) {
Player p = (Player) d; Player p = (Player) d;
if(!isInPlot(l)) { if (!isInPlot(l)) {
if(!p.hasPermission("plots.admin")) { if (!p.hasPermission("plots.admin")) {
PlayerFunctions.sendMessage(p, C.NO_PERMISSION); PlayerFunctions.sendMessage(p, C.NO_PERMISSION);
e.setCancelled(true); e.setCancelled(true);
} }
} else { } else {
Plot plot = getCurrentPlot(l); Plot plot = getCurrentPlot(l);
if(plot == null) { if (plot == null) {
if(!p.hasPermission("plots.admin")) { if (!p.hasPermission("plots.admin")) {
PlayerFunctions.sendMessage(p, C.NO_PERMISSION); PlayerFunctions.sendMessage(p, C.NO_PERMISSION);
e.setCancelled(true); e.setCancelled(true);
} }
} else if(!plot.hasRights(p)) { } else if (!plot.hasRights(p)) {
if(!p.hasPermission("plots.admin")) { if (!p.hasPermission("plots.admin")) {
PlayerFunctions.sendMessage(p, C.NO_PERMISSION); PlayerFunctions.sendMessage(p, C.NO_PERMISSION);
e.setCancelled(true); e.setCancelled(true);
} }
@ -677,22 +715,22 @@ public class PlayerEvents implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPlayerEggThrow(final PlayerEggThrowEvent e) { public void onPlayerEggThrow(final PlayerEggThrowEvent e) {
Location l = e.getEgg().getLocation(); Location l = e.getEgg().getLocation();
if(isPlotWorld(l)) { if (isPlotWorld(l)) {
Player p = e.getPlayer(); Player p = e.getPlayer();
if(!isInPlot(l)) { if (!isInPlot(l)) {
if(!p.hasPermission("plots.admin")) { if (!p.hasPermission("plots.admin")) {
PlayerFunctions.sendMessage(p, C.NO_PERMISSION); PlayerFunctions.sendMessage(p, C.NO_PERMISSION);
e.setHatching(false); e.setHatching(false);
} }
} else { } else {
Plot plot = getCurrentPlot(l); Plot plot = getCurrentPlot(l);
if(plot == null) { if (plot == null) {
if(!p.hasPermission("plots.admin")) { if (!p.hasPermission("plots.admin")) {
PlayerFunctions.sendMessage(p, C.NO_PERMISSION); PlayerFunctions.sendMessage(p, C.NO_PERMISSION);
e.setHatching(false); e.setHatching(false);
} }
} else if(!plot.hasRights(p)) { } else if (!plot.hasRights(p)) {
if(!p.hasPermission("plots.admin")) { if (!p.hasPermission("plots.admin")) {
PlayerFunctions.sendMessage(p, C.NO_PERMISSION); PlayerFunctions.sendMessage(p, C.NO_PERMISSION);
e.setHatching(false); e.setHatching(false);
} }

View File

@ -1,9 +1,5 @@
package com.intellectualcrafters.plot.listeners; package com.intellectualcrafters.plot.listeners;
import com.intellectualcrafters.plot.*;
import org.bukkit.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.block.Block; import org.bukkit.block.Block;
@ -12,116 +8,144 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.block.Action; import org.bukkit.event.block.Action;
import org.bukkit.event.player.*; import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerPortalEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import com.intellectualcrafters.plot.PWE;
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;
/** /**
* *
* @author Citymonstret * @author Citymonstret
* *
*/ */
public class WorldEditListener implements Listener{ public class WorldEditListener implements Listener {
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 onPlayerMove(final PlayerMoveEvent e){ public void onPlayerMove(final PlayerMoveEvent e) {
if(e.getPlayer().hasPermission("plots.worldedit.bypass")) return; if (e.getPlayer().hasPermission("plots.worldedit.bypass")) {
Location f = e.getFrom(); return;
Location t = e.getTo(); }
Location f = e.getFrom();
Location t = e.getTo();
boolean cm = false; boolean cm = false;
Player p = e.getPlayer(); Player p = e.getPlayer();
if(t == null) if (t == null) {
PWE.removeMask(p); PWE.removeMask(p);
else { } else {
if(f != null) { if (f != null) {
if(!f.getWorld().getName().equalsIgnoreCase(t.getWorld().getName())) if (!f.getWorld().getName().equalsIgnoreCase(t.getWorld().getName())) {
cm = true; cm = true;
else if(f.getBlockX() != t.getBlockX() || f.getBlockZ() != t.getBlockZ()) { } else if ((f.getBlockX() != t.getBlockX()) || (f.getBlockZ() != t.getBlockZ())) {
PlotId idF = PlayerFunctions.getPlot(f); PlotId idF = PlayerFunctions.getPlot(f);
PlotId idT = PlayerFunctions.getPlot(t); PlotId idT = PlayerFunctions.getPlot(t);
if(!(idF==idT)) if (!(idF == idT)) {
cm = true; cm = true;
}
} }
} }
if(cm) { if (cm) {
if(isPlotWorld(t)) { if (isPlotWorld(t)) {
PWE.setMask(p,p.getLocation()); PWE.setMask(p, p.getLocation());
} }
} }
} }
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPlayerJoin(final PlayerJoinEvent e) {
if(e.getPlayer().hasPermission("plots.worldedit.bypass")) return;
Player p = e.getPlayer();
if(isPlotWorld(p.getLocation()))
PWE.setMask(p,p.getLocation());
else
PWE.removeMask(p);
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onTeleport(final PlayerTeleportEvent e) {
if(e.getPlayer().hasPermission("plots.worldedit.bypass")) return;
Player p = e.getPlayer();
Location f = e.getFrom(), t = e.getTo();
if(t == null)
PWE.removeMask(p);
else {
if(f != null && isPlotWorld(f) && !isPlotWorld(t))
PWE.removeMask(p);
else if(isPlotWorld(t))
PWE.setMask(p,p.getLocation());
}
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPortal(PlayerPortalEvent e) {
if(e.getPlayer().hasPermission("plots.worldedit.bypass")) return;
Player p = e.getPlayer();
Location f = e.getFrom(), t = e.getTo();
if(t == null)
PWE.removeMask(p);
else {
if(f != null && isPlotWorld(f) && !isPlotWorld(t))
PWE.removeMask(p);
else if(isPlotWorld(t))
PWE.setMask(p,p.getLocation());
}
} }
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPlayerCommand(PlayerCommandPreprocessEvent e) { public void onPlayerJoin(final PlayerJoinEvent e) {
if(e.getPlayer().hasPermission("plots.worldedit.bypass")) return; if (e.getPlayer().hasPermission("plots.worldedit.bypass")) {
Player p = e.getPlayer(); return;
if(isPlotWorld(p.getLocation())) { }
String msg = e.getMessage().toLowerCase(); Player p = e.getPlayer();
if(msg.startsWith("//gmask") || msg.startsWith("/gmask") || msg.startsWith("/worldedit:gmask") || msg.startsWith("/worldedit:/gmask")) if (isPlotWorld(p.getLocation())) {
e.setCancelled(true); PWE.setMask(p, p.getLocation());
else if(msg.startsWith("/up") || msg.startsWith("//up") || msg.startsWith("/worldedit:up") || msg.startsWith("/worldedit:/up")) { } else {
Plot plot = PlayerFunctions.getCurrentPlot(p); PWE.removeMask(p);
if(p == null || !plot.hasRights(p)) }
e.setCancelled(true); }
}
}
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onInteract(PlayerInteractEvent e) { public void onTeleport(final PlayerTeleportEvent e) {
Player p = e.getPlayer(); if (e.getPlayer().hasPermission("plots.worldedit.bypass")) {
if(!p.hasPermission("plots.admin") && isPlotWorld(p.getLocation())) { return;
if((e.getAction() == Action.LEFT_CLICK_BLOCK || e.getAction() == Action.RIGHT_CLICK_BLOCK) && p.getItemInHand() != null && p.getItemInHand().getType() != Material.AIR) { }
Block b = e.getClickedBlock(); Player p = e.getPlayer();
Plot plot = PlotHelper.getCurrentPlot(b.getLocation()); Location f = e.getFrom(), t = e.getTo();
if(plot != null && plot.hasRights(p))
PWE.setMask(p, b.getLocation()); if (t == null) {
else PWE.removeMask(p);
e.setCancelled(true); } else {
} if ((f != null) && isPlotWorld(f) && !isPlotWorld(t)) {
} PWE.removeMask(p);
} } else if (isPlotWorld(t)) {
PWE.setMask(p, p.getLocation());
}
}
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPortal(PlayerPortalEvent e) {
if (e.getPlayer().hasPermission("plots.worldedit.bypass")) {
return;
}
Player p = e.getPlayer();
Location f = e.getFrom(), t = e.getTo();
if (t == null) {
PWE.removeMask(p);
} else {
if ((f != null) && isPlotWorld(f) && !isPlotWorld(t)) {
PWE.removeMask(p);
} else if (isPlotWorld(t)) {
PWE.setMask(p, p.getLocation());
}
}
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPlayerCommand(PlayerCommandPreprocessEvent e) {
if (e.getPlayer().hasPermission("plots.worldedit.bypass")) {
return;
}
Player p = e.getPlayer();
if (isPlotWorld(p.getLocation())) {
String msg = e.getMessage().toLowerCase();
if (msg.startsWith("//gmask") || msg.startsWith("/gmask") || msg.startsWith("/worldedit:gmask") || msg.startsWith("/worldedit:/gmask")) {
e.setCancelled(true);
} else if (msg.startsWith("/up") || msg.startsWith("//up") || msg.startsWith("/worldedit:up") || msg.startsWith("/worldedit:/up")) {
Plot plot = PlayerFunctions.getCurrentPlot(p);
if ((p == null) || !plot.hasRights(p)) {
e.setCancelled(true);
}
}
}
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onInteract(PlayerInteractEvent e) {
Player p = e.getPlayer();
if (!p.hasPermission("plots.admin") && isPlotWorld(p.getLocation())) {
if (((e.getAction() == Action.LEFT_CLICK_BLOCK) || (e.getAction() == Action.RIGHT_CLICK_BLOCK)) && (p.getItemInHand() != null) && (p.getItemInHand().getType() != Material.AIR)) {
Block b = e.getClickedBlock();
Plot plot = PlotHelper.getCurrentPlot(b.getLocation());
if ((plot != null) && plot.hasRights(p)) {
PWE.setMask(p, b.getLocation());
} else {
e.setCancelled(true);
}
}
}
}
} }

View File

@ -1,9 +1,5 @@
package com.intellectualcrafters.plot.uuid; package com.intellectualcrafters.plot.uuid;
import com.google.common.collect.ImmutableList;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
@ -13,6 +9,11 @@ import java.util.Map;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import com.google.common.collect.ImmutableList;
/** /**
* *
* @author * @author
@ -22,6 +23,7 @@ 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);
} }
@ -29,17 +31,19 @@ public class NameFetcher implements Callable<Map<UUID, String>> {
@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: uuids) { for (UUID uuid : this.uuids) {
if(uuidStringMap.containsKey(uuid)) continue; if (uuidStringMap.containsKey(uuid)) {
HttpURLConnection connection = (HttpURLConnection) new URL(PROFILE_URL+uuid.toString().replace("-", "")).openConnection(); continue;
JSONObject response = (JSONObject) jsonParser.parse(new InputStreamReader(connection.getInputStream())); }
HttpURLConnection connection = (HttpURLConnection) new URL(PROFILE_URL + uuid.toString().replace("-", "")).openConnection();
JSONObject response = (JSONObject) this.jsonParser.parse(new InputStreamReader(connection.getInputStream()));
String name = (String) response.get("name"); String name = (String) response.get("name");
if (name == null) { if (name == null) {
continue; continue;
} }
String cause = (String) response.get("cause"); String cause = (String) response.get("cause");
String errorMessage = (String) response.get("errorMessage"); String errorMessage = (String) response.get("errorMessage");
if (cause != null && cause.length() > 0) { if ((cause != null) && (cause.length() > 0)) {
throw new IllegalStateException(errorMessage); throw new IllegalStateException(errorMessage);
} }
uuidStringMap.put(uuid, name); uuidStringMap.put(uuid, name);

View File

@ -1,20 +1,23 @@
package com.intellectualcrafters.plot.uuid; package com.intellectualcrafters.plot.uuid;
import com.google.common.collect.ImmutableList;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.OutputStream; import java.io.OutputStream;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.util.*; import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import com.google.common.collect.ImmutableList;
/** /**
* @author * @author
*/ */
@ -34,14 +37,15 @@ public class UUIDFetcher implements Callable<Map<String, UUID>> {
this(names, true); this(names, true);
} }
@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(names.size() / PROFILES_PER_REQUEST); int requests = (int) Math.ceil(this.names.size() / PROFILES_PER_REQUEST);
for (int i = 0; i < requests; i++) { for (int i = 0; i < requests; i++) {
HttpURLConnection connection = createConnection(); HttpURLConnection connection = createConnection();
String body = JSONArray.toJSONString(names.subList(i * 100, Math.min((i + 1) * 100, names.size()))); String body = JSONArray.toJSONString(this.names.subList(i * 100, Math.min((i + 1) * 100, this.names.size())));
writeBody(connection, body); writeBody(connection, body);
JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream())); JSONArray array = (JSONArray) this.jsonParser.parse(new InputStreamReader(connection.getInputStream()));
for (Object profile : array) { for (Object profile : array) {
JSONObject jsonProfile = (JSONObject) profile; JSONObject jsonProfile = (JSONObject) profile;
String id = (String) jsonProfile.get("id"); String id = (String) jsonProfile.get("id");
@ -49,7 +53,7 @@ public class UUIDFetcher implements Callable<Map<String, UUID>> {
UUID uuid = UUIDFetcher.getUUID(id); UUID uuid = UUIDFetcher.getUUID(id);
uuidMap.put(name, uuid); uuidMap.put(name, uuid);
} }
if (rateLimiting && i != requests - 1) { if (this.rateLimiting && (i != (requests - 1))) {
Thread.sleep(100L); Thread.sleep(100L);
} }
} }
@ -75,7 +79,7 @@ public class UUIDFetcher implements Callable<Map<String, UUID>> {
} }
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) {

View File

@ -1,17 +1,14 @@
package com.intellectualsites.web; package com.intellectualsites.web;
import org.bukkit.plugin.java.JavaPlugin;
import org.simpleframework.http.Path;
import org.simpleframework.http.Query;
import org.simpleframework.http.Request;
import org.simpleframework.http.Response;
import org.simpleframework.http.core.Container;
import java.io.PrintStream; import java.io.PrintStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import org.bukkit.plugin.java.JavaPlugin;
import org.simpleframework.http.Request;
import org.simpleframework.http.Response;
import org.simpleframework.http.core.Container;
/** /**
* Created by Citymonstret on 2014-09-20. * Created by Citymonstret on 2014-09-20.
@ -19,55 +16,46 @@ import java.util.List;
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
public void handle(Request request, Response response) { public void handle(Request request, Response response) {
try { try {
PrintStream body; PrintStream body;
long time; long time;
Query query; String coverage;
Path path;
int page;
String coverage;
body = response.getPrintStream(); body = response.getPrintStream();
time = System.currentTimeMillis(); time = System.currentTimeMillis();
query = request.getQuery(); request.getQuery();
path = request.getPath(); request.getPath();
if((page = request.getInteger("page")) < 0) { if ((request.getInteger("page")) < 0) {
page = 0;
} }
if((coverage = request.getTarget()) == null || coverage.equals("/")) { if (((coverage = request.getTarget()) == null) || coverage.equals("/")) {
coverage = "index"; coverage = "index";
} }
coverage = coverage.toLowerCase(); coverage = coverage.toLowerCase();
List<String> list = new ArrayList<>( List<String> list = new ArrayList<>(Arrays.asList(new String[] { "install", "index", "stylesheet" }));
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, plugin.getDataFolder()); ResourceHandler stylesheet = new ResourceHandler("stylesheet", ResourceHandler.FileType.CSS, this.plugin.getDataFolder());
String stylesheetHTML = stylesheet.getHTML(); String stylesheetHTML = stylesheet.getHTML();
@ -80,11 +68,11 @@ public class IndexHandler implements Container {
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, plugin.getDataFolder()); ResourceHandler header = new ResourceHandler("header", ResourceHandler.FileType.HTML, this.plugin.getDataFolder());
ResourceHandler footer = new ResourceHandler("footer", ResourceHandler.FileType.HTML, plugin.getDataFolder()); ResourceHandler footer = new ResourceHandler("footer", ResourceHandler.FileType.HTML, this.plugin.getDataFolder());
ResourceHandler cPage = new ResourceHandler(coverage, ResourceHandler.FileType.HTML, plugin.getDataFolder()); ResourceHandler cPage = new ResourceHandler(coverage, ResourceHandler.FileType.HTML, this.plugin.getDataFolder());
String headerHTML = header.getHTML().replace("@title", title); String headerHTML = header.getHTML().replace("@title", this.title);
String footerHTML = footer.getHTML(); String footerHTML = footer.getHTML();
String cPageHTML = cPage.getHTML(); String cPageHTML = cPage.getHTML();
@ -97,7 +85,7 @@ public class IndexHandler implements Container {
body.print(footerHTML); body.print(footerHTML);
} }
body.close(); body.close();
} catch(Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }

View File

@ -1,7 +1,8 @@
package com.intellectualsites.web; package com.intellectualsites.web;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import com.intellectualcrafters.plot.PlotMain;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import org.simpleframework.http.core.Container; import org.simpleframework.http.core.Container;
import org.simpleframework.http.core.ContainerServer; import org.simpleframework.http.core.ContainerServer;
@ -9,9 +10,7 @@ import org.simpleframework.transport.Server;
import org.simpleframework.transport.connect.Connection; import org.simpleframework.transport.connect.Connection;
import org.simpleframework.transport.connect.SocketConnection; import org.simpleframework.transport.connect.SocketConnection;
import java.net.InetSocketAddress; import com.intellectualcrafters.plot.PlotMain;
import java.net.SocketAddress;
/** /**
* Created by Citymonstret on 2014-09-20. * Created by Citymonstret on 2014-09-20.
@ -20,30 +19,30 @@ public class 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 {
container = new IndexHandler(JavaPlugin.getPlugin(PlotMain.class), title); this.container = new IndexHandler(JavaPlugin.getPlugin(PlotMain.class), this.title);
server = new ContainerServer(container); this.server = new ContainerServer(this.container);
connection = new SocketConnection(server); this.connection = new SocketConnection(this.server);
address = new InetSocketAddress(port); this.address = new InetSocketAddress(this.port);
connection.connect(address); this.connection.connect(this.address);
PLOTWEB = this; PLOTWEB = this;
} }
public void stop() throws Exception { public void stop() throws Exception {
connection.close(); this.connection.close();
PLOTWEB = null; PLOTWEB = null;
} }
} }

View File

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

View File

@ -8,7 +8,7 @@ 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();
} }
} }