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,224 +13,151 @@ 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_1("&cID: &6%id%"), OWNER_SIGN_LINE_2("&cOwner:"), OWNER_SIGN_LINE_3("&6%plr%"), OWNER_SIGN_LINE_4("&2Claimed"),
OWNER_SIGN_LINE_2("&cOwner:"),
OWNER_SIGN_LINE_3("&6%plr%"),
OWNER_SIGN_LINE_4("&2Claimed"),
/* /*
Help * Help
*/ */
HELP_CATEGORY("&6Current Category&c: &l%category%"), 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"),
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 * Custom
*/ */
CUSTOM_STRING("-") CUSTOM_STRING("-");
;
/** /**
* Default * Default
*/ */
@ -246,13 +173,15 @@ public enum C {
@SuppressWarnings("unused") @SuppressWarnings("unused")
C() { C() {
/* /*
use setCustomString(); * use setCustomString();
*/ */
} }
/** /**
* Constructor * Constructor
* @param d default *
* @param d
* default
*/ */
C(String d) { C(String d) {
this.d = d; this.d = d;
@ -264,6 +193,7 @@ public enum C {
/** /**
* Get the default string * Get the default string
*
* @return default * @return default
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
@ -273,11 +203,13 @@ public enum C {
/** /**
* Get translated if exists * Get translated if exists
*
* @return translated if exists else default * @return translated if exists else default
*/ */
public String s() { public String s() {
if(this.s.length() < 1) if (this.s.length() < 1) {
return this.d.replace("\\n", "\n"); return this.d.replace("\\n", "\n");
}
return this.s.replace("\\n", "\n"); return this.s.replace("\\n", "\n");
} }
@ -289,5 +221,4 @@ public enum C {
return ChatColor.translateAlternateColorCodes('&', this.s()); return ChatColor.translateAlternateColorCodes('&', this.s());
} }
} }

View File

@ -21,30 +21,8 @@ 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;
} }

View File

@ -6,21 +6,30 @@ 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("")) {
@ -28,19 +37,24 @@ public class Flag {
} }
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

@ -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
* *
*/ */
@ -25,6 +26,7 @@ public class LSetCube {
/** /**
* Constructor * Constructor
*
* @param l1 * @param l1
* @param l2 * @param l2
*/ */
@ -35,6 +37,7 @@ public class LSetCube {
/** /**
* Secondary constructor * Secondary constructor
*
* @param l1 * @param l1
* @param size * @param size
*/ */
@ -45,28 +48,31 @@ public class LSetCube {
/** /**
* 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() {
@ -113,7 +119,9 @@ public class LSetCube {
* @return * @return
*/ */
public Location getNext() { public Location getNext() {
if(!hasNext()) return null; if (!hasNext()) {
return null;
}
this.current = this.current.add(1, 1, 1); this.current = this.current.add(1, 1, 1);
return this.current; return this.current;
} }

View File

@ -11,6 +11,7 @@ package com.intellectualcrafters.plot;
/** /**
* TPS and Lag Checker. * TPS and Lag Checker.
*
* @author Citymonstret * @author Citymonstret
* *
*/ */
@ -32,6 +33,7 @@ public class Lag implements Runnable{
/** /**
* 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() {
@ -40,12 +42,15 @@ public class Lag implements Runnable{
/** /**
* 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; int t = (TC - 1 - ticks) % T.length;
long e = System.currentTimeMillis() - T[t]; long e = System.currentTimeMillis() - T[t];
return ticks / (e / 1000.0D); return ticks / (e / 1000.0D);
@ -53,7 +58,9 @@ public class Lag implements Runnable{
/** /**
* 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")
@ -70,14 +77,16 @@ public class Lag implements Runnable{
/** /**
* 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() {

View File

@ -9,12 +9,17 @@
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
* *
*/ */
@ -39,13 +44,13 @@ public class Logger {
} }
public enum LogLevel { public enum LogLevel {
GENERAL("General"), GENERAL("General"), WARNING("Warning"), DANGER("Danger");
WARNING("Warning"),
DANGER("Danger");
private String name; private String name;
LogLevel(String name) { LogLevel(String name) {
this.name = name; this.name = name;
} }
@Override @Override
public String toString() { public String toString() {
return this.name; return this.name;

View File

@ -28,6 +28,26 @@ package com.intellectualcrafters.plot;
* 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;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
@ -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
@ -100,28 +111,31 @@ public class Metrics {
} }
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) {
@ -130,67 +144,76 @@ public class Metrics {
// 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
// first time we are posting,
// it is not a interval ping, so it evaluates to FALSE // it is not a interval ping, so it evaluates to FALSE
// Each time thereafter it will evaluate to TRUE, i.e PING! // Each time thereafter it will evaluate to TRUE, i.e
postPlugin(!firstPost); // PING!
postPlugin(!this.firstPost);
// After the first post we set firstPost to false // After the first post we set firstPost to false
// Each post thereafter will be a ping // Each post thereafter will be a ping
firstPost = false; 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,78 +229,86 @@ 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
// via -P) for plugins to use
// is to abuse the plugin object we already have // is to abuse the plugin object we already have
// plugin.getDataFolder() => base/plugins/PluginA/ // plugin.getDataFolder() => base/plugins/PluginA/
// pluginsFolder => base/plugins/ // pluginsFolder => base/plugins/
// The base is not necessarily relative to the startup directory. // The base is not necessarily relative to the startup directory.
File pluginsFolder = plugin.getDataFolder().getParentFile(); File pluginsFolder = this.plugin.getDataFolder().getParentFile();
// return => base/plugins/PluginMetrics/config.yml // return => base/plugins/PluginMetrics/config.yml
return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml"); return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml");
} }
@ -287,18 +318,22 @@ public class Metrics {
*/ */
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
// any code outside of this class / Java
// Construct the post data // 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));
@ -322,8 +357,8 @@ public class Metrics {
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();
@ -374,7 +409,7 @@ 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
@ -387,7 +422,7 @@ public class Metrics {
// 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")) {
@ -397,8 +432,8 @@ public class Metrics {
} 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) {
try {
gzos.close(); gzos.close();
} catch (IOException ignore) { } 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
*/ */
@ -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
@ -24,14 +23,15 @@ public class PWE {
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 (!r) {
if (p.hasPermission("plots.we.member") && plot.hasRights(p)) if (p.hasPermission("plots.we.member") && plot.hasRights(p)) {
r = true; r = true;
else if (p.hasPermission("plots.we.bypass")) { } else if (p.hasPermission("plots.we.bypass")) {
s.setMask(null); s.setMask(null);
return; return;
} }

View File

@ -9,14 +9,24 @@
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
* *
*/ */
@ -25,7 +35,8 @@ public class PlayerFunctions {
/** /**
* *
* @param player player * @param player
* player
* @return * @return
*/ */
public static boolean isInPlot(Player player) { public static boolean isInPlot(Player player) {
@ -34,7 +45,8 @@ public class PlayerFunctions {
/** /**
* *
* @param plot plot * @param plot
* plot
* @return * @return
*/ */
public static boolean hasExpired(Plot plot) { public static boolean hasExpired(Plot plot) {
@ -66,7 +78,7 @@ public class PlayerFunctions {
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 {
@ -74,11 +86,11 @@ public class PlayerFunctions {
} }
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);
} }
@ -115,8 +127,9 @@ public class PlayerFunctions {
*/ */
@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()); PlotId id = getPlot(player.getLocation());
World world = player.getWorld(); World world = player.getWorld();
if (id == null) { if (id == null) {
@ -138,6 +151,7 @@ public class PlayerFunctions {
* @param id * @param id
* @param plot * @param plot
*/ */
@Deprecated
public static void set(Integer[] id, Plot plot) { public static void set(Integer[] id, Plot plot) {
PlotMain.updatePlot(plot); PlotMain.updatePlot(plot);
} }
@ -153,8 +167,9 @@ public class PlayerFunctions {
// //
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;
} }
@ -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,12 +212,14 @@ public class PlayerFunctions {
* @return PlotMain.getPlots(); * @return PlotMain.getPlots();
* @deprecated * @deprecated
*/ */
@Deprecated
public static Set<Plot> getPlots() { public static Set<Plot> getPlots() {
return PlotMain.getPlots(); return PlotMain.getPlots();
} }
/** /**
* \\previous\\ * \\previous\\
*
* @param plr * @param plr
* @param msg * @param msg
* Was used to wrap the chat client length (Packets out--) * Was used to wrap the chat client length (Packets out--)
@ -210,26 +230,37 @@ public class PlayerFunctions {
/** /**
* 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("")) {
return;
}
sendMessageWrapped(plr, ChatColor.translateAlternateColorCodes('&', C.PREFIX.s() + msg)); sendMessageWrapped(plr, ChatColor.translateAlternateColorCodes('&', C.PREFIX.s() + msg));
} }
/** /**
* Send a message to the player * Send a message to the player
* @param plr Player to recieve message *
* @param c Caption to send * @param plr
* Player to recieve message
* @param c
* Caption to send
*/ */
public static void sendMessage(Player plr, C c, String... args) { public static void sendMessage(Player plr, C c, String... args) {
if(c.s().length() < 1) return; if (c.s().length() < 1) {
return;
}
String msg = c.s(); String msg = c.s();
if(args != null && args.length > 0) { if ((args != null) && (args.length > 0)) {
for(String str : args) for (String str : args) {
msg = msg.replaceFirst("%s", str); msg = msg.replaceFirst("%s", str);
} }
}
sendMessage(plr, msg); sendMessage(plr, msg);
} }
} }

View File

@ -9,19 +9,19 @@
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
* *
*/ */
@ -67,6 +67,7 @@ public class Plot implements Cloneable{
/** /**
* Primary constructor * Primary constructor
*
* @param id * @param id
* @param owner * @param owner
* @param plotBiome * @param plotBiome
@ -93,6 +94,7 @@ public class Plot implements Cloneable{
/** /**
* Constructor for saved plots * Constructor for saved plots
*
* @param id * @param id
* @param owner * @param owner
* @param plotBiome * @param plotBiome
@ -115,15 +117,17 @@ public class Plot implements Cloneable{
this.settings.setAlias(alias); this.settings.setAlias(alias);
this.settings.setPosition(position); this.settings.setPosition(position);
this.delete = false; this.delete = false;
if (flags!=null) if (flags != null) {
this.settings.setFlags(flags); this.settings.setFlags(flags);
else } else {
this.settings.setFlags(new Flag[0]); this.settings.setFlags(new Flag[0]);
}
this.world = world; this.world = world;
} }
/** /**
* Check if the plot has a set owner * Check if the plot has a set owner
*
* @return false if there is no owner * @return false if there is no owner
*/ */
public boolean hasOwner() { public boolean hasOwner() {
@ -132,6 +136,7 @@ public class Plot implements Cloneable{
/** /**
* Set the owner * Set the owner
*
* @param player * @param player
*/ */
public void setOwner(Player player) { public void setOwner(Player player) {
@ -140,20 +145,22 @@ public class Plot implements Cloneable{
/** /**
* Check if the player is either the owner or on the helpers list * Check if the player is either the owner or on the helpers list
*
* @param player * @param player
* @return true if the player is added as a helper or is the owner * @return true if the player is added as a helper or is the owner
*/ */
public boolean hasRights(Player player) { public boolean hasRights(Player player) {
return player.hasPermission("plots.admin") || this.helpers != null && this.helpers.contains(DBFunc.everyone) || this.helpers != null && this.helpers.contains(player.getUniqueId()) || this.owner != null && this.owner.equals(player.getUniqueId()); 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? * Should the player be allowed to enter?
*
* @param player * @param player
* @return false if the player is allowed to enter * @return false if the player is allowed to enter
*/ */
public boolean deny_entry(Player player) { public boolean deny_entry(Player player) {
return this.denied != null && (this.denied.contains(DBFunc.everyone) && !this.hasRights(player) || !this.hasRights(player) && this.denied.contains(player.getUniqueId())); return (this.denied != null) && ((this.denied.contains(DBFunc.everyone) && !this.hasRights(player)) || (!this.hasRights(player) && this.denied.contains(player.getUniqueId())));
} }
/** /**
@ -172,7 +179,6 @@ public class Plot implements Cloneable{
return this.id; return this.id;
} }
/** /**
* Get the plot World * Get the plot World
* *
@ -183,6 +189,7 @@ public class Plot implements Cloneable{
/** /**
* Get a clone of the plot * Get a clone of the plot
*
* @return * @return
*/ */
@Override @Override
@ -196,18 +203,25 @@ public class Plot implements Cloneable{
/** /**
* 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() {
@ -219,19 +233,27 @@ public class Plot implements Cloneable{
/** /**
* 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,33 +9,45 @@
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);
@ -48,7 +60,11 @@ 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) {
if (n == 1) {
return 0;
}
long r = ((nextLong() >>> 32) * n) >> 32; long r = ((nextLong() >>> 32) * n) >> 32;
return (int) r; return (int) r;
} }
@ -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,28 +126,28 @@ 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);
@ -151,7 +173,7 @@ 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;
@ -160,7 +182,8 @@ public class PlotHelper {
} }
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);
} }
@ -246,14 +269,18 @@ public class PlotHelper {
// 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;
// maxZ = Math.min(topPlot1.getBlockZ(), topPlot2.getBlockZ()) -
// Settings.PLOT_WIDTH;
// } else { // } else {
// minZ = bottomPlot1.getBlockZ(); // minZ = bottomPlot1.getBlockZ();
// maxZ = topPlot1.getBlockZ(); // maxZ = topPlot1.getBlockZ();
// //
// minX = Math.min(bottomPlot1.getBlockX(), bottomPlot2.getBlockX()) + Settings.PLOT_WIDTH; // minX = Math.min(bottomPlot1.getBlockX(), bottomPlot2.getBlockX()) +
// maxX = Math.max(topPlot1.getBlockX(), topPlot2.getBlockX()) - Settings.PLOT_WIDTH; // Settings.PLOT_WIDTH;
// maxX = Math.max(topPlot1.getBlockX(), topPlot2.getBlockX()) -
// Settings.PLOT_WIDTH;
// } // }
// //
// isWallX = (maxX - minX) > (maxZ - minZ); // isWallX = (maxX - minX) > (maxZ - minZ);
@ -324,18 +351,14 @@ 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,
Bukkit.getScheduler().scheduleSyncRepeatingTask(PlotMain.getMain(),
new Runnable() {
Location bottom = getPlotBottomLoc(w, plot.id); Location bottom = getPlotBottomLoc(w, plot.id);
Location top = getPlotTopLoc(w, plot.id); Location top = getPlotTopLoc(w, plot.id);
int y = plotworld.ROAD_HEIGHT; int y = plotworld.ROAD_HEIGHT;
@ -343,36 +366,28 @@ public class PlotHelper {
@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);
@ -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);
@ -434,7 +450,6 @@ 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,6 +458,7 @@ 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(":");
@ -478,17 +494,32 @@ public class PlotHelper {
filling_data[i] = result[1]; filling_data[i] = result[1];
} }
try {
final int prime = 31; final int prime = 31;
int h = 1; int h = 1;
h = prime * h + pos1.getBlockX(); h = (prime * h) + pos1.getBlockX();
h = prime * h + pos1.getBlockZ(); h = (prime * h) + pos1.getBlockZ();
state = h; state = h;
boolean canSetFast;
try {
new SetBlockFast();
canSetFast = true;
} catch (Exception e) {
canSetFast = false;
}
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 y = 0; y < 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, 7, (byte) 0);
}
}
}
for (int y = 1; y < plotworld.PLOT_HEIGHT; 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(filling.length);
@ -498,7 +529,7 @@ public class PlotHelper {
} }
} }
} }
for (int y = plotworld.PLOT_HEIGHT; y<plotworld.PLOT_HEIGHT+1; 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(plotfloors.length); int i = random(plotfloors.length);
@ -508,14 +539,140 @@ public class PlotHelper {
} }
} }
} }
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))); PlayerFunctions.sendMessage(requester, C.CLEARING_DONE.s().replaceAll("%time%", "" + ((System.nanoTime() - start) / 1000000.0)));
SetBlockFast.update(requester); SetBlockFast.update(requester);
return;
} catch (Exception e) {
PlayerFunctions.sendMessage(requester, C.PREFIX.s() + "&cPlot clear failed... Trying again...");
}
} }
})); }));
}
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);
}
}
}
} }
} }
@ -539,9 +696,7 @@ 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 {
@ -566,9 +721,7 @@ 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);
} }
@ -651,7 +800,7 @@ public class PlotHelper {
* 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)
return false;
if (getClass() != obj.getClass())
return false;
PlotId other = (PlotId) obj;
return (this.x==other.x && this.y==other.y);
} }
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
PlotId other = (PlotId) obj;
return ((this.x == other.x) && (this.y == other.y));
}
@Override @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 {
@ -114,8 +206,7 @@ public class PlotMain extends JavaPlugin {
@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);
@ -138,9 +229,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;
} }
@ -164,6 +256,7 @@ public class PlotMain extends JavaPlugin {
} }
return new HashSet<Plot>(myplots); return new HashSet<Plot>(myplots);
} }
/** /**
* *
* @param player * @param player
@ -183,6 +276,7 @@ public class PlotMain extends JavaPlugin {
} }
return new HashSet<Plot>(myplots); return new HashSet<Plot>(myplots);
} }
/** /**
* *
* @param world * @param world
@ -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,33 +331,38 @@ 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) {
@ -272,15 +375,18 @@ public class PlotMain extends JavaPlugin {
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,8 +394,10 @@ 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) {
@ -307,8 +415,7 @@ public class PlotMain extends JavaPlugin {
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);
} }
} }
@ -326,8 +433,7 @@ public class PlotMain extends JavaPlugin {
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()) {
@ -392,58 +497,26 @@ public class PlotMain extends JavaPlugin {
} }
// 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.");
System.out.print("\u001B[31m[Plots] MySQL is not setup correctly. The plugin will disable itself.\u001B[0m"); System.out.print("\u001B[31m[Plots] MySQL is not setup correctly. The plugin will disable itself.\u001B[0m");
@ -462,9 +535,10 @@ 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");
sendConsoleSenderMessage(C.PREFIX.s() + "&cFailed to open SQLite connection. The plugin will disable itself."); sendConsoleSenderMessage(C.PREFIX.s() + "&cFailed to open SQLite connection. The plugin will disable itself.");
@ -488,8 +562,7 @@ public class PlotMain extends JavaPlugin {
} }
} }
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");
@ -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
* *
@ -542,31 +607,28 @@ 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) {
@ -581,8 +643,7 @@ public class PlotMain extends JavaPlugin {
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
.translateAlternateColorCodes('&', C.PREFIX.s() + c.s())));
} }
System.out.println(ChatColor.stripColor(ChatColor.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
*/ */
@ -655,8 +718,7 @@ public class PlotMain extends JavaPlugin {
} }
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");
} }
@ -667,8 +729,7 @@ public class PlotMain extends JavaPlugin {
} }
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");
} }
@ -679,13 +740,11 @@ public class PlotMain extends JavaPlugin {
} }
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);
@ -717,24 +776,23 @@ 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() {
World world;
Location location; Location location;
long ticked = 0l; long ticked = 0l;
long error = 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(ticked > 36000l) { if (this.ticked > 36000l) {
ticked = 0l; this.ticked = 0l;
sendConsoleSenderMessage(C.PREFIX.s() + "KillAllEntities has been running for 60 minutes. Errors: " + error); sendConsoleSenderMessage(C.PREFIX.s() + "KillAllEntities has been running for 60 minutes. Errors: " + this.error);
error = 0l; this.error = 0l;
} }
for (String w : getPlotWorlds()) { for (String w : getPlotWorlds()) {
PlotWorld plotworld = getWorldSettings(w); getWorldSettings(w);
World world = Bukkit.getServer().getWorld(w); World world = Bukkit.getServer().getWorld(w);
try { try {
if (world.getLoadedChunks().length < 1) { if (world.getLoadedChunks().length < 1) {
@ -744,10 +802,11 @@ public class PlotMain extends JavaPlugin {
Entity[] entities = chunk.getEntities(); Entity[] entities = chunk.getEntities();
for (int i = entities.length - 1; i >= 0; i--) { for (int i = entities.length - 1; i >= 0; i--) {
Entity entity = entities[i]; Entity entity = entities[i];
if (entity.getType() == EntityType.PLAYER) if (entity.getType() == EntityType.PLAYER) {
continue; continue;
location = entity.getLocation(); }
if (!PlayerEvents.isInPlot(location)) { this.location = entity.getLocation();
if (!PlayerEvents.isInPlot(this.location)) {
boolean tamed = false; boolean tamed = false;
if (Settings.MOB_PATHFINDING) { if (Settings.MOB_PATHFINDING) {
if (entity instanceof Tameable) { if (entity instanceof Tameable) {
@ -755,8 +814,7 @@ public class PlotMain extends JavaPlugin {
if (tameable.isTamed()) { if (tameable.isTamed()) {
tamed = true; tamed = true;
} }
} } else if (entity instanceof LivingEntity) {
else if (entity instanceof LivingEntity) {
LivingEntity livingEntity = ((LivingEntity) entity); LivingEntity livingEntity = ((LivingEntity) entity);
if (livingEntity.getCustomName() != null) { if (livingEntity.getCustomName() != null) {
tamed = true; tamed = true;
@ -766,10 +824,10 @@ public class PlotMain extends JavaPlugin {
boolean found = false; boolean found = false;
int radius = 1; int radius = 1;
int dir = 0; int dir = 0;
int x = location.getBlockX(); int x = this.location.getBlockX();
int y = location.getBlockY(); int y = this.location.getBlockY();
int z = location.getBlockZ(); int z = this.location.getBlockZ();
while (!found || radius > PlotWorld.ROAD_WIDTH_DEFAULT) { while (!found || (radius > PlotWorld.ROAD_WIDTH_DEFAULT)) {
Location pos; Location pos;
switch (dir) { switch (dir) {
case 0: case 0:
@ -790,7 +848,7 @@ public class PlotMain extends JavaPlugin {
radius++; radius++;
break; break;
default: default:
pos = location; pos = this.location;
break; break;
} }
@ -809,10 +867,9 @@ public class PlotMain extends JavaPlugin {
} }
} }
} catch (Exception e) { } catch (Exception e) {
++error; ++this.error;
} } finally {
finally { ++this.ticked;
++ticked;
} }
} }
} }
@ -846,10 +903,9 @@ public class PlotMain extends JavaPlugin {
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) { public static void addPlotWorld(String world, PlotWorld plotworld) {
PlotMain.worlds.put(world, plotworld); PlotMain.worlds.put(world, plotworld);
if(!plots.containsKey(world)) if (!plots.containsKey(world)) {
plots.put(world, new HashMap<PlotId, Plot>()); plots.put(world, new HashMap<PlotId, Plot>());
} }
} }
}

View File

@ -13,22 +13,17 @@ 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
*/
@SuppressWarnings("unused")
private Plot plot;
/** /**
* plot biome * plot biome
*/ */
@ -50,12 +45,13 @@ public class PlotSettings {
*/ */
private boolean changeTime; private boolean changeTime;
private PlotHomePosition position; private PlotHomePosition position;
/** /**
* Constructor * Constructor
*
* @param plot * @param plot
*/ */
public PlotSettings(Plot plot) { public PlotSettings(Plot plot) {
this.plot = plot;
this.alias = ""; this.alias = "";
} }
@ -88,6 +84,7 @@ public class PlotSettings {
* @return * @return
* @deprecated * @deprecated
*/ */
@Deprecated
public Biome getBiome() { public Biome getBiome() {
return this.biome; return this.biome;
} }
@ -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 void setPosition(PlotHomePosition position) {
public String getLeaveMessage() { return ""; } 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
*
*/ */
/** /**

View File

@ -14,6 +14,7 @@ import org.bukkit.entity.Player;
/** /**
* Random utilities * Random utilities
*
* @author Citymonstret * @author Citymonstret
* *
*/ */
@ -46,15 +47,13 @@ public class RUtils {
} }
enum Direction { enum Direction {
SOUTH(0), SOUTH(0), EAST(1), NORTH(2), WEST(3);
EAST(1),
NORTH(2),
WEST(3)
;
private int i; private int i;
Direction(int i) { Direction(int i) {
this.i = i; this.i = i;
} }
public int getInt() { public int getInt() {
return this.i; return this.i;
} }
@ -65,14 +64,10 @@ public class RUtils {
} }
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) { switch (x) {
case 0: case 0:
return Direction.SOUTH; return Direction.SOUTH;
@ -91,24 +86,4 @@ public class RUtils {
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
@ -27,7 +27,9 @@ 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("\\.");
@ -57,29 +59,31 @@ public class ReflectionUtils {
} }
/** /**
* 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)
.replace("{nm}", "net.minecraft");
return getRefClass(Class.forName(className)); return getRefClass(Class.forName(className));
} catch (ClassNotFoundException ignored) { } 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) {
continue;
}
for (int i = 0; i < classes.length; i++) { for (int i = 0; i < classes.length; i++) {
if (!classes.equals(methodTypes)) continue findMethod; if (!classes.equals(methodTypes)) {
continue findMethod;
}
return new RefMethod(m); return new RefMethod(m);
} }
} }
@ -190,14 +227,17 @@ 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)) {
@ -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,15 +263,20 @@ 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,15 +342,20 @@ 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);
@ -311,27 +375,33 @@ 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);
} }
@ -383,15 +459,16 @@ 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);
@ -399,13 +476,16 @@ public class ReflectionUtils {
/** /**
* 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);
} }
@ -419,22 +499,23 @@ 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);
@ -442,25 +523,31 @@ public class ReflectionUtils {
/** /**
* 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,18 +1,24 @@
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.
*/ */
@ -28,7 +34,7 @@ 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);
@ -40,12 +46,12 @@ 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) {
@ -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,16 +12,20 @@ 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);
@ -28,7 +33,7 @@ public class SetBlockFast {
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
@ -39,15 +40,19 @@ public class Settings {
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 { public static class Update {
/** /**
* Update plugin? * Update plugin?
*
* @deprecated * @deprecated
*/ */
@Deprecated
public static boolean AUTO_UPDATE = false; public static boolean AUTO_UPDATE = false;
} }
@ -58,6 +63,7 @@ public class Settings {
/** /**
* Database settings * Database settings
*
* @author Citymonstret * @author Citymonstret
* *
*/ */

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,11 +264,9 @@ 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) {
@ -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,14 +343,14 @@ 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,6 +55,7 @@ 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,7 +89,7 @@ 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);
@ -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;
PlotMain.addPlotWorld(world, plotworld);
plotsize = plotworld.PLOT_WIDTH;
pathsize = plotworld.ROAD_WIDTH;
bottom = (short) Material.BEDROCK.getId();
floor1 = getBlock(plotworld.ROAD_BLOCK);
floor2 = getBlock(plotworld.ROAD_STRIPES);
wallfilling = getBlock(plotworld.WALL_FILLING);
size = pathsize + plotsize;
wall = getBlock(plotworld.WALL_BLOCK);
plotfloors = new short[plotworld.TOP_BLOCK.length];
filling = new short[plotworld.MAIN_BLOCK.length];
for (int i = 0; i < plotworld.TOP_BLOCK.length; i++) {
plotfloors[i] = getBlock(plotworld.TOP_BLOCK[i]);
} }
for (int i = 0; i < plotworld.MAIN_BLOCK.length; i++) { this.plotworld.DEFAULT_FLAGS = default_flags;
filling[i] = getBlock(plotworld.MAIN_BLOCK[i]);
PlotMain.addPlotWorld(world, this.plotworld);
this.plotsize = this.plotworld.PLOT_WIDTH;
this.pathsize = this.plotworld.ROAD_WIDTH;
this.bottom = (short) Material.BEDROCK.getId();
this.floor1 = getBlock(this.plotworld.ROAD_BLOCK);
this.floor2 = getBlock(this.plotworld.ROAD_STRIPES);
this.wallfilling = getBlock(this.plotworld.WALL_FILLING);
this.size = this.pathsize + this.plotsize;
this.wall = getBlock(this.plotworld.WALL_BLOCK);
this.plotfloors = new short[this.plotworld.TOP_BLOCK.length];
this.filling = new short[this.plotworld.MAIN_BLOCK.length];
for (int i = 0; i < this.plotworld.TOP_BLOCK.length; i++) {
this.plotfloors[i] = getBlock(this.plotworld.TOP_BLOCK[i]);
}
for (int i = 0; i < this.plotworld.MAIN_BLOCK.length; 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;
} }
} }
@ -175,339 +197,347 @@ public class WorldGenerator extends ChunkGenerator {
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);
} }
if (plotMinX+1<=16||roadStartX<=16&&roadStartX>0) { setCuboidRegion(0, 16, 1, this.roadheight + 1, Math.max(start, 0), Math.min(16, end), this.floor1);
int start = (int) Math.max(16-plotMinX-pathsize+1,16-roadStartX+1); }
int end = (int) Math.min(16-plotMinX-1,16-roadStartX+pathsize); if (((plotMinX + 1) <= 16) || ((roadStartX <= 16) && (roadStartX > 0))) {
if (start>=0 && start<=16 && end <0) int start = Math.max((16 - plotMinX - this.pathsize) + 1, (16 - roadStartX) + 1);
int end = Math.min(16 - plotMinX - 1, (16 - roadStartX) + this.pathsize);
if ((start >= 0) && (start <= 16) && (end < 0)) {
end = 16; 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, plotheight, 0, 16-roadStartZ, filling); setCuboidRegion(0, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.filling);
setCuboidRegion(0, 16, plotheight, plotheight+1, 0, 16-roadStartZ, plotfloors); setCuboidRegion(0, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.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 {
else { int z = 16 - roadStartZ;
int z = (int) (16-roadStartZ); if (z < 0) {
if (z<0)
z = 16; z = 16;
setCuboidRegion(16-plotMinX, 16, 1, plotheight, 0, z, filling); }
setCuboidRegion(16-plotMinX, 16, plotheight, plotheight+1, 0, z, plotfloors); setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, z, this.filling);
setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, z, this.plotfloors);
} }
if (roadStartZ <= 16) { if (roadStartZ <= 16) {
setCuboidRegion(16-plotMinX, 16, 1, plotheight, 0, 16-roadStartZ, filling); setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.filling);
setCuboidRegion(16-plotMinX, 16, plotheight, plotheight+1, 0, 16-roadStartZ, plotfloors); setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors);
} } else {
else {
if (roadStartX <= 16) { if (roadStartX <= 16) {
if (plotMinZ > 16) { if (plotMinZ > 16) {
int x = (int) (16-roadStartX); int x = 16 - roadStartX;
if (x<0) if (x < 0) {
x = 16; x = 16;
setCuboidRegion(0, x, 1, plotheight, 0, 16, filling); }
setCuboidRegion(0, x, plotheight,plotheight+1, 0, 16, plotfloors); setCuboidRegion(0, x, 1, this.plotheight, 0, 16, this.filling);
setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, 16, this.plotfloors);
} }
} }
} }
} } else {
else {
if (plotMinZ <= 16) { if (plotMinZ <= 16) {
if (roadStartX > 16) { if (roadStartX > 16) {
int x = (int) (16-roadStartX); int x = 16 - roadStartX;
if (x<0) if (x < 0) {
x = 16; x = 16;
setCuboidRegion(0, x, 1, plotheight, 16-plotMinZ, 16, filling);
setCuboidRegion(0, x, plotheight, plotheight+1, 16-plotMinZ, 16, plotfloors);
} }
setCuboidRegion(0, x, 1, this.plotheight, 16 - plotMinZ, 16, this.filling);
setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors);
} }
else { } else {
if (roadStartZ > 16) { if (roadStartZ > 16) {
int x = (int) (16-roadStartX); int x = 16 - roadStartX;
if (x<0) if (x < 0) {
x = 16; x = 16;
int z = (int) (16-roadStartZ); }
if (z<0) int z = 16 - roadStartZ;
if (z < 0) {
z = 16; z = 16;
}
if (roadStartX > 16) { if (roadStartX > 16) {
setCuboidRegion(0, x, 1, plotheight, 0, z, filling); setCuboidRegion(0, x, 1, this.plotheight, 0, z, this.filling);
setCuboidRegion(0, x, plotheight, plotheight+1, 0, z, plotfloors); setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, z, this.plotfloors);
} } else {
else { setCuboidRegion(0, x, 1, this.plotheight, 0, z, this.filling);
setCuboidRegion(0, x, 1, plotheight, 0, z, filling); setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, z, this.plotfloors);
setCuboidRegion(0, x, plotheight, plotheight+1, 0, z, plotfloors);
} }
} }
} }
} }
} } else {
else {
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);
} }
} }
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);
} }
if (roadStartZ <= 16) { if (roadStartZ <= 16) {
setCuboidRegion(16-plotMinX, 16, 1, plotheight, 0, 16-roadStartZ, filling); setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.filling);
setCuboidRegion(16-plotMinX, 16, plotheight, plotheight+1, 0, 16-roadStartZ, plotfloors); setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.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;
} }
@ -36,8 +36,9 @@ public class XPopulator extends BlockPopulator {
} }
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,23 +47,25 @@ 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(":");
@ -77,51 +80,52 @@ 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
@ -130,294 +134,311 @@ public class XPopulator extends BlockPopulator {
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);
} }
if (plotMinX+1<=16||roadStartX<=16&&roadStartX>0) { setCuboidRegion(0, 16, 1, this.roadheight + 1, Math.max(start, 0), Math.min(16, end), this.f1_id, this.f1_v, w);
int start = (int) Math.max(16-plotMinX-pathsize+1,16-roadStartX+1); }
int end = (int) Math.min(16-plotMinX-1,16-roadStartX+pathsize); if (((plotMinX + 1) <= 16) || ((roadStartX <= 16) && (roadStartX > 0))) {
if (start>=0 && start<=16 && end <0) int start = Math.max((16 - plotMinX - this.pathsize) + 1, (16 - roadStartX) + 1);
int end = Math.min(16 - plotMinX - 1, (16 - roadStartX) + this.pathsize);
if ((start >= 0) && (start <= 16) && (end < 0)) {
end = 16; 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, plotheight, 0, 16-roadStartZ, p_id, p_v, w); setCuboidRegion(0, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.p_id, this.p_v, w);
setCuboidRegion(0, 16, plotheight, plotheight+1, 0, 16-roadStartZ, f_id, f_v, w); setCuboidRegion(0, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.f_id, this.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 {
else { int z = 16 - roadStartZ;
int z = (int) (16-roadStartZ); if (z < 0) {
if (z<0)
z = 16; z = 16;
setCuboidRegion(16-plotMinX, 16, 1, plotheight, 0, z, p_id, p_v, w); }
setCuboidRegion(16-plotMinX, 16, plotheight, plotheight+1, 0, z, f_id, f_v, w); 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);
} }
if (roadStartZ <= 16) { if (roadStartZ <= 16) {
setCuboidRegion(16-plotMinX, 16, 1, plotheight, 0, 16-roadStartZ, p_id, p_v, w); setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.p_id, this.p_v, w);
setCuboidRegion(16-plotMinX, 16, plotheight, plotheight+1, 0, 16-roadStartZ, f_id, f_v, w); setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.f_id, this.f_v, w);
} } else {
else {
if (roadStartX <= 16) { if (roadStartX <= 16) {
if (plotMinZ > 16) { if (plotMinZ > 16) {
int x = (int) (16-roadStartX); int x = 16 - roadStartX;
if (x<0) if (x < 0) {
x = 16; x = 16;
setCuboidRegion(0, x, 1, plotheight, 0, 16, p_id, p_v, w); }
setCuboidRegion(0, x, plotheight,plotheight+1, 0, 16, f_id, f_v, w); 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);
} }
} }
} }
} } else {
else {
if (plotMinZ <= 16) { if (plotMinZ <= 16) {
if (roadStartX > 16) { if (roadStartX > 16) {
int x = (int) (16-roadStartX); int x = 16 - roadStartX;
if (x<0) if (x < 0) {
x = 16; 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);
} }
setCuboidRegion(0, x, 1, this.plotheight, 16 - plotMinZ, 16, this.p_id, this.p_v, w);
setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.f_id, this.f_v, w);
} }
else { } else {
if (roadStartZ > 16) { if (roadStartZ > 16) {
int x = (int) (16-roadStartX); int x = 16 - roadStartX;
if (x<0) if (x < 0) {
x = 16; x = 16;
int z = (int) (16-roadStartZ); }
if (z<0) int z = 16 - roadStartZ;
if (z < 0) {
z = 16; z = 16;
}
if (roadStartX > 16) { if (roadStartX > 16) {
setCuboidRegion(0, x, 1, plotheight, 0, z, p_id, p_v, w); setCuboidRegion(0, x, 1, this.plotheight, 0, z, this.p_id, this.p_v, w);
setCuboidRegion(0, x, plotheight, plotheight+1, 0, z, f_id, f_v, w); setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, z, this.f_id, this.f_v, w);
} } else {
else { setCuboidRegion(0, x, 1, this.plotheight, 0, z, this.p_id, this.p_v, w);
setCuboidRegion(0, x, 1, plotheight, 0, z, p_id, p_v, w); setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, z, this.f_id, this.f_v, w);
setCuboidRegion(0, x, plotheight, plotheight+1, 0, z, f_id, f_v, w);
} }
} }
} }
} }
} } else {
else {
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);
} }
} }
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);
} }
if (roadStartZ <= 16) { if (roadStartZ <= 16) {
setCuboidRegion(16-plotMinX, 16, 1, plotheight, 0, 16-roadStartZ, p_id, p_v, w); setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.p_id, this.p_v, w);
setCuboidRegion(16-plotMinX, 16, plotheight, plotheight+1, 0, 16-roadStartZ, f_id, f_v, w); setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.f_id, this.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,48 +9,54 @@
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.
private JavaPlugin plugin;
// To access plotMain stuffz. // To access plotMain stuffz.
private PlotMain plotMain; private PlotMain plotMain;
// Reference // Reference
public static final String ADMIN_PERMISSION = "plots.admin"; public static final String ADMIN_PERMISSION = "plots.admin";
/** /**
* Constructor. Insert any Plugin. * Constructor. Insert any Plugin.
*
* @param plugin * @param plugin
*/ */
public PlotAPI(JavaPlugin plugin) { public PlotAPI(JavaPlugin plugin) {
this.plugin = plugin;
this.plotMain = JavaPlugin.getPlugin(PlotMain.class); this.plotMain = JavaPlugin.getPlugin(PlotMain.class);
} }
/** /**
* Send a message to a player. * Send a message to a player.
*
* @param player * @param player
* @param c (Caption) * @param c
* (Caption)
*/ */
public void sendMessage(Player player, C c) { public void sendMessage(Player player, C c) {
PlayerFunctions.sendMessage(player, c); PlayerFunctions.sendMessage(player, c);
@ -58,6 +64,7 @@ public class PlotAPI {
/** /**
* Send a message to a player. * Send a message to a player.
*
* @param player * @param player
* @param string * @param string
*/ */
@ -67,6 +74,7 @@ public class PlotAPI {
/** /**
* Send a message to the console. * Send a message to the console.
*
* @param msg * @param msg
*/ */
public void sendConsoleMessage(String msg) { public void sendConsoleMessage(String msg) {
@ -75,27 +83,35 @@ public class PlotAPI {
/** /**
* Send a message to the console * Send a message to the console
* @param c (Caption) *
* @param c
* (Caption)
*/ */
public void sendConsoleMessage(C c) { public void sendConsoleMessage(C c) {
sendConsoleMessage(c.s()); sendConsoleMessage(c.s());
} }
/** /**
* Register a flag for use in plots * Register a flag for use in plots
*
* @param flag * @param flag
*/ */
public void registerFlag(Flag flag) { public void registerFlag(Flag flag) {
PlotMain.registerFlag(flag); PlotMain.registerFlag(flag);
} }
/** /**
* get all the currently registered flags * get all the currently registered flags
*
* @return array of Flag[] * @return array of Flag[]
*/ */
public Flag[] getRegisteredFlags() { public Flag[] getRegisteredFlags() {
return PlotMain.getFlags().toArray(new Flag[0]); 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
@ -107,6 +123,7 @@ public class PlotAPI {
/** /**
* Get a plot based on the location * Get a plot based on the location
*
* @param l * @param l
* @return plot if found, otherwise it creates a temporary plot- * @return plot if found, otherwise it creates a temporary plot-
*/ */
@ -116,6 +133,7 @@ public class PlotAPI {
/** /**
* Get a plot based on the player location * Get a plot based on the player location
*
* @param player * @param player
* @return plot if found, otherwise it creates a temporary plot * @return plot if found, otherwise it creates a temporary plot
*/ */
@ -125,23 +143,27 @@ public class PlotAPI {
/** /**
* Check whether or not a player has a plot * Check whether or not a player has a plot
*
* @param player * @param player
* @return true if player has a plot, false if not. * @return true if player has a plot, false if not.
*/ */
public boolean hasPlot(World world, Player player) { public boolean hasPlot(World world, Player player) {
return getPlots(world, player, true) != null && getPlots(world, player, true).length > 0; return (getPlots(world, player, true) != null) && (getPlots(world, player, true).length > 0);
} }
/** /**
* Get all plots for the player * Get all plots for the player
* @param plr 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 {
@ -152,34 +174,45 @@ public class PlotAPI {
} }
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,6 +241,7 @@ public class PlotAPI {
/** /**
* Get Bottom Location * Get Bottom Location
*
* @param p * @param p
* @return plot bottom location * @return plot bottom location
*/ */
@ -220,6 +252,7 @@ public class PlotAPI {
/** /**
* Get Top Location * Get Top Location
*
* @param p * @param p
* @return plot top location * @return plot top location
*/ */
@ -230,6 +263,7 @@ public class PlotAPI {
/** /**
* Check whether or not a player is in a plot * Check whether or not a player is in a plot
*
* @param player * @param player
* @return true if the player is in a plot, false if not- * @return true if the player is in a plot, false if not-
*/ */
@ -239,6 +273,7 @@ public class PlotAPI {
/** /**
* Register a subcommand * Register a subcommand
*
* @param c * @param c
*/ */
public void registerCommand(SubCommand c) { public void registerCommand(SubCommand c) {
@ -247,24 +282,16 @@ public class PlotAPI {
/** /**
* Get the plotMain class * Get the plotMain class
*
* @return PlotMain Class * @return PlotMain Class
*/ */
public PlotMain getPlotMain() { public PlotMain getPlotMain() {
return this.plotMain; return this.plotMain;
} }
/**
* Get the 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,14 +27,15 @@ 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);
} }
@Override
public boolean execute(Player plr, String... args) { 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) {
@ -43,13 +44,11 @@ public class Auto extends SubCommand {
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;
} }
@ -70,7 +69,7 @@ public class Auto extends SubCommand {
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++;
@ -85,4 +84,3 @@ public class Auto extends SubCommand {
} }
} }

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,10 +26,11 @@ 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;
@ -33,27 +41,27 @@ public class Camera extends SubCommand implements Listener {
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();
} }
} }
@ -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,12 +9,18 @@
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
@ -50,8 +56,8 @@ public class Claim extends SubCommand{
} }
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()) {

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,6 +24,7 @@ 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)) {
@ -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 {

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,25 +9,29 @@
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;
import com.intellectualcrafters.plot.Lag;
import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.PlotHelper;
import com.intellectualcrafters.plot.PlotMain;
import com.intellectualcrafters.plot.RUtils;
/** /**
* @author Citymonstret * @author Citymonstret \\SuperCharged Compiler made by Citymonstret\\
* \\SuperCharged Compiler made by Citymonstret\\
* ||#Compiler:ALPHA-1.0######################### * ||#Compiler:ALPHA-1.0#########################
* ||#ST:Java(1.7.*)\impl(bukkit)->api(s[])###### * ||#ST:Java(1.7.*)\impl(bukkit)->api(s[])######
* ||#Section:\Debug\############################ * ||#Section:\Debug\############################
* ||##Debug->Debug.properties|Debug.txt######### * ||##Debug->Debug.properties|Debug.txt#########
* ||############################################ * ||############################################ ||#Signed
* ||#Signed By:Citymonstret@IC################## * By:Citymonstret@IC##################
* \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ * \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
*/ */
public class Debug extends SubCommand { public class Debug extends SubCommand {
//private extends SubCommand^Implements {Command, Information} from >>\\S.txt6\\ // private extends SubCommand^Implements {Command, Information} from
// >>\\S.txt6\\
public Debug() { public Debug() {
super(Command.DEBUG, "Show debug information", "debug [msg]", CommandCategory.INFO); super(Command.DEBUG, "Show debug information", "debug [msg]", CommandCategory.INFO);
{ {
@ -39,8 +43,8 @@ public class Debug extends SubCommand{
@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");
@ -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,7 +97,8 @@ 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());

View File

@ -9,16 +9,17 @@
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.
@ -35,14 +36,21 @@ public class Denied extends SubCommand{
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 { } else {
if(plr.isOnline()) return true; return oplr.hasPlayedBefore();
else return plr.hasPlayedBefore(); }
} else {
if (plr.isOnline()) {
return true;
} else {
return plr.hasPlayedBefore();
}
} }
} }
@Override
public boolean execute(Player plr, String... args) { public boolean execute(Player plr, String... args) {
if (args.length < 2) { if (args.length < 2) {
PlayerFunctions.sendMessage(plr, C.DENIED_NEED_ARGUMENT); PlayerFunctions.sendMessage(plr, C.DENIED_NEED_ARGUMENT);
@ -53,7 +61,7 @@ public class Denied extends SubCommand{
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;
} }
@ -70,16 +78,17 @@ public class Denied extends SubCommand{
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);
@ -103,10 +112,11 @@ public class Denied extends SubCommand{
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,16 +9,17 @@
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 {
@ -27,19 +28,25 @@ public class Helpers extends SubCommand{
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 { } else {
if(plr.isOnline()) return true; return oplr.hasPlayedBefore();
else return plr.hasPlayedBefore(); }
} else {
if (plr.isOnline()) {
return true;
} else {
return plr.hasPlayedBefore();
}
} }
} }
@Override
public boolean execute(Player plr, String... args) { public boolean execute(Player plr, String... args) {
if (args.length < 2) { if (args.length < 2) {
PlayerFunctions.sendMessage(plr, C.HELPER_NEED_ARGUMENT); PlayerFunctions.sendMessage(plr, C.HELPER_NEED_ARGUMENT);
@ -50,7 +57,7 @@ public class Helpers extends SubCommand{
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;
} }
@ -67,10 +74,11 @@ public class Helpers extends SubCommand{
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);
@ -93,10 +101,11 @@ public class Helpers extends SubCommand{
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,12 +9,12 @@
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;
/** /**
* *
@ -26,13 +26,16 @@ public class Home extends SubCommand{
public Home() { public Home() {
super(Command.HOME, "Go to your plot", "home {id|alias}", CommandCategory.TELEPORT); super(Command.HOME, "Go to your plot", "home {id|alias}", CommandCategory.TELEPORT);
} }
private Plot isAlias(String a) { private Plot isAlias(String a) {
for (Plot p : PlotMain.getPlots()) { for (Plot p : PlotMain.getPlots()) {
if(p.settings.getAlias().length() > 0 && p.settings.getAlias().equalsIgnoreCase(a)) if ((p.settings.getAlias().length() > 0) && p.settings.getAlias().equalsIgnoreCase(a)) {
return p; return p;
} }
}
return null; return null;
} }
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(Player plr, String... args) {
@ -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;
} }

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,8 +20,11 @@ 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;
/** /**
* *
@ -62,12 +65,12 @@ public class Info extends SubCommand{
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");
@ -84,24 +87,32 @@ public class Info extends SubCommand{
} }
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)) {
return " none";
}
String c = C.PLOT_USER_LIST.s(); String c = C.PLOT_USER_LIST.s();
StringBuilder list = new StringBuilder(); StringBuilder list = new StringBuilder();
for (int x = 0; x < l.size(); x++) { for (int x = 0; x < l.size(); x++) {
if(x + 1 == l.size()) if ((x + 1) == l.size()) {
list.append(c.replace("%user%", getPlayerName(l.get(x))).replace(",", "")); list.append(c.replace("%user%", getPlayerName(l.get(x))).replace(",", ""));
else } else {
list.append(c.replace("%user%", getPlayerName(l.get(x)))); list.append(c.replace("%user%", getPlayerName(l.get(x))));
} }
}
return list.toString(); return list.toString();
} }
private String getPlayerName(UUID uuid) { private String getPlayerName(UUID uuid) {
if(uuid == null) 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); OfflinePlayer plr = Bukkit.getOfflinePlayer(uuid);
if(plr == null) return "unknown"; if (plr == null) {
return "unknown";
}
return plr.getName(); return plr.getName();
} }

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() {
@ -28,9 +28,10 @@ public class Inventory extends SubCommand {
public boolean execute(final Player plr, String... args) { public boolean execute(final Player plr, String... args) {
ArrayList<SubCommand> cmds = new ArrayList<>(); ArrayList<SubCommand> cmds = new ArrayList<>();
for (SubCommand cmd : MainCommand.subCommands) { for (SubCommand cmd : MainCommand.subCommands) {
if(cmd.permission.hasPermission(plr)) if (cmd.permission.hasPermission(plr)) {
cmds.add(cmd); cmds.add(cmd);
} }
}
int size = 9 * (int) Math.ceil(cmds.size() / 9.0); int size = 9 * (int) Math.ceil(cmds.size() / 9.0);
org.bukkit.inventory.Inventory inventory = Bukkit.createInventory(null, size, "PlotSquared Commands"); org.bukkit.inventory.Inventory inventory = Bukkit.createInventory(null, size, "PlotSquared Commands");
for (SubCommand cmd : cmds) { for (SubCommand cmd : cmds) {

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,40 +18,25 @@ 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);
@ -60,15 +44,13 @@ public class MainCommand implements CommandExecutor{
} }
@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 {
else {
PlotMain.sendConsoleSenderMessage(C.PREFIX.s() + C.HELP_HEADER.s()); PlotMain.sendConsoleSenderMessage(C.PREFIX.s() + C.HELP_HEADER.s());
PlotMain.sendConsoleSenderMessage("&6/plots reload &c-&6 reloads the plugin"); PlotMain.sendConsoleSenderMessage("&6/plots reload &c-&6 reloads the plugin");
} }
@ -78,8 +60,7 @@ public class MainCommand implements CommandExecutor{
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());
@ -107,20 +88,23 @@ public class MainCommand implements CommandExecutor{
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()); PlayerFunctions.sendMessage(player, help.toString());
return true; 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)) }
if (command.permission.hasPermission(player)) {
return command.execute(player, arguments); return command.execute(player, arguments);
else return no_permission(player); } else {
return no_permission(player);
}
} }
} }
PlayerFunctions.sendMessage(player, C.NOT_VALID_SUBCOMMAND); PlayerFunctions.sendMessage(player, C.NOT_VALID_SUBCOMMAND);
@ -136,7 +120,7 @@ public class MainCommand implements CommandExecutor{
} }
}; };
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);

View File

@ -9,13 +9,11 @@
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
@ -32,11 +30,12 @@ public class Reload extends SubCommand{
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,7 +13,6 @@ 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) {
@ -55,7 +55,7 @@ public class Schematic extends SubCommand {
int l1 = schematic.getSchematicDimension().getX(); int l1 = schematic.getSchematicDimension().getX();
int l2 = schematic.getSchematicDimension().getZ(); int l2 = schematic.getSchematicDimension().getZ();
int length = PlotMain.getWorldSettings(plr.getWorld()).PLOT_WIDTH; int length = PlotMain.getWorldSettings(plr.getWorld()).PLOT_WIDTH;
if(l1 != length || l2 != length) { if ((l1 != length) || (l2 != length)) {
sendMessage(plr, C.SCHEMATIC_INVALID, String.format("Wrong size (x: %s, z: %d) vs %d ", l1, l2, length)); sendMessage(plr, C.SCHEMATIC_INVALID, String.format("Wrong size (x: %s, z: %d) vs %d ", l1, l2, length));
break; break;
} }

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,9 +21,18 @@ 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;
/** /**
* *
@ -38,12 +45,8 @@ public class Set extends SubCommand{
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
@ -110,8 +113,9 @@ public class Set extends SubCommand{
} }
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);
@ -131,8 +135,7 @@ 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;
} }
@ -152,8 +155,11 @@ public class Set extends SubCommand{
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;
@ -166,7 +172,9 @@ public class Set extends SubCommand{
} }
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);
@ -224,14 +232,14 @@ public class Set extends SubCommand{
return true; return true;
} }
Material material = null; Material material = null;
for(Material m : plotworld.BLOCKS) { for (Material m : PlotWorld.BLOCKS) {
if (m.toString().equalsIgnoreCase(args[1])) { if (m.toString().equalsIgnoreCase(args[1])) {
material = m; material = m;
break; break;
} }
} }
if (material == null) { if (material == null) {
PlayerFunctions.sendMessage(plr, getBlockList(plotworld.BLOCKS)); PlayerFunctions.sendMessage(plr, getBlockList(PlotWorld.BLOCKS));
return true; return true;
} }
byte data = 0; byte data = 0;
@ -260,7 +268,7 @@ public class Set extends SubCommand{
} }
// //
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
ArrayList<Material> materials = (ArrayList<Material>) plotworld.BLOCKS.clone(); ArrayList<Material> materials = (ArrayList<Material>) PlotWorld.BLOCKS.clone();
materials.add(Material.AIR); materials.add(Material.AIR);
// //
String[] strings = args[1].split(","); String[] strings = args[1].split(",");
@ -315,14 +323,14 @@ public class Set extends SubCommand{
return true; return true;
} }
Material material = null; Material material = null;
for(Material m : plotworld.BLOCKS) { for (Material m : PlotWorld.BLOCKS) {
if (m.toString().equalsIgnoreCase(args[1])) { if (m.toString().equalsIgnoreCase(args[1])) {
material = m; material = m;
break; break;
} }
} }
if (material == null) { if (material == null) {
PlayerFunctions.sendMessage(plr, getBlockList(plotworld.BLOCKS)); PlayerFunctions.sendMessage(plr, getBlockList(PlotWorld.BLOCKS));
return true; return true;
} }
byte data = 0; byte data = 0;
@ -380,5 +388,4 @@ public class Set extends SubCommand{
return builder.toString().substring(1, builder.toString().length() - 1); return builder.toString().substring(1, builder.toString().length() - 1);
} }
} }

View File

@ -9,16 +9,17 @@
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 {
@ -29,8 +30,9 @@ 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)) {

View File

@ -9,12 +9,14 @@
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
* *
*/ */
@ -46,12 +48,18 @@ 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;
@ -64,10 +72,14 @@ public abstract class SubCommand {
/** /**
* *
* @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();
@ -77,29 +89,34 @@ public abstract class SubCommand {
this.usage = usage; this.usage = usage;
this.category = category; this.category = category;
} }
/** /**
* Execute. * Execute.
* @param plr executor *
* @param args arguments * @param plr
* executor
* @param args
* arguments
* @return true on success, false on failure * @return true on success, false on failure
*/ */
public abstract boolean execute(Player plr, String... args); public abstract boolean execute(Player plr, String... args);
public void executeConsole(String ... args) { this.execute(null, args); }
public void executeConsole(String... args) {
this.execute(null, args);
}
public void sendMessage(Player plr, C c, String... args) { public void sendMessage(Player plr, C c, String... args) {
PlayerFunctions.sendMessage(plr, c, args); PlayerFunctions.sendMessage(plr, c, args);
} }
public enum CommandCategory { public enum CommandCategory {
CLAIMING("Claiming"), 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
@ -36,9 +41,10 @@ public class TP extends SubCommand {
PlotId plotid; PlotId plotid;
World world = plr.getWorld(); World world = plr.getWorld();
if (args.length == 2) { if (args.length == 2) {
if (Bukkit.getWorld(args[1])!=null) if (Bukkit.getWorld(args[1]) != null) {
world = Bukkit.getWorld(args[1]); world = Bukkit.getWorld(args[1]);
} }
}
if (!PlotMain.isPlotWorld(world)) { if (!PlotMain.isPlotWorld(world)) {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD); PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD);
return false; return false;
@ -52,8 +58,7 @@ public class TP extends SubCommand {
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;
@ -61,9 +66,10 @@ public class TP extends SubCommand {
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,14 +9,17 @@
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;
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 class Visit extends SubCommand {
public Visit() { public Visit() {
@ -25,13 +28,14 @@ public class Visit extends SubCommand{
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) {
@ -56,7 +60,7 @@ public class Visit extends SubCommand{
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,18 +9,18 @@
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.C; import java.util.HashMap;
import com.intellectualcrafters.plot.PlayerFunctions; import java.util.UUID;
import com.intellectualcrafters.plot.Plot;
import com.intellectualcrafters.plot.PlotId;
import com.intellectualcrafters.plot.PlotMain;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import java.util.HashMap; import com.intellectualcrafters.plot.C;
import java.util.UUID; import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.Plot;
import com.intellectualcrafters.plot.PlotId;
import com.intellectualcrafters.plot.PlotMain;
/** /**
* *
@ -76,18 +76,19 @@ public class list extends SubCommand{
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) { private static String getName(UUID id) {
if(id == null) if (id == null) {
return "none"; return "none";
}
return Bukkit.getOfflinePlayer(id).getName(); 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) {
@ -96,7 +97,6 @@ public class list extends SubCommand{
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 {
@ -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,12 +113,12 @@ 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;
*/ */
/** /**
@ -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,19 +299,29 @@ 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)) {
@ -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

@ -39,8 +39,7 @@ this.plugin = plugin;
* @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
@ -80,8 +79,7 @@ public abstract boolean closeConnection() throws SQLException;
* @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, public abstract ResultSet querySQL(String query) throws SQLException, ClassNotFoundException;
ClassNotFoundException;
/** /**
* Executes an Update SQL Query<br> * Executes an Update SQL Query<br>
@ -96,6 +94,5 @@ ClassNotFoundException;
* @throws ClassNotFoundException * @throws ClassNotFoundException
* If the driver cannot be found; see {@link #openConnection()} * If the driver cannot be found; see {@link #openConnection()}
*/ */
public abstract int updateSQL(String query) throws SQLException, public abstract int updateSQL(String query) throws SQLException, ClassNotFoundException;
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
* *
@ -39,8 +39,7 @@ public class MySQL extends Database {
* @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;
@ -51,45 +50,41 @@ public class MySQL extends Database {
} }
@Override @Override
public Connection openConnection() throws SQLException, public Connection openConnection() throws SQLException, ClassNotFoundException {
ClassNotFoundException {
if (checkConnection()) { if (checkConnection()) {
return connection; return this.connection;
} }
Class.forName("com.mysql.jdbc.Driver"); Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://" this.connection = DriverManager.getConnection("jdbc:mysql://" + this.hostname + ":" + this.port + "/" + this.database, this.user, this.password);
+ this.hostname + ":" + this.port + "/" + this.database, return this.connection;
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);
@ -97,13 +92,12 @@ public class MySQL 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

@ -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,7 +32,7 @@ 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()) {
@ -76,27 +77,14 @@ public class PlotMeConverter {
} }
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,6 +21,7 @@ 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
* *
@ -28,59 +34,54 @@ public class SQLite extends Database {
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,12 +9,13 @@
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.
*/ */
@ -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,6 +13,7 @@ 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;

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,13 +9,13 @@
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();
@ -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,14 +9,11 @@
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.
@ -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,14 +9,13 @@
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.
*/ */
@ -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,14 +9,13 @@
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.
*/ */
@ -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,24 +50,37 @@ 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) {
return ChatColor.translateAlternateColorCodes('&', string);
}
private String getName(UUID uuid) { private String getName(UUID uuid) {
OfflinePlayer player = Bukkit.getOfflinePlayer(uuid); OfflinePlayer player = Bukkit.getOfflinePlayer(uuid);
if (player != null) { if (player != null) {
@ -71,8 +97,13 @@ public class PlayerEvents implements Listener {
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());
}
private boolean isPlotWorld(World w) {
return PlotMain.isPlotWorld(w);
}
public static boolean isInPlot(Location loc) { public static boolean isInPlot(Location loc) {
return getCurrentPlot(loc) != null; return getCurrentPlot(loc) != null;
@ -92,32 +123,36 @@ public class PlayerEvents implements Listener {
@EventHandler @EventHandler
public void onJoin(PlayerJoinEvent event) { public void onJoin(PlayerJoinEvent event) {
if (!event.getPlayer().hasPlayedBefore()) if (!event.getPlayer().hasPlayedBefore()) {
event.getPlayer().saveData(); 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()) {
@ -143,11 +178,13 @@ public class PlayerEvents implements Listener {
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()) }
if (plot.settings.getChangeTime()) {
PlayerFunctions.togglePlotTime(player, plot); 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());
{ {
@ -164,13 +201,16 @@ public class PlayerEvents implements Listener {
@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; return;
}
PlotWorld plotworld = PlotMain.getWorldSettings(world); PlotWorld plotworld = PlotMain.getWorldSettings(world);
if (!plotworld.PLOT_CHAT) if (!plotworld.PLOT_CHAT) {
return; return;
if (getCurrentPlot(event.getPlayer().getLocation()) == null) }
if (getCurrentPlot(event.getPlayer().getLocation()) == null) {
return; return;
}
String message = event.getMessage(); String message = event.getMessage();
String format = C.PLOT_CHAT_FORMAT.s(); String format = C.PLOT_CHAT_FORMAT.s();
String sender = event.getPlayer().getDisplayName(); String sender = event.getPlayer().getDisplayName();
@ -179,16 +219,13 @@ public class PlayerEvents implements Listener {
Set<Player> recipients = event.getRecipients(); Set<Player> recipients = event.getRecipients();
recipients.clear(); recipients.clear();
for (Player p : Bukkit.getOnlinePlayers()) { for (Player p : Bukkit.getOnlinePlayers()) {
if (p.getLocation() if (p.getLocation().distanceSquared(event.getPlayer().getLocation()) <= Math.pow(plotworld.PLOT_WIDTH, 2d)) {
.distanceSquared(event.getPlayer().getLocation()) <= Math
.pow((double) plotworld.PLOT_WIDTH, 2d)) {
if (getCurrentPlot(p.getLocation()) == plot) { if (getCurrentPlot(p.getLocation()) == plot) {
recipients.add(p); recipients.add(p);
} }
} }
} }
format = format.replaceAll("%plot_id%", id.x+";"+id.y) format = format.replaceAll("%plot_id%", id.x + ";" + id.y).replaceAll("%sender%", sender).replaceAll("%msg%", message);
.replaceAll("%sender%", sender).replaceAll("%msg%", message);
format = ChatColor.translateAlternateColorCodes('&', format); format = ChatColor.translateAlternateColorCodes('&', format);
event.setFormat(format); event.setFormat(format);
} }
@ -196,18 +233,19 @@ public class PlayerEvents implements Listener {
@EventHandler(priority = EventPriority.HIGH) @EventHandler(priority = EventPriority.HIGH)
public void BlockDestroy(BlockBreakEvent 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")) { if (event.getPlayer().hasPermission("plots.admin")) {
return; return;
} }
if (isInPlot(event.getBlock().getLocation())) { if (isInPlot(event.getBlock().getLocation())) {
Plot plot = getCurrentPlot(event.getBlock().getLocation()); Plot plot = getCurrentPlot(event.getBlock().getLocation());
if (!plot.hasRights(event.getPlayer())) if (!plot.hasRights(event.getPlayer())) {
event.setCancelled(true); event.setCancelled(true);
} }
if (PlayerFunctions.getPlot(event.getBlock().getLocation()).equals( }
"road")) { if (PlayerFunctions.getPlot(event.getBlock().getLocation()).equals("road")) {
event.setCancelled(true); event.setCancelled(true);
} }
} }
@ -215,18 +253,19 @@ public class PlayerEvents implements Listener {
@EventHandler(priority = EventPriority.HIGH) @EventHandler(priority = EventPriority.HIGH)
public void BlockCreate(BlockPlaceEvent event) { public void BlockCreate(BlockPlaceEvent 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")) { if (event.getPlayer().hasPermission("plots.admin")) {
return; return;
} }
if (isInPlot(event.getBlock().getLocation())) { if (isInPlot(event.getBlock().getLocation())) {
Plot plot = getCurrentPlot(event.getBlockPlaced().getLocation()); Plot plot = getCurrentPlot(event.getBlockPlaced().getLocation());
if (!plot.hasRights(event.getPlayer())) if (!plot.hasRights(event.getPlayer())) {
event.setCancelled(true); event.setCancelled(true);
} }
if (PlayerFunctions.getPlot(event.getBlockPlaced().getLocation()).equals( }
"road")) { if (PlayerFunctions.getPlot(event.getBlockPlaced().getLocation()).equals("road")) {
event.setCancelled(true); event.setCancelled(true);
} }
} }
@ -234,8 +273,9 @@ public class PlayerEvents implements Listener {
@EventHandler @EventHandler
public void onBigBoom(EntityExplodeEvent event) { public void onBigBoom(EntityExplodeEvent event) {
World world = event.getLocation().getWorld(); World world = event.getLocation().getWorld();
if (!isPlotWorld(world)) if (!isPlotWorld(world)) {
return; return;
}
event.setCancelled(true); event.setCancelled(true);
} }
@ -243,8 +283,9 @@ public class PlayerEvents implements Listener {
public void onPeskyMobsChangeTheWorldLikeWTFEvent( // LOL! public void onPeskyMobsChangeTheWorldLikeWTFEvent( // LOL!
EntityChangeBlockEvent event) { EntityChangeBlockEvent event) {
World world = event.getBlock().getWorld(); World world = event.getBlock().getWorld();
if (!isPlotWorld(world)) if (!isPlotWorld(world)) {
return; return;
}
Entity e = event.getEntity(); Entity e = event.getEntity();
if (!(e instanceof Player)) { if (!(e instanceof Player)) {
if (!(e instanceof org.bukkit.entity.FallingBlock)) { if (!(e instanceof org.bukkit.entity.FallingBlock)) {
@ -275,74 +316,79 @@ public class PlayerEvents implements Listener {
@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))) }
if ((!(event.getEntity() instanceof Player))) {
event.setCancelled(true); 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();
{ {
@ -362,7 +408,9 @@ public class PlayerEvents implements Listener {
} }
} }
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))) {
@ -389,11 +437,12 @@ 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);
} }
} }
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onStructureGrow(final StructureGrowEvent e) { public void onStructureGrow(final StructureGrowEvent e) {
@ -412,52 +461,42 @@ 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; return;
}
World world = event.getPlayer().getWorld(); World world = event.getPlayer().getWorld();
if (!isPlotWorld(world)) if (!isPlotWorld(world)) {
return; return;
}
if (event.getPlayer().hasPermission("plots.admin")) { if (event.getPlayer().hasPermission("plots.admin")) {
return; return;
} }
if (isInPlot(event.getClickedBlock().getLocation())) { if (isInPlot(event.getClickedBlock().getLocation())) {
Plot plot = getCurrentPlot(event.getClickedBlock().getLocation()); Plot plot = getCurrentPlot(event.getClickedBlock().getLocation());
if (new ArrayList<>(Arrays.asList(new Material[]{ 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.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
})).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) {
@ -485,11 +524,11 @@ public class PlayerEvents implements Listener {
} }
} }
} }
} } 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) {
@ -501,8 +540,7 @@ public class PlayerEvents implements Listener {
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);
} }
} }
@ -533,9 +571,10 @@ 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) {
@ -559,7 +598,6 @@ 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();

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,7 +8,19 @@ 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;
/** /**
* *
@ -27,24 +35,27 @@ public class WorldEditListener implements Listener{
@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")) {
return;
}
Location f = e.getFrom(); Location f = e.getFrom();
Location t = e.getTo(); 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());
@ -55,73 +66,86 @@ public class WorldEditListener implements Listener{
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPlayerJoin(final PlayerJoinEvent e) { public void onPlayerJoin(final PlayerJoinEvent e) {
if(e.getPlayer().hasPermission("plots.worldedit.bypass")) return; if (e.getPlayer().hasPermission("plots.worldedit.bypass")) {
return;
}
Player p = e.getPlayer(); Player p = e.getPlayer();
if(isPlotWorld(p.getLocation())) if (isPlotWorld(p.getLocation())) {
PWE.setMask(p, p.getLocation()); PWE.setMask(p, p.getLocation());
else } else {
PWE.removeMask(p); PWE.removeMask(p);
} }
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onTeleport(final PlayerTeleportEvent e) { public void onTeleport(final PlayerTeleportEvent e) {
if(e.getPlayer().hasPermission("plots.worldedit.bypass")) return; if (e.getPlayer().hasPermission("plots.worldedit.bypass")) {
return;
}
Player p = e.getPlayer(); Player p = e.getPlayer();
Location f = e.getFrom(), t = e.getTo(); Location f = e.getFrom(), t = e.getTo();
if(t == null) if (t == null) {
PWE.removeMask(p); PWE.removeMask(p);
else { } else {
if(f != null && isPlotWorld(f) && !isPlotWorld(t)) if ((f != null) && isPlotWorld(f) && !isPlotWorld(t)) {
PWE.removeMask(p); PWE.removeMask(p);
else if(isPlotWorld(t)) } else if (isPlotWorld(t)) {
PWE.setMask(p, p.getLocation()); PWE.setMask(p, p.getLocation());
} }
} }
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPortal(PlayerPortalEvent e) { public void onPortal(PlayerPortalEvent e) {
if(e.getPlayer().hasPermission("plots.worldedit.bypass")) return; if (e.getPlayer().hasPermission("plots.worldedit.bypass")) {
return;
}
Player p = e.getPlayer(); Player p = e.getPlayer();
Location f = e.getFrom(), t = e.getTo(); Location f = e.getFrom(), t = e.getTo();
if(t == null) if (t == null) {
PWE.removeMask(p); PWE.removeMask(p);
else { } else {
if(f != null && isPlotWorld(f) && !isPlotWorld(t)) if ((f != null) && isPlotWorld(f) && !isPlotWorld(t)) {
PWE.removeMask(p); PWE.removeMask(p);
else if(isPlotWorld(t)) } else if (isPlotWorld(t)) {
PWE.setMask(p, p.getLocation()); PWE.setMask(p, p.getLocation());
} }
} }
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPlayerCommand(PlayerCommandPreprocessEvent e) { public void onPlayerCommand(PlayerCommandPreprocessEvent e) {
if(e.getPlayer().hasPermission("plots.worldedit.bypass")) return; if (e.getPlayer().hasPermission("plots.worldedit.bypass")) {
return;
}
Player p = e.getPlayer(); Player p = e.getPlayer();
if (isPlotWorld(p.getLocation())) { if (isPlotWorld(p.getLocation())) {
String msg = e.getMessage().toLowerCase(); String msg = e.getMessage().toLowerCase();
if(msg.startsWith("//gmask") || msg.startsWith("/gmask") || msg.startsWith("/worldedit:gmask") || msg.startsWith("/worldedit:/gmask")) if (msg.startsWith("//gmask") || msg.startsWith("/gmask") || msg.startsWith("/worldedit:gmask") || msg.startsWith("/worldedit:/gmask")) {
e.setCancelled(true); e.setCancelled(true);
else if(msg.startsWith("/up") || msg.startsWith("//up") || msg.startsWith("/worldedit:up") || msg.startsWith("/worldedit:/up")) { } else if (msg.startsWith("/up") || msg.startsWith("//up") || msg.startsWith("/worldedit:up") || msg.startsWith("/worldedit:/up")) {
Plot plot = PlayerFunctions.getCurrentPlot(p); Plot plot = PlayerFunctions.getCurrentPlot(p);
if(p == null || !plot.hasRights(p)) if ((p == null) || !plot.hasRights(p)) {
e.setCancelled(true); e.setCancelled(true);
} }
} }
} }
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onInteract(PlayerInteractEvent e) { public void onInteract(PlayerInteractEvent e) {
Player p = e.getPlayer(); Player p = e.getPlayer();
if (!p.hasPermission("plots.admin") && isPlotWorld(p.getLocation())) { 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) { 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(); Block b = e.getClickedBlock();
Plot plot = PlotHelper.getCurrentPlot(b.getLocation()); Plot plot = PlotHelper.getCurrentPlot(b.getLocation());
if(plot != null && plot.hasRights(p)) if ((plot != null) && plot.hasRights(p)) {
PWE.setMask(p, b.getLocation()); PWE.setMask(p, b.getLocation());
else } else {
e.setCancelled(true); 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)) {
continue;
}
HttpURLConnection connection = (HttpURLConnection) new URL(PROFILE_URL + uuid.toString().replace("-", "")).openConnection(); HttpURLConnection connection = (HttpURLConnection) new URL(PROFILE_URL + uuid.toString().replace("-", "")).openConnection();
JSONObject response = (JSONObject) jsonParser.parse(new InputStreamReader(connection.getInputStream())); 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);
} }
} }

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.
@ -26,36 +23,27 @@ public class IndexHandler implements Container {
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;
Path path;
int page;
String coverage; 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";
@ -67,7 +55,7 @@ public class IndexHandler implements Container {
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();

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.
@ -33,17 +32,17 @@ public class PlotWeb {
} }
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 FileType fileType;
private File folder;
private BufferedReader reader; 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;
this.fileType = fileType;
this.folder = folder;
if (fileType == FileType.CSS) { if (fileType == FileType.CSS) {
file = new File(folder.toPath().toString() + File.separator + "web" + File.separator + "css" + File.separator + filePath + "." + fileType.toString()); this.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;
} }