diff --git a/.gitignore b/.gitignore index 108e0cc..b164e3a 100644 --- a/.gitignore +++ b/.gitignore @@ -13,4 +13,21 @@ # Maven log/ -target/ \ No newline at end of file +target/ +### Java template +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + + + +out \ No newline at end of file diff --git a/src/com/jcdesimp/landlord/LandAlerter.java b/src/com/jcdesimp/landlord/LandAlerter.java index e1b9848..bd87d59 100644 --- a/src/com/jcdesimp/landlord/LandAlerter.java +++ b/src/com/jcdesimp/landlord/LandAlerter.java @@ -3,6 +3,7 @@ import com.jcdesimp.landlord.persistantData.OwnedLand; import org.bukkit.ChatColor; import org.bukkit.Location; +import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -19,77 +20,88 @@ */ public class LandAlerter implements Listener { - HashMap landIn = new HashMap(); + HashMap landIn = new HashMap(); + private Landlord plugin; + + + public LandAlerter(Landlord plugin) { + this.plugin = plugin; + } + public void landAlertPlayer(Player player, Location loc) { + + FileConfiguration messages = plugin.getMessageConfig(); + + String leaveOwn = messages.getString("info.alerts.leaveOwnLand"); + String leaveOther = messages.getString("info.alerts.leaveOtherLand"); + String enterOwn = messages.getString("info.alerts.enterOwnLand"); + String enterOther = messages.getString("info.alerts.enterOtherLand"); + OwnedLand land = OwnedLand.getApplicableLand(loc); //Leaving Land - if(landIn.containsKey(player.getName())){ - if(land==null){ + if (landIn.containsKey(player.getName())) { + if (land == null) { String prevName = landIn.get(player.getName()); - if(prevName.equals(player.getName())){ - player.sendMessage(ChatColor.YELLOW+"** Now leaving your land."); + if (prevName.equals(player.getName())) { + player.sendMessage(ChatColor.YELLOW + "** " + leaveOwn); } else { - player.sendMessage(ChatColor.YELLOW+"** Now leaving "+ prevName +"'s land."); + player.sendMessage(ChatColor.YELLOW + "** " + (leaveOther.replace("#{owner}", prevName))); } } else { String prevName = landIn.get(player.getName()); - if(!prevName.equals(land.getOwnerUsername())){ - if(prevName.equals(player.getName())){ - player.sendMessage(ChatColor.YELLOW+"** Now leaving your land."); + if (!prevName.equals(land.getOwnerUsername())) { + if (prevName.equals(player.getName())) { + player.sendMessage(ChatColor.YELLOW + "** " + leaveOwn); } else { - player.sendMessage(ChatColor.YELLOW+"** Now leaving "+ prevName +"'s land."); + player.sendMessage(ChatColor.YELLOW + "** " + (leaveOther.replace("#{owner}", prevName))); } } } } - //Entering Land - if(land==null){ + if (land == null) { landIn.remove(player.getName()); return; } - if(landIn.containsKey(player.getName())) { + if (landIn.containsKey(player.getName())) { String prevName = landIn.get(player.getName()); if (!prevName.equals(land.getOwnerUsername())) { landIn.put(player.getName(), land.getOwnerUsername()); if (land.getOwnerUsername().equals(player.getName())) { - player.sendMessage(ChatColor.GREEN + "** Now entering your land."); + player.sendMessage(ChatColor.GREEN + "** " + enterOwn); } else { String ownerName = land.getOwnerUsername(); - player.sendMessage(ChatColor.YELLOW + "** Now entering " + ownerName + "'s land."); + player.sendMessage(ChatColor.YELLOW + "** " + enterOther.replace("#{owner}", ownerName)); } } } else { landIn.put(player.getName(), land.getOwnerUsername()); if (land.getOwnerUsername().equals(player.getName())) { - player.sendMessage(ChatColor.GREEN + "** Now entering your land."); + player.sendMessage(ChatColor.GREEN + "** " + enterOwn); } else { String ownerName = land.getOwnerUsername(); - player.sendMessage(ChatColor.YELLOW + "** Now entering " + ownerName + "'s land."); + player.sendMessage(ChatColor.YELLOW + "** " + enterOther.replace("#{owner}", ownerName)); } } } - @EventHandler(priority = EventPriority.HIGH) public void alertPlayerMove(PlayerMoveEvent event) { Player player = event.getPlayer(); - - if (player.getVehicle() != null) { return; } @@ -101,8 +113,6 @@ public void alertPlayerMove(PlayerMoveEvent event) { landAlertPlayer(player, event.getTo()); - - } } @@ -113,7 +123,7 @@ public void teleportAlert(PlayerTeleportEvent event) { } @EventHandler(priority = EventPriority.HIGH) - public void playerLeave(PlayerQuitEvent event){ + public void playerLeave(PlayerQuitEvent event) { landIn.remove(event.getPlayer().getName()); } diff --git a/src/com/jcdesimp/landlord/Landlord.java b/src/com/jcdesimp/landlord/Landlord.java index 83372ab..3d608db 100644 --- a/src/com/jcdesimp/landlord/Landlord.java +++ b/src/com/jcdesimp/landlord/Landlord.java @@ -1,15 +1,15 @@ package com.jcdesimp.landlord; import com.avaje.ebean.EbeanServer; -//import com.lennardf1989.bukkitex.MyDatabase; +import com.jcdesimp.landlord.configuration.CustomConfig; import com.jcdesimp.landlord.landFlags.*; import com.jcdesimp.landlord.landManagement.FlagManager; -//import com.jcdesimp.landlord.landManagement.LandListener; import com.jcdesimp.landlord.landManagement.ViewManager; import com.jcdesimp.landlord.landMap.MapManager; import com.jcdesimp.landlord.persistantData.*; import com.jcdesimp.landlord.pluginHooks.VaultHandler; import com.jcdesimp.landlord.pluginHooks.WorldguardHandler; +import com.sk89q.worldguard.bukkit.WorldGuardPlugin; import net.milkbowl.vault.Vault; import org.bukkit.Bukkit; import org.bukkit.configuration.Configuration; @@ -20,35 +20,38 @@ import java.io.IOException; import java.util.ArrayList; import java.util.List; -import java.util.Map; -import com.sk89q.worldguard.bukkit.WorldGuardPlugin; - -import static org.bukkit.Bukkit.getLogger; import static org.bukkit.Bukkit.getOfflinePlayer; +//import com.lennardf1989.bukkitex.MyDatabase; +//import com.jcdesimp.landlord.landManagement.LandListener; + /** - * * Main plugin class for Landlord - * */ public final class Landlord extends JavaPlugin { private MyDatabase database; private Landlord plugin; - private MapManager mapManager = new MapManager(); + private MapManager mapManager; private WorldguardHandler wgHandler; private VaultHandler vHandler; private FlagManager flagManager; private ViewManager manageViewManager; private LandAlerter pListen; + private CustomConfig mainConfig; + private CustomConfig messagesConfig; - + public static Landlord getInstance() { + return (Landlord) Bukkit.getPluginManager().getPlugin("Landlord"); + //return Bukkit.getPluginManager().getPlugin("MyPlugin"); + } @Override public void onEnable() { plugin = this; + mapManager = new MapManager(this); //listner = new LandListener(); //getServer().getPluginManager().registerEvents(new LandListener(this), this); flagManager = new FlagManager(this); @@ -56,36 +59,13 @@ public void onEnable() { getServer().getPluginManager().registerEvents(mapManager, this); - - //// CONFIG FILE MANAGEMENT //// - - - Map oldConfig = getConfig().getValues(true); - //Generates new config file if not present - saveDefaultConfig(); - //String header = getConfig().options().header(); - FileConfiguration config = getConfig(); - - - // checks for missing entries and applies new ones - for (Map.Entry entry : config.getDefaults().getValues(true).entrySet()) - { - if(oldConfig.containsKey(entry.getKey())){ - config.set(entry.getKey(),oldConfig.get(entry.getKey())); - } else { - config.set(entry.getKey(), entry.getValue()); - } - - } - - saveConfig(); - - //////////////////////////////// - - + // generate/load the main config file + mainConfig = new CustomConfig(this, "config.yml", "config.yml"); + // generate/load the main language file based on language value in config. + messagesConfig = new CustomConfig(this, "messages/english.yml", "messages/" + (mainConfig.get().getString("options.messagesFile").replace("/", "."))); // Registering Alert Listener - pListen = new LandAlerter(); - if(getConfig().getBoolean("options.showLandAlerts",true)) { + pListen = new LandAlerter(plugin); + if (getConfig().getBoolean("options.showLandAlerts", true)) { getServer().getPluginManager().registerEvents(pListen, this); } @@ -105,25 +85,24 @@ public void onEnable() { } - // Command Executor getCommand("landlord").setExecutor(new LandlordCommandExecutor(this)); //Worldguard Check - if(!hasWorldGuard() && this.getConfig().getBoolean("worldguard.blockRegionClaim", true)){ + if (!hasWorldGuard() && this.getConfig().getBoolean("worldguard.blockRegionClaim", true)) { getLogger().warning("Worldguard not found, worldguard features disabled."); - } else if(hasWorldGuard()) { + } else if (hasWorldGuard()) { getLogger().info("Worldguard found!"); wgHandler = new WorldguardHandler(getWorldGuard()); } //Vault Check - if(!hasVault() && this.getConfig().getBoolean("economy.enable", true)){ + if (!hasVault() && this.getConfig().getBoolean("economy.enable", true)) { getLogger().warning("Vault not found, economy features disabled."); } else if (hasVault()) { getLogger().info("Vault found!"); vHandler = new VaultHandler(); - if(!vHandler.hasEconomy()){ + if (!vHandler.hasEconomy()) { getLogger().warning("No economy found, economy features disabled."); } } @@ -132,26 +111,26 @@ public void onEnable() { //Register default flags - if(getConfig().getBoolean("enabled-flags.build")) { - flagManager.registerFlag(new Build()); + if (getConfig().getBoolean("enabled-flags.build")) { + flagManager.registerFlag(new Build(this)); } - if(getConfig().getBoolean("enabled-flags.harmAnimals")) { - flagManager.registerFlag(new HarmAnimals()); + if (getConfig().getBoolean("enabled-flags.harmAnimals")) { + flagManager.registerFlag(new HarmAnimals(this)); } - if(getConfig().getBoolean("enabled-flags.useContainers")) { - flagManager.registerFlag(new UseContainers()); + if (getConfig().getBoolean("enabled-flags.useContainers")) { + flagManager.registerFlag(new UseContainers(this)); } - if(getConfig().getBoolean("enabled-flags.tntDamage")) { - flagManager.registerFlag(new TntDamage()); + if (getConfig().getBoolean("enabled-flags.tntDamage")) { + flagManager.registerFlag(new TntDamage(this)); } - if(getConfig().getBoolean("enabled-flags.useRedstone")) { - flagManager.registerFlag(new UseRedstone()); + if (getConfig().getBoolean("enabled-flags.useRedstone")) { + flagManager.registerFlag(new UseRedstone(this)); } - if(getConfig().getBoolean("enabled-flags.openDoor")) { - flagManager.registerFlag(new OpenDoor()); + if (getConfig().getBoolean("enabled-flags.openDoor")) { + flagManager.registerFlag(new OpenDoor(this)); } - if(getConfig().getBoolean("enabled-flags.pvp")) { - flagManager.registerFlag(new PVP()); + if (getConfig().getBoolean("enabled-flags.pvp")) { + flagManager.registerFlag(new PVP(this)); } //flagManager.registerFlag(new OpenDoorDUPE1()); //flagManager.registerFlag(new OpenDoorDUPE2()); @@ -168,6 +147,18 @@ public void onDisable() { pListen.clearPtrack(); } + @Override + public FileConfiguration getConfig() { + return mainConfig.get(); + } + + public FileConfiguration getMessageConfig() { + return messagesConfig.get(); + } + + private FileConfiguration getMessages() { + return messagesConfig.get(); + } public FlagManager getFlagManager() { return flagManager; @@ -181,11 +172,6 @@ public ViewManager getManageViewManager() { return manageViewManager; } - public static Landlord getInstance() { - return (Landlord)Bukkit.getPluginManager().getPlugin("Landlord"); - //return Bukkit.getPluginManager().getPlugin("MyPlugin"); - } - /* @@ -194,7 +180,6 @@ public static Landlord getInstance() { * *************************** */ - /* * ************** * Worldguard @@ -214,9 +199,10 @@ private WorldGuardPlugin getWorldGuard() { /** * Provides access to the Landlord WorldGuardHandler + * * @return ll wg handler */ - public WorldguardHandler getWgHandler(){ + public WorldguardHandler getWgHandler() { return wgHandler; } @@ -243,23 +229,16 @@ public boolean hasWorldGuard() { * ************** */ - public boolean hasVault(){ + public boolean hasVault() { Plugin plugin = getServer().getPluginManager().getPlugin("Vault"); - - - - // WorldGuard may not be loaded - if (plugin == null || !(plugin instanceof Vault) || !this.getConfig().getBoolean("economy.enable", true)) { - return false; - } + return !(plugin == null || !(plugin instanceof Vault) || !this.getConfig().getBoolean("economy.enable", true)); - return true; } - public VaultHandler getvHandler(){ + public VaultHandler getvHandler() { return vHandler; } @@ -284,15 +263,15 @@ protected java.util.List> getDatabaseClasses() { list.add(LandFlagPerm.class); return list; - }; + } }; database.initializeDatabase( - config.getString("database.driver","org.sqlite.JDBC"), - config.getString("database.url","jdbc:sqlite:{DIR}{NAME}.db"), - config.getString("database.username","bukkit"), - config.getString("database.password","walrus"), - config.getString("database.isolation","SERIALIZABLE"), + config.getString("database.driver", "org.sqlite.JDBC"), + config.getString("database.url", "jdbc:sqlite:{DIR}{NAME}.db"), + config.getString("database.username", "bukkit"), + config.getString("database.password", "walrus"), + config.getString("database.isolation", "SERIALIZABLE"), config.getBoolean("database.logging", false), config.getBoolean("database.rebuild", false) ); @@ -317,19 +296,19 @@ public EbeanServer getDatabase() { public void verifyDatabaseVersion() { int CURRENT_VERSION = 1; - if (this.getDatabase().find(DBVersion.class).where().eq("identifier","version").findUnique() == null) { + if (this.getDatabase().find(DBVersion.class).where().eq("identifier", "version").findUnique() == null) { //Convert Database this.getLogger().info("Starting OwnedLand conversion..."); List allLand = plugin.getDatabase().find(OwnedLand.class).findList(); - for (OwnedLand l : allLand){ - if(l.getOwnerName().length() < 32){ + for (OwnedLand l : allLand) { + if (l.getOwnerName().length() < 32) { //plugin.getLogger().info("Converting "+ l.getId() + "..."); /* * ************************************* * mark for possible change !!!!!!!!! * ************************************* */ - if(getOfflinePlayer(l.getOwnerName()).hasPlayedBefore()) { + if (getOfflinePlayer(l.getOwnerName()).hasPlayedBefore()) { //plugin.getLogger().info("Converting "+ l.getId() + "... Owner: "+l.getOwnerName()); l.setOwnerName(getOfflinePlayer(l.getOwnerName()).getUniqueId().toString()); plugin.getDatabase().save(l); @@ -346,15 +325,15 @@ public void verifyDatabaseVersion() { this.getLogger().info("Starting Friend conversion..."); List allFriends = plugin.getDatabase().find(Friend.class).findList(); - for (Friend f : allFriends){ - if(f.getPlayerName().length() < 32){ + for (Friend f : allFriends) { + if (f.getPlayerName().length() < 32) { //plugin.getLogger().info("Converting "+ l.getId() + "..."); /* * ************************************* * mark for possible change !!!!!!!!! * ************************************* */ - if(getOfflinePlayer(f.getPlayerName()).hasPlayedBefore()) { + if (getOfflinePlayer(f.getPlayerName()).hasPlayedBefore()) { //plugin.getLogger().info("Converting "+ f.getId() + "... Name: "+f.getPlayerName()); f.setPlayerName(getOfflinePlayer(f.getPlayerName()).getUniqueId().toString()); plugin.getDatabase().save(f); @@ -370,14 +349,14 @@ public void verifyDatabaseVersion() { this.getLogger().info("Friend Conversion completed!"); this.getLogger().info("Starting Permission conversion..."); allLand = plugin.getDatabase().find(OwnedLand.class).findList(); - for (OwnedLand l : allLand){ - if(l.getPermissions() != null) { + for (OwnedLand l : allLand) { + if (l.getPermissions() != null) { String[] currPerms = l.getPermissions().split("\\|"); String newPermString = ""; for (int i = 0; i < currPerms.length; i++) { - currPerms[i]=currPerms[i].substring(0,3); + currPerms[i] = currPerms[i].substring(0, 3); newPermString += Integer.toString(Integer.parseInt(currPerms[i], 2)); if (i < currPerms.length - 1) { newPermString += "|"; @@ -389,9 +368,9 @@ public void verifyDatabaseVersion() { } } //Entries for legacy flags - this.getDatabase().save(LandFlagPerm.flagPermFromData("Build",1)); - this.getDatabase().save(LandFlagPerm.flagPermFromData("HarmAnimals",2)); - this.getDatabase().save(LandFlagPerm.flagPermFromData("UseContainers",3)); + this.getDatabase().save(LandFlagPerm.flagPermFromData("Build", 1)); + this.getDatabase().save(LandFlagPerm.flagPermFromData("HarmAnimals", 2)); + this.getDatabase().save(LandFlagPerm.flagPermFromData("UseContainers", 3)); this.getLogger().info("Permission Conversion completed!"); DBVersion vUpdate = new DBVersion(); @@ -399,8 +378,8 @@ public void verifyDatabaseVersion() { vUpdate.setIntData(1); this.getDatabase().save(vUpdate); } - int currVersion = this.getDatabase().find(DBVersion.class).where().eq("identifier","version").findUnique().getIntData(); - if(currVersion < CURRENT_VERSION){ + int currVersion = this.getDatabase().find(DBVersion.class).where().eq("identifier", "version").findUnique().getIntData(); + if (currVersion < CURRENT_VERSION) { this.getLogger().info("Database outdated!"); } diff --git a/src/com/jcdesimp/landlord/LandlordCommandExecutor.java b/src/com/jcdesimp/landlord/LandlordCommandExecutor.java index 484ca7a..fdc8935 100644 --- a/src/com/jcdesimp/landlord/LandlordCommandExecutor.java +++ b/src/com/jcdesimp/landlord/LandlordCommandExecutor.java @@ -1,1062 +1,105 @@ package com.jcdesimp.landlord; -import com.jcdesimp.landlord.landManagement.LandManagerView; -import com.jcdesimp.landlord.persistantData.Friend; -import com.jcdesimp.landlord.persistantData.OwnedLand; -import org.bukkit.*; +import com.jcdesimp.landlord.commands.*; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import java.util.ArrayList; -import java.util.List; - -import static org.bukkit.Bukkit.getOfflinePlayer; -import static org.bukkit.Bukkit.getPlayer; -import static org.bukkit.Bukkit.getWorld; -import static org.bukkit.util.NumberConversions.ceil; +import java.util.HashMap; /** * Command Executor class for LandLord */ @SuppressWarnings("UnusedParameters") public class LandlordCommandExecutor implements CommandExecutor { - private Landlord plugin; //pointer to main class - public LandlordCommandExecutor(Landlord plugin){ - this.plugin = plugin; - - } - - /** - * Main command handler - * @param sender who sent the command - * @param label exact command (or alias) run - * @param args given with command - * @return boolean - */ - @Override - public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { - if(cmd.getName().equalsIgnoreCase("landlord")){ // If the player typed /land then do the following... - /* - * **************************************************************** - * Use private methods below to define command implementation - * call those methods from within these cases - * **************************************************************** - */ - if(args.length == 0){ - - //landlord - return landlord_help(sender, args, label); - - } else if(args[0].equalsIgnoreCase("help")) { - - //landlord claim - return landlord_help(sender, args, label); - - } else if(args[0].equalsIgnoreCase("claim") || args[0].equalsIgnoreCase("buy")) { - - //landlord claim - return landlord_claim(sender, args); - - } else if(args[0].equalsIgnoreCase("unclaim") || args[0].equalsIgnoreCase("sell")) { - - //landlord unclaim - return landlord_unclaim(sender, args, label); - } else if(args[0].equalsIgnoreCase("addfriend") || args[0].equalsIgnoreCase("friend")) { - - //landlord addfriend - return landlord_addfriend(sender, args); - } else if(args[0].equalsIgnoreCase("friendall")) { - - //landlord addfriend - return landlord_friendall(sender, args); - } else if(args[0].equalsIgnoreCase("unfriendall")) { - //landlord addfriend - return landlord_unfriendall(sender, args); - } else if(args[0].equalsIgnoreCase("remfriend") || args[0].equalsIgnoreCase("unfriend")) { + private HashMap registeredCommands; - return landlord_remfriend(sender, args); - } else if(args[0].equalsIgnoreCase("map")) { + private Help helpCommand; - return landlord_map(sender, args); - //sender.sendMessage(ChatColor.RED+"Land map is temporarily disabled!"); - //return true; - } else if(args[0].equalsIgnoreCase("manage")) { - return landlord_manage(sender, args); + public LandlordCommandExecutor(Landlord plugin) { + this.registeredCommands = new HashMap<>(); - } else if(args[0].equalsIgnoreCase("list")) { - return landlord_list(sender, args, label); + this.helpCommand = new Help(plugin, this); - } else if(args[0].equalsIgnoreCase("listplayer")) { - return landlord_listplayer(sender, args, label); + // note order of registration will affect how they show up in the help menu + this.register(helpCommand); // register the help command (already instantiated) - } else if(args[0].equalsIgnoreCase("clearworld")) { - return landlord_clearWorld(sender, args, label); + this.register(new Claim(plugin)); // register the claim command + this.register(new Unclaim(plugin)); // register the unclaim command + this.register(new AddFriend(plugin)); // register the addfriend command + this.register(new Unfriend(plugin)); // register the unfriend command + this.register(new Friends(plugin)); // register the friends command + this.register(new FriendAll(plugin)); // register the friendall command + this.register(new UnfriendAll(plugin)); // register the unfriendall command + this.register(new ShowMap(plugin)); // register the map command + this.register(new Manage(plugin)); // register the manage command + this.register(new LandList(plugin)); // register the list command + this.register(new Info(plugin)); // register the info command + this.register(new ListPlayer(plugin)); // register the listplayer command + this.register(new ClearWorld(plugin)); // register the clearworld command + this.register(new Reload(plugin)); // register the reload command - } else if(args[0].equalsIgnoreCase("reload")) { - - return landlord_reload(sender, args, label); - } else if(args[0].equalsIgnoreCase("info")) { - - return landlord_info(sender, args, label); - } else if(args[0].equalsIgnoreCase("friends")) { - - return landlord_friends(sender,args,label); - } else { - return landlord_help(sender, args, label); - } - - } //If this has happened the function will return true. - // If this hasn't happened the value of false will be returned. - return false; } - - - - - - /* - * ********************************************************** - * private methods for handling each command functionality - * ********************************************************** - */ - - /** - * Called when base command /landlord or aliases (/ll /land) - * are executed with no parameters + * Main command handler * - * @param sender who executed the command - * @return boolean - */ - private boolean landlord(CommandSender sender, String[] args, String label) { - sender.sendMessage(ChatColor.DARK_GREEN + "--|| Landlord v"+Landlord.getInstance().getDescription().getVersion() + - " Created by " + ChatColor.BLUE+"Jcdesimp "+ChatColor.DARK_GREEN +"||--\n"+ - //ChatColor.GRAY+"(Aliases: /landlord, /land, or /ll)\n"+ - ChatColor.DARK_GREEN+"Type " +ChatColor.YELLOW+"/"+label+" help "+ChatColor.DARK_GREEN +"for a list of commands"); - return true; - } - - private boolean landlord_help(CommandSender sender, String[] args, String label) { - //check if page number is valid - int pageNumber = 1; - if (args.length > 1 && args[0].equals("help")){ - try{ - pageNumber = Integer.parseInt(args[1]);} - catch (NumberFormatException e){ - sender.sendMessage(ChatColor.RED+"That is not a valid page number."); - return true; - } - } - - //List myLand = plugin.getDatabase().find(OwnedLand.class).where().eq("ownerName",player.getName()).findList(); - - String header = ChatColor.DARK_GREEN + "--|| Landlord v"+Landlord.getInstance().getDescription().getVersion() + - " Created by " + ChatColor.BLUE+"Jcdesimp "+ChatColor.DARK_GREEN +"||--\n"+ - ChatColor.GRAY+"(Aliases: /landlord, /land, or /ll)\n"; - - ArrayList helpList = new ArrayList(); - - - helpList.add(ChatColor.DARK_AQUA+"/"+label + " help [page #]" + ChatColor.RESET + " - Show this help message.\n"); - String claim = ChatColor.DARK_AQUA+"/"+label + " claim (or "+"/"+label +" buy)" + ChatColor.RESET + " - Claim this chunk.\n"; - if(plugin.hasVault()){ - if(plugin.getvHandler().hasEconomy() && plugin.getConfig().getDouble("economy.buyPrice", 100.0)>0){ - claim += ChatColor.YELLOW+""+ChatColor.ITALIC+" Costs "+plugin.getvHandler().formatCash(plugin.getConfig().getDouble("economy.buyPrice", 100.0))+" to claim.\n"; - } - } - helpList.add(claim); - String unclaim = ChatColor.DARK_AQUA+"/"+label + " unclaim [x,z] [world] (or "+"/"+label +" sell)" + ChatColor.RESET + " - Unclaim this chunk.\n"; - if (plugin.hasVault() && plugin.getvHandler().hasEconomy() && plugin.getConfig().getDouble("economy.sellPrice", 50.0) > 0) { - if(plugin.getConfig().getBoolean("options.regenOnUnclaim",false)) { - unclaim+=ChatColor.RED+""+ChatColor.ITALIC +" Regenerates Chunk!"; - } - unclaim += ChatColor.YELLOW + "" + ChatColor.ITALIC + " Get " + plugin.getvHandler().formatCash(plugin.getConfig().getDouble("economy.sellPrice", 50.0)) + " per unclaim.\n"; - } else if(plugin.getConfig().getBoolean("options.regenOnUnclaim",false)) { - unclaim+=ChatColor.RED+""+ChatColor.ITALIC +" Regenerates Chunk!\n"; - } - helpList.add(unclaim); - - helpList.add(ChatColor.DARK_AQUA+"/"+label + " addfriend " + ChatColor.RESET + " - Add friend to this land.\n"); - helpList.add(ChatColor.DARK_AQUA+"/"+label + " unfriend " + ChatColor.RESET + " - Remove friend from this land.\n"); - helpList.add(ChatColor.DARK_AQUA+"/"+label + " friendall " + ChatColor.RESET + " - Add friend to all your land.\n"); - helpList.add(ChatColor.DARK_AQUA+"/"+label + " unfriendall " + ChatColor.RESET + " - Remove friend from all your land.\n"); - helpList.add(ChatColor.DARK_AQUA+"/"+label + " friends" + ChatColor.RESET + " - List friends of this land.\n"); - helpList.add(ChatColor.DARK_AQUA+"/"+label + " manage" + ChatColor.RESET + " - Manage permissions for this land.\n"); - helpList.add(ChatColor.DARK_AQUA+"/"+label + " list" + ChatColor.RESET + " - List all your owned land.\n"); - if(sender.hasPermission("landlord.player.map") && plugin.getConfig().getBoolean("options.enableMap",true)){ - helpList.add(ChatColor.DARK_AQUA+"/"+label + " map" + ChatColor.RESET + " - Toggle the land map.\n"); - } - if(sender.hasPermission("landlord.player.info") && plugin.getConfig().getBoolean("options.enableMap",true)){ - helpList.add(ChatColor.DARK_AQUA+"/"+label + " info" + ChatColor.RESET + " - View info about this chunk.\n"); - } - if(sender.hasPermission("landlord.admin.list")){ - helpList.add(ChatColor.DARK_AQUA+"/"+label + " listplayer " + ChatColor.RESET + " - List land owned by another player.\n"); - } - if(sender.hasPermission("landlord.admin.clearworld")){ - String clearHelp = ChatColor.DARK_AQUA+"/"+label + " clearworld [player]" + ChatColor.RESET + " - Delete all land owned by a player in a world." + - " Delete all land of a world from console.\n"; - if(plugin.getConfig().getBoolean("options.regenOnUnclaim",false)){ - clearHelp += ChatColor.YELLOW+""+ChatColor.ITALIC+" Does not regenerate chunks.\n"; - } - helpList.add(clearHelp); - - } - if(sender.hasPermission("landlord.admin.reload")){ - helpList.add(ChatColor.DARK_AQUA+"/"+label + " reload" + ChatColor.RESET + " - Reloads the Landlord config file.\n"); - } - //OwnedLand curr = myLand.get(0); - - //Amount to be displayed per page - final int numPerPage = 5; - - int numPages = ceil((double)helpList.size()/(double)numPerPage); - if(pageNumber > numPages){ - sender.sendMessage(ChatColor.RED+"That is not a valid page number."); - return true; - } - String pMsg = header; - if (pageNumber == numPages){ - for(int i = (numPerPage*pageNumber-numPerPage); i disabledWorlds = plugin.getConfig().getStringList("disabled-worlds"); - for (String s : disabledWorlds) { - if (s.equalsIgnoreCase(currChunk.getWorld().getName())) { - player.sendMessage(ChatColor.RED+"You cannot claim in this world."); - return true; - } - } - - if(plugin.hasWorldGuard()){ - if(!plugin.getWgHandler().canClaim(player,currChunk)){ - player.sendMessage(ChatColor.RED+"You cannot claim here."); - return true; - } - } - - - - OwnedLand land = OwnedLand.landFromProperties(player, currChunk); - OwnedLand dbLand = OwnedLand.getLandFromDatabase(currChunk.getX(), currChunk.getZ(), currChunk.getWorld().getName()); - - - if(dbLand != null){ - //Check if they already own this land - if (dbLand.ownerUUID().equals(player.getUniqueId())){ - player.sendMessage(ChatColor.YELLOW + "You already own this land!"); - return true; - } - player.sendMessage(ChatColor.YELLOW + "Someone else owns this land."); - return true; - - } - int orLimit = plugin.getConfig().getInt("limits.landLimit",10); - int limit = plugin.getConfig().getInt("limits.landLimit",10); - - if(player.hasPermission("landlord.limit.extra5")){ - limit=orLimit+plugin.getConfig().getInt("limits.extra5",0); - } else if(player.hasPermission("landlord.limit.extra4")){ - limit=orLimit+plugin.getConfig().getInt("limits.extra4",0); - } else if(player.hasPermission("landlord.limit.extra3")){ - limit=orLimit+plugin.getConfig().getInt("limits.extra3",0); - } else if(player.hasPermission("landlord.limit.extra2")){ - limit=orLimit+plugin.getConfig().getInt("limits.extra2",0); - } else if(player.hasPermission("landlord.limit.extra")){ - limit=orLimit+plugin.getConfig().getInt("limits.extra",0); - } - - if(limit >= 0 && !player.hasPermission("landlord.limit.override")){ - if(plugin.getDatabase().find(OwnedLand.class).where().eq("ownerName",player.getUniqueId().toString()).findRowCount() >= limit){ - player.sendMessage(ChatColor.RED+"You can only own " + limit + " chunks of land."); - return true; - } - } // - - //Money Handling - if(plugin.hasVault()){ - if(plugin.getvHandler().hasEconomy()){ - Double amt = plugin.getConfig().getDouble("economy.buyPrice", 100.0); - if(amt > 0){ - int numFree = plugin.getConfig().getInt("economy.freeLand", 0); - if (numFree > 0 && plugin.getDatabase().find(OwnedLand.class).where().eq("ownerName",player.getUniqueId().toString()).findRowCount() < numFree) { - //player.sendMessage(ChatColor.YELLOW+"You have been charged " + plugin.getvHandler().formatCash(amt) + " to purchase land."); - } else if(!plugin.getvHandler().chargeCash(player, amt)){ - player.sendMessage(ChatColor.RED+"It costs " + plugin.getvHandler().formatCash(amt) + " to purchase land."); - return true; - } else { - player.sendMessage(ChatColor.YELLOW+"You have been charged " + plugin.getvHandler().formatCash(amt) + " to purchase land."); - } - } - - } - } - Landlord.getInstance().getDatabase().save(land); - land.highlightLand(player, Effect.HAPPY_VILLAGER); - sender.sendMessage( - ChatColor.GREEN + "Successfully claimed chunk (" + currChunk.getX() + ", " + - currChunk.getZ() + ") in world \'" + currChunk.getWorld().getName() + "\'." ); - - if(plugin.getConfig().getBoolean("options.soundEffects",true)){ - player.playSound(player.getLocation(),Sound.FIREWORK_TWINKLE2,10,10); - } - - - plugin.getMapManager().updateAll(); - //sender.sendMessage(ChatColor.DARK_GREEN + "Land claim command executed!"); - } - return true; - } - - - /** - * Called when landlord unclaim command is executed - * This command must be run by a player - * @param sender who executed the command - * @param args given with command - * @return boolean - */ - private boolean landlord_unclaim(CommandSender sender, String[] args, String label) { - - //is sender a plater - if (!(sender instanceof Player)) { - sender.sendMessage(ChatColor.DARK_RED + "This command can only be run by a player."); - } else { - Player player = (Player) sender; - if(!player.hasPermission("landlord.player.own") && !player.hasPermission("landlord.admin.unclaim")){ - player.sendMessage(ChatColor.RED+"You do not have permission."); - return true; - } - //sender.sendMessage(ChatColor.GOLD + "Current Location: " + player.getLocation().toString()); - Chunk currChunk = player.getLocation().getChunk(); - - int x = currChunk.getX(); - int z = currChunk.getZ(); - String worldname = currChunk.getWorld().getName(); - - List disabledWorlds = plugin.getConfig().getStringList("disabled-worlds"); - for (String s : disabledWorlds) { - if (s.equalsIgnoreCase(currChunk.getWorld().getName())) { - player.sendMessage(ChatColor.RED+"You cannot claim in this world."); - return true; - } - } - - - if(args.length>1){ - try{ - String[] coords = args[1].split(","); - //System.out.println("COORDS: "+coords); - x = Integer.parseInt(coords[0]); - z = Integer.parseInt(coords[1]); - currChunk = currChunk.getWorld().getChunkAt(x,z); - if(args.length>2){ - - if(plugin.getServer().getWorld(worldname) == null){ - player.sendMessage(ChatColor.RED + "World \'"+worldname + "\' does not exist."); - return true; - } - currChunk = getWorld(worldname).getChunkAt(x, z); - - } - } catch (NumberFormatException e){ - //e.printStackTrace(); - player.sendMessage(ChatColor.RED+"usage: /"+label +" "+ args[0]+ " [x,z] [world]"); - return true; - - } catch (ArrayIndexOutOfBoundsException e){ - player.sendMessage(ChatColor.RED+"usage: /"+label +" "+ args[0]+" [x,z] [world]"); - return true; - } - } - OwnedLand dbLand = OwnedLand.getLandFromDatabase(x, z, worldname); - - - if (dbLand == null || (!dbLand.ownerUUID().equals(player.getUniqueId()) && !player.hasPermission("landlord.admin.unclaim"))){ - player.sendMessage(ChatColor.RED + "You do not own this land."); - return true; - } - if(plugin.hasVault()){ - if(plugin.getvHandler().hasEconomy()){ - Double amt = plugin.getConfig().getDouble("economy.sellPrice", 100.0); - if(amt > 0){ - int numFree = plugin.getConfig().getInt("economy.freeLand", 0); - if (numFree > 0 && plugin.getDatabase().find(OwnedLand.class).where().eq("ownerName",player.getUniqueId().toString()).findRowCount() <= numFree) { - //player.sendMessage(ChatColor.YELLOW+"You have been charged " + plugin.getvHandler().formatCash(amt) + " to purchase land."); - } else if(plugin.getvHandler().giveCash(player, amt)){ - player.sendMessage(ChatColor.GREEN+"Land sold for " + plugin.getvHandler().formatCash(amt) + "."); - //return true; - } - } - - } - } - if(!player.getUniqueId().equals(dbLand.ownerUUID())){ - player.sendMessage(ChatColor.YELLOW+"Unclaimed " + getOfflinePlayer(dbLand.ownerUUID()).getName() + "'s land."); - } - plugin.getDatabase().delete(dbLand); - dbLand.highlightLand(player, Effect.WITCH_MAGIC); - - sender.sendMessage( - ChatColor.YELLOW + "Successfully unclaimed chunk (" + currChunk.getX() + ", " + - currChunk.getZ() + ") in world \'" + currChunk.getWorld().getName() + "\'." - ); - - //Regen land if enabled - if(plugin.getConfig().getBoolean("options.regenOnUnclaim",false)){ - currChunk.getWorld().regenerateChunk(currChunk.getX(),currChunk.getZ()); - } - - if(plugin.getConfig().getBoolean("options.soundEffects",true)){ - player.playSound(player.getLocation(),Sound.ENDERMAN_HIT,10,.5f); - } - plugin.getMapManager().updateAll(); - - } - return true; - } - - /** - * Adds a friend to an owned chunk - * Called when landlord addfriend command is executed - * This command must be run by a player - * @param sender who executed the command - * @param args given with command - * @return boolean - */ - private boolean landlord_addfriend(CommandSender sender, String[] args) { - - //is sender a player - if (!(sender instanceof Player)) { - sender.sendMessage(ChatColor.DARK_RED + "This command can only be run by a player."); - } else { - if (args.length < 2){ - sender.sendMessage(ChatColor.RED + "usage: /land addfriend "); - return true; - } - Player player = (Player) sender; - if(!player.hasPermission("landlord.player.own")){ - player.sendMessage(ChatColor.RED+"You do not have permission."); - return true; - } - - Chunk currChunk = player.getLocation().getChunk(); - - OwnedLand land = OwnedLand.getLandFromDatabase(currChunk.getX(), currChunk.getZ(), currChunk.getWorld().getName()); - - //Does land exist, and if so does player own it - if( land == null || (!land.ownerUUID().equals(player.getUniqueId()) && !player.hasPermission("landlord.admin.modifyfriends")) ){ - player.sendMessage(ChatColor.RED + "You do not own this land."); - return true; - } - // - OfflinePlayer possible = getOfflinePlayer(args[1]); - if (!possible.hasPlayedBefore() && !possible.isOnline()) { - player.sendMessage(ChatColor.RED+"That player is not recognized."); - return true; - } - Friend friend = Friend.friendFromOfflinePlayer(getOfflinePlayer(args[1])); - /* - * ************************************* - * mark for possible change !!!!!!!!! - * ************************************* - */ - - if (! land.addFriend(friend)) { - player.sendMessage(ChatColor.YELLOW + "Player " + args[1] + " is already a friend of this land."); - return true; - } - if(plugin.getConfig().getBoolean("options.particleEffects",true)){ - land.highlightLand(player, Effect.HEART, 2); - } - - plugin.getDatabase().save(land); - if(plugin.getConfig().getBoolean("options.soundEffects",true)){ - player.playSound(player.getLocation(),Sound.ORB_PICKUP,10,.2f); - } - sender.sendMessage(ChatColor.GREEN + "Player " + args[1] +" is now a friend of this land."); - plugin.getMapManager().updateAll(); - - } - return true; - } - - private boolean landlord_friendall(CommandSender sender, String[] args) { - //is sender a player - if (!(sender instanceof Player)) { - sender.sendMessage(ChatColor.DARK_RED + "This command can only be run by a player."); - } else { - if (args.length < 2) { - sender.sendMessage(ChatColor.RED + "usage: /land friendall "); - return true; - } - Player player = (Player) sender; - if (!player.hasPermission("landlord.player.own")) { - player.sendMessage(ChatColor.RED + "You do not have permission."); - return true; - } - - List pLand = plugin.getDatabase().find(OwnedLand.class).where().eq("ownerName",player.getUniqueId()).findList(); - OfflinePlayer possible = getOfflinePlayer(args[1]); - if (!possible.hasPlayedBefore() && !possible.isOnline()) { - player.sendMessage(ChatColor.RED + "That player is not recognized."); - return true; - } - - if (pLand.size() > 0){ - for(OwnedLand l : pLand){ - l.addFriend(Friend.friendFromOfflinePlayer(getOfflinePlayer(args[1]))); - } - - plugin.getDatabase().save(pLand); - - - player.sendMessage(ChatColor.GREEN+args[1]+" has been added as a friend to all of your land."); - return true; - } else { - player.sendMessage(ChatColor.YELLOW+"You do not own any land!"); - } - - } - return true; - } - - private boolean landlord_unfriendall(CommandSender sender, String[] args) { - //is sender a player - if (!(sender instanceof Player)) { - sender.sendMessage(ChatColor.DARK_RED + "This command can only be run by a player."); - } else { - if (args.length < 2) { - sender.sendMessage(ChatColor.RED + "usage: /land unfriendall "); - return true; - } - Player player = (Player) sender; - if (!player.hasPermission("landlord.player.own")) { - player.sendMessage(ChatColor.RED + "You do not have permission."); - return true; - } - - List pLand = plugin.getDatabase().find(OwnedLand.class).where().eq("ownerName",player.getUniqueId()).findList(); - - OfflinePlayer possible = getOfflinePlayer(args[1]); - if (!possible.hasPlayedBefore() && !possible.isOnline()) { - player.sendMessage(ChatColor.RED + "That player is not recognized."); - return true; - } - - if (pLand.size() > 0){ - for(OwnedLand l : pLand){ - l.removeFriend(Friend.friendFromOfflinePlayer(getOfflinePlayer(args[1]))); - } - - plugin.getDatabase().save(pLand); - - - player.sendMessage(ChatColor.GREEN+args[1]+" has been removed as a friend from all of your land."); - return true; - } else { - player.sendMessage(ChatColor.YELLOW+"You do not own any land!"); - } - - } - return true; - } - - /** - * Removes a friend from an owned chunk - * Called when landlord remfriend is executed - * @param sender who executed the command - * @param args given with command + * @param sender who sent the command + * @param label exact command (or alias) run + * @param args given with command * @return boolean */ - private boolean landlord_remfriend(CommandSender sender, String[] args) { - if (!(sender instanceof Player)) { - sender.sendMessage(ChatColor.DARK_RED + "This command can only be run by a player."); - } else { - if (args.length < 2){ - sender.sendMessage(ChatColor.RED + "usage: /land unfriend "); - return true; - } - Player player = (Player) sender; - if(!player.hasPermission("landlord.player.own")){ - player.sendMessage(ChatColor.RED+"You do not have permission."); - return true; - } - - Chunk currChunk = player.getLocation().getChunk(); - /* - * ************************************* - * mark for possible change !!!!!!!!! - * ************************************* - */ - Friend frd = Friend.friendFromOfflinePlayer(getOfflinePlayer(args[1])); - OwnedLand land = OwnedLand.getLandFromDatabase(currChunk.getX(), currChunk.getZ(), currChunk.getWorld().getName()); - if( land == null || (!land.ownerUUID().equals(player.getUniqueId()) && !player.hasPermission("landlord.admin.modifyfriends")) ){ - player.sendMessage(ChatColor.RED + "You do not own this land."); - return true; - } - if(!land.removeFriend(frd)){ - player.sendMessage(ChatColor.YELLOW + "Player " + args[1] + " is not a friend of this land."); - return true; - } - if(plugin.getConfig().getBoolean("options.particleEffects",true)) { - land.highlightLand(player, Effect.VILLAGER_THUNDERCLOUD, 2); - } - plugin.getDatabase().save(land); - if(plugin.getConfig().getBoolean("options.soundEffects",true)){ - player.playSound(player.getLocation(),Sound.ZOMBIE_INFECT,10,.5f); - } - player.sendMessage(ChatColor.GREEN + "Player " + args[1] + " is no longer a friend of this land."); - - } - return true; - - } - - - private boolean landlord_friends(CommandSender sender, String[] args, String label) { - - if (!(sender instanceof Player)) { - sender.sendMessage(ChatColor.DARK_RED + "This command can only be run by a player."); - } else { - Player player = (Player) sender; - if(!player.hasPermission("landlord.player.own")){ - player.sendMessage(ChatColor.RED+"You do not have permission."); - return true; - } - Chunk currChunk = player.getLocation().getChunk(); - OwnedLand land = OwnedLand.getLandFromDatabase(currChunk.getX(), currChunk.getZ(), currChunk.getWorld().getName()); - if( land == null || ( !land.ownerUUID().equals(player.getUniqueId()) && !player.hasPermission("landlord.admin.friends") ) ){ - player.sendMessage(ChatColor.RED + "You do not own this land."); - return true; - } - if(!land.getOwnerName().equals(player.getUniqueId())){ - //player.sendMessage(ChatColor.YELLOW+"Viewing friends of someone else's land."); - } - if(plugin.getConfig().getBoolean("options.particleEffects",true)) { - land.highlightLand(player, Effect.HEART, 3); - } - //check if page number is valid - int pageNumber = 1; - if (args.length > 1 && args[0].equals("friends")){ - try { - pageNumber = Integer.parseInt(args[1]); - } catch (NumberFormatException e){ - player.sendMessage(ChatColor.RED+"That is not a valid page number."); - return true; - } - } - - //List myLand = plugin.getDatabase().find(OwnedLand.class).where().eq("ownerName",player.getName()).findList(); - - String header = ChatColor.DARK_GREEN + "----- Friends of this Land -----\n"; - - ArrayList friendList = new ArrayList(); - if(land.getFriends().isEmpty()){ - player.sendMessage(ChatColor.YELLOW+"This land has no friends."); - return true; - } - for(Friend f: land.getFriends()){ - String fr = ChatColor.DARK_GREEN+" - "+ChatColor.GOLD+f.getName()+ChatColor.DARK_GREEN+" - "; - /* - * ************************************* - * mark for possible change !!!!!!!!! - * ************************************* - */ - if(Bukkit.getOfflinePlayer(f.getUUID()).isOnline()){ - fr+= ChatColor.GREEN+""+ChatColor.ITALIC+" Online"; - } else { - fr+= ChatColor.RED+""+ChatColor.ITALIC+" Offline"; - } - - fr+="\n"; - friendList.add(fr); - } - - //Amount to be displayed per page - final int numPerPage = 8; - - int numPages = ceil((double)friendList.size()/(double)numPerPage); - if(pageNumber > numPages){ - sender.sendMessage(ChatColor.RED+"That is not a valid page number."); - return true; - } - String pMsg = header; - if (pageNumber == numPages){ - for(int i = (numPerPage*pageNumber-numPerPage); i 1){ - try{ - pageNumber = Integer.parseInt(args[1]);} - catch (NumberFormatException e){ - player.sendMessage(ChatColor.RED+"That is not a valid page number."); - return true; - } - } - - List myLand = plugin.getDatabase().find(OwnedLand.class).where().eq("ownerName",player.getUniqueId().toString()).findList(); - if(myLand.size()==0){ - player.sendMessage(ChatColor.YELLOW+"You do not own any land!"); - } else { - String header = ChatColor.DARK_GREEN+" | Coords - Chunk Coords - World Name | \n"; - ArrayList landList = new ArrayList(); - //OwnedLand curr = myLand.get(0); - for (OwnedLand aMyLand : myLand) { - landList.add((ChatColor.GOLD + " ("+ aMyLand.getXBlock() +", "+ aMyLand.getZBlock() +") - (" + aMyLand.getX() + ", " + aMyLand.getZ() + ") - " - + aMyLand.getWorldName()) + "\n") - ; - } - //Amount to be displayed per page - final int numPerPage = 7; - - int numPages = ceil((double)landList.size()/(double)numPerPage); - if(pageNumber > numPages){ - player.sendMessage(ChatColor.RED+"That is not a valid page number."); - return true; - } - String pMsg = ChatColor.DARK_GREEN+"--- " +ChatColor.YELLOW+"Your Owned Land"+ChatColor.DARK_GREEN+" ---"+ChatColor.YELLOW+" Page "+pageNumber+ChatColor.DARK_GREEN+" ---\n"+header; - if (pageNumber == numPages){ - for(int i = (numPerPage*pageNumber-numPerPage); i1){ - owner = args[1]; - } else { - sender.sendMessage(ChatColor.RED+"usage: /" + label + " listplayer [page#]"); - return true; - } + public boolean register(LandlordCommand cmd) { + String[] commandTriggers = cmd.getTriggers(); - //Player player = (Player) sender; - if(!sender.hasPermission("landlord.admin.list")){ - sender.sendMessage(ChatColor.RED+"You do not have permission."); - return true; - } + // if there are no aliases then fail, command would be impossible to trigger. + if (commandTriggers.length <= 0) { - //check if page number is valid - int pageNumber = 1; - if (args.length > 2){ - try{ - pageNumber = Integer.parseInt(args[2]);} - catch (NumberFormatException e){ - sender.sendMessage(ChatColor.RED+"That is not a valid page number."); - return true; - } + return false; } - /* - * ************************************* - * mark for possible change !!!!!!!!! - * ************************************* - */ - OfflinePlayer possible = getOfflinePlayer(args[1]); - if (!possible.hasPlayedBefore() && !possible.isOnline()) { - sender.sendMessage(ChatColor.YELLOW+ owner +" does not own any land!"); - return true; - } - List myLand = plugin.getDatabase().find(OwnedLand.class).where().ieq("ownerName", getOfflinePlayer(owner).getUniqueId().toString()).findList(); - if(myLand.size()==0){ - sender.sendMessage(ChatColor.YELLOW+ owner +" does not own any land!"); - } else { - String header = ChatColor.DARK_GREEN+" | Coords - Chunk Coords - World Name | \n"; - ArrayList landList = new ArrayList(); - //OwnedLand curr = myLand.get(0); - for (OwnedLand aMyLand : myLand) { - landList.add((ChatColor.GOLD + " ("+ aMyLand.getXBlock() +", "+ aMyLand.getZBlock() +") - (" + aMyLand.getX() + ", " + aMyLand.getZ() + ") - " - + aMyLand.getWorldName()) + "\n") - ; - } - //Amount to be displayed per page - final int numPerPage = 7; - int numPages = ceil((double)landList.size()/(double)numPerPage); - if(pageNumber > numPages){ - sender.sendMessage(ChatColor.RED+"That is not a valid page number."); - return true; - } - String pMsg = ChatColor.DARK_GREEN+"--- " +ChatColor.YELLOW+ owner +"'s Owned Land"+ChatColor.DARK_GREEN+" ---"+ChatColor.YELLOW+" Page "+pageNumber+ChatColor.DARK_GREEN+" ---\n"+header; - if (pageNumber == numPages){ - for(int i = (numPerPage*pageNumber-numPerPage); i 1){ - List land; - if(args.length > 2){ - /* - * ************************************* - * mark for possible change !!!!!!!!! - * ************************************* - */ - OfflinePlayer possible = getOfflinePlayer(args[2]); - if (!possible.hasPlayedBefore() && !possible.isOnline()) { - sender.sendMessage(ChatColor.RED+"That player is not recognized."); - return true; - } - land = plugin.getDatabase().find(OwnedLand.class).where().eq("ownerName",possible.getUniqueId().toString()).eq("worldName",args[1]).findList(); - } else { - if(sender instanceof Player){ - sender.sendMessage(ChatColor.RED+"You can only delete entire worlds from the console."); - return true; - } - land = plugin.getDatabase().find(OwnedLand.class).where().eq("worldName",args[1]).findList(); - } - if(land.isEmpty()){ - sender.sendMessage(ChatColor.RED + "No land to remove."); - return true; + // Check if the command is taken + if (registeredCommands.containsKey(trigger.toLowerCase())) { + System.out.println("Failed to register command with alias '" + trigger + "', already taken!"); + continue; // Command name is taken already } - plugin.getDatabase().delete(land); - plugin.getMapManager().updateAll(); - sender.sendMessage(ChatColor.GREEN+"Land(s) deleted!"); - - } else { - sender.sendMessage(ChatColor.RED + "format: " + label + " clearworld []"); - } - return true; - } - - - /** - * Reload landlord configuration file - * @param sender who executed the command - * @param args given with command - * @param label exact command (or alias) run - * @return boolean of success - */ - private boolean landlord_reload(CommandSender sender, String[] args, String label){ - if(sender.hasPermission("landlord.admin.reload")){ - plugin.reloadConfig(); - sender.sendMessage(ChatColor.GREEN+"Landlord config reloaded."); - return true; + // register an entry for this command trigger + registeredCommands.put(trigger.toLowerCase(), cmd); } - sender.sendMessage(ChatColor.RED+"You do not have permission."); - return true; - } - - private boolean landlord_info(CommandSender sender, String[] args, String label){ - if (!(sender instanceof Player)) { - sender.sendMessage(ChatColor.DARK_RED + "This command can only be run by a player."); - } else { - Player player = (Player) sender; - if(!player.hasPermission("landlord.player.info")){ - player.sendMessage(ChatColor.RED+"You do not have permission."); - return true; - } - Chunk currChunk = player.getLocation().getChunk(); - OwnedLand land = OwnedLand.getLandFromDatabase(currChunk.getX(), currChunk.getZ(), currChunk.getWorld().getName()); - String owner = ChatColor.GRAY + "" + ChatColor.ITALIC + "None"; - if( land != null ){ + helpCommand.addCommand(cmd); // add the command to the help list - /* - * ************************************* - * mark for possible change !!!!!!!!! - * ************************************* - */ - owner = ChatColor.GOLD + land.getOwnerUsername(); - } else { - land = OwnedLand.landFromProperties(null,currChunk); - } - - if(plugin.getConfig().getBoolean("options.particleEffects")){ - land.highlightLand(player, Effect.LAVADRIP); - } - String msg = ChatColor.DARK_GREEN + "--- You are in chunk " + ChatColor.GOLD + "(" + currChunk.getX() + ", " + currChunk.getZ() + ") " + - ChatColor.DARK_GREEN + " in world \"" + ChatColor.GOLD + currChunk.getWorld().getName() + ChatColor.DARK_GREEN + "\"\n"+ "----- Owned by: " + - owner; - player.sendMessage(msg); - - } return true; - } - - - - } diff --git a/src/com/jcdesimp/landlord/commands/AddFriend.java b/src/com/jcdesimp/landlord/commands/AddFriend.java new file mode 100644 index 0000000..4eabba7 --- /dev/null +++ b/src/com/jcdesimp/landlord/commands/AddFriend.java @@ -0,0 +1,121 @@ +package com.jcdesimp.landlord.commands; + +import com.jcdesimp.landlord.Landlord; +import com.jcdesimp.landlord.persistantData.Friend; +import com.jcdesimp.landlord.persistantData.OwnedLand; +import org.bukkit.*; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; + +import java.util.List; + +import static org.bukkit.Bukkit.getOfflinePlayer; + +/** + * Created by jcdesimp on 2/18/15. + * LandlordCommand to add a friend to a plot of land + */ +public class AddFriend implements LandlordCommand { + + private Landlord plugin; + + public AddFriend(Landlord plugin) { + this.plugin = plugin; + } + + /** + * Adds a friend to an owned chunk + * Called when landlord addfriend command is executed + * This command must be run by a player + * + * @param sender who executed the command + * @param args given with command + * @param label base command executed + * @return boolean + */ + @Override + public boolean execute(CommandSender sender, String[] args, String label) { + //is sender a player + FileConfiguration messages = plugin.getMessageConfig(); + + final String usage = messages.getString("commands.addFriend.usage"); + final String notPlayer = messages.getString("info.warnings.playerCommand"); + final String noPerms = messages.getString("info.warnings.noPerms"); + + final String notOwner = messages.getString("info.warnings.notOwner"); + final String unknownPlayer = messages.getString("info.warnings.unknownPlayer"); + final String alreadyFriend = messages.getString("commands.addFriend.alerts.alreadyFriend"); + final String nowFriend = messages.getString("commands.addFriend.alerts.success"); + + if (!(sender instanceof Player)) { + sender.sendMessage(ChatColor.DARK_RED + notPlayer); + } else { + if (args.length < 2) { + sender.sendMessage(ChatColor.RED + usage.replace("#{label}", label).replace("#{cmd}", args[0])); + return true; + } + Player player = (Player) sender; + if (!player.hasPermission("landlord.player.own")) { + player.sendMessage(ChatColor.RED + noPerms); + return true; + } + + Chunk currChunk = player.getLocation().getChunk(); + + OwnedLand land = OwnedLand.getLandFromDatabase(currChunk.getX(), currChunk.getZ(), currChunk.getWorld().getName()); + + //Does land exist, and if so does player own it + if (land == null || (!land.ownerUUID().equals(player.getUniqueId()) && !player.hasPermission("landlord.admin.modifyfriends"))) { + player.sendMessage(ChatColor.RED + notOwner); + return true; + } + // + OfflinePlayer possible = getOfflinePlayer(args[1]); + if (!possible.hasPlayedBefore() && !possible.isOnline()) { + player.sendMessage(ChatColor.RED + unknownPlayer); + return true; + } + Friend friend = Friend.friendFromOfflinePlayer(getOfflinePlayer(args[1])); + /* + * ************************************* + * mark for possible change !!!!!!!!! + * ************************************* + */ + + if (!land.addFriend(friend)) { + player.sendMessage(ChatColor.YELLOW + alreadyFriend.replace("#{player}", args[1])); + return true; + } + if (plugin.getConfig().getBoolean("options.particleEffects", true)) { //conf + land.highlightLand(player, Effect.HEART, 2); + } + + plugin.getDatabase().save(land); + if (plugin.getConfig().getBoolean("options.soundEffects", true)) { //conf + player.playSound(player.getLocation(), Sound.ENTITY_EXPERIENCE_ORB_PICKUP, 10, .2f); + } + sender.sendMessage(ChatColor.GREEN + nowFriend.replace("#{player}", args[1])); + plugin.getMapManager().updateAll(); + + } + return true; + } + + @Override + public String getHelpText(CommandSender sender) { + FileConfiguration messages = plugin.getMessageConfig(); + + final String usage = messages.getString("commands.addFriend.usage"); // get the base usage string + final String desc = messages.getString("commands.addFriend.description"); // get the description + + // return the constructed and colorized help string + return Utils.helpString(usage, desc, getTriggers()[0].toLowerCase()); + } + + @Override + public String[] getTriggers() { + final List triggers = plugin.getMessageConfig().getStringList("commands.addFriend.triggers"); + return triggers.toArray(new String[triggers.size()]); + } +} diff --git a/src/com/jcdesimp/landlord/commands/Claim.java b/src/com/jcdesimp/landlord/commands/Claim.java new file mode 100644 index 0000000..d05b817 --- /dev/null +++ b/src/com/jcdesimp/landlord/commands/Claim.java @@ -0,0 +1,197 @@ +package com.jcdesimp.landlord.commands; + +import com.jcdesimp.landlord.Landlord; +import com.jcdesimp.landlord.persistantData.OwnedLand; +import org.bukkit.ChatColor; +import org.bukkit.Chunk; +import org.bukkit.Effect; +import org.bukkit.Sound; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; + +import java.util.List; + +/** + * Created by jcdesimp on 2/17/15. + * LandlordCommand object that lets a user Claim land + */ +public class Claim implements LandlordCommand { + + + private Landlord plugin; + + + /** + * Constructor for Claim command + * + * @param plugin the main Landlord plugin + */ + public Claim(Landlord plugin) { + this.plugin = plugin; + } + + /** + * Called when landlord claim command is executed + * This command must be run by a player + * + * @param sender who executed the command + * @param args given with command + * @return boolean + */ + @Override + public boolean execute(CommandSender sender, String[] args, String label) { + + FileConfiguration messages = plugin.getMessageConfig(); + + final String notPlayer = messages.getString("info.warnings.playerCommand"); // When run by non-player + final String noPerms = messages.getString("info.warnings.noPerms"); // No permissions + + final String cannotClaim = messages.getString("info.warnings.noClaim"); // Claiming disabled in this world + final String alreadyOwn = messages.getString("commands.claim.alerts.alreadyOwn"); // When you already own this land + final String otherOwn = messages.getString("commands.claim.alerts.otherOwn"); // Someone else owns this land + final String noClaimZone = messages.getString("commands.claim.alerts.noClaimZone"); // You can't claim here! (Worldguard) + final String ownLimit = messages.getString("commands.claim.alerts.ownLimit"); // Chunk limit hit + final String claimPrice = messages.getString("commands.claim.alerts.claimPrice"); // Not enough funds + final String charged = messages.getString("commands.claim.alerts.charged"); // Charged for claim + final String success = messages.getString("commands.claim.alerts.success"); // Chunk claim successful + + //is sender a player + if (!(sender instanceof Player)) { + sender.sendMessage(ChatColor.DARK_RED + notPlayer); + } else { + Player player = (Player) sender; + if (!player.hasPermission("landlord.player.own")) { + player.sendMessage(ChatColor.RED + noPerms); + return true; + } + + + //sender.sendMessage(ChatColor.GOLD + "Current Location: " + player.getLocation().toString()); + Chunk currChunk = player.getLocation().getChunk(); + + List disabledWorlds = plugin.getConfig().getStringList("disabled-worlds"); + for (String s : disabledWorlds) { + if (s.equalsIgnoreCase(currChunk.getWorld().getName())) { + player.sendMessage(ChatColor.RED + cannotClaim); + return true; + } + } + + // Check if worldguard is installed + if (plugin.hasWorldGuard()) { + // if it is make sure that the attempted land claim isn't with a protected worldguard region. + if (!plugin.getWgHandler().canClaim(player, currChunk)) { + player.sendMessage(ChatColor.RED + noClaimZone); + return true; + } + } + + + OwnedLand land = OwnedLand.landFromProperties(player, currChunk); + OwnedLand dbLand = OwnedLand.getLandFromDatabase(currChunk.getX(), currChunk.getZ(), currChunk.getWorld().getName()); + + + if (dbLand != null) { + //Check if they already own this land + if (dbLand.ownerUUID().equals(player.getUniqueId())) { + player.sendMessage(ChatColor.YELLOW + alreadyOwn); + return true; + } + player.sendMessage(ChatColor.YELLOW + otherOwn); + return true; + + } + int orLimit = plugin.getConfig().getInt("limits.landLimit", 10); + int limit = plugin.getConfig().getInt("limits.landLimit", 10); + + if (player.hasPermission("landlord.limit.extra5")) { + limit = orLimit + plugin.getConfig().getInt("limits.extra5", 0); + } else if (player.hasPermission("landlord.limit.extra4")) { + limit = orLimit + plugin.getConfig().getInt("limits.extra4", 0); + } else if (player.hasPermission("landlord.limit.extra3")) { + limit = orLimit + plugin.getConfig().getInt("limits.extra3", 0); + } else if (player.hasPermission("landlord.limit.extra2")) { + limit = orLimit + plugin.getConfig().getInt("limits.extra2", 0); + } else if (player.hasPermission("landlord.limit.extra")) { + limit = orLimit + plugin.getConfig().getInt("limits.extra", 0); + } + + if (limit >= 0 && !player.hasPermission("landlord.limit.override")) { + if (plugin.getDatabase().find(OwnedLand.class).where().eq("ownerName", player.getUniqueId().toString()).findRowCount() >= limit) { + player.sendMessage(ChatColor.RED + ownLimit.replace("#{limit}", "" + limit)); + return true; + } + } + + //Money Handling + if (plugin.hasVault()) { + if (plugin.getvHandler().hasEconomy()) { + Double amt = plugin.getConfig().getDouble("economy.buyPrice", 100.0); + if (amt > 0) { + int numFree = plugin.getConfig().getInt("economy.freeLand", 0); + if (numFree > 0 && plugin.getDatabase().find(OwnedLand.class).where().eq("ownerName", player.getUniqueId().toString()).findRowCount() < numFree) { + //player.sendMessage(ChatColor.YELLOW+"You have been charged " + plugin.getvHandler().formatCash(amt) + " to purchase land."); + } else if (!plugin.getvHandler().chargeCash(player, amt)) { + player.sendMessage(ChatColor.RED + claimPrice.replace("#{cost}", plugin.getvHandler().formatCash(amt))); + return true; + } else { + player.sendMessage(ChatColor.YELLOW + charged.replace("#{cost}", plugin.getvHandler().formatCash(amt))); + } + } + + } + } + Landlord.getInstance().getDatabase().save(land); + land.highlightLand(player, Effect.HAPPY_VILLAGER); + sender.sendMessage( + ChatColor.GREEN + success + .replace("#{chunkCoords}", "(" + currChunk.getX() + ", " + currChunk.getZ() + ")") + .replace("#{worldName}", currChunk.getWorld().getName())); + + if (plugin.getConfig().getBoolean("options.soundEffects", true)) { + player.playSound(player.getLocation(), Sound.ENTITY_FIREWORK_TWINKLE, 10, 10); + } + + + plugin.getMapManager().updateAll(); + //sender.sendMessage(ChatColor.DARK_GREEN + "Land claim command executed!"); + } + return true; + } + + @Override + public String getHelpText(CommandSender sender) { + FileConfiguration messages = plugin.getMessageConfig(); + + String usage = messages.getString("commands.claim.usage"); // get the base usage string + String desc = messages.getString("commands.claim.description"); // get the description + String priceWarning = messages.getString("commands.claim.alerts.cost"); // get the price warning message + + + String helpString = ""; // start building the help string + + helpString += Utils.helpString(usage, desc, getTriggers()[0].toLowerCase()); + + if (plugin.hasVault()) { + if (plugin.getvHandler().hasEconomy() && plugin.getConfig().getDouble("economy.buyPrice", 100.0) > 0) { //conf + helpString += ChatColor.YELLOW + " " + ChatColor.ITALIC + priceWarning + .replace( + "#{pricetag}", // insert the formatted price string + plugin.getvHandler().formatCash(plugin.getConfig().getDouble("economy.buyPrice", 100.0)) //conf + ); + } + } + + + // return the constructed and colorized help string + return helpString; + + } + + @Override + public String[] getTriggers() { + List triggers = plugin.getMessageConfig().getStringList("commands.claim.triggers"); + return triggers.toArray(new String[triggers.size()]); + } +} diff --git a/src/com/jcdesimp/landlord/commands/ClearWorld.java b/src/com/jcdesimp/landlord/commands/ClearWorld.java new file mode 100644 index 0000000..11dda20 --- /dev/null +++ b/src/com/jcdesimp/landlord/commands/ClearWorld.java @@ -0,0 +1,117 @@ +package com.jcdesimp.landlord.commands; + +import com.jcdesimp.landlord.Landlord; +import com.jcdesimp.landlord.persistantData.OwnedLand; +import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; + +import java.util.List; + +import static org.bukkit.Bukkit.getOfflinePlayer; + +/** + * Created by jcdesimp on 2/18/15. + * Administration command to clear all land in a specified world. + */ +public class ClearWorld implements LandlordCommand { + + private Landlord plugin; + + public ClearWorld(Landlord plugin) { + this.plugin = plugin; + } + + @Override + public boolean execute(CommandSender sender, String[] args, String label) { + + FileConfiguration messages = plugin.getMessageConfig(); + + final String usage = messages.getString("commands.clearWorld.usage"); + + final String noPerms = messages.getString("info.warnings.noPerms"); + final String unknownPlayer = messages.getString("info.warnings.unknownPlayer"); + final String notConsole = messages.getString("commands.clearWorld.alerts.notConsole"); + final String noLand = messages.getString("commands.clearWorld.alerts.noLand"); + final String confirmation = messages.getString("commands.clearWorld.alerts.success"); + + + if (!sender.hasPermission("landlord.admin.clearworld")) { + sender.sendMessage(ChatColor.RED + noPerms); + return true; + } + if (args.length > 1) { + List land; + if (args.length > 2) { + /* + * ************************************* + * mark for possible change !!!!!!!!! + * ************************************* + */ + OfflinePlayer possible = getOfflinePlayer(args[2]); + if (!possible.hasPlayedBefore() && !possible.isOnline()) { + sender.sendMessage(ChatColor.RED + unknownPlayer); + return true; + } + land = plugin.getDatabase().find(OwnedLand.class).where().eq("ownerName", possible.getUniqueId().toString()).eq("worldName", args[1]).findList(); + } else { + if (sender instanceof Player) { + sender.sendMessage(ChatColor.RED + notConsole); + return true; + } + land = plugin.getDatabase().find(OwnedLand.class).where().eq("worldName", args[1]).findList(); + } + if (land.isEmpty()) { + sender.sendMessage(ChatColor.RED + noLand); + return true; + } + + plugin.getDatabase().delete(land); + plugin.getMapManager().updateAll(); + sender.sendMessage(ChatColor.GREEN + confirmation); + + } else { + sender.sendMessage(ChatColor.RED + usage.replace("#{label}", label).replace("#{cmd}", args[0])); + } + return true; + } + + @Override + public String getHelpText(CommandSender sender) { + + // only bother showing them this command if they have permission to do it. + if (!sender.hasPermission("landlord.admin.clearworld")) { + return null; + } + + FileConfiguration messages = plugin.getMessageConfig(); + + final String usage = messages.getString("commands.clearWorld.usage"); // get the base usage string + final String desc = messages.getString("commands.clearWorld.description"); + final String chunkWarning = messages.getString("commands.clearWorld.alerts.chunkWarning"); // get the "chunks won't regen" warning + + + String helpString = ""; // start building the help string + + + // add the formatted string to it. + helpString += Utils.helpString(usage, desc, getTriggers()[0].toLowerCase()); + + // If chunk regen is on, warn them that bulk deletions will not regen + if (plugin.getConfig().getBoolean("options.regenOnUnclaim", false)) { //conf + helpString += ChatColor.YELLOW + " " + ChatColor.ITALIC + chunkWarning; + } + + // return the constructed and colorized help string + return helpString; + + } + + @Override + public String[] getTriggers() { + final List triggers = plugin.getMessageConfig().getStringList("commands.clearWorld.triggers"); + return triggers.toArray(new String[triggers.size()]); + } +} diff --git a/src/com/jcdesimp/landlord/commands/FriendAll.java b/src/com/jcdesimp/landlord/commands/FriendAll.java new file mode 100644 index 0000000..e07fad2 --- /dev/null +++ b/src/com/jcdesimp/landlord/commands/FriendAll.java @@ -0,0 +1,95 @@ +package com.jcdesimp.landlord.commands; + +import com.jcdesimp.landlord.Landlord; +import com.jcdesimp.landlord.persistantData.Friend; +import com.jcdesimp.landlord.persistantData.OwnedLand; +import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; + +import java.util.List; + +import static org.bukkit.Bukkit.getOfflinePlayer; + +/** + * Created by jcdesimp on 2/18/15. + * Command for a player toi add a friend to all of their land at once. + */ +public class FriendAll implements LandlordCommand { + + private Landlord plugin; + + public FriendAll(Landlord plugin) { + this.plugin = plugin; + } + + @Override + public boolean execute(CommandSender sender, String[] args, String label) { + FileConfiguration messages = plugin.getMessageConfig(); + final String notPlayerString = messages.getString("info.warnings.playerCommand"); + final String usageString = messages.getString("commands.friendAll.usage"); + final String noPermsString = messages.getString("info.warnings.noPerms"); + final String unknownPlayer = messages.getString("info.warnings.unknownPlayer"); + final String friendAddedString = messages.getString("commands.friendAll.alerts.success"); + final String noLandString = messages.getString("commands.friendAll.alerts.noLand"); + + + //is sender a player + if (!(sender instanceof Player)) { + sender.sendMessage(ChatColor.DARK_RED + notPlayerString); + } else { + if (args.length < 2) { + sender.sendMessage(ChatColor.RED + usageString.replace("#{label}", label)); + return true; + } + Player player = (Player) sender; + if (!player.hasPermission("landlord.player.own")) { + player.sendMessage(ChatColor.RED + noPermsString); + return true; + } + + List pLand = plugin.getDatabase().find(OwnedLand.class).where().eq("ownerName", player.getUniqueId()).findList(); + OfflinePlayer possible = getOfflinePlayer(args[1]); + if (!possible.hasPlayedBefore() && !possible.isOnline()) { + player.sendMessage(ChatColor.RED + unknownPlayer); + return true; + } + + if (pLand.size() > 0) { + for (OwnedLand l : pLand) { + l.addFriend(Friend.friendFromOfflinePlayer(getOfflinePlayer(args[1]))); + } + + plugin.getDatabase().save(pLand); + + + player.sendMessage(ChatColor.GREEN + friendAddedString.replace("#{player}", args[1])); + return true; + } else { + player.sendMessage(ChatColor.YELLOW + noLandString); + } + + } + return true; + } + + @Override + public String getHelpText(CommandSender sender) { + FileConfiguration messages = plugin.getMessageConfig(); + + final String usage = messages.getString("commands.friendAll.usage"); // get the base usage string + final String desc = messages.getString("commands.friendAll.description"); // get the description + + // return the constructed and colorized help string + return Utils.helpString(usage, desc, getTriggers()[0].toLowerCase()); + + } + + @Override + public String[] getTriggers() { + final List triggers = plugin.getMessageConfig().getStringList("commands.friendAll.triggers"); + return triggers.toArray(new String[triggers.size()]); + } +} diff --git a/src/com/jcdesimp/landlord/commands/Friends.java b/src/com/jcdesimp/landlord/commands/Friends.java new file mode 100644 index 0000000..f87057b --- /dev/null +++ b/src/com/jcdesimp/landlord/commands/Friends.java @@ -0,0 +1,152 @@ +package com.jcdesimp.landlord.commands; + +import com.jcdesimp.landlord.Landlord; +import com.jcdesimp.landlord.persistantData.Friend; +import com.jcdesimp.landlord.persistantData.OwnedLand; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Chunk; +import org.bukkit.Effect; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; + +import static org.bukkit.util.NumberConversions.ceil; + +/** + * Created by jcdesimp on 2/18/15. + * List the friends of the current land + */ +public class Friends implements LandlordCommand { + + private Landlord plugin; + + public Friends(Landlord plugin) { + this.plugin = plugin; + } + + @Override + public boolean execute(CommandSender sender, String[] args, String label) { + FileConfiguration messages = plugin.getMessageConfig(); + + final String notPlayer = messages.getString("info.warnings.playerCommand"); + final String noPerms = messages.getString("info.warnings.noPerms"); + final String notOwner = messages.getString("info.warnings.notOwner"); + final String badPageNum = messages.getString("info.warnings.badPage"); + final String friendListHeader = messages.getString("commands.friends.alerts.listHeader"); + final String noFriends = messages.getString("commands.friends.alerts.noFriends"); + final String onlineString = messages.getString("commands.friends.alerts.online"); + final String offlineString = messages.getString("commands.friends.alerts.offline"); + final String invalidPage = messages.getString("info.warnings.badPage"); + final String nextPageString = messages.getString("info.alerts.nextPage"); + + + if (!(sender instanceof Player)) { + sender.sendMessage(ChatColor.DARK_RED + notPlayer); + } else { + Player player = (Player) sender; + if (!player.hasPermission("landlord.player.own")) { + player.sendMessage(ChatColor.RED + noPerms); + return true; + } + Chunk currChunk = player.getLocation().getChunk(); + OwnedLand land = OwnedLand.getLandFromDatabase(currChunk.getX(), currChunk.getZ(), currChunk.getWorld().getName()); + if (land == null || (!land.ownerUUID().equals(player.getUniqueId()) && !player.hasPermission("landlord.admin.friends"))) { + player.sendMessage(ChatColor.RED + notOwner); + return true; + } +// if(!land.getOwnerName().equals(player.getUniqueId())){ +// //player.sendMessage(ChatColor.YELLOW+"Viewing friends of someone else's land."); +// } + if (plugin.getConfig().getBoolean("options.particleEffects", true)) { //conf + land.highlightLand(player, Effect.HEART, 3); + } + //check if page number is valid + int pageNumber = 1; + if (args.length > 1 && args[0].equals("friends")) { + try { + pageNumber = Integer.parseInt(args[1]); + } catch (NumberFormatException e) { + player.sendMessage(ChatColor.RED + badPageNum); + return true; + } + } + + //List myLand = plugin.getDatabase().find(OwnedLand.class).where().eq("ownerName",player.getName()).findList(); + + String header = ChatColor.DARK_GREEN + "----- " + friendListHeader + " -----\n"; + ArrayList friendList = new ArrayList(); + if (land.getFriends().isEmpty()) { + player.sendMessage(ChatColor.YELLOW + noFriends); + return true; + } + for (Friend f : land.getFriends()) { + String fr = ChatColor.DARK_GREEN + " - " + ChatColor.GOLD + f.getName() + ChatColor.DARK_GREEN + " - "; + /* + * ************************************* + * mark for possible change !!!!!!!!! + * ************************************* + */ + if (Bukkit.getOfflinePlayer(f.getUUID()).isOnline()) { + fr += ChatColor.GREEN + "" + ChatColor.ITALIC + onlineString; + } else { + fr += ChatColor.RED + "" + ChatColor.ITALIC + offlineString; + } + + fr += "\n"; + friendList.add(fr); + } + + //Amount to be displayed per page + final int numPerPage = 8; + + int numPages = ceil((double) friendList.size() / (double) numPerPage); + if (pageNumber > numPages) { + sender.sendMessage(ChatColor.RED + invalidPage); + return true; + } + String pMsg = header; + if (pageNumber == numPages) { + for (int i = (numPerPage * pageNumber - numPerPage); i < friendList.size(); i++) { + pMsg += friendList.get(i); + } + pMsg += ChatColor.DARK_GREEN + "------------------------------"; + } else { + for (int i = (numPerPage * pageNumber - numPerPage); i < (numPerPage * pageNumber); i++) { + pMsg += friendList.get(i); + } + + pMsg += "\n" + ChatColor.DARK_GREEN + "--- " + nextPageString + .replace("#{label}", ChatColor.YELLOW + "/" + label) + .replace("#{cmd}", args[0]) + .replace("#{pageNumber}", "" + (pageNumber + 1) + ChatColor.DARK_GREEN) + + " ---"; + } + player.sendMessage(pMsg); + + + } + return true; + } + + @Override + public String getHelpText(CommandSender sender) { + FileConfiguration messages = plugin.getMessageConfig(); + + final String usage = messages.getString("commands.friends.usage"); // get the base usage string + final String desc = messages.getString("commands.friends.description"); // get the description + + // return the constructed and colorized help string + return Utils.helpString(usage, desc, getTriggers()[0].toLowerCase()); + + } + + @Override + public String[] getTriggers() { + final List triggers = plugin.getMessageConfig().getStringList("commands.friends.triggers"); + return triggers.toArray(new String[triggers.size()]); + } +} diff --git a/src/com/jcdesimp/landlord/commands/Help.java b/src/com/jcdesimp/landlord/commands/Help.java new file mode 100644 index 0000000..e6f2d50 --- /dev/null +++ b/src/com/jcdesimp/landlord/commands/Help.java @@ -0,0 +1,127 @@ +package com.jcdesimp.landlord.commands; + +import com.jcdesimp.landlord.Landlord; +import com.jcdesimp.landlord.LandlordCommandExecutor; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.FileConfiguration; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.bukkit.util.NumberConversions.ceil; + +/** + * Created by jcdesimp on 2/19/15. + * Command to display help information to the player + */ +public class Help implements LandlordCommand { + + private Landlord plugin; + private ArrayList registeredCommands; + + + public Help(Landlord plugin, LandlordCommandExecutor commandHandler) { + this.plugin = plugin; + this.registeredCommands = new ArrayList(); + } + + + public void addCommand(LandlordCommand lc) { + registeredCommands.add(lc); + } + + + @Override + public boolean execute(CommandSender sender, String[] args, String label) { + FileConfiguration messages = plugin.getMessageConfig(); + + final String badPageNum = messages.getString("info.warnings.badPage"); + final String helpHeader = messages.getString("commands.help.alerts.header"); + final String aliases = messages.getString("commands.help.alerts.aliases"); + final String nextPageString = messages.getString("info.alerts.nextPage"); + + final String aliasList = "/landlord, /land, /ll"; + + //check if page number is valid + int pageNumber = 1; + if (args.length > 1 && Arrays.asList(getTriggers()).contains(args[0])) { + try { + pageNumber = Integer.parseInt(args[1]); + } catch (NumberFormatException e) { + // Is not a number! + sender.sendMessage(ChatColor.RED + badPageNum); + return true; + } + } + + + // construct the header form the base strings + String header = ChatColor.DARK_GREEN + + "-|| " + + helpHeader // start out with the initial header + .replace("#{version}", "v" + plugin.getDescription().getVersion()) // fill in the version + .replace("#{author}", ChatColor.BLUE + plugin.getDescription().getAuthors().get(0) + ChatColor.DARK_GREEN) // fill in the author name + + " ||--" + + "\n " + ChatColor.GRAY + aliases.replace("#{aliases}", aliasList); // add the aliases line + + ArrayList helpList = new ArrayList(); + + // Get each help string + for (LandlordCommand lc : registeredCommands) { + String currCmd = lc.getHelpText(sender); + if (currCmd != null) { // make sure the help string isn't null (can happen if conditions aren't right) + helpList.add(currCmd.replace("#{label}", label)); + } + } + + + //Amount to be displayed per page + final int numPerPage = 5; + + int numPages = ceil((double) helpList.size() / (double) numPerPage); + if (pageNumber > numPages) { + sender.sendMessage(ChatColor.RED + badPageNum); + return true; + } + String pMsg = header; + if (pageNumber == numPages) { + for (int i = (numPerPage * pageNumber - numPerPage); i < helpList.size(); i++) { + pMsg += '\n' + helpList.get(i); + } + pMsg += ChatColor.DARK_GREEN + "\n------------------------------"; + } else { + for (int i = (numPerPage * pageNumber - numPerPage); i < (numPerPage * pageNumber); i++) { + pMsg += '\n' + helpList.get(i); + } + + pMsg += "\n" + ChatColor.DARK_GREEN + "--- " + nextPageString + .replace("#{label}", ChatColor.YELLOW + "/" + label) + .replace("#{cmd}", getTriggers()[0]) + .replace("#{pageNumber}", "" + (pageNumber + 1) + ChatColor.DARK_GREEN) + + " ---"; + } + + sender.sendMessage(pMsg); + return true; + } + + @Override + public String getHelpText(CommandSender sender) { + + FileConfiguration messages = plugin.getMessageConfig(); + + final String usage = messages.getString("commands.help.usage"); // get the base usage string + final String desc = messages.getString("commands.help.description"); // get the description + + // return the constructed and colorized help string + return Utils.helpString(usage, desc, getTriggers()[0].toLowerCase()); + } + + @Override + public String[] getTriggers() { + final List triggers = plugin.getMessageConfig().getStringList("commands.help.triggers"); + return triggers.toArray(new String[triggers.size()]); + } +} diff --git a/src/com/jcdesimp/landlord/commands/Info.java b/src/com/jcdesimp/landlord/commands/Info.java new file mode 100644 index 0000000..d68025b --- /dev/null +++ b/src/com/jcdesimp/landlord/commands/Info.java @@ -0,0 +1,97 @@ +package com.jcdesimp.landlord.commands; + +import com.jcdesimp.landlord.Landlord; +import com.jcdesimp.landlord.persistantData.OwnedLand; +import org.bukkit.ChatColor; +import org.bukkit.Chunk; +import org.bukkit.Effect; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; + +import java.util.List; + +/** + * Created by jcdesimp on 2/19/15. + * Command to view info about the current land. + */ +public class Info implements LandlordCommand { + + private Landlord plugin; + + public Info(Landlord plugin) { + this.plugin = plugin; + } + + @Override + public boolean execute(CommandSender sender, String[] args, String label) { + + FileConfiguration messages = plugin.getMessageConfig(); + + final String notPlayer = messages.getString("info.warnings.playerCommand"); + final String noPerms = messages.getString("info,warnings.noPerms"); + final String noOwner = messages.getString("info.alerts.noOwner"); + final String landInfoString = messages.getString("commands.info.alerts.landInfo"); + final String landOwnerString = messages.getString("commands.info.alerts.landOwner"); + + if (!(sender instanceof Player)) { + sender.sendMessage(ChatColor.DARK_RED + notPlayer); + } else { + Player player = (Player) sender; + if (!player.hasPermission("landlord.player.info")) { + player.sendMessage(ChatColor.RED + noPerms); + return true; + } + Chunk currChunk = player.getLocation().getChunk(); + OwnedLand land = OwnedLand.getLandFromDatabase(currChunk.getX(), currChunk.getZ(), currChunk.getWorld().getName()); + String owner = ChatColor.GRAY + "" + ChatColor.ITALIC + noOwner; + if (land != null) { + + /* + * ************************************* + * mark for possible change !!!!!!!!! + * ************************************* + */ + owner = ChatColor.GOLD + land.getOwnerUsername(); + } else { + land = OwnedLand.landFromProperties(null, currChunk); + } + + if (plugin.getConfig().getBoolean("options.particleEffects")) { + land.highlightLand(player, Effect.LAVADRIP); + } + + // Build the land info string + String msg = ChatColor.DARK_GREEN + "--- " + landInfoString + .replace("#{chunkCoords}", (ChatColor.GOLD + "(" + currChunk.getX() + ", " + currChunk.getZ() + ")" + ChatColor.DARK_GREEN)) + .replace("#{worldName}", ChatColor.GOLD + "\"" + currChunk.getWorld().getName() + "\"") + + + ChatColor.DARK_GREEN + "-----\n" + landOwnerString.replace("#{ownerName}", owner); + player.sendMessage(msg); + + } + return true; + } + + @Override + public String getHelpText(CommandSender sender) { + + if (!sender.hasPermission("landlord.player.info")) { // make sure player has permission to do this command + return null; + } + + FileConfiguration messages = plugin.getMessageConfig(); + + final String usage = messages.getString("commands.info.usage"); // get the base usage string + final String desc = messages.getString("commands.info.description"); // get the description + + // return the constructed and colorized help string + return Utils.helpString(usage, desc, getTriggers()[0].toLowerCase()); + } + + @Override + public String[] getTriggers() { + final List triggers = plugin.getMessageConfig().getStringList("commands.info.triggers"); + return triggers.toArray(new String[triggers.size()]); + } +} diff --git a/src/com/jcdesimp/landlord/commands/LandList.java b/src/com/jcdesimp/landlord/commands/LandList.java new file mode 100644 index 0000000..85e6c83 --- /dev/null +++ b/src/com/jcdesimp/landlord/commands/LandList.java @@ -0,0 +1,139 @@ +package com.jcdesimp.landlord.commands; + +import com.jcdesimp.landlord.Landlord; +import com.jcdesimp.landlord.persistantData.OwnedLand; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; + +import static org.bukkit.util.NumberConversions.ceil; + +/** + * Created by jcdesimp on 2/18/15. + * Command to get a list of the sender player's land + */ +public class LandList implements LandlordCommand { + + private Landlord plugin; + + public LandList(Landlord plugin) { + this.plugin = plugin; + } + + /** + * Display a list of all owned land to a player + * + * @param sender who executed the command + * @param args given with command + * @return boolean + */ + @Override + public boolean execute(CommandSender sender, String[] args, String label) { + + + FileConfiguration messages = plugin.getMessageConfig(); + + final String notPlayer = messages.getString("info.warnings.playerCommand"); + final String noPerms = messages.getString("info.warnings.noPerms"); + final String badPageNum = messages.getString("info.warnings.badPage"); + final String noLand = messages.getString("commands.landList.alerts.noLand"); + + final String outputHeader = messages.getString("commands.landList.alerts.listHeader"); + final String ownedLandString = messages.getString("commands.landList.alerts.outputHeader"); + final String pageNum = messages.getString("commands.landList.alerts.pageLabel"); + final String nextPageString = messages.getString("info.alerts.nextPage"); + + + if (!(sender instanceof Player)) { + sender.sendMessage(ChatColor.DARK_RED + notPlayer); + } else { + Player player = (Player) sender; + if (!player.hasPermission("landlord.player.own")) { + player.sendMessage(ChatColor.RED + noPerms); + return true; + } + + //check if page number is valid + int pageNumber = 1; + if (args.length > 1) { + try { + pageNumber = Integer.parseInt(args[1]); + } catch (NumberFormatException e) { + player.sendMessage(ChatColor.RED + badPageNum); + return true; + } + } + + List myLand = plugin.getDatabase().find(OwnedLand.class).where().eq("ownerName", player.getUniqueId().toString()).findList(); + if (myLand.size() == 0) { + player.sendMessage(ChatColor.YELLOW + noLand); + } else { + String header = ChatColor.DARK_GREEN + " | " + outputHeader + " |\n"; + ArrayList landList = new ArrayList<>(); + //OwnedLand curr = myLand.get(0); + for (OwnedLand aMyLand : myLand) { + landList.add((ChatColor.GOLD + " (" + aMyLand.getXBlock() + ", " + aMyLand.getZBlock() + ") - (" + aMyLand.getX() + ", " + aMyLand.getZ() + ") - " + + aMyLand.getWorldName()) + "\n") + ; + } + //Amount to be displayed per page + final int numPerPage = 7; + + int numPages = ceil((double) landList.size() / (double) numPerPage); + if (pageNumber > numPages) { + player.sendMessage(ChatColor.RED + badPageNum); + return true; + } + + //String pMsg = ChatColor.DARK_GREEN + "--- " + ChatColor.YELLOW + ownedLandString + ChatColor.DARK_GREEN + " ---" + ChatColor.YELLOW + " Page " + pageNumber + ChatColor.DARK_GREEN + " ---\n" + header; + String pMsg = (ChatColor.DARK_GREEN + "--- " + ChatColor.YELLOW + ownedLandString + ChatColor.DARK_GREEN + " --- " + ChatColor.YELLOW + pageNum) + .replace("#{pageNum}", pageNumber + "") + + ChatColor.DARK_GREEN + " ---\n" + header; + + + if (pageNumber == numPages) { + for (int i = (numPerPage * pageNumber - numPerPage); i < landList.size(); i++) { + pMsg += landList.get(i); + } + pMsg += ChatColor.DARK_GREEN + "------------------------------"; + } else { + for (int i = (numPerPage * pageNumber - numPerPage); i < (numPerPage * pageNumber); i++) { + pMsg += landList.get(i); + } + //pMsg += ChatColor.DARK_GREEN + "--- do" + ChatColor.YELLOW + " /" + label + " list " + (pageNumber + 1) + ChatColor.DARK_GREEN + " for next page ---"; + + pMsg += ChatColor.DARK_GREEN + "--- " + ChatColor.YELLOW + nextPageString + .replace("#{label}", "/" + label) + .replace("#{cmd}", args[0]) + .replace("#{pageNumber}", "" + (pageNumber + 1)) + + ChatColor.DARK_GREEN + " ---"; + } + + player.sendMessage(pMsg); + } + + } + return true; + } + + + @Override + public String getHelpText(CommandSender sender) { + FileConfiguration messages = plugin.getMessageConfig(); + final String usage = messages.getString("commands.landList.usage"); // get the base usage string + final String desc = messages.getString("commands.landList.description"); // get the description + // return the constructed and colorized help string + return Utils.helpString(usage, desc, getTriggers()[0].toLowerCase()); + + } + + @Override + public String[] getTriggers() { + final List triggers = plugin.getMessageConfig().getStringList("commands.landList.triggers"); + return triggers.toArray(new String[triggers.size()]); + } +} diff --git a/src/com/jcdesimp/landlord/commands/LandlordCommand.java b/src/com/jcdesimp/landlord/commands/LandlordCommand.java new file mode 100644 index 0000000..68e4107 --- /dev/null +++ b/src/com/jcdesimp/landlord/commands/LandlordCommand.java @@ -0,0 +1,37 @@ +package com.jcdesimp.landlord.commands; + +import org.bukkit.command.CommandSender; + +/** + * Created by jcdesimp on 2/17/15. + * Interface for a player executable Landlord command + */ +public interface LandlordCommand { + /** + * Execute the command + * + * @param sender who sent the command + * @param args array of arguments given with the command + * @param label the actual command/alias that was entered. + * @return boolean on whether or not success + */ + boolean execute(CommandSender sender, String[] args, String label); + + /** + * Get this command help test + * + * @param sender of the command. + * @return String that describes the command + */ + String getHelpText(CommandSender sender); + + /** + * Get the list of strings (non-case sensitive) that can trigger + * this command. (command names, aliases, etc.) + * + * @return the list of valid command trigger words + */ + String[] getTriggers(); + + +} diff --git a/src/com/jcdesimp/landlord/commands/ListPlayer.java b/src/com/jcdesimp/landlord/commands/ListPlayer.java new file mode 100644 index 0000000..4bed4de --- /dev/null +++ b/src/com/jcdesimp/landlord/commands/ListPlayer.java @@ -0,0 +1,153 @@ +package com.jcdesimp.landlord.commands; + +import com.jcdesimp.landlord.Landlord; +import com.jcdesimp.landlord.persistantData.OwnedLand; +import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.FileConfiguration; + +import java.util.ArrayList; +import java.util.List; + +import static org.bukkit.Bukkit.getOfflinePlayer; +import static org.bukkit.util.NumberConversions.ceil; + +/** + * Created by jcdesimp on 2/18/15. + * List the land of a specified player (typically for administrator use) + */ +public class ListPlayer implements LandlordCommand { + + private Landlord plugin; + + public ListPlayer(Landlord plugin) { + this.plugin = plugin; + } + + /** + * @param sender who sent the command + * @param args array of arguments given with the command + * @param label the actual command/alias that was entered. + * @return Boolean of success + */ + @Override + public boolean execute(CommandSender sender, String[] args, String label) { + + FileConfiguration messages = plugin.getMessageConfig(); + + final String usage = messages.getString("commands.listPlayer.usage"); + final String noPerms = messages.getString("info.warnings.noPerms"); + final String badPage = messages.getString("info.warnings.badPage"); + final String ownsNone = messages.getString("commands.listPlayer.alerts.ownsNone"); + final String listHeader = messages.getString("commands.listPlayer.alerts.listHeader"); + final String ownersLand = messages.getString("commands.listPlayer.alerts.ownersLand"); + final String pageNum = messages.getString("commands.listPlayer.alerts.pageNum"); + final String nextPageString = messages.getString("commands.listPlayer.alerts.nextPage"); + + + String owner; + + //sender.sendMessage(ChatColor.DARK_RED + "This command can only be run by a player."); + if (args.length > 1) { + owner = args[1]; + } else { + sender.sendMessage(ChatColor.RED + usage.replace("#{label}", label)); + return true; + } + + //Player player = (Player) sender; + if (!sender.hasPermission("landlord.admin.list")) { + sender.sendMessage(ChatColor.RED + noPerms); + return true; + } + + //check if page number is valid + int pageNumber = 1; + if (args.length > 2) { + try { + pageNumber = Integer.parseInt(args[2]); + } catch (NumberFormatException e) { + sender.sendMessage(ChatColor.RED + badPage); + return true; + } + } + /* + * ************************************* + * mark for possible change !!!!!!!!! + * ************************************* + */ + OfflinePlayer possible = getOfflinePlayer(args[1]); + if (!possible.hasPlayedBefore() && !possible.isOnline()) { + sender.sendMessage(ChatColor.YELLOW + ownsNone.replace("#{owner}", owner)); + return true; + } + List myLand = plugin.getDatabase().find(OwnedLand.class).where().ieq("ownerName", getOfflinePlayer(owner).getUniqueId().toString()).findList(); + if (myLand.size() == 0) { + sender.sendMessage(ChatColor.YELLOW + ownsNone.replace("#{owner}", owner)); + } else { + String header = ChatColor.DARK_GREEN + " | " + listHeader + " | \n"; + ArrayList landList = new ArrayList<>(); + //OwnedLand curr = myLand.get(0); + for (OwnedLand aMyLand : myLand) { + landList.add((ChatColor.GOLD + " (" + aMyLand.getXBlock() + ", " + aMyLand.getZBlock() + ") - (" + aMyLand.getX() + ", " + aMyLand.getZ() + ") - " + + aMyLand.getWorldName()) + "\n"); + } + //Amount to be displayed per page + final int numPerPage = 7; + + int numPages = ceil((double) landList.size() / (double) numPerPage); + if (pageNumber > numPages) { + sender.sendMessage(ChatColor.RED + badPage); + return true; + } + String pMsg = ChatColor.DARK_GREEN + "--- " + ChatColor.YELLOW + ownersLand.replace("#{owner}", owner) + ChatColor.DARK_GREEN + " ---" + ChatColor.YELLOW + + pageNum.replace("#{pageNumber}", "" + pageNumber) + ChatColor.DARK_GREEN + " ---\n" + + header; + if (pageNumber == numPages) { + for (int i = (numPerPage * pageNumber - numPerPage); i < landList.size(); i++) { + pMsg += landList.get(i); + } + pMsg += ChatColor.DARK_GREEN + "------------------------------"; + } else { + for (int i = (numPerPage * pageNumber - numPerPage); i < (numPerPage * pageNumber); i++) { + pMsg += landList.get(i); + } + + pMsg += ChatColor.DARK_GREEN + "--- " + ChatColor.YELLOW + nextPageString + .replace("#{label}", "/" + label) + .replace("#{cmd}", args[0]) + .replace("#{pageNumber}", "" + pageNumber + 1) + + " ---"; + } + + sender.sendMessage(pMsg); + } + + + return true; + } + + @Override + public String getHelpText(CommandSender sender) { + + if (!sender.hasPermission("landlord.admin.list")) { // Don't bother showing command help if player can't do it + return null; + } + + FileConfiguration messages = plugin.getMessageConfig(); + + final String usage = messages.getString("commands.listPlayer.usage"); // get the base usage string + final String desc = messages.getString("commands.listPlayer.description"); // get the description + + // return the constructed and colorized help string + return Utils.helpString(usage, desc, getTriggers()[0].toLowerCase()); + + } + + @Override + public String[] getTriggers() { + final List triggers = plugin.getMessageConfig().getStringList("commands.listPlayer.triggers"); + return triggers.toArray(new String[triggers.size()]); + } +} diff --git a/src/com/jcdesimp/landlord/commands/Manage.java b/src/com/jcdesimp/landlord/commands/Manage.java new file mode 100644 index 0000000..a1eb947 --- /dev/null +++ b/src/com/jcdesimp/landlord/commands/Manage.java @@ -0,0 +1,90 @@ +package com.jcdesimp.landlord.commands; + +import com.jcdesimp.landlord.Landlord; +import com.jcdesimp.landlord.persistantData.OwnedLand; +import org.bukkit.ChatColor; +import org.bukkit.Chunk; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; + +import java.util.List; + +/** + * Created by jcdesimp on 2/18/15. + * Command to bring up the land management interface. + */ +public class Manage implements LandlordCommand { + + private Landlord plugin; + + public Manage(Landlord plugin) { + this.plugin = plugin; + } + + /** + * Command for managing player land perms + * + * @param sender who executed the command + * @param args given with command + * @return boolean + */ + @Override + public boolean execute(CommandSender sender, String[] args, String label) { + + FileConfiguration messages = plugin.getMessageConfig(); + + final String notPlayer = messages.getString("info.warnings.playerCommand"); + final String noPerms = messages.getString("info.warnings.noPerms"); + final String noLand = messages.getString("commands.manage.alerts.noLand"); + final String notOwner = messages.getString("info.warnings.notOwner"); + final String otherLand = messages.getString("commands.manage.alerts.otherLand"); + + + if (!(sender instanceof Player)) { + sender.sendMessage(ChatColor.DARK_RED + notPlayer); + } else { + Player player = (Player) sender; + if (!player.hasPermission("landlord.player.own")) { + player.sendMessage(ChatColor.RED + noPerms); + return true; + } + if (plugin.getFlagManager().getRegisteredFlags().size() <= 0) { + player.sendMessage(ChatColor.RED + noLand); + return true; + } + Chunk currChunk = player.getLocation().getChunk(); + OwnedLand land = OwnedLand.getLandFromDatabase(currChunk.getX(), currChunk.getZ(), currChunk.getWorld().getName()); + if (land == null || (!land.ownerUUID().equals(player.getUniqueId()) && !player.hasPermission("landlord.admin.manage"))) { + player.sendMessage(ChatColor.RED + notOwner); + return true; + } + if (!land.ownerUUID().equals(player.getUniqueId())) { + player.sendMessage(ChatColor.YELLOW + otherLand); + } + plugin.getManageViewManager().activateView(player, land, plugin); + + + } + return true; + } + + @Override + public String getHelpText(CommandSender sender) { + + FileConfiguration messages = plugin.getMessageConfig(); + + final String usage = messages.getString("commands.manage.usage"); // get the base usage string + final String desc = messages.getString("commands.manage.description"); // get the description + + // return the constructed and colorized help string + return Utils.helpString(usage, desc, getTriggers()[0].toLowerCase()); + + } + + @Override + public String[] getTriggers() { + final List triggers = plugin.getMessageConfig().getStringList("commands.manage.triggers"); + return triggers.toArray(new String[triggers.size()]); + } +} diff --git a/src/com/jcdesimp/landlord/commands/Reload.java b/src/com/jcdesimp/landlord/commands/Reload.java new file mode 100644 index 0000000..42f3181 --- /dev/null +++ b/src/com/jcdesimp/landlord/commands/Reload.java @@ -0,0 +1,68 @@ +package com.jcdesimp.landlord.commands; + +import com.jcdesimp.landlord.Landlord; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.FileConfiguration; + +import java.util.List; + +/** + * Created by jcdesimp on 2/19/15. + * Administrative command to reload various resources/configuration files + */ +public class Reload implements LandlordCommand { + + private Landlord plugin; + + public Reload(Landlord plugin) { + this.plugin = plugin; + } + + /** + * Reload landlord configuration file + * + * @param sender who executed the command + * @param args given with command + * @param label exact command (or alias) run + * @return boolean of success + */ + @Override + public boolean execute(CommandSender sender, String[] args, String label) { + + FileConfiguration messages = plugin.getMessageConfig(); + + final String configReloaded = messages.getString("commands.reload.alerts.configReloaded"); + final String noPerms = messages.getString("info.warnings.noPerms"); + + if (sender.hasPermission("landlord.admin.reload")) { + plugin.reloadConfig(); + sender.sendMessage(ChatColor.GREEN + configReloaded); + return true; + } + sender.sendMessage(ChatColor.RED + noPerms); + return true; + } + + @Override + public String getHelpText(CommandSender sender) { + + if (!sender.hasPermission("landlord.admin.list")) { + return null; + } + + FileConfiguration messages = plugin.getMessageConfig(); + + final String usage = messages.getString("commands.reload.usage"); // get the base usage string + final String desc = messages.getString("commands.reload.description"); // get the description + + // return the constructed and colorized help string + return Utils.helpString(usage, desc, getTriggers()[0].toLowerCase()); + } + + @Override + public String[] getTriggers() { + final List triggers = plugin.getMessageConfig().getStringList("commands.reload.triggers"); + return triggers.toArray(new String[triggers.size()]); + } +} diff --git a/src/com/jcdesimp/landlord/commands/ShowMap.java b/src/com/jcdesimp/landlord/commands/ShowMap.java new file mode 100644 index 0000000..c57934f --- /dev/null +++ b/src/com/jcdesimp/landlord/commands/ShowMap.java @@ -0,0 +1,85 @@ +package com.jcdesimp.landlord.commands; + +import com.jcdesimp.landlord.Landlord; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; + +import java.util.List; + +/** + * Created by jcdesimp on 2/18/15. + * Display the landlord map + */ +public class ShowMap implements LandlordCommand { + + private Landlord plugin; + + public ShowMap(Landlord plugin) { + this.plugin = plugin; + } + + /** + * Toggles the land map display + * + * @param sender who executed the command + * @param args given with command + * @return boolean + */ + @Override + public boolean execute(CommandSender sender, String[] args, String label) { + + FileConfiguration messages = plugin.getMessageConfig(); + + final String mapDisabled = messages.getString("commands.showMap.alerts.mapDisabled"); + final String notPlayer = messages.getString("info.warnings.playerCommand"); + final String noPerms = messages.getString("info.warnings.noPerms"); + final String noMap = messages.getString("commands.showMap.alerts.noMap"); + + if (!plugin.getConfig().getBoolean("options.enableMap", true)) { //conf + sender.sendMessage(ChatColor.YELLOW + mapDisabled); + return true; + } + if (!(sender instanceof Player)) { + sender.sendMessage(ChatColor.DARK_RED + notPlayer); + } else { + Player player = (Player) sender; + if (!player.hasPermission("landlord.player.map")) { + player.sendMessage(ChatColor.RED + noPerms); + return true; + } + try { + plugin.getMapManager().toggleMap(player); + } catch (Exception e) { + sender.sendMessage(ChatColor.RED + noMap); + } + + } + return true; + } + + @Override + public String getHelpText(CommandSender sender) { + + // only bother showing them this command if they have permission to do it. + if (!sender.hasPermission("landlord.player.map") || !plugin.getConfig().getBoolean("options.enableMap", true)) { + return null; + } + + FileConfiguration messages = plugin.getMessageConfig(); + + final String usage = messages.getString("commands.showMap.usage"); // get the base usage string + final String desc = messages.getString("commands.showMap.description"); // get the description + + // return the constructed and colorized help string + return Utils.helpString(usage, desc, getTriggers()[0].toLowerCase()); + + } + + @Override + public String[] getTriggers() { + final List triggers = plugin.getMessageConfig().getStringList("commands.showMap.triggers"); + return triggers.toArray(new String[triggers.size()]); + } +} diff --git a/src/com/jcdesimp/landlord/commands/Unclaim.java b/src/com/jcdesimp/landlord/commands/Unclaim.java new file mode 100644 index 0000000..48429f8 --- /dev/null +++ b/src/com/jcdesimp/landlord/commands/Unclaim.java @@ -0,0 +1,201 @@ +package com.jcdesimp.landlord.commands; + +import com.jcdesimp.landlord.Landlord; +import com.jcdesimp.landlord.persistantData.OwnedLand; +import org.bukkit.ChatColor; +import org.bukkit.Chunk; +import org.bukkit.Effect; +import org.bukkit.Sound; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; + +import java.util.List; + +import static org.bukkit.Bukkit.getOfflinePlayer; +import static org.bukkit.Bukkit.getWorld; + +/** + * Created by jcdesimp on 2/17/15. + * LandlordCommand object for players to unclaim land + */ +public class Unclaim implements LandlordCommand { + + private Landlord plugin; + + public Unclaim(Landlord plugin) { + this.plugin = plugin; + } + + /** + * Called when landlord unclaim command is executed + * This command must be run by a player + * + * @param sender who executed the command + * @param args given with command + * @return boolean + */ + @Override + public boolean execute(CommandSender sender, String[] args, String label) { + + FileConfiguration messages = plugin.getMessageConfig(); + + final String notPlayer = messages.getString("info.warnings.playerCommand"); + final String noPerms = messages.getString("info.warnings.noPerms"); + final String noClaim = messages.getString("info.warnings.noClaim"); + final String noWorld = messages.getString("commands.unclaim.alerts.noWorld"); + final String usage = messages.getString("commands.unclaim.usage"); + final String notOwner = messages.getString("info.warnings.notOwner"); + final String landSold = messages.getString("commands.unclaim.alerts.landSold"); + final String unclaimOther = messages.getString("commands.unclaim.alerts.unclaimOther"); + final String unclaimed = messages.getString("commands.unclaim.alerts.unclaim"); + + + //is sender a player + if (!(sender instanceof Player)) { + sender.sendMessage(ChatColor.DARK_RED + notPlayer); + } else { + Player player = (Player) sender; + if (!player.hasPermission("landlord.player.own") && !player.hasPermission("landlord.admin.unclaim")) { + player.sendMessage(ChatColor.RED + noPerms); + return true; + } + //sender.sendMessage(ChatColor.GOLD + "Current Location: " + player.getLocation().toString()); + Chunk currChunk = player.getLocation().getChunk(); + + int x = currChunk.getX(); + int z = currChunk.getZ(); + String worldname = currChunk.getWorld().getName(); + + List disabledWorlds = plugin.getConfig().getStringList("disabled-worlds"); //conf + for (String s : disabledWorlds) { + if (s.equalsIgnoreCase(currChunk.getWorld().getName())) { + player.sendMessage(ChatColor.RED + noClaim); + return true; + } + } + + + if (args.length > 1) { + try { + String[] coords = args[1].split(","); + //System.out.println("COORDS: "+coords); + x = Integer.parseInt(coords[0]); + z = Integer.parseInt(coords[1]); + currChunk = currChunk.getWorld().getChunkAt(x, z); + if (args.length > 2) { + + if (plugin.getServer().getWorld(worldname) == null) { + player.sendMessage(ChatColor.RED + noWorld.replace("#{worldName}", "'" + worldname + "'")); + return true; + } + currChunk = getWorld(worldname).getChunkAt(x, z); + + } + } catch (NumberFormatException e) { + //e.printStackTrace(); + player.sendMessage(ChatColor.RED + usage + .replace("#{label}", label) + .replace("#{command}", args[0]) + + ); + return true; + + } catch (ArrayIndexOutOfBoundsException e) { + player.sendMessage(ChatColor.RED + usage + .replace("#{label}", label) + .replace("#{command}", args[0]) + + ); + return true; + } + } + OwnedLand dbLand = OwnedLand.getLandFromDatabase(x, z, worldname); + + + if (dbLand == null || (!dbLand.ownerUUID().equals(player.getUniqueId()) && !player.hasPermission("landlord.admin.unclaim"))) { + player.sendMessage(ChatColor.RED + notOwner); + return true; + } + if (plugin.hasVault()) { + if (plugin.getvHandler().hasEconomy()) { + Double amt = plugin.getConfig().getDouble("economy.sellPrice", 100.0); //conf + if (amt > 0) { + int numFree = plugin.getConfig().getInt("economy.freeLand", 0); + if (numFree > 0 && plugin.getDatabase().find(OwnedLand.class).where().eq("ownerName", player.getUniqueId().toString()).findRowCount() <= numFree) { + //player.sendMessage(ChatColor.YELLOW+"You have been charged " + plugin.getvHandler().formatCash(amt) + " to purchase land."); + } else if (plugin.getvHandler().giveCash(player, amt)) { + player.sendMessage(ChatColor.GREEN + landSold.replace("#{amount}", plugin.getvHandler().formatCash(amt))); + //return true; + } + } + + } + } + if (!player.getUniqueId().equals(dbLand.ownerUUID())) { + player.sendMessage(ChatColor.YELLOW + unclaimOther.replace("#{player}", getOfflinePlayer(dbLand.ownerUUID()).getName())); + } + plugin.getDatabase().delete(dbLand); + dbLand.highlightLand(player, Effect.WITCH_MAGIC); + + sender.sendMessage( + ChatColor.YELLOW + unclaimed + .replace("#{chunkCoords}", + "(" + currChunk.getX() + ", " + currChunk.getZ() + ")" + ) + .replace("#{worldName}", currChunk.getWorld().getName()) + ); + + //Regen land if enabled + if (plugin.getConfig().getBoolean("options.regenOnUnclaim", false)) { + currChunk.getWorld().regenerateChunk(currChunk.getX(), currChunk.getZ()); + } + + if (plugin.getConfig().getBoolean("options.soundEffects", true)) { + player.playSound(player.getLocation(), Sound.ENTITY_ENDERMEN_HURT, 10, .5f); + } + plugin.getMapManager().updateAll(); + + } + return true; + } + + @Override + public String getHelpText(CommandSender sender) { + + FileConfiguration messages = plugin.getMessageConfig(); + + final String usage = messages.getString("commands.unclaim.usage"); // get the base usage string + final String desc = messages.getString("commands.unclaim.description"); // get the description + final String priceWarning = messages.getString("commands.unclaim.alerts.priceWarning"); // get the price warning message + final String regenWarning = messages.getString("commands.unclaim.alerts.regenWarning"); // get the chunk regen warning message + + String helpString = ""; + + helpString += Utils.helpString(usage, desc, getTriggers()[0].toLowerCase()); + + if (plugin.hasVault()) { + if (plugin.getvHandler().hasEconomy() && plugin.getConfig().getDouble("economy.sellPrice", 50.0) > 0) { //conf + helpString += ChatColor.YELLOW + " " + ChatColor.ITALIC + priceWarning + .replace( + "#{pricetag}", // insert the formatted price string + plugin.getvHandler().formatCash(plugin.getConfig().getDouble("economy.sellPrice", 50.0)) //conf + ); + } + } + + // add chunk regen warning if needed + if (plugin.getConfig().getBoolean("options.regenOnUnclaim", false)) { + helpString += ChatColor.RED + " " + ChatColor.ITALIC + regenWarning; + } + + // return the constructed and colorized help string + return helpString; + } + + @Override + public String[] getTriggers() { + final List triggers = plugin.getMessageConfig().getStringList("commands.unclaim.triggers"); + return triggers.toArray(new String[triggers.size()]); + } +} diff --git a/src/com/jcdesimp/landlord/commands/Unfriend.java b/src/com/jcdesimp/landlord/commands/Unfriend.java new file mode 100644 index 0000000..e162973 --- /dev/null +++ b/src/com/jcdesimp/landlord/commands/Unfriend.java @@ -0,0 +1,110 @@ +package com.jcdesimp.landlord.commands; + +import com.jcdesimp.landlord.Landlord; +import com.jcdesimp.landlord.persistantData.Friend; +import com.jcdesimp.landlord.persistantData.OwnedLand; +import org.bukkit.ChatColor; +import org.bukkit.Chunk; +import org.bukkit.Effect; +import org.bukkit.Sound; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; + +import java.util.List; + +import static org.bukkit.Bukkit.getOfflinePlayer; + +/** + * Created by jcdesimp on 2/18/15. + * Removed a friend form an owned chunk + */ +public class Unfriend implements LandlordCommand { + + private Landlord plugin; + + public Unfriend(Landlord plugin) { + this.plugin = plugin; + } + + + /** + * Removes a friend from an owned chunk + * Called when landlord remfriend is executed + * + * @param sender who executed the command + * @param args given with command + * @return boolean + */ + @Override + public boolean execute(CommandSender sender, String[] args, String label) { + + FileConfiguration messages = plugin.getMessageConfig(); + + final String notPlayer = messages.getString("info.warnings.playerCommand"); + final String usage = messages.getString("commands.unfriend.usage"); + final String noPerms = messages.getString("info.warnings.noPerms"); + final String notOwner = messages.getString("info.warnings.notOwner"); + final String notFriend = messages.getString("commands.unfriend.alerts.notFriend"); + final String unfriended = messages.getString("commands.unfriend.alerts.unfriended"); + + if (!(sender instanceof Player)) { + sender.sendMessage(ChatColor.DARK_RED + notPlayer); + } else { + if (args.length < 2) { + sender.sendMessage(ChatColor.RED + usage.replace("#{label}", label).replace("#{command}", args[0])); + return true; + } + Player player = (Player) sender; + if (!player.hasPermission("landlord.player.own")) { + player.sendMessage(ChatColor.RED + noPerms); + return true; + } + + Chunk currChunk = player.getLocation().getChunk(); + /* + * ************************************* + * mark for possible change !!!!!!!!! + * ************************************* + */ + Friend frd = Friend.friendFromOfflinePlayer(getOfflinePlayer(args[1])); + OwnedLand land = OwnedLand.getLandFromDatabase(currChunk.getX(), currChunk.getZ(), currChunk.getWorld().getName()); + if (land == null || (!land.ownerUUID().equals(player.getUniqueId()) && !player.hasPermission("landlord.admin.modifyfriends"))) { + player.sendMessage(ChatColor.RED + notOwner); + return true; + } + if (!land.removeFriend(frd)) { + player.sendMessage(ChatColor.YELLOW + notFriend.replace("#{playerName}", args[1])); + return true; + } + if (plugin.getConfig().getBoolean("options.particleEffects", true)) { //conf + land.highlightLand(player, Effect.VILLAGER_THUNDERCLOUD, 2); + } + plugin.getDatabase().save(land); + if (plugin.getConfig().getBoolean("options.soundEffects", true)) { //conf + player.playSound(player.getLocation(), Sound.ENTITY_ZOMBIE_INFECT, 10, .5f); + } + player.sendMessage(ChatColor.GREEN + unfriended.replace("#{playerName}", args[1])); + + } + return true; + } + + @Override + public String getHelpText(CommandSender sender) { + + FileConfiguration messages = plugin.getMessageConfig(); + + final String usage = messages.getString("commands.unfriend.usage"); // get the base usage string + final String desc = messages.getString("commands.unfriend.description"); // get the description + + // return the constructed and colorized help string + return Utils.helpString(usage, desc, getTriggers()[0].toLowerCase()); + } + + @Override + public String[] getTriggers() { + final List triggers = plugin.getMessageConfig().getStringList("commands.unfriend.triggers"); + return triggers.toArray(new String[triggers.size()]); + } +} diff --git a/src/com/jcdesimp/landlord/commands/UnfriendAll.java b/src/com/jcdesimp/landlord/commands/UnfriendAll.java new file mode 100644 index 0000000..e0fdd0a --- /dev/null +++ b/src/com/jcdesimp/landlord/commands/UnfriendAll.java @@ -0,0 +1,96 @@ +package com.jcdesimp.landlord.commands; + +import com.jcdesimp.landlord.Landlord; +import com.jcdesimp.landlord.persistantData.Friend; +import com.jcdesimp.landlord.persistantData.OwnedLand; +import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; + +import java.util.List; + +import static org.bukkit.Bukkit.getOfflinePlayer; + +/** + * Created by jcdesimp on 2/18/15. + * Command for a user to remove a friend from all land at once. + */ +public class UnfriendAll implements LandlordCommand { + + private Landlord plugin; + + public UnfriendAll(Landlord plugin) { + this.plugin = plugin; + } + + @Override + public boolean execute(CommandSender sender, String[] args, String label) { + + FileConfiguration messages = plugin.getMessageConfig(); + + final String notPlayer = messages.getString("info.warnings.playerCommand"); + final String usage = messages.getString("commands.unfriendAll.usage"); + final String noPerms = messages.getString("info.warnings.noPerms"); + final String unknownPlayer = messages.getString("info.warnings.unknownPlayer"); + final String playerRemoved = messages.getString("commands.unfriendAll.alerts.playerRemoved"); + final String noLand = messages.getString("commands.unfriendAll.alerts.noLand"); + + //is sender a player + if (!(sender instanceof Player)) { + sender.sendMessage(ChatColor.DARK_RED + notPlayer); + } else { + if (args.length < 2) { + sender.sendMessage(ChatColor.RED + usage.replace("#label}", label).replace("#{command}", args[0])); + } + Player player = (Player) sender; + if (!player.hasPermission("landlord.player.own")) { + player.sendMessage(ChatColor.RED + noPerms); + return true; + } + + List pLand = plugin.getDatabase().find(OwnedLand.class).where().eq("ownerName", player.getUniqueId()).findList(); + + OfflinePlayer possible = getOfflinePlayer(args[1]); + if (!possible.hasPlayedBefore() && !possible.isOnline()) { + player.sendMessage(ChatColor.RED + unknownPlayer); + return true; + } + + if (pLand.size() > 0) { + for (OwnedLand l : pLand) { + l.removeFriend(Friend.friendFromOfflinePlayer(getOfflinePlayer(args[1]))); + } + + plugin.getDatabase().save(pLand); + + player.sendMessage(ChatColor.GREEN + playerRemoved.replace("#{playername}", args[1])); + return true; + } else { + player.sendMessage(ChatColor.YELLOW + noLand); + } + + } + return true; + } + + @Override + public String getHelpText(CommandSender sender) { + + FileConfiguration messages = plugin.getMessageConfig(); + + final String usage = messages.getString("commands.unfriendAll.usage"); // get the base usage string + final String desc = messages.getString("commands.unfriendAll.description"); // get the description + + // return the constructed and colorized help string + return Utils.helpString(usage, desc, getTriggers()[0].toLowerCase()); + + } + + @Override + public String[] getTriggers() { + final List triggers = plugin.getMessageConfig().getStringList("commands.unfriendAll.triggers"); + return triggers.toArray(new String[triggers.size()]); + } +} diff --git a/src/com/jcdesimp/landlord/commands/Utils.java b/src/com/jcdesimp/landlord/commands/Utils.java new file mode 100644 index 0000000..551ddf8 --- /dev/null +++ b/src/com/jcdesimp/landlord/commands/Utils.java @@ -0,0 +1,26 @@ +package com.jcdesimp.landlord.commands; + +import org.bukkit.ChatColor; + +/** + * Created by jcdesimp on 2/19/15. + * Static utility functions for landlord commands + */ +public abstract class Utils { + + /** + * Create a formatted and colorized help string for a command + * + * @param usage The usage string with command field and params + * @param desc a brief, one line description of the command + * @param command the string to use for as the command + * @return The fully formatted command help string + */ + public static String helpString(String usage, String desc, String command) { + usage = usage.replace("#{cmd}", command); // replace cmd with the first (main) alias + + // return the constructed and colorized help string + return ChatColor.DARK_AQUA + usage + ChatColor.RESET + " - " + desc; + } + +} diff --git a/src/com/jcdesimp/landlord/configuration/ConfigManager.java b/src/com/jcdesimp/landlord/configuration/ConfigManager.java deleted file mode 100644 index 026d555..0000000 --- a/src/com/jcdesimp/landlord/configuration/ConfigManager.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.jcdesimp.landlord.configuration; - -/** - * File created by jcdesimp on 4/8/14. - */ -public class ConfigManager { - //To be implemented -} diff --git a/src/com/jcdesimp/landlord/configuration/CustomConfig.java b/src/com/jcdesimp/landlord/configuration/CustomConfig.java index 66fbc79..face057 100644 --- a/src/com/jcdesimp/landlord/configuration/CustomConfig.java +++ b/src/com/jcdesimp/landlord/configuration/CustomConfig.java @@ -1,8 +1,108 @@ package com.jcdesimp.landlord.configuration; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.java.JavaPlugin; + +import java.io.*; +import java.util.Map; +import java.util.logging.Level; + /** * File created by jcdesimp on 4/8/14. */ public class CustomConfig { - //To be implemented + + private JavaPlugin plugin; + + private String resourceLocation; + private String destination; + + private FileConfiguration customConfig = null; + private File customConfigFile = null; + + public CustomConfig(JavaPlugin plugin, String resourceLocation, String destination) { + this.plugin = plugin; + this.resourceLocation = resourceLocation; + this.destination = destination; + + Map oldConfig = get().getValues(true); + + //this.reload(); + //this.save(); + this.saveDefault(); + + // checks for missing entries and applies new ones + for (Map.Entry entry : customConfig.getDefaults().getValues(true).entrySet()) { + if (oldConfig.containsKey(entry.getKey())) { + customConfig.set(entry.getKey(), oldConfig.get(entry.getKey())); + } else { + customConfig.set(entry.getKey(), entry.getValue()); + } + + } + + save(); + } + + public void reload() { + if (customConfigFile == null) { + customConfigFile = new File(plugin.getDataFolder(), destination); + } + customConfig = YamlConfiguration.loadConfiguration(customConfigFile); + + // Look for defaults in the jar + Reader defConfigStream = null; + try { + InputStream resource = plugin.getResource(resourceLocation); + if (resource == null) { + plugin.getLogger().severe("Internal resource missing at " + resourceLocation + "!"); + return; + } + defConfigStream = new InputStreamReader(resource, "UTF8"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + plugin.getLogger().severe("Error reading internal resource at " + resourceLocation + "!"); + } + if (defConfigStream != null) { + YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream); + //todo + /*try { + defConfig.save(new File(plugin.getDataFolder(), destination)); + } catch (IOException e) { + e.printStackTrace(); + }*/ + customConfig.setDefaults(defConfig); + } + } + + + public FileConfiguration get() { + if (customConfig == null) { + reload(); + } + + return customConfig; + } + + + public void save() { + if (customConfig == null || customConfigFile == null) { + return; + } + try { + get().save(customConfigFile); + } catch (IOException ex) { + plugin.getLogger().log(Level.SEVERE, "Could not save config to " + customConfigFile, ex); + } + } + + public void saveDefault() { + if (customConfigFile == null) { + customConfigFile = new File(plugin.getDataFolder(), destination); + } + if (!customConfigFile.exists()) { + plugin.saveResource(resourceLocation, false); + } + } } diff --git a/src/com/jcdesimp/landlord/landFlags/Build.java b/src/com/jcdesimp/landlord/landFlags/Build.java index d894f9b..0093e66 100644 --- a/src/com/jcdesimp/landlord/landFlags/Build.java +++ b/src/com/jcdesimp/landlord/landFlags/Build.java @@ -1,8 +1,10 @@ package com.jcdesimp.landlord.landFlags; +import com.jcdesimp.landlord.Landlord; import com.jcdesimp.landlord.landManagement.Landflag; import com.jcdesimp.landlord.persistantData.OwnedLand; -import org.bukkit.*; +import org.bukkit.ChatColor; +import org.bukkit.Material; import org.bukkit.entity.*; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; @@ -37,18 +39,15 @@ public class Build extends Landflag { /** * Constructor needs to be defined and properly call super() */ - public Build() { - super( - "Build", //Display name (will be displayed to players) - "Gives permission to place|" + - "and break blocks and edit|" + - "things like item frames and|" + //Description (Lore of headerItem '|' will seperate lines of lore.) - "note blocks.", - new ItemStack(Material.COBBLESTONE), //Itemstack (represented in and manager) - "Allowed Build", //Text shown in manager for granted permission - "can build.", //Description in manager for granted permission (ex: Friendly players ) - "Denied Build", //Text shown in manager for denied permission - "cannot build." //Desciption in manager for denied permission (ex: Regular players ) + public Build(Landlord plugin) { + super(plugin, + plugin.getMessageConfig().getString("flags.build.displayName"), //Display name (will be displayed to players) + plugin.getMessageConfig().getString("flags.build.description"), + new ItemStack(Material.COBBLESTONE), //Itemstack (represented in manager) + plugin.getMessageConfig().getString("flags.build.allowedTitle"), //Text shown in manager for granted permission + plugin.getMessageConfig().getString("flags.build.allowedText"), //Description in manager for granted permission (ex: Friendly players ) + plugin.getMessageConfig().getString("flags.build.deniedTitle"), //Text shown in manager for denied permission + plugin.getMessageConfig().getString("flags.build.deniedText") //Desciption in manager for denied permission (ex: Regular players ) ); } @@ -65,10 +64,11 @@ public Build() { /** * Event handler for block placements + * * @param event that happened */ @EventHandler(priority = EventPriority.HIGH) - public void blockPlace(BlockPlaceEvent event){ + public void blockPlace(BlockPlaceEvent event) { /* ******************************* @@ -78,7 +78,7 @@ public void blockPlace(BlockPlaceEvent event){ ******************************* */ OwnedLand land = OwnedLand.getApplicableLand(event.getBlock().getLocation()); - if(land == null){ + if (land == null) { return; } @@ -93,8 +93,8 @@ public void blockPlace(BlockPlaceEvent event){ * have to cancel the event. ************************************* */ - if(!land.hasPermTo(p, this)){ - p.sendMessage(ChatColor.RED + "You are not allowed to build on this land."); + if (!land.hasPermTo(p, this)) { + p.sendMessage(ChatColor.RED + getPlugin().getMessageConfig().getString("event.build.blockPlace")); event.setCancelled(true); } @@ -108,60 +108,60 @@ public void blockPlace(BlockPlaceEvent event){ ************************************* */ @EventHandler(priority = EventPriority.HIGH) - public void blockBreak(BlockBreakEvent event){ + public void blockBreak(BlockBreakEvent event) { OwnedLand land = OwnedLand.getApplicableLand(event.getBlock().getLocation()); - if(land == null){ + if (land == null) { return; } Player p = event.getPlayer(); - if(!land.hasPermTo(p, this)){ - p.sendMessage(ChatColor.RED + "You are not allowed to break on this land."); + if (!land.hasPermTo(p, this)) { + p.sendMessage(ChatColor.RED + getPlugin().getMessageConfig().getString("event.build.blockBreak")); event.setCancelled(true); } } @EventHandler(priority = EventPriority.HIGH) - public void liquidEmpty(PlayerBucketEmptyEvent event){ + public void liquidEmpty(PlayerBucketEmptyEvent event) { OwnedLand land = OwnedLand.getApplicableLand(event.getBlockClicked().getLocation()); - if(land == null){ + if (land == null) { return; } - Player p=event.getPlayer(); + Player p = event.getPlayer(); - if(!land.hasPermTo(p, this)){ - p.sendMessage(ChatColor.RED+"You cannot place that on this land."); + if (!land.hasPermTo(p, this)) { + p.sendMessage(ChatColor.RED + getPlugin().getMessageConfig().getString("event.build.bucketEmpty")); event.setCancelled(true); } } @EventHandler(priority = EventPriority.HIGH) - public void liquidFill(PlayerBucketFillEvent event){ + public void liquidFill(PlayerBucketFillEvent event) { OwnedLand land = OwnedLand.getApplicableLand(event.getBlockClicked().getLocation()); - if(land == null){ + if (land == null) { return; } - Player p=event.getPlayer(); + Player p = event.getPlayer(); - if(!land.hasPermTo(p, this)){ - p.sendMessage(ChatColor.RED+"You cannot do that on this land."); + if (!land.hasPermTo(p, this)) { + p.sendMessage(ChatColor.RED + getPlugin().getMessageConfig().getString("event.build.bucketFill")); event.setCancelled(true); } } @EventHandler(priority = EventPriority.HIGH) - public void paintingFrameBreak(HangingBreakByEntityEvent event){ + public void paintingFrameBreak(HangingBreakByEntityEvent event) { org.bukkit.entity.Entity victim = event.getEntity(); org.bukkit.entity.Entity remover = event.getRemover(); - OwnedLand land = OwnedLand.getApplicableLand(victim.getLocation()); - if(land == null){ + OwnedLand land = OwnedLand.getApplicableLand(victim.getLocation()); + if (land == null) { return; } - if(remover.getType().toString().equals("PLAYER")){ - Player p = (Player)remover; - if(!land.hasPermTo(p, this)){ - p.sendMessage(ChatColor.RED+"You cannot break that on this land."); + if (remover.getType().toString().equals("PLAYER")) { + Player p = (Player) remover; + if (!land.hasPermTo(p, this)) { + p.sendMessage(ChatColor.RED + getPlugin().getMessageConfig().getString("event.build.hangingBreak")); event.setCancelled(true); } //System.out.println("Attacker Name:" + p.getName()); @@ -178,12 +178,12 @@ public void interactWithArmorStand(PlayerInteractAtEntityEvent event) { } OwnedLand land = OwnedLand.getApplicableLand(event.getRightClicked().getLocation()); - if(land == null){ + if (land == null) { return; } if (!land.hasPermTo(event.getPlayer(), this)) { - event.getPlayer().sendMessage(ChatColor.RED + "You cannot do that here!"); + event.getPlayer().sendMessage(ChatColor.RED + getPlugin().getMessageConfig().getString("event.build.useArmorStand")); event.setCancelled(true); } @@ -195,36 +195,36 @@ public void interactWithArmorStand(PlayerInteractAtEntityEvent event) { public void destroyArmorStand(EntityDamageByEntityEvent event) { Entity victim = event.getEntity(); //System.out.println("Victim: "+victim); - if(!victim.getType().equals(EntityType.ARMOR_STAND)) { - return; + if (!victim.getType().equals(EntityType.ARMOR_STAND)) { + return; } OwnedLand land = OwnedLand.getApplicableLand(victim.getLocation()); - if(land == null){ + if (land == null) { return; } if (event.getDamager().getType().equals(EntityType.PLAYER)) { - Player attacker = (Player)event.getDamager(); + Player attacker = (Player) event.getDamager(); //System.out.println(attacker.getName()); - if(!land.hasPermTo(attacker ,this)){ - attacker.sendMessage(ChatColor.RED+"You cannot do that on this land."); + if (!land.hasPermTo(attacker, this)) { + attacker.sendMessage(ChatColor.RED + getPlugin().getMessageConfig().getString("event.build.breakArmorStandWithMelee")); event.setCancelled(true); } } - if (event.getDamager().getType().equals(EntityType.ARROW)) { - Arrow projectile = (Arrow)event.getDamager(); - if(projectile.getShooter() instanceof Player) { - Player attacker = (Player)projectile.getShooter(); - if(!land.hasPermTo(attacker ,this)){ - attacker.sendMessage(ChatColor.RED+"You cannot do that on this land."); - event.setCancelled(true); - } - } + if (event.getDamager().getType().equals(EntityType.ARROW)) { + Arrow projectile = (Arrow) event.getDamager(); + if (projectile.getShooter() instanceof Player) { + Player attacker = (Player) projectile.getShooter(); + if (!land.hasPermTo(attacker, this)) { + attacker.sendMessage(ChatColor.RED + getPlugin().getMessageConfig().getString("event.build.breakArmorStandWithArrow")); + event.setCancelled(true); + } + } - } + } //System.out.println(event.getDamager().getType()); } @@ -235,42 +235,40 @@ public void removeItemFromFrame(EntityDamageByEntityEvent event) { Entity victim = event.getEntity(); - if (!victim.getType().equals(EntityType.ITEM_FRAME)){ + if (!victim.getType().equals(EntityType.ITEM_FRAME)) { return; } Player p; Entity attacker = event.getDamager(); //System.out.println("Attacker: "+attacker.getType().toString()); - if(attacker.getType().toString().equals("PLAYER")) { + if (attacker.getType().toString().equals("PLAYER")) { p = (Player) attacker; OwnedLand land = OwnedLand.getApplicableLand(victim.getLocation()); - if(land == null){ + if (land == null) { return; } - if(!land.hasPermTo(p ,this)){ - p.sendMessage(ChatColor.RED+"You cannot break that on this land."); + if (!land.hasPermTo(p, this)) { + p.sendMessage(ChatColor.RED + getPlugin().getMessageConfig().getString("event.build.itemFrameRemoveWithMelee")); event.setCancelled(true); } - } else if (attacker.getType().toString().equals("ARROW")){ - Arrow a = (Arrow)attacker; - if(a.getShooter() instanceof Player){ - p = (Player)a.getShooter(); + } else if (attacker.getType().toString().equals("ARROW")) { + Arrow a = (Arrow) attacker; + if (a.getShooter() instanceof Player) { + p = (Player) a.getShooter(); } else { return; } OwnedLand land = OwnedLand.getApplicableLand(victim.getLocation()); - if(land == null){ + if (land == null) { return; } - if(!land.hasPermTo(p ,this)){ - p.sendMessage(ChatColor.RED+"You cannot break that on this land."); + if (!land.hasPermTo(p, this)) { + p.sendMessage(ChatColor.RED + getPlugin().getMessageConfig().getString("event.build.itemFrameRemoveWithArrow")); event.setCancelled(true); } - } else { - return; } @@ -280,54 +278,56 @@ public void removeItemFromFrame(EntityDamageByEntityEvent event) { public void removeItemFromFrame(PlayerInteractEntityEvent event) { Entity entity = event.getRightClicked(); Player p = event.getPlayer(); - if (!entity.getType().equals(EntityType.ITEM_FRAME)) { return; } + if (!entity.getType().equals(EntityType.ITEM_FRAME)) { + return; + } ItemFrame iFrame = (ItemFrame) entity; if (iFrame.getItem() != null && !iFrame.getItem().getType().equals(Material.AIR)) return; OwnedLand land = OwnedLand.getApplicableLand(entity.getLocation()); - if(land == null){ + if (land == null) { return; } - if(!land.hasPermTo(p ,this)){ - p.sendMessage(ChatColor.RED+"You cannot break that on this land."); + if (!land.hasPermTo(p, this)) { + p.sendMessage(ChatColor.RED + getPlugin().getMessageConfig().getString("event.build.itemFrameRemoveDirectly")); event.setCancelled(true); } } @EventHandler(priority = EventPriority.HIGH) - public void rotateItemInFrame(PlayerInteractEntityEvent event){ + public void rotateItemInFrame(PlayerInteractEntityEvent event) { Entity entity = event.getRightClicked(); Player p = event.getPlayer(); if (!entity.getType().equals(EntityType.ITEM_FRAME)) { return; } - ItemFrame iFrame = (ItemFrame)entity; + ItemFrame iFrame = (ItemFrame) entity; if ((iFrame.getItem().equals(null)) || (iFrame.getItem().getType().equals(Material.AIR))) { return; } OwnedLand land = OwnedLand.getApplicableLand(entity.getLocation()); - if(land == null){ + if (land == null) { return; } - if(!land.hasPermTo(p ,this)){ - p.sendMessage(ChatColor.RED+"You cannot do that on this land."); + if (!land.hasPermTo(p, this)) { + p.sendMessage(ChatColor.RED + getPlugin().getMessageConfig().getString("event.build.itemFrameRotate")); event.setCancelled(true); } } @EventHandler(priority = EventPriority.HIGH) - public void paintingFramePlace(HangingPlaceEvent event){ + public void paintingFramePlace(HangingPlaceEvent event) { org.bukkit.entity.Entity placer = event.getPlayer(); OwnedLand land = OwnedLand.getApplicableLand(event.getBlock().getLocation()); - if(land == null){ + if (land == null) { return; } - if(placer.getType().toString().equals("PLAYER")){ - Player p = (Player)placer; - if(!land.hasPermTo(p, this)){ - p.sendMessage(ChatColor.RED+"You cannot place that on this land."); + if (placer.getType().toString().equals("PLAYER")) { + Player p = (Player) placer; + if (!land.hasPermTo(p, this)) { + p.sendMessage(ChatColor.RED + getPlugin().getMessageConfig().getString("event.build.paintingPlace")); event.setCancelled(true); } @@ -338,7 +338,7 @@ public void paintingFramePlace(HangingPlaceEvent event){ @EventHandler(priority = EventPriority.HIGH) public void CropTrampleOrFireCharge(PlayerInteractEvent event) { - if(event.getClickedBlock()==null){ + if (event.getClickedBlock() == null) { return; } @@ -346,61 +346,58 @@ public void CropTrampleOrFireCharge(PlayerInteractEvent event) { Player p = event.getPlayer(); //trampling crops - if (p!=null && event.getAction().equals(Action.PHYSICAL) && event.getClickedBlock().getType().toString().equals("SOIL")) { + if (p != null && event.getAction().equals(Action.PHYSICAL) && event.getClickedBlock().getType().toString().equals("SOIL")) { OwnedLand land = OwnedLand.getApplicableLand(event.getClickedBlock().getLocation()); if (land == null) { return; } - if(land.hasPermTo(p, this)){ + if (land.hasPermTo(p, this)) { return; } - p.sendMessage(ChatColor.RED + "You are not allowed to destroy crops on this land."); + p.sendMessage(ChatColor.RED + getPlugin().getMessageConfig().getString("event.build.cropDestroy")); event.setCancelled(true); return; } //Using fire charge ItemStack item = event.getItem(); - if (p!=null && item!=null && event.getAction().equals(Action.RIGHT_CLICK_BLOCK) && event.getItem().getType().equals(Material.FIREBALL)) { + if (p != null && item != null && event.getAction().equals(Action.RIGHT_CLICK_BLOCK) && event.getItem().getType().equals(Material.FIREBALL)) { OwnedLand land = OwnedLand.getApplicableLand(event.getClickedBlock().getLocation()); if (land == null) { return; } - if(land.hasPermTo(p, this)){ + if (land.hasPermTo(p, this)) { return; } - p.sendMessage(ChatColor.RED + "You cannot do that on this land."); + p.sendMessage(ChatColor.RED + getPlugin().getMessageConfig().getString("event.build.useFireCharge")); event.setCancelled(true); } } @EventHandler(priority = EventPriority.HIGH) - public void protectBlockStates(PlayerInteractEvent event){ + public void protectBlockStates(PlayerInteractEvent event) { Material[] blockedItems = {Material.NOTE_BLOCK, Material.REDSTONE_COMPARATOR_OFF, Material.REDSTONE_COMPARATOR_ON, - Material.DIODE_BLOCK_OFF, Material.DIODE_BLOCK_ON, Material.FLOWER_POT, Material.CAKE_BLOCK}; - if(event.getClickedBlock()==null){ + Material.DIODE_BLOCK_OFF, Material.DIODE_BLOCK_ON, Material.FLOWER_POT, Material.CAKE_BLOCK, Material.DAYLIGHT_DETECTOR +, Material.DAYLIGHT_DETECTOR_INVERTED}; + if (event.getClickedBlock() == null) { return; } Player p = event.getPlayer(); //System.out.println(event.getClickedBlock().getType()); - if(event.getAction().equals(Action.RIGHT_CLICK_BLOCK) && - Arrays.asList(blockedItems).contains(event.getClickedBlock().getType())){ + if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK) && + Arrays.asList(blockedItems).contains(event.getClickedBlock().getType())) { OwnedLand land = OwnedLand.getApplicableLand(event.getClickedBlock().getLocation()); if (land == null) { return; } - if(land.hasPermTo(p,this)){ + if (land.hasPermTo(p, this)) { return; } - p.sendMessage(ChatColor.RED+"You cannot do that on this land."); + p.sendMessage(ChatColor.RED + getPlugin().getMessageConfig().getString("event.build.blockStateChange")); event.setCancelled(true); } } - - - - } diff --git a/src/com/jcdesimp/landlord/landFlags/HarmAnimals.java b/src/com/jcdesimp/landlord/landFlags/HarmAnimals.java index 30f5b76..2de1c44 100644 --- a/src/com/jcdesimp/landlord/landFlags/HarmAnimals.java +++ b/src/com/jcdesimp/landlord/landFlags/HarmAnimals.java @@ -1,11 +1,11 @@ package com.jcdesimp.landlord.landFlags; +import com.jcdesimp.landlord.Landlord; import com.jcdesimp.landlord.landManagement.Landflag; import com.jcdesimp.landlord.persistantData.OwnedLand; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.entity.EntityType; -import org.bukkit.entity.Ocelot; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.event.EventHandler; @@ -13,7 +13,6 @@ import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.inventory.ItemStack; -import javax.swing.text.html.parser.Entity; import java.util.Arrays; /** @@ -36,17 +35,15 @@ public class HarmAnimals extends Landflag { /* * Constructor needs to be defined and properly call super() */ - public HarmAnimals() { - super( - "Harm Animals", //Display name (will be displayed to players) - "Gives permission to hurt or kill|" + - "pigs, sheep, cows, mooshrooms,|" + //Description (Lore of headerItem '|' will seperate lines of lore.) - "chickens, horses, dogs, and cats.", - new ItemStack(Material.LEATHER), //Itemstack (represented in land manager) - "Allowed Animal Damage", //Text shown in manager for granted permission - "can harm animals.", //Description in manager for granted permission (ex: Friendly players ) - "Denied Animal Damage", //Text shown in manager for denied permission - "cannot harm animals." //Desciption in manager for denied permission (ex: Regular players ) + public HarmAnimals(Landlord plugin) { + super(plugin, + plugin.getMessageConfig().getString("flags.harmAnimals.displayName"), //Display name (will be displayed to players) + plugin.getMessageConfig().getString("flags.harmAnimals.description"), + new ItemStack(Material.LEATHER), //Itemstack (represented in manager) + plugin.getMessageConfig().getString("flags.harmAnimals.allowedTitle"), //Text shown in manager for granted permission + plugin.getMessageConfig().getString("flags.harmAnimals.allowedText"), //Description in manager for granted permission (ex: Friendly players ) + plugin.getMessageConfig().getString("flags.harmAnimals.deniedTitle"), //Text shown in manager for denied permission + plugin.getMessageConfig().getString("flags.harmAnimals.deniedText") //Desciption in manager for denied permission (ex: Regular players ) ); } @@ -63,6 +60,7 @@ public HarmAnimals() { /** * Event handler for block placements + * * @param event that happened */ @@ -74,47 +72,46 @@ public HarmAnimals() { * your flag to do it's job ************************************* */ - @EventHandler(priority = EventPriority.HIGH) - public void animalDamage(EntityDamageByEntityEvent event){ - //String[] ssafeAnimals = {"OCELOT","WOLF","HORSE","COW","PIG","MUSHROOM_COW","SHEEP","CHICKEN"}; + public void animalDamage(EntityDamageByEntityEvent event) { + //String[] safeAnimals = {"OCELOT","WOLF","HORSE","COW","PIG","MUSHROOM_COW","SHEEP","CHICKEN"}; EntityType[] safeAnimals = {EntityType.OCELOT, EntityType.WOLF, EntityType.HORSE, EntityType.COW, EntityType.PIG, - EntityType.MUSHROOM_COW, EntityType.SHEEP, EntityType.CHICKEN, EntityType.RABBIT}; + EntityType.MUSHROOM_COW, EntityType.SHEEP, EntityType.CHICKEN, EntityType.RABBIT}; org.bukkit.entity.Entity victim = event.getEntity(); - if(!Arrays.asList(safeAnimals).contains(victim.getType())){ + if (!Arrays.asList(safeAnimals).contains(victim.getType())) { return; } org.bukkit.entity.Entity attacker = event.getDamager(); - if(attacker.getType().toString().equals("PLAYER")){ - Player p = (Player)attacker; + if (attacker.getType().toString().equals("PLAYER")) { + Player p = (Player) attacker; OwnedLand land = OwnedLand.getApplicableLand(victim.getLocation()); - if(land==null){ + if (land == null) { return; } - if(!land.hasPermTo(p, this)){ + if (!land.hasPermTo(p, this)) { - p.sendMessage(ChatColor.RED+"You cannot harm animals on this land."); + p.sendMessage(ChatColor.RED + getPlugin().getMessageConfig().getString("event.harmAnimals.melee")); event.setCancelled(true); } - } else if(attacker.getType().toString().equalsIgnoreCase("Arrow") || attacker.getType().toString().equalsIgnoreCase("SPLASH_POTION")){ - Projectile a = (Projectile)attacker; + } else if (attacker.getType().toString().equalsIgnoreCase("Arrow") || attacker.getType().toString().equalsIgnoreCase("SPLASH_POTION")) { + Projectile a = (Projectile) attacker; Player p; - if(a.getShooter() instanceof Player){ + if (a.getShooter() instanceof Player) { OwnedLand land = OwnedLand.getApplicableLand(victim.getLocation()); - p = (Player)a.getShooter(); - if(land==null){ + p = (Player) a.getShooter(); + if (land == null) { return; } //System.out.println(a.getType()); - if(!land.hasPermTo(p, this)){ - if(a.getType().toString().equals("ARROW")) { - p.sendMessage(ChatColor.RED + "You cannot harm animals on this land."); + if (!land.hasPermTo(p, this)) { + if (a.getType().toString().equals("ARROW")) { + p.sendMessage(ChatColor.RED + getPlugin().getMessageConfig().getString("event.harmAnimals.projectile")); } a.remove(); event.setCancelled(true); @@ -126,7 +123,4 @@ public void animalDamage(EntityDamageByEntityEvent event){ } - - - } diff --git a/src/com/jcdesimp/landlord/landFlags/OpenDoor.java b/src/com/jcdesimp/landlord/landFlags/OpenDoor.java index c7e929b..5c20de7 100644 --- a/src/com/jcdesimp/landlord/landFlags/OpenDoor.java +++ b/src/com/jcdesimp/landlord/landFlags/OpenDoor.java @@ -1,5 +1,6 @@ package com.jcdesimp.landlord.landFlags; +import com.jcdesimp.landlord.Landlord; import com.jcdesimp.landlord.landManagement.Landflag; import com.jcdesimp.landlord.persistantData.OwnedLand; import org.bukkit.ChatColor; @@ -28,15 +29,15 @@ public class OpenDoor extends Landflag { /** * Constructor needs to be defined and properly call super() */ - public OpenDoor() { - super( - "Open Doors", //Display name (will be displayed to players) - "Gives permission to open/close doors.", //Description (Lore of headerItem '|' will seperate lines of lore.) - new ItemStack(Material.WOOD_DOOR), //Itemstack (represented in and manager) - "Allowed to Open Doors", //Text shown in manager for granted permission - "can open doors.", //Description in manager for granted permission (ex: Friendly players ) - "Not Allowed to Open Doors", //Text shown in manager for denied permission - "cannot open doors." //Desciption in manager for denied permission (ex: Regular players ) + public OpenDoor(Landlord plugin) { + super(plugin, + plugin.getMessageConfig().getString("flags.openDoor.displayName"), //Display name (will be displayed to players) + plugin.getMessageConfig().getString("flags.openDoor.description"), + new ItemStack(Material.WOOD_DOOR), //Itemstack (represented in manager) + plugin.getMessageConfig().getString("flags.openDoor.allowedTitle"), //Text shown in manager for granted permission + plugin.getMessageConfig().getString("flags.openDoor.allowedText"), //Description in manager for granted permission (ex: Friendly players ) + plugin.getMessageConfig().getString("flags.openDoor.deniedTitle"), //Text shown in manager for denied permission + plugin.getMessageConfig().getString("flags.openDoor.deniedText") //Desciption in manager for denied permission (ex: Regular players ) ); } @@ -53,6 +54,7 @@ public OpenDoor() { /** * Event handler for block placements + * * @param event that happened */ @@ -64,10 +66,8 @@ public OpenDoor() { * your flag to do it's job ************************************* */ - - @EventHandler(priority = EventPriority.HIGH) - public void protectBlockStates(PlayerInteractEvent event){ + public void protectBlockStates(PlayerInteractEvent event) { Material[] blockedItems = {Material.WOOD_DOOR, Material.TRAP_DOOR, Material.WOODEN_DOOR, Material.FENCE_GATE, Material.ACACIA_DOOR, Material.ACACIA_FENCE_GATE, Material.DARK_OAK_DOOR, Material.DARK_OAK_FENCE_GATE, @@ -75,21 +75,21 @@ public void protectBlockStates(PlayerInteractEvent event){ Material.JUNGLE_DOOR, Material.JUNGLE_FENCE_GATE, Material.SPRUCE_DOOR, Material.SPRUCE_FENCE_GATE,}; - if(event.getClickedBlock()==null){ + if (event.getClickedBlock() == null) { return; } Player p = event.getPlayer(); - if(event.getAction().equals(Action.RIGHT_CLICK_BLOCK) && - Arrays.asList(blockedItems).contains(event.getClickedBlock().getType())){ + if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK) && + Arrays.asList(blockedItems).contains(event.getClickedBlock().getType())) { OwnedLand land = OwnedLand.getApplicableLand(event.getClickedBlock().getLocation()); if (land == null) { return; } - if(land.hasPermTo(p,this)){ + if (land.hasPermTo(p, this)) { return; } - p.sendMessage(ChatColor.RED+"You cannot open doors on this land."); + p.sendMessage(ChatColor.RED + getPlugin().getMessageConfig().getString("event.openDoor.interact")); event.setCancelled(true); } diff --git a/src/com/jcdesimp/landlord/landFlags/PVP.java b/src/com/jcdesimp/landlord/landFlags/PVP.java index e9c0517..92a8818 100644 --- a/src/com/jcdesimp/landlord/landFlags/PVP.java +++ b/src/com/jcdesimp/landlord/landFlags/PVP.java @@ -1,5 +1,6 @@ package com.jcdesimp.landlord.landFlags; +import com.jcdesimp.landlord.Landlord; import com.jcdesimp.landlord.landManagement.Landflag; import com.jcdesimp.landlord.persistantData.OwnedLand; import org.bukkit.ChatColor; @@ -11,8 +12,6 @@ import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.inventory.ItemStack; -import java.util.Arrays; - /** * File created by jcdesimp on 5/24/14. */ @@ -24,58 +23,57 @@ */ public class PVP extends Landflag { - public PVP() { - super( - "PVP", //Display name (will be displayed to players) - "Gives permission to attack|" + - "players on this land|" , - new ItemStack(Material.IRON_SWORD), //Itemstack (represented in and manager) - "Allowed PvP", //Text shown in manager for granted permission - "can hurt other players.", //Description in manager for granted permission (ex: Friendly players ) - "Denied PvP", //Text shown in manager for denied permission - "cannot hurt other players." //Desciption in manager for denied permission (ex: Regular players ) + public PVP(Landlord plugin) { + super(plugin, + plugin.getMessageConfig().getString("flags.pvp.displayName"), //Display name (will be displayed to players) + plugin.getMessageConfig().getString("flags.pvp.description"), + new ItemStack(Material.IRON_SWORD), //Itemstack (represented in manager) + plugin.getMessageConfig().getString("flags.pvp.allowedTitle"), //Text shown in manager for granted permission + plugin.getMessageConfig().getString("flags.pvp.allowedText"), //Description in manager for granted permission (ex: Friendly players ) + plugin.getMessageConfig().getString("flags.pvp.deniedTitle"), //Text shown in manager for denied permission + plugin.getMessageConfig().getString("flags.pvp.deniedText") //Desciption in manager for denied permission (ex: Regular players ) ); } @EventHandler(priority = EventPriority.HIGH) - public void playerDamage(EntityDamageByEntityEvent event){ + public void playerDamage(EntityDamageByEntityEvent event) { //String[] safeAnimals = {"OCELOT","WOLF","HORSE","COW","PIG","MUSHROOM_COW","SHEEP","CHICKEN"}; org.bukkit.entity.Entity victim = event.getEntity(); - if(!(victim instanceof Player)){ + if (!(victim instanceof Player)) { return; } org.bukkit.entity.Entity attacker = event.getDamager(); - if(attacker.getType().toString().equals("PLAYER")){ - Player p = (Player)attacker; + if (attacker.getType().toString().equals("PLAYER")) { + Player p = (Player) attacker; OwnedLand land = OwnedLand.getApplicableLand(victim.getLocation()); - if(land==null){ + if (land == null) { return; } - if(!land.hasPermTo(p, this)){ + if (!land.hasPermTo(p, this)) { - p.sendMessage(ChatColor.RED+"You cannot harm other players on this land."); + p.sendMessage(ChatColor.RED + getPlugin().getMessageConfig().getString("event.pvp.melee")); event.setCancelled(true); } - } else if(attacker.getType().toString().equalsIgnoreCase("Arrow") || attacker.getType().toString().equalsIgnoreCase("SPLASH_POTION")){ - Projectile a = (Projectile)attacker; + } else if (attacker.getType().toString().equalsIgnoreCase("Arrow") || attacker.getType().toString().equalsIgnoreCase("SPLASH_POTION")) { + Projectile a = (Projectile) attacker; Player p; - if(a.getShooter() instanceof Player){ + if (a.getShooter() instanceof Player) { OwnedLand land = OwnedLand.getApplicableLand(victim.getLocation()); - p = (Player)a.getShooter(); - if(land==null){ + p = (Player) a.getShooter(); + if (land == null) { return; } //System.out.println(a.getType()); - if(!land.hasPermTo(p, this)){ - if(a.getType().toString().equals("ARROW")) { - p.sendMessage(ChatColor.RED + "You cannot harm other players on this land."); + if (!land.hasPermTo(p, this)) { + if (a.getType().toString().equals("ARROW")) { + p.sendMessage(ChatColor.RED + getPlugin().getMessageConfig().getString("event.pvp.projectile")); } a.remove(); event.setCancelled(true); @@ -86,6 +84,4 @@ public void playerDamage(EntityDamageByEntityEvent event){ } } - - } diff --git a/src/com/jcdesimp/landlord/landFlags/TntDamage.java b/src/com/jcdesimp/landlord/landFlags/TntDamage.java index 09418b3..36f054f 100644 --- a/src/com/jcdesimp/landlord/landFlags/TntDamage.java +++ b/src/com/jcdesimp/landlord/landFlags/TntDamage.java @@ -1,5 +1,6 @@ package com.jcdesimp.landlord.landFlags; +import com.jcdesimp.landlord.Landlord; import com.jcdesimp.landlord.landManagement.Landflag; import com.jcdesimp.landlord.persistantData.OwnedLand; import org.bukkit.ChatColor; @@ -15,7 +16,6 @@ import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; -import java.util.Arrays; import java.util.Iterator; import java.util.List; @@ -34,16 +34,15 @@ public class TntDamage extends Landflag { /** * Constructor needs to be defined and properly call super() */ - public TntDamage() { - super( - "TNT Damage", //Display name (will be displayed to players) - "Gives permission to cause block|" + - "damage with tnt.", //Description (Lore of headerItem '|' will seperate lines of lore.) - new ItemStack(Material.TNT), //Itemstack (represented in and manager) - "Allowed TNT Damage", //Text shown in manager for granted permission - "can damage with TNT.", //Description in manager for granted permission (ex: Friendly players ) - "Denied TNT Damage", //Text shown in manager for denied permission - "cannot damage with TNT." //Desciption in manager for denied permission (ex: Regular players ) + public TntDamage(Landlord plugin) { + super(plugin, + plugin.getMessageConfig().getString("flags.tntDamage.displayName"), //Display name (will be displayed to players) + plugin.getMessageConfig().getString("flags.tntDamage.description"), + new ItemStack(Material.TNT), //Itemstack (represented in manager) + plugin.getMessageConfig().getString("flags.tntDamage.allowedTitle"), //Text shown in manager for granted permission + plugin.getMessageConfig().getString("flags.tntDamage.allowedText"), //Description in manager for granted permission (ex: Friendly players ) + plugin.getMessageConfig().getString("flags.tntDamage.deniedTitle"), //Text shown in manager for denied permission + plugin.getMessageConfig().getString("flags.tntDamage.deniedText") //Desciption in manager for denied permission (ex: Regular players ) ); } @@ -60,6 +59,7 @@ public TntDamage() { /** * Event handler for block placements + * * @param event that happened */ @@ -72,26 +72,26 @@ public TntDamage() { ************************************* */ @EventHandler(priority = EventPriority.HIGH) - public void tntExplode( EntityExplodeEvent event ){ - if(event.getEntityType()==null){ + public void tntExplode(EntityExplodeEvent event) { + if (event.getEntityType() == null) { return; } - if(!(event.getEntityType().equals(EntityType.PRIMED_TNT))){ + if (!(event.getEntityType().equals(EntityType.PRIMED_TNT))) { return; } - TNTPrimed tnt = (TNTPrimed)event.getEntity(); + TNTPrimed tnt = (TNTPrimed) event.getEntity(); OwnedLand land = OwnedLand.getApplicableLand(event.getLocation()); if (land != null) { - if(tnt.getSource() != null && tnt.getSource().getType().equals(EntityType.PLAYER)){ - Player p = (Player)tnt.getSource(); - if(!land.hasPermTo(p,this)){ - p.sendMessage(ChatColor.RED+"You cannot detonate TNT on this land."); + if (tnt.getSource() != null && tnt.getSource().getType().equals(EntityType.PLAYER)) { + Player p = (Player) tnt.getSource(); + if (!land.hasPermTo(p, this)) { + p.sendMessage(ChatColor.RED + getPlugin().getMessageConfig().getString("event.tntDamage.detonate")); event.setCancelled(true); return; } - } else if(!land.canEveryone(this)){ + } else if (!land.canEveryone(this)) { event.setCancelled(true); return; } @@ -101,7 +101,7 @@ public void tntExplode( EntityExplodeEvent event ){ while (it.hasNext()) { Block block = it.next(); OwnedLand lnd = OwnedLand.getApplicableLand(block.getLocation()); - if (lnd != null && !lnd.canEveryone(this) ) { + if (lnd != null && !lnd.canEveryone(this)) { if (!(tnt.getSource() instanceof Player) || !lnd.hasPermTo((Player) tnt.getSource(), this)) { it.remove(); } @@ -113,17 +113,17 @@ public void tntExplode( EntityExplodeEvent event ){ } @EventHandler(priority = EventPriority.HIGH) - public void tntMinecartExplode( EntityExplodeEvent event ){ - if(event.getEntityType()==null){ + public void tntMinecartExplode(EntityExplodeEvent event) { + if (event.getEntityType() == null) { return; } - if(!event.getEntityType().equals(EntityType.MINECART_TNT)){ + if (!event.getEntityType().equals(EntityType.MINECART_TNT)) { return; } OwnedLand land = OwnedLand.getApplicableLand(event.getLocation()); if (land != null) { - if(!land.canEveryone(this)){ + if (!land.canEveryone(this)) { event.setCancelled(true); return; } @@ -145,15 +145,15 @@ public void tntMinecartExplode( EntityExplodeEvent event ){ } @EventHandler(priority = EventPriority.HIGH) - public void igniteTnt(PlayerInteractEvent event){ + public void igniteTnt(PlayerInteractEvent event) { - if(!(event.getAction().equals(Action.RIGHT_CLICK_BLOCK))){ + if (!(event.getAction().equals(Action.RIGHT_CLICK_BLOCK))) { return; } //System.out.println(event.getAction().toString()); //System.out.println(event.getClickedBlock().getType().toString()); //System.out.println(event.getItem().getType()); - if((event.getClickedBlock().getType().equals(Material.TNT)) && event.getItem() != null &&event.getItem().getType().equals(Material.FLINT_AND_STEEL)) { + if ((event.getClickedBlock().getType().equals(Material.TNT)) && event.getItem() != null && event.getItem().getType().equals(Material.FLINT_AND_STEEL)) { OwnedLand land = OwnedLand.getApplicableLand(event.getClickedBlock().getLocation()); if (land == null) { @@ -161,14 +161,10 @@ public void igniteTnt(PlayerInteractEvent event){ } Player p = event.getPlayer(); if (!land.hasPermTo(p, this)) { - p.sendMessage(ChatColor.RED + "You are not allowed to ignite tnt on this land."); + p.sendMessage(ChatColor.RED + getPlugin().getMessageConfig().getString("event.tntDamage.ignite")); event.setCancelled(true); } } } - - - - } diff --git a/src/com/jcdesimp/landlord/landFlags/UseContainers.java b/src/com/jcdesimp/landlord/landFlags/UseContainers.java index cfb6cc8..ce381b9 100644 --- a/src/com/jcdesimp/landlord/landFlags/UseContainers.java +++ b/src/com/jcdesimp/landlord/landFlags/UseContainers.java @@ -1,5 +1,6 @@ package com.jcdesimp.landlord.landFlags; +import com.jcdesimp.landlord.Landlord; import com.jcdesimp.landlord.landManagement.Landflag; import com.jcdesimp.landlord.persistantData.OwnedLand; import org.bukkit.ChatColor; @@ -28,19 +29,15 @@ public class UseContainers extends Landflag { /** * Constructor needs to be defined and properly call super() */ - public UseContainers() { - super( - "Use Containers", //Display name (will be displayed to players) - "Gives permission to use trap chests|" + - "chests, furnaces, anvils, hoppers,|" + //Description (Lore of headerItem '|' will seperate lines of lore.) - "droppers, dispensers, beacons,|" + - "brewing stands, cauldrons,|" + - "and Jukeboxes.", - new ItemStack(Material.CHEST), //Itemstack (represented in and manager) - "Allowed Container Usage", //Text shown in manager for granted permission - "can use containers.", //Description in manager for granted permission (ex: Friendly players ) - "Denied Container Usage", //Text shown in manager for denied permission - "cannot use containers." //Desciption in manager for denied permission (ex: Regular players ) + public UseContainers(Landlord plugin) { + super(plugin, + plugin.getMessageConfig().getString("flags.useContainers.displayName"), //Display name (will be displayed to players) + plugin.getMessageConfig().getString("flags.useContainers.description"), + new ItemStack(Material.CHEST), //Itemstack (represented in manager) + plugin.getMessageConfig().getString("flags.useContainers.allowedTitle"), //Text shown in manager for granted permission + plugin.getMessageConfig().getString("flags.useContainers.allowedText"), //Description in manager for granted permission (ex: Friendly players ) + plugin.getMessageConfig().getString("flags.useContainers.deniedTitle"), //Text shown in manager for denied permission + plugin.getMessageConfig().getString("flags.useContainers.deniedText") //Desciption in manager for denied permission (ex: Regular players ) ); } @@ -57,6 +54,7 @@ public UseContainers() { /** * Event handler for block placements + * * @param event that happened */ @@ -68,35 +66,29 @@ public UseContainers() { * your flag to do it's job ************************************* */ - - @EventHandler(priority = EventPriority.HIGH) - public void useContainer(PlayerInteractEvent event){ + public void useContainer(PlayerInteractEvent event) { - String[] blockAccess = {"CHEST","TRAPPED_CHEST","BURNING_FURNACE","FURNACE","ANVIL","DROPPER","DISPENSER","HOPPER","BREWING_STAND","SOIL","BEACON","JUKEBOX","CAULDRON"}; + String[] blockAccess = {"CHEST", "TRAPPED_CHEST", "BURNING_FURNACE", "FURNACE", "ANVIL", "DROPPER", "DISPENSER", "HOPPER", "BREWING_STAND", "SOIL", "BEACON", "JUKEBOX", "CAULDRON"}; - if(!(event.getAction().equals(Action.RIGHT_CLICK_BLOCK))){ + if (!(event.getAction().equals(Action.RIGHT_CLICK_BLOCK))) { return; } //System.out.println(event.getAction().toString()); //System.out.println(event.getClickedBlock().getType().toString()); //System.out.println(event.getItem()); - if(!Arrays.asList(blockAccess).contains(event.getClickedBlock().getType().toString())){ + if (!Arrays.asList(blockAccess).contains(event.getClickedBlock().getType().toString())) { return; } OwnedLand land = OwnedLand.getApplicableLand(event.getClickedBlock().getLocation()); - if(land == null){ + if (land == null) { return; } Player p = event.getPlayer(); - if(!land.hasPermTo(p, this)){ - p.sendMessage(ChatColor.RED + "You are not allowed to use containers on this land."); + if (!land.hasPermTo(p, this)) { + p.sendMessage(ChatColor.RED + getPlugin().getMessageConfig().getString("event.useContainers.interact")); event.setCancelled(true); } } - - - - } diff --git a/src/com/jcdesimp/landlord/landFlags/UseRedstone.java b/src/com/jcdesimp/landlord/landFlags/UseRedstone.java index 9410a0e..d8b202c 100644 --- a/src/com/jcdesimp/landlord/landFlags/UseRedstone.java +++ b/src/com/jcdesimp/landlord/landFlags/UseRedstone.java @@ -29,17 +29,15 @@ public class UseRedstone extends Landflag { /** * Constructor needs to be defined and properly call super() */ - public UseRedstone() { - super( - "Use Redstone", //Display name (will be displayed to players) - "Gives permission to use buttons and|" + - "levers, and trip pressure plates,|" + //Description (Lore of headerItem '|' will seperate lines of lore.) - "and tripwires.", - new ItemStack(Material.REDSTONE), //Itemstack (represented in and manager) - "Allowed Redstone Usage", //Text shown in manager for granted permission - "can use redstone.", //Description in manager for granted permission (ex: Friendly players ) - "Denied Redstone Usage", //Text shown in manager for denied permission - "cannot use redstone." //Desciption in manager for denied permission (ex: Regular players ) + public UseRedstone(Landlord plugin) { + super(plugin, + plugin.getMessageConfig().getString("flags.useRedstone.displayName"), //Display name (will be displayed to players) + plugin.getMessageConfig().getString("flags.useRedstone.description"), + new ItemStack(Material.REDSTONE), //Itemstack (represented in manager) + plugin.getMessageConfig().getString("flags.useRedstone.allowedTitle"), //Text shown in manager for granted permission + plugin.getMessageConfig().getString("flags.useRedstone.allowedText"), //Description in manager for granted permission (ex: Friendly players ) + plugin.getMessageConfig().getString("flags.useRedstone.deniedTitle"), //Text shown in manager for denied permission + plugin.getMessageConfig().getString("flags.useRedstone.deniedText") //Desciption in manager for denied permission (ex: Regular players ) ); } @@ -56,6 +54,7 @@ public UseRedstone() { /** * Event handler for block placements + * * @param event that happened */ @@ -74,35 +73,34 @@ public void useRedstone(PlayerInteractEvent event) { //System.out.println("Type Clicked: "+event.getClickedBlock().getType()); //System.out.println("Action: "+event.getAction()); //System.out.println("Item Used: "+event.getItem()); - if(event.getPlayer() == null) { + if (event.getPlayer() == null) { //System.out.println("OUTT"); return; } Player p = event.getPlayer(); - if(event.getAction().equals(Action.RIGHT_CLICK_BLOCK) && Arrays.asList(blockedInteracts).contains(event.getClickedBlock().getType())) { + if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK) && Arrays.asList(blockedInteracts).contains(event.getClickedBlock().getType())) { //System.out.println("left click"); OwnedLand land = OwnedLand.getApplicableLand(event.getClickedBlock().getLocation()); - if(land == null){ + if (land == null) { return; } - if(!land.hasPermTo(p, this)){ - p.sendMessage(ChatColor.RED+"You cannot use redstone on this land."); + if (!land.hasPermTo(p, this)) { + p.sendMessage(ChatColor.RED + getPlugin().getMessageConfig().getString("event.useRedstone.interact")); event.setCancelled(true); return; } } - if(event.getAction().equals(Action.PHYSICAL) && Arrays.asList(blockedInteracts).contains(event.getClickedBlock().getType())){ + if (event.getAction().equals(Action.PHYSICAL) && Arrays.asList(blockedInteracts).contains(event.getClickedBlock().getType())) { //System.out.println("physical"); OwnedLand land = OwnedLand.getApplicableLand(event.getClickedBlock().getLocation()); - if(land == null){ + if (land == null) { return; } - if(!land.hasPermTo(p, this)){ + if (!land.hasPermTo(p, this)) { event.setCancelled(true); - return; } } } -} +} \ No newline at end of file diff --git a/src/com/jcdesimp/landlord/landManagement/FlagManager.java b/src/com/jcdesimp/landlord/landManagement/FlagManager.java index 2b6ae43..dc6e716 100644 --- a/src/com/jcdesimp/landlord/landManagement/FlagManager.java +++ b/src/com/jcdesimp/landlord/landManagement/FlagManager.java @@ -1,11 +1,8 @@ package com.jcdesimp.landlord.landManagement; import com.jcdesimp.landlord.Landlord; -import com.jcdesimp.landlord.persistantData.DBVersion; import com.jcdesimp.landlord.persistantData.LandFlagPerm; -import org.bukkit.plugin.java.JavaPlugin; -import java.util.ArrayList; import java.util.HashMap; /** @@ -16,7 +13,7 @@ public class FlagManager { Landlord plugin; public FlagManager(Landlord plugin) { - this.registeredFlags = new HashMap(); + this.registeredFlags = new HashMap<>(); this.plugin = plugin; } @@ -26,16 +23,16 @@ public HashMap getRegisteredFlags() { } public boolean registerFlag(Landflag f) { - if(registeredFlags.containsKey(f.getClass().getSimpleName())) { - plugin.getLogger().warning("Could not register flag \""+f.getClass().getSimpleName()+"\" because a flag is already registered with that name!"); + if (registeredFlags.containsKey(f.getClass().getSimpleName())) { + plugin.getLogger().warning("Could not register flag \"" + f.getClass().getSimpleName() + "\" because a flag is already registered with that name!"); f.setUniqueName(f.getClass().getSimpleName()); return false; } - LandFlagPerm lfp = plugin.getDatabase().find(LandFlagPerm.class).where().eq("identifier",f.getClass().getSimpleName()).findUnique(); - if(lfp == null){ - plugin.getLogger().info("Registering new land flag: "+f.getClass().getSimpleName()); - lfp = LandFlagPerm.flagPermFromData(f.getClass().getSimpleName(),plugin.getDatabase().find(LandFlagPerm.class).findRowCount()+1); + LandFlagPerm lfp = plugin.getDatabase().find(LandFlagPerm.class).where().eq("identifier", f.getClass().getSimpleName()).findUnique(); + if (lfp == null) { + plugin.getLogger().info("Registering new land flag: " + f.getClass().getSimpleName()); + lfp = LandFlagPerm.flagPermFromData(f.getClass().getSimpleName(), plugin.getDatabase().find(LandFlagPerm.class).findRowCount() + 1); plugin.getDatabase().save(lfp); } f.setPermSlot(lfp.getPermSlot()); @@ -43,16 +40,15 @@ public boolean registerFlag(Landflag f) { plugin.getServer().getPluginManager().registerEvents(f, plugin); registeredFlags.put(f.getClass().getSimpleName(), f); } catch (Exception e) { - plugin.getLogger().warning("Error occured while registering flag \""+f.getClass().getSimpleName()+"\":"); + plugin.getLogger().warning("Error occured while registering flag \"" + f.getClass().getSimpleName() + "\":"); e.printStackTrace(); return false; } - plugin.getLogger().info("Registered flag: "+f.getClass().getSimpleName()); + plugin.getLogger().info("Registered flag: " + f.getClass().getSimpleName()); return true; - } public int numStoredPerms() { diff --git a/src/com/jcdesimp/landlord/landManagement/LandManagerView.java b/src/com/jcdesimp/landlord/landManagement/LandManagerView.java index ad8d648..62673a3 100644 --- a/src/com/jcdesimp/landlord/landManagement/LandManagerView.java +++ b/src/com/jcdesimp/landlord/landManagement/LandManagerView.java @@ -3,20 +3,19 @@ import com.jcdesimp.landlord.Landlord; import com.jcdesimp.landlord.persistantData.OwnedLand; import org.bukkit.*; +import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; -import org.bukkit.event.inventory.*; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; +import java.util.*; import static java.lang.Math.ceil; @@ -25,45 +24,47 @@ */ public class LandManagerView implements Listener { + private Landlord plugin; + private Player player; private Inventory ui; private OwnedLand mLand; private String[][] perms; - private ArrayList permCols = new ArrayList(); - private ArrayList permSlots = new ArrayList(); + private ArrayList permCols = new ArrayList<>(); + private ArrayList permSlots = new ArrayList<>(); private int pageNum = 0; private boolean isOpen = true; private int numPages; - public LandManagerView(Player player, OwnedLand mLand) { - Landlord.getInstance().getServer().getPluginManager().registerEvents(this, Landlord.getInstance()); + public LandManagerView(Player player, OwnedLand mLand, Landlord plugin) { + this.plugin = plugin; + + FileConfiguration messages = plugin.getMessageConfig(); + plugin.getServer().getPluginManager().registerEvents(this, Landlord.getInstance()); this.player = player; this.mLand = mLand; this.perms = mLand.getLandPerms(); - this.ui = Bukkit.createInventory(null, 36, "Land Manager"); + this.ui = Bukkit.createInventory(null, 36, messages.getString("manager.title")); this.updateUIData(); - this.numPages = (int)ceil(((double)permCols.size())/8.0); - if(numPages==1){ - this.ui = Bukkit.createInventory(null, 27, "Land Manager"); + this.numPages = (int) ceil(((double) permCols.size()) / 8.0); + if (numPages == 1) { + this.ui = Bukkit.createInventory(null, 27, messages.getString("manager.title")); } this.setToggles(); this.buildUI(); - //this.showUI(); } - private ItemStack makeButton(String displayName, String[] lore, Material material){ + private ItemStack makeButton(String displayName, String[] lore, Material material) { return makeButton(displayName, lore, new ItemStack(material)); - - } - private ItemStack makeButton(String displayName, String[] lore, ItemStack stack){ + private ItemStack makeButton(String displayName, String[] lore, ItemStack stack) { ItemMeta meta = stack.getItemMeta(); meta.setDisplayName(displayName); meta.setLore(Arrays.asList(lore)); @@ -72,8 +73,7 @@ private ItemStack makeButton(String displayName, String[] lore, ItemStack stack) } - - public void showUI(){ + public void showUI() { player.openInventory(ui); } @@ -83,59 +83,55 @@ private void hideUI(){ } */ - private void updateUIData(){ + private void updateUIData() { + FileConfiguration messages = plugin.getMessageConfig(); //Generate dynamic items based on land perms permSlots.clear(); permCols.clear(); - for(Map.Entry entry : Landlord.getInstance().getFlagManager().getRegisteredFlags().entrySet()){ + for (Map.Entry entry : Landlord.getInstance().getFlagManager().getRegisteredFlags().entrySet()) { Landflag l = entry.getValue(); - permSlots.add(new Integer(l.getPermSlot())); + permSlots.add(l.getPermSlot()); String[] loreData = l.getDescription().split("\\|"); String[] desc = colorLore(loreData); - ItemStack header = makeButton(ChatColor.YELLOW+l.getDisplayName(),desc,l.getHeaderItem()); + ItemStack header = makeButton(ChatColor.YELLOW + l.getDisplayName(), desc, l.getHeaderItem()); ItemStack allState; //System.out.println("VALUE: "+mLand.getLandPerms()[0][l.getPermSlot()]); - if(perms[0][l.getPermSlot()].equals("1")){ - desc = colorLore(( - ("Regular players "+l.getAllowedText())+"|"+ChatColor.YELLOW+"Click to toggle.").split("\\|")); - allState = makeButton(ChatColor.GREEN+l.getAllowedTitle(), desc, new ItemStack(Material.WOOL,1, (short)5)); + if (perms[0][l.getPermSlot()].equals("1")) { + desc = colorLore((messages.getString("manager.players.others") + " " + l.getAllowedText() + "|" + ChatColor.YELLOW + messages.getString("manager.toggle")).split("\\|")); + allState = makeButton(ChatColor.GREEN + l.getAllowedTitle(), desc, new ItemStack(Material.WOOL, 1, (short) 5)); } else { - desc = colorLore((("Regular players "+l.getDeniedText()+"|"+ChatColor.YELLOW+"Click to toggle.")).split("\\|")); - allState = makeButton(ChatColor.RED+l.getDeniedTitle(), desc, new ItemStack(Material.WOOL,1, (short)14)); + desc = colorLore((messages.getString("manager.players.others") + " " + l.getDeniedText() + "|" + ChatColor.YELLOW + messages.getString("manager.toggle")).split("\\|")); + allState = makeButton(ChatColor.RED + l.getDeniedTitle(), desc, new ItemStack(Material.WOOL, 1, (short) 14)); } ItemStack friendState; - if(perms[1][l.getPermSlot()].equals("1")){ - desc = colorLore((("Friends of this land "+l.getAllowedText())+"|"+ChatColor.YELLOW+"Click to toggle.").split("\\|")); - friendState = makeButton(ChatColor.GREEN+l.getAllowedTitle(), desc, new ItemStack(Material.WOOL,1, (short)5)); + if (perms[1][l.getPermSlot()].equals("1")) { + desc = colorLore((messages.getString("manager.players.friends") + " " + l.getAllowedText() + "|" + ChatColor.YELLOW + messages.getString("manager.toggle")).split("\\|")); + friendState = makeButton(ChatColor.GREEN + l.getAllowedTitle(), desc, new ItemStack(Material.WOOL, 1, (short) 5)); } else { - desc = colorLore((("Friends of this land "+l.getDeniedText()+"|"+ChatColor.YELLOW+"Click to toggle.")).split("\\|")); - friendState = makeButton(ChatColor.RED+l.getDeniedTitle(), desc, new ItemStack(Material.WOOL,1, (short)14)); + desc = colorLore((messages.getString("manager.players.friends") + " " + l.getDeniedText() + "|" + ChatColor.YELLOW + messages.getString("manager.toggle")).split("\\|")); + friendState = makeButton(ChatColor.RED + l.getDeniedTitle(), desc, new ItemStack(Material.WOOL, 1, (short) 14)); } - - permCols.add(new ItemStack[] {header,allState,friendState}); + permCols.add(new ItemStack[]{header, allState, friendState}); } } - private String[] colorLore(String[] loreData){ + private String[] colorLore(String[] loreData) { String[] desc = new String[loreData.length]; - for(int s = 0; s helpText = messages.getStringList("manager.help.text"); + ui.setItem(0, makeButton(ChatColor.GOLD + messages.getString("manager.help.button"), + helpText.toArray(new String[helpText.size()]), + Material.ENCHANTED_BOOK)); /* ui.setItem(1,makeButton(ChatColor.YELLOW+ "Build", new String[]{ChatColor.RESET+"Gives permission to place",ChatColor.RESET+"and break blocks."}, Material.COBBLESTONE)); @@ -144,66 +140,74 @@ private void buildUI(){ ui.setItem(3, makeButton(ChatColor.YELLOW+"Open Containers", new String[]{ChatColor.RESET+"Gives permission to use trap chests,", ChatColor.RESET+"chests, furnaces, anvils, hoppers,", ChatColor.RESET+"droppers, and dispensers."}, Material.CHEST)); */ - ui.setItem(9,makeButton(ChatColor.YELLOW+"Everyone", new String[]{ChatColor.RESET+"Permissions in this row apply to", - ChatColor.RESET+"people that aren't friends",ChatColor.RESET+"of this land."}, - new ItemStack(Material.SKULL_ITEM, 1, (short)2))); - ui.setItem(18,makeButton(ChatColor.YELLOW+"Friends", new String[]{ChatColor.RESET+"Permissions in this row apply to", ChatColor.RESET+"friends of this land."}, - new ItemStack(Material.SKULL_ITEM, 1, (short)3))); - if(pageNum < numPages-1){ + + final List friendsText = messages.getStringList("manager.table.friends.description"); + final List othersText = messages.getStringList("manager.table.others.description"); + + final List nextPageText = messages.getStringList("manager.pagination.next.description"); + final List prevPageText = messages.getStringList("manager.pagination.previous.description"); + + ui.setItem(9, makeButton(ChatColor.YELLOW + messages.getString("manager.table.others.title"), + othersText.toArray(new String[othersText.size()]), + new ItemStack(Material.SKULL_ITEM, 1, (short) 2))); + + ui.setItem(18, makeButton(ChatColor.YELLOW + messages.getString("manager.table.friends.title"), + friendsText.toArray(new String[friendsText.size()]), + new ItemStack(Material.SKULL_ITEM, 1, (short) 3))); + + if (pageNum < numPages - 1) { //35 - ui.setItem(35,makeButton(ChatColor.YELLOW+"Next Page", new String[]{ChatColor.RESET+"View next page of options."}, + ui.setItem(35, makeButton(ChatColor.YELLOW + messages.getString("manager.pagination.next.title"), + nextPageText.toArray(new String[nextPageText.size()]), new ItemStack(Material.PAPER))); } - if(pageNum > 0){ + if (pageNum > 0) { //27 - ui.setItem(27,makeButton(ChatColor.YELLOW+"Previous Page", new String[]{ChatColor.RESET+"View previous page of options."}, + ui.setItem(27, makeButton(ChatColor.YELLOW + messages.getString("manager.pagination.previous.title"), + prevPageText.toArray(new String[prevPageText.size()]), new ItemStack(Material.PAPER))); } - - - - } - private void setToggles(){ + private void setToggles() { - int startIndex = pageNum*8; + int startIndex = pageNum * 8; int endIndex; ui.clear(); - if(pageNum==numPages-1){ + if (pageNum == numPages - 1) { endIndex = permCols.size(); } else { - endIndex = startIndex+8; + endIndex = startIndex + 8; } int slot = 1; - for(int i=startIndex; i pSlots = Landlord.getInstance().getFlagManager().getRegisteredFlags(); + HashMap pSlots = Landlord.getInstance().getFlagManager().getRegisteredFlags(); //RowCount - int row = slot/9; + int row = slot / 9; //System.out.println("ROW: "+row); //ColCount - int col = slot%9; + int col = slot % 9; //System.out.println("COL: "+col); //System.out.println("PAGES: "+pageNum); - int startIndex = pageNum*8; + int startIndex = pageNum * 8; int endIndex; - if(pageNum==numPages-1){ + if (pageNum == numPages - 1) { endIndex = permCols.size(); } else { - endIndex = startIndex+8; + endIndex = startIndex + 8; } //System.out.println("EndIndex: "+endIndex); //System.out.println("StartIndex: "+startIndex); - if((col<=(endIndex-startIndex) && col>0)) { + if ((col <= (endIndex - startIndex) && col > 0)) { - if(row == 1) { - player.playSound(player.getLocation(), Sound.CLICK, 1L, 1L); - perms[0][permSlots.get((col-1)+((pageNum)*8))] = bSwap(perms[0][permSlots.get((col-1)+((pageNum)*8))]); - } else if (row == 2){ - player.playSound(player.getLocation(), Sound.CLICK, 1L, 1L); + if (row == 1) { + player.playSound(player.getLocation(), Sound.UI_BUTTON_CLICK, 1L, 1L); + perms[0][permSlots.get((col - 1) + ((pageNum) * 8))] = bSwap(perms[0][permSlots.get((col - 1) + ((pageNum) * 8))]); + } else if (row == 2) { + player.playSound(player.getLocation(), Sound.UI_BUTTON_CLICK, 1L, 1L); //System.out.println((col-1)+((pageNum)*8)); - perms[1][permSlots.get((col-1)+((pageNum)*8))] = bSwap(perms[1][permSlots.get((col-1)+((pageNum)*8))]); + perms[1][permSlots.get((col - 1) + ((pageNum) * 8))] = bSwap(perms[1][permSlots.get((col - 1) + ((pageNum) * 8))]); //System.out.println(perms[1][permSlots.get((col-1)+((pageNum)*8))]); } updateUIData(); @@ -259,17 +264,17 @@ public void clickButton(InventoryClickEvent event){ buildUI(); } - if(pageNum < numPages-1 && event.getRawSlot()==35){ + if (pageNum < numPages - 1 && event.getRawSlot() == 35) { //35 - player.playSound(player.getLocation(), Sound.CLICK, 1L, 1L); + player.playSound(player.getLocation(), Sound.UI_BUTTON_CLICK, 1L, 1L); pageNum++; updateUIData(); setToggles(); buildUI(); } - if(pageNum > 0 && event.getRawSlot()==27){ + if (pageNum > 0 && event.getRawSlot() == 27) { //27 - player.playSound(player.getLocation(), Sound.CLICK, 1L, 1L); + player.playSound(player.getLocation(), Sound.UI_BUTTON_CLICK, 1L, 1L); pageNum--; updateUIData(); setToggles(); @@ -280,21 +285,17 @@ public void clickButton(InventoryClickEvent event){ } - private String bSwap(String s){ - if(s.equals("0")){ + private String bSwap(String s) { + if (s.equals("0")) { return "1"; } else { return "0"; } } - public void closeView(){ + public void closeView() { player.closeInventory(); } - - - - } diff --git a/src/com/jcdesimp/landlord/landManagement/Landflag.java b/src/com/jcdesimp/landlord/landManagement/Landflag.java index 27a402a..b65d49c 100644 --- a/src/com/jcdesimp/landlord/landManagement/Landflag.java +++ b/src/com/jcdesimp/landlord/landManagement/Landflag.java @@ -1,5 +1,6 @@ package com.jcdesimp.landlord.landManagement; +import com.jcdesimp.landlord.Landlord; import org.bukkit.event.Listener; import org.bukkit.inventory.ItemStack; @@ -7,28 +8,32 @@ * File created by jcdesimp on 4/11/14. */ public abstract class Landflag implements Listener { + + private Landlord plugin; + //Data Fields private int permSlot; private String uniqueName; //Display Fields private String displayName; - private String descrition; + private String description; private ItemStack headerItem; private String allowedTitle; private String allowedText; private String deniedTitle; private String deniedText; - protected Landflag(String displayName, - String descrition, + protected Landflag(Landlord plugin, String displayName, + String description, ItemStack headerItem, String allowedTitle, String allowedText, String deniedTitle, String deniedText) { + this.plugin = plugin; this.displayName = displayName; - this.descrition = descrition; + this.description = description; this.headerItem = headerItem; this.allowedTitle = allowedTitle; this.allowedText = allowedText; @@ -48,20 +53,20 @@ public String getDeniedText() { return deniedText; } - public void setUniqueName(String uniqueName) { - this.uniqueName = uniqueName; - } - public String getUniqueName() { return uniqueName; } + public void setUniqueName(String uniqueName) { + this.uniqueName = uniqueName; + } + public String getDisplayName() { return displayName; } public String getDescription() { - return descrition; + return description; } public ItemStack getHeaderItem() { @@ -79,4 +84,8 @@ public String getAllowedText() { public String getDeniedTitle() { return deniedTitle; } + + public Landlord getPlugin() { + return plugin; + } } diff --git a/src/com/jcdesimp/landlord/landManagement/ViewManager.java b/src/com/jcdesimp/landlord/landManagement/ViewManager.java index 5bd9346..7687f96 100644 --- a/src/com/jcdesimp/landlord/landManagement/ViewManager.java +++ b/src/com/jcdesimp/landlord/landManagement/ViewManager.java @@ -1,5 +1,6 @@ package com.jcdesimp.landlord.landManagement; +import com.jcdesimp.landlord.Landlord; import com.jcdesimp.landlord.persistantData.OwnedLand; import org.bukkit.entity.Player; @@ -18,36 +19,34 @@ public ViewManager() { this.activeViews = new HashMap(); } - public void activateView(Player p, OwnedLand land){ - LandManagerView newView = new LandManagerView(p, land); + public void activateView(Player p, OwnedLand land, Landlord plugin) { + LandManagerView newView = new LandManagerView(p, land, plugin); newView.showUI(); - activeViews.put(p.getName(),newView) ; + activeViews.put(p.getName(), newView); } - public void deactivateView(Player p){ - if(activeViews.containsKey(p.getName())){ + public void deactivateView(Player p) { + if (activeViews.containsKey(p.getName())) { activeViews.get(p.getName()).closeView(); activeViews.remove(p.getName()); } } - public void deactivateView(String pName){ - if(activeViews.containsKey(pName)){ + public void deactivateView(String pName) { + if (activeViews.containsKey(pName)) { activeViews.get(pName).closeView(); activeViews.remove(pName); } } - public void NoCloseDeactivateView(Player p){ - if(activeViews.containsKey(p.getName())){ + public void NoCloseDeactivateView(Player p) { + if (activeViews.containsKey(p.getName())) { activeViews.remove(p.getName()); } } - public void deactivateAll(){ - for(String s : activeViews.keySet()) { - deactivateView(s); - } + public void deactivateAll() { + activeViews.keySet().forEach(this::deactivateView); } } diff --git a/src/com/jcdesimp/landlord/landMap/LandMap.java b/src/com/jcdesimp/landlord/landMap/LandMap.java index dc9f1cb..192e86b 100644 --- a/src/com/jcdesimp/landlord/landMap/LandMap.java +++ b/src/com/jcdesimp/landlord/landMap/LandMap.java @@ -4,6 +4,7 @@ import com.jcdesimp.landlord.Landlord; import com.jcdesimp.landlord.persistantData.OwnedLand; import org.bukkit.*; +import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scoreboard.*; @@ -24,15 +25,17 @@ public class LandMap { Chunk currChunk; List nearbyLand; String currDir; + private Landlord plugin; - public LandMap(Player p) { - this.mapViewer=p; + public LandMap(Player p, Landlord plugin) { + this.plugin = plugin; + this.mapViewer = p; this.currChunk = p.getLocation().getChunk(); //System.out.println("CURR: "+currChunk); this.nearbyLand = Landlord.getInstance().getDatabase().find(OwnedLand.class) .where() - .ge("x", this.currChunk.getX()-3).le("x", this.currChunk.getX()+3) - .ge("z", this.currChunk.getZ()-3).le("z",this.currChunk.getZ()+3) + .ge("x", this.currChunk.getX() - 3).le("x", this.currChunk.getX() + 3) + .ge("z", this.currChunk.getZ() - 3).le("z", this.currChunk.getZ() + 3) .eq("worldName", this.currChunk.getWorld().getName()) .findList(); //displayMap(mapViewer); @@ -52,13 +55,11 @@ public void run() { }, 0L, 7L);*/ this.schedulerId = new BukkitRunnable() { - @Override public void run() { - if(!currDir.equals(getPlayerDirection(mapViewer)) || !currChunk.equals(mapViewer.getLocation().getChunk())){ + if (!currDir.equals(getPlayerDirection(mapViewer)) || !currChunk.equals(mapViewer.getLocation().getChunk())) { displayMap(mapViewer); currDir = getPlayerDirection(mapViewer); } - } }.runTaskTimer(Landlord.getInstance(), 0L, 7L).getTaskId(); @@ -67,175 +68,53 @@ public void run() { } - public Player getMapViewer() { - return mapViewer; - } - - public void removeMap(){ - mapViewer.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); - Bukkit.getServer().getScheduler().cancelTask(schedulerId); - - } - - private Scoreboard displayMap(Player p){ - ScoreboardManager manager = Bukkit.getScoreboardManager(); - Scoreboard board = manager.getNewScoreboard(); - //Scoreboard board = manager.getMainScoreboard(); - Team team = board.registerNewTeam("teamname"); - team.addPlayer(p); - - Objective objective = board.registerNewObjective("Land Map", "dummy"); - /*ChatColor.STRIKETHROUGH+""+ChatColor.DARK_GREEN+ - "=== "+ChatColor.RESET+""+ChatColor.DARK_GREEN +"Land Map" - +ChatColor.STRIKETHROUGH+""+ChatColor.DARK_GREEN+" ==="*/ - objective.setDisplaySlot(DisplaySlot.SIDEBAR); - objective.setDisplayName(ChatColor.YELLOW+""+ChatColor.STRIKETHROUGH+ - "=="+ChatColor.RESET+""+ChatColor.GOLD +" Land Map " - +ChatColor.YELLOW+""+ChatColor.STRIKETHROUGH+"=="); - String[] mapData = buildMap(p); - for(int i = 0; i serialize() { - return null; - } - - @Override - public boolean isWhitelisted() { - return true; - } - - @Override - public Location getBedSpawnLocation(){ - return null; - } - - @Override - public void setWhitelisted(boolean b) { - return; - } - - @Override - public boolean isOnline(){ - return false; - } - @Override - public long getLastPlayed(){ - return 0; - } - - @Override - @Deprecated - public void setBanned(boolean b) { - return; - } - @Override - public boolean isOp(){ - return false; - } - - } - - //OfflinePlayer ofp = Bukkit.getOfflinePlayer(mapData[i].substring(5,17)); - OfflinePlayer ofp = new myOfflinePlayer(mapData[i].substring(5,17)); - //String ofp = mapData[i].substring(5,17); - - Score score = objective.getScore(ofp.getName()); - - score.setScore(mapData.length - i); - - - Team t = board.registerNewTeam(i+""); - t.setPrefix(mapData[i].substring(0,5)); - t.setSuffix(mapData[i].substring(17)); - t.addPlayer(ofp); - t.setDisplayName(mapData[i]); - - - //Score score = objective.getScore(Bukkit.getOfflinePlayer(i + "")); - //score.setScore((mapData.length)-i); - } - //Score score = objective.getScore(Bukkit.getOfflinePlayer()); //Get a fake offline player - //board. - p.setScoreboard(board); - - return board; - } - - - public static String getPlayerDirection(Player playerSelf){ + public static String getPlayerDirection(Player playerSelf) { String dir; float y = playerSelf.getLocation().getYaw(); - if( y < 0 ){y += 360;} + if (y < 0) { + y += 360; + } y %= 360; - int i = (int)((y+8) / 22.5); - if(i == 0){dir = "south";} - else if(i == 1){dir = "south southwest";} - else if(i == 2){dir = "southwest";} - else if(i == 3){dir = "west southwest";} - else if(i == 4){dir = "west";} - else if(i == 5){dir = "west northwest";} - else if(i == 6){dir = "northwest";} - else if(i == 7){dir = "north northwest";} - else if(i == 8){dir = "north";} - else if(i == 9){dir = "north northeast";} - else if(i == 10){dir = "northeast";} - else if(i == 11){dir = "east northeast";} - else if(i == 12){dir = "east";} - else if(i == 13){dir = "east southeast";} - else if(i == 14){dir = "southeast";} - else if(i == 15){dir = "south southeast";} - else {dir = "south";} + int i = (int) ((y + 8) / 22.5); + if (i == 0) { + dir = "south"; + } else if (i == 1) { + dir = "south southwest"; + } else if (i == 2) { + dir = "southwest"; + } else if (i == 3) { + dir = "west southwest"; + } else if (i == 4) { + dir = "west"; + } else if (i == 5) { + dir = "west northwest"; + } else if (i == 6) { + dir = "northwest"; + } else if (i == 7) { + dir = "north northwest"; + } else if (i == 8) { + dir = "north"; + } else if (i == 9) { + dir = "north northeast"; + } else if (i == 10) { + dir = "northeast"; + } else if (i == 11) { + dir = "east northeast"; + } else if (i == 12) { + dir = "east"; + } else if (i == 13) { + dir = "east southeast"; + } else if (i == 14) { + dir = "southeast"; + } else if (i == 15) { + dir = "south southeast"; + } else { + dir = "south"; + } return dir; } - public static String[][] getMapDir(String dir){ + public static String[][] getMapDir(String dir) { String[][] mapDir = new String[][]{ {"ā–“", "ā–’", "ā–’", "āˆž", "ā–’", "ā–’", "ā–“"}, @@ -247,7 +126,7 @@ public static String[][] getMapDir(String dir){ {"ā–’", "ā–“", "ā–“", "ā–“", "ā–“", "ā–“", "ā–’"} }; - if(dir.equals("west")){ + if (dir.equals("west")) { mapDir = new String[][]{ {"ā–“", "ā–’", "ā–’", "ā–’", "ā–’", "ā–’", "ā–“"}, {"ā–’", "ā–“", "ā–’", "ā–“", "ā–’", "ā–“", "ā–’"}, @@ -257,7 +136,7 @@ public static String[][] getMapDir(String dir){ {"ā–“", "ā–’", "ā–“", "ā–“", "ā–“", "ā–’", "ā–“"}, {"ā–’", "ā–“", "ā–“", "ā–“", "ā–“", "ā–“", "ā–’"} }; - } else if(dir.equals("west northwest")){ + } else if (dir.equals("west northwest")) { mapDir = new String[][]{ {"ā–“", "ā–’", "ā–’", "ā–’", "ā–’", "ā–’", "ā–“"}, {"āˆž", "ā–“", "ā–’", "ā–“", "ā–’", "ā–“", "ā–’"}, @@ -267,7 +146,7 @@ public static String[][] getMapDir(String dir){ {"ā–“", "ā–’", "ā–“", "ā–“", "ā–“", "ā–’", "ā–“"}, {"ā–’", "ā–“", "ā–“", "ā–“", "ā–“", "ā–“", "ā–’"} }; - } else if(dir.equals("northwest")){ + } else if (dir.equals("northwest")) { mapDir = new String[][]{ {"āˆž", "ā–’", "ā–’", "ā–’", "ā–’", "ā–’", "ā–“"}, {"ā–’", "āˆž", "ā–’", "ā–“", "ā–’", "ā–“", "ā–’"}, @@ -277,7 +156,7 @@ public static String[][] getMapDir(String dir){ {"ā–“", "ā–’", "ā–“", "ā–“", "ā–“", "ā–’", "ā–“"}, {"ā–’", "ā–“", "ā–“", "ā–“", "ā–“", "ā–“", "ā–’"} }; - } else if(dir.equals("north northwest")){ + } else if (dir.equals("north northwest")) { mapDir = new String[][]{ {"ā–“", "āˆž", "ā–’", "ā–’", "ā–’", "ā–’", "ā–“"}, {"ā–’", "ā–“", "āˆž", "ā–“", "ā–’", "ā–“", "ā–’"}, @@ -287,7 +166,7 @@ public static String[][] getMapDir(String dir){ {"ā–“", "ā–’", "ā–“", "ā–“", "ā–“", "ā–’", "ā–“"}, {"ā–’", "ā–“", "ā–“", "ā–“", "ā–“", "ā–“", "ā–’"} }; - } else if(dir.equals("north")){ + } else if (dir.equals("north")) { mapDir = new String[][]{ {"ā–“", "ā–’", "ā–’", "āˆž", "ā–’", "ā–’", "ā–“"}, {"ā–’", "ā–“", "ā–’", "āˆž", "ā–’", "ā–“", "ā–’"}, @@ -297,7 +176,7 @@ public static String[][] getMapDir(String dir){ {"ā–“", "ā–’", "ā–“", "ā–“", "ā–“", "ā–’", "ā–“"}, {"ā–’", "ā–“", "ā–“", "ā–“", "ā–“", "ā–“", "ā–’"} }; - } else if(dir.equals("north northeast")){ + } else if (dir.equals("north northeast")) { mapDir = new String[][]{ {"ā–“", "ā–’", "ā–’", "ā–’", "ā–’", "āˆž", "ā–“"}, {"ā–’", "ā–“", "ā–’", "ā–“", "āˆž", "ā–“", "ā–’"}, @@ -307,7 +186,7 @@ public static String[][] getMapDir(String dir){ {"ā–“", "ā–’", "ā–“", "ā–“", "ā–“", "ā–’", "ā–“"}, {"ā–’", "ā–“", "ā–“", "ā–“", "ā–“", "ā–“", "ā–’"} }; - } else if(dir.equals("northeast")){ + } else if (dir.equals("northeast")) { mapDir = new String[][]{ {"ā–“", "ā–’", "ā–’", "ā–’", "ā–’", "ā–’", "āˆž"}, {"ā–’", "ā–“", "ā–’", "ā–“", "ā–’", "āˆž", "ā–’"}, @@ -317,7 +196,7 @@ public static String[][] getMapDir(String dir){ {"ā–“", "ā–’", "ā–“", "ā–“", "ā–“", "ā–’", "ā–“"}, {"ā–’", "ā–“", "ā–“", "ā–“", "ā–“", "ā–“", "ā–’"} }; - } else if(dir.equals("east northeast")){ + } else if (dir.equals("east northeast")) { mapDir = new String[][]{ {"ā–“", "ā–’", "ā–’", "ā–’", "ā–’", "ā–’", "ā–“"}, {"ā–’", "ā–“", "ā–’", "ā–“", "ā–’", "ā–“", "āˆž"}, @@ -327,7 +206,7 @@ public static String[][] getMapDir(String dir){ {"ā–“", "ā–’", "ā–“", "ā–“", "ā–“", "ā–’", "ā–“"}, {"ā–’", "ā–“", "ā–“", "ā–“", "ā–“", "ā–“", "ā–’"} }; - } else if(dir.equals("east")){ + } else if (dir.equals("east")) { mapDir = new String[][]{ {"ā–“", "ā–’", "ā–’", "ā–’", "ā–’", "ā–’", "ā–“"}, {"ā–’", "ā–“", "ā–’", "ā–“", "ā–’", "ā–“", "ā–’"}, @@ -337,7 +216,7 @@ public static String[][] getMapDir(String dir){ {"ā–“", "ā–’", "ā–“", "ā–“", "ā–“", "ā–’", "ā–“"}, {"ā–’", "ā–“", "ā–“", "ā–“", "ā–“", "ā–“", "ā–’"} }; - } else if(dir.equals("east southeast")){ + } else if (dir.equals("east southeast")) { mapDir = new String[][]{ {"ā–“", "ā–’", "ā–’", "ā–’", "ā–’", "ā–’", "ā–“"}, {"ā–’", "ā–“", "ā–’", "ā–“", "ā–’", "ā–“", "ā–’"}, @@ -347,7 +226,7 @@ public static String[][] getMapDir(String dir){ {"ā–“", "ā–’", "ā–“", "ā–“", "ā–“", "ā–’", "āˆž"}, {"ā–’", "ā–“", "ā–“", "ā–“", "ā–“", "ā–“", "ā–’"} }; - } else if(dir.equals("southeast")){ + } else if (dir.equals("southeast")) { mapDir = new String[][]{ {"ā–“", "ā–’", "ā–’", "ā–’", "ā–’", "ā–’", "ā–“"}, {"ā–’", "ā–“", "ā–’", "ā–“", "ā–’", "ā–“", "ā–’"}, @@ -357,7 +236,7 @@ public static String[][] getMapDir(String dir){ {"ā–“", "ā–’", "ā–“", "ā–“", "ā–“", "āˆž", "ā–“"}, {"ā–’", "ā–“", "ā–“", "ā–“", "ā–“", "ā–“", "āˆž"} }; - } else if(dir.equals("south southeast")){ + } else if (dir.equals("south southeast")) { mapDir = new String[][]{ {"ā–“", "ā–’", "ā–’", "ā–’", "ā–’", "ā–’", "ā–“"}, {"ā–’", "ā–“", "ā–’", "ā–“", "ā–’", "ā–“", "ā–’"}, @@ -367,7 +246,7 @@ public static String[][] getMapDir(String dir){ {"ā–“", "ā–’", "ā–“", "ā–“", "āˆž", "ā–’", "ā–“"}, {"ā–’", "ā–“", "ā–“", "ā–“", "ā–“", "āˆž", "ā–’"} }; - } else if(dir.equals("south")){ + } else if (dir.equals("south")) { mapDir = new String[][]{ {"ā–“", "ā–’", "ā–’", "ā–’", "ā–’", "ā–’", "ā–“"}, {"ā–’", "ā–“", "ā–’", "ā–“", "ā–’", "ā–“", "ā–’"}, @@ -377,7 +256,7 @@ public static String[][] getMapDir(String dir){ {"ā–“", "ā–’", "ā–“", "āˆž", "ā–“", "ā–’", "ā–“"}, {"ā–’", "ā–“", "ā–“", "āˆž", "ā–“", "ā–“", "ā–’"} }; - } else if(dir.equals("south southwest")){ + } else if (dir.equals("south southwest")) { mapDir = new String[][]{ {"ā–“", "ā–’", "ā–’", "ā–’", "ā–’", "ā–’", "ā–“"}, {"ā–’", "ā–“", "ā–’", "ā–“", "ā–’", "ā–“", "ā–’"}, @@ -387,7 +266,7 @@ public static String[][] getMapDir(String dir){ {"ā–“", "ā–’", "āˆž", "ā–“", "ā–“", "ā–’", "ā–“"}, {"ā–’", "āˆž", "ā–“", "ā–“", "ā–“", "ā–“", "ā–’"} }; - } else if(dir.equals("southwest")){ + } else if (dir.equals("southwest")) { mapDir = new String[][]{ {"ā–“", "ā–’", "ā–’", "ā–’", "ā–’", "ā–’", "ā–“"}, {"ā–’", "ā–“", "ā–’", "ā–“", "ā–’", "ā–“", "ā–’"}, @@ -397,7 +276,7 @@ public static String[][] getMapDir(String dir){ {"ā–“", "āˆž", "ā–“", "ā–“", "ā–“", "ā–’", "ā–“"}, {"āˆž", "ā–“", "ā–“", "ā–“", "ā–“", "ā–“", "ā–’"} }; - } else if(dir.equals("west southwest")){ + } else if (dir.equals("west southwest")) { mapDir = new String[][]{ {"ā–“", "ā–’", "ā–’", "ā–’", "ā–’", "ā–’", "ā–“"}, {"ā–’", "ā–“", "ā–’", "ā–“", "ā–’", "ā–“", "ā–’"}, @@ -412,11 +291,160 @@ public static String[][] getMapDir(String dir){ return mapDir; } - public void updateMap(){ + public Player getMapViewer() { + return mapViewer; + } + + public void removeMap() { + mapViewer.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); + Bukkit.getServer().getScheduler().cancelTask(schedulerId); + + } + + private Scoreboard displayMap(Player p) { + ScoreboardManager manager = Bukkit.getScoreboardManager(); + Scoreboard board = manager.getNewScoreboard(); + //Scoreboard board = manager.getMainScoreboard(); + Team team = board.registerNewTeam("teamname"); + team.addPlayer(p); + + FileConfiguration messages = plugin.getMessageConfig(); + final String header = messages.getString("map.header"); + + Objective objective = board.registerNewObjective("Land Map", "dummy"); + /*ChatColor.STRIKETHROUGH+""+ChatColor.DARK_GREEN+ + "=== "+ChatColor.RESET+""+ChatColor.DARK_GREEN +"Land Map" + +ChatColor.STRIKETHROUGH+""+ChatColor.DARK_GREEN+" ==="*/ + objective.setDisplaySlot(DisplaySlot.SIDEBAR); + + /** + * Locale string is retrieved from file for use in map header. + * Scoreboards do not cooperate with headers longer than 14 characters, + * therefore it will be truncated if too long. + */ + + if (header.length() <= 14) { + objective.setDisplayName(ChatColor.YELLOW + "" + ChatColor.STRIKETHROUGH + + "==" + ChatColor.RESET + "" + ChatColor.GOLD + " " + + header + + " " + ChatColor.YELLOW + "" + ChatColor.STRIKETHROUGH + "=="); + } else { + objective.setDisplayName(ChatColor.YELLOW + "" + ChatColor.STRIKETHROUGH + + "==" + ChatColor.RESET + "" + ChatColor.GOLD + " " + + header.substring(0, 14) + + " " + ChatColor.YELLOW + "" + ChatColor.STRIKETHROUGH + "=="); + } + + + String[] mapData = buildMap(p); + for (int i = 0; i < mapData.length; i++) { + if (mapData[i].length() < 21) { + for (int f = 0; f < (21 - mapData[i].length()); f++) { + mapData[i] += ChatColor.RESET; + } + } + + + //todo THIS BETTER NOT STAY!!!!!! + class myOfflinePlayer implements OfflinePlayer { + String name; + + public myOfflinePlayer(String name) { + this.name = name; + } + + public Player getPlayer() { + return null; + } + + public boolean hasPlayedBefore() { + return false; + } + + public String getName() { + return name; + } + + public UUID getUniqueId() { + return null; + } + + public long getFirstPlayed() { + return 0; + } + + public boolean isBanned() { + return false; + } + + @Deprecated + public void setBanned(boolean b) { + return; + } + + public Map serialize() { + return null; + } + + public boolean isWhitelisted() { + return true; + } + + public void setWhitelisted(boolean b) { + return; + } + + public Location getBedSpawnLocation() { + return null; + } + + public boolean isOnline() { + return false; + } + + public long getLastPlayed() { + return 0; + } + + public boolean isOp() { + return false; + } + + public void setOp(boolean b) { + return; + } + + } + + //todo + OfflinePlayer ofp = new myOfflinePlayer(mapData[i].substring(5, 17)); + + Score score = objective.getScore(ofp.getName()); + + score.setScore(mapData.length - i); + + Team t = board.registerNewTeam(i + ""); + t.setPrefix(mapData[i].substring(0, 5)); + t.setSuffix(mapData[i].substring(17)); + t.addPlayer(ofp); + t.setDisplayName(mapData[i]); + + + //Score score = objective.getScore(Bukkit.getOfflinePlayer(i + "")); + //score.setScore((mapData.length)-i); + } + //Score score = objective.getScore(Bukkit.getOfflinePlayer()); //Get a fake offline player + //board. + p.setScoreboard(board); + + return board; + } + + public void updateMap() { nearbyLand = Landlord.getInstance().getDatabase().find(OwnedLand.class) .where() - .ge("x", currChunk.getX()-4).le("x", currChunk.getX()+4) - .ge("z", currChunk.getZ()-4).le("z",currChunk.getZ()+4) + .ge("x", currChunk.getX() - 4).le("x", currChunk.getX() + 4) + .ge("z", currChunk.getZ() - 4).le("z", currChunk.getZ() + 4) .eq("worldName", currChunk.getWorld().getName()) .findList(); currChunk = mapViewer.getLocation().getChunk(); @@ -426,45 +454,43 @@ public void updateMap(){ private String[] buildMap(Player p) { //String st ="ā–’ā–’ā–’ā–“ā–’ā–’ā–’\nā–’ā–’ā–“ā–“ā–“ā–’ā–’\nā–’ā–“ā–“ā–“ā–“ā–“ā–’\nā–“ā–“ā–“ā–ˆā–“ā–“ā–“\nā–“ā–“ā–’ā–’ā–’ā–“ā–“\nā–“ā–’ā–’ā–’ā–’ā–’ā–“\nā–’ā–’ā–’ā–’ā–’ā–’ā–’"; - int radius = 3; - - + final int radius = 3; String[][] mapBoard = getMapDir(getPlayerDirection(p)); String[] mapRows = new String[mapBoard.length + 3]; - if(!currChunk.equals(mapViewer.getLocation().getChunk())){ + if (!currChunk.equals(mapViewer.getLocation().getChunk())) { updateMap(); } - for(int z = 0; z < mapBoard.length; z++){ + for (int z = 0; z < mapBoard.length; z++) { String row = ""; //if curr chunk - for(int x = 0; x < mapBoard[z].length; x++){ + for (int x = 0; x < mapBoard[z].length; x++) { List filteredList = Landlord.getInstance().getDatabase().filter(OwnedLand.class) - .eq("x", currChunk.getX()-radius+x) - .eq("z", currChunk.getZ()-radius+z) + .eq("x", currChunk.getX() - radius + x) + .eq("z", currChunk.getZ() - radius + z) .eq("worldName", currChunk.getWorld().getName()) .filter(nearbyLand); String currSpot = mapBoard[z][x]; - if(!filteredList.isEmpty()){ + if (!filteredList.isEmpty()) { OwnedLand ol = filteredList.get(0); - if(ol.ownerUUID().equals(p.getUniqueId())){ + if (ol.ownerUUID().equals(p.getUniqueId())) { currSpot = ChatColor.GREEN + currSpot; - } else if(ol.isFriend(p)){ + } else if (ol.isFriend(p)) { currSpot = ChatColor.YELLOW + currSpot; } else { currSpot = ChatColor.RED + currSpot; } } else { - if(currSpot.equals("āˆž") || currSpot.equals("\u2062")){ + if (currSpot.equals("āˆž") || currSpot.equals("\u2062")) { currSpot = ChatColor.RESET + currSpot; } else { - currSpot = ChatColor.GRAY + currSpot; + currSpot = ChatColor.GRAY + currSpot; } } @@ -477,11 +503,41 @@ private String[] buildMap(Player p) { mapRows[z] = row; } - mapRows[mapBoard.length] = ChatColor.GREEN + "ā–ˆ-Yours"; - mapRows[mapBoard.length+1] = ChatColor.YELLOW + "ā–ˆ-Friendly"; - mapRows[mapBoard.length+2] = ChatColor.RED + "ā–ˆ-Others'"; + + //mapRows[0] = ""; + + /** + * Locale strings are retrieved from file for use in map legend. + * Scoreboards do not cooperate with strings longer than 28 characters, + * therefore they will be truncated if too long. + */ + + FileConfiguration messages = plugin.getMessageConfig(); + + final String yours = messages.getString("map.legend.yours"); + final String friends = messages.getString("map.legend.friends"); + final String others = messages.getString("map.legend.others"); + + if (yours.length() <= 25) { + mapRows[mapRows.length - 3] = ChatColor.GREEN + "ā–ˆ- " + yours; + } else { + mapRows[mapRows.length - 3] = ChatColor.GREEN + "ā–ˆ- " + yours.substring(0, 25); + } + + if (friends.length() <= 25) { + mapRows[mapRows.length - 2] = ChatColor.YELLOW + "ā–ˆ- " + friends; + } else { + mapRows[mapRows.length - 2] = ChatColor.YELLOW + "ā–ˆ- " + friends.substring(0, 25); + } + + if (others.length() <= 25) { + mapRows[mapRows.length - 1] = ChatColor.RED + "ā–ˆ- " + others; + } else { + mapRows[mapRows.length - 1] = ChatColor.RED + "ā–ˆ- " + others.substring(0, 25); + } + return mapRows; } diff --git a/src/com/jcdesimp/landlord/landMap/MapManager.java b/src/com/jcdesimp/landlord/landMap/MapManager.java index acd3cce..87a6728 100644 --- a/src/com/jcdesimp/landlord/landMap/MapManager.java +++ b/src/com/jcdesimp/landlord/landMap/MapManager.java @@ -18,30 +18,32 @@ public class MapManager implements Listener { private HashMap mapList; - public MapManager() { - this.mapList = new HashMap(); + private Landlord plugin; + public MapManager(Landlord plugin) { + this.mapList = new HashMap(); + this.plugin = plugin; } - private void addMap(LandMap m){ + private void addMap(LandMap m) { mapList.put(m.getMapViewer().getName(), m); } - public void toggleMap(Player p){ - if( mapList.containsKey(p.getName()) ){ + public void toggleMap(Player p) { + if (mapList.containsKey(p.getName())) { remMap(p.getName()); } else { - addMap(new LandMap(p)); + addMap(new LandMap(p, this.plugin)); } //System.out.println(mapList.toString()); } - public void remMap(String pName){ + public void remMap(String pName) { - if( mapList.containsKey(pName) ){ + if (mapList.containsKey(pName)) { LandMap curr = mapList.get(pName); curr.removeMap(); mapList.remove(pName); @@ -49,31 +51,31 @@ public void remMap(String pName){ //System.out.println("After Rem: "+mapList.toString()); } - public void removeAllMaps(){ - for (String k : mapList.keySet()){ + public void removeAllMaps() { + for (String k : mapList.keySet()) { mapList.get(k).removeMap(); } mapList.clear(); } - public void updateAll(){ - for (String k : mapList.keySet()){ + public void updateAll() { + for (String k : mapList.keySet()) { mapList.get(k).updateMap(); } } @EventHandler - public void playerLeave(PlayerQuitEvent event){ - if(mapList.containsKey(event.getPlayer().getName())){ + public void playerLeave(PlayerQuitEvent event) { + if (mapList.containsKey(event.getPlayer().getName())) { remMap(event.getPlayer().getName()); } } @EventHandler - public void playerWorldChange(PlayerChangedWorldEvent event){ - if (mapList.containsKey(event.getPlayer().getName())){ + public void playerWorldChange(PlayerChangedWorldEvent event) { + if (mapList.containsKey(event.getPlayer().getName())) { remMap(event.getPlayer().getName()); } } @@ -81,10 +83,11 @@ public void playerWorldChange(PlayerChangedWorldEvent event){ /** * Update map when player teleports + * * @param event that was triggered */ @EventHandler - public void playerTeleportKeepMap(PlayerTeleportEvent event){ + public void playerTeleportKeepMap(PlayerTeleportEvent event) { final Player p = event.getPlayer(); //mapList.get(p.getName()).updateMap(); @@ -103,7 +106,7 @@ public void run() { } @EventHandler - public void playerRespawn(PlayerRespawnEvent event){ + public void playerRespawn(PlayerRespawnEvent event) { final Player p = event.getPlayer(); if (mapList.containsKey(event.getPlayer().getName())) { Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(Landlord.getInstance(), new Runnable() { diff --git a/src/com/jcdesimp/landlord/persistantData/DBVersion.java b/src/com/jcdesimp/landlord/persistantData/DBVersion.java index 1e65b31..5960289 100644 --- a/src/com/jcdesimp/landlord/persistantData/DBVersion.java +++ b/src/com/jcdesimp/landlord/persistantData/DBVersion.java @@ -2,15 +2,16 @@ import com.avaje.ebean.validation.NotNull; -import javax.persistence.*; -import java.util.List; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; /** * File created by jcdesimp on 4/6/14. */ @SuppressWarnings("UnusedDeclaration") @Entity -@Table(name="ll_version") +@Table(name = "ll_version") public class DBVersion { @@ -18,7 +19,6 @@ public class DBVersion { private int id; - //Used to be the owners username @NotNull private String identifier; diff --git a/src/com/jcdesimp/landlord/persistantData/Friend.java b/src/com/jcdesimp/landlord/persistantData/Friend.java index 5dff2cb..be2046b 100644 --- a/src/com/jcdesimp/landlord/persistantData/Friend.java +++ b/src/com/jcdesimp/landlord/persistantData/Friend.java @@ -6,7 +6,9 @@ import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; -import javax.persistence.*; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; import java.util.UUID; import static org.bukkit.Bukkit.getOfflinePlayer; @@ -17,9 +19,14 @@ @SuppressWarnings("UnusedDeclaration") @Entity -@Table(name="ll_friend") +@Table(name = "ll_friend") public class Friend { + @Id + private int id; + @NotNull + private String playerName; + public static Friend friendFromPlayer(Player p) { Friend fd = new Friend(); fd.setPlayerName(p.getUniqueId().toString()); @@ -32,39 +39,32 @@ public static Friend friendFromOfflinePlayer(OfflinePlayer p) { return fd; } - - - @Id - private int id; - - - @NotNull - private String playerName; - - + public int getId() { + return id; + } public void setId(int id) { this.id = id; } - public int getId() { - return id; + public String getPlayerName() { + return playerName; } public void setPlayerName(String playerName) { this.playerName = playerName; } - public String getPlayerName() { - return playerName; - } - @Override - public boolean equals(Object obj){ + public boolean equals(Object obj) { return obj instanceof Friend && ((Friend) obj).getPlayerName().equalsIgnoreCase(playerName); } public String getName() { + + //mess ready + String unknownFriend = "Unknown"; + /* * ************************************* * mark for possible change !!!!!!!!! @@ -72,7 +72,7 @@ public String getName() { */ OfflinePlayer op = getOfflinePlayer(UUID.fromString(playerName)); if (!op.hasPlayedBefore() && !op.isOnline()) { - return ChatColor.ITALIC+"Unknown"; + return ChatColor.ITALIC + unknownFriend; } return op.getName(); } diff --git a/src/com/jcdesimp/landlord/persistantData/LandFlagPerm.java b/src/com/jcdesimp/landlord/persistantData/LandFlagPerm.java index 83f0fb4..78fb97f 100644 --- a/src/com/jcdesimp/landlord/persistantData/LandFlagPerm.java +++ b/src/com/jcdesimp/landlord/persistantData/LandFlagPerm.java @@ -11,7 +11,7 @@ */ @SuppressWarnings("UnusedDeclaration") @Entity -@Table(name="ll_flagPerm") +@Table(name = "ll_flagPerm") public class LandFlagPerm { @Id @@ -23,7 +23,7 @@ public class LandFlagPerm { @NotNull private int permSlot; - public static LandFlagPerm flagPermFromData(String ident, int pSlot){ + public static LandFlagPerm flagPermFromData(String ident, int pSlot) { LandFlagPerm lf = new LandFlagPerm(); lf.setIdentifier(ident); lf.setPermSlot(pSlot); diff --git a/src/com/jcdesimp/landlord/persistantData/MyDatabase.java b/src/com/jcdesimp/landlord/persistantData/MyDatabase.java index eb09d68..45109ef 100644 --- a/src/com/jcdesimp/landlord/persistantData/MyDatabase.java +++ b/src/com/jcdesimp/landlord/persistantData/MyDatabase.java @@ -4,19 +4,6 @@ * File created by jcdesimp on 4/6/14. */ -import java.io.BufferedReader; -import java.io.StringReader; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.net.URLConnection; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.bukkit.plugin.java.JavaPlugin; - import com.avaje.ebean.EbeanServer; import com.avaje.ebean.EbeanServerFactory; import com.avaje.ebean.config.DataSourceConfig; @@ -25,8 +12,19 @@ import com.avaje.ebeaninternal.api.SpiEbeanServer; import com.avaje.ebeaninternal.server.ddl.DdlGenerator; import com.avaje.ebeaninternal.server.lib.sql.TransactionIsolation; +import org.bukkit.plugin.java.JavaPlugin; import javax.persistence.Table; +import java.io.BufferedReader; +import java.io.StringReader; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.net.URLConnection; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; public abstract class MyDatabase { private JavaPlugin javaPlugin; @@ -53,9 +51,8 @@ public MyDatabase(JavaPlugin javaPlugin) { method.setAccessible(true); //Store the ClassLoader - this.classLoader = (ClassLoader)method.invoke(javaPlugin); - } - catch(Exception ex ) { + this.classLoader = (ClassLoader) method.invoke(javaPlugin); + } catch (Exception ex) { throw new RuntimeException("Failed to retrieve the ClassLoader of the plugin using Reflection", ex); } } @@ -63,13 +60,13 @@ public MyDatabase(JavaPlugin javaPlugin) { /** * Initialize the database using the passed arguments * - * @param driver Database-driver to use. For example: org.sqlite.JDBC - * @param url Location of the database. For example: jdbc:sqlite:{DIR}{NAME}.db - * @param username Username required to access the database - * @param password Password belonging to the username, may be empty - * @param isolation Isolation type. For example: SERIALIZABLE, also see TransactionIsolation - * @param logging If set to false, all logging will be disabled - * @param rebuild If set to true, all tables will be dropped and recreated. Be sure to create a backup before doing so! + * @param driver Database-driver to use. For example: org.sqlite.JDBC + * @param url Location of the database. For example: jdbc:sqlite:{DIR}{NAME}.db + * @param username Username required to access the database + * @param password Password belonging to the username, may be empty + * @param isolation Isolation type. For example: SERIALIZABLE, also see TransactionIsolation + * @param logging If set to false, all logging will be disabled + * @param rebuild If set to true, all tables will be dropped and recreated. Be sure to create a backup before doing so! */ public void initializeDatabase(String driver, String url, String username, String password, String isolation, boolean logging, boolean rebuild) { //Logging needs to be set back to the original level, no matter what happens @@ -85,11 +82,9 @@ public void initializeDatabase(String driver, String url, String username, Strin //Create all tables installDatabase(rebuild); - } - catch(Exception ex) { + } catch (Exception ex) { throw new RuntimeException("An exception has occured while initializing the database", ex); - } - finally { + } finally { //Enable all logging enableDatabaseLogging(logging); } @@ -114,7 +109,7 @@ private void prepareDatabase(String driver, String url, String username, String List> classes = getDatabaseClasses(); //Do a sanity check first - if(classes.size() == 0) { + if (classes.size() == 0) { //Exception: There is no use in continuing to load this database throw new RuntimeException("Database has been enabled, but no classes are registered to it"); } @@ -164,23 +159,20 @@ private void loadDatabase() { //Setup Ebean based on the configuration ebeanServer = EbeanServerFactory.create(serverConfig); - } - catch(Exception ex) { + } catch (Exception ex) { throw new RuntimeException("Failed to create a new instance of the EbeanServer", ex); - } - finally { + } finally { //Revert the ClassLoader back to its original value - if(currentClassLoader != null) { + if (currentClassLoader != null) { Thread.currentThread().setContextClassLoader(currentClassLoader); } //Revert the "defaultUseCaches"-field in URLConnection back to its original value try { - if(cacheField != null) { + if (cacheField != null) { cacheField.setBoolean(null, cacheValue); } - } - catch (Exception e) { + } catch (Exception e) { System.out.println("Failed to revert the \"defaultUseCaches\"-field back to its original value, URLConnection-caching remains disabled."); } } @@ -201,17 +193,16 @@ private void installDatabase(boolean rebuild) { //Query passed without throwing an exception, a database therefore already exists databaseExists = true; //break; - } - catch (Exception ex) { - System.out.println(classes.get(i).getName()+ " doesn't exist!"); + } catch (Exception ex) { + System.out.println(classes.get(i).getName() + " doesn't exist!"); DdlGenerator g = ((SpiEbeanServer) ebeanServer).getDdlGenerator(); String gs = g.generateCreateDdl(); String[] scriptStatements = gs.split(";"); //System.out.println("NAME: "+classes.get(i).getAnnotation(Table.class).name()); - for (String s : scriptStatements){ - if(s.contains("create table "+classes.get(i).getAnnotation(Table.class).name())) { - g.runScript(false, s+";"); + for (String s : scriptStatements) { + if (s.contains("create table " + classes.get(i).getAnnotation(Table.class).name())) { + g.runScript(false, s + ";"); break; } } @@ -225,7 +216,7 @@ private void installDatabase(boolean rebuild) { } //Check if the database has to be created or rebuilt - if(!rebuild && databaseExists) { + if (!rebuild && databaseExists) { return; } @@ -236,10 +227,9 @@ private void installDatabase(boolean rebuild) { //Fire "before drop" event try { beforeDropDatabase(); - } - catch(Exception ex) { + } catch (Exception ex) { //If the database exists, dropping has to be canceled to prevent data-loss - if(databaseExists) { + if (databaseExists) { throw new RuntimeException("An unexpected exception occured", ex); } } @@ -248,24 +238,22 @@ private void installDatabase(boolean rebuild) { gen.runScript(true, gen.generateDropDdl()); //If SQLite is being used, the database has to reloaded to release all resources - if(usingSQLite) { + if (usingSQLite) { loadDatabase(); } //Generate a CreateDDL-script - if(usingSQLite) { + if (usingSQLite) { //If SQLite is being used, the CreateDLL-script has to be validated and potentially fixed to be valid gen.runScript(false, validateCreateDDLSqlite(gen.generateCreateDdl())); - } - else { + } else { gen.runScript(false, gen.generateCreateDdl()); } //Fire "after create" event try { afterCreateDatabase(); - } - catch(Exception ex) { + } catch (Exception ex) { throw new RuntimeException("An unexpected exception occured", ex); } } @@ -300,12 +288,11 @@ private String validateCreateDDLSqlite(String oldScript) { scriptLines.add(currentLine.trim()); //Check if the current line is of any use - if(currentLine.startsWith("create table")) { + if (currentLine.startsWith("create table")) { //Found a table, so get its name and remember the line it has been encountered on currentTable = currentLine.split(" ", 4)[2]; foundTables.put(currentLine.split(" ", 3)[2], scriptLines.size() - 1); - } - else if(currentLine.startsWith(";") && currentTable != null && !currentTable.equals("")) { + } else if (currentLine.startsWith(";") && currentTable != null && !currentTable.equals("")) { //Found the end of a table definition, so update the entry int index = scriptLines.size() - 1; foundTables.put(currentTable, index); @@ -320,17 +307,16 @@ private String validateCreateDDLSqlite(String oldScript) { //Reset the table-tracker currentTable = null; - } - else if(currentLine.startsWith("alter table")) { + } else if (currentLine.startsWith("alter table")) { //Found a potentially unsupported action String[] alterTableLine = currentLine.split(" ", 4); - if(alterTableLine[3].startsWith("add constraint")) { + if (alterTableLine[3].startsWith("add constraint")) { //Found an unsupported action: ALTER TABLE using ADD CONSTRAINT String[] addConstraintLine = alterTableLine[3].split(" ", 4); //Check if this line can be fixed somehow - if(addConstraintLine[3].startsWith("foreign key")) { + if (addConstraintLine[3].startsWith("foreign key")) { //Calculate the index of last line of the current table int tableLastLine = foundTables.get(alterTableLine[2]) + tableOffset; @@ -344,8 +330,7 @@ else if(currentLine.startsWith("alter table")) { //Remove this line and raise the table offset because a line has been inserted scriptLines.remove(scriptLines.size() - 1); tableOffset++; - } - else { + } else { //Exception: This line cannot be fixed but is known the be unsupported by SQLite throw new RuntimeException("Unsupported action encountered: ALTER TABLE using ADD CONSTRAINT with " + addConstraintLine[3]); } @@ -355,7 +340,7 @@ else if(currentLine.startsWith("alter table")) { //Turn all the lines back into a single string String newScript = ""; - for(String newLine : scriptLines) { + for (String newLine : scriptLines) { newScript += newLine + "\n"; } @@ -364,8 +349,7 @@ else if(currentLine.startsWith("alter table")) { //Return the fixed script return newScript; - } - catch (Exception ex) { + } catch (Exception ex) { //Exception: Failed to fix the DDL or something just went plain wrong throw new RuntimeException("Failed to validate the CreateDDL-script for SQLite", ex); } @@ -373,7 +357,7 @@ else if(currentLine.startsWith("alter table")) { private void disableDatabaseLogging(boolean logging) { //If logging is allowed, nothing has to be changed - if(logging) { + if (logging) { return; } @@ -386,7 +370,7 @@ private void disableDatabaseLogging(boolean logging) { private void enableDatabaseLogging(boolean logging) { //If logging is allowed, nothing has to be changed - if(logging) { + if (logging) { return; } @@ -438,7 +422,8 @@ protected void afterCreateDatabase() { * @param dataSourceConfig * @param serverConfig */ - protected void prepareDatabaseAdditionalConfig(DataSourceConfig dataSourceConfig, ServerConfig serverConfig) {} + protected void prepareDatabaseAdditionalConfig(DataSourceConfig dataSourceConfig, ServerConfig serverConfig) { + } /** * Get the instance of the EbeanServer diff --git a/src/com/jcdesimp/landlord/persistantData/OwnedLand.java b/src/com/jcdesimp/landlord/persistantData/OwnedLand.java index 3e921b6..29a2948 100644 --- a/src/com/jcdesimp/landlord/persistantData/OwnedLand.java +++ b/src/com/jcdesimp/landlord/persistantData/OwnedLand.java @@ -5,35 +5,56 @@ * This class represents a plot of owned land. */ //import com.jcdesimp.landlord.DarkBladee12.ParticleAPI.ParticleEffect; + import com.avaje.ebean.validation.NotNull; import com.jcdesimp.landlord.Landlord; import com.jcdesimp.landlord.landManagement.Landflag; import org.bukkit.*; - -import javax.persistence.*; import org.bukkit.entity.Player; +import javax.persistence.*; import java.util.ArrayList; import java.util.List; import java.util.UUID; import static org.bukkit.Bukkit.getOfflinePlayer; -import static org.bukkit.Bukkit.getPlayer; @SuppressWarnings("UnusedDeclaration") @Entity -@Table(name="ll_land") +@Table(name = "ll_land") public class OwnedLand { + @OneToMany(cascade = CascadeType.ALL) + List friends; + @Id + private int id; + + + //Used to be the owners username + @NotNull + private String ownerName; + + + @NotNull + private int x; + + @NotNull + private int z; + + @NotNull + private String worldName; + private String permissions; + /** * Factory method that creates a new OwnedLand instance given an owner name and chunk + * * @param owner The owner of the land - * @param c The chunk this land represents + * @param c The chunk this land represents * @return OwnedLand */ - public static OwnedLand landFromProperties(Player owner, Chunk c){ + public static OwnedLand landFromProperties(Player owner, Chunk c) { OwnedLand lnd = new OwnedLand(); //System.out.println(owner.getUniqueId()); try { @@ -49,39 +70,47 @@ public static OwnedLand landFromProperties(Player owner, Chunk c){ } + public static OwnedLand getApplicableLand(Location l) { + Chunk c = l.getChunk(); + return getLandFromDatabase(c.getX(), c.getZ(), c.getWorld().getName()); + } - @Id - private int id; - - - - //Used to be the owners username - @NotNull - private String ownerName; - - - - - @NotNull - private int x; - - @NotNull - private int z; - - @NotNull - private String worldName; - - @OneToMany(cascade = CascadeType.ALL) - List friends; - - private String permissions; - + /** + * Helper method for boolean conversion + * + * @param s string to convert + * @return true or false + */ + public static boolean stringToBool(String s) { + if (s.equals("1")) + return true; + if (s.equals("0")) + return false; + throw new IllegalArgumentException(s + " is not a bool. Only 1 and 0 are."); + } + /** + * Gets land from the database + * + * @param x coord of chunk + * @param z coord of chunk + * @param worldName of chunk + * @return OwnedLand instance + */ + public static OwnedLand getLandFromDatabase(int x, int z, String worldName) { + return Landlord.getInstance().getDatabase().find(OwnedLand.class) + .where() + .eq("x", x) + .eq("z", z) + .eq("worldName", worldName) + .findUnique(); + } /** * Sets the properties of an OwnedLand instance + * * @param pUUID name of player to be set owner - * @param c chunk to be represented + * @param c chunk to be represented */ public void setProperties(UUID pUUID, Chunk c) { ownerName = pUUID.toString(); @@ -90,22 +119,22 @@ public void setProperties(UUID pUUID, Chunk c) { setWorldName(c.getWorld().getName()); } + public int getId() { + return id; + } public void setId(int id) { this.id = id; } - public int getId() { - return id; + public String getOwnerName() { + return ownerName; } public void setOwnerName(String ownerName) { this.ownerName = ownerName; } - public String getOwnerName() { - return ownerName; - } public UUID ownerUUID() { if (ownerName.length() < 32) { return UUID.randomUUID(); @@ -120,57 +149,72 @@ public UUID getOwnerUUID() { } public String getOwnerUsername() { + + //mess ready + String unknownUser = "Unknown"; + /* * ************************************* * mark for possible change !!!!!!!!! * ************************************* */ if (!getOfflinePlayer(UUID.fromString(ownerName)).hasPlayedBefore() && !getOfflinePlayer(UUID.fromString(ownerName)).isOnline()) { - return ChatColor.ITALIC+"Unknown"; + return ChatColor.ITALIC + unknownUser; } return getOfflinePlayer(UUID.fromString(ownerName)).getName(); } - public void setFriends(List friends) { - this.friends = friends; - } - public List getFriends() { return friends; } - public void setWorldName(String worldName) { - this.worldName = worldName; + public void setFriends(List friends) { + this.friends = friends; } public String getWorldName() { return worldName; } - public void setX(int x) { - this.x = x; + public void setWorldName(String worldName) { + this.worldName = worldName; } public int getX() { return x; } - public void setZ(int z) { - this.z = z; + public void setX(int x) { + this.x = x; } public int getZ() { return z; } + public void setZ(int z) { + this.z = z; + } + public int getXBlock() { - return getChunk().getBlock(0,0,0).getX(); + return getChunk().getBlock(0, 0, 0).getX(); } public int getZBlock() { - return getChunk().getBlock(0,0,0).getZ(); + return getChunk().getBlock(0, 0, 0).getZ(); } + + /* + ********************* + * Permissions Stuff * + ********************* + */ + + /*public enum LandAction { + BUILD, HARM_ANIMALS, OPEN_CONTAINERS + }*/ + public String getPermissions() { return permissions; } @@ -184,26 +228,20 @@ public Chunk getChunk() { return world.getChunkAt(x, z); } - /* - ********************* - * Permissions Stuff * - ********************* - */ - - /*public enum LandAction { - BUILD, HARM_ANIMALS, OPEN_CONTAINERS - }*/ - - public static OwnedLand getApplicableLand(Location l){ - Chunk c = l.getChunk(); - return getLandFromDatabase(c.getX(),c.getZ(),c.getWorld().getName()); + public void changePerm(int action, String group, int perm){ + String[][] np = getLandPerms(); + if(group.equals("friends")){ + np[1][action] = perm+""; + } else { + np[0][action] = perm+""; + } } - - + */ /** * Get default permission string + * * @return default permission string */ private String[][] getDefaultPerms() { @@ -211,82 +249,57 @@ private String[][] getDefaultPerms() { ArrayList friendsPerms = new ArrayList(); guestPerms.add("1"); friendsPerms.add("1"); - for(int i = 0; i<(Landlord.getInstance()).getFlagManager().numStoredPerms(); i++){ + for (int i = 0; i < (Landlord.getInstance()).getFlagManager().numStoredPerms(); i++) { guestPerms.add("0"); friendsPerms.add("1"); } - return new String[][]{guestPerms.toArray(new String[guestPerms.size()]),friendsPerms.toArray(new String[friendsPerms.size()])}; + return new String[][]{guestPerms.toArray(new String[guestPerms.size()]), friendsPerms.toArray(new String[friendsPerms.size()])}; } - - /** - * Helper method for boolean conversion - * @param s string to convert - * @return true or false - */ - public static boolean stringToBool(String s) { - if (s.equals("1")) - return true; - if (s.equals("0")) - return false; - throw new IllegalArgumentException(s+" is not a bool. Only 1 and 0 are."); - } - - /* - public void changePerm(int action, String group, int perm){ - String[][] np = getLandPerms(); - if(group.equals("friends")){ - np[1][action] = perm+""; - } else { - np[0][action] = perm+""; - } - } - */ - - public String[][] getLandPerms(){ + public String[][] getLandPerms() { String perms = getPermissions(); - if (perms==null){ + if (perms == null) { //System.out.println("Is null..."); return getDefaultPerms(); } String[] permString = perms.split("\\|"); //ArrayList permArray = new ArrayList(); ArrayList newPermString = new ArrayList(); - for (String s : permString){ + for (String s : permString) { newPermString.add(Integer.toBinaryString(Integer.parseInt(s))); } String ePerms = newPermString.get(0); - while(ePerms.length() edgeBlocks = new ArrayList(); - for(int i = 0; i<16; i++){ - for(int ii = -1; ii<=10; ii++){ + for (int i = 0; i < 16; i++) { + for (int ii = -1; ii <= 10; ii++) { - edgeBlocks.add(chunk.getBlock(i, (int) (p.getLocation().getY())+ii, 15).getLocation()); - edgeBlocks.add(chunk.getBlock(i, (int) (p.getLocation().getY())+ii, 0).getLocation()); - edgeBlocks.add(chunk.getBlock(0, (int) (p.getLocation().getY())+ii, i).getLocation()); - edgeBlocks.add(chunk.getBlock(15, (int) (p.getLocation().getY())+ii, i).getLocation()); + edgeBlocks.add(chunk.getBlock(i, (int) (p.getLocation().getY()) + ii, 15).getLocation()); + edgeBlocks.add(chunk.getBlock(i, (int) (p.getLocation().getY()) + ii, 0).getLocation()); + edgeBlocks.add(chunk.getBlock(0, (int) (p.getLocation().getY()) + ii, i).getLocation()); + edgeBlocks.add(chunk.getBlock(15, (int) (p.getLocation().getY()) + ii, i).getLocation()); } @@ -427,7 +422,7 @@ public void highlightLand(Player p, Effect e, int amt){ //BukkitScheduler scheduler = Bukkit.getServer().getScheduler(); for (Location edgeBlock : edgeBlocks) { - edgeBlock.setZ(edgeBlock.getBlockZ()+.5); + edgeBlock.setZ(edgeBlock.getBlockZ() + .5); edgeBlock.setX(edgeBlock.getBlockX() + .5); p.spigot().playEffect(edgeBlock, e, 0, 0, 0.2f, 0.2f, 0.2f, 0.2f, amt, 9); diff --git a/src/com/jcdesimp/landlord/pluginHooks/VaultHandler.java b/src/com/jcdesimp/landlord/pluginHooks/VaultHandler.java index c1ecadb..0d2c379 100644 --- a/src/com/jcdesimp/landlord/pluginHooks/VaultHandler.java +++ b/src/com/jcdesimp/landlord/pluginHooks/VaultHandler.java @@ -17,7 +17,7 @@ public VaultHandler() { } - private boolean setupEconomy(){ + private boolean setupEconomy() { RegisteredServiceProvider economyProvider = Landlord.getInstance().getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); if (economyProvider != null) { @@ -27,36 +27,29 @@ private boolean setupEconomy(){ return (economy != null); } - public boolean hasEconomy(){ + public boolean hasEconomy() { - if(economy == null){ - return false; - } - return true; + return economy != null; } - private boolean canAfford(Player p, double amt){ - if(economy.getBalance(p.getName()) >= amt){ - return true; - - } - return false; + private boolean canAfford(Player p, double amt) { + return economy.getBalance(p.getName()) >= amt; } - public boolean chargeCash(Player p, double amt){ - if(canAfford(p,amt)){ + public boolean chargeCash(Player p, double amt) { + if (canAfford(p, amt)) { EconomyResponse r = economy.withdrawPlayer(p.getName(), amt); return true; } return false; } - public boolean giveCash(Player p, double amt){ - EconomyResponse r = economy.depositPlayer(p.getName(),amt); + public boolean giveCash(Player p, double amt) { + EconomyResponse r = economy.depositPlayer(p.getName(), amt); return true; } - public String formatCash(double amt){ + public String formatCash(double amt) { return economy.format(amt); } diff --git a/src/com/jcdesimp/landlord/pluginHooks/WorldguardHandler.java b/src/com/jcdesimp/landlord/pluginHooks/WorldguardHandler.java index f6ab899..e42c6f1 100644 --- a/src/com/jcdesimp/landlord/pluginHooks/WorldguardHandler.java +++ b/src/com/jcdesimp/landlord/pluginHooks/WorldguardHandler.java @@ -4,7 +4,6 @@ import com.sk89q.worldguard.protection.managers.RegionManager; import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion; import com.sk89q.worldguard.protection.regions.ProtectedRegion; -import org.bukkit.ChatColor; import org.bukkit.Chunk; import org.bukkit.entity.Player; @@ -23,6 +22,7 @@ public class WorldguardHandler { /** * Constructor + * * @param worldguard plugin instance */ public WorldguardHandler(WorldGuardPlugin worldguard) { @@ -33,16 +33,17 @@ public WorldguardHandler(WorldGuardPlugin worldguard) { /** * Determines if a player is allowed to claim or not by * checking region intersections with their current chunk - * @param player trying to claim + * + * @param player trying to claim * @param currChunk that is being claimed * @return boolean of allowed or not */ - public boolean canClaim(Player player, Chunk currChunk){ + public boolean canClaim(Player player, Chunk currChunk) { RegionManager regionManager = worldguard.getRegionManager(player.getWorld()); //System.out.println("Has Worldguard"); - if(regionManager != null){ + if (regionManager != null) { //System.out.println("region manager not null"); - ProtectedRegion check = new ProtectedCuboidRegion("check", toVector(currChunk.getBlock(0,0,0)),toVector(currChunk.getBlock(15,127,15))); + ProtectedRegion check = new ProtectedCuboidRegion("check", toVector(currChunk.getBlock(0, 0, 0)), toVector(currChunk.getBlock(15, 127, 15))); //System.out.println(check.getMinimumPoint() +" " + check.getMaximumPoint()); diff --git a/src/config.yml b/src/config.yml index 4d399c4..0a63765 100644 --- a/src/config.yml +++ b/src/config.yml @@ -13,6 +13,8 @@ # regenOnUnclaim: false # #Show entey/exit messages when players enter/leave owned land. # showLandAlerts: true +# #File inside the "messages" folder to use as souce for all messages displayed to players. +# messagesFile: "english.yml" # Limits on amount of owned land # limits: # #Max land a regular player can own (-1 for no limit). @@ -59,6 +61,7 @@ options: enableMap: true regenOnUnclaim: false showLandAlerts: true + messagesFile: "english.yml" limits: landLimit: 10 extra: 10 diff --git a/src/messages/english.yml b/src/messages/english.yml new file mode 100644 index 0000000..a2fea0e --- /dev/null +++ b/src/messages/english.yml @@ -0,0 +1,308 @@ +# Default English messages for Landlord +# All player-facing messages can be modified here. +info: + alerts: + leaveOwnLand: "Now leaving your land." + leaveOtherLand: "Now leaving #{owner}'s land." + enterOwnLand: "Now entering your land." + enterOtherLand: "Now entering #{owner}'s land." + nextPage: "do #{label} #{cmd} #{pageNumber} for next page" + noOwner: "None" + warnings: + playerCommand: "This command can only be run by a player." + noPerms: "You do not have permission." + unknownPlayer: "That player is not recognized." + notOwner: "You do not own this land." + badPage: "That is not a valid page number." + noClaim: "You cannot claim in this world." +commands: + addFriend: + usage: "/#{label} #{cmd} " + description: "Add friend to this land." + alerts: + success: "Player #{player} is now a friend of this land." + alreadyFriend: "Player #{player} is already a friend of this land." + triggers: + - "friend" + - "addfriend" + - "trust" + claim: + usage: "/#{label} #{cmd}" + description: "Claim this chunk." + alerts: + success: "Successfully claimed chunk #{chunkCoords} in world '#{worldName}'" + cost: "Costs #{pricetag} to claim." + alreadyOwn: "You already own this land." + otherOwn: "Someone else owns this land." + noClaimZone: "You cannot claim here." + ownLimit: "You can only own #{limit} chunks of land." + claimPrice: "It costs #{cost} to purchase land." + charged: "You have been charged #{cost} to purchase land." + triggers: + - "claim" + - "buy" + - "protect" + clearWorld: + usage: "/#{label} #{cmd} [player]" + description: "Delete all land owned by a player in a world. Delete all land of a world (console only)." + alerts: + notConsole: "You can only delete entire worlds from the console." + chunkWarning: "Does not regenerate chunks." + noLand: "No land to remove." + success: "Land(s) deleted!" + triggers: + - "clearworld" + friendAll: + usage: "/#{label} #{cmd} " + description: "Add friend to all your land." + alerts: + success: "#{player} has been added as a friend to all of your land." + noLand: "You do not own any land!" + triggers: + - "friendall" + - "addfriendall" + friends: + usage: "/#{label} #{cmd}" + description: "List friends of this land." + alerts: + listHeader: "Friends of this Land" + noFriends: "This land has no friends" + online: "Online" + offline: "Offline" + triggers: + - "friends" + help: + usage: "/#{label} #{cmd} [page #]" + description: "Show this help message." + alerts: + header: "Landlord #{version} Created by #{author}" + aliases: "Aliases: #{aliases}" + triggers: + - "help" + - "?" + info: + usage: "/#{label} #{cmd}" + description: "View info about this chunk." + alerts: + landInfo: "You are in chunk #{chunkCoords} in world #{worldName} " + landOwner: "Owned by: #{ownerName}" + triggers: + - "info" + landList: + usage: "/#{label} #{cmd}" + description: "List all your own land." + alerts: + noLand: "You do not own any land!" + listHeader: "Coords - Chunk Coords - World Name" + outputHeader: "Your Owned land" + pageLabel: "Page #{pageNum}" + triggers: + - "list" + - "ls" + listPlayer: + usage: "/#{label} listplayer [page#]" + description: "List land owned by another player." + alerts: + ownsNone: "#{owner} does not own any land!" + listHeader: "Coords - Chunk Coords - World Name" + ownersLand: "#{owner}'s Owned Land" + pageNum: " Page #{pageNumber}" + nextPage: "do #{label} #{cmd} #{pageNumber} for next page" + triggers: + - "listplayer" + manage: + usage: "/#{label} #{cmd}" + description: "Manage permissions for this land." + alerts: + noLand: "There is nothing to manage!" + otherLand: "Managing someone else's land." + triggers: + - "manage" + - "edit" + - "config" + - "configure" + reload: + usage: "/#{label} #{cmd}" + description: "Reloads the Landlord config file." + alerts: + configReloaded: "Landlord config reloaded." + triggers: + - "reload" + showMap: + usage: "/#{label} #{cmd}" + description: "Toggle the land map." + alerts: + mapDisabled: "Land map is disabled." + noMap: "Map unavailable." + triggers: + - "map" + - "grid" + unclaim: + usage: "/#{label} #{cmd} [x, y] [world]." + description: "Unclaim this chunk." + alerts: + noWorld: "World #{worldName} does not exist." + landSold: "Land sold for #{amount}." + unclaimOther: "Unclaimed #{player}'s land" + unclaimed: "Successfully unclaimed chunk #{chunkCoords} in world #{worldName}." + priceWarning: "Get #{pricetag} per unclaim." + regenWarning: "Regenerates Chunk!" + triggers: + - "unclaim" + - "sell" + unfriend: + usage: "/#{label} #{cmd} " + description: "Remove friend from this land." + alerts: + notFriend: "Player #{playerName} is not a friend of this land." + unfriended: "Player #{playerName} is no longer a friend of this land." + triggers: + - "unfriend" + - "remfriend" + - "removefriend" + - "delfriend" + - "deletefriend" + - "untrust" + unfriendAll: + usage: "/#{label} #{cmd} " + description: "Remove friend from all your land." + alerts: + playerRemoved: "#{playername} has been removed as a friend from all of your land." + noLand: "You do not own any land!" + triggers: + - "unfriendall" + - "remfriendall" + - "remallfriends" + - "removeallfriends" + - "removefriendall" + - "untrustall" + - "delfriendall" + - "delallfriends" + - "deleteallfriends" + - "deletefriendall" +map: + legend: + yours: "Yours" + friends: "Friends'" + others: "Others'" + header: "Land Map" +flags: + build: + displayName: "Build" + #note that the pipe '|' notifies Landlord to use a new line for flag descriptions. + description: "Gives permission to place|and break blocks and edit|things like item frames and|note blocks." + allowedTitle: "Allowed Build" + allowedText: "can build." + deniedTitle: "Denied Build" + deniedText: "cannot build." + harmAnimals: + displayName: "Harm Animals" + description: "Gives permission to hurt or kill|pigs, sheep, cows, mooshrooms,|chickens, horses, dogs, and cats." + allowedTitle: "Allowed Animal Damage" + allowedText: "can harm animals." + deniedTitle: "Denied Animal Damage" + deniedText: "cannot harm animals." + openDoor: + displayName: "Open Doors" + description: "Gives permission to open/close doors." + allowedTitle: "Allowed to Open Doors" + allowedText: "can open doors." + deniedTitle: "Not Allowed to Open Doors" + deniedText: "cannot open doors." + pvp: + displayName: "PVP" + description: "Gives permission to attack|players on this land|" + allowedTitle: "Allowed PvP" + allowedText: "can hurt other players." + deniedTitle: "Denied PvP" + deniedText: "cannot hurt other players." + tntDamage: + displayName: "TNT Damage" + description: "Gives permission to cause block|damage with tnt." + allowedTitle: "Allowed TNT Damage" + allowedText: "can damage with TNT." + deniedTitle: "Denied TNT Damage" + deniedText: "cannot damage with TNT." + useContainers: + displayName: "Use Containers" + description: "Gives permission to use trap chests|chests, furnaces, anvils, hoppers,|droppers, dispensers, beacons,|brewing stands, cauldrons,|and Jukeboxes." + allowedTitle: "Allowed Container Usage" + allowedText: "can use containers." + deniedTitle: "Denied Container Usage" + deniedText: "cannot use containers." + useRedstone: + displayName: "Use Redstone" + description: "Gives permission to use buttons and|levers, and trip pressure plates,|and tripwires." + allowedTitle: "Allowed Redstone Usage" + allowedText: "can use redstone." + deniedTitle: "Denied Redstone Usage" + deniedText: "cannot use redstone." +event: + build: + blockPlace: "You are not allowed to build on this land." + blockBreak: "You are not allowed to break on this land." + bucketEmpty: "You cannot place that on this land." + bucketFill: "You cannot do that on this land." + hangingBreak: "You cannot break that on this land." + useArmorStand: "You cannot do that here!" + breakArmorStandWithMelee: "You cannot do that on this land." + breakArmorStandWithArrow: "You cannot do that on this land." + itemFrameRemoveWithMelee: "You cannot break that on this land." + itemFrameRemoveWithArrow: "You cannot break that on this land." + itemFrameRemoveDirectly: "You cannot break that on this land." + itemFrameRotate: "You cannot do that on this land." + paintingPlace: "You cannot place that on this land." + cropDestroy: "You are not allowed to destroy crops on this land." + useFireCharge: "You cannot do that on this land." + blockStateChange: "You cannot do that on this land." + harmAnimals: + melee: "You cannot harm animals on this land." + projectile: "You cannot harm animals on this land." + openDoor: + interact: "You cannot open doors on this land." + pvp: + melee: "You cannot harm other players on this land." + projectile: "You cannot harm other players on this land." + tntDamage: + detonate: "You cannot detonate TNT on this land." + ignite: "You are not allowed to ignite tnt on this land." + useContainers: + interact: "You are not allowed to use containers on this land." + useRedstone: + interact: "You cannot use redstone on this land." +manager: + title: "Land Manager" + toggle: "Click to toggle." + saved: "Land permissions saved!" + players: + friends: "Friends of this land" + others: "Regular players" + help: + button: "Help" + text: + - "Click each wool block" + - "to toggle a permission for a group." + - "Red wool means not allowed" + - "and green wool means allowed." + - "Mouse over each item for more information." + table: + friends: + title: "Friends" + description: + - "Permissions in this row apply to" + - "friends of this land." + others: + title: "Everyone" + description: + - "Permissions in this row apply to" + - "people that aren't friends" + - "of this land." + pagination: + next: + title: "Next Page" + description: + - "View next page of options." + previous: + title: "Previous Page" + description: + - "View previous page of options." \ No newline at end of file diff --git a/src/plugin.yml b/src/plugin.yml index f809497..f82efeb 100644 --- a/src/plugin.yml +++ b/src/plugin.yml @@ -1,6 +1,6 @@ name: Landlord main: com.jcdesimp.landlord.Landlord -version: 1.3 +version: 1.4.0 author: Jcdesimp authors: [] website: http://dev.bukkit.org/bukkit-plugins/landlord/