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="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/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/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-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/bukkit-1.7.9-R0.3.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@ -10,10 +10,12 @@ public class AbstractFlag {
private final String key;
public AbstractFlag(String key) {
if (!StringUtils.isAlpha(key))
if (!StringUtils.isAlpha(key)) {
throw new IllegalArgumentException("Flag must be alphabetic characters");
if (key.length()>16)
}
if (key.length() > 16) {
throw new IllegalArgumentException("Key must be <= 16 characters");
}
this.key = key.toLowerCase();
}

View File

@ -13,232 +13,159 @@ import org.bukkit.ChatColor;
/**
* Captions class.
*
* @author Citymonstret
*
*
*/
public enum C {
/*
Schematic Stuff
* Schematic Stuff
*/
SCHEMATIC_MISSING_ARG("&cYou need to specify an argument. Possible values: &6test {name}"),
SCHEMATIC_INVALID("&cThat is not a valid schematic. Reason: &c%s"),
SCHEMATIC_VALID("&cThat's a valid schematic"),
SCHEMATIC_PASTE_FAILED("&cFailed to paste schematic"),
SCHEMATIC_PASTE_SUCCESS("&cSchematic pasted successfully"),
SCHEMATIC_MISSING_ARG("&cYou need to specify an argument. Possible values: &6test {name}"), SCHEMATIC_INVALID("&cThat is not a valid schematic. Reason: &c%s"), SCHEMATIC_VALID("&cThat's a valid schematic"), SCHEMATIC_PASTE_FAILED("&cFailed to paste schematic"), SCHEMATIC_PASTE_SUCCESS("&cSchematic pasted successfully"),
/*
Title Stuff
* Title Stuff
*/
TITLE_ENTERED_PLOT("You entered plot %s"),
TITLE_ENTERED_PLOT_COLOR("GOLD"),
TITLE_ENTERED_PLOT_SUB("Owned by %s"),
TITLE_ENTERED_PLOT_SUB_COLOR("RED"),
TITLE_LEFT_PLOT("You entered plot %s"),
TITLE_LEFT_PLOT_COLOR("GOLD"),
TITLE_LEFT_PLOT_SUB("Owned by %s"),
TITLE_LEFT_PLOT_SUB_COLOR("RED"),
TITLE_ENTERED_PLOT("You entered plot %s"), TITLE_ENTERED_PLOT_COLOR("GOLD"), TITLE_ENTERED_PLOT_SUB("Owned by %s"), TITLE_ENTERED_PLOT_SUB_COLOR("RED"), TITLE_LEFT_PLOT("You entered plot %s"), TITLE_LEFT_PLOT_COLOR("GOLD"), TITLE_LEFT_PLOT_SUB("Owned by %s"), TITLE_LEFT_PLOT_SUB_COLOR("RED"),
/*
Core Stuff
* Core Stuff
*/
PREFIX("&c[&6&lPlot&c] "),
ENABLED("&6Plots are now enabled"),
EXAMPLE_MESSAGE("&cThis is an example message &k!!!"),
PREFIX("&c[&6&lPlot&c] "), ENABLED("&6Plots are now enabled"), EXAMPLE_MESSAGE("&cThis is an example message &k!!!"),
/*
Reload
* Reload
*/
RELOADED_CONFIGS("&6The translation files has been reloaded"),
RELOAD_FAILED("&cFailed to reload the translations file"),
/*
BarAPI
RELOADED_CONFIGS("&6The translation files has been reloaded"), RELOAD_FAILED("&cFailed to reload the translations file"),
/*
* BarAPI
*/
BOSSBAR_CLEARING("&cClearing plot: &6%id%"),
/*
Alias
* Alias
*/
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"),
ALIAS_SET_TO("&cPlot alias set to &6%alias%"), MISSING_ALIAS("&cYou need to specify the alias"), ALIAS_IS_TAKEN("&cThat alias is already taken"),
/*
Position
* Position
*/
MISSING_POSITION("&cYou need to specify a position. Possible values: &6default&c, &6center"),
POSITION_SET("&cPlot home position set"),
INVALID_POSITION("&cThat is not a valid position value"),
MISSING_POSITION("&cYou need to specify a position. Possible values: &6default&c, &6center"), POSITION_SET("&cPlot home position set"), INVALID_POSITION("&cThat is not a valid position value"),
/*
Time
* Time
*/
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_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_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"),
/*
Commands
* Commands
*/
NOT_VALID_SUBCOMMAND("&cThat is not a valid subcommand."),
NO_COMMANDS("&cI'm sorry, but you're not permitted to use any subcommands."),
SUBCOMMAND_SET_OPTIONS_HEADER("&cPossible Values: "),
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 {plot}
* No {plot}
*/
NOT_IN_PLOT("&cYou're not in a plot"),
NOT_IN_PLOT_WORLD("&cYou're not in a plot world"),
NOT_VALID_WORLD("&cThat is not a valid world (case sensitive)"),
NOT_VALID_PLOT_WORLD("&cThat is not a valid plot world (case sensitive)"),
NO_PLOTS("&cYou don't have any plots"),
NOT_IN_PLOT("&cYou're not in a plot"), NOT_IN_PLOT_WORLD("&cYou're not in a plot world"), NOT_VALID_WORLD("&cThat is not a valid world (case sensitive)"), NOT_VALID_PLOT_WORLD("&cThat is not a valid plot world (case sensitive)"), NO_PLOTS("&cYou don't have any plots"),
/*
Block List
* Block List
*/
NOT_VALID_BLOCK_LIST_HEADER("&cThat's not a valid block. Valid blocks are:\\n"),
BLOCK_LIST_ITEM(" &6%mat%&c,"),
NOT_VALID_BLOCK_LIST_HEADER("&cThat's not a valid block. Valid blocks are:\\n"), BLOCK_LIST_ITEM(" &6%mat%&c,"),
/*
Biome
* Biome
*/
NEED_BIOME("&cYou've got to specify a biome"),
BIOME_SET_TO("&cPlot biome set to &c"),
NEED_BIOME("&cYou've got to specify a biome"), BIOME_SET_TO("&cPlot biome set to &c"),
/*
Teleport / Entry
* Teleport / Entry
*/
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"),
DEBUG_SECTION("&c>> &6&l%val%"),
DEBUG_LINE("&c>> &6%var%&c:&6 %val%\\n"),
DEUBG_HEADER("&6Debug Information\\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_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_DATA("&cThat's not a valid data id."), NOT_VALID_BLOCK("&cThat's not a valid block."), NOT_VALID_NUMBER("&cThat's not a valid number"), NOT_VALID_PLOT_ID("&cThat's not a valid plot id."), NOT_YOUR_PLOT("&cThat is not your plot."), NO_SUCH_PLOT("&cThere is no such plot"), PLAYER_HAS_NOT_BEEN_ON("&cThat player hasn't been in the plotworld"), FOUND_NO_PLOTS("&cFound no plots with your search query"),
/*
Camera
* Camera
*/
CAMERA_STARTED("&cYou have entered camera mode for plot &6%s"),
CAMERA_STOPPED("&cYou are no longer in camera mode"),
CAMERA_STARTED("&cYou have entered camera mode for plot &6%s"), 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_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_PLOT_NUMBER("&cYou've got to specify a plot number or alias"), NEED_BLOCK("&cYou've got to specify a block"), NEED_PLOT_ID("&cYou've got to specify a plot id."), NEED_USER("&cYou need to specify a username"),
/*
Info
* Info
*/
PLOT_INFO_UNCLAIMED("&cPlot &6%s&c is not yet claimed"),
PLOT_INFO("plot ID: &6%id%&c, plot Alias: &6%alias%&c, plot Owner: &6%owner%&c, plot Biome: &6%biome%&c, plot Time: &6%time%&c, plot Weather: &6%weather%&c, plot Helpers:&6%helpers%&c, plot Denied:&6%denied%&c, plot flags: &6%flags%"),
PLOT_USER_LIST(" &6%user%&c,"),
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,"),
/*
Generating
* Generating
*/
GENERATING_FLOOR("&6Started generating floor from your settings. It will take %time%"),
GENERATING_WALL("&6Started generating wall from your settings"),
GENERATING_WALL_FILLING("&cStarted generating wall filling from your settings."),
GENERATING_FLOOR("&6Started generating floor from your settings. It will take %time%"), GENERATING_WALL("&6Started generating wall from your settings"), GENERATING_WALL_FILLING("&cStarted generating wall filling from your settings."),
/*
Clearing
* Clearing
*/
CLEARING_PLOT("&cClearing plot."),
CLEARING_DONE("&6Done, took &a%time%&6 ms!"),
CLEARING_DONE_PACKETS("&6(&a%time% &6ms for packets)"),
CLEARING_PLOT("&cClearing plot."), 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_IS_CLAIMED("&cThis plot is already claimed"),
CLAIMED("&6You successfully claimed the plot"),
PLOT_NOT_CLAIMED("&cCannot claim 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_ITEM("&c>> &6%id% &c- &6%owner%"),
PLOT_LIST_FOOTER("&c>> &6%word% a total of &c%num% &6claimed %plot%."),
PLOT_LIST_HEADER("&6List of %word% plots"), PLOT_LIST_ITEM("&c>> &6%id% &c- &6%owner%"), PLOT_LIST_FOOTER("&c>> &6%word% a total of &c%num% &6claimed %plot%."),
/*
Left
* Left
*/
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%"),
/*
Denied
* Denied
*/
DENIED_REMOVED("&cYou successfully undenied the player from this plot"),
DENIED_ADDED("&cYou successfully denied the player from this plot"),
DENIED_NEED_ARGUMENT("&cArguments are missing. &6/plot denied add {name} &cor &6/plot helpers remove {name}"),
WAS_NOT_DENIED("&cThat player was not denied on this plot"),
DENIED_REMOVED("&cYou successfully undenied the player from this plot"), DENIED_ADDED("&cYou successfully denied the player from this plot"), DENIED_NEED_ARGUMENT("&cArguments are missing. &6/plot denied add {name} &cor &6/plot helpers remove {name}"), WAS_NOT_DENIED("&cThat player was not denied on this plot"),
/*
Rain
* Rain
*/
NEED_ON_OFF("&cYou need to specify a value. Possible values: &6on&c, &6off"),
SETTING_UPDATED("&cYou successfully updated the setting"),
NEED_ON_OFF("&cYou need to specify a value. Possible values: &6on&c, &6off"), SETTING_UPDATED("&cYou successfully updated the setting"),
/*
* Flag
*/
NEED_KEY("&cPossible values: &6%values%"),
NOT_VALID_FLAG("&cThat is not a valid flag"),
NOT_VALID_VALUE("&cFlag values must be alphanumerical"),
FLAG_NOT_IN_PLOT("&cThe plot does not have that flag"),
FLAG_NOT_REMOVED("&cThe flag could not be removed"),
FLAG_NOT_ADDED("&cThe flag could not be added"),
FLAG_REMOVED("&6Successfully removed flag"),
FLAG_ADDED("&6Successfully added flag"),
NEED_KEY("&cPossible values: &6%values%"), NOT_VALID_FLAG("&cThat is not a valid flag"), NOT_VALID_VALUE("&cFlag values must be alphanumerical"), FLAG_NOT_IN_PLOT("&cThe plot does not have that flag"), FLAG_NOT_REMOVED("&cThe flag could not be removed"), FLAG_NOT_ADDED("&cThe flag could not be added"), FLAG_REMOVED("&6Successfully removed flag"), FLAG_ADDED("&6Successfully added flag"),
/*
Helper
* Helper
*/
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_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"),
/*
Set Owner
* Set Owner
*/
SET_OWNER("&6You successfully set the plot owner"),
/*
Signs
*/
OWNER_SIGN_LINE_1("&cID: &6%id%"),
OWNER_SIGN_LINE_2("&cOwner:"),
OWNER_SIGN_LINE_3("&6%plr%"),
OWNER_SIGN_LINE_4("&2Claimed"),
/*
Help
* Signs
*/
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"),
OWNER_SIGN_LINE_1("&cID: &6%id%"), OWNER_SIGN_LINE_2("&cOwner:"), OWNER_SIGN_LINE_3("&6%plr%"), OWNER_SIGN_LINE_4("&2Claimed"),
/*
Custom
* Help
*/
CUSTOM_STRING("-")
;
/**
* Default
*/
private String d;
/**
* Translated
*/
private String s;
HELP_CATEGORY("&6Current Category&c: &l%category%"), HELP_INFO("&6You need to specify a help category"), HELP_INFO_ITEM("&6/plots help %category% &c- &6%category_desc%"), HELP_PAGE("&c>> &6%usage% &c[&6%alias%&c] &c- &6%desc%"), HELP_HEADER("&6Help for Plots"),
/*
* Custom
*/
CUSTOM_STRING("-");
/**
* Default
*/
private String d;
/**
* Translated
*/
private String s;
/**
* Constructor for custom strings.
@ -246,48 +173,52 @@ public enum C {
@SuppressWarnings("unused")
C() {
/*
use setCustomString();
* use setCustomString();
*/
}
/**
* Constructor
* @param d default
*/
C(String d) {
this.d = d;
this.s = PlotMain.translations.getString(this.toString());
if (this.s==null) {
this.s = "";
}
}
/**
* Get the default string
* @return default
*/
@SuppressWarnings("unused")
public String d() {
return this.d;
}
/**
* Get translated if exists
* @return translated if exists else default
*/
public String s() {
if(this.s.length() < 1)
return this.d.replace("\\n", "\n");
return this.s.replace("\\n", "\n");
}
/**
* Constructor
*
* @param d
* default
*/
C(String d) {
this.d = d;
this.s = PlotMain.translations.getString(this.toString());
if (this.s == null) {
this.s = "";
}
}
/**
*
* Get the default string
*
* @return default
*/
@SuppressWarnings("unused")
public String d() {
return this.d;
}
/**
* Get translated if exists
*
* @return translated if exists else default
*/
public String s() {
if (this.s.length() < 1) {
return this.d.replace("\\n", "\n");
}
return this.s.replace("\\n", "\n");
}
/**
*
* @return translated and color decoded
*/
public String translated() {
return ChatColor.translateAlternateColorCodes('&', this.s());
return ChatColor.translateAlternateColorCodes('&', this.s());
}
}
}

View File

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

View File

@ -6,41 +6,55 @@ import org.bukkit.ChatColor;
public class Flag {
private AbstractFlag key;
private 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");
if (value.length()>48)
}
if (value.length() > 48) {
throw new IllegalArgumentException("Value must be <= 48 characters");
}
this.key = key;
this.value = value;
}
public AbstractFlag getAbstractFlag() { return this.key; }
public AbstractFlag getAbstractFlag() {
return this.key;
}
public String getKey() {
return this.key.getKey();
}
public String getValue() {
return this.value;
}
@Override
public String toString() {
if (this.value.equals("")) {
return this.key.getKey();
}
return this.key+":"+this.value;
return this.key + ":" + this.value;
}
@Override
public boolean equals(Object obj){
if (this == obj)
public boolean equals(Object obj) {
if (this == obj) {
return true;
if (obj == null)
}
if (obj == null) {
return false;
if (getClass() != obj.getClass())
}
if (getClass() != obj.getClass()) {
return false;
}
Flag other = (Flag) obj;
return (this.key.getKey().equals(other.key.getKey()) && this.value.equals(other.value));
}
@Override
public int hashCode() {
return key.getKey().hashCode();
return this.key.getKey().hashCode();
}
}

View File

@ -9,7 +9,7 @@ public class FlagManager {
private static ArrayList<AbstractFlag> flags;
public static boolean addFlag(AbstractFlag flag) {
if(getFlag(flag.getKey()) != null) {
if (getFlag(flag.getKey()) != null) {
return false;
}
return flags.add(flag);
@ -20,8 +20,8 @@ public class FlagManager {
}
public static AbstractFlag getFlag(String string) {
for(AbstractFlag flag : flags) {
if(flag.getKey().equalsIgnoreCase(string)) {
for (AbstractFlag flag : flags) {
if (flag.getKey().equalsIgnoreCase(string)) {
return flag;
}
}
@ -29,7 +29,7 @@ public class FlagManager {
}
public static AbstractFlag getFlag(String string, boolean create) {
if(getFlag(string) == null && create) {
if ((getFlag(string) == null) && create) {
AbstractFlag flag = new AbstractFlag(string);
return flag;
}
@ -39,7 +39,9 @@ public class FlagManager {
public static List<AbstractFlag> getPlotFlags(Plot plot) {
Set<Flag> plotFlags = plot.settings.getFlags();
List<AbstractFlag> flags = new ArrayList<>();
for(Flag flag : plotFlags) flags.add(flag.getAbstractFlag());
for (Flag flag : plotFlags) {
flags.add(flag.getAbstractFlag());
}
return flags;
}
}

View File

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

View File

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

View File

@ -9,62 +9,67 @@
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.Date;
/**
* Logging of errors and debug messages.
*
* @author Citymonstret
*
*
*/
public class Logger {
private static ArrayList<String> entries;
private static File log;
public static void setup(File file) {
log = file;
private static ArrayList<String> entries;
private static File log;
public static void setup(File file) {
log = file;
entries = new ArrayList<>();
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while((line = reader.readLine()) != null) {
while ((line = reader.readLine()) != null) {
entries.add(line);
}
reader.close();
} catch(IOException e) {
} catch (IOException e) {
PlotMain.sendConsoleSenderMessage(C.PREFIX.s() + "File setup error Logger#setup");
}
}
public enum LogLevel {
GENERAL("General"),
WARNING("Warning"),
DANGER("Danger");
private String name;
LogLevel(String name) {
this.name = name;
}
@Override
public String toString() {
return this.name;
}
}
public static void write() throws IOException {
FileWriter writer = new FileWriter(log);
for(String string : entries) {
writer.write(string + System.lineSeparator());
}
writer.close();
}
public static void add(LogLevel level, String string) {
append("[" + level.toString() + "] " + string);
}
private static void append(String string) {
entries.add("[" + new Date().toString() + "]" + string);
}
}
public enum LogLevel {
GENERAL("General"), WARNING("Warning"), DANGER("Danger");
private String name;
LogLevel(String name) {
this.name = name;
}
@Override
public String toString() {
return this.name;
}
}
public static void write() throws IOException {
FileWriter writer = new FileWriter(log);
for (String string : entries) {
writer.write(string + System.lineSeparator());
}
writer.close();
}
public static void add(LogLevel level, String string) {
append("[" + level.toString() + "] " + string);
}
private static void append(String string) {
entries.add("[" + new Date().toString() + "]" + string);
}
}

View File

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

View File

@ -9,180 +9,198 @@
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.entity.Player;
import java.util.*;
/**
* Functions involving players, plots and locations.
* @author Citymonstret
*
* Functions involving players, plots and locations.
*
* @author Citymonstret
*
*/
@SuppressWarnings("javadoc")
public class PlayerFunctions {
/**
*
* @param player player
*
* @param player
* player
* @return
*/
public static boolean isInPlot(Player player) {
return getCurrentPlot(player) != null;
}
public static boolean isInPlot(Player player) {
return getCurrentPlot(player) != null;
}
/**
*
* @param plot plot
*
* @param plot
* plot
* @return
*/
public static boolean hasExpired(Plot plot) {
OfflinePlayer player = Bukkit.getOfflinePlayer(plot.owner);
long lp = player.getLastPlayed();
long cu = System.currentTimeMillis();
return (lp - cu) > 30l;
}
public static boolean hasExpired(Plot plot) {
OfflinePlayer player = Bukkit.getOfflinePlayer(plot.owner);
long lp = player.getLastPlayed();
long cu = System.currentTimeMillis();
return (lp - cu) > 30l;
}
/**
*
*
* @param loc
* @return
*/
public static PlotId getPlot(Location loc) {
int valx = loc.getBlockX();
int valz = loc.getBlockZ();
PlotWorld plotworld = PlotMain.getWorldSettings(loc.getWorld());
int size = plotworld.PLOT_WIDTH + plotworld.ROAD_WIDTH;
int pathsize = plotworld.ROAD_WIDTH;
boolean road = false;
double n3;
int mod2 = 0;
int mod1 = 1;
int x = (int) Math.ceil((double) valx / size);
int z = (int) Math.ceil((double) valz / size);
if(pathsize % 2 == 1) {
n3 = Math.ceil(((double) pathsize) / 2);
mod2 = -1;
} else {
n3 = Math.floor(((double) pathsize) / 2);
}
for(double i = n3; i >= 0; i--) {
if((valx - i + mod1) % size == 0 || (valx + i + mod2) % size == 0) {
road = true;
x = (int) Math.ceil((valx - n3) / size);
}
if((valz - i + mod1) % size == 0 || (valz + i + mod2) % size == 0) {
road = true;
z = (int) Math.ceil((valz - n3) / size);
}
}
if(road) {
return null;
} else {
return new PlotId(x,z);
}
}
public static PlotId getPlot(Location loc) {
int valx = loc.getBlockX();
int valz = loc.getBlockZ();
PlotWorld plotworld = PlotMain.getWorldSettings(loc.getWorld());
int size = plotworld.PLOT_WIDTH + plotworld.ROAD_WIDTH;
int pathsize = plotworld.ROAD_WIDTH;
boolean road = false;
double n3;
int mod2 = 0;
int mod1 = 1;
int x = (int) Math.ceil((double) valx / size);
int z = (int) Math.ceil((double) valz / size);
if ((pathsize % 2) == 1) {
n3 = Math.ceil(((double) pathsize) / 2);
mod2 = -1;
} else {
n3 = Math.floor(((double) pathsize) / 2);
}
for (double i = n3; i >= 0; i--) {
if (((((valx - i) + mod1) % size) == 0) || (((valx + i + mod2) % size) == 0)) {
road = true;
x = (int) Math.ceil((valx - n3) / size);
}
if (((((valz - i) + mod1) % size) == 0) || (((valz + i + mod2) % size) == 0)) {
road = true;
z = (int) Math.ceil((valz - n3) / size);
}
}
if (road) {
return null;
} else {
return new PlotId(x, z);
}
}
/**
*
*
* @param player
* @param plot
*/
public static void togglePlotWeather(Player player, Plot plot) {
player.setPlayerWeather(plot.settings.getRain() ? WeatherType.DOWNFALL : WeatherType.CLEAR);
}
public static void togglePlotWeather(Player player, Plot plot) {
player.setPlayerWeather(plot.settings.getRain() ? WeatherType.DOWNFALL : WeatherType.CLEAR);
}
/**
*
*
* @param player
* @param plot
*/
public static void togglePlotTime(Player player, Plot plot) {
player.setPlayerTime(plot.settings.getTime(), false);
}
public static void togglePlotTime(Player player, Plot plot) {
player.setPlayerTime(plot.settings.getTime(), false);
}
/**
*
*
* @param player
* @return
*/
@SuppressWarnings("deprecation")
public static Plot getCurrentPlot(Player player) {
if (!PlotMain.isPlotWorld(player.getWorld()))
public static Plot getCurrentPlot(Player player) {
if (!PlotMain.isPlotWorld(player.getWorld())) {
return null;
PlotId id = getPlot(player.getLocation());
World world = player.getWorld();
if(id==null) {
return null;
}
HashMap<PlotId, Plot> plots = PlotMain.getPlots(world);
if (plots!=null) {
if(plots.containsKey(id)) {
return plots.get(id);
}
}
return new Plot(id, null, Biome.FOREST, new ArrayList<UUID>(), new ArrayList<UUID>(), world.getName());
}
PlotId id = getPlot(player.getLocation());
World world = player.getWorld();
if (id == null) {
return null;
}
HashMap<PlotId, Plot> plots = PlotMain.getPlots(world);
}
if (plots != null) {
if (plots.containsKey(id)) {
return plots.get(id);
}
}
return new Plot(id, null, Biome.FOREST, new ArrayList<UUID>(), new ArrayList<UUID>(), world.getName());
}
/**
* @deprecated
* @param id
* @param plot
*/
public static void set(Integer[] id, Plot plot) {
PlotMain.updatePlot(plot);
}
@Deprecated
public static void set(Integer[] id, Plot plot) {
PlotMain.updatePlot(plot);
}
/**
*
*
* @param plr
* @return
*/
// public static Set<Plot> getPlayerPlots(Player plr) {
// return PlotMain.getPlots(plr);
// }
//
public static Set<Plot> getPlayerPlots(World world, Player plr) {
// public static Set<Plot> getPlayerPlots(Player plr) {
// return PlotMain.getPlots(plr);
// }
//
public static Set<Plot> getPlayerPlots(World world, Player plr) {
Set<Plot> p = PlotMain.getPlots(world, plr);
if (p==null)
if (p == null) {
return new HashSet<Plot>();
}
return p;
}
/**
*
*
* @param plr
* @return
*/
// public static int getPlayerPlotCount(Player plr) {
// return getPlayerPlots(plr).size();
// }
//
public static int getPlayerPlotCount(World world, Player plr) {
// public static int getPlayerPlotCount(Player plr) {
// return getPlayerPlots(plr).size();
// }
//
public static int getPlayerPlotCount(World world, Player plr) {
return getPlayerPlots(world, plr).size();
}
/**
*
*
* @param p
* @return
*/
@SuppressWarnings("SuspiciousNameCombination")
public static int getAllowedPlots(Player p) {
if(p.hasPermission("plots.admin")) return Integer.MAX_VALUE;
if (p.hasPermission("plots.admin")) {
return Integer.MAX_VALUE;
}
int y = 0;
for(int x = 1; x <= 100; x++) {
if(p.hasPermission("plots.plot." + x)) y = x;
else {
for (int x = 1; x <= 100; x++) {
if (p.hasPermission("plots.plot." + x)) {
y = x;
} else {
break;
}
}
@ -190,46 +208,59 @@ public class PlayerFunctions {
}
/**
*
*
* @return PlotMain.getPlots();
* @deprecated
*/
public static Set<Plot> getPlots() {
return PlotMain.getPlots();
}
@Deprecated
public static Set<Plot> getPlots() {
return PlotMain.getPlots();
}
/**
* \\previous\\
*
* @param plr
* @param msg
* Was used to wrap the chat client length (Packets out--)
* Was used to wrap the chat client length (Packets out--)
*/
public static void sendMessageWrapped(Player plr, String msg) {
plr.sendMessage(msg);
}
public static void sendMessageWrapped(Player plr, String msg) {
plr.sendMessage(msg);
}
/**
* Send a message to the player
* @param plr Player to recieve message
* @param msg Message to send
*
* @param plr
* Player to recieve message
* @param msg
* Message to send
*/
public static void sendMessage(Player plr, String msg) {
if(msg.length() == 0 || msg.equalsIgnoreCase("")) return;
sendMessageWrapped(plr, ChatColor.translateAlternateColorCodes('&', C.PREFIX.s() + msg));
}
/**
* Send a message to the player
* @param plr Player to recieve message
* @param c Caption to send
*/
public static void sendMessage(Player plr, C c, String ... args) {
if(c.s().length() < 1) return;
String msg = c.s();
if(args != null && args.length > 0) {
for(String str : args)
msg = msg.replaceFirst("%s", str);
public static void sendMessage(Player plr, String msg) {
if ((msg.length() == 0) || msg.equalsIgnoreCase("")) {
return;
}
sendMessage(plr, msg);
}
sendMessageWrapped(plr, ChatColor.translateAlternateColorCodes('&', C.PREFIX.s() + msg));
}
/**
* Send a message to the player
*
* @param plr
* Player to recieve message
* @param c
* Caption to send
*/
public static void sendMessage(Player plr, C c, String... args) {
if (c.s().length() < 1) {
return;
}
String msg = c.s();
if ((args != null) && (args.length > 0)) {
for (String str : args) {
msg = msg.replaceFirst("%s", str);
}
}
sendMessage(plr, msg);
}
}

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

@ -1,31 +1,35 @@
package com.intellectualcrafters.plot;
import java.util.Arrays;
public class PlotId {
public int x;
public int y;
public PlotId(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object obj){
if (this == obj)
public boolean equals(Object obj) {
if (this == obj) {
return true;
if (obj == null)
}
if (obj == null) {
return false;
if (getClass() != obj.getClass())
}
if (getClass() != obj.getClass()) {
return false;
}
PlotId other = (PlotId) obj;
return (this.x==other.x && this.y==other.y);
return ((this.x == other.x) && (this.y == other.y));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
result = (prime * result) + this.x;
result = (prime * result) + this.y;
return result;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -13,26 +13,21 @@ import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.bukkit.block.Biome;
/**
* plot settings
*
* @author Citymonstret
*
*
*/
public class PlotSettings {
private String alias;
/**
* plot object
*/
@SuppressWarnings("unused")
private Plot plot;
/**
* plot biome
*/
private Biome biome;
/**
* plot biome
*/
private Biome biome;
/**
* plot rain
*/
@ -41,103 +36,107 @@ public class PlotSettings {
*
*/
private Set<Flag> flags;
/**
* plot time
*/
private Long time;
/**
* Change time?
*/
private boolean changeTime;
private PlotHomePosition position;
/**
* Constructor
* @param plot
*/
public PlotSettings(Plot plot) {
this.plot = plot;
/**
* plot time
*/
private Long time;
/**
* Change time?
*/
private boolean changeTime;
private PlotHomePosition position;
/**
* Constructor
*
* @param plot
*/
public PlotSettings(Plot plot) {
this.alias = "";
}
/**
*
* @param b
*/
public void setBiome(Biome b) {
this.biome = b;
}
/**
*
* @param b
*/
public void setTimeChange(boolean b) {
this.changeTime = b;
}
/**
*
* @param l
*/
public void setTime(long l) {
this.time = l;
}
/**
*
* @return
* @deprecated
*/
public Biome getBiome() {
return this.biome;
}
/**
*
* @return
*/
public boolean getRain() {
return this.rain;
}
}
/**
*
* @param b
*/
public void setBiome(Biome b) {
this.biome = b;
}
/**
*
* @param b
*/
public void setTimeChange(boolean b) {
this.changeTime = b;
}
/**
*
* @param l
*/
public void setTime(long l) {
this.time = l;
}
/**
*
* @return
* @deprecated
*/
@Deprecated
public Biome getBiome() {
return this.biome;
}
/**
*
* @return
*/
public boolean getRain() {
return this.rain;
}
public void setRain(boolean b) {
this.rain = b;
}
/**
*
* @return
*/
public long getTime() {
return this.time;
}
/**
*
* @return
*/
public boolean getChangeTime() {
return this.changeTime;
}
/**
*
* @return
*/
public long getTime() {
return this.time;
}
/**
*
* @return
*/
public boolean getChangeTime() {
return this.changeTime;
}
/**
*
* @param alias
*/
public void setAlias(String alias) {
public void setAlias(String alias) {
this.alias = alias;
}
/**
*
* @param flag
*/
public void addFlag(Flag flag) {
Flag hasFlag = getFlag(flag.getKey());
if (hasFlag!=null)
flags.remove(hasFlag);
if (hasFlag != null) {
this.flags.remove(hasFlag);
}
this.flags.add(flag);
}
/**
*
* @param flags
@ -145,6 +144,7 @@ public class PlotSettings {
public void setFlags(Flag[] flags) {
this.flags = new HashSet<Flag>(Arrays.asList(flags));
}
/**
*
* @return
@ -152,23 +152,38 @@ public class PlotSettings {
public Set<Flag> getFlags() {
return this.flags;
}
/**
*
* @param flag
* @return
*/
public Flag getFlag(String flag) {
for (Flag myflag:flags) {
if (myflag.getKey().equals(flag))
for (Flag myflag : this.flags) {
if (myflag.getKey().equals(flag)) {
return myflag;
}
}
return null;
}
public PlotHomePosition getPosition() { return this.position; }
public void setPosition(PlotHomePosition position) { this.position = position; }
public String getAlias() { return this.alias; }
public String getJoinMessage() { return ""; }
public String getLeaveMessage() { return ""; }
public PlotHomePosition getPosition() {
return this.position;
}
public void setPosition(PlotHomePosition position) {
this.position = position;
}
public String getAlias() {
return this.alias;
}
public String getJoinMessage() {
return "";
}
public String getLeaveMessage() {
return "";
}
}

View File

@ -1,31 +1,29 @@
package com.intellectualcrafters.plot;
import org.bukkit.Material;
import java.util.ArrayList;
import org.bukkit.Material;
public class PlotWorld {
/*
* This is the PlotWorld class (obviously)
* - All existing PlotWorld instances should be kept in PlotMain (worlds variable)
* - The accessors and mutators are:
* PlotMain.isPlotWorld(world)
* PlotMain.getPlotWorlds() or PlotMain.getPlotWorldsString() <- use this if you don't need to get world objects
* PlotMain.getWorldSettings(World) - get the PlotWorld class for a 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 plot.getWorld() (world object)
*
* 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):
* - 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)
*
* All new DEFAULT 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 WorldGenerator class
*
* This is the PlotWorld class (obviously) - All existing PlotWorld
* instances should be kept in PlotMain (worlds variable) - The accessors
* and mutators are: PlotMain.isPlotWorld(world) PlotMain.getPlotWorlds() or
* PlotMain.getPlotWorldsString() <- use this if you don't need to get world
* objects PlotMain.getWorldSettings(World) - get the PlotWorld class for a
* 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
* plot.getWorld() (world object) 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): - 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) All new DEFAULT
* 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
* WorldGenerator class
*/
/**
* Road Height
*/
@ -34,16 +32,16 @@ public class PlotWorld {
* Default Road Height: 64
*/
public static int ROAD_HEIGHT_DEFAULT = 64;
/**
* plot height
*/
public int PLOT_HEIGHT;
/**
* Default plot height: 64
*/
*/
public static int PLOT_HEIGHT_DEFAULT = 64;
/**
* Wall height
*/
@ -52,7 +50,7 @@ public class PlotWorld {
* Default Wall Height: 64
*/
public static int WALL_HEIGHT_DEFAULT = 64;
/**
* plot width
*/
@ -61,7 +59,7 @@ public class PlotWorld {
* Default plot width: 32
*/
public static int PLOT_WIDTH_DEFAULT = 32;
/**
* Road width
*/
@ -70,7 +68,7 @@ public class PlotWorld {
* Default road width: 7
*/
public static int ROAD_WIDTH_DEFAULT = 7;
/**
* Plot biome
*/
@ -86,7 +84,7 @@ public class PlotWorld {
/**
* Default main block: 1
*/
public static String[] MAIN_BLOCK_DEFAULT = new String[] {"1:0"};
public static String[] MAIN_BLOCK_DEFAULT = new String[] { "1:0" };
/**
* Top blocks
*/
@ -94,8 +92,8 @@ public class PlotWorld {
/**
* Default top blocks: {"2"}
*/
public static String[] TOP_BLOCK_DEFAULT = new String[] {"2:0"};
public static String[] TOP_BLOCK_DEFAULT = new String[] { "2:0" };
/**
* Wall block
*/
@ -104,7 +102,7 @@ public class PlotWorld {
* Default wall block: 44
*/
public static String WALL_BLOCK_DEFAULT = "44:0";
/**
* Wall filling
*/
@ -113,7 +111,7 @@ public class PlotWorld {
* Default wall filling: 1
*/
public static String WALL_FILLING_DEFAULT = "1:0";
/**
* Road stripes
*/
@ -124,33 +122,33 @@ public class PlotWorld {
* Default road stripes: 35
*/
public static String ROAD_STRIPES_DEFAULT = "98:0";
//
// /**
// * Road stripes data value (byte)
// */
// public int ROAD_STRIPES_DATA;
// /**
// * Default road stripes data value: (byte) 0
// */
// public static int ROAD_STRIPES_DATA_DEFAULT = 0;
//
// /**
// * Wall block data value (byte)
// */
// public int WALL_BLOCK_DATA;
// /**
// * Default wall block data value: (byte) 0
// */
// public static int WALL_BLOCK_DATA_DEFAULT = 0;
//
// /**
// * Wall filling data value (byte)
// */
// public int WALL_FILLING_DATA;
// /**
// * Default wall filling data value: (byte) 0
// */
// public static int WALL_FILLING_DATA_DEFAULT = 0;
//
// /**
// * Road stripes data value (byte)
// */
// public int ROAD_STRIPES_DATA;
// /**
// * Default road stripes data value: (byte) 0
// */
// public static int ROAD_STRIPES_DATA_DEFAULT = 0;
//
// /**
// * Wall block data value (byte)
// */
// public int WALL_BLOCK_DATA;
// /**
// * Default wall block data value: (byte) 0
// */
// public static int WALL_BLOCK_DATA_DEFAULT = 0;
//
// /**
// * Wall filling data value (byte)
// */
// public int WALL_FILLING_DATA;
// /**
// * Default wall filling data value: (byte) 0
// */
// public static int WALL_FILLING_DATA_DEFAULT = 0;
/**
* Road block
*/
@ -159,16 +157,16 @@ public class PlotWorld {
* Default road block: 155
*/
public static String ROAD_BLOCK_DEFAULT = "155:0";
//
// /**
// * Road block data value (byte)
// */
// public int ROAD_BLOCK_DATA;
// /**
// * Default road block data value: (byte) 0
// */
// public static int ROAD_BLOCK_DATA_DEFAULT = 0;
//
// /**
// * Road block data value (byte)
// */
// public int ROAD_BLOCK_DATA;
// /**
// * Default road block data value: (byte) 0
// */
// public static int ROAD_BLOCK_DATA_DEFAULT = 0;
/**
* plot chat?
*/

View File

@ -14,101 +14,76 @@ import org.bukkit.entity.Player;
/**
* Random utilities
*
* @author Citymonstret
*
*
*/
public class RUtils {
public static long getTotalRam() {
return (Runtime.getRuntime().maxMemory() / 1024) / 1024;
}
public static long getFreeRam() {
return (Runtime.getRuntime().freeMemory() / 1024) / 1024;
}
public static long getRamPercentage() {
return (getFreeRam() / getTotalRam()) * 100;
}
public static String formatTime(double sec) {
double h = sec / 3600;
public static long getTotalRam() {
return (Runtime.getRuntime().maxMemory() / 1024) / 1024;
}
public static long getFreeRam() {
return (Runtime.getRuntime().freeMemory() / 1024) / 1024;
}
public static long getRamPercentage() {
return (getFreeRam() / getTotalRam()) * 100;
}
public static String formatTime(double sec) {
double h = sec / 3600;
double m = (sec % 3600) / 60;
double s = sec % 60;
String string = C.TIME_FORMAT.s();
@SuppressWarnings("unused")
//String s_d = (int) d + " " + (d != 1 ? "days" : "day");
String s_h = (int) h + " " + ((int) h != 1 ? "hours" : "hour");
String s_m = (int) m + " " + ((int) m != 1 ? "minutes" : "minute");
String s_s = (int) s + " " + ((int) s != 1 ? "seconds" : "second");
return string.replaceAll("%sec%", s_s).replaceAll("%min%", s_m).replaceAll("%hours%", s_h);
}
enum Direction {
SOUTH(0),
EAST(1),
NORTH(2),
WEST(3)
;
private int i;
Direction(int i) {
this.i = i;
}
public int getInt() {
return this.i;
}
}
double s = sec % 60;
String string = C.TIME_FORMAT.s();
@SuppressWarnings("unused")
// String s_d = (int) d + " " + (d != 1 ? "days" : "day");
String s_h = (int) h + " " + ((int) h != 1 ? "hours" : "hour");
String s_m = (int) m + " " + ((int) m != 1 ? "minutes" : "minute");
String s_s = (int) s + " " + ((int) s != 1 ? "seconds" : "second");
return string.replaceAll("%sec%", s_s).replaceAll("%min%", s_m).replaceAll("%hours%", s_h);
}
enum Direction {
SOUTH(0), EAST(1), NORTH(2), WEST(3);
private int i;
Direction(int i) {
this.i = i;
}
public int getInt() {
return this.i;
}
}
public void forceTexture(Player p) {
p.setResourcePack(Settings.PLOT_SPECIFIC_RESOURCE_PACK);
}
public Direction getDirection(Location l) {
double d = (l.getYaw() * 4.0F / 360.0F) + 0.5D;
int i = (int) d;
int x = d < i ? i - 1 : i;
public Direction getDirection(Location l) {
double d = ((l.getYaw() * 4.0F) / 360.0F) + 0.5D;
int i = (int) d;
int x = d < i ? i - 1 : i;
float yaw;
switch(x) {
case 0:
return Direction.SOUTH;
case 1:
return Direction.EAST;
case 2:
return Direction.NORTH;
case 3:
return Direction.WEST;
default:
return null;
}
}
switch (x) {
case 0:
return Direction.SOUTH;
case 1:
return Direction.EAST;
case 2:
return Direction.NORTH;
case 3:
return Direction.WEST;
default:
return null;
}
}
public boolean compareDirections(Location l1, Location l2) {
return getDirection(l1) == getDirection(l2);
}
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,39 +1,41 @@
package com.intellectualcrafters.plot;
import org.bukkit.Bukkit;
import org.bukkit.Server;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Server;
/**
* @author DPOH-VAR
* @version 1.0
*/
@SuppressWarnings({ "UnusedDeclaration", "rawtypes" })
public class ReflectionUtils {
/** prefix of bukkit classes */
/** prefix of bukkit classes */
private static String preClassB = "org.bukkit.craftbukkit";
/** prefix of minecraft classes */
private static String preClassM = "net.minecraft.server";
/** boolean value, TRUE if server uses forge or MCPC+ */
private static boolean forge = false;
/** check server version and class names */
static {
if(Bukkit.getServer()!=null) {
if(Bukkit.getVersion().contains("MCPC")||Bukkit.getVersion().contains("Forge")) forge = true;
if (Bukkit.getServer() != null) {
if (Bukkit.getVersion().contains("MCPC") || Bukkit.getVersion().contains("Forge")) {
forge = true;
}
Server server = Bukkit.getServer();
Class<?> bukkitServerClass = server.getClass();
String[] pas = bukkitServerClass.getName().split("\\.");
if (pas.length == 5) {
String verB = pas[3];
preClassB += "."+verB;
preClassB += "." + verB;
}
try {
Method getHandle = bukkitServerClass.getDeclaredMethod("getHandle");
@ -42,164 +44,202 @@ public class ReflectionUtils {
pas = handleServerClass.getName().split("\\.");
if (pas.length == 5) {
String verM = pas[3];
preClassM += "."+verM;
preClassM += "." + verM;
}
} catch (Exception ignored) {
}
}
}
/**
* @return true if server has forge classes
*/
public static boolean isForge(){
public static boolean isForge() {
return forge;
}
/**
* Get class for name.
* Replace {nms} to net.minecraft.server.V*.
* Replace {cb} to org.bukkit.craftbukkit.V*.
* Replace {nm} to net.minecraft
* @param classes possible class paths
* Get class for name. Replace {nms} to net.minecraft.server.V*. Replace
* {cb} to org.bukkit.craftbukkit.V*. Replace {nm} to net.minecraft
*
* @param classes
* possible class paths
* @return RefClass object
* @throws RuntimeException if no class found
* @throws RuntimeException
* if no class found
*/
public static RefClass getRefClass(String... classes){
for (String className: classes) try {
className = className
.replace("{cb}", preClassB)
.replace("{nms}", preClassM)
.replace("{nm}", "net.minecraft");
return getRefClass(Class.forName(className));
} catch (ClassNotFoundException ignored) {
public static RefClass getRefClass(String... classes) {
for (String className : classes) {
try {
className = className.replace("{cb}", preClassB).replace("{nms}", preClassM).replace("{nm}", "net.minecraft");
return getRefClass(Class.forName(className));
} catch (ClassNotFoundException ignored) {
}
}
throw new RuntimeException("no class found");
}
/**
* get RefClass object by real class
* @param clazz class
*
* @param clazz
* class
* @return RefClass based on passed class
*/
public static RefClass getRefClass(Class clazz) {
return new RefClass(clazz);
}
/**
* RefClass - utility to simplify work with reflections.
*/
public static class RefClass {
private final Class<?> clazz;
/**
* get passed class
*
* @return class
*/
public Class<?> getRealClass() {
return clazz;
return this.clazz;
}
private RefClass(Class<?> clazz) {
this.clazz = clazz;
}
/**
* 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
*/
public boolean isInstance(Object object){
return clazz.isInstance(object);
public boolean isInstance(Object object) {
return this.clazz.isInstance(object);
}
/**
* get existing method by name and types
* @param name name
* @param types method parameters. can be Class or RefClass
*
* @param name
* name
* @param types
* method parameters. can be Class or RefClass
* @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 {
Class[] classes = new Class[types.length];
int i=0; for (Object e: types) {
if (e instanceof Class) classes[i++] = (Class)e;
else if (e instanceof RefClass) classes[i++] = ((RefClass) e).getRealClass();
else classes[i++] = e.getClass();
int i = 0;
for (Object e : types) {
if (e instanceof Class) {
classes[i++] = (Class) e;
} else if (e instanceof RefClass) {
classes[i++] = ((RefClass) e).getRealClass();
} else {
classes[i++] = e.getClass();
}
}
try {
return new RefMethod(clazz.getMethod(name, classes));
return new RefMethod(this.clazz.getMethod(name, classes));
} catch (NoSuchMethodException ignored) {
return new RefMethod(clazz.getDeclaredMethod(name, classes));
return new RefMethod(this.clazz.getDeclaredMethod(name, classes));
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* get existing constructor by types
* @param types parameters. can be Class or RefClass
*
* @param types
* parameters. can be Class or RefClass
* @return RefMethod object
* @throws RuntimeException if constructor not found
* @throws RuntimeException
* if constructor not found
*/
public RefConstructor getConstructor(Object... types) {
try {
Class[] classes = new Class[types.length];
int i=0; for (Object e: types) {
if (e instanceof Class) classes[i++] = (Class)e;
else if (e instanceof RefClass) classes[i++] = ((RefClass) e).getRealClass();
else classes[i++] = e.getClass();
int i = 0;
for (Object e : types) {
if (e instanceof Class) {
classes[i++] = (Class) e;
} else if (e instanceof RefClass) {
classes[i++] = ((RefClass) e).getRealClass();
} else {
classes[i++] = e.getClass();
}
}
try {
return new RefConstructor(clazz.getConstructor(classes));
return new RefConstructor(this.clazz.getConstructor(classes));
} catch (NoSuchMethodException ignored) {
return new RefConstructor(clazz.getDeclaredConstructor(classes));
return new RefConstructor(this.clazz.getDeclaredConstructor(classes));
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* find method by type parameters
* @param types parameters. can be Class or RefClass
*
* @param types
* parameters. can be Class or RefClass
* @return RefMethod object
* @throws RuntimeException if method not found
* @throws RuntimeException
* if method not found
*/
public RefMethod findMethod(Object... types) {
Class[] classes = new Class[types.length];
int t=0; for (Object e: types) {
if (e instanceof Class) classes[t++] = (Class)e;
else if (e instanceof RefClass) classes[t++] = ((RefClass) e).getRealClass();
else classes[t++] = e.getClass();
int t = 0;
for (Object e : types) {
if (e instanceof Class) {
classes[t++] = (Class) e;
} else if (e instanceof RefClass) {
classes[t++] = ((RefClass) e).getRealClass();
} else {
classes[t++] = e.getClass();
}
}
List<Method> methods = new ArrayList<>();
Collections.addAll(methods, clazz.getMethods());
Collections.addAll(methods, clazz.getDeclaredMethods());
findMethod: for (Method m: methods) {
Collections.addAll(methods, this.clazz.getMethods());
Collections.addAll(methods, this.clazz.getDeclaredMethods());
findMethod: for (Method m : methods) {
Class<?>[] methodTypes = m.getParameterTypes();
if (methodTypes.length != classes.length) continue;
for (int i=0; i<classes.length; i++) {
if (!classes.equals(methodTypes)) continue findMethod;
if (methodTypes.length != classes.length) {
continue;
}
for (int i = 0; i < classes.length; i++) {
if (!classes.equals(methodTypes)) {
continue findMethod;
}
return new RefMethod(m);
}
}
throw new RuntimeException("no such method");
}
/**
* find method by name
* @param names possible names of method
*
* @param names
* possible names of method
* @return RefMethod object
* @throws RuntimeException if method not found
* @throws RuntimeException
* if method not found
*/
public RefMethod findMethodByName(String... names) {
List<Method> methods = new ArrayList<>();
Collections.addAll(methods, clazz.getMethods());
Collections.addAll(methods, clazz.getDeclaredMethods());
for (Method m: methods) {
for (String name: names) {
Collections.addAll(methods, this.clazz.getMethods());
Collections.addAll(methods, this.clazz.getDeclaredMethods());
for (Method m : methods) {
for (String name : names) {
if (m.getName().equals(name)) {
return new RefMethod(m);
}
@ -207,92 +247,116 @@ public class ReflectionUtils {
}
throw new RuntimeException("no such method");
}
/**
* 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
*/
public RefMethod findMethodByReturnType(RefClass type) {
return findMethodByReturnType(type.clazz);
}
/**
* find method by return value
* @param type type of returned value
*
* @param type
* type of returned value
* @return RefMethod
* @throws RuntimeException if method not found
* @throws RuntimeException
* if method not found
*/
public RefMethod findMethodByReturnType(Class type) {
if (type==null) type = void.class;
if (type == null) {
type = void.class;
}
List<Method> methods = new ArrayList<>();
Collections.addAll(methods, clazz.getMethods());
Collections.addAll(methods, clazz.getDeclaredMethods());
for (Method m: methods) {
Collections.addAll(methods, this.clazz.getMethods());
Collections.addAll(methods, this.clazz.getDeclaredMethods());
for (Method m : methods) {
if (type.equals(m.getReturnType())) {
return new RefMethod(m);
}
}
throw new RuntimeException("no such method");
}
/**
* find constructor by number of arguments
* @param number number of arguments
*
* @param number
* number of arguments
* @return RefConstructor
* @throws RuntimeException if constructor not found
* @throws RuntimeException
* if constructor not found
*/
public RefConstructor findConstructor(int number) {
List<Constructor> constructors = new ArrayList<>();
Collections.addAll(constructors, clazz.getConstructors());
Collections.addAll(constructors, clazz.getDeclaredConstructors());
for (Constructor m: constructors) {
if (m.getParameterTypes().length == number) return new RefConstructor(m);
Collections.addAll(constructors, this.clazz.getConstructors());
Collections.addAll(constructors, this.clazz.getDeclaredConstructors());
for (Constructor m : constructors) {
if (m.getParameterTypes().length == number) {
return new RefConstructor(m);
}
}
throw new RuntimeException("no such constructor");
}
/**
* get field by name
* @param name field name
*
* @param name
* field name
* @return RefField
* @throws RuntimeException if field not found
* @throws RuntimeException
* if field not found
*/
public RefField getField(String name) {
try {
try {
return new RefField(clazz.getField(name));
return new RefField(this.clazz.getField(name));
} catch (NoSuchFieldException ignored) {
return new RefField(clazz.getDeclaredField(name));
return new RefField(this.clazz.getDeclaredField(name));
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* find field by type
* @param type field type
*
* @param type
* field type
* @return RefField
* @throws RuntimeException if field not found
* @throws RuntimeException
* if field not found
*/
public RefField findField(RefClass type) {
return findField(type.clazz);
}
/**
* find field by type
* @param type field type
*
* @param type
* field type
* @return RefField
* @throws RuntimeException if field not found
* @throws RuntimeException
* if field not found
*/
public RefField findField(Class type) {
if (type==null) type = void.class;
if (type == null) {
type = void.class;
}
List<Field> fields = new ArrayList<>();
Collections.addAll(fields, clazz.getFields());
Collections.addAll(fields, clazz.getDeclaredFields());
for (Field f: fields) {
Collections.addAll(fields, this.clazz.getFields());
Collections.addAll(fields, this.clazz.getDeclaredFields());
for (Field f : fields) {
if (type.equals(f.getType())) {
return new RefField(f);
}
@ -300,184 +364,208 @@ public class ReflectionUtils {
throw new RuntimeException("no such field");
}
}
/**
* Method wrapper
*/
public static class RefMethod {
private final Method method;
/**
* @return passed method
*/
public Method getRealMethod(){
return method;
public Method getRealMethod() {
return this.method;
}
/**
* @return owner class of method
*/
public RefClass getRefClass(){
return new RefClass(method.getDeclaringClass());
public RefClass getRefClass() {
return new RefClass(this.method.getDeclaringClass());
}
/**
* @return class of method return type
*/
public RefClass getReturnRefClass(){
return new RefClass(method.getReturnType());
public RefClass getReturnRefClass() {
return new RefClass(this.method.getReturnType());
}
private RefMethod (Method method) {
private RefMethod(Method method) {
this.method = method;
method.setAccessible(true);
}
/**
* 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(...)
*/
public RefExecutor of(Object e) {
return new RefExecutor(e);
}
/**
* call static method
* @param params sent parameters
*
* @param params
* sent parameters
* @return return value
*/
public Object call(Object... params) {
try{
return method.invoke(null,params);
try {
return this.method.invoke(null, params);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public class RefExecutor {
Object e;
public RefExecutor(Object e) {
this.e = e;
}
/**
* apply method for selected object
* @param params sent parameters
*
* @param params
* sent parameters
* @return return value
* @throws RuntimeException if something went wrong
* @throws RuntimeException
* if something went wrong
*/
public Object call(Object... params) {
try{
return method.invoke(e,params);
try {
return RefMethod.this.method.invoke(this.e, params);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
/**
* Constructor wrapper
*/
public static class RefConstructor {
private final Constructor constructor;
/**
* @return passed constructor
*/
public Constructor getRealConstructor(){
return constructor;
public Constructor getRealConstructor() {
return this.constructor;
}
/**
* @return owner class of method
*/
public RefClass getRefClass(){
return new RefClass(constructor.getDeclaringClass());
public RefClass getRefClass() {
return new RefClass(this.constructor.getDeclaringClass());
}
private RefConstructor (Constructor constructor) {
private RefConstructor(Constructor constructor) {
this.constructor = constructor;
constructor.setAccessible(true);
}
/**
* create new instance with constructor
* @param params parameters for constructor
*
* @param params
* parameters for constructor
* @return new object
* @throws RuntimeException if something went wrong
* @throws RuntimeException
* if something went wrong
*/
public Object create(Object... params) {
try{
return constructor.newInstance(params);
try {
return this.constructor.newInstance(params);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public static class RefField {
private Field field;
/**
* @return passed field
*/
public Field getRealField(){
return field;
public Field getRealField() {
return this.field;
}
/**
* @return owner class of field
*/
public RefClass getRefClass(){
return new RefClass(field.getDeclaringClass());
public RefClass getRefClass() {
return new RefClass(this.field.getDeclaringClass());
}
/**
* @return type of field
*/
public RefClass getFieldRefClass(){
return new RefClass(field.getType());
public RefClass getFieldRefClass() {
return new RefClass(this.field.getType());
}
private RefField (Field field) {
private RefField(Field field) {
this.field = field;
field.setAccessible(true);
}
/**
* apply fiend for object
* @param e applied object
*
* @param e
* applied object
* @return RefExecutor with getter and setter
*/
public RefExecutor of(Object e) {
return new RefExecutor(e);
}
public class RefExecutor {
Object e;
public RefExecutor(Object e) {
this.e = e;
}
/**
* set field value for applied object
* @param param value
*
* @param param
* value
*/
public void set(Object param) {
try{
field.set(e,param);
try {
RefField.this.field.set(this.e, param);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* get field value for applied object
*
* @return value of field
*/
public Object get() {
try{
return field.get(e);
try {
return RefField.this.field.get(this.e);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
}

View File

@ -1,26 +1,32 @@
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.FileInputStream;
import java.io.InputStream;
import java.util.Map;
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.
*/
public class SchematicHandler {
@SuppressWarnings("deprecation")
public boolean paste(Location location, Schematic schematic, Plot plot){
if(schematic == null) {
public boolean paste(Location location, Schematic schematic, Plot plot) {
if (schematic == null) {
PlotMain.sendConsoleSenderMessage("Schematic == null :|");
return false;
}
@ -28,11 +34,11 @@ public class SchematicHandler {
EditSession session = new EditSession(new BukkitWorld(location.getWorld()), 999999999);
CuboidClipboard clipboard = CuboidClipboard.loadSchematic(schematic.getFile());
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());
Vector v1 = new Vector(l1.getBlockX() + 1, plotWorld.PLOT_HEIGHT + 2, l1.getBlockZ() + 1);
clipboard.paste(session, v1, true);
} catch(Exception e) {
} catch (Exception e) {
return false;
}
return true;
@ -40,13 +46,13 @@ public class SchematicHandler {
public Schematic getSchematic(String name) {
{
File parent = new File(PlotMain.getPlugin(PlotMain.class).getDataFolder() + File.separator + "schematics");
if(!parent.exists()) {
File parent = new File(JavaPlugin.getPlugin(PlotMain.class).getDataFolder() + File.separator + "schematics");
if (!parent.exists()) {
parent.mkdir();
}
}
File file = new File(PlotMain.getPlugin(PlotMain.class).getDataFolder() + File.separator + "schematics" + File.separator + name + ".schematic");
if(!file.exists()) {
File file = new File(JavaPlugin.getPlugin(PlotMain.class).getDataFolder() + File.separator + "schematics" + File.separator + name + ".schematic");
if (!file.exists()) {
PlotMain.sendConsoleSenderMessage(file.toString() + " doesn't exist");
return null;
}
@ -74,7 +80,8 @@ public class SchematicHandler {
Dimension dimension = new Dimension(width, height, length);
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);
} else {
if ((index & 1) == 0) {
@ -87,12 +94,12 @@ public class SchematicHandler {
DataCollection[] collection = new DataCollection[b.length];
for(int x = 0; x < b.length; x++) {
for (int x = 0; x < b.length; x++) {
collection[x] = new DataCollection(blocks[x], d[x]);
}
schematic = new Schematic(collection, dimension, file);
} catch(Exception e) {
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
@ -100,10 +107,6 @@ public class SchematicHandler {
}
}
private int getCurrent(int x, int y, int z, Dimension dimension) {
return (x * dimension.getX()) + (y * dimension.getY()) + (z * dimension.getZ());
}
public static class Schematic {
private DataCollection[] blockCollection;
private Dimension schematicDimension;

View File

@ -1,34 +1,39 @@
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 {
private static final RefClass classBlock = getRefClass("{nms}.Block");
private static final RefClass classChunk = getRefClass("{nms}.Chunk");
private static final RefClass classWorld = getRefClass("{nms}.World");
private static final RefClass classCraftWorld = getRefClass("{cb}.CraftWorld");
private static final RefMethod methodGetHandle = classCraftWorld.getMethod("getHandle");
private static final RefMethod methodGetChunkAt = classWorld.getMethod("getChunkAt",int.class,int.class);
private static final RefMethod methodA = classChunk.getMethod("a",int.class,int.class,int.class,classBlock,int.class);
private static final RefMethod methodGetById = classBlock.getMethod("getById", int.class);
public SetBlockFast() {
private static RefMethod methodGetHandle;
private static RefMethod methodGetChunkAt;
private static RefMethod methodA;
private static RefMethod methodGetById;
public SetBlockFast() throws NoSuchMethodException {
methodGetHandle = classCraftWorld.getMethod("getHandle");
methodGetChunkAt = classWorld.getMethod("getChunkAt", int.class, int.class);
methodA = classChunk.getMethod("a", int.class, int.class, int.class, classBlock, int.class);
methodGetById = classBlock.getMethod("getById", int.class);
}
public 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 chunk = methodGetChunkAt.of(w).call(x >> 4, z >> 4);
Object block = methodGetById.of(null).call(blockId);
methodA.of(chunk).call(x & 0x0f, y, z & 0x0f,block , data);
methodA.of(chunk).call(x & 0x0f, y, z & 0x0f, block, data);
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 cz = -8; cz < 8; 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
*
* @author Citymonstret
*
* @author Empire92
@ -37,39 +38,44 @@ public class Settings {
* Default mob pathfinding: true
*/
public static boolean MOB_PATHFINDING_DEFAULT = true;
/**
* Update settings
* @author Citymonstret
*
*/
/**
* Update settings
*
* @author Citymonstret
*
*/
public static String URL = "http://dev.bukkit.org/bukkit-plugins/plotsquared/";
public static class Update {
/**
* Update plugin?
public static class Update {
/**
* Update plugin?
*
* @deprecated
*/
public static boolean AUTO_UPDATE = false;
}
public static class Web {
public static boolean ENABLED = false;
public static int PORT = 9000;
*/
@Deprecated
public static boolean AUTO_UPDATE = false;
}
/**
* Database settings
* @author Citymonstret
*
*/
public static class DB {
public static boolean USE_MONGO = false; /* TODO: Implement Mongo */;
public static boolean USE_SQLITE = false;
public static boolean USE_MYSQL = true; /* NOTE: Fixed connector */
public static String SQLITE_DB = "storage";
public static String HOST_NAME = "localhost";
public static String PORT = "3306";
public static String DATABASE = "plot_db";
public static String USER = "root";
public static String PASSWORD = "password";
}
}
public static class Web {
public static boolean ENABLED = false;
public static int PORT = 9000;
}
/**
* Database settings
*
* @author Citymonstret
*
*/
public static class DB {
public static boolean USE_MONGO = false; /* TODO: Implement Mongo */;
public static boolean USE_SQLITE = false;
public static boolean USE_MYSQL = true; /* NOTE: Fixed connector */
public static String SQLITE_DB = "storage";
public static String HOST_NAME = "localhost";
public static String PORT = "3306";
public static String DATABASE = "plot_db";
public static String USER = "root";
public static String PASSWORD = "password";
}
}

View File

@ -1,17 +1,17 @@
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.Method;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
/**
* Minecraft 1.8 Title
*
*
* @version 1.0.3
* @author Maxim Van de Wynckel
*/
@ -43,7 +43,7 @@ public class Title {
/**
* Create a new 1.8 title
*
*
* @param title
* Title
*/
@ -54,7 +54,7 @@ public class Title {
/**
* Create a new 1.8 title
*
*
* @param title
* Title text
* @param subtitle
@ -68,7 +68,7 @@ public class Title {
/**
* Create a new 1.8 title
*
*
* @param title
* Title text
* @param subtitle
@ -80,8 +80,7 @@ public class Title {
* @param fadeOutTime
* Fade out time
*/
public Title(String title, String subtitle, int fadeInTime, int stayTime,
int fadeOutTime) {
public Title(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) {
this.title = title;
this.subtitle = subtitle;
this.fadeInTime = fadeInTime;
@ -94,14 +93,14 @@ public class Title {
* Load spigot and NMS classes
*/
private void loadClasses() {
packetTitle = getClass("org.spigotmc.ProtocolInjector$PacketTitle");
packetActions = getClass("org.spigotmc.ProtocolInjector$PacketTitle$Action");
nmsChatSerializer = getNMSClass("ChatSerializer");
this.packetTitle = getClass("org.spigotmc.ProtocolInjector$PacketTitle");
this.packetActions = getClass("org.spigotmc.ProtocolInjector$PacketTitle$Action");
this.nmsChatSerializer = getNMSClass("ChatSerializer");
}
/**
* Set the title color
*
*
* @param color
* Chat color
*/
@ -111,7 +110,7 @@ public class Title {
/**
* Set the subtitle color
*
*
* @param color
* Chat color
*/
@ -121,7 +120,7 @@ public class Title {
/**
* Set title fade in time
*
*
* @param time
* Time
*/
@ -131,7 +130,7 @@ public class Title {
/**
* Set title fade out time
*
*
* @param time
* Time
*/
@ -141,7 +140,7 @@ public class Title {
/**
* Set title stay time
*
*
* @param time
* Time
*/
@ -153,70 +152,46 @@ public class Title {
* Set timings to ticks
*/
public void setTimingsToTicks() {
ticks = true;
this.ticks = true;
}
/**
* Set timings to seconds
*/
public void setTimingsToSeconds() {
ticks = false;
this.ticks = false;
}
/**
* Send the title to a player
*
*
* @param player
* Player
*/
public void send(Player player) {
if (getProtocolVersion(player) >= 47 && isSpigot()
&& packetTitle != null) {
if ((getProtocolVersion(player) >= 47) && isSpigot() && (this.packetTitle != null)) {
// First reset previous settings
resetTitle(player);
try {
// Send timings first
Object handle = getHandle(player);
Object connection = getField(handle.getClass(),
"playerConnection").get(handle);
Object[] actions = packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(),
"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));
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object[] actions = this.packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = this.packetTitle.getConstructor(this.packetActions, Integer.TYPE, Integer.TYPE, Integer.TYPE).newInstance(actions[2], this.fadeInTime * (this.ticks ? 1 : 20), this.stayTime * (this.ticks ? 1 : 20), this.fadeOutTime * (this.ticks ? 1 : 20));
// Send if set
if (fadeInTime != -1 && fadeOutTime != -1 && stayTime != -1)
if ((this.fadeInTime != -1) && (this.fadeOutTime != -1) && (this.stayTime != -1)) {
sendPacket.invoke(connection, packet);
}
// Send title
Object serialized = getMethod(nmsChatSerializer, "a",
String.class).invoke(
null,
"{text:\""
+ ChatColor.translateAlternateColorCodes('&',
title) + "\",color:"
+ titleColor.name().toLowerCase() + "}");
packet = packetTitle.getConstructor(packetActions,
getNMSClass("IChatBaseComponent")).newInstance(
actions[0], serialized);
Object serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.title) + "\",color:" + this.titleColor.name().toLowerCase() + "}");
packet = this.packetTitle.getConstructor(this.packetActions, getNMSClass("IChatBaseComponent")).newInstance(actions[0], serialized);
sendPacket.invoke(connection, packet);
if (!subtitle.equals("")) {
if (!this.subtitle.equals("")) {
// Send subtitle if present
serialized = getMethod(nmsChatSerializer, "a", String.class)
.invoke(null,
"{text:\""
+ ChatColor
.translateAlternateColorCodes(
'&', subtitle)
+ "\",color:"
+ subtitleColor.name()
.toLowerCase() + "}");
packet = packetTitle.getConstructor(packetActions,
getNMSClass("IChatBaseComponent")).newInstance(
actions[1], serialized);
serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.subtitle) + "\",color:" + this.subtitleColor.name().toLowerCase() + "}");
packet = this.packetTitle.getConstructor(this.packetActions, getNMSClass("IChatBaseComponent")).newInstance(actions[1], serialized);
sendPacket.invoke(connection, packet);
}
} catch (Exception e) {
@ -236,22 +211,19 @@ public class Title {
/**
* Clear the title
*
*
* @param player
* Player
*/
public void clearTitle(Player player) {
if (getProtocolVersion(player) >= 47 && isSpigot()) {
if ((getProtocolVersion(player) >= 47) && isSpigot()) {
try {
// Send timings first
Object handle = getHandle(player);
Object connection = getField(handle.getClass(),
"playerConnection").get(handle);
Object[] actions = packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(),
"sendPacket");
Object packet = packetTitle.getConstructor(packetActions)
.newInstance(actions[3]);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object[] actions = this.packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = this.packetTitle.getConstructor(this.packetActions).newInstance(actions[3]);
sendPacket.invoke(connection, packet);
} catch (Exception e) {
e.printStackTrace();
@ -261,22 +233,19 @@ public class Title {
/**
* Reset the title settings
*
*
* @param player
* Player
*/
public void resetTitle(Player player) {
if (getProtocolVersion(player) >= 47 && isSpigot()) {
if ((getProtocolVersion(player) >= 47) && isSpigot()) {
try {
// Send timings first
Object handle = getHandle(player);
Object connection = getField(handle.getClass(),
"playerConnection").get(handle);
Object[] actions = packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(),
"sendPacket");
Object packet = packetTitle.getConstructor(packetActions)
.newInstance(actions[4]);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object[] actions = this.packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = this.packetTitle.getConstructor(this.packetActions).newInstance(actions[4]);
sendPacket.invoke(connection, packet);
} catch (Exception e) {
e.printStackTrace();
@ -286,7 +255,7 @@ public class Title {
/**
* Get the protocol version of the player
*
*
* @param player
* Player
* @return Protocol version
@ -295,22 +264,20 @@ public class Title {
int version = 0;
try {
Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection")
.get(handle);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object networkManager = getValue("networkManager", connection);
version = (Integer) getMethod("getVersion",
networkManager.getClass()).invoke(networkManager);
version = (Integer) getMethod("getVersion", networkManager.getClass()).invoke(networkManager);
return version;
} catch (Exception ex) {
// ex.printStackTrace(); <-- spammy console
// ex.printStackTrace(); <-- spammy console
}
return version;
}
/**
* Check if running spigot
*
*
* @return Spigot
*/
private boolean isSpigot() {
@ -319,7 +286,7 @@ public class Title {
/**
* Get class by url
*
*
* @param namespace
* Namespace url
* @return Class
@ -343,24 +310,27 @@ public class Title {
}
private Class<?> getPrimitiveType(Class<?> clazz) {
return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES
.get(clazz) : clazz;
return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES.get(clazz) : clazz;
}
private Class<?>[] toPrimitiveTypeArray(Class<?>[] classes) {
int a = classes != null ? classes.length : 0;
Class<?>[] types = new Class<?>[a];
for (int i = 0; i < a; i++)
for (int i = 0; i < a; i++) {
types[i] = getPrimitiveType(classes[i]);
}
return types;
}
private static boolean equalsTypeArray(Class<?>[] a, Class<?>[] o) {
if (a.length != o.length)
if (a.length != o.length) {
return false;
for (int i = 0; i < a.length; i++)
if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i]))
}
for (int i = 0; i < a.length; i++) {
if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i])) {
return false;
}
}
return true;
}
@ -373,13 +343,13 @@ public class Title {
}
}
private Method getMethod(String name, Class<?> clazz,
Class<?>... paramTypes) {
private Method getMethod(String name, Class<?> clazz, Class<?>... paramTypes) {
Class<?>[] t = toPrimitiveTypeArray(paramTypes);
for (Method m : clazz.getMethods()) {
Class<?>[] types = toPrimitiveTypeArray(m.getParameterTypes());
if (m.getName().equals(name) && equalsTypeArray(types, t))
if (m.getName().equals(name) && equalsTypeArray(types, t)) {
return m;
}
}
return null;
}
@ -412,25 +382,26 @@ public class Title {
}
private Method getMethod(Class<?> clazz, String name, Class<?>... args) {
for (Method m : clazz.getMethods())
if (m.getName().equals(name)
&& (args.length == 0 || ClassListEqual(args,
m.getParameterTypes()))) {
for (Method m : clazz.getMethods()) {
if (m.getName().equals(name) && ((args.length == 0) || ClassListEqual(args, m.getParameterTypes()))) {
m.setAccessible(true);
return m;
}
}
return null;
}
private boolean ClassListEqual(Class<?>[] l1, Class<?>[] l2) {
boolean equal = true;
if (l1.length != l2.length)
if (l1.length != l2.length) {
return false;
for (int i = 0; i < l1.length; i++)
}
for (int i = 0; i < l1.length; i++) {
if (l1[i] != l2[i]) {
equal = false;
break;
}
}
return equal;
}
}

View File

@ -1,5 +1,30 @@
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.Material;
import org.bukkit.World;
@ -8,24 +33,19 @@ import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.generator.BlockPopulator;
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
*
* @auther Empire92
* @author Citymonstret
*
*
*/
public class WorldGenerator extends ChunkGenerator {
private long state;
public final long nextLong() {
long a=state;
state = xorShift64(a);
long a = this.state;
this.state = xorShift64(a);
return a;
}
@ -35,11 +55,12 @@ public class WorldGenerator extends ChunkGenerator {
a ^= (a << 4);
return a;
}
public final int random(int n) {
long r = ((nextLong()>>>32)*n)>>32;
long r = ((nextLong() >>> 32) * n) >> 32;
return (int) r;
}
PlotWorld plotworld;
short[][] result;
int plotsize;
@ -54,10 +75,10 @@ public class WorldGenerator extends ChunkGenerator {
int roadheight;
int wallheight;
int plotheight;
short[] plotfloors;
short[] filling;
public Short getBlock(String block) {
if (block.contains(":")) {
String[] split = block.split(":");
@ -65,29 +86,29 @@ public class WorldGenerator extends ChunkGenerator {
}
return Short.parseShort(block);
}
public WorldGenerator(String world) {
YamlConfiguration config = PlotMain.config;
plotworld = new PlotWorld();
this.plotworld = new PlotWorld();
Map<String, Object> options = new HashMap<String, Object>();
options.put("worlds."+world+".plot_height", PLOT_HEIGHT_DEFAULT);
options.put("worlds."+world+".plot_size", PLOT_WIDTH_DEFAULT);
options.put("worlds."+world+".plot_biome", PLOT_BIOME_DEFAULT);
options.put("worlds."+world+".plot_filling", Arrays.asList(MAIN_BLOCK_DEFAULT));
options.put("worlds."+world+".top_floor", Arrays.asList(TOP_BLOCK_DEFAULT));
options.put("worlds."+world+".wall.block", WALL_BLOCK_DEFAULT);
options.put("worlds."+world+".road.width", ROAD_WIDTH_DEFAULT);
options.put("worlds."+world+".road.height", ROAD_HEIGHT_DEFAULT);
options.put("worlds."+world+".road.block", ROAD_BLOCK_DEFAULT);
options.put("worlds."+world+".road.stripes", ROAD_STRIPES_DEFAULT);
options.put("worlds."+world+".road.enable_stripes", ROAD_STRIPES_ENABLED_DEFAULT);
options.put("worlds."+world+".wall.filling", WALL_FILLING_DEFAULT);
options.put("worlds."+world+".wall.height", WALL_HEIGHT_DEFAULT);
options.put("worlds."+world+".schematic.on_claim", SCHEMATIC_ON_CLAIM_DEFAULT);
options.put("worlds."+world+".schematic.file", SCHEMATIC_FILE_DEFAULT);
options.put("worlds."+world+".default_flags", DEFAULT_FLAGS_DEFAULT);
options.put("worlds." + world + ".plot_height", PLOT_HEIGHT_DEFAULT);
options.put("worlds." + world + ".plot_size", PLOT_WIDTH_DEFAULT);
options.put("worlds." + world + ".plot_biome", PLOT_BIOME_DEFAULT);
options.put("worlds." + world + ".plot_filling", Arrays.asList(MAIN_BLOCK_DEFAULT));
options.put("worlds." + world + ".top_floor", Arrays.asList(TOP_BLOCK_DEFAULT));
options.put("worlds." + world + ".wall.block", WALL_BLOCK_DEFAULT);
options.put("worlds." + world + ".road.width", ROAD_WIDTH_DEFAULT);
options.put("worlds." + world + ".road.height", ROAD_HEIGHT_DEFAULT);
options.put("worlds." + world + ".road.block", ROAD_BLOCK_DEFAULT);
options.put("worlds." + world + ".road.stripes", ROAD_STRIPES_DEFAULT);
options.put("worlds." + world + ".road.enable_stripes", ROAD_STRIPES_ENABLED_DEFAULT);
options.put("worlds." + world + ".wall.filling", WALL_FILLING_DEFAULT);
options.put("worlds." + world + ".wall.height", WALL_HEIGHT_DEFAULT);
options.put("worlds." + world + ".schematic.on_claim", SCHEMATIC_ON_CLAIM_DEFAULT);
options.put("worlds." + world + ".schematic.file", SCHEMATIC_FILE_DEFAULT);
options.put("worlds." + world + ".default_flags", DEFAULT_FLAGS_DEFAULT);
for (Entry<String, Object> node : options.entrySet()) {
if (!config.contains(node.getKey())) {
config.set(node.getKey(), node.getValue());
@ -98,416 +119,425 @@ public class WorldGenerator extends ChunkGenerator {
} 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");
}
plotworld.PLOT_HEIGHT = config.getInt("worlds."+world+".plot_height");
plotworld.PLOT_WIDTH = config.getInt("worlds."+world+".plot_size");
plotworld.PLOT_BIOME = config.getString("worlds."+world+".plot_biome");
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]);
plotworld.WALL_BLOCK = config.getString("worlds."+world+".wall.block");
plotworld.ROAD_WIDTH = config.getInt("worlds."+world+".road.width");
plotworld.ROAD_HEIGHT = config.getInt("worlds."+world+".road.height");
plotworld.ROAD_STRIPES_ENABLED = config.getBoolean("worlds."+world+".road.enable_stripes");
plotworld.ROAD_BLOCK = config.getString("worlds."+world+".road.block");
plotworld.ROAD_STRIPES = config.getString("worlds."+world+".road.stripes");
plotworld.WALL_FILLING = config.getString("worlds."+world+".wall.filling");
plotworld.WALL_HEIGHT = config.getInt("worlds."+world+".wall.height");
plotworld.PLOT_CHAT = config.getBoolean("worlds."+world+".plot_chat");
plotworld.SCHEMATIC_ON_CLAIM = config.getBoolean("worlds."+world+".schematic.on_claim");
plotworld.SCHEMATIC_FILE = config.getString("worlds."+world+".schematic.file");
String[] default_flags_string = config.getStringList("worlds."+world+".default_flags").toArray(new String[0]);
this.plotworld.PLOT_HEIGHT = config.getInt("worlds." + world + ".plot_height");
this.plotworld.PLOT_WIDTH = config.getInt("worlds." + world + ".plot_size");
this.plotworld.PLOT_BIOME = config.getString("worlds." + world + ".plot_biome");
this.plotworld.MAIN_BLOCK = config.getStringList("worlds." + world + ".plot_filling").toArray(new String[0]);
this.plotworld.TOP_BLOCK = config.getStringList("worlds." + world + ".top_floor").toArray(new String[0]);
this.plotworld.WALL_BLOCK = config.getString("worlds." + world + ".wall.block");
this.plotworld.ROAD_WIDTH = config.getInt("worlds." + world + ".road.width");
this.plotworld.ROAD_HEIGHT = config.getInt("worlds." + world + ".road.height");
this.plotworld.ROAD_STRIPES_ENABLED = config.getBoolean("worlds." + world + ".road.enable_stripes");
this.plotworld.ROAD_BLOCK = config.getString("worlds." + world + ".road.block");
this.plotworld.ROAD_STRIPES = config.getString("worlds." + world + ".road.stripes");
this.plotworld.WALL_FILLING = config.getString("worlds." + world + ".wall.filling");
this.plotworld.WALL_HEIGHT = config.getInt("worlds." + world + ".wall.height");
this.plotworld.PLOT_CHAT = config.getBoolean("worlds." + world + ".plot_chat");
this.plotworld.SCHEMATIC_ON_CLAIM = config.getBoolean("worlds." + world + ".schematic.on_claim");
this.plotworld.SCHEMATIC_FILE = config.getString("worlds." + world + ".schematic.file");
String[] default_flags_string = config.getStringList("worlds." + world + ".default_flags").toArray(new String[0]);
Flag[] default_flags = new Flag[default_flags_string.length];
for (int i = 0; i < default_flags.length; 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]);
else
} else {
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]);
this.plotworld.DEFAULT_FLAGS = default_flags;
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 < plotworld.MAIN_BLOCK.length; i++) {
filling[i] = getBlock(plotworld.MAIN_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;
roadheight = plotworld.ROAD_HEIGHT;
plotheight = plotworld.PLOT_HEIGHT;
biome = Biome.FOREST;
for (Biome myBiome:Biome.values()) {
if (myBiome.name().equalsIgnoreCase(plotworld.PLOT_BIOME)) {
biome = myBiome;
this.wallheight = this.plotworld.WALL_HEIGHT;
this.roadheight = this.plotworld.ROAD_HEIGHT;
this.plotheight = this.plotworld.PLOT_HEIGHT;
this.biome = Biome.FOREST;
for (Biome myBiome : Biome.values()) {
if (myBiome.name().equalsIgnoreCase(this.plotworld.PLOT_BIOME)) {
this.biome = myBiome;
break;
}
}
}
@Override
public List<BlockPopulator> getDefaultPopulators(World world) {
return Arrays.asList((BlockPopulator) new XPopulator(PlotMain.getWorldSettings(world)));
}
@Override
public Location getFixedSpawnLocation(World world, Random random) {
return new Location(world, 0, PlotMain.getWorldSettings(world).ROAD_HEIGHT + 2, 0);
}
public void setCuboidRegion(int x1,int x2, int y1, int y2, int z1, int z2, short id) {
public void setCuboidRegion(int x1, int x2, int y1, int y2, int z1, int z2, short id) {
for (int x = x1; x < x2; x++) {
for (int z = z1; z < z2; z++) {
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) {
if (id.length==1) {
setCuboidRegion(x1,x2,y1,y2,z1,z2,id[0]);
}
else {
if (id.length == 1) {
setCuboidRegion(x1, x2, y1, y2, z1, z2, id[0]);
} else {
for (int x = x1; x < x2; x++) {
for (int z = z1; z < z2; z++) {
for (int y = y1; y < y2; y++) {
int i = random(id.length);
setBlock(result, x, y, z, id[i]);
setBlock(this.result, x, y, z, id[i]);
}
}
}
}
}
@SuppressWarnings("deprecation")
@Override
public short[][] generateExtBlockSections(World world, Random random,
int cx, int cz, BiomeGrid biomes) {
public short[][] generateExtBlockSections(World world, Random random, int cx, int cz, BiomeGrid biomes) {
int maxY = world.getMaxHeight();
result = new short[maxY / 16][];
this.result = new short[maxY / 16][];
double pathWidthLower;
pathWidthLower = Math.floor(pathsize/2);
pathWidthLower = Math.floor(this.pathsize / 2);
final int prime = 31;
int h = 1;
h = prime * h + cx;
h = prime * h + cz;
state = h;
cx=cx%size+8*size;
cz=cz%size+8*size;
int absX = (int) (cx*16+16-pathWidthLower-1+8*size);
int absZ = (int) (cz*16+16-pathWidthLower-1+8*size);
int plotMinX = (((absX)%size));
int plotMinZ = (((absZ)%size));
int roadStartX = (plotMinX + pathsize);
int roadStartZ = (plotMinZ + pathsize);
if (roadStartX>=size)
roadStartX-=size;
if (roadStartZ>=size)
roadStartZ-=size;
h = (prime * h) + cx;
h = (prime * h) + cz;
this.state = h;
cx = (cx % this.size) + (8 * this.size);
cz = (cz % this.size) + (8 * this.size);
int absX = (int) ((((cx * 16) + 16) - pathWidthLower - 1) + (8 * this.size));
int absZ = (int) ((((cz * 16) + 16) - pathWidthLower - 1) + (8 * this.size));
int plotMinX = (((absX) % this.size));
int plotMinZ = (((absZ) % this.size));
int roadStartX = (plotMinX + this.pathsize);
int roadStartZ = (plotMinZ + this.pathsize);
if (roadStartX >= this.size) {
roadStartX -= this.size;
}
if (roadStartZ >= this.size) {
roadStartZ -= this.size;
}
// BOTTOM (1/1 cuboids)
for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) {
setBlock(result, x, 0, z, bottom);
biomes.setBiome(x, z, biome);
setBlock(this.result, x, 0, z, this.bottom);
biomes.setBiome(x, z, this.biome);
}
}
// ROAD (0/24) The following is an inefficient placeholder as it is too much work to finish it
if (plotMinZ+1<=16||roadStartZ<=16&&roadStartZ>0) {
int start = (int) Math.max(16-plotMinZ-pathsize+1,16-roadStartZ+1);
int end = (int) Math.min(16-plotMinZ-1,16-roadStartZ+pathsize);
if (start>=0 && start<=16 && end <0)
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) {
int start = (int) Math.max(16-plotMinX-pathsize+1,16-roadStartX+1);
int end = (int) Math.min(16-plotMinX-1,16-roadStartX+pathsize);
if (start>=0 && start<=16 && end <0)
end = 16;
setCuboidRegion(Math.max(start,0), Math.min(16,end), 1, roadheight+1, 0, 16, floor1);
}
// ROAD STRIPES
if (pathsize>4&&plotworld.ROAD_STRIPES_ENABLED) {
if ((plotMinZ+2)<=16) {
int value = (plotMinZ+2);
int start,end;
if (plotMinX+2<=16)
start = 16-plotMinX-1;
else
start = 16;
if (roadStartX-1<=16)
end = 16-roadStartX+1;
else
end = 0;
if (!(plotMinX+2<=16||roadStartX-1<=16)) {
start = 0;
}
setCuboidRegion(0, end, wallheight, wallheight+1, 16-value, 16-value+1, floor2); //
setCuboidRegion(start, 16, wallheight, wallheight+1, 16-value, 16-value+1, floor2); //
}
if ((plotMinX+2)<=16) {
int value = (plotMinX+2);
int start,end;
if (plotMinZ+2<=16)
start = 16-plotMinZ-1;
else
start = 16;
if (roadStartZ-1<=16)
end = 16-roadStartZ+1;
else
end = 0;
if (!(plotMinZ+2<=16||roadStartZ-1<=16)) {
start = 0;
}
setCuboidRegion( 16-value, 16-value+1,wallheight, wallheight+1, 0, end, floor2); //
setCuboidRegion( 16-value, 16-value+1, wallheight, wallheight+1,start, 16, floor2); //
}
if (roadStartZ<=16&&roadStartZ>1) {
int val = roadStartZ;
int start,end;
if (plotMinX+2<=16)
start = 16-plotMinX-1;
else
start = 16;
if (roadStartX-1<=16)
end = 16-roadStartX+1;
else
end = 0;
if (!(plotMinX+2<=16||roadStartX-1<=16)) {
start = 0;
}
setCuboidRegion(0, end, wallheight, wallheight+1, 16-val+1, 16-val+2, floor2);
setCuboidRegion(start, 16, wallheight, wallheight+1, 16-val+1, 16-val+2, floor2);
}
if (roadStartX<=16&&roadStartX>1) {
int val = roadStartX;
int start,end;
if (plotMinZ+2<=16)
start = 16-plotMinZ-1;
else
start = 16;
if (roadStartZ-1<=16)
end = 16-roadStartZ+1;
else
end = 0;
if (!(plotMinZ+2<=16||roadStartZ-1<=16)) {
start = 0;
}
setCuboidRegion(16-val+1, 16-val+2, wallheight, wallheight+1, 0, end, floor2); //
setCuboidRegion(16-val+1, 16-val+2, wallheight, wallheight+1, start, 16, floor2); //
}
}
// Plot filling (28/28 cuboids) (10x2 + 4x2)
if (plotsize>16) {
if (roadStartX<=16) {
if (roadStartZ<=16) {
setCuboidRegion(0, 16-roadStartX, 1, plotheight, 0, 16-roadStartZ, filling);
setCuboidRegion(0, 16-roadStartX, plotheight, plotheight+1, 0, 16-roadStartZ, plotfloors);
}
if (plotMinZ<=16) {
setCuboidRegion(0, 16-roadStartX, 1, plotheight, 16-plotMinZ, 16, filling);
setCuboidRegion(0, 16-roadStartX, plotheight, plotheight+1, 16-plotMinZ, 16, plotfloors);
}
}
else {
if (roadStartZ<=16) {
if (plotMinX>16) {
setCuboidRegion(0, 16, 1, plotheight, 0, 16-roadStartZ, filling);
setCuboidRegion(0, 16, plotheight, plotheight+1, 0, 16-roadStartZ, plotfloors);
}
}
}
if (plotMinX<=16) {
if (plotMinZ<=16) {
setCuboidRegion(16-plotMinX, 16, 1, plotheight, 16-plotMinZ, 16, filling);
setCuboidRegion(16-plotMinX, 16, plotheight, plotheight+1, 16-plotMinZ, 16, plotfloors);
}
else {
int z = (int) (16-roadStartZ);
if (z<0)
z=16;
setCuboidRegion(16-plotMinX, 16, 1, plotheight, 0, z, filling);
setCuboidRegion(16-plotMinX, 16, plotheight, plotheight+1, 0, z, plotfloors);
}
if (roadStartZ<=16) {
setCuboidRegion(16-plotMinX, 16, 1, plotheight, 0, 16-roadStartZ, filling);
setCuboidRegion(16-plotMinX, 16, plotheight, plotheight+1, 0, 16-roadStartZ, plotfloors);
}
else {
if (roadStartX<=16) {
if (plotMinZ>16) {
int x = (int) (16-roadStartX);
if (x<0)
x=16;
setCuboidRegion(0, x, 1, plotheight, 0, 16, filling);
setCuboidRegion(0, x, plotheight,plotheight+1, 0, 16, plotfloors);
}
}
}
}
else {
if (plotMinZ<=16) {
if (roadStartX>16) {
int x = (int) (16-roadStartX);
if (x<0)
x=16;
setCuboidRegion(0, x, 1, plotheight, 16-plotMinZ, 16, filling);
setCuboidRegion(0, x, plotheight, plotheight+1, 16-plotMinZ, 16, plotfloors);
}
}
else {
if (roadStartZ>16) {
int x = (int) (16-roadStartX);
if (x<0)
x=16;
int z = (int) (16-roadStartZ);
if (z<0)
z=16;
if (roadStartX>16) {
setCuboidRegion(0, x, 1, plotheight, 0, z, filling);
setCuboidRegion(0, x, plotheight, plotheight+1, 0, z, plotfloors);
}
else {
setCuboidRegion(0, x, 1, plotheight, 0, z, filling);
setCuboidRegion(0, x, plotheight, plotheight+1, 0, z, plotfloors);
}
}
}
}
}
else {
if (roadStartX<=16) {
if (roadStartZ<=16) {
setCuboidRegion(0, 16-roadStartX, 1, plotheight, 0, 16-roadStartZ, filling);
setCuboidRegion(0, 16-roadStartX, plotheight, plotheight+1, 0, 16-roadStartZ, plotfloors);
}
if (plotMinZ<=16) {
setCuboidRegion(0, 16-roadStartX, 1, plotheight, 16-plotMinZ, 16, filling);
setCuboidRegion(0, 16-roadStartX, plotheight, plotheight+1, 16-plotMinZ, 16, plotfloors);
}
}
if (plotMinX<=16) {
if (plotMinZ<=16) {
setCuboidRegion(16-plotMinX, 16, 1, plotheight, 16-plotMinZ, 16, filling);
setCuboidRegion(16-plotMinX, 16, plotheight, plotheight+1, 16-plotMinZ, 16, plotfloors);
}
if (roadStartZ<=16) {
setCuboidRegion(16-plotMinX, 16, 1, plotheight, 0, 16-roadStartZ, filling);
setCuboidRegion(16-plotMinX, 16, plotheight, plotheight+1, 0, 16-roadStartZ, plotfloors);
}
}
}
// WALLS (16/16 cuboids)
if (pathsize>0) {
if (plotMinZ+1<=16) {
int start,end;
if (plotMinX+2<=16)
start = 16-plotMinX-1;
else
start = 16;
if (roadStartX-1<=16)
end = 16-roadStartX+1;
else
end = 0;
if (!(plotMinX+2<=16||roadStartX-1<=16)) {
start = 0;
}
setCuboidRegion(0, end, 1, wallheight+1, 16-plotMinZ-1, 16-plotMinZ, wallfilling);
setCuboidRegion(0, end, wallheight+1, wallheight+2, 16-plotMinZ-1, 16-plotMinZ, wall);
setCuboidRegion(start, 16, 1, wallheight+1, 16-plotMinZ-1, 16-plotMinZ, wallfilling);
setCuboidRegion(start, 16, wallheight+1, wallheight+2, 16-plotMinZ-1, 16-plotMinZ, wall);
}
if (plotMinX+1<=16) {
int start,end;
if (plotMinZ+2<=16)
start = 16-plotMinZ-1;
else
start = 16;
if (roadStartZ-1<=16)
end = 16-roadStartZ+1;
else
end = 0;
if (!(plotMinZ+2<=16||roadStartZ-1<=16)) {
start = 0;
}
setCuboidRegion( 16-plotMinX-1, 16-plotMinX, 1, wallheight+1,0, end, wallfilling);
setCuboidRegion( 16-plotMinX-1, 16-plotMinX,wallheight+1, wallheight+2, 0, end, wall);
setCuboidRegion(16-plotMinX-1, 16-plotMinX, 1, wallheight+1, start, 16, wallfilling);
setCuboidRegion( 16-plotMinX-1, 16-plotMinX, wallheight+1, wallheight+2,start, 16, wall);
}
if (roadStartZ<=16&&roadStartZ>0) {
int start,end;
if (plotMinX+1<=16)
start = 16-plotMinX;
else
start = 16;
if (roadStartX+1<=16)
end = 16-roadStartX+1;
else
end = 0;
if (!(plotMinX+1<=16||roadStartX<=16)) {
start = 0;
}
setCuboidRegion(0, end, 1, wallheight+1, 16-roadStartZ, 16-roadStartZ+1, wallfilling);
setCuboidRegion(0, end, wallheight+1, wallheight+2, 16-roadStartZ, 16-roadStartZ+1, wall);
setCuboidRegion(start, 16, 1, wallheight+1, 16-roadStartZ, 16-roadStartZ+1, wallfilling);
setCuboidRegion(start, 16, wallheight+1, wallheight+2, 16-roadStartZ, 16-roadStartZ+1, wall);
}
if (roadStartX<=16&&roadStartX>0) {
int start,end;
if (plotMinZ+1<=16)
start = 16-plotMinZ;
else
start = 16;
if (roadStartZ+1<=16)
end = 16-roadStartZ+1;
else
end = 0;
if (!(plotMinZ+1<=16||roadStartZ+1<=16)) {
start = 0;
}
setCuboidRegion( 16-roadStartX, 16-roadStartX+1, 1, wallheight+1,0, end, wallfilling);
setCuboidRegion( 16-roadStartX, 16-roadStartX+1,wallheight+1, roadheight+2,0, end, wall);
setCuboidRegion( 16-roadStartX, 16-roadStartX+1, 1, wallheight+1, start, 16,wallfilling);
setCuboidRegion( 16-roadStartX, 16-roadStartX+1,wallheight+1, wallheight+2, start, 16, wall);
}
}
return 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());
// 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))) {
int start = Math.max((16 - plotMinZ - this.pathsize) + 1, (16 - roadStartZ) + 1);
int end = Math.min(16 - plotMinZ - 1, (16 - roadStartZ) + this.pathsize);
if ((start >= 0) && (start <= 16) && (end < 0)) {
end = 16;
}
setCuboidRegion(0, 16, 1, this.roadheight + 1, Math.max(start, 0), Math.min(16, end), this.floor1);
}
if (((plotMinX + 1) <= 16) || ((roadStartX <= 16) && (roadStartX > 0))) {
int start = Math.max((16 - plotMinX - this.pathsize) + 1, (16 - roadStartX) + 1);
int end = Math.min(16 - plotMinX - 1, (16 - roadStartX) + this.pathsize);
if ((start >= 0) && (start <= 16) && (end < 0)) {
end = 16;
}
setCuboidRegion(Math.max(start, 0), Math.min(16, end), 1, this.roadheight + 1, 0, 16, this.floor1);
}
// ROAD STRIPES
if ((this.pathsize > 4) && this.plotworld.ROAD_STRIPES_ENABLED) {
if ((plotMinZ + 2) <= 16) {
int value = (plotMinZ + 2);
int start, end;
if ((plotMinX + 2) <= 16) {
start = 16 - plotMinX - 1;
} else {
start = 16;
}
if ((roadStartX - 1) <= 16) {
end = (16 - roadStartX) + 1;
} else {
end = 0;
}
if (!(((plotMinX + 2) <= 16) || ((roadStartX - 1) <= 16))) {
start = 0;
}
setCuboidRegion(0, end, this.wallheight, this.wallheight + 1, 16 - value, (16 - value) + 1, this.floor2); //
setCuboidRegion(start, 16, this.wallheight, this.wallheight + 1, 16 - value, (16 - value) + 1, this.floor2); //
}
if ((plotMinX + 2) <= 16) {
int value = (plotMinX + 2);
int start, end;
if ((plotMinZ + 2) <= 16) {
start = 16 - plotMinZ - 1;
} else {
start = 16;
}
if ((roadStartZ - 1) <= 16) {
end = (16 - roadStartZ) + 1;
} else {
end = 0;
}
if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) {
start = 0;
}
setCuboidRegion(16 - value, (16 - value) + 1, this.wallheight, this.wallheight + 1, 0, end, this.floor2); //
setCuboidRegion(16 - value, (16 - value) + 1, this.wallheight, this.wallheight + 1, start, 16, this.floor2); //
}
if ((roadStartZ <= 16) && (roadStartZ > 1)) {
int val = roadStartZ;
int start, end;
if ((plotMinX + 2) <= 16) {
start = 16 - plotMinX - 1;
} else {
start = 16;
}
if ((roadStartX - 1) <= 16) {
end = (16 - roadStartX) + 1;
} else {
end = 0;
}
if (!(((plotMinX + 2) <= 16) || ((roadStartX - 1) <= 16))) {
start = 0;
}
setCuboidRegion(0, end, this.wallheight, this.wallheight + 1, (16 - val) + 1, (16 - val) + 2, this.floor2);
setCuboidRegion(start, 16, this.wallheight, this.wallheight + 1, (16 - val) + 1, (16 - val) + 2, this.floor2);
}
if ((roadStartX <= 16) && (roadStartX > 1)) {
int val = roadStartX;
int start, end;
if ((plotMinZ + 2) <= 16) {
start = 16 - plotMinZ - 1;
} else {
start = 16;
}
if ((roadStartZ - 1) <= 16) {
end = (16 - roadStartZ) + 1;
} else {
end = 0;
}
if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) {
start = 0;
}
setCuboidRegion((16 - val) + 1, (16 - val) + 2, this.wallheight, this.wallheight + 1, 0, end, this.floor2); //
setCuboidRegion((16 - val) + 1, (16 - val) + 2, this.wallheight, this.wallheight + 1, start, 16, this.floor2); //
}
}
// Plot filling (28/28 cuboids) (10x2 + 4x2)
if (this.plotsize > 16) {
if (roadStartX <= 16) {
if (roadStartZ <= 16) {
setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 0, 16 - roadStartZ, this.filling);
setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors);
}
if (plotMinZ <= 16) {
setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 16 - plotMinZ, 16, this.filling);
setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors);
}
} else {
if (roadStartZ <= 16) {
if (plotMinX > 16) {
setCuboidRegion(0, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.filling);
setCuboidRegion(0, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors);
}
}
}
if (plotMinX <= 16) {
if (plotMinZ <= 16) {
setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 16 - plotMinZ, 16, this.filling);
setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors);
} else {
int z = 16 - roadStartZ;
if (z < 0) {
z = 16;
}
setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, z, this.filling);
setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, z, this.plotfloors);
}
if (roadStartZ <= 16) {
setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.filling);
setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors);
} else {
if (roadStartX <= 16) {
if (plotMinZ > 16) {
int x = 16 - roadStartX;
if (x < 0) {
x = 16;
}
setCuboidRegion(0, x, 1, this.plotheight, 0, 16, this.filling);
setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, 16, this.plotfloors);
}
}
}
} else {
if (plotMinZ <= 16) {
if (roadStartX > 16) {
int x = 16 - roadStartX;
if (x < 0) {
x = 16;
}
setCuboidRegion(0, x, 1, this.plotheight, 16 - plotMinZ, 16, this.filling);
setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors);
}
} else {
if (roadStartZ > 16) {
int x = 16 - roadStartX;
if (x < 0) {
x = 16;
}
int z = 16 - roadStartZ;
if (z < 0) {
z = 16;
}
if (roadStartX > 16) {
setCuboidRegion(0, x, 1, this.plotheight, 0, z, this.filling);
setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, z, this.plotfloors);
} else {
setCuboidRegion(0, x, 1, this.plotheight, 0, z, this.filling);
setCuboidRegion(0, x, this.plotheight, this.plotheight + 1, 0, z, this.plotfloors);
}
}
}
}
} else {
if (roadStartX <= 16) {
if (roadStartZ <= 16) {
setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 0, 16 - roadStartZ, this.filling);
setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors);
}
if (plotMinZ <= 16) {
setCuboidRegion(0, 16 - roadStartX, 1, this.plotheight, 16 - plotMinZ, 16, this.filling);
setCuboidRegion(0, 16 - roadStartX, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors);
}
}
if (plotMinX <= 16) {
if (plotMinZ <= 16) {
setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 16 - plotMinZ, 16, this.filling);
setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 16 - plotMinZ, 16, this.plotfloors);
}
if (roadStartZ <= 16) {
setCuboidRegion(16 - plotMinX, 16, 1, this.plotheight, 0, 16 - roadStartZ, this.filling);
setCuboidRegion(16 - plotMinX, 16, this.plotheight, this.plotheight + 1, 0, 16 - roadStartZ, this.plotfloors);
}
}
}
// WALLS (16/16 cuboids)
if (this.pathsize > 0) {
if ((plotMinZ + 1) <= 16) {
int start, end;
if ((plotMinX + 2) <= 16) {
start = 16 - plotMinX - 1;
} else {
start = 16;
}
if ((roadStartX - 1) <= 16) {
end = (16 - roadStartX) + 1;
} else {
end = 0;
}
if (!(((plotMinX + 2) <= 16) || ((roadStartX - 1) <= 16))) {
start = 0;
}
setCuboidRegion(0, end, 1, this.wallheight + 1, 16 - plotMinZ - 1, 16 - plotMinZ, this.wallfilling);
setCuboidRegion(0, end, this.wallheight + 1, this.wallheight + 2, 16 - plotMinZ - 1, 16 - plotMinZ, this.wall);
setCuboidRegion(start, 16, 1, this.wallheight + 1, 16 - plotMinZ - 1, 16 - plotMinZ, this.wallfilling);
setCuboidRegion(start, 16, this.wallheight + 1, this.wallheight + 2, 16 - plotMinZ - 1, 16 - plotMinZ, this.wall);
}
if ((plotMinX + 1) <= 16) {
int start, end;
if ((plotMinZ + 2) <= 16) {
start = 16 - plotMinZ - 1;
} else {
start = 16;
}
if ((roadStartZ - 1) <= 16) {
end = (16 - roadStartZ) + 1;
} else {
end = 0;
}
if (!(((plotMinZ + 2) <= 16) || ((roadStartZ - 1) <= 16))) {
start = 0;
}
setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, 1, this.wallheight + 1, 0, end, this.wallfilling);
setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, this.wallheight + 1, this.wallheight + 2, 0, end, this.wall);
setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, 1, this.wallheight + 1, start, 16, this.wallfilling);
setCuboidRegion(16 - plotMinX - 1, 16 - plotMinX, this.wallheight + 1, this.wallheight + 2, start, 16, this.wall);
}
if ((roadStartZ <= 16) && (roadStartZ > 0)) {
int start, end;
if ((plotMinX + 1) <= 16) {
start = 16 - plotMinX;
} else {
start = 16;
}
if ((roadStartX + 1) <= 16) {
end = (16 - roadStartX) + 1;
} else {
end = 0;
}
if (!(((plotMinX + 1) <= 16) || (roadStartX <= 16))) {
start = 0;
}
setCuboidRegion(0, end, 1, this.wallheight + 1, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wallfilling);
setCuboidRegion(0, end, this.wallheight + 1, this.wallheight + 2, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wall);
setCuboidRegion(start, 16, 1, this.wallheight + 1, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wallfilling);
setCuboidRegion(start, 16, this.wallheight + 1, this.wallheight + 2, 16 - roadStartZ, (16 - roadStartZ) + 1, this.wall);
}
if ((roadStartX <= 16) && (roadStartX > 0)) {
int start, end;
if ((plotMinZ + 1) <= 16) {
start = 16 - plotMinZ;
} else {
start = 16;
}
if ((roadStartZ + 1) <= 16) {
end = (16 - roadStartZ) + 1;
} else {
end = 0;
}
if (!(((plotMinZ + 1) <= 16) || ((roadStartZ + 1) <= 16))) {
start = 0;
}
setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, 1, this.wallheight + 1, 0, end, this.wallfilling);
setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, this.wallheight + 1, this.roadheight + 2, 0, end, this.wall);
setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, 1, this.wallheight + 1, start, 16, this.wallfilling);
setCuboidRegion(16 - roadStartX, (16 - roadStartX) + 1, this.wallheight + 1, this.wallheight + 2, start, 16, this.wall);
}
}
return this.result;
}
private void setBlock(short[][] result, int x, int y, int z, short blkid) {

View File

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

View File

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

View File

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

View File

@ -1,9 +1,7 @@
package com.intellectualcrafters.plot.commands;
import ca.mera.CameraAPI;
import ca.mera.CameraController;
import ca.mera.events.TravelEndEvent;
import com.intellectualcrafters.plot.*;
import java.util.ArrayList;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
@ -11,7 +9,16 @@ import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
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.
@ -19,41 +26,42 @@ import java.util.ArrayList;
public class Camera extends SubCommand implements Listener {
private CameraAPI api;
public Camera() {
super("camera", "plots.camera", "Go into camera mode", "camera", "c", CommandCategory.TELEPORT);
api = CameraAPI.getInstance();
travelers = new ArrayList<String>();
this.api = CameraAPI.getInstance();
this.travelers = new ArrayList<String>();
}
private ArrayList<String> travelers;
@Override
public boolean execute(Player player, String ... args) {
if(!PlayerFunctions.isInPlot(player)) {
public boolean execute(Player player, String... args) {
if (!PlayerFunctions.isInPlot(player)) {
PlayerFunctions.sendMessage(player, C.NOT_IN_PLOT);
return false;
}
api = CameraAPI.getInstance();
this.api = CameraAPI.getInstance();
Plot plot = PlotHelper.getCurrentPlot(player.getLocation());
if(api.isTravelling(player)) {
api.stopTravel(player);
if (this.api.isTravelling(player)) {
this.api.stopTravel(player);
PlayerFunctions.sendMessage(player, C.CAMERA_STOPPED);
return true;
}
api.travel(getController(player, plot));
PlayerFunctions.sendMessage(player, C.CAMERA_STARTED, plot.getId().x+";"+plot.getId().y);
travelers.add(player.getName());
this.api.travel(getController(player, plot));
PlayerFunctions.sendMessage(player, C.CAMERA_STARTED, plot.getId().x + ";" + plot.getId().y);
this.travelers.add(player.getName());
return true;
}
@EventHandler
public void onTravelEnded(TravelEndEvent event) {
if(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);
}
if(travelers.contains(event.getPlayer().getName())) {
if (this.travelers.contains(event.getPlayer().getName())) {
event.getHandlers().bake();
}
}
@ -65,7 +73,7 @@ public class Camera extends SubCommand implements Listener {
Location loc1, loc2, loc3, loc4, loc5;
double y = player.getLocation().getY();
Location bottomLoc = PlotHelper.getPlotBottomLoc(w, plot.id);
Location topLoc = PlotHelper.getPlotTopLoc(w, plot.id );
Location topLoc = PlotHelper.getPlotTopLoc(w, plot.id);
World world = bottomLoc.getWorld();
int maxX = Math.max(bottomLoc.getBlockX(), topLoc.getBlockX());
int maxZ = Math.max(bottomLoc.getBlockZ(), topLoc.getBlockZ());
@ -75,12 +83,12 @@ public class Camera extends SubCommand implements Listener {
loc2 = new Location(world, maxX, y, minZ);
loc3 = new Location(world, minX, y, minZ);
loc4 = new Location(world, minX, y, maxZ);
loc1.setYaw((3 / 4.0F * 360.0F) - 0.5F);
loc3.setYaw((1 / 4.0F * 360.0F) - 0.5F);
loc4.setYaw((2 / 4.0F * 360.0F) - 0.5F);
loc2.setYaw((0 / 4.0F * 360.0F) - 0.5F);
loc1.setYaw(((3 / 4.0F) * 360.0F) - 0.5F);
loc3.setYaw(((1 / 4.0F) * 360.0F) - 0.5F);
loc4.setYaw(((2 / 4.0F) * 360.0F) - 0.5F);
loc2.setYaw(((0 / 4.0F) * 360.0F) - 0.5F);
loc5 = loc1.clone();
CameraController controller = api.createController(player, seconds, loc1, loc2, loc3, loc4, loc5);
CameraController controller = this.api.createController(player, seconds, loc1, loc2, loc3, loc4, loc5);
return controller;
}
}

View File

@ -9,35 +9,41 @@
package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.*;
import com.intellectualcrafters.plot.events.PlayerClaimPlotEvent;
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.PlotHelper;
import com.intellectualcrafters.plot.PlotMain;
import com.intellectualcrafters.plot.PlotWorld;
import com.intellectualcrafters.plot.SchematicHandler;
import com.intellectualcrafters.plot.events.PlayerClaimPlotEvent;
/**
*
* @author Citymonstret
*
*
*/
public class Claim extends SubCommand{
public class Claim extends SubCommand {
public Claim() {
super(Command.CLAIM, "Claim the current plot you're standing on.", "claim", CommandCategory.CLAIMING);
}
@Override
public boolean execute(Player plr, String ... args) {
if(!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
return true;
}
if(PlayerFunctions.getPlayerPlotCount(plr.getWorld() , plr) >= PlayerFunctions.getAllowedPlots(plr)) {
public Claim() {
super(Command.CLAIM, "Claim the current plot you're standing on.", "claim", CommandCategory.CLAIMING);
}
@Override
public boolean execute(Player plr, String... args) {
if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
return true;
}
if (PlayerFunctions.getPlayerPlotCount(plr.getWorld(), plr) >= PlayerFunctions.getAllowedPlots(plr)) {
PlayerFunctions.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS);
return true;
}
Plot plot = PlayerFunctions.getCurrentPlot(plr);
if(plot.hasOwner()) {
Plot plot = PlayerFunctions.getCurrentPlot(plr);
if (plot.hasOwner()) {
PlayerFunctions.sendMessage(plr, C.PLOT_IS_CLAIMED);
return false;
}
@ -47,22 +53,22 @@ public class Claim extends SubCommand{
return false;
}
return true;
}
}
public static boolean claimPlot(Player player, Plot plot, boolean teleport) {
plot.clear(player);
PlayerClaimPlotEvent event = new PlayerClaimPlotEvent(player, plot);
Bukkit.getPluginManager().callEvent(event);
if(!event.isCancelled()) {
if (!event.isCancelled()) {
PlotHelper.createPlot(player, plot);
PlotHelper.setSign(player, plot);
PlayerFunctions.sendMessage(player, C.CLAIMED);
if(teleport) {
if (teleport) {
PlotMain.teleportPlayer(player, player.getLocation(), plot);
}
PlotWorld world = PlotMain.getWorldSettings(plot.getWorld());
if(world.SCHEMATIC_ON_CLAIM) {
if (world.SCHEMATIC_ON_CLAIM) {
SchematicHandler handler = new SchematicHandler();
SchematicHandler.Schematic schematic = handler.getSchematic(world.SCHEMATIC_FILE);
handler.paste(player.getLocation(), schematic, plot);

View File

@ -9,11 +9,12 @@
package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.PlotMain;
import org.bukkit.entity.Player;
import com.intellectualcrafters.plot.PlayerFunctions;
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.
@ -23,9 +24,10 @@ public class Clear extends SubCommand {
public Clear() {
super(Command.CLEAR, "Clear a plot", "clear", CommandCategory.ACTIONS);
}
@Override
public boolean execute(Player plr, String ... args) {
if(!PlayerFunctions.isInPlot(plr)) {
public boolean execute(Player plr, String... args) {
if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, "You're not in a plot.");
return true;
}
@ -34,8 +36,7 @@ public class Clear extends SubCommand {
if (result) {
DBFunc.delete(plr.getWorld().getName(), plot);
plot.clear(plr);
}
else {
} else {
PlayerFunctions.sendMessage(plr, "Plot clearing has been denied.");
}
return true;

View File

@ -11,6 +11,7 @@ package com.intellectualcrafters.plot.commands;
/**
* Created by Citymonstret on 2014-08-03.
*
* @author Citymonstret
*/
public enum Command {
@ -68,7 +69,7 @@ public enum Command {
private CommandPermission permission;
/**
*
*
* @param command
*/
Command(String command) {
@ -78,7 +79,7 @@ public enum Command {
}
/**
*
*
* @param command
* @param permission
*/
@ -89,7 +90,7 @@ public enum Command {
}
/**
*
*
* @param command
* @param alias
*/
@ -100,7 +101,7 @@ public enum Command {
}
/**
*
*
* @param Command
* @param alias
* @param permission
@ -112,7 +113,7 @@ public enum Command {
}
/**
*
*
* @return
*/
public String getCommand() {
@ -120,7 +121,7 @@ public enum Command {
}
/**
*
*
* @return
*/
public String getAlias() {
@ -128,10 +129,10 @@ public enum Command {
}
/**
*
*
* @return
*/
public CommandPermission getPermission(){
public CommandPermission getPermission() {
return this.permission;
}
}

View File

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

View File

@ -9,40 +9,44 @@
package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.*;
import org.bukkit.World;
import org.bukkit.entity.Player;
/**
* @author Citymonstret
* \\SuperCharged Compiler made by Citymonstret\\
* ||#Compiler:ALPHA-1.0#########################
* ||#ST:Java(1.7.*)\impl(bukkit)->api(s[])######
* ||#Section:\Debug\############################
* ||##Debug->Debug.properties|Debug.txt#########
* ||############################################
* ||#Signed By:Citymonstret@IC##################
* \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
*/
public class Debug extends SubCommand{
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;
//private extends SubCommand^Implements {Command, Information} from >>\\S.txt6\\
public Debug() {
super(Command.DEBUG, "Show debug information", "debug [msg]", CommandCategory.INFO);
/**
* @author Citymonstret \\SuperCharged Compiler made by Citymonstret\\
* ||#Compiler:ALPHA-1.0#########################
* ||#ST:Java(1.7.*)\impl(bukkit)->api(s[])######
* ||#Section:\Debug\############################
* ||##Debug->Debug.properties|Debug.txt#########
* ||############################################ ||#Signed
* By:Citymonstret@IC##################
* \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
*/
public class Debug extends SubCommand {
// private extends SubCommand^Implements {Command, Information} from
// >>\\S.txt6\\
public Debug() {
super(Command.DEBUG, "Show debug information", "debug [msg]", CommandCategory.INFO);
{
/**
* This.
*/
}
}
@Override
public boolean execute(Player plr, String ... args) {
PlotWorld plotworld = PlotMain.getWorldSettings(plr.getWorld());
if(args.length > 0 && args[0].equalsIgnoreCase("msg")) {
}
@Override
public boolean execute(Player plr, String... args) {
PlotMain.getWorldSettings(plr.getWorld());
if ((args.length > 0) && args[0].equalsIgnoreCase("msg")) {
StringBuilder msg = new StringBuilder();
for(C c : C.values()) {
for (C c : C.values()) {
msg.append(c.s() + "\n");
}
PlayerFunctions.sendMessage(plr, msg.toString());
@ -60,24 +64,19 @@ public class Debug extends SubCommand{
section = C.DEBUG_SECTION.s();
}
/**
* {||direct:: load: debug::I>Captions::trsl}
* \\
* if(missing) set(default) -> this->(){}
* \\
* echo line->line(Compiler.cpp -> lineCompiler);
* when finished: now = this();
* now(getter)->setter(this())->{
* "string" = getter(this);
* setter(string) = getter(this->setter);
* }
* when ^ finished compile;
* if(^compile failed -> |this->failed.|tests->failed.|
* ||run test {this->test}|on fail(action(){return FAILED})|
* {||direct:: load: debug::I>Captions::trsl} \\ if(missing)
* set(default) -> this->(){} \\ echo line->line(Compiler.cpp ->
* lineCompiler); when finished: now = this();
* now(getter)->setter(this())->{ "string" = getter(this);
* setter(string) = getter(this->setter); } when ^ finished compile;
* if(^compile failed -> |this->failed.|tests->failed.| ||run test
* {this->test}|on fail(action(){return FAILED})|
*/
{
StringBuilder worlds = new StringBuilder("");
for (String world: PlotMain.getPlotWorlds())
worlds.append(world+" ");
for (String world : PlotMain.getPlotWorlds()) {
worlds.append(world + " ");
}
information.append(header);
information.append(getSection(section, "Lag / TPS"));
information.append(getLine(line, "Ticks Per Second", Lag.getTPS()));
@ -98,20 +97,21 @@ public class Debug extends SubCommand{
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());
}
return true;
}
}
private String getSection(String line, String val) {
return line.replaceAll("%val%", val) + "\n";
}
private String getLine(String line, String var, Object val) {
return line.replaceAll("%var%", var).replaceAll("%val%", "" + val) + "\n";
}
private String getLine(String line, String var, Object val) {
return line.replaceAll("%var%", var).replaceAll("%val%", "" + val) + "\n";
}
}

View File

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

View File

@ -18,5 +18,9 @@ public class Help extends SubCommand {
public Help() {
super("help", "", "Get this help menu", "help", "he", SubCommand.CommandCategory.INFO);
}
public boolean execute(Player plr, String ... args) { return false; }
@Override
public boolean execute(Player plr, String... args) {
return false;
}
}

View File

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

View File

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

View File

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

View File

@ -9,6 +9,8 @@
package com.intellectualcrafters.plot.commands;
import java.util.ArrayList;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
@ -16,8 +18,6 @@ import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList;
public class Inventory extends SubCommand {
public Inventory() {
@ -25,19 +25,20 @@ public class Inventory extends SubCommand {
}
@Override
public boolean execute(final Player plr, String ... args) {
ArrayList<SubCommand> cmds = new ArrayList<>();
for(SubCommand cmd : MainCommand.subCommands) {
if(cmd.permission.hasPermission(plr))
cmds.add(cmd);
}
int size = 9 * (int) Math.ceil(cmds.size() / 9.0);
org.bukkit.inventory.Inventory inventory = Bukkit.createInventory(null, size, "PlotSquared Commands");
for(SubCommand cmd : cmds) {
inventory.addItem(getItem(cmd));
}
plr.openInventory(inventory);
return true;
public boolean execute(final Player plr, String... args) {
ArrayList<SubCommand> cmds = new ArrayList<>();
for (SubCommand cmd : MainCommand.subCommands) {
if (cmd.permission.hasPermission(plr)) {
cmds.add(cmd);
}
}
int size = 9 * (int) Math.ceil(cmds.size() / 9.0);
org.bukkit.inventory.Inventory inventory = Bukkit.createInventory(null, size, "PlotSquared Commands");
for (SubCommand cmd : cmds) {
inventory.addItem(getItem(cmd));
}
plr.openInventory(inventory);
return true;
}
private ItemStack getItem(final SubCommand cmd) {
@ -46,12 +47,12 @@ public class Inventory extends SubCommand {
{
meta.setDisplayName(ChatColor.GREEN + cmd.cmd + ChatColor.DARK_GRAY + " [" + ChatColor.GREEN + cmd.alias + ChatColor.DARK_GRAY + "]");
meta.setLore(new ArrayList<String>() {
{
add(ChatColor.RED + "Category: " + ChatColor.GOLD + cmd.category.toString());
add(ChatColor.RED + "Description: " + ChatColor.GOLD + cmd.description);
add(ChatColor.RED + "Usage: " + ChatColor.GOLD + "/plot " + cmd.usage);
}
});
{
add(ChatColor.RED + "Category: " + ChatColor.GOLD + cmd.category.toString());
add(ChatColor.RED + "Description: " + ChatColor.GOLD + cmd.description);
add(ChatColor.RED + "Usage: " + ChatColor.GOLD + "/plot " + cmd.usage);
}
});
}
stack.setItemMeta(meta);
return stack;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -9,12 +9,13 @@
package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.PlotMain;
import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.Settings;
import java.util.ArrayList;
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 {
@ -23,7 +24,7 @@ public class plugin extends SubCommand {
}
@Override
public boolean execute(Player plr, String ... args) {
public boolean execute(Player plr, String... args) {
ArrayList<String> strings = new ArrayList<String>() {
{
add(String.format("&c>> &6PlotSquared (Version: %s)", PlotMain.getMain().getDescription().getVersion()));
@ -31,10 +32,10 @@ public class plugin extends SubCommand {
add(String.format("&c>> &6Download at %s", Settings.URL));
}
};
for(String s : strings)
for (String s : strings) {
PlayerFunctions.sendMessage(plr, s);
}
return true;
}
}

View File

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

View File

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

View File

@ -1,13 +1,13 @@
package com.intellectualcrafters.plot.database;
import org.bukkit.plugin.Plugin;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.bukkit.plugin.Plugin;
/**
* Connects to and uses a MySQL database
*
@ -15,99 +15,93 @@ import java.sql.Statement;
* @author tips48
*/
public class MySQL extends Database {
private final String user;
private final String database;
private final String password;
private final String port;
private final String hostname;
private final String user;
private final String database;
private final String password;
private final String port;
private final String hostname;
private Connection connection;
private Connection connection;
/**
* Creates a new MySQL instance
*
* @param plugin
* Plugin instance
* @param hostname
* Name of the host
* @param port
* Port number
* @param database
* Database name
* @param username
* Username
* @param password
* Password
*/
public MySQL(Plugin plugin, String hostname, String port, String database,
String username, String password) {
super(plugin);
this.hostname = hostname;
this.port = port;
this.database = database;
this.user = username;
this.password = password;
this.connection = null;
}
/**
* Creates a new MySQL instance
*
* @param plugin
* Plugin instance
* @param hostname
* Name of the host
* @param port
* Port number
* @param database
* Database name
* @param username
* Username
* @param password
* Password
*/
public MySQL(Plugin plugin, String hostname, String port, String database, String username, String password) {
super(plugin);
this.hostname = hostname;
this.port = port;
this.database = database;
this.user = username;
this.password = password;
this.connection = null;
}
@Override
public Connection openConnection() throws SQLException,
ClassNotFoundException {
if (checkConnection()) {
return connection;
}
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://"
+ this.hostname + ":" + this.port + "/" + this.database,
this.user, this.password);
return connection;
}
@Override
public Connection openConnection() throws SQLException, ClassNotFoundException {
if (checkConnection()) {
return this.connection;
}
Class.forName("com.mysql.jdbc.Driver");
this.connection = DriverManager.getConnection("jdbc:mysql://" + this.hostname + ":" + this.port + "/" + this.database, this.user, this.password);
return this.connection;
}
@Override
public boolean checkConnection() throws SQLException {
return connection != null && !connection.isClosed();
}
@Override
public boolean checkConnection() throws SQLException {
return (this.connection != null) && !this.connection.isClosed();
}
@Override
public Connection getConnection() {
return connection;
}
@Override
public Connection getConnection() {
return this.connection;
}
@Override
public boolean closeConnection() throws SQLException {
if (connection == null) {
return false;
}
connection.close();
return true;
}
@Override
public boolean closeConnection() throws SQLException {
if (this.connection == null) {
return false;
}
this.connection.close();
return true;
}
@Override
public ResultSet querySQL(String query) throws SQLException,
ClassNotFoundException {
if (checkConnection()) {
openConnection();
}
@Override
public ResultSet querySQL(String query) throws SQLException, ClassNotFoundException {
if (checkConnection()) {
openConnection();
}
Statement statement = connection.createStatement();
Statement statement = this.connection.createStatement();
ResultSet result = statement.executeQuery(query);
ResultSet result = statement.executeQuery(query);
return result;
}
return result;
}
@Override
public int updateSQL(String query) throws SQLException,
ClassNotFoundException {
if (checkConnection()) {
openConnection();
}
@Override
public int updateSQL(String query) throws SQLException, ClassNotFoundException {
if (checkConnection()) {
openConnection();
}
Statement statement = connection.createStatement();
Statement statement = this.connection.createStatement();
int result = statement.executeUpdate(query);
int result = statement.executeUpdate(query);
return result;
}
return result;
}
}
}

View File

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

View File

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

View File

@ -9,16 +9,17 @@
package com.intellectualcrafters.plot.events;
import com.intellectualcrafters.plot.Plot;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerEvent;
import com.intellectualcrafters.plot.Plot;
/**
* Created by Citymonstret on 2014-08-09.
*/
public class PlayerClaimPlotEvent extends PlayerEvent implements Cancellable{
public class PlayerClaimPlotEvent extends PlayerEvent implements Cancellable {
private static HandlerList handlers = new HandlerList();
private boolean cancelled;
@ -28,15 +29,16 @@ public class PlayerClaimPlotEvent extends PlayerEvent implements Cancellable{
super(player);
this.plot = plot;
}
public Plot getPlot() {
return this.plot;
}
public static HandlerList getHandlerList() {
return handlers;
}
@Override
public HandlerList getHandlers() {
return handlers;
}

View File

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

View File

@ -1,11 +1,12 @@
package com.intellectualcrafters.plot.events;
import com.intellectualcrafters.plot.Plot;
import java.util.UUID;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import java.util.UUID;
import com.intellectualcrafters.plot.Plot;
/**
* Created by Citymonstret on 2014-08-16.
@ -45,4 +46,4 @@ public class PlayerPlotDeniedEvent extends Event {
public HandlerList getHandlers() {
return handlers;
}
}
}

View File

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

View File

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

View File

@ -9,19 +9,16 @@
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.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.event.player.PlayerEvent;
import com.intellectualcrafters.plot.PlotId;
/**
* Created by Citymonstret on 2014-08-09.
*/
public class PlotDeleteEvent extends Event implements Cancellable{
public class PlotDeleteEvent extends Event implements Cancellable {
private static HandlerList handlers = new HandlerList();
private boolean cancelled;
@ -32,11 +29,11 @@ public class PlotDeleteEvent extends Event implements Cancellable{
this.id = id;
this.world = world;
}
public PlotId getPlotId() {
return this.id;
}
public String getWorld() {
return this.world;
}
@ -45,6 +42,7 @@ public class PlotDeleteEvent extends Event implements Cancellable{
return handlers;
}
@Override
public HandlerList getHandlers() {
return handlers;
}

View File

@ -9,18 +9,17 @@
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.Event;
import org.bukkit.event.HandlerList;
import com.intellectualcrafters.plot.Flag;
import com.intellectualcrafters.plot.Plot;
/**
* Created by Citymonstret on 2014-08-09.
*/
public class PlotFlagAddEvent extends Event implements Cancellable{
public class PlotFlagAddEvent extends Event implements Cancellable {
private static HandlerList handlers = new HandlerList();
private boolean cancelled;
@ -31,11 +30,11 @@ public class PlotFlagAddEvent extends Event implements Cancellable{
this.plot = plot;
this.flag = flag;
}
public Plot getPlot() {
return this.plot;
}
public Flag getFlag() {
return this.flag;
}
@ -44,6 +43,7 @@ public class PlotFlagAddEvent extends Event implements Cancellable{
return handlers;
}
@Override
public HandlerList getHandlers() {
return handlers;
}

View File

@ -9,18 +9,17 @@
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.Event;
import org.bukkit.event.HandlerList;
import com.intellectualcrafters.plot.Flag;
import com.intellectualcrafters.plot.Plot;
/**
* Created by Citymonstret on 2014-08-09.
*/
public class PlotFlagRemoveEvent extends Event implements Cancellable{
public class PlotFlagRemoveEvent extends Event implements Cancellable {
private static HandlerList handlers = new HandlerList();
private boolean cancelled;
@ -31,11 +30,11 @@ public class PlotFlagRemoveEvent extends Event implements Cancellable{
this.plot = plot;
this.flag = flag;
}
public Plot getPlot() {
return this.plot;
}
public Flag getFlag() {
return this.flag;
}
@ -44,6 +43,7 @@ public class PlotFlagRemoveEvent extends Event implements Cancellable{
return handlers;
}
@Override
public HandlerList getHandlers() {
return handlers;
}

View File

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

View File

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

View File

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

View File

@ -1,20 +1,23 @@
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.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
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 org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import com.google.common.collect.ImmutableList;
/**
* @author
*/
@ -24,24 +27,25 @@ public class UUIDFetcher implements Callable<Map<String, UUID>> {
private final JSONParser jsonParser = new JSONParser();
private final List<String> names;
private final boolean rateLimiting;
public UUIDFetcher(List<String> names, boolean rateLimiting) {
this.names = ImmutableList.copyOf(names);
this.rateLimiting = rateLimiting;
}
public UUIDFetcher(List<String> names) {
this(names, true);
}
@Override
public Map<String, UUID> call() throws Exception {
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++) {
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);
JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream()));
JSONArray array = (JSONArray) this.jsonParser.parse(new InputStreamReader(connection.getInputStream()));
for (Object profile : array) {
JSONObject jsonProfile = (JSONObject) profile;
String id = (String) jsonProfile.get("id");
@ -49,20 +53,20 @@ public class UUIDFetcher implements Callable<Map<String, UUID>> {
UUID uuid = UUIDFetcher.getUUID(id);
uuidMap.put(name, uuid);
}
if (rateLimiting && i != requests - 1) {
if (this.rateLimiting && (i != (requests - 1))) {
Thread.sleep(100L);
}
}
return uuidMap;
}
private static void writeBody(HttpURLConnection connection, String body) throws Exception {
OutputStream stream = connection.getOutputStream();
stream.write(body.getBytes());
stream.flush();
stream.close();
}
private static HttpURLConnection createConnection() throws Exception {
URL url = new URL(PROFILE_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
@ -73,18 +77,18 @@ public class UUIDFetcher implements Callable<Map<String, UUID>> {
connection.setDoOutput(true);
return connection;
}
public static UUID getUUID(String id) {
return UUID.fromString(id.substring(0, 8) + "-" + id.substring(8, 12) + "-" + id.substring(12, 16) + "-" + id.substring(16, 20) + "-" +id.substring(20, 32));
return UUID.fromString(id.substring(0, 8) + "-" + id.substring(8, 12) + "-" + id.substring(12, 16) + "-" + id.substring(16, 20) + "-" + id.substring(20, 32));
}
public static byte[] toBytes(UUID uuid) {
ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]);
byteBuffer.putLong(uuid.getMostSignificantBits());
byteBuffer.putLong(uuid.getLeastSignificantBits());
return byteBuffer.array();
}
public static UUID fromBytes(byte[] array) {
if (array.length != 16) {
throw new IllegalArgumentException("Illegal byte array length: " + array.length);
@ -94,8 +98,8 @@ public class UUIDFetcher implements Callable<Map<String, UUID>> {
long leastSignificant = byteBuffer.getLong();
return new UUID(mostSignificant, leastSignificant);
}
public static UUID getUUIDOf(String name) throws Exception {
return new UUIDFetcher(Arrays.asList(name)).call().get(name);
}
}
}

View File

@ -1,17 +1,14 @@
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.util.ArrayList;
import java.util.Arrays;
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.
@ -19,55 +16,46 @@ import java.util.List;
public class IndexHandler implements Container {
private JavaPlugin plugin;
private String title;
private String title;
public IndexHandler(JavaPlugin plugin, String title) {
this.plugin = plugin;
this.title = title;
this.title = title;
}
@Override
public void handle(Request request, Response response) {
try {
PrintStream body;
long time;
Query query;
Path path;
int page;
String coverage;
long time;
String coverage;
body = response.getPrintStream();
time = System.currentTimeMillis();
query = request.getQuery();
path = request.getPath();
body = response.getPrintStream();
time = System.currentTimeMillis();
request.getQuery();
request.getPath();
if((page = request.getInteger("page")) < 0) {
page = 0;
if ((request.getInteger("page")) < 0) {
}
if((coverage = request.getTarget()) == null || coverage.equals("/")) {
if (((coverage = request.getTarget()) == null) || coverage.equals("/")) {
coverage = "index";
}
coverage = coverage.toLowerCase();
List<String> list = new ArrayList<>(
Arrays.asList(new String[] {
"install",
"index",
"stylesheet"
})
);
List<String> list = new ArrayList<>(Arrays.asList(new String[] { "install", "index", "stylesheet" }));
if(!list.contains(coverage)) {
if (!list.contains(coverage)) {
coverage = "index";
}
if(coverage.equals("stylesheet")) {
if (coverage.equals("stylesheet")) {
response.setValue("Content-Type", "text/css");
response.setValue("Server", "PlotWeb/1.0 (Simple 5.0)");
response.setDate("Date", time);
response.setDate("Last-Modified", time);
ResourceHandler stylesheet = new ResourceHandler("stylesheet", ResourceHandler.FileType.CSS, plugin.getDataFolder());
ResourceHandler stylesheet = new ResourceHandler("stylesheet", ResourceHandler.FileType.CSS, this.plugin.getDataFolder());
String stylesheetHTML = stylesheet.getHTML();
@ -80,11 +68,11 @@ public class IndexHandler implements Container {
response.setDate("Date", time);
response.setDate("Last-Modified", time);
ResourceHandler header = new ResourceHandler("header", ResourceHandler.FileType.HTML, plugin.getDataFolder());
ResourceHandler footer = new ResourceHandler("footer", ResourceHandler.FileType.HTML, plugin.getDataFolder());
ResourceHandler cPage = new ResourceHandler(coverage, ResourceHandler.FileType.HTML, plugin.getDataFolder());
ResourceHandler header = new ResourceHandler("header", ResourceHandler.FileType.HTML, this.plugin.getDataFolder());
ResourceHandler footer = new ResourceHandler("footer", ResourceHandler.FileType.HTML, this.plugin.getDataFolder());
ResourceHandler cPage = new ResourceHandler(coverage, ResourceHandler.FileType.HTML, this.plugin.getDataFolder());
String headerHTML = header.getHTML().replace("@title", title);
String headerHTML = header.getHTML().replace("@title", this.title);
String footerHTML = footer.getHTML();
String cPageHTML = cPage.getHTML();
@ -97,8 +85,8 @@ public class IndexHandler implements Container {
body.print(footerHTML);
}
body.close();
} catch(Exception e) {
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

View File

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

View File

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

View File

@ -8,9 +8,9 @@ public class Test {
public static void main(String[] args) {
try {
new PlotWeb("Test", 9000).start();
} catch(Exception e) {
} catch (Exception e) {
e.printStackTrace();
}
}
}
}