Code cleanup. Made use of some Java8 features. Renamed PlayerManager#isAKnownPlayer() to PlayerManager#isKnown()

This commit is contained in:
Poslovitch 2017-08-18 16:05:35 +02:00
parent 55101f7ff2
commit 4943c89c42
62 changed files with 1219 additions and 1417 deletions

View File

@ -45,7 +45,7 @@ public class BSkyBlock extends JavaPlugin{
private static BSkyBlock plugin; private static BSkyBlock plugin;
private HashMap<String, BSBLocale> locales = new HashMap<String, BSBLocale>(); private HashMap<String, BSBLocale> locales = new HashMap<>();
// Databases // Databases
private PlayersManager playersManager; private PlayersManager playersManager;
@ -165,7 +165,7 @@ public class BSkyBlock extends JavaPlugin{
plugin = null; plugin = null;
} }
private void registerCustomCharts(){ private void registerCustomCharts(){
metrics.addCustomChart(new Metrics.SingleLineChart("islands_count") { metrics.addCustomChart(new Metrics.SingleLineChart("islands_count") {
@Override @Override
@ -293,7 +293,7 @@ public class BSkyBlock extends JavaPlugin{
} }
} }
// Store all the locales available // Store all the locales available
for (String language : localeDir.list(ymlFilter)) { for (String language : localeDir.list(ymlFilter)) {
try { try {
BSBLocale locale = new BSBLocale(this, language); BSBLocale locale = new BSBLocale(this, language);
locales.put(locale.getLocaleId(), locale); locales.put(locale.getLocaleId(), locale);

View File

@ -53,7 +53,7 @@ public abstract class AbstractCommand implements CommandExecutor, TabCompleter {
this.label = label; this.label = label;
this.aliases = aliases; this.aliases = aliases;
this.help = help; this.help = help;
this.teamMembers = new HashSet<UUID>(); this.teamMembers = new HashSet<>();
// Register the help argument if needed // Register the help argument if needed
if (help) { if (help) {
@ -120,8 +120,8 @@ public abstract class AbstractCommand implements CommandExecutor, TabCompleter {
String[] usage = argumentsMap.get(command).usage(sender); String[] usage = argumentsMap.get(command).usage(sender);
if (usage == null) usage = new String[2]; if (usage == null) usage = new String[2];
msg = msg.replace("[args]", (usage != null && usage[0] != null) ? usage[0] : "") msg = msg.replace("[args]", (usage[0] != null) ? usage[0] : "")
.replace("[info]", (usage != null && usage[1] != null) ? usage[1] : ""); .replace("[info]", (usage[1] != null) ? usage[1] : "");
return msg; return msg;
} }
@ -150,8 +150,7 @@ public abstract class AbstractCommand implements CommandExecutor, TabCompleter {
} }
public boolean isAlias(String argument) { public boolean isAlias(String argument) {
if (aliasesMap.containsValue(argument)) return true; return aliasesMap.containsValue(argument);
return false;
} }
public void addAliases(String parent, String... aliases) { public void addAliases(String parent, String... aliases) {
@ -220,7 +219,7 @@ public abstract class AbstractCommand implements CommandExecutor, TabCompleter {
@Override @Override
public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args){ public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args){
List<String> options = new ArrayList<String>(); List<String> options = new ArrayList<>();
checkForPlayer(sender); checkForPlayer(sender);
String lastArg = (args.length != 0 ? args[args.length - 1] : ""); String lastArg = (args.length != 0 ? args[args.length - 1] : "");
if (canUse(sender).isAllowed()) { if (canUse(sender).isAllowed()) {
@ -243,11 +242,11 @@ public abstract class AbstractCommand implements CommandExecutor, TabCompleter {
} }
private static String[] clean(final String[] v) { private static String[] clean(final String[] v) {
List<String> list = new ArrayList<String>(Arrays.asList(v)); List<String> list = new ArrayList<>(Arrays.asList(v));
list.removeAll(Collections.singleton("")); list.removeAll(Collections.singleton(""));
return list.toArray(new String[list.size()]); return list.toArray(new String[list.size()]);
} }
/** /**
* Sets some variables and flags if this is a player * Sets some variables and flags if this is a player
* @param sender * @param sender
@ -269,9 +268,9 @@ public abstract class AbstractCommand implements CommandExecutor, TabCompleter {
} else { } else {
inTeam = false; inTeam = false;
} }
} }
/** /**
* Response class for the canUse check * Response class for the canUse check
* @author tastybento * @author tastybento
@ -280,7 +279,7 @@ public abstract class AbstractCommand implements CommandExecutor, TabCompleter {
public class CanUseResp { public class CanUseResp {
private boolean allowed; private boolean allowed;
private String errorResponse; // May be shown if required private String errorResponse; // May be shown if required
/** /**
* Cannot use situation * Cannot use situation
* @param errorResponse - error response * @param errorResponse - error response
@ -289,7 +288,7 @@ public abstract class AbstractCommand implements CommandExecutor, TabCompleter {
this.allowed = false; this.allowed = false;
this.errorResponse = errorResponse; this.errorResponse = errorResponse;
} }
/** /**
* Can or cannot use situation, no error response. * Can or cannot use situation, no error response.
* @param b * @param b
@ -321,7 +320,7 @@ public abstract class AbstractCommand implements CommandExecutor, TabCompleter {
*/ */
public void setErrorResponse(String errorResponse) { public void setErrorResponse(String errorResponse) {
this.errorResponse = errorResponse; this.errorResponse = errorResponse;
} }
} }
// These methods below just neaten up the code in the commands so "plugin." isn't always used // These methods below just neaten up the code in the commands so "plugin." isn't always used
/** /**

View File

@ -5,7 +5,7 @@ import org.bukkit.event.HandlerList;
/** /**
* Fired when BSkyBlock is ready to play and all files are loaded * Fired when BSkyBlock is ready to play and all files are loaded
* *
* @author tastybento * @author tastybento
* @since 1.0 * @since 1.0
*/ */

View File

@ -14,23 +14,23 @@ import us.tastybento.bskyblock.database.objects.Island;
public class IslandEvent extends Event implements Cancellable{ public class IslandEvent extends Event implements Cancellable{
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
private boolean cancelled; private boolean cancelled;
private final Island island; private final Island island;
/** /**
* @param island * @param island
*/ */
public IslandEvent(Island island){ public IslandEvent(Island island){
this.island = island; this.island = island;
} }
/** /**
* @return the island involved in this event * @return the island involved in this event
*/ */
public Island getIsland(){ public Island getIsland(){
return this.island; return this.island;
} }
@Override @Override
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
@ -39,7 +39,7 @@ public class IslandEvent extends Event implements Cancellable{
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
@Override @Override
public boolean isCancelled() { public boolean isCancelled() {
return cancelled; return cancelled;

View File

@ -7,7 +7,7 @@ import us.tastybento.bskyblock.database.objects.Island;
/** /**
* Fired when the owner of an island changes * Fired when the owner of an island changes
* *
* @author Poslovitch * @author Poslovitch
* @version 1.0 * @version 1.0
*/ */

View File

@ -9,7 +9,7 @@ import us.tastybento.bskyblock.database.objects.Island;
/** /**
* Fired when a player enters an island's area * Fired when a player enters an island's area
* *
* @author tastybento * @author tastybento
* @since 1.0 * @since 1.0
*/ */

View File

@ -9,7 +9,7 @@ import us.tastybento.bskyblock.database.objects.Island;
/** /**
* Fired when a player exits an island's protected area * Fired when a player exits an island's protected area
* *
* @author tastybento * @author tastybento
* @since 1.0 * @since 1.0
*/ */

View File

@ -7,7 +7,7 @@ import us.tastybento.bskyblock.database.objects.Island;
/** /**
* Fired when a player joins an existing island. * Fired when a player joins an existing island.
* *
* @author tastybento * @author tastybento
* @since 1.0 * @since 1.0
*/ */

View File

@ -7,7 +7,7 @@ import us.tastybento.bskyblock.database.objects.Island;
/** /**
* Fired when a player leaves an existing island. * Fired when a player leaves an existing island.
* *
* @author tastybento * @author tastybento
* @since 1.0 * @since 1.0
*/ */

View File

@ -9,7 +9,7 @@ import us.tastybento.bskyblock.database.objects.Island;
* This event is fired when an island is going to be locked. * This event is fired when an island is going to be locked.
* <p> * <p>
* Cancelling this event will result in keeping the island unlocked. * Cancelling this event will result in keeping the island unlocked.
* *
* @author Poslovitch * @author Poslovitch
* @since 1.0 * @since 1.0
*/ */

View File

@ -7,7 +7,7 @@ import us.tastybento.bskyblock.database.objects.Island;
/** /**
* This event is fired when a player resets an island * This event is fired when a player resets an island
* *
* @author tastybento * @author tastybento
* @since 1.0 * @since 1.0
*/ */

View File

@ -9,7 +9,7 @@ import us.tastybento.bskyblock.database.objects.Island;
* This event is fired when an island is going to be unlocked. * This event is fired when an island is going to be unlocked.
* <p> * <p>
* Cancelling this event will result in keeping the island locked. * Cancelling this event will result in keeping the island locked.
* *
* @author Poslovitch * @author Poslovitch
* @since 1.0 * @since 1.0
*/ */

View File

@ -10,7 +10,7 @@ import us.tastybento.bskyblock.database.objects.Island.SettingsFlag;
* This event is fired when a player changes a setting on his island * This event is fired when a player changes a setting on his island
* <p> * <p>
* Canceling this event will result in canceling the change. * Canceling this event will result in canceling the change.
* *
* @author Poslovitch * @author Poslovitch
* @since 1.0 * @since 1.0
*/ */

View File

@ -6,7 +6,7 @@ import us.tastybento.bskyblock.database.objects.Island;
/** /**
* This event is fired before an island is going to be purged. * This event is fired before an island is going to be purged.
* Canceling this event will prevent the plugin to remove the island. * Canceling this event will prevent the plugin to remove the island.
* *
* @author Poslovitch * @author Poslovitch
* @since 1.0 * @since 1.0
*/ */

View File

@ -11,7 +11,7 @@ import org.bukkit.event.HandlerList;
* This event is fired when islands to remove have been chosen and before starting to remove them. * This event is fired when islands to remove have been chosen and before starting to remove them.
* You can remove or add islands to remove. * You can remove or add islands to remove.
* Canceling this event will cancel the purge * Canceling this event will cancel the purge
* *
* @author Poslovitch * @author Poslovitch
* @since 1.0 * @since 1.0
*/ */

View File

@ -7,7 +7,7 @@ import us.tastybento.bskyblock.database.objects.Island;
/** /**
* Fired when a player joins an island team as a coop member * Fired when a player joins an island team as a coop member
* *
* @author tastybento * @author tastybento
* @since 1.0 * @since 1.0
*/ */
@ -24,7 +24,7 @@ public class CoopJoinEvent extends IslandEvent {
this.player = player; this.player = player;
this.inviter = inviter; this.inviter = inviter;
} }
/** /**
* The UUID of the player who were coop'd * The UUID of the player who were coop'd
* @return the coop'd * @return the coop'd
@ -32,7 +32,7 @@ public class CoopJoinEvent extends IslandEvent {
public UUID getPlayer() { public UUID getPlayer() {
return player; return player;
} }
/** /**
* The UUID of the player who invited the player to join the island * The UUID of the player who invited the player to join the island
* @return the inviter * @return the inviter

View File

@ -7,7 +7,7 @@ import us.tastybento.bskyblock.database.objects.Island;
/** /**
* Fired when a player leaves an island coop * Fired when a player leaves an island coop
* *
* @author tastybento * @author tastybento
* @since 1.0 * @since 1.0
*/ */
@ -26,7 +26,7 @@ public class CoopLeaveEvent extends IslandEvent {
this.player = player; this.player = player;
this.expeller = expeller; this.expeller = expeller;
} }
/** /**
* The UUID of the player who left * The UUID of the player who left
* @return the player who left the coop * @return the player who left the coop
@ -34,7 +34,7 @@ public class CoopLeaveEvent extends IslandEvent {
public UUID getPlayer() { public UUID getPlayer() {
return player; return player;
} }
/** /**
* @return the expelling player * @return the expelling player
*/ */

View File

@ -11,29 +11,29 @@ import org.bukkit.event.HandlerList;
* @since 1.0 * @since 1.0
*/ */
public class PlayerAcceptInviteEvent extends Event { public class PlayerAcceptInviteEvent extends Event {
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
private final Player player; private final Player player;
/** /**
* @param player * @param player
*/ */
public PlayerAcceptInviteEvent(Player player) { public PlayerAcceptInviteEvent(Player player) {
this.player = player; this.player = player;
} }
/** /**
* @return the player * @return the player
*/ */
public Player getPlayer() { public Player getPlayer() {
return this.player; return this.player;
} }
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() { @Override
return handlers; public HandlerList getHandlers() {
} return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
} }

View File

@ -28,29 +28,29 @@ import org.bukkit.event.HandlerList;
* @since 1.0 * @since 1.0
*/ */
public class PlayerRejectInviteEvent extends Event { public class PlayerRejectInviteEvent extends Event {
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
private final Player player; private final Player player;
/** /**
* @param player * @param player
*/ */
public PlayerRejectInviteEvent(Player player) { public PlayerRejectInviteEvent(Player player) {
this.player = player; this.player = player;
} }
/** /**
* @return the player * @return the player
*/ */
public Player getPlayer() { public Player getPlayer() {
return this.player; return this.player;
} }
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() { @Override
return handlers; public HandlerList getHandlers() {
} return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
} }

View File

@ -7,14 +7,14 @@ import us.tastybento.bskyblock.database.objects.Island;
/** /**
* This event is fired when a player talks in TeamChat * This event is fired when a player talks in TeamChat
* *
* @author Poslovitch * @author Poslovitch
* @since 1.0 * @since 1.0
*/ */
public class TeamChatEvent extends IslandEvent { public class TeamChatEvent extends IslandEvent {
private final UUID player; private final UUID player;
private String message; private String message;
/** /**
* @param island * @param island
* @param player * @param player
@ -25,14 +25,14 @@ public class TeamChatEvent extends IslandEvent {
this.player = player; this.player = player;
this.message = message; this.message = message;
} }
/** /**
* @return the player who talked * @return the player who talked
*/ */
public UUID getPlayer() { public UUID getPlayer() {
return player; return player;
} }
/** /**
* Gets the message that the player is attempting to send. * Gets the message that the player is attempting to send.
* @return the message * @return the message
@ -40,10 +40,10 @@ public class TeamChatEvent extends IslandEvent {
public String getMessage() { public String getMessage() {
return this.message; return this.message;
} }
/** /**
* Sets the message that the player will send. * Sets the message that the player will send.
* @param the message to send * @param message the message to send
*/ */
public void setMessage(String message) { public void setMessage(String message) {
this.message = message; this.message = message;

View File

@ -9,7 +9,7 @@ import us.tastybento.bskyblock.api.commands.AbstractCommand;
import us.tastybento.bskyblock.config.Settings; import us.tastybento.bskyblock.config.Settings;
public class AdminCommand extends AbstractCommand { public class AdminCommand extends AbstractCommand {
BSkyBlock plugin; BSkyBlock plugin;
public AdminCommand(BSkyBlock plugin) { public AdminCommand(BSkyBlock plugin) {
@ -26,7 +26,6 @@ public class AdminCommand extends AbstractCommand {
@Override @Override
public CanUseResp canUse(CommandSender sender) { public CanUseResp canUse(CommandSender sender) {
// TODO Auto-generated method stub
return new CanUseResp(true); return new CanUseResp(true);
} }
@ -37,7 +36,6 @@ public class AdminCommand extends AbstractCommand {
@Override @Override
public Set<String> tabComplete(CommandSender sender, String[] args) { public Set<String> tabComplete(CommandSender sender, String[] args) {
// TODO Auto-generated method stub
return null; return null;
} }
@ -46,19 +44,18 @@ public class AdminCommand extends AbstractCommand {
return new String[] {null, plugin.getLocale(sender).get("help.admin.delete")}; return new String[] {null, plugin.getLocale(sender).get("help.admin.delete")};
} }
}); });
} }
@Override @Override
public CanUseResp canUse(CommandSender sender) { public CanUseResp canUse(CommandSender sender) {
// TODO Auto-generated method stub
return new CanUseResp(true); return new CanUseResp(true);
} }
@Override @Override
public void execute(CommandSender sender, String[] args) { public void execute(CommandSender sender, String[] args) {
} }
} }

View File

@ -43,15 +43,15 @@ public class IslandCommand extends AbstractCommand {
*/ */
private final BiMap<UUID, UUID> inviteList = HashBiMap.create(); private final BiMap<UUID, UUID> inviteList = HashBiMap.create();
// The time a player has to wait until they can reset their island again // The time a player has to wait until they can reset their island again
private HashMap<UUID, Long> resetWaitTime = new HashMap<UUID, Long>(); private HashMap<UUID, Long> resetWaitTime = new HashMap<>();
protected Set<UUID> leavingPlayers = new HashSet<UUID>(); protected Set<UUID> leavingPlayers = new HashSet<>();
public IslandCommand(BSkyBlock plugin) { public IslandCommand(BSkyBlock plugin) {
super(plugin, Settings.ISLANDCOMMAND, new String[]{"is"}, true); super(plugin, Settings.ISLANDCOMMAND, new String[]{"is"}, true);
plugin.getCommand(Settings.ISLANDCOMMAND).setExecutor(this); plugin.getCommand(Settings.ISLANDCOMMAND).setExecutor(this);
plugin.getCommand(Settings.ISLANDCOMMAND).setTabCompleter(this); plugin.getCommand(Settings.ISLANDCOMMAND).setTabCompleter(this);
this.plugin = plugin; this.plugin = plugin;
} }
@Override @Override
public CanUseResp canUse(CommandSender sender) { public CanUseResp canUse(CommandSender sender) {
@ -466,9 +466,7 @@ public class IslandCommand extends AbstractCommand {
} }
} }
// Do some sanity checking // Do some sanity checking
if (maxSize < 1) { if (maxSize < 1) maxSize = 1;
maxSize = 1;
}
} }
if (teamMembers.size() < maxSize) { if (teamMembers.size() < maxSize) {
Util.sendMessage(player, ChatColor.GREEN + getLocale(sender).get("invite.youCanInvite").replace("[number]", String.valueOf(maxSize - teamMembers.size()))); Util.sendMessage(player, ChatColor.GREEN + getLocale(sender).get("invite.youCanInvite").replace("[number]", String.valueOf(maxSize - teamMembers.size())));
@ -513,7 +511,7 @@ public class IslandCommand extends AbstractCommand {
if (!getPlayers().hasIsland(playerUUID)) { if (!getPlayers().hasIsland(playerUUID)) {
// If the player is in a team, they are not the leader // If the player is in a team, they are not the leader
if (getPlayers().inTeam(playerUUID)) { if (getPlayers().inTeam(playerUUID)) {
return new CanUseResp(ChatColor.RED + getLocale(sender).get("general.errors.not-leader")); return new CanUseResp(ChatColor.RED + getLocale(sender).get("general.errors.not-leader"));
} }
return new CanUseResp(ChatColor.RED + getLocale(sender).get("invite.error.YouMustHaveIslandToInvite")); return new CanUseResp(ChatColor.RED + getLocale(sender).get("invite.error.YouMustHaveIslandToInvite"));
} }
@ -580,9 +578,7 @@ public class IslandCommand extends AbstractCommand {
} }
} }
// Do some sanity checking // Do some sanity checking
if (maxSize < 1) { if (maxSize < 1) maxSize = 1;
maxSize = 1;
}
} }
if (teamMembers.size() < maxSize) { if (teamMembers.size() < maxSize) {
// If that player already has an invite out then retract it. // If that player already has an invite out then retract it.
@ -648,7 +644,6 @@ public class IslandCommand extends AbstractCommand {
} else { } else {
Util.sendMessage(player, ChatColor.RED + getLocale(sender).get("island.help.invite")); Util.sendMessage(player, ChatColor.RED + getLocale(sender).get("island.help.invite"));
} }
return;
} }
@Override @Override
@ -687,18 +682,15 @@ public class IslandCommand extends AbstractCommand {
if (Settings.leaveConfirmation && !leavingPlayers.contains(playerUUID)) { if (Settings.leaveConfirmation && !leavingPlayers.contains(playerUUID)) {
leavingPlayers.add(playerUUID); leavingPlayers.add(playerUUID);
Util.sendMessage(player, ChatColor.RED + getLocale(sender).get("leave.Warning")); Util.sendMessage(player, ChatColor.RED + getLocale(sender).get("leave.Warning"));
new BukkitRunnable() {
@Override plugin.getServer().getScheduler().runTaskLater(plugin, () -> {
public void run() { // If the player is still on the list, remove them and cancel the leave
// If the player is still on the list, remove them and cancel the leave if (leavingPlayers.contains(playerUUID)) {
if (leavingPlayers.contains(playerUUID)) { leavingPlayers.remove(playerUUID);
leavingPlayers.remove(playerUUID); Util.sendMessage(player, ChatColor.RED + getLocale(sender).get("leave.Canceled"));
Util.sendMessage(player, ChatColor.RED + getLocale(sender).get("leave.Canceled"));
}
} }
}, Settings.leaveConfirmWait * 20L);
}.runTaskLater(plugin, Settings.leaveConfirmWait * 20L);
return; return;
} }
// Remove from confirmation list // Remove from confirmation list
@ -804,7 +796,7 @@ public class IslandCommand extends AbstractCommand {
if (!getIslands().hasIsland(prospectiveTeamLeaderUUID)) { if (!getIslands().hasIsland(prospectiveTeamLeaderUUID)) {
Util.sendMessage(player, ChatColor.RED + getLocale(sender).get("invite.error.InvalidInvite")); Util.sendMessage(player, ChatColor.RED + getLocale(sender).get("invite.error.InvalidInvite"));
inviteList.remove(playerUUID); inviteList.remove(playerUUID);
return; return;
} }
if (DEBUG) if (DEBUG)
plugin.getLogger().info("DEBUG: Invite is valid"); plugin.getLogger().info("DEBUG: Invite is valid");
@ -831,7 +823,7 @@ public class IslandCommand extends AbstractCommand {
setResetWaitTime(player); setResetWaitTime(player);
if (Settings.teamJoinDeathReset) { if (Settings.teamJoinDeathReset) {
getPlayers().setDeaths(player.getUniqueId(), 0); getPlayers().setDeaths(playerUUID, 0);
} }
if (DEBUG) if (DEBUG)
plugin.getLogger().info("DEBUG: Setting home. team leader's home is " + getPlayers().getHomeLocation(prospectiveTeamLeaderUUID)); plugin.getLogger().info("DEBUG: Setting home. team leader's home is " + getPlayers().getHomeLocation(prospectiveTeamLeaderUUID));
@ -1404,7 +1396,7 @@ public class IslandCommand extends AbstractCommand {
* @param player * @param player
*/ */
private void setResetWaitTime(final Player player) { private void setResetWaitTime(final Player player) {
resetWaitTime.put(player.getUniqueId(), Long.valueOf(Calendar.getInstance().getTimeInMillis() + Settings.resetWait * 1000)); resetWaitTime.put(player.getUniqueId(), Calendar.getInstance().getTimeInMillis() + Settings.resetWait * 1000);
} }
/** /**

View File

@ -68,33 +68,33 @@ public class BSBLocale {
plugin.getLogger().severe(reference + " not found in " + languageTag + " or default lang " + Settings.defaultLanguage); plugin.getLogger().severe(reference + " not found in " + languageTag + " or default lang " + Settings.defaultLanguage);
return reference; // Return reference for debug purposes, like for the mods. return reference; // Return reference for debug purposes, like for the mods.
} }
/** /**
* Returns the locale language * Returns the locale language
* @return the locale language * @return the locale language
*/ */
public String getLanguageName(){ public String getLanguageName(){
if(localeObject == null) return "unknown"; if(localeObject == null) return "unknown";
return localeObject.getDisplayLanguage(localeObject); return localeObject.getDisplayLanguage(localeObject);
} }
/** /**
* Returns the locale country * Returns the locale country
* @return the locale country * @return the locale country
*/ */
public String getCountryName(){ public String getCountryName(){
if(localeObject == null) return "unknown"; if(localeObject == null) return "unknown";
return localeObject.getDisplayCountry(localeObject); return localeObject.getDisplayCountry(localeObject);
} }
/** /**
* Returns the locale identifier (e.g: en-GB) * Returns the locale identifier (e.g: en-GB)
* @return the locale ID * @return the locale ID
*/ */
public String getLocaleId(){ public String getLocaleId(){
return this.localeObject.toLanguageTag(); return this.localeObject.toLanguageTag();
} }
} }

View File

@ -11,7 +11,7 @@ import us.tastybento.bskyblock.BSkyBlock;
/** /**
* This class runs when the config file is not set up enough, or is unsafe. * This class runs when the config file is not set up enough, or is unsafe.
* It provides useful information to the admin on what is wrong. * It provides useful information to the admin on what is wrong.
* *
* @author Tastybento * @author Tastybento
* @author Poslovitch * @author Poslovitch
*/ */
@ -30,7 +30,7 @@ public class NotSetup implements CommandExecutor{
ISLAND_HEIGHT_TOO_LOW(3, 304), ISLAND_HEIGHT_TOO_LOW(3, 304),
NETHER_SPAWN_RADIUS_TOO_LOW(3, 305), NETHER_SPAWN_RADIUS_TOO_LOW(3, 305),
NETHER_SPAWN_RADIUS_TOO_HIGH(3, 306); NETHER_SPAWN_RADIUS_TOO_HIGH(3, 306);
/* /*
* Priority: * Priority:
* 0 - CRITICAL * 0 - CRITICAL
@ -45,7 +45,7 @@ public class NotSetup implements CommandExecutor{
this.priority = priority; this.priority = priority;
this.id = id; this.id = id;
} }
public static ConfigError getById(int id){ public static ConfigError getById(int id){
for(ConfigError e : ConfigError.values()){ for(ConfigError e : ConfigError.values()){
if(e.id == id) return e; if(e.id == id) return e;
@ -53,13 +53,13 @@ public class NotSetup implements CommandExecutor{
return null; return null;
} }
} }
private BSkyBlock plugin; private BSkyBlock plugin;
private List<Error> errors; private List<Error> errors;
/** /**
* Handles plugin operation if a critical config-related issue happened * Handles plugin operation if a critical config-related issue happened
* *
* @param plugin * @param plugin
* @param errors * @param errors
*/ */
@ -67,10 +67,10 @@ public class NotSetup implements CommandExecutor{
this.plugin = plugin; this.plugin = plugin;
this.errors = errors; this.errors = errors;
} }
@Override @Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
return true; return true;
} }
} }

View File

@ -25,7 +25,7 @@ public class PluginConfig {
plugin.saveDefaultConfig(); plugin.saveDefaultConfig();
// Initialize the errors list // Initialize the errors list
HashMap<ConfigError, Object> errors = new HashMap<ConfigError, Object>(); HashMap<ConfigError, Object> errors = new HashMap<>();
//TODO config version //TODO config version
@ -116,8 +116,8 @@ public class PluginConfig {
// TODO: add to config // TODO: add to config
Settings.endGenerate = true; Settings.endGenerate = true;
Settings.endIslands = false; Settings.endIslands = false;
Settings.limitedBlocks = new HashMap<String, Integer>(); Settings.limitedBlocks = new HashMap<>();
Settings.defaultWorldSettings = new HashMap<SettingsFlag, Boolean>(); Settings.defaultWorldSettings = new HashMap<>();
for (SettingsFlag flag: SettingsFlag.values()) { for (SettingsFlag flag: SettingsFlag.values()) {
Settings.defaultWorldSettings.put(flag, false); Settings.defaultWorldSettings.put(flag, false);
} }

View File

@ -14,7 +14,6 @@
*/ */
package us.tastybento.bskyblock.config; package us.tastybento.bskyblock.config;
import static java.util.Arrays.asList; import static java.util.Arrays.asList;
import static java.util.Collections.enumeration; import static java.util.Collections.enumeration;
import static java.util.Collections.unmodifiableList; import static java.util.Collections.unmodifiableList;
@ -86,14 +85,14 @@ public class YamlResourceBundle extends ResourceBundle {
e -> e.getKey(), e -> e.getKey(),
e -> e.getValue(), e -> e.getValue(),
(oldValue, newValue) -> newValue (oldValue, newValue) -> newValue
)); ));
} }
/** /**
* Flatten yaml tree structure. * Flatten yaml tree structure.
* *
* @param entry {@link Entry} of yaml tree. * @param entry {@link Entry} of yaml tree.
* @return {@link Stream} of entries. * @return {@link Stream} of entries
*/ */
private static Stream<Entry<String, Object>> flattenYamlTree(Entry<?, ?> entry) { private static Stream<Entry<String, Object>> flattenYamlTree(Entry<?, ?> entry) {
String key = entry.getKey().toString(); String key = entry.getKey().toString();
@ -110,8 +109,8 @@ public class YamlResourceBundle extends ResourceBundle {
return Stream.concat( return Stream.concat(
Stream.of(new SimpleImmutableEntry<>(key, value)), Stream.of(new SimpleImmutableEntry<>(key, value)),
valueAsList.stream() valueAsList.stream()
.map(v -> new SimpleImmutableEntry<>(key + "[" + index.getAndIncrement() + "]", v)) .map(v -> new SimpleImmutableEntry<>(key + "[" + index.getAndIncrement() + "]", v))
); );
} }
return Stream.of(new SimpleImmutableEntry<>(key, value)); return Stream.of(new SimpleImmutableEntry<>(key, value));
} }
@ -159,8 +158,8 @@ public class YamlResourceBundle extends ResourceBundle {
/** {@inheritDoc} */ /** {@inheritDoc} */
@Override @Override
public ResourceBundle newBundle(String baseName, public ResourceBundle newBundle(String baseName,
Locale locale, String format, ClassLoader loader, boolean reload) Locale locale, String format, ClassLoader loader, boolean reload)
throws IllegalAccessException, InstantiationException, IOException { throws IllegalAccessException, InstantiationException, IOException {
if (!getFormats(baseName).contains(format)) { if (!getFormats(baseName).contains(format)) {
return null; return null;
} }

View File

@ -12,7 +12,7 @@ public abstract class BSBDatabase {
/** /**
* Gets the type of database being used. Currently supported options are * Gets the type of database being used. Currently supported options are
* FLATFILE, MYSQL and SQLITE. Default is FLATFILE * FLATFILE and MYSQL. Default is FLATFILE
* @return Database type * @return Database type
*/ */
public static BSBDatabase getDatabase(){ public static BSBDatabase getDatabase(){

View File

@ -6,15 +6,15 @@ import java.sql.SQLException;
import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.configuration.file.YamlConfiguration;
/** /**
* *
* Creates a connection to a database. * Creates a connection to a database.
* *
*/ */
public interface DatabaseConnecter { public interface DatabaseConnecter {
/** /**
* Establishes a new connection to the database * Establishes a new connection to the database
* *
* @return A new connection to the database * @return A new connection to the database
* @throws SQLException * @throws SQLException
*/ */
@ -22,18 +22,18 @@ public interface DatabaseConnecter {
/** /**
* Returns the connection url * Returns the connection url
* *
* @return * @return
*/ */
public String getConnectionUrl(); public String getConnectionUrl();
/** /**
* Looks through the database (or files) and returns a known unique key * Looks through the database (or files) and returns a known unique key
* @param tableName * @param tableName
* @return a unique key for this record * @return a unique key for this record
*/ */
public String getUniqueId(String tableName); public String getUniqueId(String tableName);
/** /**
* Check if a key exists in the database in this table or not * Check if a key exists in the database in this table or not
* @param simpleName * @param simpleName

View File

@ -26,14 +26,12 @@ public class FlatFileDatabaseConnecter implements DatabaseConnecter {
@Override @Override
public Connection createConnection() throws SQLException { public Connection createConnection() throws SQLException {
// TODO Auto-generated method stub return null; // Not used
return null;
} }
@Override @Override
public String getConnectionUrl() { public String getConnectionUrl() {
// TODO Auto-generated method stub return null; // Not used
return null;
} }
/** /**

View File

@ -29,9 +29,9 @@ import us.tastybento.bskyblock.util.Util;
/** /**
* Class that creates a list of <T>s filled with values from the corresponding * Class that creates a list of <T>s filled with values from the corresponding
* database-table. * database-table.
* *
* @author tastybento * @author tastybento
* *
* @param <T> * @param <T>
*/ */
public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> { public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
@ -51,27 +51,27 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
} }
@Override @Override
protected String createDeleteQuery() { protected String createDeleteQuery() {
// TODO Auto-generated method stub return ""; // Not used
return null;
} }
/** /**
* Creates a <T> filled with values from the corresponding * Creates a <T> filled with values from the corresponding
* database file * database file
* *
* @return <T> filled with values from the corresponding database file * @return <T> filled with values from the corresponding database file
* @throws IntrospectionException * @throws IntrospectionException
* @throws InvocationTargetException * @throws InvocationTargetException
* @throws IllegalArgumentException * @throws IllegalArgumentException
* @throws IllegalAccessException * @throws IllegalAccessException
* @throws InstantiationException * @throws InstantiationException
* @throws ClassNotFoundException * @throws ClassNotFoundException
*/ */
@Override @Override
public T loadObject(String key) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException, ClassNotFoundException { public T loadObject(String key) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException, ClassNotFoundException {
YamlConfiguration config = databaseConnecter.loadYamlFile(type.getSimpleName(), key); YamlConfiguration config = databaseConnecter.loadYamlFile(type.getSimpleName(), key);
return createObject(config); return createObject(config);
} }
@Override @Override
public boolean objectExits(String key) { public boolean objectExits(String key) {
return databaseConnecter.uniqueIdExists(type.getSimpleName(), key); return databaseConnecter.uniqueIdExists(type.getSimpleName(), key);
@ -85,7 +85,7 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
* @throws IllegalArgumentException * @throws IllegalArgumentException
* @throws InvocationTargetException * @throws InvocationTargetException
* @throws IntrospectionException * @throws IntrospectionException
* @throws ClassNotFoundException * @throws ClassNotFoundException
*/ */
@Override @Override
public List<T> loadObjects() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException, ClassNotFoundException { public List<T> loadObjects() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException, ClassNotFoundException {
@ -114,19 +114,19 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
return list; return list;
} }
/** /**
* *
* Creates a list of <T>s filled with values from the provided ResultSet * Creates a list of <T>s filled with values from the provided ResultSet
* *
* @param config - YAML config file * @param config - YAML config file
* *
* @return <T> filled with values * @return <T> filled with values
* *
* @throws InstantiationException * @throws InstantiationException
* @throws IllegalAccessException * @throws IllegalAccessException
* @throws IntrospectionException * @throws IntrospectionException
* @throws IllegalArgumentException * @throws IllegalArgumentException
* @throws InvocationTargetException * @throws InvocationTargetException
* @throws ClassNotFoundException * @throws ClassNotFoundException
*/ */
private T createObject(YamlConfiguration config) throws InstantiationException, IllegalAccessException, IntrospectionException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException { private T createObject(YamlConfiguration config) throws InstantiationException, IllegalAccessException, IntrospectionException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException {
T instance = type.newInstance(); T instance = type.newInstance();
@ -202,7 +202,7 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
/** /**
* Inserts T into the corresponding database-table * Inserts T into the corresponding database-table
* *
* @param instance that should be inserted into the database * @param instance that should be inserted into the database
* @throws IllegalAccessException * @throws IllegalAccessException
* @throws IllegalArgumentException * @throws IllegalArgumentException
@ -300,7 +300,7 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
return object; return object;
} }
private Object deserialize(Object value, Class<? extends Object> clazz) { private Object deserialize(Object value, Class<? extends Object> clazz) {
//plugin.getLogger().info("DEBUG: deserialize - class is " + clazz.getCanonicalName()); //plugin.getLogger().info("DEBUG: deserialize - class is " + clazz.getCanonicalName());
if (value instanceof String && value.equals("null")) { if (value instanceof String && value.equals("null")) {
// If the value is null as a string, return null // If the value is null as a string, return null
@ -353,7 +353,7 @@ public class FlatFileDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
if (tableFolder.exists()) { if (tableFolder.exists()) {
File file = new File(tableFolder, fileName); File file = new File(tableFolder, fileName);
file.delete(); file.delete();
} }
} }
} }

View File

@ -11,10 +11,7 @@ import us.tastybento.bskyblock.database.DatabaseConnecter;
/** /**
* An abstract class that handles insert/select-operations into/from a database * An abstract class that handles insert/select-operations into/from a database
* *
* @param <T>
*/
/**
* @author tastybento * @author tastybento
* *
* @param <T> * @param <T>
@ -44,7 +41,7 @@ public abstract class AbstractDatabaseHandler<T> {
/** /**
* Constructor * Constructor
* *
* @param type * @param type
* The type of the objects that should be created and filled with * The type of the objects that should be created and filled with
* values from the database or inserted into the database * values from the database or inserted into the database
@ -71,7 +68,7 @@ public abstract class AbstractDatabaseHandler<T> {
protected abstract String createDeleteQuery(); protected abstract String createDeleteQuery();
/** /**
* *
* Creates a comma-separated-String with the names of the variables in this * Creates a comma-separated-String with the names of the variables in this
* class * class
* Not used in Flat File database. * Not used in Flat File database.
@ -108,9 +105,9 @@ public abstract class AbstractDatabaseHandler<T> {
* @throws IllegalArgumentException * @throws IllegalArgumentException
* @throws InvocationTargetException * @throws InvocationTargetException
* @throws IntrospectionException * @throws IntrospectionException
* @throws SecurityException * @throws SecurityException
* @throws SQLException * @throws SQLException
* @throws ClassNotFoundException * @throws ClassNotFoundException
*/ */
protected abstract List<T> loadObjects() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException, SQLException, SecurityException, ClassNotFoundException; protected abstract List<T> loadObjects() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException, SQLException, SecurityException, ClassNotFoundException;
@ -119,42 +116,42 @@ public abstract class AbstractDatabaseHandler<T> {
* database file * database file
* @param uniqueId * @param uniqueId
* @return <T> * @return <T>
* @throws IntrospectionException * @throws IntrospectionException
* @throws InvocationTargetException * @throws InvocationTargetException
* @throws IllegalArgumentException * @throws IllegalArgumentException
* @throws IllegalAccessException * @throws IllegalAccessException
* @throws InstantiationException * @throws InstantiationException
* @throws SQLException * @throws SQLException
* @throws ClassNotFoundException * @throws ClassNotFoundException
* @throws SecurityException * @throws SecurityException
*/ */
protected abstract T loadObject(String uniqueId) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException, SQLException, SecurityException, ClassNotFoundException; protected abstract T loadObject(String uniqueId) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException, SQLException, SecurityException, ClassNotFoundException;
/** /**
* Save T into the corresponding database * Save T into the corresponding database
* *
* @param instance that should be inserted into the database * @param instance that should be inserted into the database
* @throws IllegalAccessException * @throws IllegalAccessException
* @throws IllegalArgumentException * @throws IllegalArgumentException
* @throws InvocationTargetException * @throws InvocationTargetException
* @throws IntrospectionException * @throws IntrospectionException
* @throws InstantiationException * @throws InstantiationException
* @throws SecurityException * @throws SecurityException
* @throws SQLException * @throws SQLException
* @throws NoSuchMethodException * @throws NoSuchMethodException
*/ */
protected abstract void saveObject(T instance) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException, SQLException, SecurityException, InstantiationException, NoSuchMethodException; protected abstract void saveObject(T instance) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException, SQLException, SecurityException, InstantiationException, NoSuchMethodException;
/** /**
* Deletes the object with the unique id from the database * Deletes the object with the unique id from the database
* @param instance * @param instance
* @throws InvocationTargetException * @throws InvocationTargetException
* @throws IllegalArgumentException * @throws IllegalArgumentException
* @throws IllegalAccessException * @throws IllegalAccessException
* @throws IntrospectionException * @throws IntrospectionException
* @throws SQLException * @throws SQLException
* @throws SecurityException * @throws SecurityException
* @throws NoSuchMethodException * @throws NoSuchMethodException
*/ */
public abstract void deleteObject(T instance) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException, SQLException, NoSuchMethodException, SecurityException; public abstract void deleteObject(T instance) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException, SQLException, NoSuchMethodException, SecurityException;

View File

@ -60,18 +60,19 @@ public class IslandsManager {
*/ */
private HashMap<UUID, Island> islandsByUUID; private HashMap<UUID, Island> islandsByUUID;
// 2D islandGrid of islands, x,z // 2D islandGrid of islands, x,z
private TreeMap<Integer, TreeMap<Integer, Island>> islandGrid = new TreeMap<Integer, TreeMap<Integer, Island>>(); private TreeMap<Integer, TreeMap<Integer, Island>> islandGrid = new TreeMap<>();
/** /**
* One island can be spawn, this is the one - otherwise, this value is null * One island can be spawn, this is the one - otherwise, this value is null
*/ */
private Island spawn; private Island spawn;
// Metrics data
private int metrics_createdcount = 0;
private AbstractDatabaseHandler<Island> handler; private AbstractDatabaseHandler<Island> handler;
private Location last; private Location last;
// Metrics data
private int metrics_createdcount = 0;
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public IslandsManager(BSkyBlock plugin){ public IslandsManager(BSkyBlock plugin){
this.plugin = plugin; this.plugin = plugin;
@ -79,7 +80,7 @@ public class IslandsManager {
// Set up the database handler to store and retrieve Island classes // Set up the database handler to store and retrieve Island classes
handler = (AbstractDatabaseHandler<Island>) database.getHandler(plugin, Island.class); handler = (AbstractDatabaseHandler<Island>) database.getHandler(plugin, Island.class);
islandsByLocation = HashBiMap.create(); islandsByLocation = HashBiMap.create();
islandsByUUID = new HashMap<UUID, Island>(); islandsByUUID = new HashMap<>();
spawn = null; spawn = null;
} }
@ -100,36 +101,24 @@ public class IslandsManager {
addToGrid(island); addToGrid(island);
} }
} catch (Exception e) { } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
} }
public void save(boolean async){ public void save(boolean async){
if(async){ Runnable save = () -> {
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
for(Island island : islandsByLocation.values()){
try {
handler.saveObject(island);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
} else {
for(Island island : islandsByLocation.values()){ for(Island island : islandsByLocation.values()){
try { try {
handler.saveObject(island); handler.saveObject(island);
} catch (Exception e) { } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
} }
};
if(async){
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, save);
} else {
save.run();
} }
} }
@ -147,10 +136,6 @@ public class IslandsManager {
return islandsByLocation.get(location) != null; return islandsByLocation.get(location) != null;
} }
public Island getIsland(Location location){
return islandsByLocation.get(location);
}
/** /**
* Gets the island for this player. If they are in a team, the team island is returned * Gets the island for this player. If they are in a team, the team island is returned
* @param uuid * @param uuid
@ -234,7 +219,7 @@ public class IslandsManager {
/** /**
* Deletes an island from the database. Does not remove blocks * Deletes an island from the database. Does not remove blocks
* @param location * @param island
*/ */
public void deleteIslandFromCache(Island island) { public void deleteIslandFromCache(Island island) {
islandsByLocation.inverse().remove(island); islandsByLocation.inverse().remove(island);
@ -296,7 +281,6 @@ public class IslandsManager {
try { try {
handler.deleteObject(island); handler.deleteObject(island);
} catch (Exception e) { } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
// Remove blocks from world // Remove blocks from world
@ -314,16 +298,6 @@ public class IslandsManager {
return spawn; return spawn;
} }
// Metrics-related methods //
public int metrics_getCreatedCount(){
return metrics_createdcount;
}
public void metrics_setCreatedCount(int count){
this.metrics_createdcount = count;
}
/** /**
* Removes this player from any and all islands * Removes this player from any and all islands
* @param playerUUID * @param playerUUID
@ -353,7 +327,6 @@ public class IslandsManager {
* Puts a player in a team. Removes them from their old island if required. * Puts a player in a team. Removes them from their old island if required.
* @param playerUUID * @param playerUUID
* @param teamLeader * @param teamLeader
* @param islandLocation
* @return true if successful, false if not * @return true if successful, false if not
*/ */
public boolean setJoinTeam(UUID playerUUID, UUID teamLeader) { public boolean setJoinTeam(UUID playerUUID, UUID teamLeader) {
@ -409,7 +382,7 @@ public class IslandsManager {
} }
// Save the database // Save the database
save(false); save(false);
return true; return true;
} }
@ -446,7 +419,7 @@ public class IslandsManager {
/** /**
* Returns a set of island member UUID's for the island of playerUUID * Returns a set of island member UUID's for the island of playerUUID
* *
* @param playerUUID * @param playerUUID
* @return Set of team UUIDs * @return Set of team UUIDs
*/ */
@ -471,9 +444,9 @@ public class IslandsManager {
/** /**
* Returns the island at the location or null if there is none. * Returns the island at the location or null if there is none.
* This includes the full island space, not just the protected area * This includes the full island space, not just the protected area
* *
* @param location * @param location
* @return PlayerIsland object * @return Island object
*/ */
public Island getIslandAt(Location location) { public Island getIslandAt(Location location) {
if (location == null) { if (location == null) {
@ -496,10 +469,10 @@ public class IslandsManager {
/** /**
* Returns the island at the x,z location or null if there is none. * Returns the island at the x,z location or null if there is none.
* This includes the full island space, not just the protected area. * This includes the full island space, not just the protected area.
* *
* @param x * @param x
* @param z * @param z
* @return PlayerIsland or null * @return Island or null
*/ */
public Island getIslandAt(int x, int z) { public Island getIslandAt(int x, int z) {
if (DEBUG2) { if (DEBUG2) {
@ -540,7 +513,7 @@ public class IslandsManager {
/** /**
* Returns the player's island location. * Returns the player's island location.
* Returns an island location OR a team island location * Returns an island location OR a team island location
* *
* @param playerUUID * @param playerUUID
* @return Location of player's island or null if one does not exist * @return Location of player's island or null if one does not exist
*/ */
@ -557,7 +530,7 @@ public class IslandsManager {
public Set<UUID> getBanList(UUID playerUUID) { public Set<UUID> getBanList(UUID playerUUID) {
// Get player's island // Get player's island
Island island = getIsland(playerUUID); Island island = getIsland(playerUUID);
return island == null ? new HashSet<UUID>(): island.getBanned(); return island == null ? new HashSet<>(): island.getBanned();
} }
/** /**
@ -566,7 +539,7 @@ public class IslandsManager {
*/ */
public boolean isOwner(UUID uniqueId) { public boolean isOwner(UUID uniqueId) {
if (hasIsland(uniqueId)) { if (hasIsland(uniqueId)) {
return getIsland(uniqueId).getOwner().equals(uniqueId) ? true : false; return getIsland(uniqueId).getOwner().equals(uniqueId);
} }
return false; return false;
} }
@ -574,7 +547,7 @@ public class IslandsManager {
/** /**
* This teleports player to their island. If not safe place can be found * This teleports player to their island. If not safe place can be found
* then the player is sent to spawn via /spawn command * then the player is sent to spawn via /spawn command
* *
* @param player * @param player
* @return true if the home teleport is successful * @return true if the home teleport is successful
*/ */
@ -589,7 +562,7 @@ public class IslandsManager {
* @return true if successful, false if not * @return true if successful, false if not
*/ */
public boolean homeTeleport(final Player player, int number) { public boolean homeTeleport(final Player player, int number) {
Location home = null; Location home;
if (DEBUG) if (DEBUG)
plugin.getLogger().info("home teleport called for #" + number); plugin.getLogger().info("home teleport called for #" + number);
home = getSafeHomeLocation(player.getUniqueId(), number); home = getSafeHomeLocation(player.getUniqueId(), number);
@ -628,13 +601,12 @@ public class IslandsManager {
player.setGameMode(GameMode.SURVIVAL); player.setGameMode(GameMode.SURVIVAL);
} }
return true; return true;
} }
/** /**
* Determines a safe teleport spot on player's island or the team island * Determines a safe teleport spot on player's island or the team island
* they belong to. * they belong to.
* *
* @param playerUUID UUID of player * @param playerUUID UUID of player
* @param number - starting home location e.g., 1 * @param number - starting home location e.g., 1
* @return Location of a safe teleport spot or null if one cannot be found * @return Location of a safe teleport spot or null if one cannot be found
@ -821,7 +793,7 @@ public class IslandsManager {
} }
//plugin.getLogger().info("DEBUG: Radii " + minXradius + "," + minYradius + "," + minZradius + //plugin.getLogger().info("DEBUG: Radii " + minXradius + "," + minYradius + "," + minZradius +
// "," + maxXradius + "," + maxYradius + "," + maxZradius); // "," + maxXradius + "," + maxYradius + "," + maxZradius);
} while (minXradius < i || maxXradius < i || minZradius < i || maxZradius < i || minYradius < depth } while (minXradius < i || maxXradius < i || minZradius < i || maxZradius < i || minYradius < depth
|| maxYradius < height); || maxYradius < height);
// Nothing worked // Nothing worked
return null; return null;
@ -831,7 +803,7 @@ public class IslandsManager {
* Checks if this location is safe for a player to teleport to. Used by * Checks if this location is safe for a player to teleport to. Used by
* warps and boat exits Unsafe is any liquid or air and also if there's no * warps and boat exits Unsafe is any liquid or air and also if there's no
* space * space
* *
* @param l * @param l
* - Location to be checked * - Location to be checked
* @return true if safe, otherwise false * @return true if safe, otherwise false
@ -916,7 +888,7 @@ public class IslandsManager {
* @param schematic * @param schematic
*/ */
public void newIsland(Player player, Schematic schematic) { public void newIsland(Player player, Schematic schematic) {
newIsland(player, schematic, null); newIsland(player, schematic, null);
} }
/** /**
@ -1004,7 +976,7 @@ public class IslandsManager {
} }
} }
} }
} }
// Start the reset cooldown // Start the reset cooldown
@ -1013,7 +985,7 @@ public class IslandsManager {
//} //}
// Set the custom protection range if appropriate // Set the custom protection range if appropriate
// Dynamic island range sizes with permissions // Dynamic island range sizes with permissions
int range = Settings.islandProtectionRange; int range = Settings.islandProtectionRange;
for (PermissionAttachmentInfo perms : player.getEffectivePermissions()) { for (PermissionAttachmentInfo perms : player.getEffectivePermissions()) {
if (perms.getPermission().startsWith(Settings.PERMPREFIX + "island.range.")) { if (perms.getPermission().startsWith(Settings.PERMPREFIX + "island.range.")) {
if (perms.getPermission().contains(Settings.PERMPREFIX + "island.range.*")) { if (perms.getPermission().contains(Settings.PERMPREFIX + "island.range.*")) {
@ -1098,7 +1070,7 @@ public class IslandsManager {
/** /**
* Finds the next free island spot based off the last known island Uses * Finds the next free island spot based off the last known island Uses
* island_distance setting from the config file Builds up in a grid fashion * island_distance setting from the config file Builds up in a grid fashion
* *
* @param lastIsland * @param lastIsland
* @return Location of next free island * @return Location of next free island
*/ */
@ -1136,7 +1108,7 @@ public class IslandsManager {
* This removes players from an island overworld and nether - used when reseting or deleting an island * This removes players from an island overworld and nether - used when reseting or deleting an island
* Mobs are killed when the chunks are refreshed. * Mobs are killed when the chunks are refreshed.
* @param island to remove players from * @param island to remove players from
* @param uuid * @param uuid
*/ */
public void removePlayersFromIsland(final Island island, UUID uuid) { public void removePlayersFromIsland(final Island island, UUID uuid) {
// Teleport players away // Teleport players away
@ -1180,9 +1152,9 @@ public class IslandsManager {
/** /**
* Returns the island being public at the location or null if there is none * Returns the island being public at the location or null if there is none
* *
* @param location * @param location
* @return PlayerIsland object * @return Island object
*/ */
public Island getProtectedIslandAt(Location location) { public Island getProtectedIslandAt(Location location) {
//plugin.getLogger().info("DEBUG: getProtectedIslandAt " + location); //plugin.getLogger().info("DEBUG: getProtectedIslandAt " + location);
@ -1208,7 +1180,7 @@ public class IslandsManager {
/** /**
* Indicates whether a player is at the island spawn or not * Indicates whether a player is at the island spawn or not
* *
* @param playerLoc * @param playerLoc
* @return true if they are, false if they are not, or spawn does not exist * @return true if they are, false if they are not, or spawn does not exist
*/ */
@ -1222,7 +1194,7 @@ public class IslandsManager {
/** /**
* Checks if a specific location is within the protected range of an island * Checks if a specific location is within the protected range of an island
* owned by the player * owned by the player
* *
* @param player * @param player
* @param loc * @param loc
* @return true if location is on island of player * @return true if location is on island of player
@ -1281,7 +1253,7 @@ public class IslandsManager {
/** /**
* Checks if an online player is in the protected area of their island, a team island or a * Checks if an online player is in the protected area of their island, a team island or a
* coop island * coop island
* *
* @param player * @param player
* @return true if on valid island, false if not * @return true if on valid island, false if not
*/ */
@ -1316,7 +1288,7 @@ public class IslandsManager {
if (Settings.netherGenerate && Settings.netherIslands && IslandWorld.getNetherWorld() != null) { if (Settings.netherGenerate && Settings.netherIslands && IslandWorld.getNetherWorld() != null) {
islandTestLocations.add(netherIsland(plugin.getIslands().getIslandLocation(player.getUniqueId()))); islandTestLocations.add(netherIsland(plugin.getIslands().getIslandLocation(player.getUniqueId())));
} }
} }
// TODO: Check coop locations // TODO: Check coop locations
/* /*
if (coop) { if (coop) {
@ -1370,7 +1342,7 @@ public class IslandsManager {
if (islandsByUUID.containsKey(owner)) { if (islandsByUUID.containsKey(owner)) {
Island island = islandsByUUID.get(owner); Island island = islandsByUUID.get(owner);
if (!island.getName().isEmpty()) { if (!island.getName().isEmpty()) {
result = island.getName(); result = island.getName();
} }
} }
return ChatColor.translateAlternateColorCodes('&', result) + ChatColor.RESET; return ChatColor.translateAlternateColorCodes('&', result) + ChatColor.RESET;
@ -1398,4 +1370,13 @@ public class IslandsManager {
return spawn.getSpawnPoint(); return spawn.getSpawnPoint();
} }
// Metrics-related methods //
public int metrics_getCreatedCount(){
return metrics_createdcount;
}
public void metrics_setCreatedCount(int count){
this.metrics_createdcount = count;
}
} }

View File

@ -22,7 +22,7 @@ public class OfflineHistoryMessages {
private BSBDatabase database; private BSBDatabase database;
// Offline Messages // Offline Messages
private HashMap<UUID, List<String>> messages = new HashMap<UUID, List<String>>(); private HashMap<UUID, List<String>> messages = new HashMap<>();
public OfflineHistoryMessages(BSkyBlock plugin){ public OfflineHistoryMessages(BSkyBlock plugin){
this.plugin = plugin; this.plugin = plugin;
@ -34,16 +34,14 @@ public class OfflineHistoryMessages {
} }
public void save(boolean async){ public void save(boolean async){
if(async){ Runnable save = () -> {
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
//database.saveOfflineHistoryMessages(messages);
}
});
} else {
//database.saveOfflineHistoryMessages(messages); //database.saveOfflineHistoryMessages(messages);
};
if(async){
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, save);
} else {
save.run();
} }
} }
@ -63,7 +61,7 @@ public class OfflineHistoryMessages {
TEAM, TEAM,
ISLAND, ISLAND,
DEATH, DEATH,
PERSONAL; PERSONAL
} }
/** /**
@ -115,7 +113,7 @@ public class OfflineHistoryMessages {
if (playerMessages != null) { if (playerMessages != null) {
playerMessages.add(message); playerMessages.add(message);
} else { } else {
playerMessages = new ArrayList<String>(Arrays.asList(message)); playerMessages = new ArrayList<>(Arrays.asList(message));
} }
messages.put(playerUUID, playerMessages); messages.put(playerUUID, playerMessages);
} }

View File

@ -33,7 +33,7 @@ public class PlayersManager{
* Provides a memory cache of online player information * Provides a memory cache of online player information
* This is the one-stop-shop of player info * This is the one-stop-shop of player info
* If the player is not cached, then a request is made to Players to obtain it * If the player is not cached, then a request is made to Players to obtain it
* *
* @param plugin * @param plugin
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -42,8 +42,8 @@ public class PlayersManager{
database = BSBDatabase.getDatabase(); database = BSBDatabase.getDatabase();
// Set up the database handler to store and retrieve Players classes // Set up the database handler to store and retrieve Players classes
handler = (AbstractDatabaseHandler<Players>) database.getHandler(plugin, Players.class); handler = (AbstractDatabaseHandler<Players>) database.getHandler(plugin, Players.class);
playerCache = new HashMap<UUID, Players>(); playerCache = new HashMap<>();
inTeleport = new HashSet<UUID>(); inTeleport = new HashSet<>();
} }
/** /**
@ -57,7 +57,6 @@ public class PlayersManager{
playerCache.put(player.getPlayerUUID(), player); playerCache.put(player.getPlayerUUID(), player);
} }
} catch (Exception e) { } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -67,30 +66,20 @@ public class PlayersManager{
* @param async - if true, save async * @param async - if true, save async
*/ */
public void save(boolean async){ public void save(boolean async){
if(async){ Runnable save = () -> {
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
for(Players player : playerCache.values()){
try {
handler.saveObject(player);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
} else {
for(Players player : playerCache.values()){ for(Players player : playerCache.values()){
try { try {
handler.saveObject(player); handler.saveObject(player);
} catch (Exception e) { } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
} }
};
if(async){
plugin.getServer().getScheduler().runTaskAsynchronously(plugin, save);
} else {
save.run();
} }
} }
@ -119,7 +108,7 @@ public class PlayersManager{
if (playerUUID == null) if (playerUUID == null)
return null; return null;
if (DEBUG) if (DEBUG)
plugin.getLogger().info("DEBUG: adding player " + playerUUID); plugin.getLogger().info("DEBUG: adding player " + playerUUID);
if (!playerCache.containsKey(playerUUID)) { if (!playerCache.containsKey(playerUUID)) {
if (DEBUG) if (DEBUG)
plugin.getLogger().info("DEBUG: player not in cache"); plugin.getLogger().info("DEBUG: player not in cache");
@ -149,9 +138,9 @@ public class PlayersManager{
/** /**
* Stores the player's info and removes the player from the cache * Stores the player's info and removes the player from the cache
* *
* @param player - UUID of player * @param player - UUID of player
* *
*/ */
public void removeOnlinePlayer(final UUID player) { public void removeOnlinePlayer(final UUID player) {
// plugin.getLogger().info("Removing player from cache: " + player); // plugin.getLogger().info("Removing player from cache: " + player);
@ -163,7 +152,6 @@ public class PlayersManager{
| InvocationTargetException | SecurityException | InvocationTargetException | SecurityException
| InstantiationException | NoSuchMethodException | InstantiationException | NoSuchMethodException
| IntrospectionException | SQLException e) { | IntrospectionException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -185,11 +173,11 @@ public class PlayersManager{
/** /**
* Checks if the player is known or not * Checks if the player is known or not
* *
* @param uniqueID * @param uniqueID
* @return true if player is know, otherwise false * @return true if player is know, otherwise false
*/ */
public boolean isAKnownPlayer(final UUID uniqueID) { public boolean isKnown(final UUID uniqueID) {
if (uniqueID == null) { if (uniqueID == null) {
return false; return false;
} }
@ -204,7 +192,7 @@ public class PlayersManager{
/** /**
* Returns the player object for the named player * Returns the player object for the named player
* *
* @param playerUUID * @param playerUUID
* - String name of player * - String name of player
* @return - player object * @return - player object
@ -216,7 +204,7 @@ public class PlayersManager{
/** /**
* Checks if player has an island. * Checks if player has an island.
* *
* @param playerUUID * @param playerUUID
* - string name of player * - string name of player
* @return true if player has island * @return true if player has island
@ -228,18 +216,18 @@ public class PlayersManager{
/** /**
* Checks if player is in a Team from cache if available * Checks if player is in a Team from cache if available
* *
* @param playerUUID * @param playerUUID
* @return true if player in a team * @return true if player in a team
*/ */
public boolean inTeam(final UUID playerUUID) { public boolean inTeam(final UUID playerUUID) {
addPlayer(playerUUID); addPlayer(playerUUID);
return plugin.getIslands().getMembers(playerUUID).size() > 1 ? true: false; return plugin.getIslands().getMembers(playerUUID).size() > 1;
} }
/** /**
* Clears player home locations * Clears player home locations
* *
* @param playerUUID * @param playerUUID
*/ */
public void clearPlayerHomes(UUID playerUUID) { public void clearPlayerHomes(UUID playerUUID) {
@ -283,9 +271,9 @@ public class PlayersManager{
/** /**
* Returns the home location, or null if none * Returns the home location, or null if none
* *
* @param playerUUID * @param playerUUID
* @param number * @param number
* @return Home location or null if none * @return Home location or null if none
*/ */
public Location getHomeLocation(UUID playerUUID, int number) { public Location getHomeLocation(UUID playerUUID, int number) {
@ -333,7 +321,7 @@ public class PlayersManager{
// Look in the database if it ready // Look in the database if it ready
// TODO: finish this! // TODO: finish this!
return Bukkit.getOfflinePlayer(string).getUniqueId(); return Bukkit.getOfflinePlayer(string).getUniqueId();
//return database.getUUID(string, adminCheck); //return database.getUUID(string, adminCheck);
} }
@ -351,7 +339,7 @@ public class PlayersManager{
/** /**
* Obtains the name of the player from their UUID * Obtains the name of the player from their UUID
* Player must have logged into the game before * Player must have logged into the game before
* *
* @param playerUUID * @param playerUUID
* @return String - playerName * @return String - playerName
*/ */
@ -365,7 +353,7 @@ public class PlayersManager{
/** /**
* Reverse lookup - returns the owner of an island from the location * Reverse lookup - returns the owner of an island from the location
* *
* @param loc * @param loc
* @return UUID of owner of island * @return UUID of owner of island
*/ */
@ -382,7 +370,7 @@ public class PlayersManager{
/** /**
* Gets how many island resets the player has left * Gets how many island resets the player has left
* *
* @param playerUUID * @param playerUUID
* @return number of resets * @return number of resets
*/ */
@ -393,7 +381,7 @@ public class PlayersManager{
/** /**
* Sets how many resets the player has left * Sets how many resets the player has left
* *
* @param playerUUID * @param playerUUID
* @param resets * @param resets
*/ */
@ -405,7 +393,7 @@ public class PlayersManager{
/** /**
* Returns how long the player must wait before they can be invited to an * Returns how long the player must wait before they can be invited to an
* island with the location * island with the location
* *
* @param playerUUID * @param playerUUID
* @param location * @param location
* @return time to wait in minutes/hours * @return time to wait in minutes/hours
@ -419,7 +407,7 @@ public class PlayersManager{
* Starts the timer for the player for this location before which they can * Starts the timer for the player for this location before which they can
* be invited * be invited
* Called when they are kicked from an island or leave. * Called when they are kicked from an island or leave.
* *
* @param playerUUID * @param playerUUID
* @param location * @param location
*/ */
@ -435,9 +423,7 @@ public class PlayersManager{
*/ */
public String getLocale(UUID playerUUID) { public String getLocale(UUID playerUUID) {
addPlayer(playerUUID); addPlayer(playerUUID);
if (playerUUID == null) { if (playerUUID == null) return "";
return "";
}
return playerCache.get(playerUUID).getLocale(); return playerCache.get(playerUUID).getLocale();
} }
@ -472,9 +458,9 @@ public class PlayersManager{
* Unban target from player's island * Unban target from player's island
* @param playerUUID * @param playerUUID
* @param targetUUID * @param targetUUID
* @return * @return
*/ */
public boolean unBan(UUID playerUUID, UUID targetUUID) { public boolean unban(UUID playerUUID, UUID targetUUID) {
addPlayer(playerUUID); addPlayer(playerUUID);
addPlayer(targetUUID); addPlayer(targetUUID);
Island island = plugin.getIslands().getIsland(playerUUID); Island island = plugin.getIslands().getIsland(playerUUID);
@ -517,7 +503,7 @@ public class PlayersManager{
public void clearResets(int resetLimit) { public void clearResets(int resetLimit) {
for (Players player : playerCache.values()) { for (Players player : playerCache.values()) {
player.setResetsLeft(resetLimit); player.setResetsLeft(resetLimit);
} }
} }
/** /**
@ -575,7 +561,7 @@ public class PlayersManager{
* @param uniqueId * @param uniqueId
*/ */
public void setInTeleport(UUID uniqueId) { public void setInTeleport(UUID uniqueId) {
inTeleport.add(uniqueId); inTeleport.add(uniqueId);
} }
/** /**
@ -583,7 +569,7 @@ public class PlayersManager{
* @param uniqueId * @param uniqueId
*/ */
public void removeInTeleport(UUID uniqueId) { public void removeInTeleport(UUID uniqueId) {
inTeleport.remove(uniqueId); inTeleport.remove(uniqueId);
} }
/** /**
@ -591,7 +577,7 @@ public class PlayersManager{
* @return true if a player is mid-teleport * @return true if a player is mid-teleport
*/ */
public boolean isInTeleport(UUID uniqueId) { public boolean isInTeleport(UUID uniqueId) {
return inTeleport.contains(uniqueId); return inTeleport.contains(uniqueId);
} }
/** /**
@ -618,7 +604,6 @@ public class PlayersManager{
| InvocationTargetException | SecurityException | InvocationTargetException | SecurityException
| InstantiationException | NoSuchMethodException | InstantiationException | NoSuchMethodException
| IntrospectionException | SQLException e) { | IntrospectionException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
} else { } else {

View File

@ -10,11 +10,11 @@ import us.tastybento.bskyblock.database.DatabaseConnecter;
import us.tastybento.bskyblock.database.DatabaseConnectionSettingsImpl; import us.tastybento.bskyblock.database.DatabaseConnectionSettingsImpl;
public class MySQLDatabaseConnecter implements DatabaseConnecter { public class MySQLDatabaseConnecter implements DatabaseConnecter {
private String connectionUrl; private String connectionUrl;
private DatabaseConnectionSettingsImpl dbSettings; private DatabaseConnectionSettingsImpl dbSettings;
private Connection connection = null; private Connection connection = null;
/** /**
* Class for MySQL database connections using the settings provided * Class for MySQL database connections using the settings provided
* @param dbSettings * @param dbSettings
@ -57,7 +57,7 @@ public class MySQLDatabaseConnecter implements DatabaseConnecter {
@Override @Override
public void saveYamlFile(YamlConfiguration yamlFile, String tableName, String fileName) { public void saveYamlFile(YamlConfiguration yamlFile, String tableName, String fileName) {
// Not used // Not used
} }
@Override @Override

View File

@ -36,11 +36,11 @@ import us.tastybento.bskyblock.database.managers.AbstractDatabaseHandler;
import us.tastybento.bskyblock.util.Util; import us.tastybento.bskyblock.util.Util;
/** /**
* *
* Class that inserts a <T> into the corresponding database-table. * Class that inserts a <T> into the corresponding database-table.
* *
* @author tastybento * @author tastybento
* *
* @param <T> * @param <T>
*/ */
public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> { public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
@ -54,7 +54,7 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
*/ */
private static HashMap<String, String> mySQLmapping; private static HashMap<String, String> mySQLmapping;
{ {
mySQLmapping = new HashMap<String, String>(); mySQLmapping = new HashMap<>();
mySQLmapping.put(boolean.class.getTypeName(), "BOOL"); mySQLmapping.put(boolean.class.getTypeName(), "BOOL");
mySQLmapping.put(byte.class.getTypeName(), "TINYINT"); mySQLmapping.put(byte.class.getTypeName(), "TINYINT");
mySQLmapping.put(short.class.getTypeName(), "SMALLINT"); mySQLmapping.put(short.class.getTypeName(), "SMALLINT");
@ -106,10 +106,8 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
try { try {
createSchema(); createSchema();
} catch (IntrospectionException e) { } catch (IntrospectionException e) {
// TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} catch (SQLException e) { } catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
} }
@ -169,7 +167,7 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
sql += " PRIMARY KEY (uniqueId))"; sql += " PRIMARY KEY (uniqueId))";
//plugin.getLogger().info("DEBUG: SQL string = " + sql); //plugin.getLogger().info("DEBUG: SQL string = " + sql);
// Prepare and execute the database statements // Prepare and execute the database statements
pstmt = connection.prepareStatement(sql.toString()); pstmt = connection.prepareStatement(sql);
pstmt.executeUpdate(); pstmt.executeUpdate();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
@ -293,12 +291,12 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
@Override @Override
protected String createDeleteQuery() { protected String createDeleteQuery() {
return "DELETE FROM [table_name] WHERE uniqueId = ?"; return "DELETE FROM [table_name] WHERE uniqueId = ?";
} }
/** /**
* Inserts a <T> into the corresponding database-table * Inserts a <T> into the corresponding database-table
* *
* @param instance <T> that should be inserted into the corresponding database-table. Must extend DataObject. * @param instance <T> that should be inserted into the corresponding database-table. Must extend DataObject.
* @throws SQLException * @throws SQLException
* @throws SecurityException * @throws SecurityException
@ -307,16 +305,16 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
* @throws IllegalAccessException * @throws IllegalAccessException
* @throws IntrospectionException * @throws IntrospectionException
* @throws InvocationTargetException * @throws InvocationTargetException
* @throws NoSuchMethodException * @throws NoSuchMethodException
*/ */
/* (non-Javadoc) /* (non-Javadoc)
* @see us.tastybento.bskyblock.database.managers.AbstractDatabaseHandler#insertObject(java.lang.Object) * @see us.tastybento.bskyblock.database.managers.AbstractDatabaseHandler#insertObject(java.lang.Object)
*/ */
@Override @Override
public void saveObject(T instance) throws SQLException, public void saveObject(T instance) throws SQLException,
SecurityException, IllegalArgumentException, SecurityException, IllegalArgumentException,
InstantiationException, IllegalAccessException, InstantiationException, IllegalAccessException,
IntrospectionException, InvocationTargetException, NoSuchMethodException { IntrospectionException, InvocationTargetException, NoSuchMethodException {
Connection connection = null; Connection connection = null;
PreparedStatement preparedStatement = null; PreparedStatement preparedStatement = null;
@ -437,7 +435,7 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
* @param clazz - the known class of value * @param clazz - the known class of value
* @return the object to write to the database * @return the object to write to the database
*/ */
private Object serialize(Object value, Class<? extends Object> clazz) { private Object serialize(Object value, Class<? extends Object> clazz) {
//plugin.getLogger().info("DEBUG: serialize - class is " + clazz.getTypeName()); //plugin.getLogger().info("DEBUG: serialize - class is " + clazz.getTypeName());
if (value == null) { if (value == null) {
// If the value is null to start, return null as a string // If the value is null to start, return null as a string
@ -446,22 +444,22 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
// Types that need to be serialized // Types that need to be serialized
// TODO - add others, like Date, Timestamp, etc. // TODO - add others, like Date, Timestamp, etc.
if (clazz.equals(UUID.class)) { if (clazz.equals(UUID.class)) {
value = ((UUID)value).toString(); value = value.toString();
} }
else else
// Bukkit Types // Bukkit Types
if (clazz.equals(Location.class)) { if (clazz.equals(Location.class)) {
// Serialize // Serialize
value = Util.getStringLocation(((Location)value)); value = Util.getStringLocation(((Location)value));
} else } else
if (clazz.equals(World.class)) { if (clazz.equals(World.class)) {
// Serialize - get the name // Serialize - get the name
value = ((World)value).getName(); value = ((World)value).getName();
} else } else
if (clazz.getSuperclass() != null && clazz.getSuperclass().equals(Enum.class)) { if (clazz.getSuperclass() != null && clazz.getSuperclass().equals(Enum.class)) {
//Custom enums are a child of the Enum class. Just get the names of each one. //Custom enums are a child of the Enum class. Just get the names of each one.
value = ((Enum<?>)value).name(); value = ((Enum<?>)value).name();
} }
if (value == null) { if (value == null) {
// The value could become null from the above checks // The value could become null from the above checks
return "null"; return "null";
@ -473,10 +471,10 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
/** /**
* Creates a list of <T>s filled with values from the corresponding * Creates a list of <T>s filled with values from the corresponding
* database-table * database-table
* *
* @return List of <T>s filled with values from the corresponding * @return List of <T>s filled with values from the corresponding
* database-table * database-table
* *
* @throws SQLException * @throws SQLException
* @throws SecurityException * @throws SecurityException
* @throws IllegalArgumentException * @throws IllegalArgumentException
@ -484,13 +482,13 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
* @throws IllegalAccessException * @throws IllegalAccessException
* @throws IntrospectionException * @throws IntrospectionException
* @throws InvocationTargetException * @throws InvocationTargetException
* @throws ClassNotFoundException * @throws ClassNotFoundException
*/ */
@Override @Override
public List<T> loadObjects() throws SQLException, public List<T> loadObjects() throws SQLException,
SecurityException, IllegalArgumentException, SecurityException, IllegalArgumentException,
InstantiationException, IllegalAccessException, InstantiationException, IllegalAccessException,
IntrospectionException, InvocationTargetException, ClassNotFoundException { IntrospectionException, InvocationTargetException, ClassNotFoundException {
Connection connection = null; Connection connection = null;
Statement statement = null; Statement statement = null;
@ -515,8 +513,8 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
*/ */
@Override @Override
protected T loadObject(String uniqueId) throws InstantiationException, protected T loadObject(String uniqueId) throws InstantiationException,
IllegalAccessException, IllegalArgumentException, IllegalAccessException, IllegalArgumentException,
InvocationTargetException, IntrospectionException, SQLException, SecurityException, ClassNotFoundException { InvocationTargetException, IntrospectionException, SQLException, SecurityException, ClassNotFoundException {
Connection connection = null; Connection connection = null;
Statement statement = null; Statement statement = null;
ResultSet resultSet = null; ResultSet resultSet = null;
@ -543,15 +541,15 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
/** /**
* *
* Creates a list of <T>s filled with values from the provided ResultSet * Creates a list of <T>s filled with values from the provided ResultSet
* *
* @param resultSet * @param resultSet
* ResultSet that contains the result of the * ResultSet that contains the result of the
* database-select-query * database-select-query
* *
* @return List of <T>s filled with values from the provided ResultSet * @return List of <T>s filled with values from the provided ResultSet
* *
* @throws SecurityException * @throws SecurityException
* @throws IllegalArgumentException * @throws IllegalArgumentException
* @throws SQLException * @throws SQLException
@ -559,7 +557,7 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
* @throws IllegalAccessException * @throws IllegalAccessException
* @throws IntrospectionException * @throws IntrospectionException
* @throws InvocationTargetException * @throws InvocationTargetException
* @throws ClassNotFoundException * @throws ClassNotFoundException
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private List<T> createObjects(ResultSet resultSet) private List<T> createObjects(ResultSet resultSet)
@ -608,7 +606,7 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
// Set the unique ID // Set the unique ID
collStatement.setObject(1, uniqueId); collStatement.setObject(1, uniqueId);
//plugin.getLogger().info("DEBUG: collStatement = " + collStatement.toString()); //plugin.getLogger().info("DEBUG: collStatement = " + collStatement.toString());
ResultSet collectionResultSet = collStatement.executeQuery(); ResultSet collectionResultSet = collStatement.executeQuery();
//plugin.getLogger().info("DEBUG: collectionResultSet = " + collectionResultSet.toString()); //plugin.getLogger().info("DEBUG: collectionResultSet = " + collectionResultSet.toString());
// Do single dimension types (set and list) // Do single dimension types (set and list)
if (propertyDescriptor.getPropertyType().equals(Set.class)) { if (propertyDescriptor.getPropertyType().equals(Set.class)) {
@ -689,7 +687,7 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
* @return the deserialized value * @return the deserialized value
*/ */
@SuppressWarnings({ "unchecked", "rawtypes" }) @SuppressWarnings({ "unchecked", "rawtypes" })
private Object deserialize(Object value, Class<? extends Object> clazz) { private Object deserialize(Object value, Class<? extends Object> clazz) {
//plugin.getLogger().info("DEBUG: deserialize - class is " + clazz.getTypeName()); //plugin.getLogger().info("DEBUG: deserialize - class is " + clazz.getTypeName());
if (value instanceof String && value.equals("null")) { if (value instanceof String && value.equals("null")) {
// If the value is null as a string, return null // If the value is null as a string, return null
@ -777,7 +775,7 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
} finally { } finally {
// Close properly // Close properly
MySQLDatabaseResourceCloser.close(preparedStatement); MySQLDatabaseResourceCloser.close(preparedStatement);
} }
} }
@ -797,7 +795,6 @@ public class MySQLDatabaseHandler<T> extends AbstractDatabaseHandler<T> {
resultSet = preparedStatement.executeQuery(); resultSet = preparedStatement.executeQuery();
return resultSet.next(); return resultSet.next();
} catch (SQLException e) { } catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
MySQLDatabaseResourceCloser.close(resultSet); MySQLDatabaseResourceCloser.close(resultSet);

View File

@ -9,7 +9,7 @@ public class MySQLDatabaseResourceCloser {
/** /**
* Closes the provided ResultSets * Closes the provided ResultSets
* *
* @param resultSets * @param resultSets
* ResultSets that should be closed * ResultSets that should be closed
*/ */
@ -18,19 +18,21 @@ public class MySQLDatabaseResourceCloser {
if (resultSets == null) if (resultSets == null)
return; return;
for (ResultSet resultSet : resultSets) for (ResultSet resultSet : resultSets) {
if (resultSet != null) if (resultSet != null) {
try { try {
resultSet.close(); resultSet.close();
} catch (SQLException e) { } catch (SQLException e) {
/* Do some exception-logging here. */ /* Do some exception-logging here. */
e.printStackTrace(); e.printStackTrace();
} }
}
}
} }
/** /**
* Closes the provided Statements * Closes the provided Statements
* *
* @param statements * @param statements
* Statements that should be closed * Statements that should be closed
*/ */
@ -43,35 +45,38 @@ public class MySQLDatabaseResourceCloser {
if (statements == null) if (statements == null)
return; return;
for (Statement statement : statements) for (Statement statement : statements) {
if (statement != null) if (statement != null) {
try { try {
statement.close(); statement.close();
} catch (SQLException e) { } catch (SQLException e) {
/* Do some exception-logging here. */ /* Do some exception-logging here. */
e.printStackTrace(); e.printStackTrace();
} }
}
}
} }
/** /**
* Closes the provided Connections * Closes the provided Connections
* *
* @param connections * @param connections
* Connections that should be closed * Connections that should be closed
*/ */
public static void close(Connection... connections) { public static void close(Connection... connections) {
if (connections == null) if (connections == null)
return; return;
for (Connection connection : connections) for (Connection connection : connections) {
if (connection != null) if (connection != null) {
try { try {
connection.close(); connection.close();
} catch (SQLException e) { } catch (SQLException e) {
/* Do some exception-logging here. */ /* Do some exception-logging here. */
e.printStackTrace(); e.printStackTrace();
} }
}
}
} }
} }

View File

@ -22,7 +22,7 @@ import us.tastybento.bskyblock.util.Util;
* Stores all the info about an island * Stores all the info about an island
* Managed by IslandsManager * Managed by IslandsManager
* Responsible for team information as well. * Responsible for team information as well.
* *
* @author Tastybento * @author Tastybento
* @author Poslovitch * @author Poslovitch
*/ */
@ -42,19 +42,18 @@ public class Island extends DataObject {
@Override @Override
public void setUniqueId(String uniqueId) { public void setUniqueId(String uniqueId) {
this.uniqueId = uniqueId; this.uniqueId = uniqueId;
} }
/** /**
* Island Guard Settings flags * Island Guard Settings flags
* Covers island, spawn and system settings * Covers island, spawn and system settings
* *
* @author Tastybento * @author Tastybento
*/ */
public enum SettingsFlag{ public enum SettingsFlag{
ACID_DAMAGE, ACID_DAMAGE,
// Can use Anvil // Can use Anvil
ANVIL, ANVIL,
@ -78,7 +77,7 @@ public class Island extends DataObject {
// Can use buttons // Can use buttons
BUTTON, BUTTON,
// Can empty or fill buckets // Can empty or fill buckets
BUCKET, BUCKET,
@ -108,7 +107,7 @@ public class Island extends DataObject {
// Can open doors // Can open doors
DOOR, DOOR,
// Can open trapdoors, iron or wood // Can open trapdoors, iron or wood
TRAPDOOR, TRAPDOOR,
@ -144,7 +143,7 @@ public class Island extends DataObject {
// Can open gates // Can open gates
GATE, GATE,
// Can hurt animals (e.g. cows) - Villagers excluded // Can hurt animals (e.g. cows) - Villagers excluded
HURT_ANIMALS, HURT_ANIMALS,
@ -207,16 +206,16 @@ public class Island extends DataObject {
// Can activate pressure plates // Can activate pressure plates
PRESSURE_PLATE, PRESSURE_PLATE,
// Can do PvP in the overworld // Can do PvP in the overworld
PVP_OVERWORLD, PVP_OVERWORLD,
// Can do PvP in the nether // Can do PvP in the nether
PVP_NETHER, PVP_NETHER,
// Can do PvP in the end // Can do PvP in the end
PVP_END, PVP_END,
// Can interact with redstone items (repeaters, comparators) // Can interact with redstone items (repeaters, comparators)
REDSTONE, REDSTONE,
@ -240,7 +239,7 @@ public class Island extends DataObject {
// Can throw splash potions // Can throw splash potions
THROW_SPLASH_POTIONS, THROW_SPLASH_POTIONS,
// Can throw lingering potions // Can throw lingering potions
THROW_LINGERING_POTIONS, THROW_LINGERING_POTIONS,
@ -249,10 +248,10 @@ public class Island extends DataObject {
// Allow TNT to destroy blocks // Allow TNT to destroy blocks
TNT_GRIEFING, TNT_GRIEFING,
// Allow TNTs to blow up any chest or inventory block (only if TNT_griefing is enabled) // Allow TNTs to blow up any chest or inventory block (only if TNT_griefing is enabled)
TNT_BLOW_UP_CHEST, TNT_BLOW_UP_CHEST,
// Can trade with villagers // Can trade with villagers
VILLAGER_TRADING VILLAGER_TRADING
} }
@ -285,7 +284,6 @@ public class Island extends DataObject {
// Time parameters // Time parameters
private long createdDate; private long createdDate;
private long updatedDate; private long updatedDate;
//// Team //// //// Team ////
@ -293,27 +291,27 @@ public class Island extends DataObject {
private UUID owner; private UUID owner;
// Members (use set because each value must be unique) // Members (use set because each value must be unique)
private Set<UUID> members = new HashSet<UUID>(); private Set<UUID> members = new HashSet<>();
// Trustees // Trustees
private Set<UUID> trustees = new HashSet<UUID>(); private Set<UUID> trustees = new HashSet<>();
// Coops // Coops
private Set<UUID> coops = new HashSet<UUID>(); private Set<UUID> coops = new HashSet<>();
// Banned players // Banned players
private Set<UUID> banned = new HashSet<UUID>(); private Set<UUID> banned = new HashSet<>();
//// State //// //// State ////
private boolean locked = false; private boolean locked = false;
private boolean spawn = false; private boolean spawn = false;
private boolean purgeProtected = false; private boolean purgeProtected = false;
//// Protection //// //// Protection ////
private HashMap<SettingsFlag, Boolean> flags = new HashMap<SettingsFlag, Boolean>(); private HashMap<SettingsFlag, Boolean> flags = new HashMap<>();
private int levelHandicap; private int levelHandicap;
private Location spawnPoint; private Location spawnPoint;
public Island() {}; public Island() {}
public Island(Location location, UUID owner, int protectionRange) { public Island(Location location, UUID owner, int protectionRange) {
this.members.add(owner); this.members.add(owner);
@ -336,8 +334,8 @@ public class Island extends DataObject {
public void addMember(UUID playerUUID) { public void addMember(UUID playerUUID) {
members.add(playerUUID); members.add(playerUUID);
banned.remove(playerUUID); banned.remove(playerUUID);
} }
/** /**
* Adds target to a list of banned players for this island. May be blocked by the event being cancelled. * Adds target to a list of banned players for this island. May be blocked by the event being cancelled.
* If the player is a member, coop or trustee, they will be removed from those lists. * If the player is a member, coop or trustee, they will be removed from those lists.
@ -365,25 +363,28 @@ public class Island extends DataObject {
public Set<UUID> getBanned() { public Set<UUID> getBanned() {
return banned; return banned;
} }
/** /**
* @return the center Location * @return the center Location
*/ */
public Location getCenter(){ public Location getCenter(){
return center; return center;
} }
/** /**
* @return the coop players of the island * @return the coop players of the island
*/ */
public Set<UUID> getCoops(){ public Set<UUID> getCoops(){
return coops; return coops;
} }
/** /**
* @return the date when the island was created * @return the date when the island was created
*/ */
public long getCreatedDate(){ public long getCreatedDate(){
return createdDate; return createdDate;
} }
/** /**
* Get the Island Guard flag status * Get the Island Guard flag status
* @param flag * @param flag
@ -408,15 +409,17 @@ public class Island extends DataObject {
public HashMap<SettingsFlag, Boolean> getFlags() { public HashMap<SettingsFlag, Boolean> getFlags() {
return flags; return flags;
} }
/** /**
* @return the members of the island (owner included) * @return the members of the island (owner included)
*/ */
public Set<UUID> getMembers(){ public Set<UUID> getMembers(){
if (members == null) { if (members == null) {
members = new HashSet<UUID>(); members = new HashSet<>();
} }
return members; return members;
} }
/** /**
* @return the minProtectedX * @return the minProtectedX
*/ */
@ -449,15 +452,15 @@ public class Island extends DataObject {
* @return the island display name or the owner's name if none is set * @return the island display name or the owner's name if none is set
*/ */
public String getName() { public String getName() {
if (name != null) { if (name != null) {
return name; return name;
} }
if (owner != null) { if (owner != null) {
OfflinePlayer player = Bukkit.getServer().getOfflinePlayer(owner); OfflinePlayer player = Bukkit.getServer().getOfflinePlayer(owner);
name = player.getName(); name = player.getName();
return player.getName(); return player.getName();
} }
return ""; return "";
} }
/** /**
@ -569,7 +572,7 @@ public class Island extends DataObject {
/** /**
* Checks if a location is within this island's protected area * Checks if a location is within this island's protected area
* *
* @param target * @param target
* @return true if it is, false if not * @return true if it is, false if not
*/ */
@ -789,7 +792,7 @@ public class Island extends DataObject {
*/ */
public void toggleFlag(SettingsFlag flag){ public void toggleFlag(SettingsFlag flag){
if(flags.containsKey(flag)) { if(flags.containsKey(flag)) {
flags.put(flag, (flags.get(flag)) ? false : true); flags.put(flag, (flags.get(flag)));
} }
} }
@ -827,7 +830,7 @@ public class Island extends DataObject {
* a tile entity. * a tile entity.
*/ */
public int getTileEntityCount(Material material, World world) { public int getTileEntityCount(Material material, World world) {
int result = 0; int result = 0;
for (int x = getMinProtectedX() /16; x <= (getMinProtectedX() + getProtectionRange() - 1)/16; x++) { for (int x = getMinProtectedX() /16; x <= (getMinProtectedX() + getProtectionRange() - 1)/16; x++) {
for (int z = getMinProtectedZ() /16; z <= (getMinProtectedZ() + getProtectionRange() - 1)/16; z++) { for (int z = getMinProtectedZ() /16; z <= (getMinProtectedZ() + getProtectionRange() - 1)/16; z++) {
for (BlockState holder : world.getChunkAt(x, z).getTileEntities()) { for (BlockState holder : world.getChunkAt(x, z).getTileEntities()) {
@ -860,7 +863,7 @@ public class Island extends DataObject {
result++; result++;
} }
} }
} }
} }
return result; return result;
} }
@ -882,6 +885,6 @@ public class Island extends DataObject {
} }
public void removeMember(UUID playerUUID) { public void removeMember(UUID playerUUID) {
this.members.remove(playerUUID); this.members.remove(playerUUID);
} }
} }

View File

@ -13,7 +13,7 @@ import us.tastybento.bskyblock.config.Settings;
/** /**
* Tracks the following info on the player * Tracks the following info on the player
* *
* @author tastybento * @author tastybento
*/ */
public class Players extends DataObject { public class Players extends DataObject {
@ -34,16 +34,16 @@ public class Players extends DataObject {
/** /**
* @param uniqueId * @param uniqueId
* Constructor - initializes the state variables * Constructor - initializes the state variables
* *
*/ */
public Players(final UUID uniqueId) { public Players(final UUID uniqueId) {
this.uniqueId = uniqueId; this.uniqueId = uniqueId;
this.homeLocations = new HashMap<Integer,Location>(); this.homeLocations = new HashMap<>();
this.playerName = ""; this.playerName = "";
this.resetsLeft = Settings.resetLimit; this.resetsLeft = Settings.resetLimit;
this.locale = ""; this.locale = "";
this.useControlPanel = Settings.useControlPanel; this.useControlPanel = Settings.useControlPanel;
this.kickedList = new HashMap<Location, Long>(); this.kickedList = new HashMap<>();
this.playerName = Bukkit.getServer().getOfflinePlayer(uniqueId).getName(); this.playerName = Bukkit.getServer().getOfflinePlayer(uniqueId).getName();
} }
@ -70,7 +70,7 @@ public class Players extends DataObject {
if (number == en.getKey()) if (number == en.getKey())
Bukkit.getLogger().info("DEBUG: key = number"); Bukkit.getLogger().info("DEBUG: key = number");
}*/ }*/
return homeLocations.get(Integer.valueOf(number)); return homeLocations.get(number);
} }
/** /**
@ -156,7 +156,7 @@ public class Players extends DataObject {
/** /**
* Stores the home location of the player in a String format * Stores the home location of the player in a String format
* *
* @param l * @param l
* a Bukkit location * a Bukkit location
*/ */
@ -251,7 +251,7 @@ public class Players extends DataObject {
/** /**
* Can invite or still waiting for cool down to end * Can invite or still waiting for cool down to end
* *
* @param location * @param location
* to check * to check
* @return number of mins/hours left until cool down ends * @return number of mins/hours left until cool down ends

View File

@ -8,9 +8,8 @@ public class SQLiteDatabase extends BSBDatabase{
@Override @Override
public AbstractDatabaseHandler<?> getHandler(BSkyBlock plugin, Class<?> type) { public AbstractDatabaseHandler<?> getHandler(BSkyBlock plugin, Class<?> type) {
// return new SQLLiteDatabaseHandler<Island>(plugin, Island.class, new FlatFileDatabaseConnecter(plugin, null)); // return new SQLLiteDatabaseHandler<Island>(plugin, Island.class, new FlatFileDatabaseConnecter(plugin, null));
return null; return null;
} }
} }

View File

@ -1,4 +1,4 @@
package us.tastybento.bskyblock.generators; package us.tastybento.bskyblock.generators;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@ -35,7 +35,7 @@ public class ChunkGeneratorWorld extends ChunkGenerator {
for (int x = 0; x < 16; x++) { for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) { for (int z = 0; z < 16; z++) {
for (int y = 0; y < Settings.seaHeight; y++) { for (int y = 0; y < Settings.seaHeight; y++) {
setBlock(result, x, y, z, (byte) Material.STATIONARY_WATER.getId()); setBlock(result, x, y, z, (byte) Material.STATIONARY_WATER.getId());
} }
} }
} }
@ -111,33 +111,33 @@ public class ChunkGeneratorWorld extends ChunkGenerator {
if (r > 0.5D) { if (r > 0.5D) {
// Have blobs of glowstone // Have blobs of glowstone
switch (random.nextInt(4)) { switch (random.nextInt(4)) {
case 1: case 1:
// Single block // Single block
setBlock(result, x, (maxHeight - 8), z, (byte) Material.GLOWSTONE.getId()); setBlock(result, x, (maxHeight - 8), z, (byte) Material.GLOWSTONE.getId());
if (x < 14 && z < 14) { if (x < 14 && z < 14) {
setBlock(result, x + 1, (maxHeight - 8), z + 1, (byte) Material.GLOWSTONE.getId()); setBlock(result, x + 1, (maxHeight - 8), z + 1, (byte) Material.GLOWSTONE.getId());
setBlock(result, x + 2, (maxHeight - 8), z + 2, (byte) Material.GLOWSTONE.getId()); setBlock(result, x + 2, (maxHeight - 8), z + 2, (byte) Material.GLOWSTONE.getId());
setBlock(result, x + 1, (maxHeight - 8), z + 2, (byte) Material.GLOWSTONE.getId()); setBlock(result, x + 1, (maxHeight - 8), z + 2, (byte) Material.GLOWSTONE.getId());
setBlock(result, x + 1, (maxHeight - 8), z + 2, (byte) Material.GLOWSTONE.getId()); setBlock(result, x + 1, (maxHeight - 8), z + 2, (byte) Material.GLOWSTONE.getId());
} }
break; break;
case 2: case 2:
// Stalatite // Stalatite
for (int i = 0; i < random.nextInt(10); i++) { for (int i = 0; i < random.nextInt(10); i++) {
setBlock(result, x, (maxHeight - 8 - i), z, (byte) Material.GLOWSTONE.getId()); setBlock(result, x, (maxHeight - 8 - i), z, (byte) Material.GLOWSTONE.getId());
} }
case 3: case 3:
setBlock(result, x, (maxHeight - 8), z, (byte) Material.GLOWSTONE.getId()); setBlock(result, x, (maxHeight - 8), z, (byte) Material.GLOWSTONE.getId());
if (x > 3 && z > 3) { if (x > 3 && z > 3) {
for (int xx = 0; xx < 3; xx++) { for (int xx = 0; xx < 3; xx++) {
for (int zz = 0; zz < 3; zz++) { for (int zz = 0; zz < 3; zz++) {
setBlock(result, x - xx, (maxHeight - 8 - random.nextInt(2)), z - xx, (byte) Material.GLOWSTONE.getId()); setBlock(result, x - xx, (maxHeight - 8 - random.nextInt(2)), z - xx, (byte) Material.GLOWSTONE.getId());
}
} }
} }
} break;
break; default:
default: setBlock(result, x, (maxHeight - 8), z, (byte) Material.GLOWSTONE.getId());
setBlock(result, x, (maxHeight - 8), z, (byte) Material.GLOWSTONE.getId());
} }
setBlock(result, x, (maxHeight - 8), z, (byte) Material.GLOWSTONE.getId()); setBlock(result, x, (maxHeight - 8), z, (byte) Material.GLOWSTONE.getId());
} else { } else {

View File

@ -16,10 +16,7 @@ public class IslandWorld {
private static World endWorld; private static World endWorld;
/** /**
* Returns the World object for the island world named in config.yml. * Generates the Skyblock worlds.
* If the world does not exist then it is created.
*
* @return Bukkit World object for the BSkyBlock overworld
*/ */
public IslandWorld(BSkyBlock plugin) { public IslandWorld(BSkyBlock plugin) {
if (Settings.useOwnGenerator) { if (Settings.useOwnGenerator) {

View File

@ -18,7 +18,7 @@ import org.bukkit.inventory.ItemStack;
/** /**
* @author tastybento * @author tastybento
* Populates the Nether with appropriate blocks * Populates the Nether with appropriate blocks
* *
*/ */
public class NetherPopulator extends BlockPopulator { public class NetherPopulator extends BlockPopulator {
@ -32,17 +32,17 @@ public class NetherPopulator extends BlockPopulator {
if (b.getType().equals(Material.MOB_SPAWNER)) { if (b.getType().equals(Material.MOB_SPAWNER)) {
CreatureSpawner cs = (CreatureSpawner) b.getState(); CreatureSpawner cs = (CreatureSpawner) b.getState();
switch (random.nextInt(3)) { switch (random.nextInt(3)) {
case 0: case 0:
cs.setSpawnedType(EntityType.BLAZE); cs.setSpawnedType(EntityType.BLAZE);
break; break;
case 1: case 1:
cs.setSpawnedType(EntityType.SKELETON); cs.setSpawnedType(EntityType.SKELETON);
break; break;
case 2: case 2:
cs.setSpawnedType(EntityType.MAGMA_CUBE); cs.setSpawnedType(EntityType.MAGMA_CUBE);
break; break;
default: default:
cs.setSpawnedType(EntityType.BLAZE); cs.setSpawnedType(EntityType.BLAZE);
} }
} else if (b.getType().equals(Material.OBSIDIAN)) { } else if (b.getType().equals(Material.OBSIDIAN)) {
b.setType(Material.CHEST); b.setType(Material.CHEST);

View File

@ -41,7 +41,7 @@ public class JoinLeaveListener implements Listener {
if (playerUUID == null) { if (playerUUID == null) {
return; return;
} }
if (plugin.getPlayers().isAKnownPlayer(playerUUID)) { if (plugin.getPlayers().isKnown(playerUUID)) {
if (DEBUG) if (DEBUG)
plugin.getLogger().info("DEBUG: known player"); plugin.getLogger().info("DEBUG: known player");
// Load player // Load player

View File

@ -37,7 +37,7 @@ public class NetherPortals implements Listener {
/** /**
* This handles non-player portal use * This handles non-player portal use
* Currently disables portal use by entities * Currently disables portal use by entities
* *
* @param event * @param event
*/ */
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
@ -85,7 +85,7 @@ public class NetherPortals implements Listener {
} }
// Vehicles // Vehicles
if (event.getEntity() instanceof Vehicle) { if (event.getEntity() instanceof Vehicle) {
Vehicle vehicle = (Vehicle)event.getEntity(); Vehicle vehicle = (Vehicle)event.getEntity();
vehicle.eject(); vehicle.eject();
} }
new SafeSpotTeleport(plugin, event.getEntity(), dest); new SafeSpotTeleport(plugin, event.getEntity(), dest);
@ -112,7 +112,7 @@ public class NetherPortals implements Listener {
// Check if player has permission // Check if player has permission
Island island = plugin.getIslands().getIslandAt(currentLocation); Island island = plugin.getIslands().getIslandAt(currentLocation);
// TODO: if ((island == null && !Settings.defaultWorldSettings.get(SettingsFlag.PORTAL)) // TODO: if ((island == null && !Settings.defaultWorldSettings.get(SettingsFlag.PORTAL))
if (island == null if (island == null
|| (island != null && !(island.getFlag(SettingsFlag.PORTAL) || island.getMembers().contains(event.getPlayer().getUniqueId())))) { || (island != null && !(island.getFlag(SettingsFlag.PORTAL) || island.getMembers().contains(event.getPlayer().getUniqueId())))) {
// Portals use is not allowed // Portals use is not allowed
if (DEBUG) if (DEBUG)
@ -125,131 +125,131 @@ public class NetherPortals implements Listener {
} }
// Determine what portal it is // Determine what portal it is
switch (event.getCause()) { switch (event.getCause()) {
case END_PORTAL: case END_PORTAL:
if (DEBUG) if (DEBUG)
plugin.getLogger().info("DEBUG: End portal"); plugin.getLogger().info("DEBUG: End portal");
// Same action for all worlds except the end itself // Same action for all worlds except the end itself
if (!event.getFrom().getWorld().getEnvironment().equals(Environment.THE_END)) { if (!event.getFrom().getWorld().getEnvironment().equals(Environment.THE_END)) {
if (plugin.getServer().getWorld(Settings.worldName + "_the_end") != null) { if (plugin.getServer().getWorld(Settings.worldName + "_the_end") != null) {
// The end exists // The end exists
event.setCancelled(true); event.setCancelled(true);
Location end_place = plugin.getServer().getWorld(Settings.worldName + "_the_end").getSpawnLocation(); Location end_place = plugin.getServer().getWorld(Settings.worldName + "_the_end").getSpawnLocation();
if (IslandsManager.isSafeLocation(end_place)) { if (IslandsManager.isSafeLocation(end_place)) {
event.getPlayer().teleport(end_place); event.getPlayer().teleport(end_place);
// event.getPlayer().sendBlockChange(end_place, // event.getPlayer().sendBlockChange(end_place,
// end_place.getBlock().getType(),end_place.getBlock().getData()); // end_place.getBlock().getType(),end_place.getBlock().getData());
return; return;
} else {
Util.sendMessage(event.getPlayer(), ChatColor.RED + plugin.getLocale(event.getPlayer().getUniqueId()).get("warps.error.NotSafe"));
plugin.getIslands().homeTeleport(event.getPlayer());
return;
}
}
} else {
event.setCancelled(true);
plugin.getIslands().homeTeleport(event.getPlayer());
}
break;
case NETHER_PORTAL:
if (DEBUG)
plugin.getLogger().info("DEBUG: nether portal");
// Get the home world of this player
World homeWorld = IslandWorld.getIslandWorld();
Location home = plugin.getPlayers().getHomeLocation(event.getPlayer().getUniqueId());
if (home != null) {
homeWorld = home.getWorld();
}
if (!Settings.netherIslands) {
// Legacy action
if (event.getFrom().getWorld().getEnvironment().equals(Environment.NORMAL)) {
// Going to Nether
if (homeWorld.getEnvironment().equals(Environment.NORMAL)) {
// Home world is over world
event.setTo(IslandWorld.getNetherWorld().getSpawnLocation());
event.useTravelAgent(true);
} else {
// Home world is nether - going home
event.useTravelAgent(false);
Location dest = plugin.getIslands().getSafeHomeLocation(playerUUID,1);
if (dest != null) {
event.setTo(dest);
} else { } else {
event.setCancelled(true); Util.sendMessage(event.getPlayer(), ChatColor.RED + plugin.getLocale(event.getPlayer().getUniqueId()).get("warps.error.NotSafe"));
new SafeSpotTeleport(plugin, event.getPlayer(), plugin.getIslands().getIslandLocation(playerUUID), 1); plugin.getIslands().homeTeleport(event.getPlayer());
} return;
}
} }
} else { } else {
// Going to Over world
if (homeWorld.getEnvironment().equals(Environment.NORMAL)) {
// Home world is over world
event.useTravelAgent(false);
Location dest = plugin.getIslands().getSafeHomeLocation(playerUUID,1);
if (dest != null) {
event.setTo(dest);
} else {
event.setCancelled(true);
new SafeSpotTeleport(plugin, event.getPlayer(), plugin.getIslands().getIslandLocation(playerUUID), 1);
}
} else {
// Home world is nether
event.setTo(IslandWorld.getIslandWorld().getSpawnLocation());
event.useTravelAgent(true);
}
}
} else {
// Island Nether
if (DEBUG)
plugin.getLogger().info("DEBUG: Island nether");
// Get location of the island where the player is at
if (island == null) {
if (DEBUG)
plugin.getLogger().info("DEBUG: island is null");
event.setCancelled(true); event.setCancelled(true);
return; plugin.getIslands().homeTeleport(event.getPlayer());
} }
// Can go both ways now break;
Location overworldIsland = island.getCenter().toVector().toLocation(IslandWorld.getIslandWorld()); case NETHER_PORTAL:
Location netherIsland = island.getCenter().toVector().toLocation(IslandWorld.getNetherWorld()); if (DEBUG)
//Location dest = event.getFrom().toVector().toLocation(IslandWorld.getIslandWorld()); plugin.getLogger().info("DEBUG: nether portal");
if (event.getFrom().getWorld().getEnvironment().equals(Environment.NORMAL)) { // Get the home world of this player
// Going to Nether World homeWorld = IslandWorld.getIslandWorld();
// Check that there is a nether island there. Due to legacy reasons it may not exist Location home = plugin.getPlayers().getHomeLocation(event.getPlayer().getUniqueId());
if (DEBUG) if (home != null) {
plugin.getLogger().info("DEBUG: island center = " + island.getCenter()); homeWorld = home.getWorld();
if (netherIsland.getBlock().getType() != Material.BEDROCK) { }
// Check to see if there is anything there if (!Settings.netherIslands) {
if (plugin.getIslands().bigScan(netherIsland, 20) == null) { // Legacy action
if (DEBUG) if (event.getFrom().getWorld().getEnvironment().equals(Environment.NORMAL)) {
plugin.getLogger().info("DEBUG: big scan is null"); // Going to Nether
plugin.getLogger().warning("Creating nether island for " + event.getPlayer().getName() + " using default nether schematic"); if (homeWorld.getEnvironment().equals(Environment.NORMAL)) {
Schematic nether = plugin.getSchematics().getSchematic("nether"); // Home world is over world
if (nether != null) { event.setTo(IslandWorld.getNetherWorld().getSpawnLocation());
if (DEBUG) event.useTravelAgent(true);
plugin.getLogger().info("DEBUG: pasting at " + island.getCenter().toVector()); } else {
nether.pasteSchematic(netherIsland, event.getPlayer(), false, PasteReason.PARTNER, island); // Home world is nether - going home
event.useTravelAgent(false);
Location dest = plugin.getIslands().getSafeHomeLocation(playerUUID,1);
if (dest != null) {
event.setTo(dest);
} else { } else {
plugin.getLogger().severe("Cannot teleport player to nether because there is no nether schematic");
event.setCancelled(true); event.setCancelled(true);
Util.sendMessage(event.getPlayer(), ChatColor.RED + plugin.getLocale(event.getPlayer().getUniqueId()).get("warps.error.NotSafe")); new SafeSpotTeleport(plugin, event.getPlayer(), plugin.getIslands().getIslandLocation(playerUUID), 1);
return;
} }
} }
} else {
// Going to Over world
if (homeWorld.getEnvironment().equals(Environment.NORMAL)) {
// Home world is over world
event.useTravelAgent(false);
Location dest = plugin.getIslands().getSafeHomeLocation(playerUUID,1);
if (dest != null) {
event.setTo(dest);
} else {
event.setCancelled(true);
new SafeSpotTeleport(plugin, event.getPlayer(), plugin.getIslands().getIslandLocation(playerUUID), 1);
}
} else {
// Home world is nether
event.setTo(IslandWorld.getIslandWorld().getSpawnLocation());
event.useTravelAgent(true);
}
} }
} else {
// Island Nether
if (DEBUG) if (DEBUG)
plugin.getLogger().info("DEBUG: Teleporting to " + event.getFrom().toVector().toLocation(IslandWorld.getNetherWorld())); plugin.getLogger().info("DEBUG: Island nether");
// Get location of the island where the player is at
if (island == null) {
if (DEBUG)
plugin.getLogger().info("DEBUG: island is null");
event.setCancelled(true);
return;
}
// Can go both ways now
Location overworldIsland = island.getCenter().toVector().toLocation(IslandWorld.getIslandWorld());
Location netherIsland = island.getCenter().toVector().toLocation(IslandWorld.getNetherWorld());
//Location dest = event.getFrom().toVector().toLocation(IslandWorld.getIslandWorld());
if (event.getFrom().getWorld().getEnvironment().equals(Environment.NORMAL)) {
// Going to Nether
// Check that there is a nether island there. Due to legacy reasons it may not exist
if (DEBUG)
plugin.getLogger().info("DEBUG: island center = " + island.getCenter());
if (netherIsland.getBlock().getType() != Material.BEDROCK) {
// Check to see if there is anything there
if (plugin.getIslands().bigScan(netherIsland, 20) == null) {
if (DEBUG)
plugin.getLogger().info("DEBUG: big scan is null");
plugin.getLogger().warning("Creating nether island for " + event.getPlayer().getName() + " using default nether schematic");
Schematic nether = plugin.getSchematics().getSchematic("nether");
if (nether != null) {
if (DEBUG)
plugin.getLogger().info("DEBUG: pasting at " + island.getCenter().toVector());
nether.pasteSchematic(netherIsland, event.getPlayer(), false, PasteReason.PARTNER, island);
} else {
plugin.getLogger().severe("Cannot teleport player to nether because there is no nether schematic");
event.setCancelled(true);
Util.sendMessage(event.getPlayer(), ChatColor.RED + plugin.getLocale(event.getPlayer().getUniqueId()).get("warps.error.NotSafe"));
return;
}
}
}
if (DEBUG)
plugin.getLogger().info("DEBUG: Teleporting to " + event.getFrom().toVector().toLocation(IslandWorld.getNetherWorld()));
event.setCancelled(true);
// Teleport using the new safeSpot teleport
new SafeSpotTeleport(plugin, event.getPlayer(), netherIsland);
return;
}
// Going to the over world - if there isn't an island, do nothing
event.setCancelled(true); event.setCancelled(true);
// Teleport using the new safeSpot teleport // Teleport using the new safeSpot teleport
new SafeSpotTeleport(plugin, event.getPlayer(), netherIsland); new SafeSpotTeleport(plugin, event.getPlayer(), overworldIsland);
return;
} }
// Going to the over world - if there isn't an island, do nothing break;
event.setCancelled(true); default:
// Teleport using the new safeSpot teleport break;
new SafeSpotTeleport(plugin, event.getPlayer(), overworldIsland);
}
break;
default:
break;
} }
} }

View File

@ -25,7 +25,7 @@ import us.tastybento.bskyblock.util.Util;
/** /**
* This class manages flying mobs. If they exist the spawned island's limits they will be removed. * This class manages flying mobs. If they exist the spawned island's limits they will be removed.
* *
* @author tastybento * @author tastybento
* *
*/ */
@ -39,38 +39,35 @@ public class FlyingMobEvents implements Listener {
*/ */
public FlyingMobEvents(BSkyBlock plugin) { public FlyingMobEvents(BSkyBlock plugin) {
this.plugin = plugin; this.plugin = plugin;
this.mobSpawnInfo = new WeakHashMap<Entity, Island>(); this.mobSpawnInfo = new WeakHashMap<>();
new BukkitRunnable() {
public void run() { plugin.getServer().getScheduler().runTaskTimer(plugin, () -> {
//Bukkit.getLogger().info("DEBUG: checking - mobspawn size = " + mobSpawnInfo.size()); //Bukkit.getLogger().info("DEBUG: checking - mobspawn size = " + mobSpawnInfo.size());
Iterator<Entry<Entity, Island>> it = mobSpawnInfo.entrySet().iterator(); Iterator<Entry<Entity, Island>> it = mobSpawnInfo.entrySet().iterator();
while (it.hasNext()) { while (it.hasNext()) {
Entry<Entity, Island> entry = it.next(); Entry<Entity, Island> entry = it.next();
if (entry.getKey() == null) { if (entry.getKey() == null) {
//Bukkit.getLogger().info("DEBUG: removing null entity"); //Bukkit.getLogger().info("DEBUG: removing null entity");
it.remove(); it.remove();
} else { } else {
if (entry.getKey() instanceof LivingEntity) { if (entry.getKey() instanceof LivingEntity) {
if (!entry.getValue().inIslandSpace(entry.getKey().getLocation())) { if (!entry.getValue().inIslandSpace(entry.getKey().getLocation())) {
//Bukkit.getLogger().info("DEBUG: removing entity outside of island"); //Bukkit.getLogger().info("DEBUG: removing entity outside of island");
it.remove();
// Kill mob
LivingEntity mob = (LivingEntity)entry.getKey();
mob.setHealth(0);
entry.getKey().remove();
} else {
//Bukkit.getLogger().info("DEBUG: entity " + entry.getKey().getName() + " is in island space");
}
} else {
// Not living entity
it.remove(); it.remove();
// Kill mob
LivingEntity mob = (LivingEntity)entry.getKey();
mob.setHealth(0);
entry.getKey().remove();
} else {
//Bukkit.getLogger().info("DEBUG: entity " + entry.getKey().getName() + " is in island space");
} }
} else {
// Not living entity
it.remove();
} }
} }
} }
}, 20L, 20L);
}.runTaskTimer(plugin, 20L, 20L);
} }
/** /**
@ -108,12 +105,12 @@ public class FlyingMobEvents implements Listener {
if (e.getEntity() == null || !Util.inWorld(e.getEntity())) { if (e.getEntity() == null || !Util.inWorld(e.getEntity())) {
return; return;
} }
if (mobSpawnInfo.containsKey(e.getEntity().getUniqueId())) { if (mobSpawnInfo.containsKey(e.getEntity())) {
// We know about this mob // We know about this mob
if (DEBUG) { if (DEBUG) {
plugin.getLogger().info("DEBUG: We know about this mob"); plugin.getLogger().info("DEBUG: We know about this mob");
} }
if (!mobSpawnInfo.get(e.getEntity().getUniqueId()).inIslandSpace(e.getLocation())) { if (!mobSpawnInfo.get(e.getEntity()).inIslandSpace(e.getLocation())) {
// Cancel the explosion and block damage // Cancel the explosion and block damage
if (DEBUG) { if (DEBUG) {
plugin.getLogger().info("DEBUG: cancel flying mob explosion"); plugin.getLogger().info("DEBUG: cancel flying mob explosion");
@ -140,7 +137,7 @@ public class FlyingMobEvents implements Listener {
if (e.getEntityType() == EntityType.WITHER) { if (e.getEntityType() == EntityType.WITHER) {
//plugin.getLogger().info("DEBUG: Wither"); //plugin.getLogger().info("DEBUG: Wither");
// Check the location // Check the location
if (mobSpawnInfo.containsKey(e.getEntity().getUniqueId())) { if (mobSpawnInfo.containsKey(e.getEntity())) {
// We know about this wither // We know about this wither
if (DEBUG) { if (DEBUG) {
plugin.getLogger().info("DEBUG: We know about this wither"); plugin.getLogger().info("DEBUG: We know about this wither");
@ -163,12 +160,12 @@ public class FlyingMobEvents implements Listener {
//plugin.getLogger().info("DEBUG: shooter is wither"); //plugin.getLogger().info("DEBUG: shooter is wither");
Wither wither = (Wither)projectile.getShooter(); Wither wither = (Wither)projectile.getShooter();
// Check the location // Check the location
if (mobSpawnInfo.containsKey(wither.getUniqueId())) { if (mobSpawnInfo.containsKey(wither)) {
// We know about this wither // We know about this wither
if (DEBUG) { if (DEBUG) {
plugin.getLogger().info("DEBUG: We know about this wither"); plugin.getLogger().info("DEBUG: We know about this wither");
} }
if (!mobSpawnInfo.get(wither.getUniqueId()).inIslandSpace(e.getEntity().getLocation())) { if (!mobSpawnInfo.get(wither).inIslandSpace(e.getEntity().getLocation())) {
// Cancel the explosion // Cancel the explosion
if (DEBUG) { if (DEBUG) {
plugin.getLogger().info("DEBUG: cancel wither skull explosion"); plugin.getLogger().info("DEBUG: cancel wither skull explosion");

View File

@ -9,9 +9,9 @@ import us.tastybento.bskyblock.BSkyBlock;
/** /**
* Stashes inventories when required for a player * Stashes inventories when required for a player
* *
* @author tastybento * @author tastybento
* *
*/ */
public class InventorySave { public class InventorySave {
private static InventorySave instance = new InventorySave(BSkyBlock.getPlugin()); private static InventorySave instance = new InventorySave(BSkyBlock.getPlugin());
@ -21,7 +21,7 @@ public class InventorySave {
* Saves the inventory of a player * Saves the inventory of a player
*/ */
public InventorySave(BSkyBlock plugin) { public InventorySave(BSkyBlock plugin) {
inventories = new HashMap<UUID, InventoryStore>(); inventories = new HashMap<>();
} }
/** Save player's inventory /** Save player's inventory
@ -43,7 +43,7 @@ public class InventorySave {
} }
/** /**
* Load the player's inventory * Load the player's inventory
* *
* @param player * @param player
*/ */
public void loadPlayerInventory(Player player) { public void loadPlayerInventory(Player player) {

View File

@ -4,7 +4,7 @@ import org.bukkit.inventory.ItemStack;
/** /**
* Where the inventory data is stored * Where the inventory data is stored
* *
* @author tastybento * @author tastybento
*/ */
public class InventoryStore { public class InventoryStore {

View File

@ -37,7 +37,6 @@ public class IslandGuard1_8 implements Listener {
} }
/** /**
* Checks if action is allowed for player in location for flag * Checks if action is allowed for player in location for flag
* @param player * @param player
@ -64,7 +63,7 @@ public class IslandGuard1_8 implements Listener {
/** /**
* Handle interaction with armor stands V1.8 * Handle interaction with armor stands V1.8
* Note - some armor stand protection is done in IslandGuard.java, e.g. against projectiles. * Note - some armor stand protection is done in IslandGuard.java, e.g. against projectiles.
* *
* @param e * @param e
*/ */
@EventHandler(priority = EventPriority.LOW, ignoreCancelled=true) @EventHandler(priority = EventPriority.LOW, ignoreCancelled=true)
@ -88,7 +87,7 @@ public class IslandGuard1_8 implements Listener {
* Handle V1.8 blocks that need special treatment * Handle V1.8 blocks that need special treatment
* Tilling of coarse dirt into dirt * Tilling of coarse dirt into dirt
* Usually prevented because it could lead to an endless supply of dirt with gravel * Usually prevented because it could lead to an endless supply of dirt with gravel
* *
* @param e * @param e
*/ */
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")

View File

@ -54,7 +54,7 @@ public class IslandGuard1_9 implements Listener {
public IslandGuard1_9(final BSkyBlock plugin) { public IslandGuard1_9(final BSkyBlock plugin) {
this.plugin = plugin; this.plugin = plugin;
this.thrownPotions = new HashMap<Integer, UUID>(); this.thrownPotions = new HashMap<>();
} }
/** /**
@ -96,7 +96,7 @@ public class IslandGuard1_9 implements Listener {
/** /**
* Handle interaction with end crystals 1.9 * Handle interaction with end crystals 1.9
* *
* @param e * @param e
*/ */
@EventHandler(priority = EventPriority.LOW, ignoreCancelled=true) @EventHandler(priority = EventPriority.LOW, ignoreCancelled=true)
@ -217,7 +217,7 @@ public class IslandGuard1_9 implements Listener {
plugin.getLogger().info("1.9 " +"Damager is a projectile shot by " + p.getName()); plugin.getLogger().info("1.9 " +"Damager is a projectile shot by " + p.getName());
} }
} }
if (p != null) { if (p != null) {
if (p.isOp() || VaultHelper.hasPerm(p, Settings.PERMPREFIX + "mod.bypassprotect")) { if (p.isOp() || VaultHelper.hasPerm(p, Settings.PERMPREFIX + "mod.bypassprotect")) {
if (DEBUG) { if (DEBUG) {
plugin.getLogger().info("1.9 " +"Bypassing protection"); plugin.getLogger().info("1.9 " +"Bypassing protection");
@ -274,18 +274,18 @@ public class IslandGuard1_9 implements Listener {
e.blockList().clear(); e.blockList().clear();
} else { } else {
if (!Settings.allowChestDamage) { if (!Settings.allowChestDamage) {
List<Block> toberemoved = new ArrayList<Block>(); List<Block> toberemoved = new ArrayList<>();
// Save the chest blocks in a list // Save the chest blocks in a list
for (Block b : e.blockList()) { for (Block b : e.blockList()) {
switch (b.getType()) { switch (b.getType()) {
case CHEST: case CHEST:
case ENDER_CHEST: case ENDER_CHEST:
case STORAGE_MINECART: case STORAGE_MINECART:
case TRAPPED_CHEST: case TRAPPED_CHEST:
toberemoved.add(b); toberemoved.add(b);
break; break;
default: default:
break; break;
} }
} }
// Now delete them // Now delete them
@ -306,7 +306,7 @@ public class IslandGuard1_9 implements Listener {
* Handle blocks that need special treatment * Handle blocks that need special treatment
* Tilling of coarse dirt into dirt using off-hand (regular hand is in 1.8) * Tilling of coarse dirt into dirt using off-hand (regular hand is in 1.8)
* Usually prevented because it could lead to an endless supply of dirt with gravel * Usually prevented because it could lead to an endless supply of dirt with gravel
* *
* @param e * @param e
*/ */
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@ -359,21 +359,13 @@ public class IslandGuard1_9 implements Listener {
return; return;
} }
// Try to get the shooter // Try to get the shooter
Projectile projectile = (Projectile) e.getEntity(); Projectile projectile = e.getEntity();
plugin.getLogger().info("shooter = " + projectile.getShooter()); plugin.getLogger().info("shooter = " + projectile.getShooter());
if (projectile.getShooter() != null && projectile.getShooter() instanceof Player) { if (projectile.getShooter() != null && projectile.getShooter() instanceof Player) {
UUID uuid = ((Player)projectile.getShooter()).getUniqueId(); UUID uuid = ((Player)projectile.getShooter()).getUniqueId();
// Store it and remove it when the effect is gone // Store it and remove it when the effect is gone
thrownPotions.put(e.getAreaEffectCloud().getEntityId(), uuid); thrownPotions.put(e.getAreaEffectCloud().getEntityId(), uuid);
plugin.getServer().getScheduler().runTaskLater(plugin, new Runnable() { plugin.getServer().getScheduler().runTaskLater(plugin, () -> thrownPotions.remove(e.getAreaEffectCloud().getEntityId()), e.getAreaEffectCloud().getDuration());
@Override
public void run() {
if (DEBUG)
plugin.getLogger().info("DEBUG: Effect finished");
thrownPotions.remove(e.getAreaEffectCloud().getEntityId());
}}, e.getAreaEffectCloud().getDuration());
} }
} }
@ -441,18 +433,14 @@ public class IslandGuard1_9 implements Listener {
// Players being hurt PvP // Players being hurt PvP
if (e.getEntity() instanceof Player) { if (e.getEntity() instanceof Player) {
if (pvp) { if (!pvp) {
if (DEBUG) plugin.getLogger().info("DEBUG: PVP allowed");
return;
} else {
if (DEBUG) plugin.getLogger().info("DEBUG: PVP not allowed"); if (DEBUG) plugin.getLogger().info("DEBUG: PVP not allowed");
e.setCancelled(true); e.setCancelled(true);
return;
} }
} }
} }
} }
/** /**
* Checks if action is allowed for player in location for flag * Checks if action is allowed for player in location for flag
* @param uuid * @param uuid
@ -478,7 +466,7 @@ public class IslandGuard1_9 implements Listener {
} }
return false; return false;
} }
/** /**
* Action allowed in this location * Action allowed in this location
* @param location * @param location

View File

@ -36,7 +36,7 @@ public class NetherEvents implements Listener {
/** /**
* This handles non-player portal use * This handles non-player portal use
* Currently disables portal use by entities * Currently disables portal use by entities
* *
* @param event * @param event
*/ */
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
@ -84,7 +84,7 @@ public class NetherEvents implements Listener {
} }
// Vehicles // Vehicles
if (event.getEntity() instanceof Vehicle) { if (event.getEntity() instanceof Vehicle) {
Vehicle vehicle = (Vehicle)event.getEntity(); Vehicle vehicle = (Vehicle)event.getEntity();
vehicle.eject(); vehicle.eject();
} }
new SafeSpotTeleport(plugin, event.getEntity(), dest); new SafeSpotTeleport(plugin, event.getEntity(), dest);
@ -95,23 +95,19 @@ public class NetherEvents implements Listener {
/** /**
* Function to check proximity to nether spawn location * Function to check proximity to nether spawn location
* *
* @param player * @param player
* @return true if in the spawn area, false if not * @return true if in the spawn area, false if not
*/ */
private boolean awayFromSpawn(Player player) { private boolean awayFromSpawn(Player player) {
Vector p = player.getLocation().toVector().multiply(new Vector(1, 0, 1)); Vector p = player.getLocation().toVector().multiply(new Vector(1, 0, 1));
Vector spawn = player.getWorld().getSpawnLocation().toVector().multiply(new Vector(1, 0, 1)); Vector spawn = player.getWorld().getSpawnLocation().toVector().multiply(new Vector(1, 0, 1));
if (spawn.distanceSquared(p) < (Settings.netherSpawnRadius * Settings.netherSpawnRadius)) { return spawn.distanceSquared(p) < (Settings.netherSpawnRadius * Settings.netherSpawnRadius);
return false;
} else {
return true;
}
} }
/** /**
* Prevents blocks from being broken * Prevents blocks from being broken
* *
* @param e * @param e
*/ */
@EventHandler(priority = EventPriority.LOW) @EventHandler(priority = EventPriority.LOW)
@ -136,7 +132,7 @@ public class NetherEvents implements Listener {
/** /**
* Prevents placing of blocks * Prevents placing of blocks
* *
* @param e * @param e
*/ */
@EventHandler(priority = EventPriority.LOW) @EventHandler(priority = EventPriority.LOW)
@ -175,7 +171,7 @@ public class NetherEvents implements Listener {
/** /**
* Prevent the Nether spawn from being blown up * Prevent the Nether spawn from being blown up
* *
* @param e * @param e
*/ */
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
@ -203,7 +199,7 @@ public class NetherEvents implements Listener {
/** /**
* Converts trees to gravel and glowstone * Converts trees to gravel and glowstone
* *
* @param e * @param e
*/ */
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)

View File

@ -19,9 +19,9 @@ import us.tastybento.org.jnbt.Tag;
/** /**
* This class describes banners and is used in schematic importing * This class describes banners and is used in schematic importing
* *
* @author tastybento * @author tastybento
* *
*/ */
public class BannerBlock { public class BannerBlock {
private DyeColor bannerBaseColor; private DyeColor bannerBaseColor;
@ -33,7 +33,7 @@ public class BannerBlock {
// ss, tt // ss, tt
static { static {
patternKey = new HashMap<String, PatternType>(); patternKey = new HashMap<>();
patternKey.put("", PatternType.BASE); patternKey.put("", PatternType.BASE);
patternKey.put("bo", PatternType.BORDER); patternKey.put("bo", PatternType.BORDER);
patternKey.put("bri", PatternType.BRICKS); patternKey.put("bri", PatternType.BRICKS);
@ -101,7 +101,7 @@ public class BannerBlock {
// baseColor green = 10 // baseColor green = 10
bannerBaseColor = DyeColor.getByDyeData((byte) baseColor); bannerBaseColor = DyeColor.getByDyeData((byte) baseColor);
// Do the patterns (no idea if this will work or not) // Do the patterns (no idea if this will work or not)
bannerPattern = new ArrayList<Pattern>(); bannerPattern = new ArrayList<>();
ListTag patterns = (ListTag) tileData.get("Patterns"); ListTag patterns = (ListTag) tileData.get("Patterns");
if (patterns != null) { if (patterns != null) {
for (Tag pattern : patterns.getValue()) { for (Tag pattern : patterns.getValue()) {

View File

@ -33,7 +33,7 @@ public class EntityObject {
// Items informations // Items informations
private Byte count = null; private Byte count = null;
private Short damage = null; private Short damage = null;
private String id = null; private String id = null;
/** /**
* @return the type * @return the type

View File

@ -44,9 +44,9 @@ public class IslandBlock {
private BannerBlock banner; private BannerBlock banner;
private EntityType spawnerBlockType; private EntityType spawnerBlockType;
// Chest contents // Chest contents
private HashMap<Byte,ItemStack> chestContents = new HashMap<Byte,ItemStack>(); private HashMap<Byte,ItemStack> chestContents = new HashMap<>();
public static final HashMap<String, Material> WEtoM = new HashMap<String, Material>(); public static final HashMap<String, Material> WEtoM = new HashMap<>();
public static final HashMap<String, EntityType> WEtoME = new HashMap<String, EntityType>(); public static final HashMap<String, EntityType> WEtoME = new HashMap<>();
static { static {
// Establish the World Edit to Material look up // Establish the World Edit to Material look up
@ -201,7 +201,7 @@ public class IslandBlock {
signText = null; signText = null;
banner = null; banner = null;
spawnerBlockType = null; spawnerBlockType = null;
chestContents = new HashMap<Byte,ItemStack>(); chestContents = new HashMap<>();
} }
/** /**
* @return the type * @return the type
@ -265,7 +265,7 @@ public class IslandBlock {
*/ */
public void setSpawnerType(Map<String, Tag> tileData) { public void setSpawnerType(Map<String, Tag> tileData) {
//Bukkit.getLogger().info("DEBUG: " + tileData.toString()); //Bukkit.getLogger().info("DEBUG: " + tileData.toString());
String creatureType = ""; String creatureType = "";
if (tileData.containsKey("EntityId")) { if (tileData.containsKey("EntityId")) {
creatureType = ((StringTag) tileData.get("EntityId")).getValue().toUpperCase(); creatureType = ((StringTag) tileData.get("EntityId")).getValue().toUpperCase();
} else if (tileData.containsKey("SpawnData")) { } else if (tileData.containsKey("SpawnData")) {
@ -298,8 +298,8 @@ public class IslandBlock {
* @param tileData * @param tileData
*/ */
public void setSign(Map<String, Tag> tileData) { public void setSign(Map<String, Tag> tileData) {
signText = new ArrayList<String>(); signText = new ArrayList<>();
List<String> text = new ArrayList<String>(); List<String> text = new ArrayList<>();
for (int i = 1; i < 5; i++) { for (int i = 1; i < 5; i++) {
String line = ((StringTag) tileData.get("Text" + String.valueOf(i))).getValue(); String line = ((StringTag) tileData.get("Text" + String.valueOf(i))).getValue();
// This value can actually be a string that says null sometimes. // This value can actually be a string that says null sometimes.
@ -374,7 +374,7 @@ public class IslandBlock {
Bukkit.getLogger().warning("Unknown format " + value +" in sign when pasting schematic, skipping..."); Bukkit.getLogger().warning("Unknown format " + value +" in sign when pasting schematic, skipping...");
} }
} }
} }
} }
} else { } else {
// This is unformatted text. It is included in "". A reset is required to clear // This is unformatted text. It is included in "". A reset is required to clear
@ -382,7 +382,7 @@ public class IslandBlock {
if (format.length()>1) { if (format.length()>1) {
lineText += ChatColor.RESET + format.substring(format.indexOf('"')+1,format.lastIndexOf('"')); lineText += ChatColor.RESET + format.substring(format.indexOf('"')+1,format.lastIndexOf('"'));
} }
} }
} }
} else { } else {
// No extra tag // No extra tag

View File

@ -87,7 +87,7 @@ public class Schematic {
private String description; private String description;
private int rating; private int rating;
private boolean useDefaultChest; private boolean useDefaultChest;
private Material icon; private Material icon;
private Biome biome; private Biome biome;
private boolean usePhysics; private boolean usePhysics;
private boolean pasteEntities; private boolean pasteEntities;
@ -142,7 +142,7 @@ public class Schematic {
perm = ""; perm = "";
icon = Material.MAP; icon = Material.MAP;
rating = 50; rating = 50;
useDefaultChest = true; useDefaultChest = true;
biome = Settings.defaultBiome; biome = Settings.defaultBiome;
usePhysics = Settings.usePhysics; usePhysics = Settings.usePhysics;
file = null; file = null;
@ -269,7 +269,7 @@ public class Schematic {
attachable.add(Material.BIRCH_DOOR.getId()); attachable.add(Material.BIRCH_DOOR.getId());
attachable.add(Material.SPRUCE_DOOR.getId()); attachable.add(Material.SPRUCE_DOOR.getId());
attachable.add(Material.DARK_OAK_DOOR.getId()); attachable.add(Material.DARK_OAK_DOOR.getId());
attachable.add(Material.JUNGLE_DOOR.getId()); attachable.add(Material.JUNGLE_DOOR.getId());
} }
// Entities // Entities
@ -380,7 +380,7 @@ public class Schematic {
ent.setType(type); ent.setType(type);
break; break;
} }
} }
} }
} }
@ -478,7 +478,7 @@ public class Schematic {
if (itemEntry.getValue() instanceof StringTag){ if (itemEntry.getValue() instanceof StringTag){
ent.setId(((StringTag) itemEntry.getValue()).getValue()); ent.setId(((StringTag) itemEntry.getValue()).getValue());
} }
} }
} }
} }
} else if (entry.getKey().equals("TileX")){ } else if (entry.getKey().equals("TileX")){
@ -583,7 +583,7 @@ public class Schematic {
} else if (blocks[index] == 2) { } else if (blocks[index] == 2) {
// Grass // Grass
grassBlocks.add(new Vector(x,y,z)); grassBlocks.add(new Vector(x,y,z));
} }
} }
} }
} }
@ -762,8 +762,8 @@ public class Schematic {
* This method pastes a schematic. * This method pastes a schematic.
* @param loc * @param loc
* @param player * @param player
* @param oldIsland * @param oldIsland
* @param partner * @param partner
*/ */
public void pasteSchematic(final Location loc, final Player player, boolean teleport, final PasteReason reason, Island oldIsland) { public void pasteSchematic(final Location loc, final Player player, boolean teleport, final PasteReason reason, Island oldIsland) {
// If this is not a file schematic, paste the default island // If this is not a file schematic, paste the default island
@ -895,7 +895,7 @@ public class Schematic {
spawned.setVelocity(ent.getMotion()); spawned.setVelocity(ent.getMotion());
if (ent.getType() == EntityType.SHEEP) { if (ent.getType() == EntityType.SHEEP) {
Sheep sheep = (Sheep)spawned; Sheep sheep = (Sheep)spawned;
if (ent.isSheared()) { if (ent.isSheared()) {
sheep.setSheared(true); sheep.setSheared(true);
} }
DyeColor[] set = DyeColor.values(); DyeColor[] set = DyeColor.values();
@ -951,7 +951,7 @@ public class Schematic {
grass = gr; grass = gr;
} else { } else {
grass = null; grass = null;
} }
//Bukkit.getLogger().info("DEBUG cow location " + grass); //Bukkit.getLogger().info("DEBUG cow location " + grass);
Block blockToChange = null; Block blockToChange = null;
@ -1088,7 +1088,7 @@ public class Schematic {
//IslandCmd.runCommands(Settings.resetCommands, player); //IslandCmd.runCommands(Settings.resetCommands, player);
} }
} }
// Delete the old island if required // Delete the old island if required
if (oldIsland != null) { if (oldIsland != null) {
plugin.getLogger().info("DEBUG: Deleting old island"); plugin.getLogger().info("DEBUG: Deleting old island");
@ -1237,7 +1237,7 @@ public class Schematic {
public void setIcon(Material icon, int damage) { public void setIcon(Material icon, int damage) {
this.icon = icon; this.icon = icon;
this.durability = damage; this.durability = damage;
} }
/** /**
* @param icon the icon to set * @param icon the icon to set
@ -1302,7 +1302,7 @@ public class Schematic {
* Creates the AcidIsland default island block by block * Creates the AcidIsland default island block by block
* @param islandLoc * @param islandLoc
* @param player * @param player
* @param reason * @param reason
*/ */
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void generateIslandBlocks(final Location islandLoc, final Player player, PasteReason reason) { public void generateIslandBlocks(final Location islandLoc, final Player player, PasteReason reason) {
@ -1476,7 +1476,7 @@ public class Schematic {
//plugin.getLogger().info("DEBUG: Reset"); //plugin.getLogger().info("DEBUG: Reset");
if (!player.hasPermission(Settings.PERMPREFIX + "command.resetexempt")) { if (!player.hasPermission(Settings.PERMPREFIX + "command.resetexempt")) {
//plugin.getLogger().info("DEBUG: Executing reset island commands"); //plugin.getLogger().info("DEBUG: Executing reset island commands");
// IslandCmd.runCommands(Settings.resetCommands, player); // IslandCmd.runCommands(Settings.resetCommands, player);
} }
} }
if (!islandCompanion.isEmpty()) { if (!islandCompanion.isEmpty()) {
@ -1490,7 +1490,7 @@ public class Schematic {
} }
/** /**
* Get child tag of a NBT structure. * Get child tag of a NBT structure.
* *
* @param items * @param items
* The parent tag map * The parent tag map
* @param key * @param key
@ -1529,7 +1529,7 @@ public class Schematic {
//plugin.getLogger().info("DEBUG: name is " + name); //plugin.getLogger().info("DEBUG: name is " + name);
companion.setCustomName(name); companion.setCustomName(name);
companion.setCustomNameVisible(true); companion.setCustomNameVisible(true);
} }
} }
} }
} }

View File

@ -29,7 +29,7 @@ public class SchematicsMgr {
this.plugin = plugin; this.plugin = plugin;
loadSchematics(); loadSchematics();
} }
/** /**
* Loads schematics. If the default * Loads schematics. If the default
* island is not included, it will be made * island is not included, it will be made
@ -90,7 +90,7 @@ public class SchematicsMgr {
} catch (IOException e) { } catch (IOException e) {
plugin.getLogger().severe("Could not load default nether schematic!"); plugin.getLogger().severe("Could not load default nether schematic!");
e.printStackTrace(); e.printStackTrace();
} }
} else { } else {
plugin.getLogger().severe("Could not find default nether schematic!"); plugin.getLogger().severe("Could not find default nether schematic!");
} }
@ -130,7 +130,7 @@ public class SchematicsMgr {
schematics.get("nether").setUseDefaultChest(false); schematics.get("nether").setUseDefaultChest(false);
} }
} }
// TODO: Load other settings from config.yml // TODO: Load other settings from config.yml
} }
@ -142,7 +142,7 @@ public class SchematicsMgr {
public Schematic getSchematic(String name) { public Schematic getSchematic(String name) {
return schematics.get(name); return schematics.get(name);
} }
/** /**
* List schematics this player can access. If @param ignoreNoPermission is true, then only * List schematics this player can access. If @param ignoreNoPermission is true, then only
* schematics with a specific permission set will be checked. I.e., no common schematics will * schematics with a specific permission set will be checked. I.e., no common schematics will
@ -152,7 +152,7 @@ public class SchematicsMgr {
* @return List of schematics this player can use based on their permission level * @return List of schematics this player can use based on their permission level
*/ */
public List<Schematic> getSchematics(Player player, boolean ignoreNoPermission) { public List<Schematic> getSchematics(Player player, boolean ignoreNoPermission) {
List<Schematic> result = new ArrayList<Schematic>(); List<Schematic> result = new ArrayList<>();
// Find out what schematics this player can choose from // Find out what schematics this player can choose from
//Bukkit.getLogger().info("DEBUG: Checking schematics for " + player.getName()); //Bukkit.getLogger().info("DEBUG: Checking schematics for " + player.getName());
for (Schematic schematic : schematics.values()) { for (Schematic schematic : schematics.values()) {
@ -175,14 +175,7 @@ public class SchematicsMgr {
} }
} }
// Sort according to order // Sort according to order
Collections.sort(result, new Comparator<Schematic>() { Collections.sort(result, (s1, s2) -> (s2.getOrder() < s1.getOrder()) ? 1 : -1);
@Override
public int compare(Schematic o1, Schematic o2) {
return ((o2.getOrder() < o1.getOrder()) ? 1 : -1);
}
});
return result; return result;
} }

View File

@ -21,13 +21,13 @@ import us.tastybento.bskyblock.util.nms.NMSAbstraction;
/** /**
* Deletes islands fast using chunk regeneration * Deletes islands fast using chunk regeneration
* *
* @author tastybento * @author tastybento
* *
*/ */
public class DeleteIslandBlocks { public class DeleteIslandBlocks {
protected static final int CLEAN_RATE = 2; protected static final int CLEAN_RATE = 2;
private Set<Pair> chunksToClear = new HashSet<Pair>(); private Set<Pair> chunksToClear = new HashSet<>();
//private HashMap<Location, Material> blocksToClear = new HashMap<Location,Material>(); //private HashMap<Location, Material> blocksToClear = new HashMap<Location,Material>();
private NMSAbstraction nms = null; private NMSAbstraction nms = null;
@ -133,7 +133,7 @@ public class DeleteIslandBlocks {
public void run() { public void run() {
Iterator<Pair> it = chunksToClear.iterator(); Iterator<Pair> it = chunksToClear.iterator();
int count = 0; int count = 0;
while (it.hasNext() && count++ < CLEAN_RATE) { while (it.hasNext() && count++ < CLEAN_RATE) {
Pair pair = it.next(); Pair pair = it.next();
//plugin.getLogger().info("DEBUG: There are " + chunksToClear.size() + " chunks that need to be cleared up"); //plugin.getLogger().info("DEBUG: There are " + chunksToClear.size() + " chunks that need to be cleared up");
//plugin.getLogger().info("DEBUG: Deleting chunk " + pair.getLeft() + ", " + pair.getRight()); //plugin.getLogger().info("DEBUG: Deleting chunk " + pair.getLeft() + ", " + pair.getRight());
@ -142,12 +142,12 @@ public class DeleteIslandBlocks {
for (int z = 0; z < 16; z ++) { for (int z = 0; z < 16; z ++) {
int xCoord = pair.getLeft() * 16 + x; int xCoord = pair.getLeft() * 16 + x;
int zCoord = pair.getRight() * 16 + z; int zCoord = pair.getRight() * 16 + z;
if (island.inIslandSpace(xCoord, zCoord)) { if (island.inIslandSpace(xCoord, zCoord)) {
//plugin.getLogger().info(xCoord + "," + zCoord + " is in island space - deleting column"); //plugin.getLogger().info(xCoord + "," + zCoord + " is in island space - deleting column");
// Delete all the blocks here // Delete all the blocks here
for (int y = 0; y < IslandWorld.getIslandWorld().getMaxHeight(); y ++) { for (int y = 0; y < IslandWorld.getIslandWorld().getMaxHeight(); y ++) {
// Overworld // Overworld
Block b = IslandWorld.getIslandWorld().getBlockAt(xCoord, y, zCoord); Block b = IslandWorld.getIslandWorld().getBlockAt(xCoord, y, zCoord);
Material bt = b.getType(); Material bt = b.getType();
Material setTo = Material.AIR; Material setTo = Material.AIR;
// Split depending on below or above water line // Split depending on below or above water line
@ -157,57 +157,57 @@ public class DeleteIslandBlocks {
// Grab anything out of containers (do that it is // Grab anything out of containers (do that it is
// destroyed) // destroyed)
switch (bt) { switch (bt) {
case CHEST: case CHEST:
case TRAPPED_CHEST: case TRAPPED_CHEST:
case FURNACE: case FURNACE:
case DISPENSER: case DISPENSER:
case HOPPER: case HOPPER:
final InventoryHolder ih = ((InventoryHolder)b.getState()); final InventoryHolder ih = ((InventoryHolder)b.getState());
ih.getInventory().clear(); ih.getInventory().clear();
b.setType(setTo); b.setType(setTo);
break; break;
case AIR: case AIR:
if (setTo.equals(Material.STATIONARY_WATER)) { if (setTo.equals(Material.STATIONARY_WATER)) {
nms.setBlockSuperFast(b, setTo.getId(), (byte)0, false);
}
case STATIONARY_WATER:
if (setTo.equals(Material.AIR)) {
nms.setBlockSuperFast(b, setTo.getId(), (byte)0, false);
}
default:
nms.setBlockSuperFast(b, setTo.getId(), (byte)0, false); nms.setBlockSuperFast(b, setTo.getId(), (byte)0, false);
} break;
case STATIONARY_WATER:
if (setTo.equals(Material.AIR)) {
nms.setBlockSuperFast(b, setTo.getId(), (byte)0, false);
}
default:
nms.setBlockSuperFast(b, setTo.getId(), (byte)0, false);
break;
} }
// Nether, if it exists // Nether, if it exists
if (Settings.netherIslands && Settings.netherGenerate && y < IslandWorld.getNetherWorld().getMaxHeight() - 8) { if (Settings.netherIslands && Settings.netherGenerate && y < IslandWorld.getNetherWorld().getMaxHeight() - 8) {
b = IslandWorld.getNetherWorld().getBlockAt(xCoord, y, zCoord); b = IslandWorld.getNetherWorld().getBlockAt(xCoord, y, zCoord);
bt = b.getType(); bt = b.getType();
if (!b.equals(Material.AIR)) { if (!bt.equals(Material.AIR)) {
setTo = Material.AIR; setTo = Material.AIR;
// Grab anything out of containers (do that it is // Grab anything out of containers (do that it is
// destroyed) // destroyed)
switch (bt) { switch (bt) {
case CHEST: case CHEST:
case TRAPPED_CHEST: case TRAPPED_CHEST:
case FURNACE: case FURNACE:
case DISPENSER: case DISPENSER:
case HOPPER: case HOPPER:
final InventoryHolder ih = ((InventoryHolder)b.getState()); final InventoryHolder ih = ((InventoryHolder)b.getState());
ih.getInventory().clear(); ih.getInventory().clear();
b.setType(setTo); b.setType(setTo);
break; break;
default: default:
nms.setBlockSuperFast(b, setTo.getId(), (byte)0, false); nms.setBlockSuperFast(b, setTo.getId(), (byte)0, false);
break; break;
} }
} }
} }
} }
} }
} }
} }
it.remove(); it.remove();
} }
if (chunksToClear.isEmpty()){ if (chunksToClear.isEmpty()){
plugin.getLogger().info("Finished island deletion"); plugin.getLogger().info("Finished island deletion");
this.cancel(); this.cancel();
@ -217,7 +217,7 @@ public class DeleteIslandBlocks {
} }
} }
/** /**
* Class that pairs two ints together * Class that pairs two ints together
* @author tastybento * @author tastybento

View File

@ -35,27 +35,16 @@ public class FileLister{
* @throws IOException * @throws IOException
*/ */
public List<String> list(String folderPath, boolean checkJar) throws IOException { public List<String> list(String folderPath, boolean checkJar) throws IOException {
List<String> result = new ArrayList<String>(); List<String> result = new ArrayList<>();
// Check if the folder exists // Check if the folder exists
File localeDir = new File(plugin.getDataFolder(), folderPath); File localeDir = new File(plugin.getDataFolder(), folderPath);
if (localeDir.exists()) { if (localeDir.exists()) {
FilenameFilter ymlFilter = new FilenameFilter() { FilenameFilter ymlFilter = (File dir, String name) -> name.toLowerCase().endsWith(".yml");
@Override
public boolean accept(File dir, String name) {
String lowercaseName = name.toLowerCase();
//plugin.getLogger().info("DEBUG: filename = " + name);
if (lowercaseName.endsWith(".yml")) {
return true;
} else {
return false;
}
}
};
return Arrays.asList(localeDir.list(ymlFilter)); return Arrays.asList(localeDir.list(ymlFilter));
} else if (checkJar) { } else if (checkJar) {
// Else look in the JAR // Else look in the JAR
File jarfile = null; File jarfile;
/** /**
* Get the jar file from the plugin. * Get the jar file from the plugin.
@ -98,9 +87,9 @@ public class FileLister{
} }
public List<String> listJar(String folderPath) throws IOException { public List<String> listJar(String folderPath) throws IOException {
List<String> result = new ArrayList<String>(); List<String> result = new ArrayList<>();
// Look in the JAR // Look in the JAR
File jarfile = null; File jarfile;
/** /**
* Get the jar file from the plugin. * Get the jar file from the plugin.

View File

@ -20,7 +20,7 @@ import us.tastybento.bskyblock.database.objects.Island;
/** /**
* A class that calculates finds a safe spot asynchronously and then teleports the player there. * A class that calculates finds a safe spot asynchronously and then teleports the player there.
* @author tastybento * @author tastybento
* *
*/ */
public class SafeSpotTeleport { public class SafeSpotTeleport {
@ -56,7 +56,7 @@ public class SafeSpotTeleport {
*/ */
public SafeSpotTeleport(final BSkyBlock plugin, final Entity player, final Location l) { public SafeSpotTeleport(final BSkyBlock plugin, final Entity player, final Location l) {
new SafeSpotTeleport(plugin, player, l, 1, "", false); new SafeSpotTeleport(plugin, player, l, 1, "", false);
} }
/** /**
* Teleport to a safe spot on an island * Teleport to a safe spot on an island
@ -88,7 +88,7 @@ public class SafeSpotTeleport {
for (int z = island.getMinProtectedZ() /16; z <= (island.getMinProtectedZ() + island.getProtectionRange() - 1)/16; z++) { for (int z = island.getMinProtectedZ() /16; z <= (island.getMinProtectedZ() + island.getProtectionRange() - 1)/16; z++) {
// This includes the center spots again, so is not as efficient... // This includes the center spots again, so is not as efficient...
chunkSnapshot.add(world.getChunkAt(x, z).getChunkSnapshot()); chunkSnapshot.add(world.getChunkAt(x, z).getChunkSnapshot());
} }
} }
//plugin.getLogger().info("DEBUG: size of chunk ss = " + chunkSnapshot.size()); //plugin.getLogger().info("DEBUG: size of chunk ss = " + chunkSnapshot.size());
final List<ChunkSnapshot> finalChunk = chunkSnapshot; final List<ChunkSnapshot> finalChunk = chunkSnapshot;
@ -223,23 +223,20 @@ public class SafeSpotTeleport {
if (player.getGameMode().equals(GameMode.SPECTATOR)) { if (player.getGameMode().equals(GameMode.SPECTATOR)) {
player.setGameMode(GameMode.SURVIVAL); player.setGameMode(GameMode.SURVIVAL);
} }
} }
}}); }});
} else { } else {
// We did not find a spot // We did not find a spot
plugin.getServer().getScheduler().runTask(plugin, new Runnable() { plugin.getServer().getScheduler().runTask(plugin, () -> {
//plugin.getLogger().info("DEBUG: safe spot not found");
@Override if (entity instanceof Player) {
public void run() { if (!failureMessage.isEmpty()) {
//plugin.getLogger().info("DEBUG: safe spot not found"); Util.sendMessage(entity, failureMessage);
if (entity instanceof Player) { } else {
if (!failureMessage.isEmpty()) { Util.sendMessage(entity, ChatColor.RED + "Warp not safe");
Util.sendMessage(((Player)entity), failureMessage);
} else {
Util.sendMessage(((Player)entity), ChatColor.RED + "Warp not safe");
}
} }
}}); }
});
} }
} }
@ -249,7 +246,7 @@ public class SafeSpotTeleport {
* @param x * @param x
* @param y * @param y
* @param z * @param z
* @param worldHeight * @param worldHeight
* @return * @return
*/ */
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@ -262,44 +259,44 @@ public class SafeSpotTeleport {
// Now there is a chance that this is a safe spot // Now there is a chance that this is a safe spot
// Check for safe ground // Check for safe ground
Material mat = Material.getMaterial(type); Material mat = Material.getMaterial(type);
if (!mat.toString().contains("FENCE") if (!mat.toString().contains("FENCE")
&& !mat.toString().contains("DOOR") && !mat.toString().contains("DOOR")
&& !mat.toString().contains("GATE") && !mat.toString().contains("GATE")
&& !mat.toString().contains("PLATE")) { && !mat.toString().contains("PLATE")) {
switch (mat) { switch (mat) {
// Unsafe // Unsafe
case ANVIL: case ANVIL:
case BARRIER: case BARRIER:
case BOAT: case BOAT:
case CACTUS: case CACTUS:
case DOUBLE_PLANT: case DOUBLE_PLANT:
case ENDER_PORTAL: case ENDER_PORTAL:
case FIRE: case FIRE:
case FLOWER_POT: case FLOWER_POT:
case LADDER: case LADDER:
case LAVA: case LAVA:
case LEVER: case LEVER:
case LONG_GRASS: case LONG_GRASS:
case PISTON_EXTENSION: case PISTON_EXTENSION:
case PISTON_MOVING_PIECE: case PISTON_MOVING_PIECE:
case PORTAL: case PORTAL:
case SIGN_POST: case SIGN_POST:
case SKULL: case SKULL:
case STANDING_BANNER: case STANDING_BANNER:
case STATIONARY_LAVA: case STATIONARY_LAVA:
case STATIONARY_WATER: case STATIONARY_WATER:
case STONE_BUTTON: case STONE_BUTTON:
case TORCH: case TORCH:
case TRIPWIRE: case TRIPWIRE:
case WATER: case WATER:
case WEB: case WEB:
case WOOD_BUTTON: case WOOD_BUTTON:
//System.out.println("Block is dangerous " + mat.toString()); //System.out.println("Block is dangerous " + mat.toString());
break; break;
default: default:
// Safe // Safe
// System.out.println("Block is safe " + mat.toString()); // System.out.println("Block is safe " + mat.toString());
return true; return true;
} }
} }
} }
@ -308,40 +305,4 @@ public class SafeSpotTeleport {
}}); }});
} }
} }
/**
* Checks what version the server is running and picks the appropriate NMS handler, or fallback
* @return NMSAbstraction class
* @throws ClassNotFoundException
* @throws IllegalArgumentException
* @throws SecurityException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws NoSuchMethodException
*/
/*
private NMSAbstraction checkVersion() throws ClassNotFoundException, IllegalArgumentException,
SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
String serverPackageName = plugin.getServer().getClass().getPackage().getName();
String pluginPackageName = plugin.getClass().getPackage().getName();
String version = serverPackageName.substring(serverPackageName.lastIndexOf('.') + 1);
Class<?> clazz;
try {
//plugin.getLogger().info("DEBUG: Trying " + pluginPackageName + ".nms." + version + ".NMSHandler");
clazz = Class.forName(pluginPackageName + ".nms." + version + ".NMSHandler");
} catch (Exception e) {
plugin.getLogger().info("No NMS Handler found, falling back to Bukkit API.");
clazz = Class.forName(pluginPackageName + ".nms.fallback.NMSHandler");
}
//plugin.getLogger().info("DEBUG: " + serverPackageName);
//plugin.getLogger().info("DEBUG: " + pluginPackageName);
// Check if we have a NMSAbstraction implementing class at that location.
if (NMSAbstraction.class.isAssignableFrom(clazz)) {
return (NMSAbstraction) clazz.getConstructor().newInstance();
} else {
throw new IllegalStateException("Class " + clazz.getName() + " does not implement NMSAbstraction");
}
}*/
} }

View File

@ -27,7 +27,7 @@ import us.tastybento.bskyblock.util.placeholders.PlaceholderHandler;
/** /**
* A set of utility methods * A set of utility methods
* *
* @author Tastybento * @author Tastybento
* @author Poslovitch * @author Poslovitch
*/ */
@ -36,7 +36,7 @@ public class Util {
public static void sendMessage(CommandSender receiver, String message){ public static void sendMessage(CommandSender receiver, String message){
message = PlaceholderHandler.replacePlaceholders(receiver, message); message = PlaceholderHandler.replacePlaceholders(receiver, message);
if (!ChatColor.stripColor(message).trim().isEmpty()) { if (!ChatColor.stripColor(message).trim().isEmpty()) {
for(String part : message.split("\n")){ for(String part : message.split("\n")){
receiver.sendMessage(part); receiver.sendMessage(part);
@ -56,8 +56,8 @@ public class Util {
* @throws NoSuchMethodException * @throws NoSuchMethodException
*/ */
public static NMSAbstraction getNMSHandler() throws ClassNotFoundException, IllegalArgumentException, public static NMSAbstraction getNMSHandler() throws ClassNotFoundException, IllegalArgumentException,
SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException,
NoSuchMethodException { NoSuchMethodException {
String serverPackageName = plugin.getServer().getClass().getPackage().getName(); String serverPackageName = plugin.getServer().getClass().getPackage().getName();
String pluginPackageName = plugin.getClass().getPackage().getName(); String pluginPackageName = plugin.getClass().getPackage().getName();
String version = serverPackageName.substring(serverPackageName.lastIndexOf('.') + 1); String version = serverPackageName.substring(serverPackageName.lastIndexOf('.') + 1);
@ -79,13 +79,13 @@ public class Util {
/** /**
* Converts a serialized location to a Location. Returns null if string is * Converts a serialized location to a Location. Returns null if string is
* empty * empty
* *
* @param s * @param s
* - serialized location in format "world:x:y:z" * - serialized location in format "world:x:y:z"
* @return Location * @return Location
*/ */
static public Location getLocationString(final String s) { static public Location getLocationString(final String s) {
if (s == null || s.trim() == "") { if (s == null || s.trim().equals("")) {
return null; return null;
} }
final String[] parts = s.split(":"); final String[] parts = s.split(":");
@ -116,7 +116,7 @@ public class Util {
/** /**
* Converts a location to a simple string representation * Converts a location to a simple string representation
* If location is null, returns empty string * If location is null, returns empty string
* *
* @param location * @param location
* @return String of location * @return String of location
*/ */
@ -126,14 +126,14 @@ public class Util {
} }
return location.getWorld().getName() + ":" + location.getBlockX() + ":" + location.getBlockY() + ":" + location.getBlockZ() + ":" + Float.floatToIntBits(location.getYaw()) + ":" + Float.floatToIntBits(location.getPitch()); return location.getWorld().getName() + ":" + location.getBlockX() + ":" + location.getBlockY() + ":" + location.getBlockZ() + ":" + Float.floatToIntBits(location.getYaw()) + ":" + Float.floatToIntBits(location.getPitch());
} }
/** /**
* Get a list of parameter types for the collection argument in this method * Get a list of parameter types for the collection argument in this method
* @param writeMethod * @param writeMethod
* @return * @return
*/ */
public static List<Type> getCollectionParameterTypes(Method writeMethod) { public static List<Type> getCollectionParameterTypes(Method writeMethod) {
List<Type> result = new ArrayList<Type>(); List<Type> result = new ArrayList<>();
// Get the return type // Get the return type
// This uses a trick to extract what the arguments are of the writeMethod of the field. // This uses a trick to extract what the arguments are of the writeMethod of the field.
// In this way, we can deduce what type needs to be written at runtime. // In this way, we can deduce what type needs to be written at runtime.
@ -164,7 +164,7 @@ public class Util {
public static List<ItemStack> getPlayerInHandItems(Player player) { public static List<ItemStack> getPlayerInHandItems(Player player) {
List<ItemStack> result = new ArrayList<ItemStack>(2); List<ItemStack> result = new ArrayList<ItemStack>(2);
if (plugin.getServer().getVersion().contains("(MC: 1.7") if (plugin.getServer().getVersion().contains("(MC: 1.7")
|| plugin.getServer().getVersion().contains("(MC: 1.8")) { || plugin.getServer().getVersion().contains("(MC: 1.8")) {
if (player.getItemInHand() != null) if (player.getItemInHand() != null)
result.add(player.getItemInHand()); result.add(player.getItemInHand());
return result; return result;
@ -178,11 +178,11 @@ public class Util {
/** /**
* Converts a name like IRON_INGOT into Iron Ingot to improve readability * Converts a name like IRON_INGOT into Iron Ingot to improve readability
* *
* @param ugly * @param ugly
* The string such as IRON_INGOT * The string such as IRON_INGOT
* @return A nicer version, such as Iron Ingot * @return A nicer version, such as Iron Ingot
* *
* Credits to mikenon on GitHub! * Credits to mikenon on GitHub!
*/ */
public static String prettifyText(String ugly) { public static String prettifyText(String ugly) {
@ -214,7 +214,7 @@ public class Util {
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public static boolean playerIsHolding(Player player, Material type) { public static boolean playerIsHolding(Player player, Material type) {
if (plugin.getServer().getVersion().contains("(MC: 1.7") if (plugin.getServer().getVersion().contains("(MC: 1.7")
|| plugin.getServer().getVersion().contains("(MC: 1.8")) { || plugin.getServer().getVersion().contains("(MC: 1.8")) {
if (player.getItemInHand() != null && player.getItemInHand().getType().equals(type)) { if (player.getItemInHand() != null && player.getItemInHand().getType().equals(type)) {
return true; return true;
} }
@ -228,7 +228,7 @@ public class Util {
} }
return false; return false;
} }
/** /**
* Display message to player in action bar (1.11+ or chat) * Display message to player in action bar (1.11+ or chat)
* @param player * @param player
@ -246,7 +246,7 @@ public class Util {
plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(),
"minecraft:title " + player.getName() + " actionbar {\"text\":\"" + ChatColor.stripColor(message) + "\"}"); "minecraft:title " + player.getName() + " actionbar {\"text\":\"" + ChatColor.stripColor(message) + "\"}");
} }
/** /**
* Determines if a location is in the island world or not or * Determines if a location is in the island world or not or
* in the new nether if it is activated * in the new nether if it is activated
@ -267,7 +267,7 @@ public class Util {
} }
return true; return true;
} }
/** /**
* Determines if an entity is in the island world or not or * Determines if an entity is in the island world or not or
* in the new nether if it is activated * in the new nether if it is activated
@ -293,27 +293,27 @@ public class Util {
* @return * @return
*/ */
public static List<String> getOnlinePlayerList(Player player) { public static List<String> getOnlinePlayerList(Player player) {
final List<String> returned = new ArrayList<String>(); final List<String> returned = new ArrayList<>();
for (Player p : Bukkit.getServer().getOnlinePlayers()) { for (Player p : Bukkit.getServer().getOnlinePlayers()) {
if (player == null) { if (player == null) {
returned.add(p.getName()); returned.add(p.getName());
} else if (player.canSee(p)) { } else if (player.canSee(p)) {
returned.add(p.getName()); returned.add(p.getName());
} }
} }
return returned; return returned;
} }
/** /**
* Returns all of the items that begin with the given start, * Returns all of the items that begin with the given start,
* ignoring case. Intended for tabcompletion. * ignoring case. Intended for tabcompletion.
* *
* @param list * @param list
* @param start * @param start
* @return List of items that start with the letters * @return List of items that start with the letters
*/ */
public static List<String> tabLimit(final List<String> list, final String start) { public static List<String> tabLimit(final List<String> list, final String start) {
final List<String> returned = new ArrayList<String>(); final List<String> returned = new ArrayList<>();
for (String s : list) { for (String s : list) {
if (s == null) if (s == null)
continue; continue;

View File

@ -17,7 +17,7 @@ public class VaultHelper {
/** /**
* Sets up the economy instance * Sets up the economy instance
* *
* @return true if successful * @return true if successful
*/ */
public static boolean setupEconomy() { public static boolean setupEconomy() {
@ -31,7 +31,7 @@ public class VaultHelper {
/** /**
* Sets up the permissions instance * Sets up the permissions instance
* *
* @return true if successful * @return true if successful
*/ */
public static boolean setupPermissions() { public static boolean setupPermissions() {
@ -45,7 +45,7 @@ public class VaultHelper {
/** /**
* Checks permission of player in the world the player is in now * Checks permission of player in the world the player is in now
* *
* @param player * @param player
* @param perm * @param perm
* @return true if the player has the perm * @return true if the player has the perm
@ -56,7 +56,7 @@ public class VaultHelper {
/** /**
* Checks permission of player in world * Checks permission of player in world
* *
* @param player * @param player
* @param perm * @param perm
* @param world * @param world
@ -68,14 +68,14 @@ public class VaultHelper {
/** /**
* Adds permission to player * Adds permission to player
* *
* @param player * @param player
* @param perm * @param perm
*/ */
public static void addPerm(final Player player, final String perm) { public static void addPerm(final Player player, final String perm) {
permission.playerAdd(player, perm); permission.playerAdd(player, perm);
} }
/** /**
* Add permission to player in world * Add permission to player in world
* @param player * @param player
@ -88,7 +88,7 @@ public class VaultHelper {
/** /**
* Removes a player's permission * Removes a player's permission
* *
* @param player * @param player
* @param perm * @param perm
*/ */
@ -98,7 +98,7 @@ public class VaultHelper {
/** /**
* Removes a player's permission in world * Removes a player's permission in world
* *
* @param player * @param player
* @param perm * @param perm
* @param world * @param world