diff --git a/src/main/java/com/graywolf336/jail/HandCuffManager.java b/src/main/java/com/graywolf336/jail/HandCuffManager.java index 17a0ff2..2e9b240 100644 --- a/src/main/java/com/graywolf336/jail/HandCuffManager.java +++ b/src/main/java/com/graywolf336/jail/HandCuffManager.java @@ -26,72 +26,72 @@ import org.bukkit.Location; * @version 1.0.2 */ public class HandCuffManager { - private HashMap handcuffed; - private HashMap locs; - - /** Constructs a new HandCuff Manager, for handling all the handcuffing. */ - public HandCuffManager() { - this.handcuffed = new HashMap(); - this.locs = new HashMap(); - } - - /** - * Adds handcuffs to a player. - * - * @param uuid of the player - * @param location where the player was handcuffed, so they can't move - */ - public void addHandCuffs(UUID uuid, Location location) { - this.handcuffed.put(uuid, System.currentTimeMillis()); - this.locs.put(uuid, location); - } - - /** - * Removes the handcuffs from the given player. - * - * @param uuid of the person to remove the handcuffs from - */ - public void removeHandCuffs(UUID uuid) { - this.handcuffed.remove(uuid); - this.locs.remove(uuid); - } - - /** - * Gets if the player is handcuffed or not. - * - * @param uuid of the player to check - * @return true if they are handcuffed, false if not - */ - public boolean isHandCuffed(UUID uuid) { - return this.handcuffed.containsKey(uuid); - } - - /** - * Gets the next Long time we should send a message to the player. - * - * @param uuid of the player to get the name we're supposed to message them next - * @return long value of the system time in milliseconds - */ - public Long getNextMessageTime(UUID uuid) { - return this.handcuffed.get(uuid); - } - - /** - * Updates the time to the next 10 seconds from now to when we should send them a message. - * - * @param uuid of the player we're setting the message time to - */ - public void updateNextTime(UUID uuid) { - this.handcuffed.put(uuid, System.currentTimeMillis() + 10000); - } - - /** - * Gets the location where the given player was handcuffed at. - * - * @param uuid of the player get the location for - * @return the location where the player was handcuffed at - */ - public Location getLocation(UUID uuid) { - return this.locs.get(uuid); - } + private HashMap handcuffed; + private HashMap locs; + + /** Constructs a new HandCuff Manager, for handling all the handcuffing. */ + public HandCuffManager() { + this.handcuffed = new HashMap(); + this.locs = new HashMap(); + } + + /** + * Adds handcuffs to a player. + * + * @param uuid of the player + * @param location where the player was handcuffed, so they can't move + */ + public void addHandCuffs(UUID uuid, Location location) { + this.handcuffed.put(uuid, System.currentTimeMillis()); + this.locs.put(uuid, location); + } + + /** + * Removes the handcuffs from the given player. + * + * @param uuid of the person to remove the handcuffs from + */ + public void removeHandCuffs(UUID uuid) { + this.handcuffed.remove(uuid); + this.locs.remove(uuid); + } + + /** + * Gets if the player is handcuffed or not. + * + * @param uuid of the player to check + * @return true if they are handcuffed, false if not + */ + public boolean isHandCuffed(UUID uuid) { + return this.handcuffed.containsKey(uuid); + } + + /** + * Gets the next Long time we should send a message to the player. + * + * @param uuid of the player to get the name we're supposed to message them next + * @return long value of the system time in milliseconds + */ + public Long getNextMessageTime(UUID uuid) { + return this.handcuffed.get(uuid); + } + + /** + * Updates the time to the next 10 seconds from now to when we should send them a message. + * + * @param uuid of the player we're setting the message time to + */ + public void updateNextTime(UUID uuid) { + this.handcuffed.put(uuid, System.currentTimeMillis() + 10000); + } + + /** + * Gets the location where the given player was handcuffed at. + * + * @param uuid of the player get the location for + * @return the location where the player was handcuffed at + */ + public Location getLocation(UUID uuid) { + return this.locs.get(uuid); + } } diff --git a/src/main/java/com/graywolf336/jail/JailIO.java b/src/main/java/com/graywolf336/jail/JailIO.java index 4eaf921..c27ba45 100644 --- a/src/main/java/com/graywolf336/jail/JailIO.java +++ b/src/main/java/com/graywolf336/jail/JailIO.java @@ -35,1129 +35,1129 @@ import com.graywolf336.jail.enums.Settings; * */ public class JailIO { - private JailMain pl; - private FileConfiguration flat, records; - private Connection con; - private int storage; //0 = flatfile, 1 = sqlite, 2 = mysql - private String prefix; - - public JailIO(JailMain plugin) { - this.pl = plugin; - - String st = pl.getConfig().getString("storage.type", "flatfile"); - if(st.equalsIgnoreCase("sqlite")) { - storage = 1; - prefix = pl.getConfig().getString("storage.mysql.prefix"); - }else if(st.equalsIgnoreCase("mysql")) { - storage = 2; - prefix = pl.getConfig().getString("storage.mysql.prefix"); - }else { - storage = 0; - } - - pl.debug("The storage type " + st + " with the type being " + storage + "."); - if(!pl.inDebug()) pl.getLogger().info("Storage type selected: " + st); - } - - /** Loads the language file from disk, if there is none then we save the default one. */ - @SuppressWarnings("deprecation") - public void loadLanguage() { - String language = pl.getConfig().getString(Settings.LANGUAGE.getPath()); - boolean save = false; - File langFile = new File(pl.getDataFolder(), language + ".yml"); - - //File or folder already exists, let's check - if(langFile.exists()) { - if(langFile.isFile()) { - Lang.setFile(YamlConfiguration.loadConfiguration(langFile)); - pl.getLogger().info("Loaded the language: " + language); - }else { - pl.getLogger().severe("The language file can not be a folder."); - pl.getLogger().severe("As a result, we are reverting back to English as the language."); - Lang.setFile(YamlConfiguration.loadConfiguration(pl.getResource("en.yml"))); - save = true; - } - }else { - pl.getLogger().warning("Loading the default language of: en"); - pl.getLogger().warning("If you wish to change this, please rename 'en.yml' to whatever you wish and set the config value to the name of the file."); - Lang.setFile(YamlConfiguration.loadConfiguration(pl.getResource("en.yml"))); - save = true; - } - - //Make sure we have all the new language settings loaded - if(!save) save = Lang.writeNewLanguage(YamlConfiguration.loadConfiguration(pl.getResource("en.yml"))); - - //If we have flagged to save the language file, let's save it as en.yml as this flag usually means they didn't have it loaded. - if(save) { - try { - Lang.getFile().save(new File(pl.getDataFolder(), "en.yml")); - } catch (IOException e) { - pl.getLogger().severe("Unable to save the language file: " + e.getMessage()); - } - } - } - - /** Prepares the storage engine to be used, returns true if everything went good. */ - public boolean prepareStorage(boolean doInitialCreations) { - switch(storage) { - case 1: - try { - Class.forName("org.sqlite.JDBC"); - pl.getLogger().info("Connecting to the sqlite database."); - Connection sqliteConnection = DriverManager.getConnection("jdbc:sqlite:" + new File(pl.getDataFolder().getPath(), "jail3.sqlite").getPath()); - sqliteConnection.setAutoCommit(true); - this.con = sqliteConnection; - pl.debug("Connection created for sqlite."); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Sqlite driver not found, disabling the plugin."); - return false; - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Unable to connect to the sqlite database, please update your config accordingly."); - return false; - } - - break; - case 2: - try { - Class.forName("com.mysql.jdbc.Driver"); - pl.getLogger().info("Connecting to the MySQL database."); - Connection mysqlConnection = DriverManager.getConnection("jdbc:mysql://" + pl.getConfig().getString("storage.mysql.host") + ":" - + pl.getConfig().getString("storage.mysql.port") + "/" - + pl.getConfig().getString("storage.mysql.database"), pl.getConfig().getString("storage.mysql.username"), pl.getConfig().getString("storage.mysql.password")); - mysqlConnection.setAutoCommit(true); - this.con = mysqlConnection; - pl.debug("Connection created for MySQL."); - - if(doInitialCreations) createTables(); - } catch(ClassNotFoundException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("MySQL driver not found, disabling the plugin."); - return false; - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Unable to connect to the MySQL database, please update your config accordingly."); - return false; - } - - break; - default: - flat = YamlConfiguration.loadConfiguration(new File(pl.getDataFolder(), "data.yml")); - records = YamlConfiguration.loadConfiguration(new File(pl.getDataFolder(), "records.yml")); - break; - } - - return true; - } - - /** - * Gets the connection for the sqlite and mysql, null if flatfile. - * - * @return The connection for the sql database. - */ - public Connection getConnection() { - switch(storage) { - case 1: - case 2: - if(con == null) this.prepareStorage(false); - try { - if(!con.isValid(10)) this.prepareStorage(false); - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Unable to get a Sql connection, please see the error above and fix the problem."); - return null; - } - return con; - default: - return null; - } - } - - /** Closes the sql connection. */ - public void closeConnection() { - switch(storage) { - case 1: - case 2: - try { - if(con != null) { - con.close(); - con = null; - - pl.debug("Closed the SQL connection."); - } - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Unable to close the SQL connection."); - } - - break; - default: - break; - } - } - - private void createTables() { - if(con == null) { - pl.debug("The connection was null when we tried to create a table."); - return; - } - - try { - Statement st = con.createStatement(); - switch(storage){ - case 1: - //TODO: yeah big time! - break; - case 2: - String jailCreateCmd = "CREATE TABLE IF NOT EXISTS `" + prefix + "jails` (" - + "`name` VARCHAR(250) NOT NULL," - + "`world` VARCHAR(250) NOT NULL COMMENT 'The world for the top, bottom, and teleport in.'," - + "`top.x` INT NOT NULL COMMENT 'The top coordinate x.'," - + "`top.y` INT NOT NULL COMMENT 'The top coordinate y.'," - + "`top.z` INT NOT NULL COMMENT 'The top coordinate z.'," - + "`bottom.x` INT NOT NULL COMMENT 'The bottom coordinate x.'," - + "`bottom.y` INT NOT NULL COMMENT 'The bottom coordinate y.'," - + "`bottom.z` INT NOT NULL COMMENT 'The bottom coordinate z.'," - + "`tps.in.x` DOUBLE NOT NULL COMMENT 'The teleport in x coordinate.'," - + "`tps.in.y` DOUBLE NOT NULL COMMENT 'The teleport in y coordinate.'," - + "`tps.in.z` DOUBLE NOT NULL COMMENT 'The teleport in z coordinate.'," - + "`tps.in.yaw` DOUBLE NOT NULL COMMENT 'The teleport in yaw.'," - + "`tps.in.pitch` DOUBLE NOT NULL COMMENT 'The teleport in pitch.'," - + "`tps.free.world` VARCHAR(250) NOT NULL COMMENT 'The teleport for being free world.'," - + "`tps.free.x` DOUBLE NOT NULL COMMENT 'The teleport for being free x coordinate.'," - + "`tps.free.y` DOUBLE NOT NULL COMMENT 'The teleport for being free y coordinate.'," - + "`tps.free.z` DOUBLE NOT NULL COMMENT 'The teleport for being free z coordinate.'," - + "`tps.free.yaw` DOUBLE NOT NULL COMMENT 'The teleport for being free yaw.'," - + "`tps.free.pitch` DOUBLE NOT NULL COMMENT 'The teleport for being free pitch.'," - + "PRIMARY KEY (`name`)," - + "UNIQUE INDEX `name_UNIQUE` (`name` ASC))" - + "COMMENT = 'Holds all the jails for the Bukkit Jail plugin.';"; - - //pl.debug(jailCreateCmd); - st.executeUpdate(jailCreateCmd); - - String cellCreateCmd = "CREATE TABLE IF NOT EXISTS `" + prefix + "cells` (" - + "`cellid` INT NOT NULL AUTO_INCREMENT COMMENT 'The cellid for the database.'," - + "`name` VARCHAR(250) NOT NULL COMMENT 'The name of the cell.'," - + "`jail` VARCHAR(250) NOT NULL COMMENT 'The name of the jail the cell is in.'," - + "`tp.x` DOUBLE NOT NULL COMMENT 'The teleport in x coordinate.'," - + "`tp.y` DOUBLE NOT NULL COMMENT 'The teleport in y coordinate.'," - + "`tp.z` DOUBLE NOT NULL COMMENT 'The teleport in z coordinate.'," - + "`tp.yaw` DOUBLE NOT NULL COMMENT 'The teleport in yaw.'," - + "`tp.pitch` DOUBLE NOT NULL COMMENT 'The teleport in pitch.'," - + "`chest.x` INT NULL COMMENT 'The chest x coordinate.'," - + "`chest.y` INT NULL COMMENT 'The chest y coordinate.'," - + "`chest.z` INT NULL COMMENT 'The chest z coordinate.'," - + "`signs` VARCHAR(250) NULL COMMENT 'A string containing the signs.'," - + "PRIMARY KEY (`cellid`)," - + "UNIQUE INDEX `cellid_UNIQUE` (`cellid` ASC))" - + "COMMENT = 'Contains all the cells for the jails.';"; - - //pl.debug(cellCreateCmd); - st.executeUpdate(cellCreateCmd); - - String prisCreateCmd = "CREATE TABLE IF NOT EXISTS `" + prefix + "prisoners` (" - + "`uuid` VARCHAR(36) NOT NULL COMMENT 'The UUID of the prisoner.'," - + "`name` VARCHAR(16) NOT NULL COMMENT 'The name of the prisoner.'," - + "`jail` VARCHAR(250) NOT NULL COMMENT 'The jail the prisoner is in.'," - + "`cell` VARCHAR(250) NULL COMMENT 'The cell the prisoner is in.'," - + "`muted` TINYINT NOT NULL COMMENT 'Whether the player is muted or not.'," - + "`time` BIGINT NOT NULL COMMENT 'The remaining time the prisoner has.'," - + "`offlinePending` TINYINT NOT NULL COMMENT 'Whether the prisoner has something happened to them while they were offline.'," - + "`toBeTransferred` TINYINT NOT NULL COMMENT 'Whether the prisoner is to be transferred.'," - + "`jailer` VARCHAR(250) NOT NULL COMMENT 'The name of the person who jailed them.'," - + "`reason` VARCHAR(250) NOT NULL COMMENT 'The reason they are jailed.'," - + "`inventory` BLOB NULL COMMENT 'Their inventory in base64.'," - + "`armor` BLOB NULL COMMENT 'The armor in base64.'," - + "`previousLocation` VARCHAR(250) NULL COMMENT 'A string of their previous location.'," - + "`previousGameMode` VARCHAR(16) NULL COMMENT 'Their previous gamemode before they were jailed.'," - + "PRIMARY KEY (`uuid`)," - + "UNIQUE INDEX `uuid_UNIQUE` (`uuid` ASC))" - + "COMMENT = 'Contains all the prisoners, in cells and jails.';"; - - //pl.debug(prisCreateCmd); - st.executeUpdate(prisCreateCmd); - - String proCreateCmd = "CREATE TABLE IF NOT EXISTS `" + prefix + "records` (" - + "`recordid` INT NOT NULL AUTO_INCREMENT COMMENT 'Auto generated number for the records database.'," - + "`uuid` VARCHAR(36) NOT NULL COMMENT 'The UUID of the prisoner.'," - + "`username` VARCHAR(16) NOT NULL COMMENT 'The username of the prisoner.'," - + "`jailer` VARCHAR(250) NOT NULL COMMENT 'The name of the person who jailed the prisoner.'," - + "`date` VARCHAR(32) NOT NULL COMMENT 'A string of the date.'," - + "`time` BIGINT NOT NULL COMMENT 'The milliseconds they were jailed for.'," - + "`reason` VARCHAR(250) NOT NULL COMMENT 'The reason they were jailed for.'," - + "PRIMARY KEY (`recordid`)," - + "UNIQUE INDEX `recordid_UNIQUE` (`recordid` ASC))" - + "COMMENT = 'Holds a history of all the times prisoners have been jailed.'"; - - //pl.debug(proCreateCmd); - st.executeUpdate(proCreateCmd); - st.close(); - break; - default: - break; - } - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Error while creating the tables, please check the error and fix what is wrong."); - } - } - - /** - * Loads the jails, this should only be called after {@link #prepareStorage(boolean)}. - */ - public void loadJails() { - switch(storage) { - case 1: - case 2: - //load the jails from mysql and sqlite - long st = System.currentTimeMillis(); - - try { - if(con == null) this.prepareStorage(false); - PreparedStatement ps = con.prepareStatement("SELECT * FROM " + prefix + "jails"); - ResultSet set = ps.executeQuery(); - - while(set.next()) { - Jail j = new Jail(pl, set.getString("name")); - - j.setWorld(set.getString("world")); - j.setMaxPoint(new int[] { set.getInt("top.x"), set.getInt("top.y"), set.getInt("top.z") }); - j.setMinPoint(new int[] { set.getInt("bottom.x"), set.getInt("bottom.y"), set.getInt("bottom.z") }); - j.setTeleportIn(new Location(pl.getServer().getWorld(j.getWorldName()), set.getDouble("tps.in.x"), - set.getDouble("tps.in.y"), set.getDouble("tps.in.z"), - set.getFloat("tps.in.yaw"), set.getFloat("tps.in.pitch"))); - j.setTeleportFree(new Location(pl.getServer().getWorld(j.getWorldName()), set.getDouble("tps.free.x"), - set.getDouble("tps.free.y"), set.getDouble("tps.free.z"), - set.getFloat("tps.free.yaw"), set.getFloat("tps.free.pitch"))); - pl.getJailManager().addJail(j, false); - } - - set.close(); - ps.close(); - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Error while loading the jails, please check the error and fix what is wrong."); - } - - //This list contains an integer which refers to the cellid column in sql - //this list only gets populated if there are cells which reference a jail - //that doesn't exist anymore - List cellsToRemove = new LinkedList(); - - try { - if(con == null) this.prepareStorage(false); - PreparedStatement ps = con.prepareStatement("SELECT * FROM " + prefix + "cells"); - ResultSet set = ps.executeQuery(); - - while(set.next()) { - Jail j = pl.getJailManager().getJail(set.getString("jail")); - - if(j != null) { - Cell c = new Cell(set.getString("name")); - c.setTeleport(new SimpleLocation(j.getWorldName(), set.getDouble("tp.x"), set.getDouble("tp.y"), set.getDouble("tp.z"), - set.getFloat("tp.yaw"), set.getFloat("tp.pitch"))); - - c.setChestLocation(new Location(j.getWorld(), set.getInt("chest.x"), set.getInt("chest.y"), set.getInt("chest.z"))); - - String cSigns = set.getString("signs"); - if(!cSigns.isEmpty()) { - String[] signs = cSigns.split(";"); - for(String s : signs) { - String[] co = s.split(","); - c.addSign(new SimpleLocation(co[0], co[1], co[2], co[3])); - } - } - - - j.addCell(c, false); - }else { - cellsToRemove.add(set.getInt("cellid")); - } - } - - pl.debug("There are " + cellsToRemove.size() + " cells we need to remove due to being invalid."); - - set.close(); - ps.close(); - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Error while loading all of the cells, please check the error and fix what is wrong."); - } - - //Remove the invalid prisoners - if(cellsToRemove.size() != 0) { - String names = ""; - for(int c : cellsToRemove) { - if(names.isEmpty()) names = "'" + c + "'"; - else names += "," + "'" + c + "'"; - } - - try { - PreparedStatement cds = con.prepareStatement("delete from " + prefix + "cells where cellid in (" + names + ");"); - - pl.debug("Deleting old cells: 'delete from " + prefix + "cells where cellid in (" + names + ");'"); - - int count = cds.executeUpdate(); - pl.getLogger().info("Deleted " + count + " old cells which referenced a jail no longer valid: " + names); - cds.close(); - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Error while deleting the old cells which don't have a valid jail, please check the error and fix what is wrong."); - } - } - - //This list contains a string which refers to the name of the prisoner in sql - //this list only gets populated if there are prisoners which reference a jail - //that doesn't exist anymore - List prisonersToRemove = new LinkedList(); - - try { - if(con == null) this.prepareStorage(false); - PreparedStatement ps = con.prepareStatement("SELECT * FROM " + prefix + "prisoners"); - ResultSet set = ps.executeQuery(); - - while(set.next()) { - Jail j = pl.getJailManager().getJail(set.getString("jail")); - - if(j != null) { - String cellname = set.getString("cell"); - Cell c = j.getCell(cellname); - - Prisoner p = new Prisoner(set.getString("uuid"), set.getString("name"), set.getBoolean("muted"), set.getLong("time"), set.getString("jailer"), set.getString("reason")); - p.setOfflinePending(set.getBoolean("offlinePending")); - p.setToBeTransferred(set.getBoolean("toBeTransferred")); - Blob inv = set.getBlob("inventory"); - p.setInventory(new String(inv.getBytes(1, (int) inv.length()))); - Blob ar = set.getBlob("armor"); - p.setArmor(new String(ar.getBytes(1, (int)ar.length()))); - p.setPreviousPosition(set.getString("previousLocation")); - p.setPreviousGameMode(set.getString("previousGameMode")); - p.setChanged(false);//Since we just loaded the prisoner, we really don't need to save them. - - if(cellname == null || cellname.isEmpty()) { - j.addPrisoner(p); - }else if(c != null) { - c.setPrisoner(p); - }else { - //the prisoner is assigned to a cell which doesn't exist, so just put them into the jail - j.addPrisoner(p); - } - } else { - //if the jail doesn't exist, do the same as the cells - prisonersToRemove.add(set.getString("name")); - } - } - - set.close(); - ps.close(); - - pl.debug("There are " + prisonersToRemove.size() + " prisoners we need to remove due to being invalid."); - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Error while loading all of the prisoners, please check the error and fix what is wrong."); - } - - //Remove the invalid prisoners - if(prisonersToRemove.size() != 0) { - String names = ""; - for(String s : prisonersToRemove) { - if(names.isEmpty()) names = "'" + s + "'"; - else names += "," + "'" + s + "'"; - } - - try { - PreparedStatement pds = con.prepareStatement("delete from " + prefix + "prisoners where name in (" + names + ");"); - - pl.debug("Deleting old prisoners: 'delete from " + prefix + "prisoners where name in (" + names + ");'"); - - int count = pds.executeUpdate(); - pl.getLogger().info("Deleted " + count + " old prisoners which referenced a jail no longer valid: " + names); - pds.close(); - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Error while deleting the old prisoners which don't have a valid jail, please check the error and fix what is wrong."); - } - } - - pl.debug("Took " + (System.currentTimeMillis() - st) + " millis to load the jails and all the data."); - break; - default: - //load the jails from flatfile - if(flat.isConfigurationSection("jails")) { - Set jails = flat.getConfigurationSection("jails").getKeys(false); - if(!jails.isEmpty()) { - for(String name : jails) { - loadJailFromFlatFile(name); - } - } - } - break; - } - - int js = pl.getJailManager().getJails().size(); - pl.getLogger().info("Loaded " + js + (js == 1 ? " jail." : " jails.")); - - int cs = pl.getJailManager().getAllCells().size(); - pl.getLogger().info("Loaded " + cs + (cs == 1 ? " cell." : " cells.")); - - int ps = pl.getJailManager().getAllPrisoners().size(); - pl.getLogger().info("Loaded " + ps + (ps == 1 ? " prisoner." : " prisoners.")); - } - - private void loadJailFromFlatFile(String name) { - String node = "jails." + name + "."; - String cNode = node + "cells."; - Jail j = new Jail(pl, name); - - j.setWorld(flat.getString(node + "world")); - j.setMaxPoint(new int[] {flat.getInt(node + "top.x"), flat.getInt(node + "top.y"), flat.getInt(node + "top.z")}); - j.setMinPoint(new int[] {flat.getInt(node + "bottom.x"), flat.getInt(node + "bottom.y"), flat.getInt(node + "bottom.z")}); - - j.setTeleportIn(new Location( - pl.getServer().getWorld(flat.getString(node + "world")), - flat.getDouble(node + "tps.in.x"), - flat.getDouble(node + "tps.in.y"), - flat.getDouble(node + "tps.in.z"), - (float) flat.getDouble(node + "tps.in.yaw"), - (float) flat.getDouble(node + "tps.in.pitch"))); - j.setTeleportFree(new Location( - pl.getServer().getWorld(flat.getString(node + "world")), - flat.getDouble(node + "tps.free.x"), - flat.getDouble(node + "tps.free.y"), - flat.getDouble(node + "tps.free.z"), - (float) flat.getDouble(node + "tps.free.yaw"), - (float) flat.getDouble(node + "tps.free.pitch"))); - - if(flat.isConfigurationSection(node + "cells")) { - Set cells = flat.getConfigurationSection(node + "cells").getKeys(false); - if(!cells.isEmpty()) { - for(String cell : cells) { - Cell c = new Cell(cell); - String cellNode = cNode + cell + "."; - - c.setTeleport(new SimpleLocation(j.getTeleportIn().getWorld().getName(), - flat.getDouble(cellNode + "tp.x"), - flat.getDouble(cellNode + "tp.y"), - flat.getDouble(cellNode + "tp.z"), - (float) flat.getDouble(cellNode + "tp.yaw"), - (float) flat.getDouble(cellNode + "tp.pitch"))); - c.setChestLocation(new Location(j.getTeleportIn().getWorld(), - flat.getInt(cellNode + "chest.x"), - flat.getInt(cellNode + "chest.y"), - flat.getInt(cellNode + "chest.z"))); - - for(String sign : flat.getStringList(cellNode + "signs")) { - String[] arr = sign.split(","); - c.addSign(new SimpleLocation(arr[0], - Double.valueOf(arr[1]), - Double.valueOf(arr[2]), - Double.valueOf(arr[3]), - Float.valueOf(arr[4]), - Float.valueOf(arr[5]))); - } - - if(flat.contains(cellNode + "prisoner")) { - Prisoner p = new Prisoner(flat.getString(cellNode + "prisoner.uuid"), - flat.getString(cellNode + "prisoner.name"), - flat.getBoolean(cellNode + "prisoner.muted"), - flat.getLong(cellNode + "prisoner.time"), - flat.getString(cellNode + "prisoner.jailer"), - flat.getString(cellNode + "prisoner.reason")); - p.setOfflinePending(flat.getBoolean(cellNode + "prisoner.offlinePending")); - p.setToBeTransferred(flat.getBoolean(cellNode + "prisoner.toBeTransferred")); - p.setPreviousPosition(flat.getString(cellNode + "prisoner.previousLocation")); - p.setPreviousGameMode(flat.getString(cellNode + "prisoner.previousGameMode")); - p.setInventory(flat.getString(cellNode + "prisoner.inventory", "")); - p.setArmor(flat.getString(cellNode + "prisoner.armor", "")); - p.setChanged(false);//Since we just loaded the prisoner, we really don't need to save them. - c.setPrisoner(p); - } - - j.addCell(c, false); - } - } - } - - if(flat.isConfigurationSection(node + "prisoners")) { - Set prisoners = flat.getConfigurationSection(node + "prisoners").getKeys(false); - if(!prisoners.isEmpty()) { - for(String uuid : prisoners) { - String pNode = node + "prisoners." + uuid + "."; - Prisoner pris = new Prisoner(uuid, - flat.getString(pNode + "name"), - flat.getBoolean(pNode + "muted"), - flat.getLong(pNode + "time"), - flat.getString(pNode + "jailer"), - flat.getString(pNode + "reason")); - pris.setOfflinePending(flat.getBoolean(pNode + "offlinePending")); - pris.setToBeTransferred(flat.getBoolean(pNode + "toBeTransferred")); - pris.setPreviousPosition(flat.getString(pNode + "previousLocation")); - pris.setPreviousGameMode(flat.getString(pNode + "previousGameMode")); - pris.setInventory(flat.getString(pNode + "inventory", "")); - pris.setArmor(flat.getString(pNode + "armor", "")); - pris.setChanged(false);//Since we just loaded the prisoner, we really don't need to save them. - j.addPrisoner(pris); - } - } - } - - if(pl.getServer().getWorld(j.getWorldName()) != null) { - pl.getJailManager().addJail(j, false); - pl.getLogger().info("Loaded jail " + j.getName() + " with " + j.getAllPrisoners().size() + " prisoners and " + j.getCellCount() + " cells."); - } else - pl.getLogger().severe("Failed to load the jail " + j.getName() + " as the world '" + j.getWorldName() + "' does not exist (is null). Did you remove this world?"); - } - - /** Saves everything about a jail, don't usually call this. */ - public void saveEverything() { - long st = System.currentTimeMillis(); - - for(Jail j : pl.getJailManager().getJails()) { - saveJail(j); - - for(Cell c : j.getCells()) { - saveCell(j, c); - } - } - - pl.debug("Saving everything took " + (System.currentTimeMillis() - st) + " millis."); - } - - /** - * Saves the provided {@link Jail jail} to the storage system we are using. - * - * @param j The jail to save. - */ - public void saveJail(Jail j) { - switch(storage) { - case 1: - case 2: - long st = System.currentTimeMillis(); - - try { - if(con == null) this.prepareStorage(false); - PreparedStatement ps = con.prepareStatement("REPLACE INTO " - + prefix + "jails (`name`, `world`, `top.x`, `top.y`, `top.z`, `bottom.x`, `bottom.y`," - + "`bottom.z`, `tps.in.x`, `tps.in.y`, `tps.in.z`, `tps.in.yaw`, `tps.in.pitch`," - + "`tps.free.world`, `tps.free.x`, `tps.free.y`, `tps.free.z`, `tps.free.yaw`, `tps.free.pitch`)" - + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); - - ps.setString(1, j.getName()); - ps.setString(2, j.getWorldName()); - ps.setInt(3, j.getMaxPoint().getBlockX()); - ps.setInt(4, j.getMaxPoint().getBlockY()); - ps.setInt(5, j.getMaxPoint().getBlockZ()); - ps.setInt(6, j.getMinPoint().getBlockX()); - ps.setInt(7, j.getMinPoint().getBlockY()); - ps.setInt(8, j.getMinPoint().getBlockZ()); - ps.setDouble(9, j.getTeleportIn().getX()); - ps.setDouble(10, j.getTeleportIn().getY()); - ps.setDouble(11, j.getTeleportIn().getZ()); - ps.setDouble(12, j.getTeleportIn().getYaw()); - ps.setDouble(13, j.getTeleportIn().getPitch()); - ps.setString(14, j.getTeleportFree().getWorld().getName()); - ps.setDouble(15, j.getTeleportFree().getX()); - ps.setDouble(16, j.getTeleportFree().getY()); - ps.setDouble(17, j.getTeleportFree().getZ()); - ps.setDouble(18, j.getTeleportFree().getYaw()); - ps.setDouble(19, j.getTeleportFree().getPitch()); - - ps.executeUpdate(); - ps.close(); - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Error while saving the Jail '" + j.getName() + "' (not updating the prisoners), please check the error and fix what is wrong."); - } - - try { - if(con == null) this.prepareStorage(false); - - for(Cell c : j.getCells()) { - if(c.hasPrisoner() && c.getPrisoner().wasChanged()) { - Prisoner p = c.getPrisoner(); - PreparedStatement pPS = con.prepareStatement("REPLACE INTO `" + prefix + "prisoners` (`uuid`, `name`, `jail`, `cell`, `muted`, `time`," - + "`offlinePending`, `toBeTransferred`, `jailer`, `reason`, `inventory`, `armor`, `previousLocation`, `previousGameMode`)" - + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); - pPS.setString(1, p.getUUID().toString()); - pPS.setString(2, p.getLastKnownName()); - pPS.setString(3, j.getName()); - pPS.setString(4, c.getName()); - pPS.setBoolean(5, p.isMuted()); - pPS.setFloat(6, p.getRemainingTime()); - pPS.setBoolean(7, p.isOfflinePending()); - pPS.setBoolean(8, p.isToBeTransferred()); - pPS.setString(9, p.getJailer()); - pPS.setString(10, p.getReason()); - pPS.setBytes(11, p.getInventory().getBytes()); - pPS.setBytes(12, p.getArmor().getBytes()); - pPS.setString(13, p.getPreviousLocationString()); - pPS.setString(14, p.getPreviousGameMode().toString()); - - pPS.executeUpdate(); - pPS.close(); - - p.setChanged(false);//Since we just saved the prisoner - } - } - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Error while saving the cells of the Jail '" + j.getName() + "', please check the error and fix what is wrong."); - } - - try { - if(con == null) this.prepareStorage(false); - - for(Prisoner p : j.getPrisonersNotInCells().values()) { - if(p.wasChanged()) { - PreparedStatement pPS = con.prepareStatement("REPLACE INTO `" + prefix + "prisoners` (`uuid`, `name`, `jail`, `cell`, `muted`, `time`," - + "`offlinePending`, `toBeTransferred`, `jailer`, `reason`, `inventory`, `armor`, `previousLocation`, `previousGameMode`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); - pPS.setString(1, p.getUUID().toString()); - pPS.setString(2, p.getLastKnownName()); - pPS.setString(3, j.getName()); - pPS.setString(4, ""); - pPS.setBoolean(5, p.isMuted()); - pPS.setFloat(6, p.getRemainingTime()); - pPS.setBoolean(7, p.isOfflinePending()); - pPS.setBoolean(8, p.isToBeTransferred()); - pPS.setString(9, p.getJailer()); - pPS.setString(10, p.getReason()); - pPS.setBytes(11, p.getInventory().getBytes()); - pPS.setBytes(12, p.getArmor().getBytes()); - pPS.setString(13, p.getPreviousLocationString()); - pPS.setString(14, p.getPreviousGameMode().toString()); - - pPS.executeUpdate(); - pPS.close(); - p.setChanged(false);//Since we just saved the prisoner - } - } - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Error while saving the prisoners of the Jail '" + j.getName() + "', please check the error and fix what is wrong."); - } - - pl.debug("Took " + (System.currentTimeMillis() - st) + " millis to save the jail " + j.getName() + "."); - break; - default: - if(flat != null) { - String node = "jails." + j.getName() + "."; - - //Corners - flat.set(node + "world", j.getWorldName()); - flat.set(node + "top.x", j.getMaxPoint().getBlockX()); - flat.set(node + "top.y", j.getMaxPoint().getBlockY()); - flat.set(node + "top.z", j.getMaxPoint().getBlockZ()); - flat.set(node + "bottom.x", j.getMinPoint().getBlockX()); - flat.set(node + "bottom.y", j.getMinPoint().getBlockY()); - flat.set(node + "bottom.z", j.getMinPoint().getBlockZ()); - - //Tele in - flat.set(node + "tps.in.x", j.getTeleportIn().getX()); - flat.set(node + "tps.in.y", j.getTeleportIn().getY()); - flat.set(node + "tps.in.z", j.getTeleportIn().getZ()); - flat.set(node + "tps.in.yaw", j.getTeleportIn().getYaw()); - flat.set(node + "tps.in.pitch", j.getTeleportIn().getPitch()); - - //Tele out - flat.set(node + "tps.free.world", j.getTeleportFree().getWorld().getName()); - flat.set(node + "tps.free.x", j.getTeleportFree().getX()); - flat.set(node + "tps.free.y", j.getTeleportFree().getY()); - flat.set(node + "tps.free.z", j.getTeleportFree().getZ()); - flat.set(node + "tps.free.yaw", j.getTeleportFree().getYaw()); - flat.set(node + "tps.free.pitch", j.getTeleportFree().getPitch()); - - //Set all the cells to nothing, then we save each of them so no cells are left behind - flat.set(node + "cells", null); - for(Cell c : j.getCells()) { - String cNode = node + "cells." + c.getName() + "."; - - if(c.getTeleport() != null) { - flat.set(cNode + "tp.x", c.getTeleport().getX()); - flat.set(cNode + "tp.y", c.getTeleport().getY()); - flat.set(cNode + "tp.z", c.getTeleport().getZ()); - flat.set(cNode + "tp.yaw", c.getTeleport().getYaw()); - flat.set(cNode + "tp.pitch", c.getTeleport().getPitch()); - } - - if(c.getChestLocation() != null) { - flat.set(cNode + "chest.x", c.getChestLocation().getBlockX()); - flat.set(cNode + "chest.y", c.getChestLocation().getBlockY()); - flat.set(cNode + "chest.z", c.getChestLocation().getBlockZ()); - } - - String[] signs = new String[c.getSigns().size()]; - int count = 0; - for(SimpleLocation loc : c.getSigns()) { - signs[count] = loc.toString(); - count++; - } - - flat.set(cNode + "signs", signs); - - if(c.getPrisoner() != null) { - Prisoner p = c.getPrisoner(); - flat.set(cNode + "prisoner.uuid", p.getUUID().toString()); - flat.set(cNode + "prisoner.name", p.getLastKnownName()); - flat.set(cNode + "prisoner.muted", p.isMuted()); - flat.set(cNode + "prisoner.time", p.getRemainingTime()); - flat.set(cNode + "prisoner.offlinePending", p.isOfflinePending()); - flat.set(cNode + "prisoner.toBeTransferred", p.isToBeTransferred()); - flat.set(cNode + "prisoner.jailer", p.getJailer()); - flat.set(cNode + "prisoner.reason", p.getReason()); - flat.set(cNode + "prisoner.inventory", p.getInventory()); - flat.set(cNode + "prisoner.armor", p.getArmor()); - if(p.getPreviousLocationString() != null) - flat.set(cNode + "prisoner.previousLocation", p.getPreviousLocationString()); - if(p.getPreviousGameMode() != null) - flat.set(cNode + "prisoner.previousGameMode", p.getPreviousGameMode().toString()); - } - } - - //Null all the prisoners out before we save them again, this way no prisoners are left behind - flat.set(node + "prisoners", null); - for(Prisoner p : j.getPrisonersNotInCells().values()) { - String pNode = node + "prisoners." + p.getUUID().toString() + "."; - flat.set(pNode + "name", p.getLastKnownName()); - flat.set(pNode + "muted", p.isMuted()); - flat.set(pNode + "time", p.getRemainingTime()); - flat.set(pNode + "offlinePending", p.isOfflinePending()); - flat.set(pNode + "toBeTransferred", p.isToBeTransferred()); - flat.set(pNode + "jailer", p.getJailer()); - flat.set(pNode + "reason", p.getReason()); - flat.set(pNode + "inventory", p.getInventory()); - flat.set(pNode + "armor", p.getArmor()); - if(p.getPreviousLocationString() != null) - flat.set(pNode + "previousLocation", p.getPreviousLocationString()); - if(p.getPreviousGameMode() != null) - flat.set(pNode + "previousGameMode", p.getPreviousGameMode().toString()); - } - - try { - flat.save(new File(pl.getDataFolder(), "data.yml")); - } catch (IOException e) { - pl.getLogger().severe("Unable to save the Jail data: " + e.getMessage()); - } - }else { - pl.getLogger().severe("Storage not enabled, could not save the jail " + j.getName()); - } - break; - } - } - - public void saveCell(Jail j, Cell c) { - switch(storage) { - case 1: - case 2: - try { - if(con == null) this.prepareStorage(false); - - PreparedStatement cPS = con.prepareStatement("INSERT INTO `" + prefix + "cells` (`name`, `jail`, `tp.x`, `tp.y`, `tp.z`, `tp.yaw`," - + "`tp.pitch`, `chest.x`, `chest.y`, `chest.z`, `signs`) VALUES (?,?,?,?,?,?,?,?,?,?,?)"); - - cPS.setString(1, c.getName()); - cPS.setString(2, j.getName()); - cPS.setDouble(3, c.getTeleport().getX()); - cPS.setDouble(4, c.getTeleport().getY()); - cPS.setDouble(5, c.getTeleport().getZ()); - cPS.setDouble(6, c.getTeleport().getYaw()); - cPS.setDouble(7, c.getTeleport().getPitch()); - - if(c.hasChest()) { - cPS.setInt(8, c.getChestLocation().getBlockX()); - cPS.setInt(9, c.getChestLocation().getBlockY()); - cPS.setInt(10, c.getChestLocation().getBlockZ()); - }else { - cPS.setNull(8, java.sql.Types.INTEGER); - cPS.setNull(9, java.sql.Types.INTEGER); - cPS.setNull(10, java.sql.Types.INTEGER); - } - - cPS.setString(11, c.getSignString()); - - cPS.executeUpdate(); - cPS.close(); - - if(c.hasPrisoner()) { - Prisoner p = c.getPrisoner(); - PreparedStatement pPS = con.prepareStatement("REPLACE INTO `" + prefix + "prisoners` (`uuid`, `name`, `jail`, `cell`, `muted`, `time`," - + "`offlinePending`, `toBeTransferred`, `jailer`, `reason`, `inventory`, `armor`, `previousLocation`, `previousGameMode`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); - pPS.setString(1, p.getUUID().toString()); - pPS.setString(2, p.getLastKnownName()); - pPS.setString(3, j.getName()); - pPS.setString(4, c.getName()); - pPS.setBoolean(5, p.isMuted()); - pPS.setFloat(6, p.getRemainingTime()); - pPS.setBoolean(7, p.isOfflinePending()); - pPS.setBoolean(8, p.isToBeTransferred()); - pPS.setString(9, p.getJailer()); - pPS.setString(10, p.getReason()); - pPS.setBytes(11, p.getInventory().getBytes()); - pPS.setBytes(12, p.getArmor().getBytes()); - pPS.setString(13, p.getPreviousLocationString()); - pPS.setString(14, p.getPreviousGameMode().toString()); - - pPS.executeUpdate(); - pPS.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Error while saving the cell '" + c.getName() + "' of the Jail '" + j.getName() + "', please check the error and fix what is wrong."); - } - - break; - default: - this.saveJail(j); - break; - } - } - - /** - * Removes the prisoner from the storage system. - * - * @param j the jail which the prisoner is in. - * @param p the prisoner data - */ - public void removePrisoner(Jail j, Prisoner p) { - this.removePrisoner(j, null, p); - } - - /** - * Removes the prisoner from the storage system. - * - * @param j the jail which the prisoner is in. - * @param c the cell which the prisoner is in, null if none - * @param p the prisoner data - */ - public void removePrisoner(Jail j, Cell c, Prisoner p) { - switch(storage) { - case 1: - case 2: - try { - PreparedStatement pp = con.prepareStatement("delete from `" + prefix + "prisoners` where uuid = ? limit 1;"); - pp.setString(1, p.getUUID().toString()); - - pl.debug("Removing " + p.getLastKnownName() + " (" + p.getUUID().toString() + ") from MySQL database."); - - pp.executeUpdate(); - pp.close(); - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Error while removing the prisoner '" + p.getLastKnownName() + "' (" + p.getUUID().toString() + ") from the database, please check the error and fix what is wrong."); - } - break; - default: - if(c == null) - flat.set("jails." + j.getName() + ".prisoners." + p.getUUID().toString(), null); - else - flat.set("jails." + j.getName() + "." + c.getName() + ".prisoner", null); - - try { - flat.save(new File(pl.getDataFolder(), "data.yml")); - } catch (IOException e) { - pl.getLogger().severe("Unable to save the Jail data: " + e.getMessage()); - } - break; - } - } - - /** - * Removes the provided cell from the jail. - * - * @param j instance of the jail the cell is in - * @param c instance of the cell we are removing - */ - public void removeCell(Jail j, Cell c) { - //Clear the inventory before we delete it - if(c.hasChest()) c.getChest().getInventory().clear(); - - //transfer the prisoner if it has one - if(c.hasPrisoner()) { - pl.getLogger().warning("Removing of cell '" + c.getName() + "' from the jail '" + j.getName() + "' failed as it has a prisoner."); - return; - } - - switch(storage) { - case 1: - case 2: - try { - PreparedStatement p = con.prepareStatement("delete from `" + prefix + "cells` where name = ? and jail = ? limit 1;"); - p.setString(1, c.getName()); - p.setString(2, j.getName()); - - p.executeUpdate(); - p.close(); - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Error while removing the cell '" + c.getName() + "' from the Jail '" + j.getName() + "', please check the error and fix what is wrong."); - } - break; - default: - if(flat != null) { - flat.set("jails." + j.getName() + "cells." + c.getName(), null); - - try { - flat.save(new File(pl.getDataFolder(), "data.yml")); - } catch (IOException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Removing of the cell '" + c.getName() + "' from the jail '" + j.getName() + "' errored out while on saving."); - } - } - break; - } - } - - /** - * Removes a jail from the storage system. - * - * @param j the jail instance to remove. - */ - public void removeJail(Jail j) { - String name = j.getName(); - - switch(storage) { - case 1: - case 2: - for(Cell c : j.getCells()) { - removeCell(j, c); - } - - try { - PreparedStatement p = con.prepareStatement("delete from `" + prefix + "jails` where name = ?"); - p.setString(1, name); - - p.executeUpdate(); - p.close(); - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Error while removing the Jail '" + j.getName() + "', please check the error and fix what is wrong."); - } - break; - default: - flat.set("jails." + name, null); - - try { - flat.save(new File(pl.getDataFolder(), "data.yml")); - } catch (IOException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Removing of the jail '" + j.getName() + "' errored out while on saving."); - } - break; - } - } - - /** - * Adds an entry to the database/file for the user, logging when they was jailed. - * - * @param uuid of the player - * @param username of the player - * @param jailer who jailed them - * @param date string of when they are jailed - * @param time of the player's sentence - * @param reason the player is jailed - */ - public void addRecordEntry(String uuid, String username, String jailer, String date, long time, String reason) { - switch(storage) { - case 1: - break; - case 2: - try { - PreparedStatement p = con.prepareStatement("insert into `" + prefix + "records` (`uuid`, `username`, `jailer`, `date`, `time`, `reason`) VALUES (?,?,?,?,?,?);"); - p.setString(1, uuid); - p.setString(2, username); - p.setString(3, jailer); - p.setString(4, date); - p.setLong(5, time); - p.setString(6, reason); - - p.executeUpdate(); - p.close(); - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Error while adding a record entry for '" + username + "', please check the error and fix what is wrong."); - } - break; - default: - if(records == null) records = YamlConfiguration.loadConfiguration(new File(pl.getDataFolder(), "records.yml")); - - List previous = records.getStringList(uuid); - previous.add(Lang.RECORDENTRY.get(new String[] { date, username, jailer, String.valueOf(time), reason, uuid })); - - records.set(username, previous); - - try { - records.save(new File(pl.getDataFolder(), "records.yml")); - } catch (IOException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Saving the records.yml file failed while putting an entry in for '" + username + "'."); - } - break; - } - } - - /** - * Gets all the record entries for the given player. - * - * @param username the of the prisoner's records to get. - * @return A List of strings containing the record entries. - * @deprecated This calls getOfflinePlayer which is a blocking call from Bukkit - */ - public List getRecordEntries(String username) { - UUID uuid = pl.getServer().getOfflinePlayer(username).getUniqueId(); - List entries = new ArrayList(); - - switch(storage) { - case 1: - break; - case 2: - try { - PreparedStatement ps = con.prepareStatement("SELECT * FROM " + prefix + "records where uuid = ?"); - ps.setString(1, uuid.toString()); - ResultSet set = ps.executeQuery(); - - while(set.next()) { - entries.add(Lang.RECORDENTRY.get(new String[] { set.getString("date"), set.getString("username"), set.getString("jailer"), String.valueOf(set.getLong("time")), set.getString("reason") })); - } - - set.close(); - ps.close(); - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Error while getting all the record entries for '" + uuid + "', please check the error and fix what is wrong."); - } - break; - default: - if(records == null) records = YamlConfiguration.loadConfiguration(new File(pl.getDataFolder(), "records.yml")); - - entries = records.getStringList(uuid.toString()); - break; - } - - return entries; - } + private JailMain pl; + private FileConfiguration flat, records; + private Connection con; + private int storage; //0 = flatfile, 1 = sqlite, 2 = mysql + private String prefix; + + public JailIO(JailMain plugin) { + this.pl = plugin; + + String st = pl.getConfig().getString("storage.type", "flatfile"); + if(st.equalsIgnoreCase("sqlite")) { + storage = 1; + prefix = pl.getConfig().getString("storage.mysql.prefix"); + }else if(st.equalsIgnoreCase("mysql")) { + storage = 2; + prefix = pl.getConfig().getString("storage.mysql.prefix"); + }else { + storage = 0; + } + + pl.debug("The storage type " + st + " with the type being " + storage + "."); + if(!pl.inDebug()) pl.getLogger().info("Storage type selected: " + st); + } + + /** Loads the language file from disk, if there is none then we save the default one. */ + @SuppressWarnings("deprecation") + public void loadLanguage() { + String language = pl.getConfig().getString(Settings.LANGUAGE.getPath()); + boolean save = false; + File langFile = new File(pl.getDataFolder(), language + ".yml"); + + //File or folder already exists, let's check + if(langFile.exists()) { + if(langFile.isFile()) { + Lang.setFile(YamlConfiguration.loadConfiguration(langFile)); + pl.getLogger().info("Loaded the language: " + language); + }else { + pl.getLogger().severe("The language file can not be a folder."); + pl.getLogger().severe("As a result, we are reverting back to English as the language."); + Lang.setFile(YamlConfiguration.loadConfiguration(pl.getResource("en.yml"))); + save = true; + } + }else { + pl.getLogger().warning("Loading the default language of: en"); + pl.getLogger().warning("If you wish to change this, please rename 'en.yml' to whatever you wish and set the config value to the name of the file."); + Lang.setFile(YamlConfiguration.loadConfiguration(pl.getResource("en.yml"))); + save = true; + } + + //Make sure we have all the new language settings loaded + if(!save) save = Lang.writeNewLanguage(YamlConfiguration.loadConfiguration(pl.getResource("en.yml"))); + + //If we have flagged to save the language file, let's save it as en.yml as this flag usually means they didn't have it loaded. + if(save) { + try { + Lang.getFile().save(new File(pl.getDataFolder(), "en.yml")); + } catch (IOException e) { + pl.getLogger().severe("Unable to save the language file: " + e.getMessage()); + } + } + } + + /** Prepares the storage engine to be used, returns true if everything went good. */ + public boolean prepareStorage(boolean doInitialCreations) { + switch(storage) { + case 1: + try { + Class.forName("org.sqlite.JDBC"); + pl.getLogger().info("Connecting to the sqlite database."); + Connection sqliteConnection = DriverManager.getConnection("jdbc:sqlite:" + new File(pl.getDataFolder().getPath(), "jail3.sqlite").getPath()); + sqliteConnection.setAutoCommit(true); + this.con = sqliteConnection; + pl.debug("Connection created for sqlite."); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Sqlite driver not found, disabling the plugin."); + return false; + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Unable to connect to the sqlite database, please update your config accordingly."); + return false; + } + + break; + case 2: + try { + Class.forName("com.mysql.jdbc.Driver"); + pl.getLogger().info("Connecting to the MySQL database."); + Connection mysqlConnection = DriverManager.getConnection("jdbc:mysql://" + pl.getConfig().getString("storage.mysql.host") + ":" + + pl.getConfig().getString("storage.mysql.port") + "/" + + pl.getConfig().getString("storage.mysql.database"), pl.getConfig().getString("storage.mysql.username"), pl.getConfig().getString("storage.mysql.password")); + mysqlConnection.setAutoCommit(true); + this.con = mysqlConnection; + pl.debug("Connection created for MySQL."); + + if(doInitialCreations) createTables(); + } catch(ClassNotFoundException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("MySQL driver not found, disabling the plugin."); + return false; + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Unable to connect to the MySQL database, please update your config accordingly."); + return false; + } + + break; + default: + flat = YamlConfiguration.loadConfiguration(new File(pl.getDataFolder(), "data.yml")); + records = YamlConfiguration.loadConfiguration(new File(pl.getDataFolder(), "records.yml")); + break; + } + + return true; + } + + /** + * Gets the connection for the sqlite and mysql, null if flatfile. + * + * @return The connection for the sql database. + */ + public Connection getConnection() { + switch(storage) { + case 1: + case 2: + if(con == null) this.prepareStorage(false); + try { + if(!con.isValid(10)) this.prepareStorage(false); + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Unable to get a Sql connection, please see the error above and fix the problem."); + return null; + } + return con; + default: + return null; + } + } + + /** Closes the sql connection. */ + public void closeConnection() { + switch(storage) { + case 1: + case 2: + try { + if(con != null) { + con.close(); + con = null; + + pl.debug("Closed the SQL connection."); + } + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Unable to close the SQL connection."); + } + + break; + default: + break; + } + } + + private void createTables() { + if(con == null) { + pl.debug("The connection was null when we tried to create a table."); + return; + } + + try { + Statement st = con.createStatement(); + switch(storage){ + case 1: + //TODO: yeah big time! + break; + case 2: + String jailCreateCmd = "CREATE TABLE IF NOT EXISTS `" + prefix + "jails` (" + + "`name` VARCHAR(250) NOT NULL," + + "`world` VARCHAR(250) NOT NULL COMMENT 'The world for the top, bottom, and teleport in.'," + + "`top.x` INT NOT NULL COMMENT 'The top coordinate x.'," + + "`top.y` INT NOT NULL COMMENT 'The top coordinate y.'," + + "`top.z` INT NOT NULL COMMENT 'The top coordinate z.'," + + "`bottom.x` INT NOT NULL COMMENT 'The bottom coordinate x.'," + + "`bottom.y` INT NOT NULL COMMENT 'The bottom coordinate y.'," + + "`bottom.z` INT NOT NULL COMMENT 'The bottom coordinate z.'," + + "`tps.in.x` DOUBLE NOT NULL COMMENT 'The teleport in x coordinate.'," + + "`tps.in.y` DOUBLE NOT NULL COMMENT 'The teleport in y coordinate.'," + + "`tps.in.z` DOUBLE NOT NULL COMMENT 'The teleport in z coordinate.'," + + "`tps.in.yaw` DOUBLE NOT NULL COMMENT 'The teleport in yaw.'," + + "`tps.in.pitch` DOUBLE NOT NULL COMMENT 'The teleport in pitch.'," + + "`tps.free.world` VARCHAR(250) NOT NULL COMMENT 'The teleport for being free world.'," + + "`tps.free.x` DOUBLE NOT NULL COMMENT 'The teleport for being free x coordinate.'," + + "`tps.free.y` DOUBLE NOT NULL COMMENT 'The teleport for being free y coordinate.'," + + "`tps.free.z` DOUBLE NOT NULL COMMENT 'The teleport for being free z coordinate.'," + + "`tps.free.yaw` DOUBLE NOT NULL COMMENT 'The teleport for being free yaw.'," + + "`tps.free.pitch` DOUBLE NOT NULL COMMENT 'The teleport for being free pitch.'," + + "PRIMARY KEY (`name`)," + + "UNIQUE INDEX `name_UNIQUE` (`name` ASC))" + + "COMMENT = 'Holds all the jails for the Bukkit Jail plugin.';"; + + //pl.debug(jailCreateCmd); + st.executeUpdate(jailCreateCmd); + + String cellCreateCmd = "CREATE TABLE IF NOT EXISTS `" + prefix + "cells` (" + + "`cellid` INT NOT NULL AUTO_INCREMENT COMMENT 'The cellid for the database.'," + + "`name` VARCHAR(250) NOT NULL COMMENT 'The name of the cell.'," + + "`jail` VARCHAR(250) NOT NULL COMMENT 'The name of the jail the cell is in.'," + + "`tp.x` DOUBLE NOT NULL COMMENT 'The teleport in x coordinate.'," + + "`tp.y` DOUBLE NOT NULL COMMENT 'The teleport in y coordinate.'," + + "`tp.z` DOUBLE NOT NULL COMMENT 'The teleport in z coordinate.'," + + "`tp.yaw` DOUBLE NOT NULL COMMENT 'The teleport in yaw.'," + + "`tp.pitch` DOUBLE NOT NULL COMMENT 'The teleport in pitch.'," + + "`chest.x` INT NULL COMMENT 'The chest x coordinate.'," + + "`chest.y` INT NULL COMMENT 'The chest y coordinate.'," + + "`chest.z` INT NULL COMMENT 'The chest z coordinate.'," + + "`signs` VARCHAR(250) NULL COMMENT 'A string containing the signs.'," + + "PRIMARY KEY (`cellid`)," + + "UNIQUE INDEX `cellid_UNIQUE` (`cellid` ASC))" + + "COMMENT = 'Contains all the cells for the jails.';"; + + //pl.debug(cellCreateCmd); + st.executeUpdate(cellCreateCmd); + + String prisCreateCmd = "CREATE TABLE IF NOT EXISTS `" + prefix + "prisoners` (" + + "`uuid` VARCHAR(36) NOT NULL COMMENT 'The UUID of the prisoner.'," + + "`name` VARCHAR(16) NOT NULL COMMENT 'The name of the prisoner.'," + + "`jail` VARCHAR(250) NOT NULL COMMENT 'The jail the prisoner is in.'," + + "`cell` VARCHAR(250) NULL COMMENT 'The cell the prisoner is in.'," + + "`muted` TINYINT NOT NULL COMMENT 'Whether the player is muted or not.'," + + "`time` BIGINT NOT NULL COMMENT 'The remaining time the prisoner has.'," + + "`offlinePending` TINYINT NOT NULL COMMENT 'Whether the prisoner has something happened to them while they were offline.'," + + "`toBeTransferred` TINYINT NOT NULL COMMENT 'Whether the prisoner is to be transferred.'," + + "`jailer` VARCHAR(250) NOT NULL COMMENT 'The name of the person who jailed them.'," + + "`reason` VARCHAR(250) NOT NULL COMMENT 'The reason they are jailed.'," + + "`inventory` BLOB NULL COMMENT 'Their inventory in base64.'," + + "`armor` BLOB NULL COMMENT 'The armor in base64.'," + + "`previousLocation` VARCHAR(250) NULL COMMENT 'A string of their previous location.'," + + "`previousGameMode` VARCHAR(16) NULL COMMENT 'Their previous gamemode before they were jailed.'," + + "PRIMARY KEY (`uuid`)," + + "UNIQUE INDEX `uuid_UNIQUE` (`uuid` ASC))" + + "COMMENT = 'Contains all the prisoners, in cells and jails.';"; + + //pl.debug(prisCreateCmd); + st.executeUpdate(prisCreateCmd); + + String proCreateCmd = "CREATE TABLE IF NOT EXISTS `" + prefix + "records` (" + + "`recordid` INT NOT NULL AUTO_INCREMENT COMMENT 'Auto generated number for the records database.'," + + "`uuid` VARCHAR(36) NOT NULL COMMENT 'The UUID of the prisoner.'," + + "`username` VARCHAR(16) NOT NULL COMMENT 'The username of the prisoner.'," + + "`jailer` VARCHAR(250) NOT NULL COMMENT 'The name of the person who jailed the prisoner.'," + + "`date` VARCHAR(32) NOT NULL COMMENT 'A string of the date.'," + + "`time` BIGINT NOT NULL COMMENT 'The milliseconds they were jailed for.'," + + "`reason` VARCHAR(250) NOT NULL COMMENT 'The reason they were jailed for.'," + + "PRIMARY KEY (`recordid`)," + + "UNIQUE INDEX `recordid_UNIQUE` (`recordid` ASC))" + + "COMMENT = 'Holds a history of all the times prisoners have been jailed.'"; + + //pl.debug(proCreateCmd); + st.executeUpdate(proCreateCmd); + st.close(); + break; + default: + break; + } + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Error while creating the tables, please check the error and fix what is wrong."); + } + } + + /** + * Loads the jails, this should only be called after {@link #prepareStorage(boolean)}. + */ + public void loadJails() { + switch(storage) { + case 1: + case 2: + //load the jails from mysql and sqlite + long st = System.currentTimeMillis(); + + try { + if(con == null) this.prepareStorage(false); + PreparedStatement ps = con.prepareStatement("SELECT * FROM " + prefix + "jails"); + ResultSet set = ps.executeQuery(); + + while(set.next()) { + Jail j = new Jail(pl, set.getString("name")); + + j.setWorld(set.getString("world")); + j.setMaxPoint(new int[] { set.getInt("top.x"), set.getInt("top.y"), set.getInt("top.z") }); + j.setMinPoint(new int[] { set.getInt("bottom.x"), set.getInt("bottom.y"), set.getInt("bottom.z") }); + j.setTeleportIn(new Location(pl.getServer().getWorld(j.getWorldName()), set.getDouble("tps.in.x"), + set.getDouble("tps.in.y"), set.getDouble("tps.in.z"), + set.getFloat("tps.in.yaw"), set.getFloat("tps.in.pitch"))); + j.setTeleportFree(new Location(pl.getServer().getWorld(j.getWorldName()), set.getDouble("tps.free.x"), + set.getDouble("tps.free.y"), set.getDouble("tps.free.z"), + set.getFloat("tps.free.yaw"), set.getFloat("tps.free.pitch"))); + pl.getJailManager().addJail(j, false); + } + + set.close(); + ps.close(); + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Error while loading the jails, please check the error and fix what is wrong."); + } + + //This list contains an integer which refers to the cellid column in sql + //this list only gets populated if there are cells which reference a jail + //that doesn't exist anymore + List cellsToRemove = new LinkedList(); + + try { + if(con == null) this.prepareStorage(false); + PreparedStatement ps = con.prepareStatement("SELECT * FROM " + prefix + "cells"); + ResultSet set = ps.executeQuery(); + + while(set.next()) { + Jail j = pl.getJailManager().getJail(set.getString("jail")); + + if(j != null) { + Cell c = new Cell(set.getString("name")); + c.setTeleport(new SimpleLocation(j.getWorldName(), set.getDouble("tp.x"), set.getDouble("tp.y"), set.getDouble("tp.z"), + set.getFloat("tp.yaw"), set.getFloat("tp.pitch"))); + + c.setChestLocation(new Location(j.getWorld(), set.getInt("chest.x"), set.getInt("chest.y"), set.getInt("chest.z"))); + + String cSigns = set.getString("signs"); + if(!cSigns.isEmpty()) { + String[] signs = cSigns.split(";"); + for(String s : signs) { + String[] co = s.split(","); + c.addSign(new SimpleLocation(co[0], co[1], co[2], co[3])); + } + } + + + j.addCell(c, false); + }else { + cellsToRemove.add(set.getInt("cellid")); + } + } + + pl.debug("There are " + cellsToRemove.size() + " cells we need to remove due to being invalid."); + + set.close(); + ps.close(); + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Error while loading all of the cells, please check the error and fix what is wrong."); + } + + //Remove the invalid prisoners + if(cellsToRemove.size() != 0) { + String names = ""; + for(int c : cellsToRemove) { + if(names.isEmpty()) names = "'" + c + "'"; + else names += "," + "'" + c + "'"; + } + + try { + PreparedStatement cds = con.prepareStatement("delete from " + prefix + "cells where cellid in (" + names + ");"); + + pl.debug("Deleting old cells: 'delete from " + prefix + "cells where cellid in (" + names + ");'"); + + int count = cds.executeUpdate(); + pl.getLogger().info("Deleted " + count + " old cells which referenced a jail no longer valid: " + names); + cds.close(); + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Error while deleting the old cells which don't have a valid jail, please check the error and fix what is wrong."); + } + } + + //This list contains a string which refers to the name of the prisoner in sql + //this list only gets populated if there are prisoners which reference a jail + //that doesn't exist anymore + List prisonersToRemove = new LinkedList(); + + try { + if(con == null) this.prepareStorage(false); + PreparedStatement ps = con.prepareStatement("SELECT * FROM " + prefix + "prisoners"); + ResultSet set = ps.executeQuery(); + + while(set.next()) { + Jail j = pl.getJailManager().getJail(set.getString("jail")); + + if(j != null) { + String cellname = set.getString("cell"); + Cell c = j.getCell(cellname); + + Prisoner p = new Prisoner(set.getString("uuid"), set.getString("name"), set.getBoolean("muted"), set.getLong("time"), set.getString("jailer"), set.getString("reason")); + p.setOfflinePending(set.getBoolean("offlinePending")); + p.setToBeTransferred(set.getBoolean("toBeTransferred")); + Blob inv = set.getBlob("inventory"); + p.setInventory(new String(inv.getBytes(1, (int) inv.length()))); + Blob ar = set.getBlob("armor"); + p.setArmor(new String(ar.getBytes(1, (int)ar.length()))); + p.setPreviousPosition(set.getString("previousLocation")); + p.setPreviousGameMode(set.getString("previousGameMode")); + p.setChanged(false);//Since we just loaded the prisoner, we really don't need to save them. + + if(cellname == null || cellname.isEmpty()) { + j.addPrisoner(p); + }else if(c != null) { + c.setPrisoner(p); + }else { + //the prisoner is assigned to a cell which doesn't exist, so just put them into the jail + j.addPrisoner(p); + } + } else { + //if the jail doesn't exist, do the same as the cells + prisonersToRemove.add(set.getString("name")); + } + } + + set.close(); + ps.close(); + + pl.debug("There are " + prisonersToRemove.size() + " prisoners we need to remove due to being invalid."); + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Error while loading all of the prisoners, please check the error and fix what is wrong."); + } + + //Remove the invalid prisoners + if(prisonersToRemove.size() != 0) { + String names = ""; + for(String s : prisonersToRemove) { + if(names.isEmpty()) names = "'" + s + "'"; + else names += "," + "'" + s + "'"; + } + + try { + PreparedStatement pds = con.prepareStatement("delete from " + prefix + "prisoners where name in (" + names + ");"); + + pl.debug("Deleting old prisoners: 'delete from " + prefix + "prisoners where name in (" + names + ");'"); + + int count = pds.executeUpdate(); + pl.getLogger().info("Deleted " + count + " old prisoners which referenced a jail no longer valid: " + names); + pds.close(); + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Error while deleting the old prisoners which don't have a valid jail, please check the error and fix what is wrong."); + } + } + + pl.debug("Took " + (System.currentTimeMillis() - st) + " millis to load the jails and all the data."); + break; + default: + //load the jails from flatfile + if(flat.isConfigurationSection("jails")) { + Set jails = flat.getConfigurationSection("jails").getKeys(false); + if(!jails.isEmpty()) { + for(String name : jails) { + loadJailFromFlatFile(name); + } + } + } + break; + } + + int js = pl.getJailManager().getJails().size(); + pl.getLogger().info("Loaded " + js + (js == 1 ? " jail." : " jails.")); + + int cs = pl.getJailManager().getAllCells().size(); + pl.getLogger().info("Loaded " + cs + (cs == 1 ? " cell." : " cells.")); + + int ps = pl.getJailManager().getAllPrisoners().size(); + pl.getLogger().info("Loaded " + ps + (ps == 1 ? " prisoner." : " prisoners.")); + } + + private void loadJailFromFlatFile(String name) { + String node = "jails." + name + "."; + String cNode = node + "cells."; + Jail j = new Jail(pl, name); + + j.setWorld(flat.getString(node + "world")); + j.setMaxPoint(new int[] {flat.getInt(node + "top.x"), flat.getInt(node + "top.y"), flat.getInt(node + "top.z")}); + j.setMinPoint(new int[] {flat.getInt(node + "bottom.x"), flat.getInt(node + "bottom.y"), flat.getInt(node + "bottom.z")}); + + j.setTeleportIn(new Location( + pl.getServer().getWorld(flat.getString(node + "world")), + flat.getDouble(node + "tps.in.x"), + flat.getDouble(node + "tps.in.y"), + flat.getDouble(node + "tps.in.z"), + (float) flat.getDouble(node + "tps.in.yaw"), + (float) flat.getDouble(node + "tps.in.pitch"))); + j.setTeleportFree(new Location( + pl.getServer().getWorld(flat.getString(node + "world")), + flat.getDouble(node + "tps.free.x"), + flat.getDouble(node + "tps.free.y"), + flat.getDouble(node + "tps.free.z"), + (float) flat.getDouble(node + "tps.free.yaw"), + (float) flat.getDouble(node + "tps.free.pitch"))); + + if(flat.isConfigurationSection(node + "cells")) { + Set cells = flat.getConfigurationSection(node + "cells").getKeys(false); + if(!cells.isEmpty()) { + for(String cell : cells) { + Cell c = new Cell(cell); + String cellNode = cNode + cell + "."; + + c.setTeleport(new SimpleLocation(j.getTeleportIn().getWorld().getName(), + flat.getDouble(cellNode + "tp.x"), + flat.getDouble(cellNode + "tp.y"), + flat.getDouble(cellNode + "tp.z"), + (float) flat.getDouble(cellNode + "tp.yaw"), + (float) flat.getDouble(cellNode + "tp.pitch"))); + c.setChestLocation(new Location(j.getTeleportIn().getWorld(), + flat.getInt(cellNode + "chest.x"), + flat.getInt(cellNode + "chest.y"), + flat.getInt(cellNode + "chest.z"))); + + for(String sign : flat.getStringList(cellNode + "signs")) { + String[] arr = sign.split(","); + c.addSign(new SimpleLocation(arr[0], + Double.valueOf(arr[1]), + Double.valueOf(arr[2]), + Double.valueOf(arr[3]), + Float.valueOf(arr[4]), + Float.valueOf(arr[5]))); + } + + if(flat.contains(cellNode + "prisoner")) { + Prisoner p = new Prisoner(flat.getString(cellNode + "prisoner.uuid"), + flat.getString(cellNode + "prisoner.name"), + flat.getBoolean(cellNode + "prisoner.muted"), + flat.getLong(cellNode + "prisoner.time"), + flat.getString(cellNode + "prisoner.jailer"), + flat.getString(cellNode + "prisoner.reason")); + p.setOfflinePending(flat.getBoolean(cellNode + "prisoner.offlinePending")); + p.setToBeTransferred(flat.getBoolean(cellNode + "prisoner.toBeTransferred")); + p.setPreviousPosition(flat.getString(cellNode + "prisoner.previousLocation")); + p.setPreviousGameMode(flat.getString(cellNode + "prisoner.previousGameMode")); + p.setInventory(flat.getString(cellNode + "prisoner.inventory", "")); + p.setArmor(flat.getString(cellNode + "prisoner.armor", "")); + p.setChanged(false);//Since we just loaded the prisoner, we really don't need to save them. + c.setPrisoner(p); + } + + j.addCell(c, false); + } + } + } + + if(flat.isConfigurationSection(node + "prisoners")) { + Set prisoners = flat.getConfigurationSection(node + "prisoners").getKeys(false); + if(!prisoners.isEmpty()) { + for(String uuid : prisoners) { + String pNode = node + "prisoners." + uuid + "."; + Prisoner pris = new Prisoner(uuid, + flat.getString(pNode + "name"), + flat.getBoolean(pNode + "muted"), + flat.getLong(pNode + "time"), + flat.getString(pNode + "jailer"), + flat.getString(pNode + "reason")); + pris.setOfflinePending(flat.getBoolean(pNode + "offlinePending")); + pris.setToBeTransferred(flat.getBoolean(pNode + "toBeTransferred")); + pris.setPreviousPosition(flat.getString(pNode + "previousLocation")); + pris.setPreviousGameMode(flat.getString(pNode + "previousGameMode")); + pris.setInventory(flat.getString(pNode + "inventory", "")); + pris.setArmor(flat.getString(pNode + "armor", "")); + pris.setChanged(false);//Since we just loaded the prisoner, we really don't need to save them. + j.addPrisoner(pris); + } + } + } + + if(pl.getServer().getWorld(j.getWorldName()) != null) { + pl.getJailManager().addJail(j, false); + pl.getLogger().info("Loaded jail " + j.getName() + " with " + j.getAllPrisoners().size() + " prisoners and " + j.getCellCount() + " cells."); + } else + pl.getLogger().severe("Failed to load the jail " + j.getName() + " as the world '" + j.getWorldName() + "' does not exist (is null). Did you remove this world?"); + } + + /** Saves everything about a jail, don't usually call this. */ + public void saveEverything() { + long st = System.currentTimeMillis(); + + for(Jail j : pl.getJailManager().getJails()) { + saveJail(j); + + for(Cell c : j.getCells()) { + saveCell(j, c); + } + } + + pl.debug("Saving everything took " + (System.currentTimeMillis() - st) + " millis."); + } + + /** + * Saves the provided {@link Jail jail} to the storage system we are using. + * + * @param j The jail to save. + */ + public void saveJail(Jail j) { + switch(storage) { + case 1: + case 2: + long st = System.currentTimeMillis(); + + try { + if(con == null) this.prepareStorage(false); + PreparedStatement ps = con.prepareStatement("REPLACE INTO " + + prefix + "jails (`name`, `world`, `top.x`, `top.y`, `top.z`, `bottom.x`, `bottom.y`," + + "`bottom.z`, `tps.in.x`, `tps.in.y`, `tps.in.z`, `tps.in.yaw`, `tps.in.pitch`," + + "`tps.free.world`, `tps.free.x`, `tps.free.y`, `tps.free.z`, `tps.free.yaw`, `tps.free.pitch`)" + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); + + ps.setString(1, j.getName()); + ps.setString(2, j.getWorldName()); + ps.setInt(3, j.getMaxPoint().getBlockX()); + ps.setInt(4, j.getMaxPoint().getBlockY()); + ps.setInt(5, j.getMaxPoint().getBlockZ()); + ps.setInt(6, j.getMinPoint().getBlockX()); + ps.setInt(7, j.getMinPoint().getBlockY()); + ps.setInt(8, j.getMinPoint().getBlockZ()); + ps.setDouble(9, j.getTeleportIn().getX()); + ps.setDouble(10, j.getTeleportIn().getY()); + ps.setDouble(11, j.getTeleportIn().getZ()); + ps.setDouble(12, j.getTeleportIn().getYaw()); + ps.setDouble(13, j.getTeleportIn().getPitch()); + ps.setString(14, j.getTeleportFree().getWorld().getName()); + ps.setDouble(15, j.getTeleportFree().getX()); + ps.setDouble(16, j.getTeleportFree().getY()); + ps.setDouble(17, j.getTeleportFree().getZ()); + ps.setDouble(18, j.getTeleportFree().getYaw()); + ps.setDouble(19, j.getTeleportFree().getPitch()); + + ps.executeUpdate(); + ps.close(); + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Error while saving the Jail '" + j.getName() + "' (not updating the prisoners), please check the error and fix what is wrong."); + } + + try { + if(con == null) this.prepareStorage(false); + + for(Cell c : j.getCells()) { + if(c.hasPrisoner() && c.getPrisoner().wasChanged()) { + Prisoner p = c.getPrisoner(); + PreparedStatement pPS = con.prepareStatement("REPLACE INTO `" + prefix + "prisoners` (`uuid`, `name`, `jail`, `cell`, `muted`, `time`," + + "`offlinePending`, `toBeTransferred`, `jailer`, `reason`, `inventory`, `armor`, `previousLocation`, `previousGameMode`)" + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); + pPS.setString(1, p.getUUID().toString()); + pPS.setString(2, p.getLastKnownName()); + pPS.setString(3, j.getName()); + pPS.setString(4, c.getName()); + pPS.setBoolean(5, p.isMuted()); + pPS.setFloat(6, p.getRemainingTime()); + pPS.setBoolean(7, p.isOfflinePending()); + pPS.setBoolean(8, p.isToBeTransferred()); + pPS.setString(9, p.getJailer()); + pPS.setString(10, p.getReason()); + pPS.setBytes(11, p.getInventory().getBytes()); + pPS.setBytes(12, p.getArmor().getBytes()); + pPS.setString(13, p.getPreviousLocationString()); + pPS.setString(14, p.getPreviousGameMode().toString()); + + pPS.executeUpdate(); + pPS.close(); + + p.setChanged(false);//Since we just saved the prisoner + } + } + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Error while saving the cells of the Jail '" + j.getName() + "', please check the error and fix what is wrong."); + } + + try { + if(con == null) this.prepareStorage(false); + + for(Prisoner p : j.getPrisonersNotInCells().values()) { + if(p.wasChanged()) { + PreparedStatement pPS = con.prepareStatement("REPLACE INTO `" + prefix + "prisoners` (`uuid`, `name`, `jail`, `cell`, `muted`, `time`," + + "`offlinePending`, `toBeTransferred`, `jailer`, `reason`, `inventory`, `armor`, `previousLocation`, `previousGameMode`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); + pPS.setString(1, p.getUUID().toString()); + pPS.setString(2, p.getLastKnownName()); + pPS.setString(3, j.getName()); + pPS.setString(4, ""); + pPS.setBoolean(5, p.isMuted()); + pPS.setFloat(6, p.getRemainingTime()); + pPS.setBoolean(7, p.isOfflinePending()); + pPS.setBoolean(8, p.isToBeTransferred()); + pPS.setString(9, p.getJailer()); + pPS.setString(10, p.getReason()); + pPS.setBytes(11, p.getInventory().getBytes()); + pPS.setBytes(12, p.getArmor().getBytes()); + pPS.setString(13, p.getPreviousLocationString()); + pPS.setString(14, p.getPreviousGameMode().toString()); + + pPS.executeUpdate(); + pPS.close(); + p.setChanged(false);//Since we just saved the prisoner + } + } + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Error while saving the prisoners of the Jail '" + j.getName() + "', please check the error and fix what is wrong."); + } + + pl.debug("Took " + (System.currentTimeMillis() - st) + " millis to save the jail " + j.getName() + "."); + break; + default: + if(flat != null) { + String node = "jails." + j.getName() + "."; + + //Corners + flat.set(node + "world", j.getWorldName()); + flat.set(node + "top.x", j.getMaxPoint().getBlockX()); + flat.set(node + "top.y", j.getMaxPoint().getBlockY()); + flat.set(node + "top.z", j.getMaxPoint().getBlockZ()); + flat.set(node + "bottom.x", j.getMinPoint().getBlockX()); + flat.set(node + "bottom.y", j.getMinPoint().getBlockY()); + flat.set(node + "bottom.z", j.getMinPoint().getBlockZ()); + + //Tele in + flat.set(node + "tps.in.x", j.getTeleportIn().getX()); + flat.set(node + "tps.in.y", j.getTeleportIn().getY()); + flat.set(node + "tps.in.z", j.getTeleportIn().getZ()); + flat.set(node + "tps.in.yaw", j.getTeleportIn().getYaw()); + flat.set(node + "tps.in.pitch", j.getTeleportIn().getPitch()); + + //Tele out + flat.set(node + "tps.free.world", j.getTeleportFree().getWorld().getName()); + flat.set(node + "tps.free.x", j.getTeleportFree().getX()); + flat.set(node + "tps.free.y", j.getTeleportFree().getY()); + flat.set(node + "tps.free.z", j.getTeleportFree().getZ()); + flat.set(node + "tps.free.yaw", j.getTeleportFree().getYaw()); + flat.set(node + "tps.free.pitch", j.getTeleportFree().getPitch()); + + //Set all the cells to nothing, then we save each of them so no cells are left behind + flat.set(node + "cells", null); + for(Cell c : j.getCells()) { + String cNode = node + "cells." + c.getName() + "."; + + if(c.getTeleport() != null) { + flat.set(cNode + "tp.x", c.getTeleport().getX()); + flat.set(cNode + "tp.y", c.getTeleport().getY()); + flat.set(cNode + "tp.z", c.getTeleport().getZ()); + flat.set(cNode + "tp.yaw", c.getTeleport().getYaw()); + flat.set(cNode + "tp.pitch", c.getTeleport().getPitch()); + } + + if(c.getChestLocation() != null) { + flat.set(cNode + "chest.x", c.getChestLocation().getBlockX()); + flat.set(cNode + "chest.y", c.getChestLocation().getBlockY()); + flat.set(cNode + "chest.z", c.getChestLocation().getBlockZ()); + } + + String[] signs = new String[c.getSigns().size()]; + int count = 0; + for(SimpleLocation loc : c.getSigns()) { + signs[count] = loc.toString(); + count++; + } + + flat.set(cNode + "signs", signs); + + if(c.getPrisoner() != null) { + Prisoner p = c.getPrisoner(); + flat.set(cNode + "prisoner.uuid", p.getUUID().toString()); + flat.set(cNode + "prisoner.name", p.getLastKnownName()); + flat.set(cNode + "prisoner.muted", p.isMuted()); + flat.set(cNode + "prisoner.time", p.getRemainingTime()); + flat.set(cNode + "prisoner.offlinePending", p.isOfflinePending()); + flat.set(cNode + "prisoner.toBeTransferred", p.isToBeTransferred()); + flat.set(cNode + "prisoner.jailer", p.getJailer()); + flat.set(cNode + "prisoner.reason", p.getReason()); + flat.set(cNode + "prisoner.inventory", p.getInventory()); + flat.set(cNode + "prisoner.armor", p.getArmor()); + if(p.getPreviousLocationString() != null) + flat.set(cNode + "prisoner.previousLocation", p.getPreviousLocationString()); + if(p.getPreviousGameMode() != null) + flat.set(cNode + "prisoner.previousGameMode", p.getPreviousGameMode().toString()); + } + } + + //Null all the prisoners out before we save them again, this way no prisoners are left behind + flat.set(node + "prisoners", null); + for(Prisoner p : j.getPrisonersNotInCells().values()) { + String pNode = node + "prisoners." + p.getUUID().toString() + "."; + flat.set(pNode + "name", p.getLastKnownName()); + flat.set(pNode + "muted", p.isMuted()); + flat.set(pNode + "time", p.getRemainingTime()); + flat.set(pNode + "offlinePending", p.isOfflinePending()); + flat.set(pNode + "toBeTransferred", p.isToBeTransferred()); + flat.set(pNode + "jailer", p.getJailer()); + flat.set(pNode + "reason", p.getReason()); + flat.set(pNode + "inventory", p.getInventory()); + flat.set(pNode + "armor", p.getArmor()); + if(p.getPreviousLocationString() != null) + flat.set(pNode + "previousLocation", p.getPreviousLocationString()); + if(p.getPreviousGameMode() != null) + flat.set(pNode + "previousGameMode", p.getPreviousGameMode().toString()); + } + + try { + flat.save(new File(pl.getDataFolder(), "data.yml")); + } catch (IOException e) { + pl.getLogger().severe("Unable to save the Jail data: " + e.getMessage()); + } + }else { + pl.getLogger().severe("Storage not enabled, could not save the jail " + j.getName()); + } + break; + } + } + + public void saveCell(Jail j, Cell c) { + switch(storage) { + case 1: + case 2: + try { + if(con == null) this.prepareStorage(false); + + PreparedStatement cPS = con.prepareStatement("INSERT INTO `" + prefix + "cells` (`name`, `jail`, `tp.x`, `tp.y`, `tp.z`, `tp.yaw`," + + "`tp.pitch`, `chest.x`, `chest.y`, `chest.z`, `signs`) VALUES (?,?,?,?,?,?,?,?,?,?,?)"); + + cPS.setString(1, c.getName()); + cPS.setString(2, j.getName()); + cPS.setDouble(3, c.getTeleport().getX()); + cPS.setDouble(4, c.getTeleport().getY()); + cPS.setDouble(5, c.getTeleport().getZ()); + cPS.setDouble(6, c.getTeleport().getYaw()); + cPS.setDouble(7, c.getTeleport().getPitch()); + + if(c.hasChest()) { + cPS.setInt(8, c.getChestLocation().getBlockX()); + cPS.setInt(9, c.getChestLocation().getBlockY()); + cPS.setInt(10, c.getChestLocation().getBlockZ()); + }else { + cPS.setNull(8, java.sql.Types.INTEGER); + cPS.setNull(9, java.sql.Types.INTEGER); + cPS.setNull(10, java.sql.Types.INTEGER); + } + + cPS.setString(11, c.getSignString()); + + cPS.executeUpdate(); + cPS.close(); + + if(c.hasPrisoner()) { + Prisoner p = c.getPrisoner(); + PreparedStatement pPS = con.prepareStatement("REPLACE INTO `" + prefix + "prisoners` (`uuid`, `name`, `jail`, `cell`, `muted`, `time`," + + "`offlinePending`, `toBeTransferred`, `jailer`, `reason`, `inventory`, `armor`, `previousLocation`, `previousGameMode`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); + pPS.setString(1, p.getUUID().toString()); + pPS.setString(2, p.getLastKnownName()); + pPS.setString(3, j.getName()); + pPS.setString(4, c.getName()); + pPS.setBoolean(5, p.isMuted()); + pPS.setFloat(6, p.getRemainingTime()); + pPS.setBoolean(7, p.isOfflinePending()); + pPS.setBoolean(8, p.isToBeTransferred()); + pPS.setString(9, p.getJailer()); + pPS.setString(10, p.getReason()); + pPS.setBytes(11, p.getInventory().getBytes()); + pPS.setBytes(12, p.getArmor().getBytes()); + pPS.setString(13, p.getPreviousLocationString()); + pPS.setString(14, p.getPreviousGameMode().toString()); + + pPS.executeUpdate(); + pPS.close(); + } + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Error while saving the cell '" + c.getName() + "' of the Jail '" + j.getName() + "', please check the error and fix what is wrong."); + } + + break; + default: + this.saveJail(j); + break; + } + } + + /** + * Removes the prisoner from the storage system. + * + * @param j the jail which the prisoner is in. + * @param p the prisoner data + */ + public void removePrisoner(Jail j, Prisoner p) { + this.removePrisoner(j, null, p); + } + + /** + * Removes the prisoner from the storage system. + * + * @param j the jail which the prisoner is in. + * @param c the cell which the prisoner is in, null if none + * @param p the prisoner data + */ + public void removePrisoner(Jail j, Cell c, Prisoner p) { + switch(storage) { + case 1: + case 2: + try { + PreparedStatement pp = con.prepareStatement("delete from `" + prefix + "prisoners` where uuid = ? limit 1;"); + pp.setString(1, p.getUUID().toString()); + + pl.debug("Removing " + p.getLastKnownName() + " (" + p.getUUID().toString() + ") from MySQL database."); + + pp.executeUpdate(); + pp.close(); + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Error while removing the prisoner '" + p.getLastKnownName() + "' (" + p.getUUID().toString() + ") from the database, please check the error and fix what is wrong."); + } + break; + default: + if(c == null) + flat.set("jails." + j.getName() + ".prisoners." + p.getUUID().toString(), null); + else + flat.set("jails." + j.getName() + "." + c.getName() + ".prisoner", null); + + try { + flat.save(new File(pl.getDataFolder(), "data.yml")); + } catch (IOException e) { + pl.getLogger().severe("Unable to save the Jail data: " + e.getMessage()); + } + break; + } + } + + /** + * Removes the provided cell from the jail. + * + * @param j instance of the jail the cell is in + * @param c instance of the cell we are removing + */ + public void removeCell(Jail j, Cell c) { + //Clear the inventory before we delete it + if(c.hasChest()) c.getChest().getInventory().clear(); + + //transfer the prisoner if it has one + if(c.hasPrisoner()) { + pl.getLogger().warning("Removing of cell '" + c.getName() + "' from the jail '" + j.getName() + "' failed as it has a prisoner."); + return; + } + + switch(storage) { + case 1: + case 2: + try { + PreparedStatement p = con.prepareStatement("delete from `" + prefix + "cells` where name = ? and jail = ? limit 1;"); + p.setString(1, c.getName()); + p.setString(2, j.getName()); + + p.executeUpdate(); + p.close(); + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Error while removing the cell '" + c.getName() + "' from the Jail '" + j.getName() + "', please check the error and fix what is wrong."); + } + break; + default: + if(flat != null) { + flat.set("jails." + j.getName() + "cells." + c.getName(), null); + + try { + flat.save(new File(pl.getDataFolder(), "data.yml")); + } catch (IOException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Removing of the cell '" + c.getName() + "' from the jail '" + j.getName() + "' errored out while on saving."); + } + } + break; + } + } + + /** + * Removes a jail from the storage system. + * + * @param j the jail instance to remove. + */ + public void removeJail(Jail j) { + String name = j.getName(); + + switch(storage) { + case 1: + case 2: + for(Cell c : j.getCells()) { + removeCell(j, c); + } + + try { + PreparedStatement p = con.prepareStatement("delete from `" + prefix + "jails` where name = ?"); + p.setString(1, name); + + p.executeUpdate(); + p.close(); + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Error while removing the Jail '" + j.getName() + "', please check the error and fix what is wrong."); + } + break; + default: + flat.set("jails." + name, null); + + try { + flat.save(new File(pl.getDataFolder(), "data.yml")); + } catch (IOException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Removing of the jail '" + j.getName() + "' errored out while on saving."); + } + break; + } + } + + /** + * Adds an entry to the database/file for the user, logging when they was jailed. + * + * @param uuid of the player + * @param username of the player + * @param jailer who jailed them + * @param date string of when they are jailed + * @param time of the player's sentence + * @param reason the player is jailed + */ + public void addRecordEntry(String uuid, String username, String jailer, String date, long time, String reason) { + switch(storage) { + case 1: + break; + case 2: + try { + PreparedStatement p = con.prepareStatement("insert into `" + prefix + "records` (`uuid`, `username`, `jailer`, `date`, `time`, `reason`) VALUES (?,?,?,?,?,?);"); + p.setString(1, uuid); + p.setString(2, username); + p.setString(3, jailer); + p.setString(4, date); + p.setLong(5, time); + p.setString(6, reason); + + p.executeUpdate(); + p.close(); + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Error while adding a record entry for '" + username + "', please check the error and fix what is wrong."); + } + break; + default: + if(records == null) records = YamlConfiguration.loadConfiguration(new File(pl.getDataFolder(), "records.yml")); + + List previous = records.getStringList(uuid); + previous.add(Lang.RECORDENTRY.get(new String[] { date, username, jailer, String.valueOf(time), reason, uuid })); + + records.set(username, previous); + + try { + records.save(new File(pl.getDataFolder(), "records.yml")); + } catch (IOException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Saving the records.yml file failed while putting an entry in for '" + username + "'."); + } + break; + } + } + + /** + * Gets all the record entries for the given player. + * + * @param username the of the prisoner's records to get. + * @return A List of strings containing the record entries. + * @deprecated This calls getOfflinePlayer which is a blocking call from Bukkit + */ + public List getRecordEntries(String username) { + UUID uuid = pl.getServer().getOfflinePlayer(username).getUniqueId(); + List entries = new ArrayList(); + + switch(storage) { + case 1: + break; + case 2: + try { + PreparedStatement ps = con.prepareStatement("SELECT * FROM " + prefix + "records where uuid = ?"); + ps.setString(1, uuid.toString()); + ResultSet set = ps.executeQuery(); + + while(set.next()) { + entries.add(Lang.RECORDENTRY.get(new String[] { set.getString("date"), set.getString("username"), set.getString("jailer"), String.valueOf(set.getLong("time")), set.getString("reason") })); + } + + set.close(); + ps.close(); + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Error while getting all the record entries for '" + uuid + "', please check the error and fix what is wrong."); + } + break; + default: + if(records == null) records = YamlConfiguration.loadConfiguration(new File(pl.getDataFolder(), "records.yml")); + + entries = records.getStringList(uuid.toString()); + break; + } + + return entries; + } } diff --git a/src/main/java/com/graywolf336/jail/JailMain.java b/src/main/java/com/graywolf336/jail/JailMain.java index cf5e53f..1dc6a54 100644 --- a/src/main/java/com/graywolf336/jail/JailMain.java +++ b/src/main/java/com/graywolf336/jail/JailMain.java @@ -31,286 +31,286 @@ import com.graywolf336.jail.listeners.WorldListener; * @version 3.0.0 */ public class JailMain extends JavaPlugin { - private CommandHandler cmdHand; - private HandCuffManager hcm; - private JailHandler jh; - private JailIO io; - private JailManager jm; - private JailPayManager jpm; - private JailStickManager jsm; - private JailTimer jt; - private PrisonerManager pm; - private ScoreBoardManager sbm; - private MoveProtectionListener mpl; - private Update update; - private boolean debug = false; - private int updateCheckTask = -1; - - public void onEnable() { - long st = System.currentTimeMillis(); - loadConfig(); - - debug = getConfig().getBoolean(Settings.DEBUG.getPath()); - if(debug) getLogger().info("Debugging enabled."); - - hcm = new HandCuffManager(); - jm = new JailManager(this); - - //Try to load the old stuff before we load anything, esp the storage stuff - LegacyManager lm = new LegacyManager(this); - if(lm.doWeNeedToConvert()) { - lm.convertOldData(); - if(!lm.wasAnythingConverted()) getLogger().severe("We was unable to convert some, or all, of the old data."); - } - - io = new JailIO(this); - io.loadLanguage(); - - //If the prepareStorage returns false, we need to disable the plugin - if(!io.prepareStorage(true)) { - this.getLogger().severe("An error occured while preparing the connection to the storage, please see the error above for more information."); - this.getServer().getPluginManager().disablePlugin(this); - return; - } - - io.loadJails(); - - //If we converted something, let's save EVERYTHING including the cells - if(lm.wasAnythingConverted()) { - io.saveEverything(); - } - - cmdHand = new CommandHandler(this); - jh = new JailHandler(this); - pm = new PrisonerManager(this); - - PluginManager plm = this.getServer().getPluginManager(); - plm.registerEvents(new BlockListener(this), this); - plm.registerEvents(new CacheListener(this), this); - plm.registerEvents(new EntityListener(this), this); - plm.registerEvents(new HandCuffListener(this), this); - plm.registerEvents(new JailingListener(this), this); - plm.registerEvents(new PlayerListener(this), this); - plm.registerEvents(new ProtectionListener(this), this); - plm.registerEvents(new WorldListener(this), this); - - //Only register the move protection listener if this is enabled in the - //config when we first start the plugin. The reason for this change is - //that the move event is called a ton of times per single move and so - //not registering this event listener will hopefully safe some performance. - //But doing this also forces people to restart their server if they to - //enable it after disabling it. - if(getConfig().getBoolean(Settings.MOVEPROTECTION.getPath())) { - this.mpl = new MoveProtectionListener(this); - plm.registerEvents(this.mpl, this); - } - - jt = new JailTimer(this); - sbm = new ScoreBoardManager(this); - reloadJailPayManager(); - reloadJailSticks(); - reloadUpdateCheck(); - - new JailsAPI(this); - debug("Took " + (System.currentTimeMillis() - st) + " to enable the plugin."); - getLogger().info("Completed enablement."); - } + private CommandHandler cmdHand; + private HandCuffManager hcm; + private JailHandler jh; + private JailIO io; + private JailManager jm; + private JailPayManager jpm; + private JailStickManager jsm; + private JailTimer jt; + private PrisonerManager pm; + private ScoreBoardManager sbm; + private MoveProtectionListener mpl; + private Update update; + private boolean debug = false; + private int updateCheckTask = -1; - public void onDisable() { - if(jm != null) - for(Jail j : jm.getJails()) - io.saveJail(j); - - if(jt != null) - if(jt.getTimer() != null) - jt.getTimer().stop(); - - if(io != null) - io.closeConnection(); - - getServer().getScheduler().cancelTasks(this); - - update = null; - jt = null; - sbm = null; - jpm = null; - cmdHand = null; - pm = null; - jm = null; - jsm = null; - io = null; - hcm = null; - } - - private void loadConfig() { - //Only create the default config if it doesn't exist - saveDefaultConfig(); - - //Append new key-value pairs to the config - getConfig().options().copyDefaults(true); - - // Set the header and save + public void onEnable() { + long st = System.currentTimeMillis(); + loadConfig(); + + debug = getConfig().getBoolean(Settings.DEBUG.getPath()); + if(debug) getLogger().info("Debugging enabled."); + + hcm = new HandCuffManager(); + jm = new JailManager(this); + + //Try to load the old stuff before we load anything, esp the storage stuff + LegacyManager lm = new LegacyManager(this); + if(lm.doWeNeedToConvert()) { + lm.convertOldData(); + if(!lm.wasAnythingConverted()) getLogger().severe("We was unable to convert some, or all, of the old data."); + } + + io = new JailIO(this); + io.loadLanguage(); + + //If the prepareStorage returns false, we need to disable the plugin + if(!io.prepareStorage(true)) { + this.getLogger().severe("An error occured while preparing the connection to the storage, please see the error above for more information."); + this.getServer().getPluginManager().disablePlugin(this); + return; + } + + io.loadJails(); + + //If we converted something, let's save EVERYTHING including the cells + if(lm.wasAnythingConverted()) { + io.saveEverything(); + } + + cmdHand = new CommandHandler(this); + jh = new JailHandler(this); + pm = new PrisonerManager(this); + + PluginManager plm = this.getServer().getPluginManager(); + plm.registerEvents(new BlockListener(this), this); + plm.registerEvents(new CacheListener(this), this); + plm.registerEvents(new EntityListener(this), this); + plm.registerEvents(new HandCuffListener(this), this); + plm.registerEvents(new JailingListener(this), this); + plm.registerEvents(new PlayerListener(this), this); + plm.registerEvents(new ProtectionListener(this), this); + plm.registerEvents(new WorldListener(this), this); + + //Only register the move protection listener if this is enabled in the + //config when we first start the plugin. The reason for this change is + //that the move event is called a ton of times per single move and so + //not registering this event listener will hopefully safe some performance. + //But doing this also forces people to restart their server if they to + //enable it after disabling it. + if(getConfig().getBoolean(Settings.MOVEPROTECTION.getPath())) { + this.mpl = new MoveProtectionListener(this); + plm.registerEvents(this.mpl, this); + } + + jt = new JailTimer(this); + sbm = new ScoreBoardManager(this); + reloadJailPayManager(); + reloadJailSticks(); + reloadUpdateCheck(); + + new JailsAPI(this); + debug("Took " + (System.currentTimeMillis() - st) + " to enable the plugin."); + getLogger().info("Completed enablement."); + } + + public void onDisable() { + if(jm != null) + for(Jail j : jm.getJails()) + io.saveJail(j); + + if(jt != null) + if(jt.getTimer() != null) + jt.getTimer().stop(); + + if(io != null) + io.closeConnection(); + + getServer().getScheduler().cancelTasks(this); + + update = null; + jt = null; + sbm = null; + jpm = null; + cmdHand = null; + pm = null; + jm = null; + jsm = null; + io = null; + hcm = null; + } + + private void loadConfig() { + //Only create the default config if it doesn't exist + saveDefaultConfig(); + + //Append new key-value pairs to the config + getConfig().options().copyDefaults(true); + + // Set the header and save getConfig().options().header(getHeader()); saveConfig(); - } - - private String getHeader() { - String sep = System.getProperty("line.separator"); - - return "###################" + sep - + "Jail v" + this.getDescription().getVersion() + " config file" + sep - + "Note: You -must- use spaces instead of tabs!" + sep + - "###################"; - } - - /* Majority of the new command system was heavily influenced by the MobArena. - * Thank you garbagemule for the great system you have in place there. - * - * Send the command off to the CommandHandler class, that way this main class doesn't get clogged up. - */ - public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { - if(commandLabel.equalsIgnoreCase("jail") || commandLabel.equalsIgnoreCase("j")) { - jh.parseCommand(jm, sender, args); - }else { - cmdHand.handleCommand(jm, sender, command.getName().toLowerCase(), args); - } - - return true;//Always return true here, that way we can handle the help and command usage ourself. - } - - /** Reloads the scoreboard manager class, useful when something is changed int he config about it. */ - public void reloadScoreBoardManager() { - this.sbm.removeAllScoreboards(); - this.sbm = null; - this.sbm = new ScoreBoardManager(this); - - if(getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) { - for(Jail j : jm.getJails()) { - for(Prisoner p : j.getAllPrisoners().values()) { - if(getServer().getPlayer(p.getUUID()) != null) { - this.sbm.addScoreBoard(getServer().getPlayer(p.getUUID()), p); - } - } - } - } - } - - /** Reloads the Jail Sticks, so the new ones can be loaded from the config. */ - public void reloadJailSticks() { - if(getConfig().getBoolean(Settings.JAILSTICKENABLED.getPath())) { - if(this.jsm != null) { - this.jsm.removeAllStickUsers(); - this.jsm = null; - } - - this.jsm = new JailStickManager(this); - } - } - - /** - * Reloads the {@link JailPayManager}. - * - * @throws Exception If we couldn't successfully create a new Jail Pay Manager instance. - */ - public void reloadJailPayManager() { - this.jpm = null; - - if(getConfig().getBoolean(Settings.JAILPAYENABLED.getPath())) { - if(getServer().getPluginManager().isPluginEnabled("Vault")) { - this.jpm = new JailPayManager(this); - }else { - getConfig().set(Settings.JAILPAYENABLED.getPath(), false); - getLogger().severe("Jail Pay couldn't find an economy, disabling Jail Pay."); - } - } - } - - /** Reloads the update checker, in case they changed a setting about it. */ - public void reloadUpdateCheck() { - getServer().getScheduler().cancelTask(updateCheckTask); - update = new Update(this); - if(getConfig().getBoolean(Settings.UPDATENOTIFICATIONS.getPath())) { - try { - updateCheckTask = getServer().getScheduler().runTaskTimerAsynchronously(this, new Runnable() { - public void run() { - update.query(); - } - }, 80L, Util.getTime(getConfig().getString(Settings.UPDATETIME.getPath()), TimeUnit.SECONDS) * 20).getTaskId(); - } catch (Exception e) { - e.printStackTrace(); - getLogger().severe("Was unable to schedule the update checking, please check your time format is correct."); - } - } - } - - /** Gets the {@link HandCuffManager} instance. */ - public HandCuffManager getHandCuffManager() { - return this.hcm; - } - - /** Gets the {@link JailIO} instance. */ - public JailIO getJailIO() { - return this.io; - } - - /** Gets the {@link JailManager} instance. */ - public JailManager getJailManager() { - return this.jm; - } - - /** Gets the {@link JailPayManager} instance. */ - public JailPayManager getJailPayManager() { - return this.jpm; - } - - /** Gets the {@link PrisonerManager} instance. */ - public PrisonerManager getPrisonerManager() { - return this.pm; - } - - /** Gets the {@link JailStickManager} instance. */ - public JailStickManager getJailStickManager() { - return this.jsm; - } - - /** Gets the {@link ScoreBoardManager} instance. */ - public ScoreBoardManager getScoreBoardManager() { - return this.sbm; - } - - /** Gets the {@link Update} instance. */ - public Update getUpdate() { - return this.update; - } - - /** Sets whether the plugin is in debugging or not. */ - public boolean setDebugging(boolean debug) { - this.debug = debug; - - //Save whether we are debugging when we disable the plugin - getConfig().set(Settings.DEBUG.getPath(), this.debug); - saveConfig(); - - return this.debug; - } - - /** Returns if the plugin is in debug state or not. */ - public boolean inDebug() { - return this.debug; - } - - /** Logs a debugging message to the console if debugging is enabled. */ - public void debug(String message) { - if(inDebug()) getLogger().info("[Debug]: " + message); - } - - /** - * This method is only for testing, there is no need to use this. - * - * @return the move protection listener - * @deprecated - */ - public MoveProtectionListener getPlayerMoveListener() { - return this.mpl; - } + } + + private String getHeader() { + String sep = System.getProperty("line.separator"); + + return "###################" + sep + + "Jail v" + this.getDescription().getVersion() + " config file" + sep + + "Note: You -must- use spaces instead of tabs!" + sep + + "###################"; + } + + /* Majority of the new command system was heavily influenced by the MobArena. + * Thank you garbagemule for the great system you have in place there. + * + * Send the command off to the CommandHandler class, that way this main class doesn't get clogged up. + */ + public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { + if(commandLabel.equalsIgnoreCase("jail") || commandLabel.equalsIgnoreCase("j")) { + jh.parseCommand(jm, sender, args); + }else { + cmdHand.handleCommand(jm, sender, command.getName().toLowerCase(), args); + } + + return true;//Always return true here, that way we can handle the help and command usage ourself. + } + + /** Reloads the scoreboard manager class, useful when something is changed int he config about it. */ + public void reloadScoreBoardManager() { + this.sbm.removeAllScoreboards(); + this.sbm = null; + this.sbm = new ScoreBoardManager(this); + + if(getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) { + for(Jail j : jm.getJails()) { + for(Prisoner p : j.getAllPrisoners().values()) { + if(getServer().getPlayer(p.getUUID()) != null) { + this.sbm.addScoreBoard(getServer().getPlayer(p.getUUID()), p); + } + } + } + } + } + + /** Reloads the Jail Sticks, so the new ones can be loaded from the config. */ + public void reloadJailSticks() { + if(getConfig().getBoolean(Settings.JAILSTICKENABLED.getPath())) { + if(this.jsm != null) { + this.jsm.removeAllStickUsers(); + this.jsm = null; + } + + this.jsm = new JailStickManager(this); + } + } + + /** + * Reloads the {@link JailPayManager}. + * + * @throws Exception If we couldn't successfully create a new Jail Pay Manager instance. + */ + public void reloadJailPayManager() { + this.jpm = null; + + if(getConfig().getBoolean(Settings.JAILPAYENABLED.getPath())) { + if(getServer().getPluginManager().isPluginEnabled("Vault")) { + this.jpm = new JailPayManager(this); + }else { + getConfig().set(Settings.JAILPAYENABLED.getPath(), false); + getLogger().severe("Jail Pay couldn't find an economy, disabling Jail Pay."); + } + } + } + + /** Reloads the update checker, in case they changed a setting about it. */ + public void reloadUpdateCheck() { + getServer().getScheduler().cancelTask(updateCheckTask); + update = new Update(this); + if(getConfig().getBoolean(Settings.UPDATENOTIFICATIONS.getPath())) { + try { + updateCheckTask = getServer().getScheduler().runTaskTimerAsynchronously(this, new Runnable() { + public void run() { + update.query(); + } + }, 80L, Util.getTime(getConfig().getString(Settings.UPDATETIME.getPath()), TimeUnit.SECONDS) * 20).getTaskId(); + } catch (Exception e) { + e.printStackTrace(); + getLogger().severe("Was unable to schedule the update checking, please check your time format is correct."); + } + } + } + + /** Gets the {@link HandCuffManager} instance. */ + public HandCuffManager getHandCuffManager() { + return this.hcm; + } + + /** Gets the {@link JailIO} instance. */ + public JailIO getJailIO() { + return this.io; + } + + /** Gets the {@link JailManager} instance. */ + public JailManager getJailManager() { + return this.jm; + } + + /** Gets the {@link JailPayManager} instance. */ + public JailPayManager getJailPayManager() { + return this.jpm; + } + + /** Gets the {@link PrisonerManager} instance. */ + public PrisonerManager getPrisonerManager() { + return this.pm; + } + + /** Gets the {@link JailStickManager} instance. */ + public JailStickManager getJailStickManager() { + return this.jsm; + } + + /** Gets the {@link ScoreBoardManager} instance. */ + public ScoreBoardManager getScoreBoardManager() { + return this.sbm; + } + + /** Gets the {@link Update} instance. */ + public Update getUpdate() { + return this.update; + } + + /** Sets whether the plugin is in debugging or not. */ + public boolean setDebugging(boolean debug) { + this.debug = debug; + + //Save whether we are debugging when we disable the plugin + getConfig().set(Settings.DEBUG.getPath(), this.debug); + saveConfig(); + + return this.debug; + } + + /** Returns if the plugin is in debug state or not. */ + public boolean inDebug() { + return this.debug; + } + + /** Logs a debugging message to the console if debugging is enabled. */ + public void debug(String message) { + if(inDebug()) getLogger().info("[Debug]: " + message); + } + + /** + * This method is only for testing, there is no need to use this. + * + * @return the move protection listener + * @deprecated + */ + public MoveProtectionListener getPlayerMoveListener() { + return this.mpl; + } } diff --git a/src/main/java/com/graywolf336/jail/JailManager.java b/src/main/java/com/graywolf336/jail/JailManager.java index e678db8..e6d8034 100644 --- a/src/main/java/com/graywolf336/jail/JailManager.java +++ b/src/main/java/com/graywolf336/jail/JailManager.java @@ -38,632 +38,632 @@ import com.graywolf336.jail.steps.JailCreationSteps; * @version 1.1.0 */ public class JailManager { - private JailMain plugin; - private HashMap jails; - private HashMap jailCreators; - private HashMap cellCreators; - private HashMap confirms; - private HashMap cache; - private JailCreationSteps jcs; - private CellCreationSteps ccs; - - public JailManager(JailMain plugin) { - this.plugin = plugin; - this.jails = new HashMap(); - this.jailCreators = new HashMap(); - this.cellCreators = new HashMap(); - this.confirms = new HashMap(); - this.cache = new HashMap(); - this.jcs = new JailCreationSteps(); - this.ccs = new CellCreationSteps(); - } - - /** Returns the instance of the plugin main class. */ - public JailMain getPlugin() { - return this.plugin; - } - - /** Returns a HashSet of all the jails. */ - public HashSet getJails() { - return new HashSet(jails.values()); - } - - /** Returns an array of all the names of the jails. */ - public String[] getJailNames() { - return this.jails.keySet().toArray(new String[jails.size()]); - } - - /** - * Adds a jail to the collection of them. - * - * @param jail The jail to add - * @param n True if this is a new jail, false if it isn't. - */ - public void addJail(Jail jail, boolean n) { - this.jails.put(jail.getName(), jail); - if(n) plugin.getJailIO().saveJail(jail); - } - - /** - * Removes a {@link Jail}. - * - * @param name of the jail to remove - */ - public void removeJail(String name) { - plugin.getJailIO().removeJail(this.jails.get(name)); - this.jails.remove(name); - } - - /** - * Gets a jail by the given name. - * - * @param name The name of the jail to get. - * @return The {@link Jail} with the given name, if no jail found this will return null. - */ - public Jail getJail(String name) { - return name.isEmpty() ? this.jails.values().iterator().next() : this.jails.get(name); - } - - /** - * Gets the nearest {@link Jail} to the player, if the sender is a player or else it will get the first jail defined. - * - * @param sender The sender who we are looking around. - * @return The nearest {@link Jail} to the sender if it is a player or else the first jail defined. - */ - public Jail getNearestJail(CommandSender sender) { - if(sender instanceof Player) { - Location loc = ((Player) sender).getLocation(); - - Jail j = null; - double len = -1; - - for(Jail jail : jails.values()) { - double clen = jail.getDistance(loc); - - if (clen < len || len == -1) { - len = clen; - j = jail; - } - } - - return (j == null ? jails.values().iterator().next() : j); - }else { - return jails.values().iterator().next(); - } - } - - /** - * Gets the jail which this location is in, will return null if none exist. - * - * @param loc to get the jail from - * @return The jail this block is in, null if no jail found. - */ - public Jail getJailFromLocation(Location loc) { - for(Jail j : jails.values()) { - if(Util.isInsideAB(loc.toVector(), j.getMinPoint().toVector(), j.getMaxPoint().toVector())) { - return j; - } - } - - return null; - } - - /** - * Checks to see if the given name for a {@link Jail} is valid, returns true if it is a valid jail. - * - * @param name The name of the jail to check. - * @return True if a valid jail was found, false if no jail was found. - */ - public boolean isValidJail(String name) { - return this.jails.get(name) != null; - } - - /** - * Gets all the {@link Cell cells} in the jail system, best for system wide count of the cells or touching each cell. - * - * @return HashSet of all the Cells. - */ - public HashSet getAllCells() { - HashSet cells = new HashSet(); - - for(Jail j : jails.values()) - cells.addAll(j.getCells()); - - return cells; - } - - /** - * Adds a prisoner to the cache. - * - * @param cache object to store - * @return The same object given - */ - public CachePrisoner addCacheObject(CachePrisoner cache) { - plugin.debug("Adding " + cache.getPrisoner().getUUID().toString() + " to the cache."); - this.cache.put(cache.getPrisoner().getUUID(), cache); - return cache; - } - - /** - * Checks if the given uuid is in the cache. - * - * @param uuid of the player - * @return true if in cache, false if not - */ - public boolean inCache(UUID uuid) { - return this.cache.containsKey(uuid); - } - - /** - * Gets a cached prisoner object. - * - * @param uuid of the prisoner to get - * @return the cahced prisoner object, will be null if it doesn't exist - */ - public CachePrisoner getCacheObject(UUID uuid) { - return this.cache.get(uuid); - } - - /** - * Removes the cache object stored for this uuid. - * - * @param uuid of the prisoner to remove - */ - public void removeCacheObject(UUID uuid) { - plugin.debug("Removing " + uuid.toString() + " from the cache."); - this.cache.remove(uuid); - } - - /** - * Gets all the prisoners in the system, best for a system wide count of the prisoners or accessing all the prisoners at once. - * - * @return HashSet of Prisoners. - */ - public HashMap getAllPrisoners() { - HashMap prisoners = new HashMap(); - - for(Jail j : jails.values()) - prisoners.putAll(j.getAllPrisoners()); - - return prisoners; - } - - /** - * Gets the {@link Jail jail} the given prisoner is in. - * - * @param prisoner The prisoner data for the prisoner we are checking - * @return The jail the player is in, CAN BE NULL. - */ - public Jail getJailPrisonerIsIn(Prisoner prisoner) { - if(prisoner == null) return null; - else return getJailPlayerIsIn(prisoner.getUUID()); - } - - /** - * Gets the {@link Jail jail} the given player is in. - * - *

- * - * Checks the cache first. - * - * @param uuid The uuid of the player who's jail we are getting. - * @return The jail the player is in, CAN BE NULL. - */ - public Jail getJailPlayerIsIn(UUID uuid) { - if(this.cache.containsKey(uuid)) { - plugin.debug(uuid.toString() + " is in the cache (getJailPlayerIsIn)."); - return this.cache.get(uuid).getJail(); - } - - for(Jail j : jails.values()) - if(j.isPlayerJailed(uuid)) - return j; - - return null; - } - - /** - * Gets if the given uuid of a player is jailed or not, in all the jails and cells. - * - * @param uuid The uuid of the player to check. - * @return true if they are jailed, false if not. - */ - public boolean isPlayerJailed(UUID uuid) { - return getJailPlayerIsIn(uuid) != null; - } - - /** - * Gets the {@link Prisoner} data from for this user, if they are jailed. - * - * @param uuid The uuid of prisoner who's data to get - * @return {@link Prisoner prisoner} data. - */ - public Prisoner getPrisoner(UUID uuid) { - Jail j = getJailPlayerIsIn(uuid); - - return j == null ? null : j.getPrisoner(uuid); - } - - /** - * Gets the {@link Jail} the player is in from their last known username, null if not jailed. - * - * @param username Last known username to search by - * @return {@link Jail jail} player is in - */ - public Jail getJailPlayerIsInByLastKnownName(String username) { - for(Jail j : jails.values()) - for(Prisoner p : j.getAllPrisoners().values()) - if(p.getLastKnownName().equalsIgnoreCase(username)) - return j; - - return null; - } - - /** - * Gets the {@link Prisoner}'s data from the last known username, returning null if no prisoner has that name. - * - * @param username Last known username to go by - * @return {@link Prisoner prisoner} data - */ - public Prisoner getPrisonerByLastKnownName(String username) { - for(Prisoner p : this.getAllPrisoners().values()) - if(p.getLastKnownName().equalsIgnoreCase(username)) - return p; - - return null; - } - - /** - * Checks if the provided username is jailed, using last known username. - * - * @param username Last known username to go by - * @return true if they are jailed, false if not - */ - public boolean isPlayerJailedByLastKnownUsername(String username) { - return this.getPrisonerByLastKnownName(username) != null; - } - - /** - * Clears a {@link Jail} of all its prisoners if the jail is provided, otherwise it releases all the prisoners in all the jails. - * - * @param jail The name of the jail to release the prisoners in, null if wanting to clear all. - * @return The resulting message to be sent to the caller of this method. - */ - public String clearJailOfPrisoners(String jail) { - //If they don't pass in a jail name, clear all the jails - if(jail != null) { - Jail j = getJail(jail); - - if(j != null) { - for(Prisoner p : j.getAllPrisoners().values()) { - getPlugin().getPrisonerManager().schedulePrisonerRelease(p); - } - - return Lang.PRISONERSCLEARED.get(j.getName()); - }else { - return Lang.NOJAIL.get(jail); - } - }else { - return clearAllJailsOfAllPrisoners(); - } - } - - /** - * Clears all the {@link Jail jails} of prisoners by releasing them. - * - * @return The resulting message to be sent to the caller of this method. - */ - public String clearAllJailsOfAllPrisoners() { - //No name of a jail has been passed, so release all of the prisoners in all the jails - if(getJails().size() == 0) { - return Lang.NOJAILS.get(); - }else { - for(Jail j : getJails()) { - for(Prisoner p : j.getAllPrisoners().values()) { - getPlugin().getPrisonerManager().schedulePrisonerRelease(p); - } - } - - return Lang.PRISONERSCLEARED.get(Lang.ALLJAILS); - } - } - - /** - * Forcefully clears all the jails if name provided is null. - * - *

- * - * This method just clears them from the storage, doesn't release them. - * - * @param name of the jail to clear, null if all of them. - * @return The resulting message to be sent to the caller of this method. - */ - public String forcefullyClearJailOrJails(String name) { - if(name == null) { - if(getJails().size() == 0) { - return Lang.NOJAILS.get(); - }else { - for(Jail j : getJails()) { - j.clearPrisoners(); - } - - return Lang.PRISONERSCLEARED.get(Lang.ALLJAILS); - } - }else { - Jail j = getJail(name); - - if(j != null) { - j.clearPrisoners(); - return Lang.PRISONERSCLEARED.get(j.getName()); - }else { - return Lang.NOJAIL.get(name); - } - } - } - - /** - * Deletes a jail's cell, checking everything is setup right for it to be deleted. - * - * @param jail Name of the jail to delete a cell in. - * @param cell Name of the cell to delete. - * @return The resulting message to be sent to the caller of this method. - */ - public String deleteJailCell(String jail, String cell) { - //Check if the jail name provided is a valid jail - if(isValidJail(jail)) { - Jail j = getJail(jail); - - //check if the cell is a valid cell - if(j.isValidCell(cell)) { - if(j.getCell(cell).hasPrisoner()) { - //The cell has a prisoner, so tell them to first transfer the prisoner - //or release the prisoner - return Lang.CELLREMOVALUNSUCCESSFUL.get(new String[] { cell, jail }); - }else { - j.removeCell(cell); - return Lang.CELLREMOVED.get(new String[] { cell, jail }); - } - }else { - //No cell found by the provided name in the stated jail - return Lang.NOCELL.get(new String[] { cell, jail }); - } - }else { - //No jail found by the provided name - return Lang.NOJAIL.get(jail); - } - } - - /** - * Deletes all the cells in a jail, returns a list of Strings. - * - * @param jail The name of the jail to delete all the jails in. - * @return An array of strings of messages to send. - */ - public String[] deleteAllJailCells(String jail) { - LinkedList msgs = new LinkedList(); - - //Check if the jail name provided is a valid jail - if(isValidJail(jail)) { - Jail j = getJail(jail); - - if(j.getCellCount() == 0) { - //There are no cells in this jail, thus we can't delete them. - msgs.add(Lang.NOCELLS.get(j.getName())); - }else { - //Keep a local copy of the hashset so that we don't get any CMEs. - HashSet cells = new HashSet(j.getCells()); - - for(Cell c : cells) { - if(c.hasPrisoner()) { - //The cell has a prisoner, so tell them to first transfer the prisoner - //or release the prisoner - msgs.add(Lang.CELLREMOVALUNSUCCESSFUL.get(new String[] { c.getName(), j.getName() })); - }else { - j.removeCell(c.getName()); - msgs.add(Lang.CELLREMOVED.get(new String[] { c.getName(), j.getName() })); - } - } - } - }else { - //No jail found by the provided name - msgs.add(Lang.NOJAIL.get(jail)); - } - - return msgs.toArray(new String[msgs.size()]); - } - - /** - * Deletes a jail while doing some checks to verify it can be deleted. - * - * @param jail The name of the jail to delete. - * @return The resulting message to be sent to the caller of this method. - */ - public String deleteJail(String jail) { - //Check if the jail name provided is a valid jail - if(isValidJail(jail)) { - //check if the jail doesn't contain prisoners - if(getJail(jail).getAllPrisoners().size() == 0) { - //There are no prisoners, so we can delete it - removeJail(jail); - return Lang.JAILREMOVED.get(jail); - }else { - //The jail has prisoners, they need to release them first - return Lang.JAILREMOVALUNSUCCESSFUL.get(jail); - } - }else { - //No jail found by the provided name - return Lang.NOJAIL.get(jail); - } - } - - /** - * Returns whether or not the player is creating a jail or a cell. - * - *

- * - * If you want to check to see if they're just creating a jail then use {@link #isCreatingAJail(String) isCreatingAJail} or if you want to see if they're creating a cell then use {@link #isCreatingACell(String) isCreatingACell}. - * - * @param name The name of the player, in any case as we convert it to lowercase. - * @return True if the player is creating a jail or cell, false if they're not creating anything. - */ - public boolean isCreatingSomething(String name) { - return this.jailCreators.containsKey(name.toLowerCase()) || this.cellCreators.containsKey(name.toLowerCase()); - } - - /** Returns a message used for telling them what they're creating and what step they're on. */ - public String getStepMessage(String player) { - String message = ""; - - if(isCreatingACell(player)) {//Check whether it is a jail cell - CreationPlayer cp = this.getCellCreationPlayer(player); - message = "You're already creating a Cell with the name '" + cp.getCellName() + "' and you still need to "; - - switch(cp.getStep()) { - case 1: - message += "set the teleport in location."; - break; - case 2: - message += "select all the signs."; - break; - case 3: - message += "set the double chest location."; - break; - } - - }else if(isCreatingAJail(player)) {//If not a cell, then check if a jail. - CreationPlayer cp = this.getJailCreationPlayer(player); - message = "You're already creating a Jail with the name '" + cp.getJailName() + "' and you still need to "; - - switch(cp.getStep()) { - case 1: - message += "select the first point."; - break; - case 2: - message += "select the second point."; - break; - case 3: - message += "set the teleport in location."; - break; - case 4: - message += "set the release location."; - break; - } - } - - return message; - } - - /** Returns whether or not someone is creating a Jail. */ - public boolean isCreatingAJail(String name) { - return this.jailCreators.containsKey(name.toLowerCase()); - } - - /** - * Method for setting a player to be creating a Jail, returns whether or not they were added successfully. - * - * @param player The player who is creating a jail. - * @param jailName The name of the jail we are creating. - * @return True if they were added successfully, false if they are already creating a Jail. - */ - public boolean addCreatingJail(String player, String jailName) { - if(isCreatingAJail(player)) { - return false; - }else { - this.jailCreators.put(player.toLowerCase(), new CreationPlayer(jailName)); - return true; - } - } - - /** Returns the instance of the CreationPlayer for this player, null if there was none found. */ - public CreationPlayer getJailCreationPlayer(String name) { - return this.jailCreators.get(name.toLowerCase()); - } - - /** Removes a CreationPlayer with the given name from the jail creators. */ - public void removeJailCreationPlayer(String name) { - this.jailCreators.remove(name.toLowerCase()); - } - - /** Returns whether or not someone is creating a Cell. */ - public boolean isCreatingACell(String name) { - return this.cellCreators.containsKey(name.toLowerCase()); - } - - /** - * Method for setting a player to be creating a Cell, returns whether or not they were added successfully. - * - * @param player The player who is creating a jail. - * @param jailName The name of the jail this cell is going. - * @param cellName The name of the cell we are creating. - * @return True if they were added successfully, false if they are already creating a Jail. - */ - public boolean addCreatingCell(String player, String jailName, String cellName) { - if(isCreatingACell(player)) { - return false; - }else { - this.cellCreators.put(player.toLowerCase(), new CreationPlayer(jailName, cellName)); - return true; - } - } - - /** Returns the instance of the CreationPlayer for this player, null if there was none found. */ - public CreationPlayer getCellCreationPlayer(String name) { - return this.cellCreators.get(name.toLowerCase()); - } - - /** Removes a CreationPlayer with the given name from the cell creators. */ - public void removeCellCreationPlayer(String name) { - this.cellCreators.remove(name.toLowerCase()); - } - - /** Gets the instance of the {@link JailCreationSteps}. */ - public JailCreationSteps getJailCreationSteps() { - return this.jcs; - } - - /** Gets the instance of the {@link CellCreationSteps}. */ - public CellCreationSteps getCellCreationSteps() { - return this.ccs; - } - - /** Adds something to the confirming list. */ - public void addConfirming(String name, ConfirmPlayer confirmer) { - getPlugin().debug("Adding a confirming for " + name + " to confirm " + confirmer.getConfirming().toString().toLowerCase()); - this.confirms.put(name, confirmer); - } - - /** Removes a name from the confirming list. */ - public void removeConfirming(String name) { - this.confirms.remove(name); - } - - /** Checks if the given name is confirming something. */ - public boolean isConfirming(String name) { - if(this.confirms.containsKey(name)) { - if(this.confirmingHasExpired(name)) { - getPlugin().debug("Removing " + name + "'s confirmation as it expired."); - this.removeConfirming(name); - } - - return this.confirms.containsKey(name); - }else { - return false; - } - } - - /** Returns true if the confirmation has expired, false if it is still valid. */ - public boolean confirmingHasExpired(String name) { - //If the expiry time is LESS than the current time, it has expired - return this.confirms.get(name).getExpiryTime() < System.currentTimeMillis(); - } - - /** Returns the original arguments for what we are confirming. */ - public String[] getOriginalArgs(String name) { - return this.confirms.get(name).getArguments(); - } - - /** Returns what the given name is confirming. */ - public Confirmation getWhatIsConfirming(String name) { - return this.confirms.get(name).getConfirming(); - } + private JailMain plugin; + private HashMap jails; + private HashMap jailCreators; + private HashMap cellCreators; + private HashMap confirms; + private HashMap cache; + private JailCreationSteps jcs; + private CellCreationSteps ccs; + + public JailManager(JailMain plugin) { + this.plugin = plugin; + this.jails = new HashMap(); + this.jailCreators = new HashMap(); + this.cellCreators = new HashMap(); + this.confirms = new HashMap(); + this.cache = new HashMap(); + this.jcs = new JailCreationSteps(); + this.ccs = new CellCreationSteps(); + } + + /** Returns the instance of the plugin main class. */ + public JailMain getPlugin() { + return this.plugin; + } + + /** Returns a HashSet of all the jails. */ + public HashSet getJails() { + return new HashSet(jails.values()); + } + + /** Returns an array of all the names of the jails. */ + public String[] getJailNames() { + return this.jails.keySet().toArray(new String[jails.size()]); + } + + /** + * Adds a jail to the collection of them. + * + * @param jail The jail to add + * @param n True if this is a new jail, false if it isn't. + */ + public void addJail(Jail jail, boolean n) { + this.jails.put(jail.getName(), jail); + if(n) plugin.getJailIO().saveJail(jail); + } + + /** + * Removes a {@link Jail}. + * + * @param name of the jail to remove + */ + public void removeJail(String name) { + plugin.getJailIO().removeJail(this.jails.get(name)); + this.jails.remove(name); + } + + /** + * Gets a jail by the given name. + * + * @param name The name of the jail to get. + * @return The {@link Jail} with the given name, if no jail found this will return null. + */ + public Jail getJail(String name) { + return name.isEmpty() ? this.jails.values().iterator().next() : this.jails.get(name); + } + + /** + * Gets the nearest {@link Jail} to the player, if the sender is a player or else it will get the first jail defined. + * + * @param sender The sender who we are looking around. + * @return The nearest {@link Jail} to the sender if it is a player or else the first jail defined. + */ + public Jail getNearestJail(CommandSender sender) { + if(sender instanceof Player) { + Location loc = ((Player) sender).getLocation(); + + Jail j = null; + double len = -1; + + for(Jail jail : jails.values()) { + double clen = jail.getDistance(loc); + + if (clen < len || len == -1) { + len = clen; + j = jail; + } + } + + return (j == null ? jails.values().iterator().next() : j); + }else { + return jails.values().iterator().next(); + } + } + + /** + * Gets the jail which this location is in, will return null if none exist. + * + * @param loc to get the jail from + * @return The jail this block is in, null if no jail found. + */ + public Jail getJailFromLocation(Location loc) { + for(Jail j : jails.values()) { + if(Util.isInsideAB(loc.toVector(), j.getMinPoint().toVector(), j.getMaxPoint().toVector())) { + return j; + } + } + + return null; + } + + /** + * Checks to see if the given name for a {@link Jail} is valid, returns true if it is a valid jail. + * + * @param name The name of the jail to check. + * @return True if a valid jail was found, false if no jail was found. + */ + public boolean isValidJail(String name) { + return this.jails.get(name) != null; + } + + /** + * Gets all the {@link Cell cells} in the jail system, best for system wide count of the cells or touching each cell. + * + * @return HashSet of all the Cells. + */ + public HashSet getAllCells() { + HashSet cells = new HashSet(); + + for(Jail j : jails.values()) + cells.addAll(j.getCells()); + + return cells; + } + + /** + * Adds a prisoner to the cache. + * + * @param cache object to store + * @return The same object given + */ + public CachePrisoner addCacheObject(CachePrisoner cache) { + plugin.debug("Adding " + cache.getPrisoner().getUUID().toString() + " to the cache."); + this.cache.put(cache.getPrisoner().getUUID(), cache); + return cache; + } + + /** + * Checks if the given uuid is in the cache. + * + * @param uuid of the player + * @return true if in cache, false if not + */ + public boolean inCache(UUID uuid) { + return this.cache.containsKey(uuid); + } + + /** + * Gets a cached prisoner object. + * + * @param uuid of the prisoner to get + * @return the cahced prisoner object, will be null if it doesn't exist + */ + public CachePrisoner getCacheObject(UUID uuid) { + return this.cache.get(uuid); + } + + /** + * Removes the cache object stored for this uuid. + * + * @param uuid of the prisoner to remove + */ + public void removeCacheObject(UUID uuid) { + plugin.debug("Removing " + uuid.toString() + " from the cache."); + this.cache.remove(uuid); + } + + /** + * Gets all the prisoners in the system, best for a system wide count of the prisoners or accessing all the prisoners at once. + * + * @return HashSet of Prisoners. + */ + public HashMap getAllPrisoners() { + HashMap prisoners = new HashMap(); + + for(Jail j : jails.values()) + prisoners.putAll(j.getAllPrisoners()); + + return prisoners; + } + + /** + * Gets the {@link Jail jail} the given prisoner is in. + * + * @param prisoner The prisoner data for the prisoner we are checking + * @return The jail the player is in, CAN BE NULL. + */ + public Jail getJailPrisonerIsIn(Prisoner prisoner) { + if(prisoner == null) return null; + else return getJailPlayerIsIn(prisoner.getUUID()); + } + + /** + * Gets the {@link Jail jail} the given player is in. + * + *

+ * + * Checks the cache first. + * + * @param uuid The uuid of the player who's jail we are getting. + * @return The jail the player is in, CAN BE NULL. + */ + public Jail getJailPlayerIsIn(UUID uuid) { + if(this.cache.containsKey(uuid)) { + plugin.debug(uuid.toString() + " is in the cache (getJailPlayerIsIn)."); + return this.cache.get(uuid).getJail(); + } + + for(Jail j : jails.values()) + if(j.isPlayerJailed(uuid)) + return j; + + return null; + } + + /** + * Gets if the given uuid of a player is jailed or not, in all the jails and cells. + * + * @param uuid The uuid of the player to check. + * @return true if they are jailed, false if not. + */ + public boolean isPlayerJailed(UUID uuid) { + return getJailPlayerIsIn(uuid) != null; + } + + /** + * Gets the {@link Prisoner} data from for this user, if they are jailed. + * + * @param uuid The uuid of prisoner who's data to get + * @return {@link Prisoner prisoner} data. + */ + public Prisoner getPrisoner(UUID uuid) { + Jail j = getJailPlayerIsIn(uuid); + + return j == null ? null : j.getPrisoner(uuid); + } + + /** + * Gets the {@link Jail} the player is in from their last known username, null if not jailed. + * + * @param username Last known username to search by + * @return {@link Jail jail} player is in + */ + public Jail getJailPlayerIsInByLastKnownName(String username) { + for(Jail j : jails.values()) + for(Prisoner p : j.getAllPrisoners().values()) + if(p.getLastKnownName().equalsIgnoreCase(username)) + return j; + + return null; + } + + /** + * Gets the {@link Prisoner}'s data from the last known username, returning null if no prisoner has that name. + * + * @param username Last known username to go by + * @return {@link Prisoner prisoner} data + */ + public Prisoner getPrisonerByLastKnownName(String username) { + for(Prisoner p : this.getAllPrisoners().values()) + if(p.getLastKnownName().equalsIgnoreCase(username)) + return p; + + return null; + } + + /** + * Checks if the provided username is jailed, using last known username. + * + * @param username Last known username to go by + * @return true if they are jailed, false if not + */ + public boolean isPlayerJailedByLastKnownUsername(String username) { + return this.getPrisonerByLastKnownName(username) != null; + } + + /** + * Clears a {@link Jail} of all its prisoners if the jail is provided, otherwise it releases all the prisoners in all the jails. + * + * @param jail The name of the jail to release the prisoners in, null if wanting to clear all. + * @return The resulting message to be sent to the caller of this method. + */ + public String clearJailOfPrisoners(String jail) { + //If they don't pass in a jail name, clear all the jails + if(jail != null) { + Jail j = getJail(jail); + + if(j != null) { + for(Prisoner p : j.getAllPrisoners().values()) { + getPlugin().getPrisonerManager().schedulePrisonerRelease(p); + } + + return Lang.PRISONERSCLEARED.get(j.getName()); + }else { + return Lang.NOJAIL.get(jail); + } + }else { + return clearAllJailsOfAllPrisoners(); + } + } + + /** + * Clears all the {@link Jail jails} of prisoners by releasing them. + * + * @return The resulting message to be sent to the caller of this method. + */ + public String clearAllJailsOfAllPrisoners() { + //No name of a jail has been passed, so release all of the prisoners in all the jails + if(getJails().size() == 0) { + return Lang.NOJAILS.get(); + }else { + for(Jail j : getJails()) { + for(Prisoner p : j.getAllPrisoners().values()) { + getPlugin().getPrisonerManager().schedulePrisonerRelease(p); + } + } + + return Lang.PRISONERSCLEARED.get(Lang.ALLJAILS); + } + } + + /** + * Forcefully clears all the jails if name provided is null. + * + *

+ * + * This method just clears them from the storage, doesn't release them. + * + * @param name of the jail to clear, null if all of them. + * @return The resulting message to be sent to the caller of this method. + */ + public String forcefullyClearJailOrJails(String name) { + if(name == null) { + if(getJails().size() == 0) { + return Lang.NOJAILS.get(); + }else { + for(Jail j : getJails()) { + j.clearPrisoners(); + } + + return Lang.PRISONERSCLEARED.get(Lang.ALLJAILS); + } + }else { + Jail j = getJail(name); + + if(j != null) { + j.clearPrisoners(); + return Lang.PRISONERSCLEARED.get(j.getName()); + }else { + return Lang.NOJAIL.get(name); + } + } + } + + /** + * Deletes a jail's cell, checking everything is setup right for it to be deleted. + * + * @param jail Name of the jail to delete a cell in. + * @param cell Name of the cell to delete. + * @return The resulting message to be sent to the caller of this method. + */ + public String deleteJailCell(String jail, String cell) { + //Check if the jail name provided is a valid jail + if(isValidJail(jail)) { + Jail j = getJail(jail); + + //check if the cell is a valid cell + if(j.isValidCell(cell)) { + if(j.getCell(cell).hasPrisoner()) { + //The cell has a prisoner, so tell them to first transfer the prisoner + //or release the prisoner + return Lang.CELLREMOVALUNSUCCESSFUL.get(new String[] { cell, jail }); + }else { + j.removeCell(cell); + return Lang.CELLREMOVED.get(new String[] { cell, jail }); + } + }else { + //No cell found by the provided name in the stated jail + return Lang.NOCELL.get(new String[] { cell, jail }); + } + }else { + //No jail found by the provided name + return Lang.NOJAIL.get(jail); + } + } + + /** + * Deletes all the cells in a jail, returns a list of Strings. + * + * @param jail The name of the jail to delete all the jails in. + * @return An array of strings of messages to send. + */ + public String[] deleteAllJailCells(String jail) { + LinkedList msgs = new LinkedList(); + + //Check if the jail name provided is a valid jail + if(isValidJail(jail)) { + Jail j = getJail(jail); + + if(j.getCellCount() == 0) { + //There are no cells in this jail, thus we can't delete them. + msgs.add(Lang.NOCELLS.get(j.getName())); + }else { + //Keep a local copy of the hashset so that we don't get any CMEs. + HashSet cells = new HashSet(j.getCells()); + + for(Cell c : cells) { + if(c.hasPrisoner()) { + //The cell has a prisoner, so tell them to first transfer the prisoner + //or release the prisoner + msgs.add(Lang.CELLREMOVALUNSUCCESSFUL.get(new String[] { c.getName(), j.getName() })); + }else { + j.removeCell(c.getName()); + msgs.add(Lang.CELLREMOVED.get(new String[] { c.getName(), j.getName() })); + } + } + } + }else { + //No jail found by the provided name + msgs.add(Lang.NOJAIL.get(jail)); + } + + return msgs.toArray(new String[msgs.size()]); + } + + /** + * Deletes a jail while doing some checks to verify it can be deleted. + * + * @param jail The name of the jail to delete. + * @return The resulting message to be sent to the caller of this method. + */ + public String deleteJail(String jail) { + //Check if the jail name provided is a valid jail + if(isValidJail(jail)) { + //check if the jail doesn't contain prisoners + if(getJail(jail).getAllPrisoners().size() == 0) { + //There are no prisoners, so we can delete it + removeJail(jail); + return Lang.JAILREMOVED.get(jail); + }else { + //The jail has prisoners, they need to release them first + return Lang.JAILREMOVALUNSUCCESSFUL.get(jail); + } + }else { + //No jail found by the provided name + return Lang.NOJAIL.get(jail); + } + } + + /** + * Returns whether or not the player is creating a jail or a cell. + * + *

+ * + * If you want to check to see if they're just creating a jail then use {@link #isCreatingAJail(String) isCreatingAJail} or if you want to see if they're creating a cell then use {@link #isCreatingACell(String) isCreatingACell}. + * + * @param name The name of the player, in any case as we convert it to lowercase. + * @return True if the player is creating a jail or cell, false if they're not creating anything. + */ + public boolean isCreatingSomething(String name) { + return this.jailCreators.containsKey(name.toLowerCase()) || this.cellCreators.containsKey(name.toLowerCase()); + } + + /** Returns a message used for telling them what they're creating and what step they're on. */ + public String getStepMessage(String player) { + String message = ""; + + if(isCreatingACell(player)) {//Check whether it is a jail cell + CreationPlayer cp = this.getCellCreationPlayer(player); + message = "You're already creating a Cell with the name '" + cp.getCellName() + "' and you still need to "; + + switch(cp.getStep()) { + case 1: + message += "set the teleport in location."; + break; + case 2: + message += "select all the signs."; + break; + case 3: + message += "set the double chest location."; + break; + } + + }else if(isCreatingAJail(player)) {//If not a cell, then check if a jail. + CreationPlayer cp = this.getJailCreationPlayer(player); + message = "You're already creating a Jail with the name '" + cp.getJailName() + "' and you still need to "; + + switch(cp.getStep()) { + case 1: + message += "select the first point."; + break; + case 2: + message += "select the second point."; + break; + case 3: + message += "set the teleport in location."; + break; + case 4: + message += "set the release location."; + break; + } + } + + return message; + } + + /** Returns whether or not someone is creating a Jail. */ + public boolean isCreatingAJail(String name) { + return this.jailCreators.containsKey(name.toLowerCase()); + } + + /** + * Method for setting a player to be creating a Jail, returns whether or not they were added successfully. + * + * @param player The player who is creating a jail. + * @param jailName The name of the jail we are creating. + * @return True if they were added successfully, false if they are already creating a Jail. + */ + public boolean addCreatingJail(String player, String jailName) { + if(isCreatingAJail(player)) { + return false; + }else { + this.jailCreators.put(player.toLowerCase(), new CreationPlayer(jailName)); + return true; + } + } + + /** Returns the instance of the CreationPlayer for this player, null if there was none found. */ + public CreationPlayer getJailCreationPlayer(String name) { + return this.jailCreators.get(name.toLowerCase()); + } + + /** Removes a CreationPlayer with the given name from the jail creators. */ + public void removeJailCreationPlayer(String name) { + this.jailCreators.remove(name.toLowerCase()); + } + + /** Returns whether or not someone is creating a Cell. */ + public boolean isCreatingACell(String name) { + return this.cellCreators.containsKey(name.toLowerCase()); + } + + /** + * Method for setting a player to be creating a Cell, returns whether or not they were added successfully. + * + * @param player The player who is creating a jail. + * @param jailName The name of the jail this cell is going. + * @param cellName The name of the cell we are creating. + * @return True if they were added successfully, false if they are already creating a Jail. + */ + public boolean addCreatingCell(String player, String jailName, String cellName) { + if(isCreatingACell(player)) { + return false; + }else { + this.cellCreators.put(player.toLowerCase(), new CreationPlayer(jailName, cellName)); + return true; + } + } + + /** Returns the instance of the CreationPlayer for this player, null if there was none found. */ + public CreationPlayer getCellCreationPlayer(String name) { + return this.cellCreators.get(name.toLowerCase()); + } + + /** Removes a CreationPlayer with the given name from the cell creators. */ + public void removeCellCreationPlayer(String name) { + this.cellCreators.remove(name.toLowerCase()); + } + + /** Gets the instance of the {@link JailCreationSteps}. */ + public JailCreationSteps getJailCreationSteps() { + return this.jcs; + } + + /** Gets the instance of the {@link CellCreationSteps}. */ + public CellCreationSteps getCellCreationSteps() { + return this.ccs; + } + + /** Adds something to the confirming list. */ + public void addConfirming(String name, ConfirmPlayer confirmer) { + getPlugin().debug("Adding a confirming for " + name + " to confirm " + confirmer.getConfirming().toString().toLowerCase()); + this.confirms.put(name, confirmer); + } + + /** Removes a name from the confirming list. */ + public void removeConfirming(String name) { + this.confirms.remove(name); + } + + /** Checks if the given name is confirming something. */ + public boolean isConfirming(String name) { + if(this.confirms.containsKey(name)) { + if(this.confirmingHasExpired(name)) { + getPlugin().debug("Removing " + name + "'s confirmation as it expired."); + this.removeConfirming(name); + } + + return this.confirms.containsKey(name); + }else { + return false; + } + } + + /** Returns true if the confirmation has expired, false if it is still valid. */ + public boolean confirmingHasExpired(String name) { + //If the expiry time is LESS than the current time, it has expired + return this.confirms.get(name).getExpiryTime() < System.currentTimeMillis(); + } + + /** Returns the original arguments for what we are confirming. */ + public String[] getOriginalArgs(String name) { + return this.confirms.get(name).getArguments(); + } + + /** Returns what the given name is confirming. */ + public Confirmation getWhatIsConfirming(String name) { + return this.confirms.get(name).getConfirming(); + } } diff --git a/src/main/java/com/graywolf336/jail/JailPayManager.java b/src/main/java/com/graywolf336/jail/JailPayManager.java index 699434a..90728b6 100644 --- a/src/main/java/com/graywolf336/jail/JailPayManager.java +++ b/src/main/java/com/graywolf336/jail/JailPayManager.java @@ -11,157 +11,157 @@ import com.graywolf336.jail.beans.Prisoner; import com.graywolf336.jail.enums.Settings; public class JailPayManager { - private Economy economy = null; - private double minteCost, infiniteCost; - private Material item; - private boolean infinite, timed; - - public JailPayManager(JailMain plugin) { - this.item = Material.getMaterial(plugin.getConfig().getString(Settings.JAILPAYITEM.getPath().toUpperCase())); - if(this.item == null) this.item = Material.AIR; - - this.minteCost = plugin.getConfig().getDouble(Settings.JAILPAYPRICEPERMINUTE.getPath()); - - if(!this.usingItemsForPayment()) { - if(!this.setupEconomy(plugin)) { - plugin.getConfig().set(Settings.JAILPAYENABLED.getPath(), false); - } - } - - this.timed = plugin.getConfig().getDouble(Settings.JAILPAYPRICEPERMINUTE.getPath()) != 0; - this.infinite = plugin.getConfig().getDouble(Settings.JAILPAYPRICEINFINITE.getPath()) != 0; - } - - /** Checks if paying for infinite is enabled. */ - public boolean isInfiniteEnabled() { - return this.infinite; - } - - /** Checks if paying for timed is enabled. */ - public boolean isTimedEnabled() { - return this.timed; - } - - /** Gets how much it cost per minute in string format. */ - public String getCostPerMinute() { - return String.valueOf(this.minteCost); - } - - /** - * Calculates how much players have to pay to get completely free. - * - * @param prisoner data of who we're calculating - * @return The economy cost the prisoner will need to pay to get completely free. - */ - public double calculateBill(Prisoner prisoner) { - return prisoner.getRemainingTime() > 0 ? prisoner.getRemainingTimeInMinutes() * this.minteCost : infiniteCost; - } - - /** Gets how many minutes someone is paying for (rounds to the lowest number). */ - public long getMinutesPayingFor(double amount) { - return (long) Math.floor(amount / this.minteCost); - } - - /** Returns if we are using items for payment instead of economy. */ - public boolean usingItemsForPayment() { - return this.item != Material.AIR; - } - - /** - * Gets the {@link Material} it costs for jail pay, will be air if using economy. - * - * @return The item type it costs, air if using virtual economy. - */ - public Material getItemItCost() { - return this.item; - } - - /** - * Checks if the player has enough money/items to pay what they have said they want to. - * - * @param p The player who is doing the paying. - * @param amt The amount to check they if they have. - * @return true if they have enough, false if not. - */ - public boolean hasEnoughToPay(Player p, double amt) { - if(this.usingItemsForPayment()) { - return p.getInventory().contains(this.item, (int) Math.ceil(amt)); - }else { - - return this.economy.has(p.getName(), amt); - } - } - - /** - * Pays the required fees from the given player, removing items or money from economy. - * - * @param p The player who is paying. - * @param amt The amount of items or money to withdraw from the player. - */ - public void pay(Player p, double amt) { - if(this.usingItemsForPayment()) { - int amtNeeded = (int) Math.ceil(amt); - - for (int i = 0; i < p.getInventory().getSize(); i++) { - ItemStack it = p.getInventory().getItem(i); - - //The item is either air or we doesn't match out needs - if(it == null || it.getType() != this.item) continue; - - //If the itemstack has more than or equal to the amount - //that we need, remove it and subject from the amt needed - if (amtNeeded >= it.getAmount()) { - amtNeeded -= it.getAmount(); - p.getInventory().clear(i); - } else { - //Otherwise, subject from the itemstack just the amount we need - it.setAmount(it.getAmount() - amtNeeded); - p.getInventory().setItem(i, it); - amtNeeded = 0; - } - - if (amtNeeded == 0) break; - } - }else { - this.economy.withdrawPlayer(p.getName(), amt); - } - } - - /** Gets the name of the item in nice capitals. */ - public String getCurrencyName(){ - if(this.usingItemsForPayment()) { - String name = item.toString().replaceAll("_", " "); - - if(name.contains(" ")){ - String[] split = name.split(" "); - for(int i=0; i < split.length; i++){ - split[i] = split[i].substring(0, 1).toUpperCase() + split[i].substring(1).toLowerCase(); - } - - name = ""; - for(String s : split){ - name += " " + s; - } - - name = name.substring(1); - } else { - name = name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase(); - } - - return name; - }else { - return this.economy.currencyNamePlural(); - } - } - - /** Returns the economy provider to do transaction with. */ - public Economy getEconomy() { - return this.economy; - } - - private boolean setupEconomy(JailMain plugin) { - if (economy != null) return true; - + private Economy economy = null; + private double minteCost, infiniteCost; + private Material item; + private boolean infinite, timed; + + public JailPayManager(JailMain plugin) { + this.item = Material.getMaterial(plugin.getConfig().getString(Settings.JAILPAYITEM.getPath().toUpperCase())); + if(this.item == null) this.item = Material.AIR; + + this.minteCost = plugin.getConfig().getDouble(Settings.JAILPAYPRICEPERMINUTE.getPath()); + + if(!this.usingItemsForPayment()) { + if(!this.setupEconomy(plugin)) { + plugin.getConfig().set(Settings.JAILPAYENABLED.getPath(), false); + } + } + + this.timed = plugin.getConfig().getDouble(Settings.JAILPAYPRICEPERMINUTE.getPath()) != 0; + this.infinite = plugin.getConfig().getDouble(Settings.JAILPAYPRICEINFINITE.getPath()) != 0; + } + + /** Checks if paying for infinite is enabled. */ + public boolean isInfiniteEnabled() { + return this.infinite; + } + + /** Checks if paying for timed is enabled. */ + public boolean isTimedEnabled() { + return this.timed; + } + + /** Gets how much it cost per minute in string format. */ + public String getCostPerMinute() { + return String.valueOf(this.minteCost); + } + + /** + * Calculates how much players have to pay to get completely free. + * + * @param prisoner data of who we're calculating + * @return The economy cost the prisoner will need to pay to get completely free. + */ + public double calculateBill(Prisoner prisoner) { + return prisoner.getRemainingTime() > 0 ? prisoner.getRemainingTimeInMinutes() * this.minteCost : infiniteCost; + } + + /** Gets how many minutes someone is paying for (rounds to the lowest number). */ + public long getMinutesPayingFor(double amount) { + return (long) Math.floor(amount / this.minteCost); + } + + /** Returns if we are using items for payment instead of economy. */ + public boolean usingItemsForPayment() { + return this.item != Material.AIR; + } + + /** + * Gets the {@link Material} it costs for jail pay, will be air if using economy. + * + * @return The item type it costs, air if using virtual economy. + */ + public Material getItemItCost() { + return this.item; + } + + /** + * Checks if the player has enough money/items to pay what they have said they want to. + * + * @param p The player who is doing the paying. + * @param amt The amount to check they if they have. + * @return true if they have enough, false if not. + */ + public boolean hasEnoughToPay(Player p, double amt) { + if(this.usingItemsForPayment()) { + return p.getInventory().contains(this.item, (int) Math.ceil(amt)); + }else { + + return this.economy.has(p.getName(), amt); + } + } + + /** + * Pays the required fees from the given player, removing items or money from economy. + * + * @param p The player who is paying. + * @param amt The amount of items or money to withdraw from the player. + */ + public void pay(Player p, double amt) { + if(this.usingItemsForPayment()) { + int amtNeeded = (int) Math.ceil(amt); + + for (int i = 0; i < p.getInventory().getSize(); i++) { + ItemStack it = p.getInventory().getItem(i); + + //The item is either air or we doesn't match out needs + if(it == null || it.getType() != this.item) continue; + + //If the itemstack has more than or equal to the amount + //that we need, remove it and subject from the amt needed + if (amtNeeded >= it.getAmount()) { + amtNeeded -= it.getAmount(); + p.getInventory().clear(i); + } else { + //Otherwise, subject from the itemstack just the amount we need + it.setAmount(it.getAmount() - amtNeeded); + p.getInventory().setItem(i, it); + amtNeeded = 0; + } + + if (amtNeeded == 0) break; + } + }else { + this.economy.withdrawPlayer(p.getName(), amt); + } + } + + /** Gets the name of the item in nice capitals. */ + public String getCurrencyName(){ + if(this.usingItemsForPayment()) { + String name = item.toString().replaceAll("_", " "); + + if(name.contains(" ")){ + String[] split = name.split(" "); + for(int i=0; i < split.length; i++){ + split[i] = split[i].substring(0, 1).toUpperCase() + split[i].substring(1).toLowerCase(); + } + + name = ""; + for(String s : split){ + name += " " + s; + } + + name = name.substring(1); + } else { + name = name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase(); + } + + return name; + }else { + return this.economy.currencyNamePlural(); + } + } + + /** Returns the economy provider to do transaction with. */ + public Economy getEconomy() { + return this.economy; + } + + private boolean setupEconomy(JailMain plugin) { + if (economy != null) return true; + RegisteredServiceProvider economyProvider = plugin.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); if (economyProvider != null) { economy = economyProvider.getProvider(); diff --git a/src/main/java/com/graywolf336/jail/JailStickManager.java b/src/main/java/com/graywolf336/jail/JailStickManager.java index 7e50609..2bef633 100644 --- a/src/main/java/com/graywolf336/jail/JailStickManager.java +++ b/src/main/java/com/graywolf336/jail/JailStickManager.java @@ -18,134 +18,134 @@ import com.graywolf336.jail.enums.Settings; * */ public class JailStickManager { - private ArrayList stickers; - private HashMap sticks; - - public JailStickManager(JailMain plugin) { - this.stickers = new ArrayList(); - this.sticks = new HashMap(); - - this.loadJailSticks(plugin); - } - - private void loadJailSticks(JailMain pl) { - //item name,time,jail name,reason - if(pl.getJailManager().getJails().size() == 0) { - pl.getLogger().warning("Can't have jail sticks without any jails."); - }else { - for(String s : pl.getConfig().getStringList(Settings.JAILSTICKSTICKS.getPath())) { - pl.debug(s); - String[] a = s.split(","); - String jail = a[2]; - - //Check if the jail given, if any, exists - if(jail.isEmpty()) { - jail = pl.getJailManager().getJail("").getName(); - }else { - if(!pl.getJailManager().isValidJail(jail)) { - pl.getLogger().severe(s); - pl.getLogger().severe("The above jail stick configuration is invalid and references a jail that doesn't exist."); - continue; - } - } - - Material m = Material.getMaterial(a[0].toUpperCase()); - if(this.sticks.containsKey(m)) { - pl.getLogger().severe(s); - pl.getLogger().severe("You can not use the same item for two different Jail Sticks. This already exists as a Jail Stick: " + a[0]); - continue; - } - - long time = 5; - try { - time = Util.getTime(a[1]); - } catch (Exception e) { - pl.getLogger().severe(s); - pl.getLogger().severe("The time format on the above jail stick configuration is incorrect."); - continue; - } - - double health = -1; - if(a.length > 5) health = Double.valueOf(a[4]); - - try { - this.sticks.put(m, new Stick(jail, a[3], time, health)); - }catch (Exception e) { - e.printStackTrace(); - pl.getLogger().severe(s); - pl.getLogger().severe("Unable to create a new stick for " + a[0] + ", see the exception above for details."); - continue; - } - } - } - - int c = sticks.size(); - pl.getLogger().info("Loaded " + c + " jail stick" + (c == 1 ? "" : "s") + "."); - } - - /** - * Gets the {@link Stick jail stick} by the provided {@link Material}, can be null. - * - * @param mat of the stick to get - * @return The {@link Stick jail stick} - */ - public Stick getStick(Material mat) { - return this.sticks.get(mat); - } - - /** Checks if the provided Material is a valid {@link Stick jail stick}. */ - public boolean isValidStick(Material mat) { - return this.sticks.containsKey(mat); - } - - /** - * Adds a player to be using a jail stick, with the uuid of the player. - * - * @param id of the player to add - */ - public void addUsingStick(UUID id) { - this.stickers.add(id); - } - - /** - * Removes a player from using a jail stick, with the uuid of the player. - * - * @param id of the player to remove using a jail stick - */ - public void removeUsingStick(UUID id) { - this.stickers.remove(id); - } - - /** - * Returns whether or not the player is using a jail stick. - * - * @param id of the player to check if using one - * @return true if the player is using a jail stick, false if not - */ - public boolean isUsingJailStick(UUID id) { - return this.stickers.contains(id); - } - - /** - * Toggles whether the player is using a jail stick, returning the true if enabled false if disabled. - * - * @param id of the player to toggle using a stick - * @return true if we enabled it, false if we disabled it. - */ - public boolean toggleUsingStick(UUID id) { - if(this.stickers.contains(id)) { - this.stickers.remove(id); - return false; - }else { - this.stickers.add(id); - return true; - } - } - - /** Removes all the users currently using the sticks. */ - public void removeAllStickUsers() { - for(UUID id : stickers) { - this.removeUsingStick(id); - } - } + private ArrayList stickers; + private HashMap sticks; + + public JailStickManager(JailMain plugin) { + this.stickers = new ArrayList(); + this.sticks = new HashMap(); + + this.loadJailSticks(plugin); + } + + private void loadJailSticks(JailMain pl) { + //item name,time,jail name,reason + if(pl.getJailManager().getJails().size() == 0) { + pl.getLogger().warning("Can't have jail sticks without any jails."); + }else { + for(String s : pl.getConfig().getStringList(Settings.JAILSTICKSTICKS.getPath())) { + pl.debug(s); + String[] a = s.split(","); + String jail = a[2]; + + //Check if the jail given, if any, exists + if(jail.isEmpty()) { + jail = pl.getJailManager().getJail("").getName(); + }else { + if(!pl.getJailManager().isValidJail(jail)) { + pl.getLogger().severe(s); + pl.getLogger().severe("The above jail stick configuration is invalid and references a jail that doesn't exist."); + continue; + } + } + + Material m = Material.getMaterial(a[0].toUpperCase()); + if(this.sticks.containsKey(m)) { + pl.getLogger().severe(s); + pl.getLogger().severe("You can not use the same item for two different Jail Sticks. This already exists as a Jail Stick: " + a[0]); + continue; + } + + long time = 5; + try { + time = Util.getTime(a[1]); + } catch (Exception e) { + pl.getLogger().severe(s); + pl.getLogger().severe("The time format on the above jail stick configuration is incorrect."); + continue; + } + + double health = -1; + if(a.length > 5) health = Double.valueOf(a[4]); + + try { + this.sticks.put(m, new Stick(jail, a[3], time, health)); + }catch (Exception e) { + e.printStackTrace(); + pl.getLogger().severe(s); + pl.getLogger().severe("Unable to create a new stick for " + a[0] + ", see the exception above for details."); + continue; + } + } + } + + int c = sticks.size(); + pl.getLogger().info("Loaded " + c + " jail stick" + (c == 1 ? "" : "s") + "."); + } + + /** + * Gets the {@link Stick jail stick} by the provided {@link Material}, can be null. + * + * @param mat of the stick to get + * @return The {@link Stick jail stick} + */ + public Stick getStick(Material mat) { + return this.sticks.get(mat); + } + + /** Checks if the provided Material is a valid {@link Stick jail stick}. */ + public boolean isValidStick(Material mat) { + return this.sticks.containsKey(mat); + } + + /** + * Adds a player to be using a jail stick, with the uuid of the player. + * + * @param id of the player to add + */ + public void addUsingStick(UUID id) { + this.stickers.add(id); + } + + /** + * Removes a player from using a jail stick, with the uuid of the player. + * + * @param id of the player to remove using a jail stick + */ + public void removeUsingStick(UUID id) { + this.stickers.remove(id); + } + + /** + * Returns whether or not the player is using a jail stick. + * + * @param id of the player to check if using one + * @return true if the player is using a jail stick, false if not + */ + public boolean isUsingJailStick(UUID id) { + return this.stickers.contains(id); + } + + /** + * Toggles whether the player is using a jail stick, returning the true if enabled false if disabled. + * + * @param id of the player to toggle using a stick + * @return true if we enabled it, false if we disabled it. + */ + public boolean toggleUsingStick(UUID id) { + if(this.stickers.contains(id)) { + this.stickers.remove(id); + return false; + }else { + this.stickers.add(id); + return true; + } + } + + /** Removes all the users currently using the sticks. */ + public void removeAllStickUsers() { + for(UUID id : stickers) { + this.removeUsingStick(id); + } + } } diff --git a/src/main/java/com/graywolf336/jail/JailTimer.java b/src/main/java/com/graywolf336/jail/JailTimer.java index fc02e7c..5375aa6 100644 --- a/src/main/java/com/graywolf336/jail/JailTimer.java +++ b/src/main/java/com/graywolf336/jail/JailTimer.java @@ -21,87 +21,87 @@ import com.graywolf336.jail.enums.Settings; * */ public class JailTimer { - private JailMain pl; - private Timer timer; - private Long lastTime; - private Long afkTime = 0L; - - public JailTimer(JailMain plugin) { - this.pl = plugin; - try { - afkTime = Util.getTime(pl.getConfig().getString(Settings.MAXAFKTIME.getPath())); - } catch (Exception e) { - pl.getLogger().severe("Error while processing the max afk time: " + e.getMessage()); - } - - this.lastTime = System.currentTimeMillis(); - if(pl.getConfig().getBoolean(Settings.USEBUKKITTIMER.getPath())) { - pl.getLogger().info("Using the Bukkit Scheduler."); - pl.getServer().getScheduler().runTaskTimerAsynchronously(pl, new TimeEvent(), 200, 200); - }else { - pl.getLogger().info("Using the Java Timer."); - timer = new Timer(10000, new ActionListener () { - public void actionPerformed (ActionEvent event) { - pl.getServer().getScheduler().scheduleSyncDelayedTask(pl, new TimeEvent()); - }; - }); - - timer.start(); - } - - //Save all the jail information every minute, not every 10 seconds - pl.getServer().getScheduler().runTaskTimerAsynchronously(pl, new Runnable() { - public void run() { - for(Jail j : pl.getJailManager().getJails()) { - pl.getJailIO().saveJail(j); - } - } - }, 1200L, 1200L); - } - - /** Returns the instance of this timer. */ - public Timer getTimer() { - return this.timer; - } - - class TimeEvent implements Runnable { - public void run() { - long timePassed = System.currentTimeMillis() - lastTime; - lastTime = System.currentTimeMillis(); - - for(Jail j : pl.getJailManager().getJails()) { - for(Prisoner p : j.getAllPrisoners().values()) { - //only execute this code if the prisoner's time is more than 0 milliseconds - //and they don't have any offline pending things - if(p.getRemainingTime() > 0 && !p.isOfflinePending()) { - Player player = pl.getServer().getPlayer(p.getUUID()); - - //Check if the player is offline - if(player == null) { - //if they are offline AND the config has counting down the time - //while the prisoner is offline, then let's do it - if(pl.getConfig().getBoolean(Settings.COUNTDOWNTIMEOFFLINE.getPath())) { - //Set their remaining time but if it is less than zero, set it to zero - p.setRemainingTime(Math.max(0, p.getRemainingTime() - timePassed)); - if(p.getRemainingTime() == 0) pl.getPrisonerManager().schedulePrisonerRelease(p); - } - }else { - if(afkTime > 0) { - p.setAFKTime(p.getAFKTime() + timePassed); - if(p.getAFKTime() > afkTime) { - p.setAFKTime(0); - player.kickPlayer(Lang.AFKKICKMESSAGE.get()); - } - } - - //The prisoner isn't offline, so let's count down - //Set their remaining time but if it is less than zero, set it to zero - p.setRemainingTime(Math.max(0, p.getRemainingTime() - timePassed)); - if(p.getRemainingTime() == 0) pl.getPrisonerManager().schedulePrisonerRelease(p); - } - } - } - } - } - } + private JailMain pl; + private Timer timer; + private Long lastTime; + private Long afkTime = 0L; + + public JailTimer(JailMain plugin) { + this.pl = plugin; + try { + afkTime = Util.getTime(pl.getConfig().getString(Settings.MAXAFKTIME.getPath())); + } catch (Exception e) { + pl.getLogger().severe("Error while processing the max afk time: " + e.getMessage()); + } + + this.lastTime = System.currentTimeMillis(); + if(pl.getConfig().getBoolean(Settings.USEBUKKITTIMER.getPath())) { + pl.getLogger().info("Using the Bukkit Scheduler."); + pl.getServer().getScheduler().runTaskTimerAsynchronously(pl, new TimeEvent(), 200, 200); + }else { + pl.getLogger().info("Using the Java Timer."); + timer = new Timer(10000, new ActionListener () { + public void actionPerformed (ActionEvent event) { + pl.getServer().getScheduler().scheduleSyncDelayedTask(pl, new TimeEvent()); + }; + }); + + timer.start(); + } + + //Save all the jail information every minute, not every 10 seconds + pl.getServer().getScheduler().runTaskTimerAsynchronously(pl, new Runnable() { + public void run() { + for(Jail j : pl.getJailManager().getJails()) { + pl.getJailIO().saveJail(j); + } + } + }, 1200L, 1200L); + } + + /** Returns the instance of this timer. */ + public Timer getTimer() { + return this.timer; + } + + class TimeEvent implements Runnable { + public void run() { + long timePassed = System.currentTimeMillis() - lastTime; + lastTime = System.currentTimeMillis(); + + for(Jail j : pl.getJailManager().getJails()) { + for(Prisoner p : j.getAllPrisoners().values()) { + //only execute this code if the prisoner's time is more than 0 milliseconds + //and they don't have any offline pending things + if(p.getRemainingTime() > 0 && !p.isOfflinePending()) { + Player player = pl.getServer().getPlayer(p.getUUID()); + + //Check if the player is offline + if(player == null) { + //if they are offline AND the config has counting down the time + //while the prisoner is offline, then let's do it + if(pl.getConfig().getBoolean(Settings.COUNTDOWNTIMEOFFLINE.getPath())) { + //Set their remaining time but if it is less than zero, set it to zero + p.setRemainingTime(Math.max(0, p.getRemainingTime() - timePassed)); + if(p.getRemainingTime() == 0) pl.getPrisonerManager().schedulePrisonerRelease(p); + } + }else { + if(afkTime > 0) { + p.setAFKTime(p.getAFKTime() + timePassed); + if(p.getAFKTime() > afkTime) { + p.setAFKTime(0); + player.kickPlayer(Lang.AFKKICKMESSAGE.get()); + } + } + + //The prisoner isn't offline, so let's count down + //Set their remaining time but if it is less than zero, set it to zero + p.setRemainingTime(Math.max(0, p.getRemainingTime() - timePassed)); + if(p.getRemainingTime() == 0) pl.getPrisonerManager().schedulePrisonerRelease(p); + } + } + } + } + } + } } diff --git a/src/main/java/com/graywolf336/jail/JailsAPI.java b/src/main/java/com/graywolf336/jail/JailsAPI.java index 777dfd2..03bc7e2 100644 --- a/src/main/java/com/graywolf336/jail/JailsAPI.java +++ b/src/main/java/com/graywolf336/jail/JailsAPI.java @@ -13,39 +13,39 @@ package com.graywolf336.jail; * @since 3.0.0 */ public class JailsAPI { - private static JailMain pl; - - public JailsAPI(JailMain plugin) { - pl = plugin; - } - - /** - * The instance of the {@link JailManager} which contains all the jails and in return prisoners. - * - * @return instance of the {@link JailManager} - * @see JailManager - */ - public static JailManager getJailManager() { - return pl.getJailManager(); - } - - /** - * The instance of the {@link PrisonerManager} which handles all the jailing of players. - * - * @return instance of the {@link PrisonerManager} - * @see PrisonerManager - */ - public static PrisonerManager getPrisonerManager() { - return pl.getPrisonerManager(); - } - - /** - * The instance of the {@link HandCuffManager} which handles all the handcuffing of players. - * - * @return instance of the {@link HandCuffManager} - * @see HandCuffManager - */ - public static HandCuffManager getHandCuffManager() { - return pl.getHandCuffManager(); - } + private static JailMain pl; + + public JailsAPI(JailMain plugin) { + pl = plugin; + } + + /** + * The instance of the {@link JailManager} which contains all the jails and in return prisoners. + * + * @return instance of the {@link JailManager} + * @see JailManager + */ + public static JailManager getJailManager() { + return pl.getJailManager(); + } + + /** + * The instance of the {@link PrisonerManager} which handles all the jailing of players. + * + * @return instance of the {@link PrisonerManager} + * @see PrisonerManager + */ + public static PrisonerManager getPrisonerManager() { + return pl.getPrisonerManager(); + } + + /** + * The instance of the {@link HandCuffManager} which handles all the handcuffing of players. + * + * @return instance of the {@link HandCuffManager} + * @see HandCuffManager + */ + public static HandCuffManager getHandCuffManager() { + return pl.getHandCuffManager(); + } } diff --git a/src/main/java/com/graywolf336/jail/PrisonerManager.java b/src/main/java/com/graywolf336/jail/PrisonerManager.java index a490aa5..071ba07 100644 --- a/src/main/java/com/graywolf336/jail/PrisonerManager.java +++ b/src/main/java/com/graywolf336/jail/PrisonerManager.java @@ -41,641 +41,641 @@ import com.graywolf336.jail.events.PrisonerTransferredEvent; * @version 3.0.0 */ public class PrisonerManager { - private JailMain pl; - private ArrayList releases; - - public PrisonerManager(JailMain plugin) { - this.pl = plugin; - this.releases = new ArrayList(); - - // Schedule the releasing of prisoners - plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() { - public void run() { - releaseScheduledPrisoners(); - } - }, 100L, 20L); - } - - /** - * Does everything preparing for the jailing of the provided prisoner, if they are online it forwards it to {@link #jailPrisoner(Jail, Cell, Player, Prisoner)}. - * - *

- * - * In this we do the following: - *

    - *
  1. Checks if the jail is null, if so it throws an Exception
  2. - *
  3. Checks if the prisoner is null, if so it throws an Exception
  4. - *
  5. Sets the prisoner data to offline pending or not, player == null
  6. - *
  7. If the cell is null, add the prisoner data to the jail otherwise we set the cell's prisoner to this one. Check before here if the cell already contains a prisoner.
  8. - *
  9. Saves the jail information, goes out to the {@link JailIO} to initate a save.
  10. - *
  11. If the prisoner is not offline, we will actually {@link #jailPrisoner(Jail, Cell, Player, Prisoner) jail} them now.
  12. - *
  13. Does checks to get the right message for the next two items.
  14. - *
  15. If we broadcast the jailing, then let's broadcast it.
  16. - *
  17. If we log the jailing to console and we haven't broadcasted it, then we log it to the console.
  18. - *
- * - * @param jail The {@link Jail jail instance} we are sending this prisoner to - * @param cell The name of the {@link Cell cell} we are sending this prisoner to - * @param player The {@link Player player} we are preparing the jail for. - * @param prisoner The {@link Prisoner prisoner} file. - * @throws Exception if the jail or prisoner are null. - */ - public void prepareJail(Jail jail, Cell cell, Player player, Prisoner prisoner) throws Exception { - //Do some checks of whether the passed params are null. - if(jail == null) - throw new Exception("The jail can not be null."); - - if(prisoner == null) - throw new Exception("Prisoner data can not be null."); - - //Set whether the prisoner is offline or not. - prisoner.setOfflinePending(player == null); - - //Now that we've got those checks out of the way, let's start preparing. - if(cell == null) { - jail.addPrisoner(prisoner); - }else { - cell.setPrisoner(prisoner); - } - - //If they are NOT offline, jail them - if(!prisoner.isOfflinePending()) { - jailPrisoner(jail, cell, player, prisoner); - } - - //Get a message ready for broadcasting or logging. - String msg = ""; - - if(prisoner.getRemainingTime() < 0L) - msg = Lang.BROADCASTMESSAGEFOREVER.get(prisoner.getLastKnownName()); - else - msg = Lang.BROADCASTMESSAGEFORMINUTES.get(new String[] { prisoner.getLastKnownName(), String.valueOf(prisoner.getRemainingTimeInMinutes()) }); - - boolean broadcasted = false; - //Broadcast the message, if it is enabled - if(pl.getConfig().getBoolean(Settings.BROADCASTJAILING.getPath(), false)) { - pl.getServer().broadcastMessage(msg); - broadcasted = true; - } - - //Log the message, if it is enabled - if(pl.getConfig().getBoolean(Settings.LOGJAILINGTOCONSOLE.getPath(), true) && !broadcasted) { - pl.getServer().getConsoleSender().sendMessage(msg); - } - } - - /** - * Jails the given player, only use when that player has offline data pending. - * - * @param uuid of the player to jail. - */ - public void jailPlayer(UUID uuid) { - Jail j = pl.getJailManager().getJailPlayerIsIn(uuid); - jailPrisoner(j, j.getCellPrisonerIsIn(uuid), pl.getServer().getPlayer(uuid), j.getPrisoner(uuid)); - } - - /** - * Jails the prisoner with the proper information given. - * - * @param jail where they are going - * @param cell where they are being placed in, can be null - * @param player who is the prisoner - * @param prisoner data containing everything pertaining to them - */ - public void jailPrisoner(Jail jail, Cell cell, Player player, Prisoner prisoner) { - //If they have handcuffs on them, then let's remove them before we continue - //this way the handcuff listeners and this aren't battleing each other - if(pl.getHandCuffManager().isHandCuffed(player.getUniqueId())) { - pl.getHandCuffManager().removeHandCuffs(player.getUniqueId()); - } - - //They are no longer offline, so set that. - prisoner.setOfflinePending(false); - - //We are getting ready to teleport them, so set it to true so that - //the *future* move checkers won't be canceling our moving. - prisoner.setTeleporting(true); - - //If their reason is empty send proper message, else send other proper message - if(prisoner.getReason().isEmpty()) { - player.sendMessage(Lang.JAILED.get()); - }else { - player.sendMessage(Lang.JAILEDWITHREASON.get(prisoner.getReason())); - } - - //If the config has releasing them back to their previous position, - //then let's set it in the prisoner data. - if(pl.getConfig().getBoolean(Settings.RELEASETOPREVIOUSPOSITION.getPath(), false)) { - prisoner.setPreviousPosition(player.getLocation()); - } - - //If the config has restoring their previous gamemode enabled, - //then let's set it in their prisoner data. - if(pl.getConfig().getBoolean(Settings.RESTOREPREVIOUSGAMEMODE.getPath(), false)) { - prisoner.setPreviousGameMode(player.getGameMode()); - } - - //Set their gamemode to the one in the config, if we get a null value - //from the parsing then we set theirs to adventure - try { - player.setGameMode(GameMode.valueOf(pl.getConfig().getString(Settings.JAILEDGAMEMODE.getPath(), "ADVENTURE").toUpperCase())); - }catch(Exception e) { - pl.getLogger().severe("Your jailedgamemode setting is incorrect, please fix."); - player.setGameMode(GameMode.ADVENTURE); - } - - //only eject them if they're inside a vehicle and also eject anyone else on top of them - if(player.isInsideVehicle()) { - player.getVehicle().eject(); - player.getPassenger().eject(); - player.eject(); - } - - //If we are ignoring the sleeping state of prisoners, - //then let's set that - if(pl.getConfig().getBoolean(Settings.IGNORESLEEPINGSTATE.getPath(), true)) { - player.setSleepingIgnored(true); - } - - //Get the max and min food level in the config - int maxFood = pl.getConfig().getInt(Settings.FOODCONTROLMAX.getPath(), 20); - int minFood = pl.getConfig().getInt(Settings.FOODCONTROLMIN.getPath(), 10); - - //If their food level is less than the min food level, set it to the min - //but if it is higher than the max, set it to the max - if (player.getFoodLevel() < minFood) { - player.setFoodLevel(minFood); - } else if (player.getFoodLevel() > maxFood) { - player.setFoodLevel(maxFood); - } - - //If the cell doesn't equal null, then let's put them in the jail - if(cell != null) { - //check if we store the inventory - if(pl.getConfig().getBoolean(Settings.JAILEDSTOREINVENTORY.getPath(), true)) { - List blacklist = pl.getConfig().getStringList(Settings.JAILEDINVENTORYBLACKLIST.getPath()); - //Check if there is a chest to store our items to and if it is a double chest, if not we will then serialize it - if(cell.hasChest()) { - //Get the chest's inventory and then clear it - Inventory chest = cell.getChest().getInventory(); - chest.clear(); - - //Get the separate inventory, so we can iterate of them - ItemStack[] inventory = player.getInventory().getContents(); - ItemStack[] armor = player.getInventory().getArmorContents(); - - for(ItemStack item : inventory) { - if(item != null) { - if(!Util.isStringInsideList(blacklist, item.getType().toString())) { - int i = chest.firstEmpty(); - if(i != -1) {//Check that we have got a free spot, should never happen but just in case - chest.setItem(i, item); - } - } - } - } - - for(ItemStack item : armor) { - if(item != null) { - if(!Util.isStringInsideList(blacklist, item.getType().toString())) { - int i = chest.firstEmpty(); - if(i != -1) {//Check that we have got a free spot, should never happen but just in case - chest.setItem(i, item); - } - } - } - } - - player.getInventory().setArmorContents(null); - player.getInventory().clear(); - - //Here so we don't forget about it later as this method isn't finished, but - //Updates the cell's signs - cell.update(); - }else { - for(ItemStack item : player.getInventory().getContents()) - if(item != null) - if(Util.isStringInsideList(blacklist, item.getType().toString())) - player.getInventory().remove(item); - - for(ItemStack item : player.getInventory().getArmorContents()) - if(item != null) - if(Util.isStringInsideList(blacklist, item.getType().toString())) - player.getInventory().remove(item); - - String[] inv = Util.playerInventoryToBase64(player.getInventory()); - prisoner.setInventory(inv[0]); - prisoner.setArmor(inv[1]); - - player.getInventory().setArmorContents(null); - player.getInventory().clear(); - } - } - - //Teleport them to the cell's teleport location - //they will now be placed in jail. - pl.debug("Teleporting " + player.getName() + " to " + jail.getName() + " in the cell " + cell.getName() + "'s in: " + jail.getTeleportIn().toString()); - player.teleport(cell.getTeleport()); - }else { - //There is no cell we're jailing them to, so stick them in the jail - if(pl.getConfig().getBoolean(Settings.JAILEDSTOREINVENTORY.getPath(), true)) { - List blacklist = pl.getConfig().getStringList(Settings.JAILEDINVENTORYBLACKLIST.getPath()); - - for(ItemStack item : player.getInventory().getContents()) - if(item != null) - if(Util.isStringInsideList(blacklist, item.getType().toString())) - player.getInventory().remove(item); - - for(ItemStack item : player.getInventory().getArmorContents()) - if(item != null) - if(Util.isStringInsideList(blacklist, item.getType().toString())) - player.getInventory().remove(item); - - String[] inv = Util.playerInventoryToBase64(player.getInventory()); - prisoner.setInventory(inv[0]); - prisoner.setArmor(inv[1]); - - player.getInventory().setArmorContents(null); - player.getInventory().clear(); - } - - //Teleport them to the jail's teleport in location - //They will now be placed in jail. - pl.debug("Teleporting " + player.getName() + " to " + jail.getName() + "'s in: " + jail.getTeleportIn().toString()); - player.teleport(jail.getTeleportIn()); - } - - //Set them to not allowing teleporting, as we are not going to be moving them anymore - //this way the move checkers will start checking this player. - prisoner.setTeleporting(false); - - //Get the commands to execute after they are jailed - //replace all of the %p% so that the commands can have a player name in them - for(String command : pl.getConfig().getStringList(Settings.COMMANDSONJAIL.getPath())) { - command = command.replaceAll("%p%", player.getName()); - pl.getServer().dispatchCommand(pl.getServer().getConsoleSender(), command); - } - - //Add the scoreboard to them if it is enabled - if(pl.getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) { - pl.getScoreBoardManager().addScoreBoard(player, prisoner); - } - - //Save the data, as we have changed it - pl.getJailIO().saveJail(jail); - - //Call our custom event for when a prisoner is actually jailed. - PrisonerJailedEvent event = new PrisonerJailedEvent(jail, cell, prisoner, player); - pl.getServer().getPluginManager().callEvent(event); - } - - /** - * Schedules a prisoner to be released, this method is to be used async. - * - * @param prisoner to be released. - * @see {@link #unJail(Jail, Cell, Player, Prisoner, CommandSender)} - If you're wanting to unjail a prisoner. - */ - public void schedulePrisonerRelease(Prisoner prisoner) { - releases.add(prisoner); - } - - private void releaseScheduledPrisoners() { - ArrayList lettingGo = new ArrayList(releases); - for(Prisoner p : lettingGo) { - releases.remove(p); - releasePrisoner(pl.getServer().getPlayer(p.getUUID()), p); - } - } - - /** - * Release the given prisoner from jailing, does the checks if they are offline or not. - * - * @param player we are releasing, can be null and if so they'll be treated as offline. - * @param prisoner data to handle. - */ - private void releasePrisoner(Player player, Prisoner prisoner) { - if(player == null) { - prisoner.setOfflinePending(true); - prisoner.setRemainingTime(0); - }else { - Jail j = pl.getJailManager().getJailPlayerIsIn(player.getUniqueId()); - - try { - unJail(j, j.getCellPrisonerIsIn(player.getUniqueId()), player, prisoner, null); - }catch(Exception e) { - if(pl.inDebug()) { - e.printStackTrace(); - } - - pl.getLogger().severe("Unable to unjail the prisoner " + player.getName() + " because '" + e.getMessage() + "'."); - } - - } - } - - /** - * Unjails a prisoner from jail, removing all their data. - * - *

- * - * Throws an exception if either the jail is null or the prisoner is null. - * - * @param jail where the prisoner is located at - * @param cell which the prisoner is in, can be null - * @param player instance for the prisoner we're unjailing - * @param prisoner data where everything resides - * @param sender The {@link CommandSender} who unjailed this player, can be null. - * @throws Exception - */ - public void unJail(Jail jail, Cell cell, Player player, Prisoner prisoner, CommandSender sender) throws Exception { - //Do some checks of whether the passed params are null. - if(jail == null) - throw new Exception("The jail can not be null."); - - if(prisoner == null) - throw new Exception("Prisoner data can not be null."); - - //Throw the custom event which is called before we start releasing them - PrePrisonerReleasedEvent preEvent = new PrePrisonerReleasedEvent(jail, cell, prisoner, player); - pl.getServer().getPluginManager().callEvent(preEvent); - - //We are getting ready to teleport them, so set it to true so that - //the *future* move checkers won't be canceling our moving. - prisoner.setTeleporting(true); - - //In case they have somehow got on a vehicle, let's unmount - //them so we can possibly teleport them - if(player.isInsideVehicle()) { - player.getVehicle().eject(); - player.getPassenger().eject(); - player.eject(); - } - - //In case we had set their sleeping state to be ignored - //let's enable their sleeping state taking place again - player.setSleepingIgnored(false); - - //If the config has us teleporting them back to their - //previous position then let's do that - boolean tpd = false; - if(pl.getConfig().getBoolean(Settings.RELEASETOPREVIOUSPOSITION.getPath(), false)) { - if(prisoner.getPreviousLocation() != null) - tpd = player.teleport(prisoner.getPreviousLocation()); - } - - //If they haven't already been teleported and the config has us to teleport on release, - //then we teleport players to the jail's free spot - if(!tpd && pl.getConfig().getBoolean(Settings.TELEPORTONRELEASE.getPath(), true)) { - player.teleport(jail.getTeleportFree()); - } - - //If we are to restore their previous gamemode and we have it stored, - //then by all means let's restore it - if(pl.getConfig().getBoolean(Settings.RESTOREPREVIOUSGAMEMODE.getPath(), false)) { - player.setGameMode(prisoner.getPreviousGameMode()); - } - - //Now, let's restore their inventory - //First up, clear their inventory - player.closeInventory(); - player.getInventory().setArmorContents(null); - player.getInventory().clear(); - - //if the cell isn't null, let's check if the cell has a chest and if so then try out best to restore - //the prisoner's inventory from that - if(cell != null) { - if(cell.hasChest()) { - Inventory chest = cell.getChest().getInventory(); - - for (ItemStack item : chest.getContents()) { - if (item == null || item.getType() == Material.AIR) continue; - - if(item.getType().toString().toLowerCase().contains("helmet") && (player.getInventory().getHelmet() == null || player.getInventory().getHelmet().getType() == Material.AIR)) { - player.getInventory().setHelmet(item); - } else if(item.getType().toString().toLowerCase().contains("chestplate") && (player.getInventory().getChestplate() == null || player.getInventory().getChestplate().getType() == Material.AIR)) { - player.getInventory().setChestplate(item); - } else if(item.getType().toString().toLowerCase().contains("leg") && (player.getInventory().getLeggings() == null || player.getInventory().getLeggings().getType() == Material.AIR)) { - player.getInventory().setLeggings(item); - } else if(item.getType().toString().toLowerCase().contains("boots") && (player.getInventory().getBoots() == null || player.getInventory().getBoots().getType() == Material.AIR)) { - player.getInventory().setBoots(item); - } else if (player.getInventory().firstEmpty() == -1) { - player.getWorld().dropItem(player.getLocation(), item); - } else { - player.getInventory().addItem(item); - } - } - - chest.clear(); - }else { - Util.restoreInventory(player, prisoner); - } - - pl.getJailIO().removePrisoner(jail, cell, prisoner); - cell.removePrisoner(); - }else { - Util.restoreInventory(player, prisoner); - - pl.getJailIO().removePrisoner(jail, prisoner); - jail.removePrisoner(prisoner); - } - - //Get the commands to execute prisoners are unjailed - //replace all of the %p% so that the commands can have a player name in them - for(String command : pl.getConfig().getStringList(Settings.COMMANDSONRELEASE.getPath())) { - command = command.replaceAll("%p%", player.getName()); - pl.getServer().dispatchCommand(pl.getServer().getConsoleSender(), command); - } - - //Remove the scoreboard to them if it is enabled - if(pl.getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) { - pl.getScoreBoardManager().removeScoreBoard(player); - } - - //Call the prisoner released event as we have released them. - PrisonerReleasedEvent event = new PrisonerReleasedEvent(jail, cell, prisoner, player); - pl.getServer().getPluginManager().callEvent(event); - - player.sendMessage(Lang.UNJAILED.get()); - if(sender != null) sender.sendMessage(Lang.UNJAILSUCCESS.get(player.getName())); - } - - /** - * Forcefully unjails a {@link Prisoner prisoner} from {@link Jail}. - * - *

- * - * This method forcefully removes all the references to this prisoner, - * meaning if they're offline the following won't happened: - *

    - *
  • Inventory restored
  • - *
  • Teleported anywhere
  • - *
  • No messages sent, they'll be clueless.
  • - *
- * - * But if they're online, it goes through the regular unjailing methods. - * - *

- * - * @param prisoner to release - * @param sender who is releasing the prisoner, can be null - */ - public void forceRelease(Prisoner prisoner, CommandSender sender) { - Jail j = pl.getJailManager().getJailPrisonerIsIn(prisoner); - forceUnJail(j, j.getCellPrisonerIsIn(prisoner.getUUID()), pl.getServer().getPlayer(prisoner.getUUID()), prisoner, sender); - } - - /** - * Forcefully unjails a {@link Prisoner prisoner} from {@link Jail}. - * - * - *

- * - * This method forcefully removes all the references to this prisoner, - * meaning if they're offline the following won't happened: - *

    - *
  • Inventory restored
  • - *
  • Teleported anywhere
  • - *
  • No messages sent, they'll be clueless.
  • - *
- * - * But if they're online, it goes through the regular unjailing methods. - * - *

- * - * @param jail the prisoner is in - * @param cell the prisoner is in, can be null - * @param player of the prisoner, if this is null then the player won't be teleported when they come back on. - * @param prisoner to release and remove data - * @param sender who is releasing the prisoner, can be null - */ - public void forceUnJail(Jail jail, Cell cell, Player player, Prisoner prisoner, CommandSender sender) { - if(player == null) { - //Player is offline, we just forcefully remove them from the database - pl.getJailIO().removePrisoner(jail, cell, prisoner); - - if(cell == null) { - jail.removePrisoner(prisoner); - }else { - cell.removePrisoner(); - } - - if(sender != null) sender.sendMessage(Lang.FORCEUNJAILED.get(prisoner.getLastKnownName())); - }else { - try { - unJail(jail, cell, player, prisoner, sender); - } catch (Exception e) { - releasePrisoner(player, prisoner); - } - } - } - - /** - * Transfers the prisoner from one jail, or cell, to another jail, and/or cell. - * - * @param originJail The jail where they are coming from. - * @param originCell The cell where they are coming from. - * @param targetJail The jail we're transferring them from. - * @param targetCell The cell we're putting them into. - * @param prisoner The prisoner data we're handling. - */ - public void transferPrisoner(Jail originJail, Cell originCell, Jail targetJail, Cell targetCell, Prisoner prisoner) { - Player player = pl.getServer().getPlayer(prisoner.getUUID()); - - //If there is no origin cell, then we need to basically just put them to their targetJail - if(originCell == null) { - //But first thing is first, let's check if there is a targetCell we're putting them in - if(targetCell == null) { - //There is no cell, so we're just going to be putting them into - //the target jail and that's it - targetJail.addPrisoner(prisoner); - //Now then let's remove them from their old jail - originJail.removePrisoner(prisoner); - - //If the player is not online, trigger them to be teleported when they - //come online again - if(player == null) { - //Set them to have an action on offline pending, so it gets triggered - prisoner.setOfflinePending(true); - //Now let's set them to be transferred when they come online next - prisoner.setToBeTransferred(true); - }else { - prisoner.setTeleporting(true); - player.teleport(targetJail.getTeleportIn()); - prisoner.setTeleporting(false); - player.sendMessage(Lang.TRANSFERRED.get(targetJail.getName())); - } - }else { - //They are set to go to the targetCell, so handle accordingly - targetCell.setPrisoner(prisoner); - - //If the player is not online, trigger them to be teleported when they - //come online again - if(player == null) { - //Set them to have an action on offline pending, so it gets triggered - prisoner.setOfflinePending(true); - //Now let's set them to be transferred when they come online next - prisoner.setToBeTransferred(true); - }else { - prisoner.setTeleporting(true); - player.teleport(targetCell.getTeleport()); - prisoner.setTeleporting(false); - player.sendMessage(Lang.TRANSFERRED.get(targetJail.getName())); - } - } - }else { - //They are being transferred from a cell, so we need to handle getting the inventory - //and all that sort of stuff from the old cell before we transfer them over to the new cell - - //If they're not being sent to a cell any more, handle that differently as well - if(targetCell == null) { - //Add them to the target jail - targetJail.addPrisoner(prisoner); - //Next, remove them from the cell - originCell.removePrisoner(); - - //If the cell they came from has any items from their inventory, - //let's get it all and store it - if(originCell.hasChest()) { - //Convert the inventory to base64 string and store it in the prisoner's file - prisoner.setInventory(Util.toBase64(originCell.getChest().getInventory())); - //Clear the origin cell's inventory so nothing is left behind - originCell.getChest().getInventory().clear(); - } - }else { - //They are being transferred to a cell in another cell, - //we aren't going to do any sanity checks as we hope the method that is - //calling this one does those sanity checks for us. - - //Set the cell's prisoner to this one - targetCell.setPrisoner(prisoner); - //Remove the prisoner from the old one - originCell.removePrisoner(); - - //Check if the origin cell has a chest, put all the player's inventory into it - if(originCell.hasChest()) { - //If the targetCell has a chest - if(targetCell.hasChest()) { - //Loop through the origin's chest inventory and add it to the target cell's chest - for(ItemStack i : originCell.getChest().getInventory().getContents()) { - targetCell.getChest().getInventory().addItem(i); - } - - //Clear the origin cell's chest as it is clear now - originCell.getChest().getInventory().clear(); - }else { - //targetCell has no chest so we aren't going to try and put anything into it - - //Convert the inventory to base64 string and store it in the prisoner's file - prisoner.setInventory(Util.toBase64(originCell.getChest().getInventory())); - //Clear the origin cell's inventory so nothing is left behind - originCell.getChest().getInventory().clear(); - } - } - } - } - - //Throw our custom event PrisonerTransferredEvent to say it was successful - PrisonerTransferredEvent event = new PrisonerTransferredEvent(originJail, originCell, targetJail, targetCell, prisoner, player); - pl.getServer().getPluginManager().callEvent(event); - } + private JailMain pl; + private ArrayList releases; + + public PrisonerManager(JailMain plugin) { + this.pl = plugin; + this.releases = new ArrayList(); + + // Schedule the releasing of prisoners + plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() { + public void run() { + releaseScheduledPrisoners(); + } + }, 100L, 20L); + } + + /** + * Does everything preparing for the jailing of the provided prisoner, if they are online it forwards it to {@link #jailPrisoner(Jail, Cell, Player, Prisoner)}. + * + *

+ * + * In this we do the following: + *

    + *
  1. Checks if the jail is null, if so it throws an Exception
  2. + *
  3. Checks if the prisoner is null, if so it throws an Exception
  4. + *
  5. Sets the prisoner data to offline pending or not, player == null
  6. + *
  7. If the cell is null, add the prisoner data to the jail otherwise we set the cell's prisoner to this one. Check before here if the cell already contains a prisoner.
  8. + *
  9. Saves the jail information, goes out to the {@link JailIO} to initate a save.
  10. + *
  11. If the prisoner is not offline, we will actually {@link #jailPrisoner(Jail, Cell, Player, Prisoner) jail} them now.
  12. + *
  13. Does checks to get the right message for the next two items.
  14. + *
  15. If we broadcast the jailing, then let's broadcast it.
  16. + *
  17. If we log the jailing to console and we haven't broadcasted it, then we log it to the console.
  18. + *
+ * + * @param jail The {@link Jail jail instance} we are sending this prisoner to + * @param cell The name of the {@link Cell cell} we are sending this prisoner to + * @param player The {@link Player player} we are preparing the jail for. + * @param prisoner The {@link Prisoner prisoner} file. + * @throws Exception if the jail or prisoner are null. + */ + public void prepareJail(Jail jail, Cell cell, Player player, Prisoner prisoner) throws Exception { + //Do some checks of whether the passed params are null. + if(jail == null) + throw new Exception("The jail can not be null."); + + if(prisoner == null) + throw new Exception("Prisoner data can not be null."); + + //Set whether the prisoner is offline or not. + prisoner.setOfflinePending(player == null); + + //Now that we've got those checks out of the way, let's start preparing. + if(cell == null) { + jail.addPrisoner(prisoner); + }else { + cell.setPrisoner(prisoner); + } + + //If they are NOT offline, jail them + if(!prisoner.isOfflinePending()) { + jailPrisoner(jail, cell, player, prisoner); + } + + //Get a message ready for broadcasting or logging. + String msg = ""; + + if(prisoner.getRemainingTime() < 0L) + msg = Lang.BROADCASTMESSAGEFOREVER.get(prisoner.getLastKnownName()); + else + msg = Lang.BROADCASTMESSAGEFORMINUTES.get(new String[] { prisoner.getLastKnownName(), String.valueOf(prisoner.getRemainingTimeInMinutes()) }); + + boolean broadcasted = false; + //Broadcast the message, if it is enabled + if(pl.getConfig().getBoolean(Settings.BROADCASTJAILING.getPath(), false)) { + pl.getServer().broadcastMessage(msg); + broadcasted = true; + } + + //Log the message, if it is enabled + if(pl.getConfig().getBoolean(Settings.LOGJAILINGTOCONSOLE.getPath(), true) && !broadcasted) { + pl.getServer().getConsoleSender().sendMessage(msg); + } + } + + /** + * Jails the given player, only use when that player has offline data pending. + * + * @param uuid of the player to jail. + */ + public void jailPlayer(UUID uuid) { + Jail j = pl.getJailManager().getJailPlayerIsIn(uuid); + jailPrisoner(j, j.getCellPrisonerIsIn(uuid), pl.getServer().getPlayer(uuid), j.getPrisoner(uuid)); + } + + /** + * Jails the prisoner with the proper information given. + * + * @param jail where they are going + * @param cell where they are being placed in, can be null + * @param player who is the prisoner + * @param prisoner data containing everything pertaining to them + */ + public void jailPrisoner(Jail jail, Cell cell, Player player, Prisoner prisoner) { + //If they have handcuffs on them, then let's remove them before we continue + //this way the handcuff listeners and this aren't battleing each other + if(pl.getHandCuffManager().isHandCuffed(player.getUniqueId())) { + pl.getHandCuffManager().removeHandCuffs(player.getUniqueId()); + } + + //They are no longer offline, so set that. + prisoner.setOfflinePending(false); + + //We are getting ready to teleport them, so set it to true so that + //the *future* move checkers won't be canceling our moving. + prisoner.setTeleporting(true); + + //If their reason is empty send proper message, else send other proper message + if(prisoner.getReason().isEmpty()) { + player.sendMessage(Lang.JAILED.get()); + }else { + player.sendMessage(Lang.JAILEDWITHREASON.get(prisoner.getReason())); + } + + //If the config has releasing them back to their previous position, + //then let's set it in the prisoner data. + if(pl.getConfig().getBoolean(Settings.RELEASETOPREVIOUSPOSITION.getPath(), false)) { + prisoner.setPreviousPosition(player.getLocation()); + } + + //If the config has restoring their previous gamemode enabled, + //then let's set it in their prisoner data. + if(pl.getConfig().getBoolean(Settings.RESTOREPREVIOUSGAMEMODE.getPath(), false)) { + prisoner.setPreviousGameMode(player.getGameMode()); + } + + //Set their gamemode to the one in the config, if we get a null value + //from the parsing then we set theirs to adventure + try { + player.setGameMode(GameMode.valueOf(pl.getConfig().getString(Settings.JAILEDGAMEMODE.getPath(), "ADVENTURE").toUpperCase())); + }catch(Exception e) { + pl.getLogger().severe("Your jailedgamemode setting is incorrect, please fix."); + player.setGameMode(GameMode.ADVENTURE); + } + + //only eject them if they're inside a vehicle and also eject anyone else on top of them + if(player.isInsideVehicle()) { + player.getVehicle().eject(); + player.getPassenger().eject(); + player.eject(); + } + + //If we are ignoring the sleeping state of prisoners, + //then let's set that + if(pl.getConfig().getBoolean(Settings.IGNORESLEEPINGSTATE.getPath(), true)) { + player.setSleepingIgnored(true); + } + + //Get the max and min food level in the config + int maxFood = pl.getConfig().getInt(Settings.FOODCONTROLMAX.getPath(), 20); + int minFood = pl.getConfig().getInt(Settings.FOODCONTROLMIN.getPath(), 10); + + //If their food level is less than the min food level, set it to the min + //but if it is higher than the max, set it to the max + if (player.getFoodLevel() < minFood) { + player.setFoodLevel(minFood); + } else if (player.getFoodLevel() > maxFood) { + player.setFoodLevel(maxFood); + } + + //If the cell doesn't equal null, then let's put them in the jail + if(cell != null) { + //check if we store the inventory + if(pl.getConfig().getBoolean(Settings.JAILEDSTOREINVENTORY.getPath(), true)) { + List blacklist = pl.getConfig().getStringList(Settings.JAILEDINVENTORYBLACKLIST.getPath()); + //Check if there is a chest to store our items to and if it is a double chest, if not we will then serialize it + if(cell.hasChest()) { + //Get the chest's inventory and then clear it + Inventory chest = cell.getChest().getInventory(); + chest.clear(); + + //Get the separate inventory, so we can iterate of them + ItemStack[] inventory = player.getInventory().getContents(); + ItemStack[] armor = player.getInventory().getArmorContents(); + + for(ItemStack item : inventory) { + if(item != null) { + if(!Util.isStringInsideList(blacklist, item.getType().toString())) { + int i = chest.firstEmpty(); + if(i != -1) {//Check that we have got a free spot, should never happen but just in case + chest.setItem(i, item); + } + } + } + } + + for(ItemStack item : armor) { + if(item != null) { + if(!Util.isStringInsideList(blacklist, item.getType().toString())) { + int i = chest.firstEmpty(); + if(i != -1) {//Check that we have got a free spot, should never happen but just in case + chest.setItem(i, item); + } + } + } + } + + player.getInventory().setArmorContents(null); + player.getInventory().clear(); + + //Here so we don't forget about it later as this method isn't finished, but + //Updates the cell's signs + cell.update(); + }else { + for(ItemStack item : player.getInventory().getContents()) + if(item != null) + if(Util.isStringInsideList(blacklist, item.getType().toString())) + player.getInventory().remove(item); + + for(ItemStack item : player.getInventory().getArmorContents()) + if(item != null) + if(Util.isStringInsideList(blacklist, item.getType().toString())) + player.getInventory().remove(item); + + String[] inv = Util.playerInventoryToBase64(player.getInventory()); + prisoner.setInventory(inv[0]); + prisoner.setArmor(inv[1]); + + player.getInventory().setArmorContents(null); + player.getInventory().clear(); + } + } + + //Teleport them to the cell's teleport location + //they will now be placed in jail. + pl.debug("Teleporting " + player.getName() + " to " + jail.getName() + " in the cell " + cell.getName() + "'s in: " + jail.getTeleportIn().toString()); + player.teleport(cell.getTeleport()); + }else { + //There is no cell we're jailing them to, so stick them in the jail + if(pl.getConfig().getBoolean(Settings.JAILEDSTOREINVENTORY.getPath(), true)) { + List blacklist = pl.getConfig().getStringList(Settings.JAILEDINVENTORYBLACKLIST.getPath()); + + for(ItemStack item : player.getInventory().getContents()) + if(item != null) + if(Util.isStringInsideList(blacklist, item.getType().toString())) + player.getInventory().remove(item); + + for(ItemStack item : player.getInventory().getArmorContents()) + if(item != null) + if(Util.isStringInsideList(blacklist, item.getType().toString())) + player.getInventory().remove(item); + + String[] inv = Util.playerInventoryToBase64(player.getInventory()); + prisoner.setInventory(inv[0]); + prisoner.setArmor(inv[1]); + + player.getInventory().setArmorContents(null); + player.getInventory().clear(); + } + + //Teleport them to the jail's teleport in location + //They will now be placed in jail. + pl.debug("Teleporting " + player.getName() + " to " + jail.getName() + "'s in: " + jail.getTeleportIn().toString()); + player.teleport(jail.getTeleportIn()); + } + + //Set them to not allowing teleporting, as we are not going to be moving them anymore + //this way the move checkers will start checking this player. + prisoner.setTeleporting(false); + + //Get the commands to execute after they are jailed + //replace all of the %p% so that the commands can have a player name in them + for(String command : pl.getConfig().getStringList(Settings.COMMANDSONJAIL.getPath())) { + command = command.replaceAll("%p%", player.getName()); + pl.getServer().dispatchCommand(pl.getServer().getConsoleSender(), command); + } + + //Add the scoreboard to them if it is enabled + if(pl.getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) { + pl.getScoreBoardManager().addScoreBoard(player, prisoner); + } + + //Save the data, as we have changed it + pl.getJailIO().saveJail(jail); + + //Call our custom event for when a prisoner is actually jailed. + PrisonerJailedEvent event = new PrisonerJailedEvent(jail, cell, prisoner, player); + pl.getServer().getPluginManager().callEvent(event); + } + + /** + * Schedules a prisoner to be released, this method is to be used async. + * + * @param prisoner to be released. + * @see {@link #unJail(Jail, Cell, Player, Prisoner, CommandSender)} - If you're wanting to unjail a prisoner. + */ + public void schedulePrisonerRelease(Prisoner prisoner) { + releases.add(prisoner); + } + + private void releaseScheduledPrisoners() { + ArrayList lettingGo = new ArrayList(releases); + for(Prisoner p : lettingGo) { + releases.remove(p); + releasePrisoner(pl.getServer().getPlayer(p.getUUID()), p); + } + } + + /** + * Release the given prisoner from jailing, does the checks if they are offline or not. + * + * @param player we are releasing, can be null and if so they'll be treated as offline. + * @param prisoner data to handle. + */ + private void releasePrisoner(Player player, Prisoner prisoner) { + if(player == null) { + prisoner.setOfflinePending(true); + prisoner.setRemainingTime(0); + }else { + Jail j = pl.getJailManager().getJailPlayerIsIn(player.getUniqueId()); + + try { + unJail(j, j.getCellPrisonerIsIn(player.getUniqueId()), player, prisoner, null); + }catch(Exception e) { + if(pl.inDebug()) { + e.printStackTrace(); + } + + pl.getLogger().severe("Unable to unjail the prisoner " + player.getName() + " because '" + e.getMessage() + "'."); + } + + } + } + + /** + * Unjails a prisoner from jail, removing all their data. + * + *

+ * + * Throws an exception if either the jail is null or the prisoner is null. + * + * @param jail where the prisoner is located at + * @param cell which the prisoner is in, can be null + * @param player instance for the prisoner we're unjailing + * @param prisoner data where everything resides + * @param sender The {@link CommandSender} who unjailed this player, can be null. + * @throws Exception + */ + public void unJail(Jail jail, Cell cell, Player player, Prisoner prisoner, CommandSender sender) throws Exception { + //Do some checks of whether the passed params are null. + if(jail == null) + throw new Exception("The jail can not be null."); + + if(prisoner == null) + throw new Exception("Prisoner data can not be null."); + + //Throw the custom event which is called before we start releasing them + PrePrisonerReleasedEvent preEvent = new PrePrisonerReleasedEvent(jail, cell, prisoner, player); + pl.getServer().getPluginManager().callEvent(preEvent); + + //We are getting ready to teleport them, so set it to true so that + //the *future* move checkers won't be canceling our moving. + prisoner.setTeleporting(true); + + //In case they have somehow got on a vehicle, let's unmount + //them so we can possibly teleport them + if(player.isInsideVehicle()) { + player.getVehicle().eject(); + player.getPassenger().eject(); + player.eject(); + } + + //In case we had set their sleeping state to be ignored + //let's enable their sleeping state taking place again + player.setSleepingIgnored(false); + + //If the config has us teleporting them back to their + //previous position then let's do that + boolean tpd = false; + if(pl.getConfig().getBoolean(Settings.RELEASETOPREVIOUSPOSITION.getPath(), false)) { + if(prisoner.getPreviousLocation() != null) + tpd = player.teleport(prisoner.getPreviousLocation()); + } + + //If they haven't already been teleported and the config has us to teleport on release, + //then we teleport players to the jail's free spot + if(!tpd && pl.getConfig().getBoolean(Settings.TELEPORTONRELEASE.getPath(), true)) { + player.teleport(jail.getTeleportFree()); + } + + //If we are to restore their previous gamemode and we have it stored, + //then by all means let's restore it + if(pl.getConfig().getBoolean(Settings.RESTOREPREVIOUSGAMEMODE.getPath(), false)) { + player.setGameMode(prisoner.getPreviousGameMode()); + } + + //Now, let's restore their inventory + //First up, clear their inventory + player.closeInventory(); + player.getInventory().setArmorContents(null); + player.getInventory().clear(); + + //if the cell isn't null, let's check if the cell has a chest and if so then try out best to restore + //the prisoner's inventory from that + if(cell != null) { + if(cell.hasChest()) { + Inventory chest = cell.getChest().getInventory(); + + for (ItemStack item : chest.getContents()) { + if (item == null || item.getType() == Material.AIR) continue; + + if(item.getType().toString().toLowerCase().contains("helmet") && (player.getInventory().getHelmet() == null || player.getInventory().getHelmet().getType() == Material.AIR)) { + player.getInventory().setHelmet(item); + } else if(item.getType().toString().toLowerCase().contains("chestplate") && (player.getInventory().getChestplate() == null || player.getInventory().getChestplate().getType() == Material.AIR)) { + player.getInventory().setChestplate(item); + } else if(item.getType().toString().toLowerCase().contains("leg") && (player.getInventory().getLeggings() == null || player.getInventory().getLeggings().getType() == Material.AIR)) { + player.getInventory().setLeggings(item); + } else if(item.getType().toString().toLowerCase().contains("boots") && (player.getInventory().getBoots() == null || player.getInventory().getBoots().getType() == Material.AIR)) { + player.getInventory().setBoots(item); + } else if (player.getInventory().firstEmpty() == -1) { + player.getWorld().dropItem(player.getLocation(), item); + } else { + player.getInventory().addItem(item); + } + } + + chest.clear(); + }else { + Util.restoreInventory(player, prisoner); + } + + pl.getJailIO().removePrisoner(jail, cell, prisoner); + cell.removePrisoner(); + }else { + Util.restoreInventory(player, prisoner); + + pl.getJailIO().removePrisoner(jail, prisoner); + jail.removePrisoner(prisoner); + } + + //Get the commands to execute prisoners are unjailed + //replace all of the %p% so that the commands can have a player name in them + for(String command : pl.getConfig().getStringList(Settings.COMMANDSONRELEASE.getPath())) { + command = command.replaceAll("%p%", player.getName()); + pl.getServer().dispatchCommand(pl.getServer().getConsoleSender(), command); + } + + //Remove the scoreboard to them if it is enabled + if(pl.getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) { + pl.getScoreBoardManager().removeScoreBoard(player); + } + + //Call the prisoner released event as we have released them. + PrisonerReleasedEvent event = new PrisonerReleasedEvent(jail, cell, prisoner, player); + pl.getServer().getPluginManager().callEvent(event); + + player.sendMessage(Lang.UNJAILED.get()); + if(sender != null) sender.sendMessage(Lang.UNJAILSUCCESS.get(player.getName())); + } + + /** + * Forcefully unjails a {@link Prisoner prisoner} from {@link Jail}. + * + *

+ * + * This method forcefully removes all the references to this prisoner, + * meaning if they're offline the following won't happened: + *

    + *
  • Inventory restored
  • + *
  • Teleported anywhere
  • + *
  • No messages sent, they'll be clueless.
  • + *
+ * + * But if they're online, it goes through the regular unjailing methods. + * + *

+ * + * @param prisoner to release + * @param sender who is releasing the prisoner, can be null + */ + public void forceRelease(Prisoner prisoner, CommandSender sender) { + Jail j = pl.getJailManager().getJailPrisonerIsIn(prisoner); + forceUnJail(j, j.getCellPrisonerIsIn(prisoner.getUUID()), pl.getServer().getPlayer(prisoner.getUUID()), prisoner, sender); + } + + /** + * Forcefully unjails a {@link Prisoner prisoner} from {@link Jail}. + * + * + *

+ * + * This method forcefully removes all the references to this prisoner, + * meaning if they're offline the following won't happened: + *

    + *
  • Inventory restored
  • + *
  • Teleported anywhere
  • + *
  • No messages sent, they'll be clueless.
  • + *
+ * + * But if they're online, it goes through the regular unjailing methods. + * + *

+ * + * @param jail the prisoner is in + * @param cell the prisoner is in, can be null + * @param player of the prisoner, if this is null then the player won't be teleported when they come back on. + * @param prisoner to release and remove data + * @param sender who is releasing the prisoner, can be null + */ + public void forceUnJail(Jail jail, Cell cell, Player player, Prisoner prisoner, CommandSender sender) { + if(player == null) { + //Player is offline, we just forcefully remove them from the database + pl.getJailIO().removePrisoner(jail, cell, prisoner); + + if(cell == null) { + jail.removePrisoner(prisoner); + }else { + cell.removePrisoner(); + } + + if(sender != null) sender.sendMessage(Lang.FORCEUNJAILED.get(prisoner.getLastKnownName())); + }else { + try { + unJail(jail, cell, player, prisoner, sender); + } catch (Exception e) { + releasePrisoner(player, prisoner); + } + } + } + + /** + * Transfers the prisoner from one jail, or cell, to another jail, and/or cell. + * + * @param originJail The jail where they are coming from. + * @param originCell The cell where they are coming from. + * @param targetJail The jail we're transferring them from. + * @param targetCell The cell we're putting them into. + * @param prisoner The prisoner data we're handling. + */ + public void transferPrisoner(Jail originJail, Cell originCell, Jail targetJail, Cell targetCell, Prisoner prisoner) { + Player player = pl.getServer().getPlayer(prisoner.getUUID()); + + //If there is no origin cell, then we need to basically just put them to their targetJail + if(originCell == null) { + //But first thing is first, let's check if there is a targetCell we're putting them in + if(targetCell == null) { + //There is no cell, so we're just going to be putting them into + //the target jail and that's it + targetJail.addPrisoner(prisoner); + //Now then let's remove them from their old jail + originJail.removePrisoner(prisoner); + + //If the player is not online, trigger them to be teleported when they + //come online again + if(player == null) { + //Set them to have an action on offline pending, so it gets triggered + prisoner.setOfflinePending(true); + //Now let's set them to be transferred when they come online next + prisoner.setToBeTransferred(true); + }else { + prisoner.setTeleporting(true); + player.teleport(targetJail.getTeleportIn()); + prisoner.setTeleporting(false); + player.sendMessage(Lang.TRANSFERRED.get(targetJail.getName())); + } + }else { + //They are set to go to the targetCell, so handle accordingly + targetCell.setPrisoner(prisoner); + + //If the player is not online, trigger them to be teleported when they + //come online again + if(player == null) { + //Set them to have an action on offline pending, so it gets triggered + prisoner.setOfflinePending(true); + //Now let's set them to be transferred when they come online next + prisoner.setToBeTransferred(true); + }else { + prisoner.setTeleporting(true); + player.teleport(targetCell.getTeleport()); + prisoner.setTeleporting(false); + player.sendMessage(Lang.TRANSFERRED.get(targetJail.getName())); + } + } + }else { + //They are being transferred from a cell, so we need to handle getting the inventory + //and all that sort of stuff from the old cell before we transfer them over to the new cell + + //If they're not being sent to a cell any more, handle that differently as well + if(targetCell == null) { + //Add them to the target jail + targetJail.addPrisoner(prisoner); + //Next, remove them from the cell + originCell.removePrisoner(); + + //If the cell they came from has any items from their inventory, + //let's get it all and store it + if(originCell.hasChest()) { + //Convert the inventory to base64 string and store it in the prisoner's file + prisoner.setInventory(Util.toBase64(originCell.getChest().getInventory())); + //Clear the origin cell's inventory so nothing is left behind + originCell.getChest().getInventory().clear(); + } + }else { + //They are being transferred to a cell in another cell, + //we aren't going to do any sanity checks as we hope the method that is + //calling this one does those sanity checks for us. + + //Set the cell's prisoner to this one + targetCell.setPrisoner(prisoner); + //Remove the prisoner from the old one + originCell.removePrisoner(); + + //Check if the origin cell has a chest, put all the player's inventory into it + if(originCell.hasChest()) { + //If the targetCell has a chest + if(targetCell.hasChest()) { + //Loop through the origin's chest inventory and add it to the target cell's chest + for(ItemStack i : originCell.getChest().getInventory().getContents()) { + targetCell.getChest().getInventory().addItem(i); + } + + //Clear the origin cell's chest as it is clear now + originCell.getChest().getInventory().clear(); + }else { + //targetCell has no chest so we aren't going to try and put anything into it + + //Convert the inventory to base64 string and store it in the prisoner's file + prisoner.setInventory(Util.toBase64(originCell.getChest().getInventory())); + //Clear the origin cell's inventory so nothing is left behind + originCell.getChest().getInventory().clear(); + } + } + } + } + + //Throw our custom event PrisonerTransferredEvent to say it was successful + PrisonerTransferredEvent event = new PrisonerTransferredEvent(originJail, originCell, targetJail, targetCell, prisoner, player); + pl.getServer().getPluginManager().callEvent(event); + } } diff --git a/src/main/java/com/graywolf336/jail/ScoreBoardManager.java b/src/main/java/com/graywolf336/jail/ScoreBoardManager.java index 3e23c3b..79a35ba 100644 --- a/src/main/java/com/graywolf336/jail/ScoreBoardManager.java +++ b/src/main/java/com/graywolf336/jail/ScoreBoardManager.java @@ -15,90 +15,90 @@ import com.graywolf336.jail.beans.Prisoner; import com.graywolf336.jail.enums.Settings; public class ScoreBoardManager { - private JailMain pl; - private ScoreboardManager man; - private HashMap boards; - private OfflinePlayer time; - - public ScoreBoardManager(JailMain plugin) { - this.pl = plugin; - this.man = plugin.getServer().getScoreboardManager(); - this.boards = new HashMap(); - this.time = plugin.getServer().getOfflinePlayer(Util.getColorfulMessage(pl.getConfig().getString(Settings.SCOREBOARDTIME.getPath()))); - - //Start the task if it is enabled - if(plugin.getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) { - plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() { - public void run() { - updatePrisonersTime(); - } - }, 200L, 100L); - } - } - - /** - * Adds the jailing score board to the player if they don't have one, otherwise it just updates it. - * - * @param player of whom to add the scoreboard to. - * @param pris data for the provided prisoner - */ - public void addScoreBoard(Player player, Prisoner pris) { - if(!boards.containsKey(player.getUniqueId())) { - boards.put(player.getUniqueId(), man.getNewScoreboard()); - Objective o = boards.get(player.getUniqueId()).registerNewObjective("test", "dummy"); - o.setDisplaySlot(DisplaySlot.SIDEBAR); - o.setDisplayName(Util.getColorfulMessage(pl.getConfig().getString(Settings.SCOREBOARDTITLE.getPath()))); - o.getScore(time).setScore(pris.getRemainingTimeInMinutesInt()); - player.setScoreboard(boards.get(player.getUniqueId())); - }else { - updatePrisonersBoard(player, pris); - } - } - - /** - * Removes a player's jail scoreboard for their jail time and sets it to the main one. - * - * @param player of whom to remove the scoreboard for. - */ - public void removeScoreBoard(Player player) { - boards.remove(player.getUniqueId()); - //TODO: See if this works or if we need to set it to a new one - player.setScoreboard(man.getMainScoreboard()); - } - - /** Removes all of the scoreboards from the prisoners. */ - public void removeAllScoreboards() { - HashMap temp = new HashMap(boards); - - for(UUID id : temp.keySet()) { - Player p = pl.getServer().getPlayer(id); - - if(p != null) { - p.setScoreboard(man.getMainScoreboard()); - } - - boards.remove(id); - } - } - - /** Updates the prisoners time on their scoreboard. */ - private void updatePrisonersTime() { - for(Jail j : pl.getJailManager().getJails()) { - for(Prisoner p : j.getAllPrisoners().values()) { - if(pl.getServer().getPlayer(p.getUUID()) != null) { - addScoreBoard(pl.getServer().getPlayer(p.getUUID()), p); - } - } - } - } - - /** - * Updates a player's time in the scoreboard. - * - * @param player of whom to update the scoreboard for. - * @param pris data for the player - */ - private void updatePrisonersBoard(Player player, Prisoner pris) { - boards.get(player.getUniqueId()).getObjective("test").getScore(time).setScore(pris.getRemainingTimeInMinutesInt()); - } + private JailMain pl; + private ScoreboardManager man; + private HashMap boards; + private OfflinePlayer time; + + public ScoreBoardManager(JailMain plugin) { + this.pl = plugin; + this.man = plugin.getServer().getScoreboardManager(); + this.boards = new HashMap(); + this.time = plugin.getServer().getOfflinePlayer(Util.getColorfulMessage(pl.getConfig().getString(Settings.SCOREBOARDTIME.getPath()))); + + //Start the task if it is enabled + if(plugin.getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) { + plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() { + public void run() { + updatePrisonersTime(); + } + }, 200L, 100L); + } + } + + /** + * Adds the jailing score board to the player if they don't have one, otherwise it just updates it. + * + * @param player of whom to add the scoreboard to. + * @param pris data for the provided prisoner + */ + public void addScoreBoard(Player player, Prisoner pris) { + if(!boards.containsKey(player.getUniqueId())) { + boards.put(player.getUniqueId(), man.getNewScoreboard()); + Objective o = boards.get(player.getUniqueId()).registerNewObjective("test", "dummy"); + o.setDisplaySlot(DisplaySlot.SIDEBAR); + o.setDisplayName(Util.getColorfulMessage(pl.getConfig().getString(Settings.SCOREBOARDTITLE.getPath()))); + o.getScore(time).setScore(pris.getRemainingTimeInMinutesInt()); + player.setScoreboard(boards.get(player.getUniqueId())); + }else { + updatePrisonersBoard(player, pris); + } + } + + /** + * Removes a player's jail scoreboard for their jail time and sets it to the main one. + * + * @param player of whom to remove the scoreboard for. + */ + public void removeScoreBoard(Player player) { + boards.remove(player.getUniqueId()); + //TODO: See if this works or if we need to set it to a new one + player.setScoreboard(man.getMainScoreboard()); + } + + /** Removes all of the scoreboards from the prisoners. */ + public void removeAllScoreboards() { + HashMap temp = new HashMap(boards); + + for(UUID id : temp.keySet()) { + Player p = pl.getServer().getPlayer(id); + + if(p != null) { + p.setScoreboard(man.getMainScoreboard()); + } + + boards.remove(id); + } + } + + /** Updates the prisoners time on their scoreboard. */ + private void updatePrisonersTime() { + for(Jail j : pl.getJailManager().getJails()) { + for(Prisoner p : j.getAllPrisoners().values()) { + if(pl.getServer().getPlayer(p.getUUID()) != null) { + addScoreBoard(pl.getServer().getPlayer(p.getUUID()), p); + } + } + } + } + + /** + * Updates a player's time in the scoreboard. + * + * @param player of whom to update the scoreboard for. + * @param pris data for the player + */ + private void updatePrisonersBoard(Player player, Prisoner pris) { + boards.get(player.getUniqueId()).getObjective("test").getScore(time).setScore(pris.getRemainingTimeInMinutesInt()); + } } diff --git a/src/main/java/com/graywolf336/jail/Update.java b/src/main/java/com/graywolf336/jail/Update.java index 5cb657b..2d21e20 100644 --- a/src/main/java/com/graywolf336/jail/Update.java +++ b/src/main/java/com/graywolf336/jail/Update.java @@ -14,9 +14,9 @@ import org.json.simple.JSONValue; import com.graywolf336.jail.enums.Settings; public class Update { - private JailMain plugin; - - // The project's unique ID + private JailMain plugin; + + // The project's unique ID private static final int projectID = 31139; // Static information for querying the API @@ -24,28 +24,28 @@ public class Update { private static final String CI_STABLEDEV_API_QUERY = "http://ci.graywolf336.com/job/Jail/lastStableBuild/api/json"; private static final String CI_DEV_API_QUERY = "http://ci.graywolf336.com/job/Jail/lastSuccessfulBuild/api/json"; private boolean needed = false; - + // The url for the new file and file version private String fileUrl = "", version = ""; - + public Update(JailMain plugin) { - this.plugin = plugin; + this.plugin = plugin; } - + public void query() { - String channel = plugin.getConfig().getString(Settings.UPDATECHANNEL.getPath(), "bukkit"); + String channel = plugin.getConfig().getString(Settings.UPDATECHANNEL.getPath(), "bukkit"); URL url = null; try { - if(channel.equalsIgnoreCase("stable-dev")) { - url = new URL(CI_STABLEDEV_API_QUERY); - }else if(channel.equalsIgnoreCase("dev")) { - url = new URL(CI_DEV_API_QUERY); - }else { - url = new URL(BUKKIT_API_QUERY); - } + if(channel.equalsIgnoreCase("stable-dev")) { + url = new URL(CI_STABLEDEV_API_QUERY); + }else if(channel.equalsIgnoreCase("dev")) { + url = new URL(CI_DEV_API_QUERY); + }else { + url = new URL(BUKKIT_API_QUERY); + } } catch (MalformedURLException e) { - plugin.getLogger().warning("The url for checking for an update was malformed, please open a ticket about this."); + plugin.getLogger().warning("The url for checking for an update was malformed, please open a ticket about this."); return; } @@ -62,30 +62,30 @@ public class Update { String response = reader.readLine(); if(channel.equalsIgnoreCase("stable-dev") || channel.equalsIgnoreCase("dev")) { - // Parse the object from the response from the CI server - JSONObject obj = (JSONObject) JSONValue.parse(response); - // Get the latest build number - long number = Long.parseLong(obj.get("number").toString()); - // Get the current running version - String[] ver = plugin.getDescription().getVersion().split("-b"); - // Let them know they're on a custom version when on build #0. - if(ver[ver.length - 1].equalsIgnoreCase("0")) { - plugin.getLogger().info("You are using a custom version, you can disable update checking."); - } - - // Parse the current build number to a number - long curr = Long.parseLong(ver[ver.length - 1]); - plugin.debug(number + " verus " + curr); - // Check if the build on the CI server is higher than the one we're running - needed = number > curr; - - // Alert the console that an update is needed, if it is needed - if(needed) { - this.version = obj.get("fullDisplayName").toString(); - this.fileUrl = obj.get("url").toString(); - plugin.getLogger().info("New development version of Jail is available: " + this.version); - plugin.getLogger().info(this.fileUrl); - } + // Parse the object from the response from the CI server + JSONObject obj = (JSONObject) JSONValue.parse(response); + // Get the latest build number + long number = Long.parseLong(obj.get("number").toString()); + // Get the current running version + String[] ver = plugin.getDescription().getVersion().split("-b"); + // Let them know they're on a custom version when on build #0. + if(ver[ver.length - 1].equalsIgnoreCase("0")) { + plugin.getLogger().info("You are using a custom version, you can disable update checking."); + } + + // Parse the current build number to a number + long curr = Long.parseLong(ver[ver.length - 1]); + plugin.debug(number + " verus " + curr); + // Check if the build on the CI server is higher than the one we're running + needed = number > curr; + + // Alert the console that an update is needed, if it is needed + if(needed) { + this.version = obj.get("fullDisplayName").toString(); + this.fileUrl = obj.get("url").toString(); + plugin.getLogger().info("New development version of Jail is available: " + this.version); + plugin.getLogger().info(this.fileUrl); + } }else { // Parse the array of files from the query's response JSONArray array = (JSONArray) JSONValue.parse(response); @@ -94,21 +94,21 @@ public class Update { if (array.size() > 0) { // Get the newest file's details JSONObject latest = (JSONObject) array.get(array.size() - 1); - + // Split the numbers into their own separate items String remoteVer = ((String) latest.get("name")).split(" v")[1]; - + // 3.0.0-SNAPSHOT-b0 String currentVer = plugin.getDescription().getVersion().split("-")[0]; - + plugin.debug(remoteVer + " verus " + currentVer); this.needed = this.versionCompare(remoteVer, currentVer) > 0; - + if(needed) { - this.version = latest.get("name").toString(); - this.fileUrl = latest.get("fileUrl").toString(); - plugin.getLogger().info("New stable version of Jail is available: " + this.version); - plugin.getLogger().info(this.fileUrl); + this.version = latest.get("name").toString(); + this.fileUrl = latest.get("fileUrl").toString(); + plugin.getLogger().info("New stable version of Jail is available: " + this.version); + plugin.getLogger().info(this.fileUrl); } } } @@ -119,19 +119,19 @@ public class Update { return; } } - + /** - * Compares two version strings. + * Compares two version strings. * - * Use this instead of String.compareTo() for a non-lexicographical + * Use this instead of String.compareTo() for a non-lexicographical * comparison that works for version strings. e.g. "1.10".compareTo("1.6"). * * @note It does not work if "1.10" is supposed to be equal to "1.10.0". * - * @param str1 a string of ordinal numbers separated by decimal points. + * @param str1 a string of ordinal numbers separated by decimal points. * @param str2 a string of ordinal numbers separated by decimal points. - * @return The result is a negative integer if str1 is _numerically_ less than str2. - * The result is a positive integer if str1 is _numerically_ greater than str2. + * @return The result is a negative integer if str1 is _numerically_ less than str2. + * The result is a positive integer if str1 is _numerically_ greater than str2. * The result is zero if the strings are _numerically_ equal. */ private Integer versionCompare(String str1, String str2) { @@ -140,33 +140,33 @@ public class Update { int i = 0; // set index to first non-equal ordinal or length of shortest version string while (i < vals1.length && i < vals2.length && vals1[i].equals(vals2[i])) { - i++; + i++; } - + // compare first non-equal ordinal number if (i < vals1.length && i < vals2.length) { return Integer.signum(Integer.valueOf(vals1[i]).compareTo(Integer.valueOf(vals2[i]))); } - + // the strings are equal or one string is a substring of the other // e.g. "1.2.3" = "1.2.3" or "1.2.3" < "1.2.3.4" else { return Integer.signum(vals1.length - vals2.length); } } - + /** Returns true if there is an update needed, false if not. */ public boolean isAvailable() { - return this.needed; + return this.needed; } - + /** Returns the new version. */ public String getNewVersion() { - return this.version; + return this.version; } - + /** Returns the new file url. */ public String getFileUrl() { - return this.fileUrl; + return this.fileUrl; } } diff --git a/src/main/java/com/graywolf336/jail/Util.java b/src/main/java/com/graywolf336/jail/Util.java index 5716672..c370aea 100644 --- a/src/main/java/com/graywolf336/jail/Util.java +++ b/src/main/java/com/graywolf336/jail/Util.java @@ -32,25 +32,25 @@ import com.graywolf336.jail.beans.Prisoner; * @version 3.0.0 */ public class Util { - private final static Pattern DURATION_PATTERN = Pattern.compile("^(\\d+)\\s*(m(?:inute)?s?|h(?:ours?)?|d(?:ays?)?|s(?:econd)?s?)?$", Pattern.CASE_INSENSITIVE); - - /** - * Checks if the first {@link Vector} is inside this region. - * - * @param point The point to check - * @param first point of the region - * @param second second point of the region - * @return True if all the coords of the first vector are in the entire region. - */ - public static boolean isInsideAB(Vector point, Vector first, Vector second) { - boolean x = isInside(point.getBlockX(), first.getBlockX(), second.getBlockX()); - boolean y = isInside(point.getBlockY(), first.getBlockY(), second.getBlockY()); - boolean z = isInside(point.getBlockZ(), first.getBlockZ(), second.getBlockZ()); - - return x && y && z; - } - - /** + private final static Pattern DURATION_PATTERN = Pattern.compile("^(\\d+)\\s*(m(?:inute)?s?|h(?:ours?)?|d(?:ays?)?|s(?:econd)?s?)?$", Pattern.CASE_INSENSITIVE); + + /** + * Checks if the first {@link Vector} is inside this region. + * + * @param point The point to check + * @param first point of the region + * @param second second point of the region + * @return True if all the coords of the first vector are in the entire region. + */ + public static boolean isInsideAB(Vector point, Vector first, Vector second) { + boolean x = isInside(point.getBlockX(), first.getBlockX(), second.getBlockX()); + boolean y = isInside(point.getBlockY(), first.getBlockY(), second.getBlockY()); + boolean z = isInside(point.getBlockZ(), first.getBlockZ(), second.getBlockZ()); + + return x && y && z; + } + + /** * Checks if two numbers are inside a point, or something. * *

@@ -73,43 +73,43 @@ public class Util { return (point1 <= loc) && (loc <= point2); } - + /** * Checks if the given string is inside the list, ignoring the casing. * *

* * @param list of strings to check - * @param value to check + * @param value to check * @return true if the list contains the provided value, false if it doesn't */ public static boolean isStringInsideList(List list, String value) { - for(String s : list) - if(s.equalsIgnoreCase(value)) - return true; - - return false; + for(String s : list) + if(s.equalsIgnoreCase(value)) + return true; + + return false; } - + /** Returns a colorful message from the color codes. */ public static String getColorfulMessage(String message) { - return message.replaceAll("(?i)&([0-9abcdefklmnor])", "\u00A7$1"); - } - + return message.replaceAll("(?i)&([0-9abcdefklmnor])", "\u00A7$1"); + } + /** Returns the wand used throughout the different creation steps. */ public static ItemStack getWand() { - ItemStack wand = new ItemStack(Material.WOOD_SWORD); - ItemMeta meta = wand.getItemMeta(); - meta.setDisplayName(ChatColor.AQUA + "Jail Wand"); - LinkedList lore = new LinkedList(); - lore.add(ChatColor.BLUE + "The wand for creating"); - lore.add(ChatColor.BLUE + "a jail or cell."); - meta.setLore(lore); - wand.setItemMeta(meta); - - return wand; + ItemStack wand = new ItemStack(Material.WOOD_SWORD); + ItemMeta meta = wand.getItemMeta(); + meta.setDisplayName(ChatColor.AQUA + "Jail Wand"); + LinkedList lore = new LinkedList(); + lore.add(ChatColor.BLUE + "The wand for creating"); + lore.add(ChatColor.BLUE + "a jail or cell."); + meta.setLore(lore); + wand.setItemMeta(meta); + + return wand; } - + /** * * Converts a string like '20minutes' into the appropriate amount of the given unit. @@ -120,9 +120,9 @@ public class Util { * @throws Exception if there are no matches */ public static Long getTime(String time, TimeUnit unit) throws Exception { - return unit.convert(getTime(time), TimeUnit.MILLISECONDS); + return unit.convert(getTime(time), TimeUnit.MILLISECONDS); } - + /** * Converts a string like '20minutes' into the appropriate amount of milliseconds. * @@ -131,35 +131,35 @@ public class Util { * @throws Exception if there are no matches */ public static Long getTime(String time) throws Exception { - if(time.equalsIgnoreCase("-1")) return -1L; - - Long t = 10L; - Matcher match = DURATION_PATTERN.matcher(time); - - if (match.matches()) { - String units = match.group(2); - if ("seconds".equals(units) || "second".equals(units) || "s".equals(units)) - t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.SECONDS); - else if ("minutes".equals(units) || "minute".equals(units) || "mins".equals(units) || "min".equals(units) || "m".equals(units)) + if(time.equalsIgnoreCase("-1")) return -1L; + + Long t = 10L; + Matcher match = DURATION_PATTERN.matcher(time); + + if (match.matches()) { + String units = match.group(2); + if ("seconds".equals(units) || "second".equals(units) || "s".equals(units)) + t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.SECONDS); + else if ("minutes".equals(units) || "minute".equals(units) || "mins".equals(units) || "min".equals(units) || "m".equals(units)) t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.MINUTES); else if ("hours".equals(units) || "hour".equals(units) || "h".equals(units)) - t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.HOURS); + t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.HOURS); else if ("days".equals(units) || "day".equals(units) || "d".equals(units)) - t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.DAYS); + t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.DAYS); else { - try { - t = TimeUnit.MILLISECONDS.convert(Long.parseLong(time), TimeUnit.MINUTES); - }catch(NumberFormatException e) { - throw new Exception("Invalid format."); - } + try { + t = TimeUnit.MILLISECONDS.convert(Long.parseLong(time), TimeUnit.MINUTES); + }catch(NumberFormatException e) { + throw new Exception("Invalid format."); + } } - }else { - throw new Exception("Invalid format."); - } - - return t; + }else { + throw new Exception("Invalid format."); + } + + return t; } - + /** * Converts the player inventory to a String array of Base64 strings. First string is the content and second string is the armor. * @@ -168,13 +168,13 @@ public class Util { * @throws IllegalStateException */ public static String[] playerInventoryToBase64(PlayerInventory playerInventory) throws IllegalStateException { - //get the main content part, this doesn't return the armor - String content = toBase64(playerInventory); - String armor = itemStackArrayToBase64(playerInventory.getArmorContents()); - - return new String[] { content, armor }; + //get the main content part, this doesn't return the armor + String content = toBase64(playerInventory); + String armor = itemStackArrayToBase64(playerInventory.getArmorContents()); + + return new String[] { content, armor }; } - + /** * * A method to serialize an {@link ItemStack} array to Base64 String. @@ -188,18 +188,18 @@ public class Util { * @throws IllegalStateException */ public static String itemStackArrayToBase64(ItemStack[] items) throws IllegalStateException { - try { + try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); - + // Write the size of the inventory dataOutput.writeInt(items.length); - + // Save every element in the list for (int i = 0; i < items.length; i++) { dataOutput.writeObject(items[i]); } - + // Serialize that array dataOutput.close(); return Base64Coder.encodeLines(outputStream.toByteArray()); @@ -207,7 +207,7 @@ public class Util { throw new IllegalStateException("Unable to save item stacks.", e); } } - + /** * A method to serialize an inventory to Base64 string. * @@ -226,15 +226,15 @@ public class Util { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); - + // Write the size of the inventory dataOutput.writeInt(inventory.getSize()); - + // Save every element in the list for (int i = 0; i < inventory.getSize(); i++) { dataOutput.writeObject(inventory.getItem(i)); } - + // Serialize that array dataOutput.close(); return Base64Coder.encodeLines(outputStream.toByteArray()); @@ -242,7 +242,7 @@ public class Util { throw new IllegalStateException("Unable to save item stacks.", e); } } - + /** * * A method to get an {@link Inventory} from an encoded, Base64, string. @@ -259,25 +259,25 @@ public class Util { * @throws IOException */ public static Inventory fromBase64(String data) throws IOException { - if(data.isEmpty()) return Bukkit.getServer().createInventory(null, 0); - + if(data.isEmpty()) return Bukkit.getServer().createInventory(null, 0); + try { ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); Inventory inventory = Bukkit.getServer().createInventory(null, dataInput.readInt()); - + // Read the serialized inventory for (int i = 0; i < inventory.getSize(); i++) { inventory.setItem(i, (ItemStack) dataInput.readObject()); } - + dataInput.close(); return inventory; } catch (ClassNotFoundException e) { throw new IOException("Unable to decode class type.", e); } } - + /** * Gets an array of ItemStacks from Base64 string. * @@ -290,57 +290,57 @@ public class Util { * @throws IOException */ public static ItemStack[] itemStackArrayFromBase64(String data) throws IOException { - if(data.isEmpty()) return new ItemStack[] {}; - - try { + if(data.isEmpty()) return new ItemStack[] {}; + + try { ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); ItemStack[] items = new ItemStack[dataInput.readInt()]; - + // Read the serialized inventory for (int i = 0; i < items.length; i++) { - items[i] = (ItemStack) dataInput.readObject(); + items[i] = (ItemStack) dataInput.readObject(); } - + dataInput.close(); return items; } catch (ClassNotFoundException e) { throw new IOException("Unable to decode class type.", e); } } - - public static void restoreInventory(Player player, Prisoner prisoner) { - try { - Inventory content = Util.fromBase64(prisoner.getInventory()); - ItemStack[] armor = Util.itemStackArrayFromBase64(prisoner.getArmor()); - - for(ItemStack item : armor) { - if(item == null) - continue; - else if(item.getType().toString().toLowerCase().contains("helmet")) - player.getInventory().setHelmet(item); - else if(item.getType().toString().toLowerCase().contains("chestplate")) - player.getInventory().setChestplate(item); - else if(item.getType().toString().toLowerCase().contains("leg")) - player.getInventory().setLeggings(item); - else if(item.getType().toString().toLowerCase().contains("boots")) - player.getInventory().setBoots(item); - else if (player.getInventory().firstEmpty() == -1) - player.getWorld().dropItem(player.getLocation(), item); - else - player.getInventory().addItem(item); - } - - for(ItemStack item : content.getContents()) { - if(item == null) continue; - else if(player.getInventory().firstEmpty() == -1) - player.getWorld().dropItem(player.getLocation(), item); - else - player.getInventory().addItem(item); - } - } catch (IOException e) { - e.printStackTrace(); - Bukkit.getLogger().severe("Unable to restore " + player.getName() + "'s inventory."); - } - } + + public static void restoreInventory(Player player, Prisoner prisoner) { + try { + Inventory content = Util.fromBase64(prisoner.getInventory()); + ItemStack[] armor = Util.itemStackArrayFromBase64(prisoner.getArmor()); + + for(ItemStack item : armor) { + if(item == null) + continue; + else if(item.getType().toString().toLowerCase().contains("helmet")) + player.getInventory().setHelmet(item); + else if(item.getType().toString().toLowerCase().contains("chestplate")) + player.getInventory().setChestplate(item); + else if(item.getType().toString().toLowerCase().contains("leg")) + player.getInventory().setLeggings(item); + else if(item.getType().toString().toLowerCase().contains("boots")) + player.getInventory().setBoots(item); + else if (player.getInventory().firstEmpty() == -1) + player.getWorld().dropItem(player.getLocation(), item); + else + player.getInventory().addItem(item); + } + + for(ItemStack item : content.getContents()) { + if(item == null) continue; + else if(player.getInventory().firstEmpty() == -1) + player.getWorld().dropItem(player.getLocation(), item); + else + player.getInventory().addItem(item); + } + } catch (IOException e) { + e.printStackTrace(); + Bukkit.getLogger().severe("Unable to restore " + player.getName() + "'s inventory."); + } + } } diff --git a/src/main/java/com/graywolf336/jail/beans/CachePrisoner.java b/src/main/java/com/graywolf336/jail/beans/CachePrisoner.java index 03988b9..58b8f98 100644 --- a/src/main/java/com/graywolf336/jail/beans/CachePrisoner.java +++ b/src/main/java/com/graywolf336/jail/beans/CachePrisoner.java @@ -8,21 +8,21 @@ package com.graywolf336.jail.beans; * @version 1.0.0 */ public class CachePrisoner { - private Jail jail; - private Prisoner p; - - public CachePrisoner(Jail jail, Prisoner prisoner) { - this.jail = jail; - this.p = prisoner; - } - - /** Gets the Jail this cache is in. */ - public Jail getJail() { - return this.jail; - } - - /** Gets the Prisoner in this cache. */ - public Prisoner getPrisoner() { - return this.p; - } + private Jail jail; + private Prisoner p; + + public CachePrisoner(Jail jail, Prisoner prisoner) { + this.jail = jail; + this.p = prisoner; + } + + /** Gets the Jail this cache is in. */ + public Jail getJail() { + return this.jail; + } + + /** Gets the Prisoner in this cache. */ + public Prisoner getPrisoner() { + return this.p; + } } diff --git a/src/main/java/com/graywolf336/jail/beans/Cell.java b/src/main/java/com/graywolf336/jail/beans/Cell.java index 6fe8236..7b03cd8 100644 --- a/src/main/java/com/graywolf336/jail/beans/Cell.java +++ b/src/main/java/com/graywolf336/jail/beans/Cell.java @@ -14,131 +14,131 @@ import org.bukkit.block.Chest; * @version 1.1.2 */ public class Cell { - private String name; - private Prisoner p; - private HashSet signs; - private SimpleLocation teleport, chest; - - /** Creates a new Cell with the given name - * - * @param name The name of the cell. - */ - public Cell(String name) { - this.name = name; - this.signs = new HashSet(); - } - - /** Gets the name of the cell. */ - public String getName() { - return this.name; - } - - /** Updates the signs of the cell, with the player name and time and such. TODO */ - public void update() { - //TODO: Update the signs - } - - /** Sets the prisoner in this cell. */ - public void setPrisoner(Prisoner prisoner) { - this.p = prisoner; - } - - /** Gets the prisoner being held in this cell. */ - public Prisoner getPrisoner() { - return this.p; - } - - /** Nullifies the prisoner data. */ - public void removePrisoner() { - this.p = null; - } - - /** Returns true if there is currently a prisoner in this cell. */ - public boolean hasPrisoner() { - return this.p != null; //Return true if prison is not null, as when it isn't null we have a prisoner in this cell - } - - /** Adds all the given signs to the cell. */ - public void addAllSigns(HashSet signs) { - this.signs.addAll(signs); - } - - /** Adds a sign to the cell. */ - public void addSign(SimpleLocation sign) { - this.signs.add(sign); - } - - /** Returns all the signs for this cell. */ - public HashSet getSigns() { - return this.signs; - } - - /** Returns the entire list of signs in a string. */ - public String getSignString() { - String r = ""; - - for(SimpleLocation s : signs) { - if(r.isEmpty()) { - r = s.toString(); - }else { - r += ";" + s.toString(); - } - } - - return r; - } - - /** Sets the location of where the prisoner will be teleported at when jailed here. */ - public void setTeleport(SimpleLocation location) { - this.teleport = location; - } - - /** Gets the teleport location where the prisoner will be teleported at when jailed here. */ - public Location getTeleport() { - return this.teleport.getLocation(); - } - - /** Sets the location of the chest. */ - public void setChestLocation(Location location) { - this.chest = new SimpleLocation(location); - } - - /** - * Gets the location of the chest, returns null if no chest is stored at this cell. - * - * @return The location of the chest, null if none. - */ - public Location getChestLocation() { - return this.chest.getLocation(); - } - - /** - * Gets the chest for this cell, returns null if there is no chest or the location we have is not a chest. - * - * @return The chest and its state. - */ - public Chest getChest() { - if(this.chest == null) return null; - if((this.chest.getLocation().getBlock() == null) || (this.chest.getLocation().getBlock().getType() != Material.CHEST)) return null; - - return (Chest) this.chest.getLocation().getBlock().getState(); - } - - /** - * Checks if the chest location doesn't equal null and if it is a double chest. - * - * @return true if there is a chest, false if there isn't. - */ - public boolean hasChest() { - Chest c = getChest(); - if(c != null) { - if(c.getInventory().getSize() >= 40) - return true; - else { - Bukkit.getLogger().severe("The cell " + this.name + " has chest that isn't a double chest, please fix."); - return false; - } - }else - return false; - } + private String name; + private Prisoner p; + private HashSet signs; + private SimpleLocation teleport, chest; + + /** Creates a new Cell with the given name + * + * @param name The name of the cell. + */ + public Cell(String name) { + this.name = name; + this.signs = new HashSet(); + } + + /** Gets the name of the cell. */ + public String getName() { + return this.name; + } + + /** Updates the signs of the cell, with the player name and time and such. TODO */ + public void update() { + //TODO: Update the signs + } + + /** Sets the prisoner in this cell. */ + public void setPrisoner(Prisoner prisoner) { + this.p = prisoner; + } + + /** Gets the prisoner being held in this cell. */ + public Prisoner getPrisoner() { + return this.p; + } + + /** Nullifies the prisoner data. */ + public void removePrisoner() { + this.p = null; + } + + /** Returns true if there is currently a prisoner in this cell. */ + public boolean hasPrisoner() { + return this.p != null; //Return true if prison is not null, as when it isn't null we have a prisoner in this cell + } + + /** Adds all the given signs to the cell. */ + public void addAllSigns(HashSet signs) { + this.signs.addAll(signs); + } + + /** Adds a sign to the cell. */ + public void addSign(SimpleLocation sign) { + this.signs.add(sign); + } + + /** Returns all the signs for this cell. */ + public HashSet getSigns() { + return this.signs; + } + + /** Returns the entire list of signs in a string. */ + public String getSignString() { + String r = ""; + + for(SimpleLocation s : signs) { + if(r.isEmpty()) { + r = s.toString(); + }else { + r += ";" + s.toString(); + } + } + + return r; + } + + /** Sets the location of where the prisoner will be teleported at when jailed here. */ + public void setTeleport(SimpleLocation location) { + this.teleport = location; + } + + /** Gets the teleport location where the prisoner will be teleported at when jailed here. */ + public Location getTeleport() { + return this.teleport.getLocation(); + } + + /** Sets the location of the chest. */ + public void setChestLocation(Location location) { + this.chest = new SimpleLocation(location); + } + + /** + * Gets the location of the chest, returns null if no chest is stored at this cell. + * + * @return The location of the chest, null if none. + */ + public Location getChestLocation() { + return this.chest.getLocation(); + } + + /** + * Gets the chest for this cell, returns null if there is no chest or the location we have is not a chest. + * + * @return The chest and its state. + */ + public Chest getChest() { + if(this.chest == null) return null; + if((this.chest.getLocation().getBlock() == null) || (this.chest.getLocation().getBlock().getType() != Material.CHEST)) return null; + + return (Chest) this.chest.getLocation().getBlock().getState(); + } + + /** + * Checks if the chest location doesn't equal null and if it is a double chest. + * + * @return true if there is a chest, false if there isn't. + */ + public boolean hasChest() { + Chest c = getChest(); + if(c != null) { + if(c.getInventory().getSize() >= 40) + return true; + else { + Bukkit.getLogger().severe("The cell " + this.name + " has chest that isn't a double chest, please fix."); + return false; + } + }else + return false; + } } diff --git a/src/main/java/com/graywolf336/jail/beans/ConfirmPlayer.java b/src/main/java/com/graywolf336/jail/beans/ConfirmPlayer.java index f9b3af8..a47bb7c 100644 --- a/src/main/java/com/graywolf336/jail/beans/ConfirmPlayer.java +++ b/src/main/java/com/graywolf336/jail/beans/ConfirmPlayer.java @@ -10,35 +10,35 @@ import com.graywolf336.jail.enums.Confirmation; * @since 3.0.0 */ public class ConfirmPlayer { - private String name; - private String[] args; - private Confirmation confirm; - private Long expires; - - public ConfirmPlayer(String name, String[] args, Confirmation confirm) { - this.name = name; - this.args = args; - this.confirm = confirm; - this.expires = System.currentTimeMillis() + 5000L; - } - - /** Returns the name of the thing needing to confirm. */ - public String getName() { - return this.name; - } - - /** Returns the initial arguments they sent with their command. */ - public String[] getArguments() { - return this.args; - } - - /** Returns what they are {@link Confirmation confirming}. */ - public Confirmation getConfirming() { - return this.confirm; - } - - /** Returns the time in milliseconds their confirmation time frame expires. */ - public Long getExpiryTime() { - return this.expires; - } + private String name; + private String[] args; + private Confirmation confirm; + private Long expires; + + public ConfirmPlayer(String name, String[] args, Confirmation confirm) { + this.name = name; + this.args = args; + this.confirm = confirm; + this.expires = System.currentTimeMillis() + 5000L; + } + + /** Returns the name of the thing needing to confirm. */ + public String getName() { + return this.name; + } + + /** Returns the initial arguments they sent with their command. */ + public String[] getArguments() { + return this.args; + } + + /** Returns what they are {@link Confirmation confirming}. */ + public Confirmation getConfirming() { + return this.confirm; + } + + /** Returns the time in milliseconds their confirmation time frame expires. */ + public Long getExpiryTime() { + return this.expires; + } } diff --git a/src/main/java/com/graywolf336/jail/beans/CreationPlayer.java b/src/main/java/com/graywolf336/jail/beans/CreationPlayer.java index 4df202b..bc97fa7 100644 --- a/src/main/java/com/graywolf336/jail/beans/CreationPlayer.java +++ b/src/main/java/com/graywolf336/jail/beans/CreationPlayer.java @@ -1,227 +1,227 @@ -package com.graywolf336.jail.beans; - -import java.util.HashSet; - -import org.bukkit.Bukkit; -import org.bukkit.Location; - -/** - * Represents an instance of a player creating something, whether it be a jail or cell. - * - * @author graywolf336 - * @since 3.0.0 - * @version 1.1.0 - * - */ -public class CreationPlayer { - private String jailName, cellName; - private int step; - private int x1, y1, z1, x2, y2, z2; - private String inWorld, freeWorld; - private double inX, inY, inZ, freeX, freeY, freeZ; - private float inPitch, inYaw, freePitch, freeYaw; - private HashSet signs; - private Location chest; - - /** - * Create a new instance of a CreationPlayer, given the name of the jail. - * - * @param jailName The name of the jail. - */ - public CreationPlayer(String jailName) { - this.jailName = jailName; - this.step = 1; //Set the default to 1 when creating this. - } - - /** - * Creates a new instance of a CreationPlayer, give the name of the jail and cell. - * - * @param jailName The name of the jail. - * @param cellName The name of the cell. - */ - public CreationPlayer(String jailName, String cellName) { - this.jailName = jailName; - this.cellName = cellName; - this.signs = new HashSet(); - this.step = 1; - } - - /** Gets the name of the jail. */ - public String getJailName() { - return this.jailName; - } - - /** Gets the name of the cell. */ - public String getCellName() { - return this.cellName; - } - - /** - * Returns the step the creation is in. - * - *

- * - * If it is a Jail, then when these numbers are returned it means the following: - *

    - *
  1. Creating the first block of the Jail region.
  2. - *
  3. Creating the second block of the Jail region.
  4. - *
  5. Creating the teleport in location.
  6. - *
  7. Creating the teleport out location.
  8. - *
- * - * If it is a Cell, then when these numbers are returned it means the following: - *
    - *
  1. Setting the teleport in location.
  2. - *
  3. Setting all the signs.
  4. - *
  5. Setting the double chest.
  6. - *
- * - * @return The step of the Jail/Cell Creation, as an integer. - */ - public int getStep() { - return this.step; - } - - /** - * Sets the step of the creation. - * - * @param step The state of the creation, see {@link #getStep() getStep} for more information. - */ - public void setStep(int step) { - this.step = step; - } - - /** - * Increments the current step up one. - * - *

- * - * Notice: Using this method can cause the step to go above four (three for cell), - * which might cause errors later on. Only use when you know that it won't - * be used again or you know for a fact that the next step is not above four (three for cell). - * - */ - public void nextStep() { - this.step++; - } - - /** Sets the first corner with the given location. */ - public void setCornerOne(Location loc) { - this.x1 = loc.getBlockX(); - this.y1 = loc.getBlockY(); - this.z1 = loc.getBlockZ(); - } - - /** Sets the first corner with the given x, y, and z. */ - public void setCornerOne(int x, int y, int z) { - this.x1 = x; - this.y1 = y; - this.z1 = z; - } - - /** Returns the first corner coords an array of int. 0 = x, 1 = y, 2 = z */ - public int[] getCornerOne() { - int[] t = {x1, y1, z1}; - return t; - } - - /** Sets the second corner with the given location. */ - public void setCornerTwo(Location loc) { - this.x2 = loc.getBlockX(); - this.y2 = loc.getBlockY(); - this.z2 = loc.getBlockZ(); - } - - /** Sets the second corner with the given x, y, and z. */ - public void setCornerTwo(int x, int y, int z) { - this.x2 = x; - this.y2 = y; - this.z2 = z; - } - - /** Returns the second corner coords an array of int. 0 = x, 1 = y, 2 = z */ - public int[] getCornerTwo() { - int[] t = {x2, y2, z2}; - return t; - } - - /** Sets the teleport in coords from the given location. */ - public void setTeleportIn(Location location) { - this.inWorld = location.getWorld().getName(); - this.inX = location.getX(); - this.inY = location.getY(); - this.inZ = location.getZ(); - this.inYaw = location.getYaw(); - this.inPitch = location.getPitch(); - } - - /** Sets the teleport in coords from the given params. */ - public void setTeleportIn(String world, double x, double y, double z, float yaw, float pitch) { - this.inWorld = world; - this.inX = x; - this.inY = y; - this.inZ = z; - this.inYaw = yaw; - this.inPitch = pitch; - } - - /** Gets the teleport in location in a {@link Location}. */ - public Location getTeleportIn() { - return new Location(Bukkit.getWorld(inWorld), inX, inY, inZ, inYaw, inPitch); - } - - /** Gets the teleport in location in a {@link SimpleLocation}. */ - public SimpleLocation getTeleportInSL() { - return new SimpleLocation(inWorld, inX, inY, inZ, inYaw, inPitch); - } - - /** Sets the teleport free coords from the given location. */ - public void setTeleportFree(Location location) { - this.freeWorld = location.getWorld().getName(); - this.freeX = location.getX(); - this.freeY = location.getY(); - this.freeZ = location.getZ(); - this.freeYaw = location.getYaw(); - this.freePitch = location.getPitch(); - } - - /** Sets the teleport in coords from the given params. */ - public void setTeleportFree(String world, double x, double y, double z, float yaw, float pitch) { - this.freeWorld = world; - this.freeX = x; - this.freeY = y; - this.freeZ = z; - this.freeYaw = yaw; - this.freePitch = pitch; - } - - /** Gets the teleport free location in a {@link Location}. */ - public Location getTeleportFree() { - return new Location(Bukkit.getWorld(freeWorld), freeX, freeY, freeZ, freeYaw, freePitch); - } - - /** Gets the teleport free location in a {@link SimpleLocation}. */ - public SimpleLocation getTeleportFreeSL() { - return new SimpleLocation(freeWorld, freeX, freeY, freeZ, freeYaw, freePitch); - } - - /** Adds a sign to this cell. */ - public void addSign(SimpleLocation sign) { - this.signs.add(sign); - } - - /** Returns all the signs, null if none (usually null when a jail is being created). */ - public HashSet getSigns() { - return this.signs == null ? null : new HashSet(this.signs); - } - - /** Sets the chest's location, used mainly for cells. */ - public void setChestLocation(Location loc) { - this.chest = loc; - } - - /** Gets the chest's location. */ - public Location getChestLocation() { - return this.chest; - } -} +package com.graywolf336.jail.beans; + +import java.util.HashSet; + +import org.bukkit.Bukkit; +import org.bukkit.Location; + +/** + * Represents an instance of a player creating something, whether it be a jail or cell. + * + * @author graywolf336 + * @since 3.0.0 + * @version 1.1.0 + * + */ +public class CreationPlayer { + private String jailName, cellName; + private int step; + private int x1, y1, z1, x2, y2, z2; + private String inWorld, freeWorld; + private double inX, inY, inZ, freeX, freeY, freeZ; + private float inPitch, inYaw, freePitch, freeYaw; + private HashSet signs; + private Location chest; + + /** + * Create a new instance of a CreationPlayer, given the name of the jail. + * + * @param jailName The name of the jail. + */ + public CreationPlayer(String jailName) { + this.jailName = jailName; + this.step = 1; //Set the default to 1 when creating this. + } + + /** + * Creates a new instance of a CreationPlayer, give the name of the jail and cell. + * + * @param jailName The name of the jail. + * @param cellName The name of the cell. + */ + public CreationPlayer(String jailName, String cellName) { + this.jailName = jailName; + this.cellName = cellName; + this.signs = new HashSet(); + this.step = 1; + } + + /** Gets the name of the jail. */ + public String getJailName() { + return this.jailName; + } + + /** Gets the name of the cell. */ + public String getCellName() { + return this.cellName; + } + + /** + * Returns the step the creation is in. + * + *

+ * + * If it is a Jail, then when these numbers are returned it means the following: + *

    + *
  1. Creating the first block of the Jail region.
  2. + *
  3. Creating the second block of the Jail region.
  4. + *
  5. Creating the teleport in location.
  6. + *
  7. Creating the teleport out location.
  8. + *
+ * + * If it is a Cell, then when these numbers are returned it means the following: + *
    + *
  1. Setting the teleport in location.
  2. + *
  3. Setting all the signs.
  4. + *
  5. Setting the double chest.
  6. + *
+ * + * @return The step of the Jail/Cell Creation, as an integer. + */ + public int getStep() { + return this.step; + } + + /** + * Sets the step of the creation. + * + * @param step The state of the creation, see {@link #getStep() getStep} for more information. + */ + public void setStep(int step) { + this.step = step; + } + + /** + * Increments the current step up one. + * + *

+ * + * Notice: Using this method can cause the step to go above four (three for cell), + * which might cause errors later on. Only use when you know that it won't + * be used again or you know for a fact that the next step is not above four (three for cell). + * + */ + public void nextStep() { + this.step++; + } + + /** Sets the first corner with the given location. */ + public void setCornerOne(Location loc) { + this.x1 = loc.getBlockX(); + this.y1 = loc.getBlockY(); + this.z1 = loc.getBlockZ(); + } + + /** Sets the first corner with the given x, y, and z. */ + public void setCornerOne(int x, int y, int z) { + this.x1 = x; + this.y1 = y; + this.z1 = z; + } + + /** Returns the first corner coords an array of int. 0 = x, 1 = y, 2 = z */ + public int[] getCornerOne() { + int[] t = {x1, y1, z1}; + return t; + } + + /** Sets the second corner with the given location. */ + public void setCornerTwo(Location loc) { + this.x2 = loc.getBlockX(); + this.y2 = loc.getBlockY(); + this.z2 = loc.getBlockZ(); + } + + /** Sets the second corner with the given x, y, and z. */ + public void setCornerTwo(int x, int y, int z) { + this.x2 = x; + this.y2 = y; + this.z2 = z; + } + + /** Returns the second corner coords an array of int. 0 = x, 1 = y, 2 = z */ + public int[] getCornerTwo() { + int[] t = {x2, y2, z2}; + return t; + } + + /** Sets the teleport in coords from the given location. */ + public void setTeleportIn(Location location) { + this.inWorld = location.getWorld().getName(); + this.inX = location.getX(); + this.inY = location.getY(); + this.inZ = location.getZ(); + this.inYaw = location.getYaw(); + this.inPitch = location.getPitch(); + } + + /** Sets the teleport in coords from the given params. */ + public void setTeleportIn(String world, double x, double y, double z, float yaw, float pitch) { + this.inWorld = world; + this.inX = x; + this.inY = y; + this.inZ = z; + this.inYaw = yaw; + this.inPitch = pitch; + } + + /** Gets the teleport in location in a {@link Location}. */ + public Location getTeleportIn() { + return new Location(Bukkit.getWorld(inWorld), inX, inY, inZ, inYaw, inPitch); + } + + /** Gets the teleport in location in a {@link SimpleLocation}. */ + public SimpleLocation getTeleportInSL() { + return new SimpleLocation(inWorld, inX, inY, inZ, inYaw, inPitch); + } + + /** Sets the teleport free coords from the given location. */ + public void setTeleportFree(Location location) { + this.freeWorld = location.getWorld().getName(); + this.freeX = location.getX(); + this.freeY = location.getY(); + this.freeZ = location.getZ(); + this.freeYaw = location.getYaw(); + this.freePitch = location.getPitch(); + } + + /** Sets the teleport in coords from the given params. */ + public void setTeleportFree(String world, double x, double y, double z, float yaw, float pitch) { + this.freeWorld = world; + this.freeX = x; + this.freeY = y; + this.freeZ = z; + this.freeYaw = yaw; + this.freePitch = pitch; + } + + /** Gets the teleport free location in a {@link Location}. */ + public Location getTeleportFree() { + return new Location(Bukkit.getWorld(freeWorld), freeX, freeY, freeZ, freeYaw, freePitch); + } + + /** Gets the teleport free location in a {@link SimpleLocation}. */ + public SimpleLocation getTeleportFreeSL() { + return new SimpleLocation(freeWorld, freeX, freeY, freeZ, freeYaw, freePitch); + } + + /** Adds a sign to this cell. */ + public void addSign(SimpleLocation sign) { + this.signs.add(sign); + } + + /** Returns all the signs, null if none (usually null when a jail is being created). */ + public HashSet getSigns() { + return this.signs == null ? null : new HashSet(this.signs); + } + + /** Sets the chest's location, used mainly for cells. */ + public void setChestLocation(Location loc) { + this.chest = loc; + } + + /** Gets the chest's location. */ + public Location getChestLocation() { + return this.chest; + } +} diff --git a/src/main/java/com/graywolf336/jail/beans/Jail.java b/src/main/java/com/graywolf336/jail/beans/Jail.java index 477cea4..10e0607 100644 --- a/src/main/java/com/graywolf336/jail/beans/Jail.java +++ b/src/main/java/com/graywolf336/jail/beans/Jail.java @@ -20,375 +20,375 @@ import com.graywolf336.jail.Util; * @version 1.0.3 */ public class Jail { - private JailMain plugin; - private boolean enabled; - private HashMap cells; - private HashMap nocellPrisoners;//prisoners who aren't in a cell - private String name = "", world = ""; - private int minX, minY, minZ, maxX, maxY, maxZ; - private Location in, free; - - public Jail(JailMain plugin, String name) { - this.plugin = plugin; - this.enabled = true; - this.name = name; - cells = new HashMap(); - nocellPrisoners = new HashMap(); - } - - /** Gets the instance of the plugin's main class. */ - public JailMain getPlugin() { - return this.plugin; - } - - /** Sets whether this jail can be used or not. */ - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - /** Gets whether this jail is enabled or not. */ - public boolean isEnabled() { - return this.enabled; - } - - /** Sets the name of the jail. */ - public void setName(String name) { - this.name = name; - } - - /** Gets the name of the jail. */ - public String getName() { - return this.name; - } - - /** Sets the location of the minimum point to the given location's coordinates. */ - public void setMinPoint(Location location) { - if(this.world.isEmpty()) this.world = location.getWorld().getName(); - - this.minX = location.getBlockX(); - this.minY = location.getBlockY(); - this.minZ = location.getBlockZ(); - } - - /** Accepts an array of ints as the coord, where 0 = x, 1 = y, 2 = z. */ - public void setMinPoint(int[] coords) { - if(coords.length != 3) return; - - this.minX = coords[0]; - this.minY = coords[1]; - this.minZ = coords[2]; - } - - /** Gets the minimum point as a Bukkit Location class. */ - public Location getMinPoint() { - return new Location(plugin.getServer().getWorld(world), minX, minY, minZ); - } - - /** Sets the location of the maximum point to the given location's coordinates. */ - public void setMaxPoint(Location location) { - if(this.world.isEmpty()) this.world = location.getWorld().getName(); - - this.maxX = location.getBlockX(); - this.maxY = location.getBlockY(); - this.maxZ = location.getBlockZ(); - } - - /** Gets the minimum point as a Bukkit Location class. */ - public Location getMaxPoint() { - return new Location(plugin.getServer().getWorld(world), maxX, maxY, maxZ); - } - - /** Accepts an array of ints as the coord, where 0 = x, 1 = y, 2 = z. */ - public void setMaxPoint(int[] coords) { - if(coords.length != 3) return; - - this.maxX = coords[0]; - this.maxY = coords[1]; - this.maxZ = coords[2]; - } - - /** Sets the name of the world this Jail is in. */ - public void setWorld(String name) { - this.world = name; - } - - /** Gets the name of the world this Jail is in. */ - public String getWorldName() { - return this.world; - } - - /** Gets the instance of the {@link World world} this Jail is in. */ - public World getWorld() { - return plugin.getServer().getWorld(world); - } - - /** Sets the {@link Location location} of the teleport in. */ - public void setTeleportIn(Location location) { - if(this.world.isEmpty()) this.world = location.getWorld().getName(); - - this.in = location; - } - - /** Gets the {@link Location location} of the teleport in. */ - public Location getTeleportIn() { - return this.in; - } - - /** Sets the {@link Location location} of the teleport for the free spot. */ - public void setTeleportFree(Location location) { - this.free = location; - } - - /** Gets the {@link Location location} of the teleport free spot.*/ - public Location getTeleportFree() { - return this.free; - } - - /** Add a prisoner to this jail. */ - public void addPrisoner(Prisoner p) { - this.nocellPrisoners.put(p.getUUID(), p); - } - - /** Removes a prisoner from this jail, doesn't remove it from the cell. */ - public void removePrisoner(Prisoner p) { - this.nocellPrisoners.remove(p.getUUID()); - } - - /** Adds a cell to the Jail. */ - public void addCell(Cell cell, boolean save) { - if(save) plugin.getJailIO().saveCell(this, cell); - this.cells.put(cell.getName(), cell); - } - - /** Gets the cell with the given name. */ - public Cell getCell(String name) { - return this.cells.get(name); - } - - /** Checks if the given name is a valid cell. */ - public boolean isValidCell(String name) { - return this.cells.get(name) != null; - } - - /** Removes the cell from the jail. */ - public void removeCell(String name) { - Cell c = this.cells.get(name); - //If we have a chest, clear the inventory - if(c.hasChest()) { - c.getChest().getInventory().clear(); - } - - //For each sign, clear the lines on the sign - for(SimpleLocation s : c.getSigns()) { - if(s.getLocation().getBlock() instanceof Sign) { - Sign sign = (Sign) s.getLocation().getBlock(); - for(int i = 0; i < 4; i++) { - sign.setLine(i, ""); - } - } - } - - //remove the information from the storage first as it requires an instance - plugin.getJailIO().removeCell(this, c); - //now remove it from the local storage - this.cells.remove(name); - } - - /** Returns the cell which the given player name is jailed in, null if not. */ - public Cell getCellPrisonerIsIn(UUID uuid) { - for(Cell c : cells.values()) - if(c.hasPrisoner()) - if(c.getPrisoner().getUUID().equals(uuid)) - return c; - - return null; - } - - /** Returns the first empty cell, returns null if there aren't any cells or any free cells. */ - public Cell getFirstEmptyCell() { - for(Cell c : getCells()) - if(c.hasPrisoner()) - continue; - else - return c; - - return null; - } - - /** Gets the amount of cells the jail. */ - public int getCellCount() { - return this.cells.size(); - } - - /** Gets all the cells in the jail. */ - public HashSet getCells() { - return new HashSet(this.cells.values()); - } - - /** Gets the closest cell to the provided location, via the teleport in location of the cells. */ - public Cell getNearestCell(Location loc) { - Cell cell = null; - double distance = -1; - - for(Cell c : getCells()) { - //Check if the worlds are the same, if not we can't calculate anything - if(c.getTeleport().getWorld().getName().equalsIgnoreCase(loc.getWorld().getName())) { - //They are in the same world - double dist = c.getTeleport().distance(loc); - if (dist < distance || distance < 0) { - cell = c; - distance = dist; - } - }else { - //If they aren't, return the first cell found. - return c; - } - } - - return cell; - } - - /** Clears all the prisoners from this Jail. */ - public void clearPrisoners() { - //Remove the prisoners from all the cells - for(Cell c : getCells()) { - c.removePrisoner(); - } - - //Replace all the current no cell prisoners with - //a new hashset of prisoners. - this.nocellPrisoners = new HashMap(); - } - - /** Gets a HashMap of all the prisoners, the ones in cells and ones who aren't. */ - public HashMap getAllPrisoners() { - HashMap all = new HashMap(nocellPrisoners); //initalize the temp one to return with the prisoners not in any cells - - for(Cell c : cells.values()) - if(c.hasPrisoner()) - all.put(c.getPrisoner().getUUID(), c.getPrisoner()); - - return all; - } - - /** Gets a HashSet of the prisoners in cells. */ - public HashSet getPrisonersInCells() { - HashSet all = new HashSet(); - - for(Cell c : getCells()) - if(c.hasPrisoner()) - all.add(c.getPrisoner()); - - return all; - } - - /** Gets a HashSet of the prisoners not in cells.*/ - public HashMap getPrisonersNotInCells() { - return this.nocellPrisoners; - } - - /** - * Returns whether the player is a prisoner in the system, whether in a cell or no cell. - * - * @param player The {@link Player player instance} of the person we're checking. - * @return true if is jailed, false if not. - */ - public boolean isPlayerJailed(Player player) { - return this.isPlayerAPrisoner(player.getUniqueId()); - } - - /** - * Returns whether the uuid of a player is a prisoner in the system, whether in a cell or no cell. - * - * @param uuid The uuid of the person we're checking. - * @return true if is jailed, false if not. - */ - public boolean isPlayerJailed(UUID uuid) { - return this.isPlayerAPrisoner(uuid); - } - - /** - * Returns whether the uuid of a player is a prisoner in this jail, no matter if they're in a cell or not. - * - * @param uuid The name of the person we're checking. - * @return true if is a prisoner, false if not. - */ - private boolean isPlayerAPrisoner(UUID uuid) { - return this.getAllPrisoners().containsKey(uuid); - } - - /** - * Checks if the given uuid of a player is a prisoner in a cell. - * - * @param uuid of the prisoner to check. - * @return true if is jailed in a cell, false if not. - */ - public boolean isJailedInACell(UUID uuid) { - if(this.nocellPrisoners.containsKey(uuid)) return false; - - for(Cell c : cells.values()) - if(c.getPrisoner() != null) - if(c.getPrisoner().getUUID().equals(uuid)) - return true; - - return false; - } - - /** - * Gets the {@link Prisoner prisoner} instance for the given name. - * - * @param name The name of the prisoner to get. - * @return the prisoner instance, can be null - */ - public Prisoner getPrisonerByLastKnownName(String name) { - for(Prisoner p : this.getAllPrisoners().values()) - if(p.getLastKnownName().equalsIgnoreCase(name)) - return p; - - return null; - } - - /** - * Gets the {@link Prisoner prisoner} instance for the given uuid. - * - * @param uuid The uuid of the prisoner to get. - * @return the prisoner instance, can be null - */ - public Prisoner getPrisoner(UUID uuid) { - if(this.nocellPrisoners.containsKey(uuid)) return this.nocellPrisoners.get(uuid); - - for(Cell c : cells.values()) - if(c.hasPrisoner()) - if(c.getPrisoner().getUUID().equals(uuid)) - return c.getPrisoner(); - - return null; - } - - /** - * Returns the squared distance between teleport location of this jail - * and specified location in blocks. If locations are not in same world, - * distance cannot be calculated and it will return Integer.MAX_VALUE. - * - * @param loc The location to check - * @return Distance between the location provided and the teleport in location. - */ - public double getDistance(Location loc) { - if (!loc.getWorld().getName().equalsIgnoreCase(getTeleportIn().getWorld().getName())) return (double) Integer.MAX_VALUE; - else return loc.distance(getTeleportIn()); - } - - /** - * Returns whether the given location is inside this Jail. - * - * @param loc to check whether is inside this jail - * @return True if the location is in the jail, false if it isn't - */ - public boolean isInside(Location loc) { - if(loc.getWorld().getName().equalsIgnoreCase(world)) { - return Util.isInsideAB(loc.toVector(), new Vector(minX, minY, minZ), new Vector(maxX, maxY, maxZ)); - }else { - return false; - } - } + private JailMain plugin; + private boolean enabled; + private HashMap cells; + private HashMap nocellPrisoners;//prisoners who aren't in a cell + private String name = "", world = ""; + private int minX, minY, minZ, maxX, maxY, maxZ; + private Location in, free; + + public Jail(JailMain plugin, String name) { + this.plugin = plugin; + this.enabled = true; + this.name = name; + cells = new HashMap(); + nocellPrisoners = new HashMap(); + } + + /** Gets the instance of the plugin's main class. */ + public JailMain getPlugin() { + return this.plugin; + } + + /** Sets whether this jail can be used or not. */ + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + /** Gets whether this jail is enabled or not. */ + public boolean isEnabled() { + return this.enabled; + } + + /** Sets the name of the jail. */ + public void setName(String name) { + this.name = name; + } + + /** Gets the name of the jail. */ + public String getName() { + return this.name; + } + + /** Sets the location of the minimum point to the given location's coordinates. */ + public void setMinPoint(Location location) { + if(this.world.isEmpty()) this.world = location.getWorld().getName(); + + this.minX = location.getBlockX(); + this.minY = location.getBlockY(); + this.minZ = location.getBlockZ(); + } + + /** Accepts an array of ints as the coord, where 0 = x, 1 = y, 2 = z. */ + public void setMinPoint(int[] coords) { + if(coords.length != 3) return; + + this.minX = coords[0]; + this.minY = coords[1]; + this.minZ = coords[2]; + } + + /** Gets the minimum point as a Bukkit Location class. */ + public Location getMinPoint() { + return new Location(plugin.getServer().getWorld(world), minX, minY, minZ); + } + + /** Sets the location of the maximum point to the given location's coordinates. */ + public void setMaxPoint(Location location) { + if(this.world.isEmpty()) this.world = location.getWorld().getName(); + + this.maxX = location.getBlockX(); + this.maxY = location.getBlockY(); + this.maxZ = location.getBlockZ(); + } + + /** Gets the minimum point as a Bukkit Location class. */ + public Location getMaxPoint() { + return new Location(plugin.getServer().getWorld(world), maxX, maxY, maxZ); + } + + /** Accepts an array of ints as the coord, where 0 = x, 1 = y, 2 = z. */ + public void setMaxPoint(int[] coords) { + if(coords.length != 3) return; + + this.maxX = coords[0]; + this.maxY = coords[1]; + this.maxZ = coords[2]; + } + + /** Sets the name of the world this Jail is in. */ + public void setWorld(String name) { + this.world = name; + } + + /** Gets the name of the world this Jail is in. */ + public String getWorldName() { + return this.world; + } + + /** Gets the instance of the {@link World world} this Jail is in. */ + public World getWorld() { + return plugin.getServer().getWorld(world); + } + + /** Sets the {@link Location location} of the teleport in. */ + public void setTeleportIn(Location location) { + if(this.world.isEmpty()) this.world = location.getWorld().getName(); + + this.in = location; + } + + /** Gets the {@link Location location} of the teleport in. */ + public Location getTeleportIn() { + return this.in; + } + + /** Sets the {@link Location location} of the teleport for the free spot. */ + public void setTeleportFree(Location location) { + this.free = location; + } + + /** Gets the {@link Location location} of the teleport free spot.*/ + public Location getTeleportFree() { + return this.free; + } + + /** Add a prisoner to this jail. */ + public void addPrisoner(Prisoner p) { + this.nocellPrisoners.put(p.getUUID(), p); + } + + /** Removes a prisoner from this jail, doesn't remove it from the cell. */ + public void removePrisoner(Prisoner p) { + this.nocellPrisoners.remove(p.getUUID()); + } + + /** Adds a cell to the Jail. */ + public void addCell(Cell cell, boolean save) { + if(save) plugin.getJailIO().saveCell(this, cell); + this.cells.put(cell.getName(), cell); + } + + /** Gets the cell with the given name. */ + public Cell getCell(String name) { + return this.cells.get(name); + } + + /** Checks if the given name is a valid cell. */ + public boolean isValidCell(String name) { + return this.cells.get(name) != null; + } + + /** Removes the cell from the jail. */ + public void removeCell(String name) { + Cell c = this.cells.get(name); + //If we have a chest, clear the inventory + if(c.hasChest()) { + c.getChest().getInventory().clear(); + } + + //For each sign, clear the lines on the sign + for(SimpleLocation s : c.getSigns()) { + if(s.getLocation().getBlock() instanceof Sign) { + Sign sign = (Sign) s.getLocation().getBlock(); + for(int i = 0; i < 4; i++) { + sign.setLine(i, ""); + } + } + } + + //remove the information from the storage first as it requires an instance + plugin.getJailIO().removeCell(this, c); + //now remove it from the local storage + this.cells.remove(name); + } + + /** Returns the cell which the given player name is jailed in, null if not. */ + public Cell getCellPrisonerIsIn(UUID uuid) { + for(Cell c : cells.values()) + if(c.hasPrisoner()) + if(c.getPrisoner().getUUID().equals(uuid)) + return c; + + return null; + } + + /** Returns the first empty cell, returns null if there aren't any cells or any free cells. */ + public Cell getFirstEmptyCell() { + for(Cell c : getCells()) + if(c.hasPrisoner()) + continue; + else + return c; + + return null; + } + + /** Gets the amount of cells the jail. */ + public int getCellCount() { + return this.cells.size(); + } + + /** Gets all the cells in the jail. */ + public HashSet getCells() { + return new HashSet(this.cells.values()); + } + + /** Gets the closest cell to the provided location, via the teleport in location of the cells. */ + public Cell getNearestCell(Location loc) { + Cell cell = null; + double distance = -1; + + for(Cell c : getCells()) { + //Check if the worlds are the same, if not we can't calculate anything + if(c.getTeleport().getWorld().getName().equalsIgnoreCase(loc.getWorld().getName())) { + //They are in the same world + double dist = c.getTeleport().distance(loc); + if (dist < distance || distance < 0) { + cell = c; + distance = dist; + } + }else { + //If they aren't, return the first cell found. + return c; + } + } + + return cell; + } + + /** Clears all the prisoners from this Jail. */ + public void clearPrisoners() { + //Remove the prisoners from all the cells + for(Cell c : getCells()) { + c.removePrisoner(); + } + + //Replace all the current no cell prisoners with + //a new hashset of prisoners. + this.nocellPrisoners = new HashMap(); + } + + /** Gets a HashMap of all the prisoners, the ones in cells and ones who aren't. */ + public HashMap getAllPrisoners() { + HashMap all = new HashMap(nocellPrisoners); //initalize the temp one to return with the prisoners not in any cells + + for(Cell c : cells.values()) + if(c.hasPrisoner()) + all.put(c.getPrisoner().getUUID(), c.getPrisoner()); + + return all; + } + + /** Gets a HashSet of the prisoners in cells. */ + public HashSet getPrisonersInCells() { + HashSet all = new HashSet(); + + for(Cell c : getCells()) + if(c.hasPrisoner()) + all.add(c.getPrisoner()); + + return all; + } + + /** Gets a HashSet of the prisoners not in cells.*/ + public HashMap getPrisonersNotInCells() { + return this.nocellPrisoners; + } + + /** + * Returns whether the player is a prisoner in the system, whether in a cell or no cell. + * + * @param player The {@link Player player instance} of the person we're checking. + * @return true if is jailed, false if not. + */ + public boolean isPlayerJailed(Player player) { + return this.isPlayerAPrisoner(player.getUniqueId()); + } + + /** + * Returns whether the uuid of a player is a prisoner in the system, whether in a cell or no cell. + * + * @param uuid The uuid of the person we're checking. + * @return true if is jailed, false if not. + */ + public boolean isPlayerJailed(UUID uuid) { + return this.isPlayerAPrisoner(uuid); + } + + /** + * Returns whether the uuid of a player is a prisoner in this jail, no matter if they're in a cell or not. + * + * @param uuid The name of the person we're checking. + * @return true if is a prisoner, false if not. + */ + private boolean isPlayerAPrisoner(UUID uuid) { + return this.getAllPrisoners().containsKey(uuid); + } + + /** + * Checks if the given uuid of a player is a prisoner in a cell. + * + * @param uuid of the prisoner to check. + * @return true if is jailed in a cell, false if not. + */ + public boolean isJailedInACell(UUID uuid) { + if(this.nocellPrisoners.containsKey(uuid)) return false; + + for(Cell c : cells.values()) + if(c.getPrisoner() != null) + if(c.getPrisoner().getUUID().equals(uuid)) + return true; + + return false; + } + + /** + * Gets the {@link Prisoner prisoner} instance for the given name. + * + * @param name The name of the prisoner to get. + * @return the prisoner instance, can be null + */ + public Prisoner getPrisonerByLastKnownName(String name) { + for(Prisoner p : this.getAllPrisoners().values()) + if(p.getLastKnownName().equalsIgnoreCase(name)) + return p; + + return null; + } + + /** + * Gets the {@link Prisoner prisoner} instance for the given uuid. + * + * @param uuid The uuid of the prisoner to get. + * @return the prisoner instance, can be null + */ + public Prisoner getPrisoner(UUID uuid) { + if(this.nocellPrisoners.containsKey(uuid)) return this.nocellPrisoners.get(uuid); + + for(Cell c : cells.values()) + if(c.hasPrisoner()) + if(c.getPrisoner().getUUID().equals(uuid)) + return c.getPrisoner(); + + return null; + } + + /** + * Returns the squared distance between teleport location of this jail + * and specified location in blocks. If locations are not in same world, + * distance cannot be calculated and it will return Integer.MAX_VALUE. + * + * @param loc The location to check + * @return Distance between the location provided and the teleport in location. + */ + public double getDistance(Location loc) { + if (!loc.getWorld().getName().equalsIgnoreCase(getTeleportIn().getWorld().getName())) return Integer.MAX_VALUE; + else return loc.distance(getTeleportIn()); + } + + /** + * Returns whether the given location is inside this Jail. + * + * @param loc to check whether is inside this jail + * @return True if the location is in the jail, false if it isn't + */ + public boolean isInside(Location loc) { + if(loc.getWorld().getName().equalsIgnoreCase(world)) { + return Util.isInsideAB(loc.toVector(), new Vector(minX, minY, minZ), new Vector(maxX, maxY, maxZ)); + }else { + return false; + } + } } diff --git a/src/main/java/com/graywolf336/jail/beans/Prisoner.java b/src/main/java/com/graywolf336/jail/beans/Prisoner.java index e6e2f64..1454da8 100644 --- a/src/main/java/com/graywolf336/jail/beans/Prisoner.java +++ b/src/main/java/com/graywolf336/jail/beans/Prisoner.java @@ -15,273 +15,273 @@ import org.bukkit.Location; * @version 3.0.2 */ public class Prisoner { - private String uuid, name, jailer, reason, inventory, armor; - private boolean muted, offlinePending, teleporting, toBeTransferred, changed; - private long time, afk; - private Location previousPosition; - private GameMode previousGameMode; - - /** - * Creates a new prisoner with a name and whether they are muted or not. - * - * @param uuid The uuid of the prisoner - * @param name The name of the prisoner - * @param muted Whether the prisoner is muted or not - * @param time The amount of remaining time the prisoner has - * @param jailer The name of the person who jailed this prisoner - * @param reason The reason why this prisoner is in jail - */ - public Prisoner(String uuid, String name, boolean muted, long time, String jailer, String reason) { - this.uuid = uuid; - this.name = name; - this.muted = muted; - this.time = time; - this.jailer = jailer; - this.reason = reason; - this.offlinePending = false; - this.teleporting = false; - this.toBeTransferred = false; - this.previousPosition = null; - this.previousGameMode = GameMode.SURVIVAL; - this.inventory = ""; - this.armor = ""; - this.afk = 0; - this.changed = false; - } - - /** Returns the UUID of the prisoner. */ - public UUID getUUID() { - return UUID.fromString(this.uuid); - } - - /** Gets the name of this prisoner. */ - public String getLastKnownName() { - return this.name; - } - - /** Sets the name of this prisoner. */ - public String setLastKnownName(String username) { - this.name = username; - this.changed = true; - return this.name; - } - - /** Gets the reason this player was jailed for. */ - public String getReason() { - return this.reason; - } - - /** - * Sets the reason this player was jailed for. - * - * @param reason the player was jailed. - * @return the reason the player was jailed, what we have stored about them. - */ - public String setReason(String reason) { - this.reason = reason; - this.changed = true; - return this.reason; - } - - /** Gets the person who jailed this prisoner. */ - public String getJailer() { - return this.jailer; - } - - /** Sets the person who jailed this prisoner. */ - public void setJailer(String jailer) { - this.jailer = jailer; - this.changed = true; - } - - /** Gets whether the prisoner is muted or not. */ - public boolean isMuted() { - return this.muted; - } - - /** Sets whether the prisoner is muted or not. */ - public void setMuted(boolean muted) { - this.muted = muted; - this.changed = true; - } - - /** Gets the remaining time the prisoner has. */ - public long getRemainingTime() { - return this.time; - } - - /** Gets the remaining time the prisoner has in minutes. */ - public long getRemainingTimeInMinutes() { - return TimeUnit.MINUTES.convert(time, TimeUnit.MILLISECONDS); - } - - /** Gets the remaining time the prison has in minutes except only in int format. */ - public int getRemainingTimeInMinutesInt() { - return (int) this.getRemainingTimeInMinutes(); - } - - /** - * Sets the remaining time the prisoner has left. - * - * @param time The amount of time left, in milliseconds. - */ - public void setRemainingTime(long time) { - this.time = time; - this.changed = true; - } - - /** - * Adds the given time to the remaining time the prisoner has left. - * - * @param time to add to the prisoner's remaining time. - * @return the new remaining time the prisoner has - */ - public long addTime(long time) { - this.time += time; - this.changed = true; - return this.time; - } - - /** - * Subtracts the given time from the remaining time the prisoner has left. - * - * @param time to subtract from the prisoner's remaining time. - * @return the new remaining time the prisoner has - */ - public long subtractTime(long time) { - this.time -= time; - this.changed = true; - return this.time; - } - - /** Gets whether the player is offline or not. */ - public boolean isOfflinePending() { - return this.offlinePending; - } - - /** Sets whether the player is offline or not. */ - public void setOfflinePending(boolean offline) { - this.offlinePending = offline; - this.changed = true; - } - - /** Gets whether the player is being teleported or not. */ - public boolean isTeleporting() { - return this.teleporting; - } - - /** Sets whether the player is being teleported or not. */ - public void setTeleporting(boolean teleport) { - this.teleporting = teleport; - } - - /** Gets whether the prisoner is going to be transferred or not, mainly for teleporting on join purposes. */ - public boolean isToBeTransferred() { - return this.toBeTransferred; - } - - /** Sets whether the prisoner is going to be transferred or not, mainly for teleporting on join purposes. */ - public void setToBeTransferred(boolean transferred) { - this.toBeTransferred = transferred; - this.changed = true; - } - - /** Gets the previous location of this player, can be null. */ - public Location getPreviousLocation() { - return this.previousPosition; - } - - /** Gets the previous location of this player, separated by a comma. */ - public String getPreviousLocationString() { - if(previousPosition == null) return ""; - else if(previousPosition.getWorld() == null) return ""; - else return previousPosition.getWorld().getName() + "," + - previousPosition.getX() + "," + - previousPosition.getY() + "," + - previousPosition.getZ() + "," + - previousPosition.getYaw() + "," + - previousPosition.getPitch(); - } - - /** Sets the previous location of this player. */ - public void setPreviousPosition(Location location) { - this.previousPosition = location; - } - - /** Sets the previous location of this player from a comma separated string. */ - public void setPreviousPosition(String location) { - if(location == null) return; - if(location.isEmpty()) return; - - this.changed = true; - String[] s = location.split(","); - this.previousPosition = new Location(Bukkit.getWorld(s[0]), - Double.valueOf(s[1]), - Double.valueOf(s[2]), - Double.valueOf(s[3]), - Float.valueOf(s[4]), - Float.valueOf(s[5])); - } - - /** Gets the previous gamemode of this player. */ - public GameMode getPreviousGameMode() { - return this.previousGameMode; - } - - /** Sets the previous gamemode of this player. */ - public void setPreviousGameMode(GameMode previous) { - this.previousGameMode = previous; - this.changed = true; - } - - /** Sets the previous gamemode of this player based upon the provided string. */ - public void setPreviousGameMode(String previous) { - if(previous == null) return; - else if(previous.isEmpty()) return; - else this.previousGameMode = GameMode.valueOf(previous); - this.changed = true; - } - - /** Gets the inventory string for this player, it is encoded in Base64 string. */ - public String getInventory() { - return this.inventory; - } - - /** Sets the inventory Base64 string. */ - public void setInventory(String inventory) { - this.inventory = inventory; - this.changed = true; - } - - /** Gets the armor content, encoded in Base64 string. */ - public String getArmor() { - return this.armor; - } - - /** Sets the armor inventory Base64 string. */ - public void setArmor(String armor) { - this.armor = armor; - this.changed = true; - } - - /** Gets the time, in milliseconds, this prisoner has been afk. */ - public long getAFKTime() { - return this.afk; - } - - /** Sets the time, in milliseconds, this prisoner has been afk. */ - public void setAFKTime(long time) { - this.afk = time; - } - - /** Checks if the prisoner was changed or not. */ - public boolean wasChanged() { - return this.changed; - } - - /** Sets whether the prisoner was changed or not. */ - public boolean setChanged(boolean change) { - this.changed = change; - return this.changed; - } + private String uuid, name, jailer, reason, inventory, armor; + private boolean muted, offlinePending, teleporting, toBeTransferred, changed; + private long time, afk; + private Location previousPosition; + private GameMode previousGameMode; + + /** + * Creates a new prisoner with a name and whether they are muted or not. + * + * @param uuid The uuid of the prisoner + * @param name The name of the prisoner + * @param muted Whether the prisoner is muted or not + * @param time The amount of remaining time the prisoner has + * @param jailer The name of the person who jailed this prisoner + * @param reason The reason why this prisoner is in jail + */ + public Prisoner(String uuid, String name, boolean muted, long time, String jailer, String reason) { + this.uuid = uuid; + this.name = name; + this.muted = muted; + this.time = time; + this.jailer = jailer; + this.reason = reason; + this.offlinePending = false; + this.teleporting = false; + this.toBeTransferred = false; + this.previousPosition = null; + this.previousGameMode = GameMode.SURVIVAL; + this.inventory = ""; + this.armor = ""; + this.afk = 0; + this.changed = false; + } + + /** Returns the UUID of the prisoner. */ + public UUID getUUID() { + return UUID.fromString(this.uuid); + } + + /** Gets the name of this prisoner. */ + public String getLastKnownName() { + return this.name; + } + + /** Sets the name of this prisoner. */ + public String setLastKnownName(String username) { + this.name = username; + this.changed = true; + return this.name; + } + + /** Gets the reason this player was jailed for. */ + public String getReason() { + return this.reason; + } + + /** + * Sets the reason this player was jailed for. + * + * @param reason the player was jailed. + * @return the reason the player was jailed, what we have stored about them. + */ + public String setReason(String reason) { + this.reason = reason; + this.changed = true; + return this.reason; + } + + /** Gets the person who jailed this prisoner. */ + public String getJailer() { + return this.jailer; + } + + /** Sets the person who jailed this prisoner. */ + public void setJailer(String jailer) { + this.jailer = jailer; + this.changed = true; + } + + /** Gets whether the prisoner is muted or not. */ + public boolean isMuted() { + return this.muted; + } + + /** Sets whether the prisoner is muted or not. */ + public void setMuted(boolean muted) { + this.muted = muted; + this.changed = true; + } + + /** Gets the remaining time the prisoner has. */ + public long getRemainingTime() { + return this.time; + } + + /** Gets the remaining time the prisoner has in minutes. */ + public long getRemainingTimeInMinutes() { + return TimeUnit.MINUTES.convert(time, TimeUnit.MILLISECONDS); + } + + /** Gets the remaining time the prison has in minutes except only in int format. */ + public int getRemainingTimeInMinutesInt() { + return (int) this.getRemainingTimeInMinutes(); + } + + /** + * Sets the remaining time the prisoner has left. + * + * @param time The amount of time left, in milliseconds. + */ + public void setRemainingTime(long time) { + this.time = time; + this.changed = true; + } + + /** + * Adds the given time to the remaining time the prisoner has left. + * + * @param time to add to the prisoner's remaining time. + * @return the new remaining time the prisoner has + */ + public long addTime(long time) { + this.time += time; + this.changed = true; + return this.time; + } + + /** + * Subtracts the given time from the remaining time the prisoner has left. + * + * @param time to subtract from the prisoner's remaining time. + * @return the new remaining time the prisoner has + */ + public long subtractTime(long time) { + this.time -= time; + this.changed = true; + return this.time; + } + + /** Gets whether the player is offline or not. */ + public boolean isOfflinePending() { + return this.offlinePending; + } + + /** Sets whether the player is offline or not. */ + public void setOfflinePending(boolean offline) { + this.offlinePending = offline; + this.changed = true; + } + + /** Gets whether the player is being teleported or not. */ + public boolean isTeleporting() { + return this.teleporting; + } + + /** Sets whether the player is being teleported or not. */ + public void setTeleporting(boolean teleport) { + this.teleporting = teleport; + } + + /** Gets whether the prisoner is going to be transferred or not, mainly for teleporting on join purposes. */ + public boolean isToBeTransferred() { + return this.toBeTransferred; + } + + /** Sets whether the prisoner is going to be transferred or not, mainly for teleporting on join purposes. */ + public void setToBeTransferred(boolean transferred) { + this.toBeTransferred = transferred; + this.changed = true; + } + + /** Gets the previous location of this player, can be null. */ + public Location getPreviousLocation() { + return this.previousPosition; + } + + /** Gets the previous location of this player, separated by a comma. */ + public String getPreviousLocationString() { + if(previousPosition == null) return ""; + else if(previousPosition.getWorld() == null) return ""; + else return previousPosition.getWorld().getName() + "," + + previousPosition.getX() + "," + + previousPosition.getY() + "," + + previousPosition.getZ() + "," + + previousPosition.getYaw() + "," + + previousPosition.getPitch(); + } + + /** Sets the previous location of this player. */ + public void setPreviousPosition(Location location) { + this.previousPosition = location; + } + + /** Sets the previous location of this player from a comma separated string. */ + public void setPreviousPosition(String location) { + if(location == null) return; + if(location.isEmpty()) return; + + this.changed = true; + String[] s = location.split(","); + this.previousPosition = new Location(Bukkit.getWorld(s[0]), + Double.valueOf(s[1]), + Double.valueOf(s[2]), + Double.valueOf(s[3]), + Float.valueOf(s[4]), + Float.valueOf(s[5])); + } + + /** Gets the previous gamemode of this player. */ + public GameMode getPreviousGameMode() { + return this.previousGameMode; + } + + /** Sets the previous gamemode of this player. */ + public void setPreviousGameMode(GameMode previous) { + this.previousGameMode = previous; + this.changed = true; + } + + /** Sets the previous gamemode of this player based upon the provided string. */ + public void setPreviousGameMode(String previous) { + if(previous == null) return; + else if(previous.isEmpty()) return; + else this.previousGameMode = GameMode.valueOf(previous); + this.changed = true; + } + + /** Gets the inventory string for this player, it is encoded in Base64 string. */ + public String getInventory() { + return this.inventory; + } + + /** Sets the inventory Base64 string. */ + public void setInventory(String inventory) { + this.inventory = inventory; + this.changed = true; + } + + /** Gets the armor content, encoded in Base64 string. */ + public String getArmor() { + return this.armor; + } + + /** Sets the armor inventory Base64 string. */ + public void setArmor(String armor) { + this.armor = armor; + this.changed = true; + } + + /** Gets the time, in milliseconds, this prisoner has been afk. */ + public long getAFKTime() { + return this.afk; + } + + /** Sets the time, in milliseconds, this prisoner has been afk. */ + public void setAFKTime(long time) { + this.afk = time; + } + + /** Checks if the prisoner was changed or not. */ + public boolean wasChanged() { + return this.changed; + } + + /** Sets whether the prisoner was changed or not. */ + public boolean setChanged(boolean change) { + this.changed = change; + return this.changed; + } } diff --git a/src/main/java/com/graywolf336/jail/beans/SimpleLocation.java b/src/main/java/com/graywolf336/jail/beans/SimpleLocation.java index ec2c73c..2125989 100644 --- a/src/main/java/com/graywolf336/jail/beans/SimpleLocation.java +++ b/src/main/java/com/graywolf336/jail/beans/SimpleLocation.java @@ -12,92 +12,92 @@ import org.bukkit.World; * @version 1.1.1 */ public class SimpleLocation { - private String world; - private double x, y, z; - private float yaw, pitch; - - /** - * Creates a new SimpleLocation with each detail provided separately. - * - * @param world as a string - * @param x coordinate as a double - * @param y coordinate as a double - * @param z coordinate as a double - * @param yaw as a float - * @param pitch as a float - */ - public SimpleLocation(String world, double x, double y, double z, float yaw, float pitch) { - this.world = world; - this.x = x; - this.y = y; - this.z = z; - this.yaw = yaw; - this.pitch = pitch; - } - - /** - * Creates a new SimpleLocation with all the detail provided from {@link Location}. - * - * @param location to convert to a SimpleLocation - */ - public SimpleLocation(Location location) { - this.world = location.getWorld().getName(); - this.x = location.getX(); - this.y = location.getY(); - this.z = location.getZ(); - this.yaw = location.getYaw(); - this.pitch = location.getPitch(); - } - - /** - * Creates a new Simple Location with all the inputs being in string. - * - * @param world the name of the world - * @param x coordinate as a string - * @param y coordinate as a string - * @param z coordinate as a string - */ - public SimpleLocation(String world, String x, String y, String z) { - this.world = world; - this.x = Double.valueOf(x); - this.y = Double.valueOf(y); - this.z = Double.valueOf(z); - this.yaw = 0; - this.pitch = 0; - } - - /** - * Creates a new SimpleLocation with each detail provided separately. - * - * @param world as a string - * @param x coordinate as a double - * @param y coordinate as a double - * @param z coordinate as a double - */ - public SimpleLocation(String world, double x, double y, double z) { - this.world = world; - this.x = x; - this.y = y; - this.z = z; - } + private String world; + private double x, y, z; + private float yaw, pitch; - /** Returns the instance from Bukkit of the world this location is in. */ - public World getWorld() { - return Bukkit.getWorld(world); - } - - /** Returns the name of the world this location is in. */ - public String getWorldName() { - return this.world; - } - - /** Returns a new {@link Location} from this SimpleLocation. */ - public Location getLocation() { - return new Location(Bukkit.getWorld(world), x, y, z, yaw, pitch); - } - - @Override - public String toString() { - return world + "," + x + "," + y + "," + z + "," + yaw + "," + pitch; - } + /** + * Creates a new SimpleLocation with each detail provided separately. + * + * @param world as a string + * @param x coordinate as a double + * @param y coordinate as a double + * @param z coordinate as a double + * @param yaw as a float + * @param pitch as a float + */ + public SimpleLocation(String world, double x, double y, double z, float yaw, float pitch) { + this.world = world; + this.x = x; + this.y = y; + this.z = z; + this.yaw = yaw; + this.pitch = pitch; + } + + /** + * Creates a new SimpleLocation with all the detail provided from {@link Location}. + * + * @param location to convert to a SimpleLocation + */ + public SimpleLocation(Location location) { + this.world = location.getWorld().getName(); + this.x = location.getX(); + this.y = location.getY(); + this.z = location.getZ(); + this.yaw = location.getYaw(); + this.pitch = location.getPitch(); + } + + /** + * Creates a new Simple Location with all the inputs being in string. + * + * @param world the name of the world + * @param x coordinate as a string + * @param y coordinate as a string + * @param z coordinate as a string + */ + public SimpleLocation(String world, String x, String y, String z) { + this.world = world; + this.x = Double.valueOf(x); + this.y = Double.valueOf(y); + this.z = Double.valueOf(z); + this.yaw = 0; + this.pitch = 0; + } + + /** + * Creates a new SimpleLocation with each detail provided separately. + * + * @param world as a string + * @param x coordinate as a double + * @param y coordinate as a double + * @param z coordinate as a double + */ + public SimpleLocation(String world, double x, double y, double z) { + this.world = world; + this.x = x; + this.y = y; + this.z = z; + } + + /** Returns the instance from Bukkit of the world this location is in. */ + public World getWorld() { + return Bukkit.getWorld(world); + } + + /** Returns the name of the world this location is in. */ + public String getWorldName() { + return this.world; + } + + /** Returns a new {@link Location} from this SimpleLocation. */ + public Location getLocation() { + return new Location(Bukkit.getWorld(world), x, y, z, yaw, pitch); + } + + @Override + public String toString() { + return world + "," + x + "," + y + "," + z + "," + yaw + "," + pitch; + } } diff --git a/src/main/java/com/graywolf336/jail/beans/Stick.java b/src/main/java/com/graywolf336/jail/beans/Stick.java index d98c54f..bef2014 100644 --- a/src/main/java/com/graywolf336/jail/beans/Stick.java +++ b/src/main/java/com/graywolf336/jail/beans/Stick.java @@ -9,52 +9,52 @@ package com.graywolf336.jail.beans; * */ public class Stick { - private String jail, reason; - private long time; - private double health; - - /** - * Creates a new Jail Stick instance. - * - * @param jail the player will be jailed in. - * @param reason the player will be jailed for. - * @param time the player will be jailed for. - * @param health a player must have, at the least, before being able to be jailed with this stick, -1 disables this feature - */ - public Stick(String jail, String reason, long time, double health) { - this.jail = jail; - this.reason = reason; - this.time = time; - this.health = health; - } - - /** Gets the name of the jail a player will be sent when jailed via this jail stick. */ - public String getJail() { - return this.jail; - } - - /** Gets the reason a player will be jailed for when jailed via this stick. */ - public String getReason() { - return this.reason; - } - - /** Gets the amount of time a player has to serve when they are jailed via this stick. */ - public long getTime() { - return this.time; - } - - /** Gets the amount of health a player has to have before getting jailed via this stick. - * - *

- * - * See here for reference: http://dev.bukkit.org/bukkit-plugins/jail/tickets/415/ - */ - public double getHealth() { - return this.health; - } - - @Override - public String toString() { - return time + "," + jail + "," + reason + "," + health; - } + private String jail, reason; + private long time; + private double health; + + /** + * Creates a new Jail Stick instance. + * + * @param jail the player will be jailed in. + * @param reason the player will be jailed for. + * @param time the player will be jailed for. + * @param health a player must have, at the least, before being able to be jailed with this stick, -1 disables this feature + */ + public Stick(String jail, String reason, long time, double health) { + this.jail = jail; + this.reason = reason; + this.time = time; + this.health = health; + } + + /** Gets the name of the jail a player will be sent when jailed via this jail stick. */ + public String getJail() { + return this.jail; + } + + /** Gets the reason a player will be jailed for when jailed via this stick. */ + public String getReason() { + return this.reason; + } + + /** Gets the amount of time a player has to serve when they are jailed via this stick. */ + public long getTime() { + return this.time; + } + + /** Gets the amount of health a player has to have before getting jailed via this stick. + * + *

+ * + * See here for reference: http://dev.bukkit.org/bukkit-plugins/jail/tickets/415/ + */ + public double getHealth() { + return this.health; + } + + @Override + public String toString() { + return time + "," + jail + "," + reason + "," + health; + } } diff --git a/src/main/java/com/graywolf336/jail/command/Command.java b/src/main/java/com/graywolf336/jail/command/Command.java index 052c8d7..046fbbf 100644 --- a/src/main/java/com/graywolf336/jail/command/Command.java +++ b/src/main/java/com/graywolf336/jail/command/Command.java @@ -1,31 +1,31 @@ -package com.graywolf336.jail.command; - -import org.bukkit.command.CommandSender; - -import com.graywolf336.jail.JailManager; - -/** - * The base of all the commands. - * - * @author graywolf336 - * @since 3.0.0 - * @version 1.0.0 - */ -public interface Command { - /** - * Execute the command given the arguments, returning whether the command handled it or not. - * - *

- * - * When the method returns false, the usage message is printed to the sender. If the method - * handles the command in any way, such as sending a message to the sender or actually doing - * something, then it should return true so that the sender of the command doesn't get the - * usage message. - * - * @param jm An instance of the {@link JailManager} - * @param sender The {@link CommandSender sender} of the command - * @param args The args, in an array - * @return True if the method handled it in any way, false if we should send the usage message. - */ - public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception; -} +package com.graywolf336.jail.command; + +import org.bukkit.command.CommandSender; + +import com.graywolf336.jail.JailManager; + +/** + * The base of all the commands. + * + * @author graywolf336 + * @since 3.0.0 + * @version 1.0.0 + */ +public interface Command { + /** + * Execute the command given the arguments, returning whether the command handled it or not. + * + *

+ * + * When the method returns false, the usage message is printed to the sender. If the method + * handles the command in any way, such as sending a message to the sender or actually doing + * something, then it should return true so that the sender of the command doesn't get the + * usage message. + * + * @param jm An instance of the {@link JailManager} + * @param sender The {@link CommandSender sender} of the command + * @param args The args, in an array + * @return True if the method handled it in any way, false if we should send the usage message. + */ + public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception; +} diff --git a/src/main/java/com/graywolf336/jail/command/CommandHandler.java b/src/main/java/com/graywolf336/jail/command/CommandHandler.java index b5396ce..39098d2 100644 --- a/src/main/java/com/graywolf336/jail/command/CommandHandler.java +++ b/src/main/java/com/graywolf336/jail/command/CommandHandler.java @@ -13,8 +13,8 @@ import com.graywolf336.jail.JailManager; import com.graywolf336.jail.command.commands.HandCuffCommand; import com.graywolf336.jail.command.commands.ToggleJailDebugCommand; import com.graywolf336.jail.command.commands.UnHandCuffCommand; -import com.graywolf336.jail.command.commands.UnJailForceCommand; import com.graywolf336.jail.command.commands.UnJailCommand; +import com.graywolf336.jail.command.commands.UnJailForceCommand; import com.graywolf336.jail.enums.Lang; /** @@ -26,148 +26,148 @@ import com.graywolf336.jail.enums.Lang; * */ public class CommandHandler { - private LinkedHashMap commands; - - public CommandHandler(JailMain plugin) { - commands = new LinkedHashMap(); - loadCommands(); - - plugin.debug("Loaded " + commands.size() + " commands."); - } - - /** - * Handles the given command and checks that the command is in valid form. - * - *

- * - * It checks in the following order: - *

    - *
  1. If the command is registered or not.
  2. - *
  3. If more than one command matches the command's name and sends the usage for each one.
  4. - *
  5. If they have permission for it, if they don't then we send them a message stating so.
  6. - *
  7. If the command needs a player instance, if so we send a message stating that.
  8. - *
  9. If the required minimum arguments have been passed, if not sends the usage.
  10. - *
  11. If the required maximum arguments have been passed (if there is a max, -1 if no max), if not sends the usage.
  12. - *
  13. Then executes, upon failed execution it sends the usage command.
  14. - *
- * - * @param jailmanager The instance of {@link JailManager}. - * @param sender The sender of the command. - * @param commandLine The name of the command. - * @param args The arguments passed to the command. - */ - public void handleCommand(JailManager jailmanager, CommandSender sender, String commandLine, String[] args) { - List matches = getMatches(commandLine); - - //If no matches were found, send them the unknown command message. - if(matches.size() == 0) { - if(commandLine.startsWith("jail")) { - String j = commandLine.substring(0, 4); - String a0 = commandLine.substring(4, commandLine.length()); - - ArrayList args2 = new ArrayList(); - for(String s : args) - args2.add(s); - args2.add(a0); - - if(jailmanager.getPlugin().onCommand(sender, null, j, args2.toArray(new String[args2.size()]))) - return; - } - - sender.sendMessage(Lang.UNKNOWNCOMMAND.get(commandLine)); - return; - } - - //If more than one command was found, send them each command's help message. - if(matches.size() > 1) { - for(Command c : matches) - showUsage(sender, c); - return; - } - - Command c = matches.get(0); - CommandInfo i = c.getClass().getAnnotation(CommandInfo.class); - - // First, let's check if the sender has permission for the command. - if(!sender.hasPermission(i.permission())) { - sender.sendMessage(Lang.NOPERMISSION.get()); - return; - } - - // Next, let's check if we need a player and then if the sender is actually a player - if(i.needsPlayer() && !(sender instanceof Player)) { - sender.sendMessage(Lang.PLAYERCONTEXTREQUIRED.get()); - return; - } - - // Now, let's check the size of the arguments passed. If it is shorter than the minimum required args, let's show the usage. - if(args.length < i.minimumArgs()) { - showUsage(sender, c); - return; - } - - // Then, if the maximumArgs doesn't equal -1, we need to check if the size of the arguments passed is greater than the maximum args. - if(i.maxArgs() != -1 && i.maxArgs() < args.length) { - showUsage(sender, c); - return; - } - - // Since everything has been checked and we're all clear, let's execute it. - // But if get back false, let's show the usage message. - try { - if(!c.execute(jailmanager, sender, args)) { - showUsage(sender, c); - return; - } - } catch (Exception e) { - e.printStackTrace(); - jailmanager.getPlugin().getLogger().severe("An error occured while handling the command: " + i.usage()); - showUsage(sender, c); - } - } - - private List getMatches(String command) { - List result = new ArrayList(); - - for(Entry entry : commands.entrySet()) { - if(command.matches(entry.getKey())) { - result.add(entry.getValue()); - } - } - - return result; - } - - /** - * Shows the usage information to the sender, if they have permission. - * - * @param sender The sender of the command - * @param command The command to send usage of. - */ - private void showUsage(CommandSender sender, Command command) { - CommandInfo info = command.getClass().getAnnotation(CommandInfo.class); - if(!sender.hasPermission(info.permission())) return; - - sender.sendMessage(info.usage()); - } - - /** Loads all the commands into the hashmap. */ - private void loadCommands() { - load(HandCuffCommand.class); - load(ToggleJailDebugCommand.class); - load(UnHandCuffCommand.class); - load(UnJailCommand.class); - load(UnJailForceCommand.class); - } + private LinkedHashMap commands; - private void load(Class c) { - CommandInfo info = c.getAnnotation(CommandInfo.class); - if(info == null) return; - - try { - commands.put(info.pattern(), c.newInstance()); - }catch(Exception e) { - e.printStackTrace(); - } - } + public CommandHandler(JailMain plugin) { + commands = new LinkedHashMap(); + loadCommands(); + + plugin.debug("Loaded " + commands.size() + " commands."); + } + + /** + * Handles the given command and checks that the command is in valid form. + * + *

+ * + * It checks in the following order: + *

    + *
  1. If the command is registered or not.
  2. + *
  3. If more than one command matches the command's name and sends the usage for each one.
  4. + *
  5. If they have permission for it, if they don't then we send them a message stating so.
  6. + *
  7. If the command needs a player instance, if so we send a message stating that.
  8. + *
  9. If the required minimum arguments have been passed, if not sends the usage.
  10. + *
  11. If the required maximum arguments have been passed (if there is a max, -1 if no max), if not sends the usage.
  12. + *
  13. Then executes, upon failed execution it sends the usage command.
  14. + *
+ * + * @param jailmanager The instance of {@link JailManager}. + * @param sender The sender of the command. + * @param commandLine The name of the command. + * @param args The arguments passed to the command. + */ + public void handleCommand(JailManager jailmanager, CommandSender sender, String commandLine, String[] args) { + List matches = getMatches(commandLine); + + //If no matches were found, send them the unknown command message. + if(matches.size() == 0) { + if(commandLine.startsWith("jail")) { + String j = commandLine.substring(0, 4); + String a0 = commandLine.substring(4, commandLine.length()); + + ArrayList args2 = new ArrayList(); + for(String s : args) + args2.add(s); + args2.add(a0); + + if(jailmanager.getPlugin().onCommand(sender, null, j, args2.toArray(new String[args2.size()]))) + return; + } + + sender.sendMessage(Lang.UNKNOWNCOMMAND.get(commandLine)); + return; + } + + //If more than one command was found, send them each command's help message. + if(matches.size() > 1) { + for(Command c : matches) + showUsage(sender, c); + return; + } + + Command c = matches.get(0); + CommandInfo i = c.getClass().getAnnotation(CommandInfo.class); + + // First, let's check if the sender has permission for the command. + if(!sender.hasPermission(i.permission())) { + sender.sendMessage(Lang.NOPERMISSION.get()); + return; + } + + // Next, let's check if we need a player and then if the sender is actually a player + if(i.needsPlayer() && !(sender instanceof Player)) { + sender.sendMessage(Lang.PLAYERCONTEXTREQUIRED.get()); + return; + } + + // Now, let's check the size of the arguments passed. If it is shorter than the minimum required args, let's show the usage. + if(args.length < i.minimumArgs()) { + showUsage(sender, c); + return; + } + + // Then, if the maximumArgs doesn't equal -1, we need to check if the size of the arguments passed is greater than the maximum args. + if(i.maxArgs() != -1 && i.maxArgs() < args.length) { + showUsage(sender, c); + return; + } + + // Since everything has been checked and we're all clear, let's execute it. + // But if get back false, let's show the usage message. + try { + if(!c.execute(jailmanager, sender, args)) { + showUsage(sender, c); + return; + } + } catch (Exception e) { + e.printStackTrace(); + jailmanager.getPlugin().getLogger().severe("An error occured while handling the command: " + i.usage()); + showUsage(sender, c); + } + } + + private List getMatches(String command) { + List result = new ArrayList(); + + for(Entry entry : commands.entrySet()) { + if(command.matches(entry.getKey())) { + result.add(entry.getValue()); + } + } + + return result; + } + + /** + * Shows the usage information to the sender, if they have permission. + * + * @param sender The sender of the command + * @param command The command to send usage of. + */ + private void showUsage(CommandSender sender, Command command) { + CommandInfo info = command.getClass().getAnnotation(CommandInfo.class); + if(!sender.hasPermission(info.permission())) return; + + sender.sendMessage(info.usage()); + } + + /** Loads all the commands into the hashmap. */ + private void loadCommands() { + load(HandCuffCommand.class); + load(ToggleJailDebugCommand.class); + load(UnHandCuffCommand.class); + load(UnJailCommand.class); + load(UnJailForceCommand.class); + } + + private void load(Class c) { + CommandInfo info = c.getAnnotation(CommandInfo.class); + if(info == null) return; + + try { + commands.put(info.pattern(), c.newInstance()); + }catch(Exception e) { + e.printStackTrace(); + } + } } diff --git a/src/main/java/com/graywolf336/jail/command/CommandInfo.java b/src/main/java/com/graywolf336/jail/command/CommandInfo.java index efd11ba..c8ddefd 100644 --- a/src/main/java/com/graywolf336/jail/command/CommandInfo.java +++ b/src/main/java/com/graywolf336/jail/command/CommandInfo.java @@ -23,53 +23,53 @@ import java.lang.annotation.RetentionPolicy; * for that command. Finally we have the usage string, which is sent * when the sender of the command sends an incorrectly formatted * command. The order of checking is as defined in {@link CommandHandler#handleCommand(com.graywolf336.jail.JailManager, org.bukkit.command.CommandSender, String, String[]) CommandHandler.handleCommand}. - * + * * @author graywolf336 * @since 3.0.0 * @version 1.0.0 * */ @Retention (RetentionPolicy.RUNTIME) -public @interface CommandInfo { - /** - * Gets the maximum amount of arguments required, -1 if no maximum (ex: Jailing someone with a reason or editing a reason). - * - * @return The maximum number of arguments required, -1 if no maximum. - */ - public int maxArgs(); - - /** - * Gets the minimum amount of arguments required. - * - * @return The minimum number of arguments required. - */ - public int minimumArgs(); - - /** - * Whether the command needs a player context or not. - * - * @return True if requires a player, false if not. - */ - public boolean needsPlayer(); - - /** - * A regex pattern that allows for alternatives to the command (ex: /jail or /j, /jailstatus or /js). - * - * @return The regex pattern to match. - */ - public String pattern(); - - /** - * Gets the permission required to execute this command. - * - * @return The permission required. - */ - public String permission(); - - /** - * Gets the usage message for this command. - * - * @return The usage message. - */ - public String usage(); +public @interface CommandInfo { + /** + * Gets the maximum amount of arguments required, -1 if no maximum (ex: Jailing someone with a reason or editing a reason). + * + * @return The maximum number of arguments required, -1 if no maximum. + */ + public int maxArgs(); + + /** + * Gets the minimum amount of arguments required. + * + * @return The minimum number of arguments required. + */ + public int minimumArgs(); + + /** + * Whether the command needs a player context or not. + * + * @return True if requires a player, false if not. + */ + public boolean needsPlayer(); + + /** + * A regex pattern that allows for alternatives to the command (ex: /jail or /j, /jailstatus or /js). + * + * @return The regex pattern to match. + */ + public String pattern(); + + /** + * Gets the permission required to execute this command. + * + * @return The permission required. + */ + public String permission(); + + /** + * Gets the usage message for this command. + * + * @return The usage message. + */ + public String usage(); } diff --git a/src/main/java/com/graywolf336/jail/command/JailHandler.java b/src/main/java/com/graywolf336/jail/command/JailHandler.java index cf59ca3..d4276a8 100644 --- a/src/main/java/com/graywolf336/jail/command/JailHandler.java +++ b/src/main/java/com/graywolf336/jail/command/JailHandler.java @@ -10,11 +10,11 @@ import org.bukkit.entity.Player; import com.graywolf336.jail.JailMain; import com.graywolf336.jail.JailManager; -import com.graywolf336.jail.command.subcommands.JailCreateCellCommand; import com.graywolf336.jail.command.subcommands.JailCheckCommand; import com.graywolf336.jail.command.subcommands.JailClearCommand; import com.graywolf336.jail.command.subcommands.JailCommand; import com.graywolf336.jail.command.subcommands.JailConfirmCommand; +import com.graywolf336.jail.command.subcommands.JailCreateCellCommand; import com.graywolf336.jail.command.subcommands.JailCreateCommand; import com.graywolf336.jail.command.subcommands.JailDeleteCellCommand; import com.graywolf336.jail.command.subcommands.JailDeleteCellsCommand; @@ -37,176 +37,176 @@ import com.graywolf336.jail.command.subcommands.JailVersionCommand; import com.graywolf336.jail.enums.Lang; public class JailHandler { - private LinkedHashMap commands; - - public JailHandler(JailMain plugin) { - commands = new LinkedHashMap(); - loadCommands(); - - plugin.debug("Loaded " + commands.size() + " sub-commands of /jail."); - } - - /** - * Handles the given command and checks that the command is in valid form. - * - *

- * - * It checks in the following order: - *

    - *
  1. If they have permission for it, if they don't then we send them a message stating so.
  2. - *
  3. If the command needs a player instance, if so we send a message stating that.
  4. - *
  5. If the required minimum arguments have been passed, if not sends the usage.
  6. - *
  7. If the required maximum arguments have been passed (if there is a max, -1 if no max), if not sends the usage.
  8. - *
  9. Then executes, upon failed execution it sends the usage command.
  10. - *
- * - * @param jailmanager The instance of {@link JailManager}. - * @param sender The sender of the command. - * @param args The arguments passed to the command. - */ - public boolean parseCommand(JailManager jailmanager, CommandSender sender, String[] args) { - Command c = null; - - //If they didn't provide any arguments (aka just: /jail) then we will need to send them some help - if(args.length == 0) { - //TODO: Create the help page(s) - c = getMatches("jail").get(0); - - }else { - //Get the matches from the first argument passed - List matches = getMatches(args[0]); - - if(matches.size() == 0) { - //No matches found, thus it is more likely than not they are trying to jail someone - c = getMatches("jail").get(0); - - } else if(matches.size() > 1) { - //If there was found more than one match - //then let's send the usage of each match to the sender - for(Command cmd : matches) - showUsage(sender, cmd); - return true; - - }else { - //Only one match was found, so let's continue - c = matches.get(0); - } - } - - CommandInfo i = c.getClass().getAnnotation(CommandInfo.class); - - // First, let's check if the sender has permission for the command. - if(!i.permission().isEmpty()) { - if(!sender.hasPermission(i.permission())) { - jailmanager.getPlugin().debug("Sender has no permission."); - sender.sendMessage(Lang.NOPERMISSION.get()); - return true; - } - } - - // Next, let's check if we need a player and then if the sender is actually a player - if(i.needsPlayer() && !(sender instanceof Player)) { - jailmanager.getPlugin().debug("Sender is not a player."); - sender.sendMessage(Lang.PLAYERCONTEXTREQUIRED.get()); - return true; - } - - // Now, let's check the size of the arguments passed. If it is shorter than the minimum required args, let's show the usage. - // The reason we are subtracting one is because the command is now `/jail ` and the subcommand is viewed as an argument - if(args.length - 1 < i.minimumArgs()) { - jailmanager.getPlugin().debug("Sender didn't provide enough arguments."); - showUsage(sender, c); - return true; - } - - // Then, if the maximumArgs doesn't equal -1, we need to check if the size of the arguments passed is greater than the maximum args. - // The reason we are subtracting one is because the command is now `/jail ` and the subcommand is viewed as an argument - if(i.maxArgs() != -1 && i.maxArgs() < args.length - 1) { - jailmanager.getPlugin().debug("Sender provided too many arguments."); - showUsage(sender, c); - return true; - } - - // Since everything has been checked and we're all clear, let's execute it. - // But if get back false, let's show the usage message. - try { - if(!c.execute(jailmanager, sender, args)) { - showUsage(sender, c); - return true; - }else { - return true; - } - } catch (Exception e) { - if(jailmanager.getPlugin().inDebug()) { - e.printStackTrace(); - } - - jailmanager.getPlugin().getLogger().severe("An error occured while handling the command: " + i.usage()); - showUsage(sender, c); - return true; - } - } - - private List getMatches(String command) { - List result = new ArrayList(); - - for(Entry entry : commands.entrySet()) { - if(command.matches(entry.getKey())) { - result.add(entry.getValue()); - } - } - - return result; - } - - /** - * Shows the usage information to the sender, if they have permission. - * - * @param sender The sender of the command - * @param command The command to send usage of. - */ - private void showUsage(CommandSender sender, Command command) { - CommandInfo info = command.getClass().getAnnotation(CommandInfo.class); - if(!sender.hasPermission(info.permission())) return; - - sender.sendMessage(info.usage()); - } - - private void loadCommands() { - load(JailCreateCellCommand.class); - load(JailCheckCommand.class); - load(JailClearCommand.class); - load(JailCommand.class); - load(JailConfirmCommand.class); - load(JailCreateCommand.class); - load(JailDeleteCellCommand.class); - load(JailDeleteCellsCommand.class); - load(JailDeleteCommand.class); - load(JailListCellsCommand.class); - load(JailListCommand.class); - load(JailMuteCommand.class); - load(JailPayCommand.class); - load(JailRecordCommand.class); - load(JailReloadCommand.class); - load(JailStatusCommand.class); - load(JailStickCommand.class); - load(JailStopCommand.class); - load(JailTeleInCommand.class); - load(JailTeleOutCommand.class); - load(JailTimeCommand.class); - load(JailTransferAllCommand.class); - load(JailTransferCommand.class); - load(JailVersionCommand.class); - } - - private void load(Class c) { - CommandInfo info = c.getAnnotation(CommandInfo.class); - if(info == null) return; - - try { - commands.put(info.pattern(), c.newInstance()); - }catch(Exception e) { - e.printStackTrace(); - } - } + private LinkedHashMap commands; + + public JailHandler(JailMain plugin) { + commands = new LinkedHashMap(); + loadCommands(); + + plugin.debug("Loaded " + commands.size() + " sub-commands of /jail."); + } + + /** + * Handles the given command and checks that the command is in valid form. + * + *

+ * + * It checks in the following order: + *

    + *
  1. If they have permission for it, if they don't then we send them a message stating so.
  2. + *
  3. If the command needs a player instance, if so we send a message stating that.
  4. + *
  5. If the required minimum arguments have been passed, if not sends the usage.
  6. + *
  7. If the required maximum arguments have been passed (if there is a max, -1 if no max), if not sends the usage.
  8. + *
  9. Then executes, upon failed execution it sends the usage command.
  10. + *
+ * + * @param jailmanager The instance of {@link JailManager}. + * @param sender The sender of the command. + * @param args The arguments passed to the command. + */ + public boolean parseCommand(JailManager jailmanager, CommandSender sender, String[] args) { + Command c = null; + + //If they didn't provide any arguments (aka just: /jail) then we will need to send them some help + if(args.length == 0) { + //TODO: Create the help page(s) + c = getMatches("jail").get(0); + + }else { + //Get the matches from the first argument passed + List matches = getMatches(args[0]); + + if(matches.size() == 0) { + //No matches found, thus it is more likely than not they are trying to jail someone + c = getMatches("jail").get(0); + + } else if(matches.size() > 1) { + //If there was found more than one match + //then let's send the usage of each match to the sender + for(Command cmd : matches) + showUsage(sender, cmd); + return true; + + }else { + //Only one match was found, so let's continue + c = matches.get(0); + } + } + + CommandInfo i = c.getClass().getAnnotation(CommandInfo.class); + + // First, let's check if the sender has permission for the command. + if(!i.permission().isEmpty()) { + if(!sender.hasPermission(i.permission())) { + jailmanager.getPlugin().debug("Sender has no permission."); + sender.sendMessage(Lang.NOPERMISSION.get()); + return true; + } + } + + // Next, let's check if we need a player and then if the sender is actually a player + if(i.needsPlayer() && !(sender instanceof Player)) { + jailmanager.getPlugin().debug("Sender is not a player."); + sender.sendMessage(Lang.PLAYERCONTEXTREQUIRED.get()); + return true; + } + + // Now, let's check the size of the arguments passed. If it is shorter than the minimum required args, let's show the usage. + // The reason we are subtracting one is because the command is now `/jail ` and the subcommand is viewed as an argument + if(args.length - 1 < i.minimumArgs()) { + jailmanager.getPlugin().debug("Sender didn't provide enough arguments."); + showUsage(sender, c); + return true; + } + + // Then, if the maximumArgs doesn't equal -1, we need to check if the size of the arguments passed is greater than the maximum args. + // The reason we are subtracting one is because the command is now `/jail ` and the subcommand is viewed as an argument + if(i.maxArgs() != -1 && i.maxArgs() < args.length - 1) { + jailmanager.getPlugin().debug("Sender provided too many arguments."); + showUsage(sender, c); + return true; + } + + // Since everything has been checked and we're all clear, let's execute it. + // But if get back false, let's show the usage message. + try { + if(!c.execute(jailmanager, sender, args)) { + showUsage(sender, c); + return true; + }else { + return true; + } + } catch (Exception e) { + if(jailmanager.getPlugin().inDebug()) { + e.printStackTrace(); + } + + jailmanager.getPlugin().getLogger().severe("An error occured while handling the command: " + i.usage()); + showUsage(sender, c); + return true; + } + } + + private List getMatches(String command) { + List result = new ArrayList(); + + for(Entry entry : commands.entrySet()) { + if(command.matches(entry.getKey())) { + result.add(entry.getValue()); + } + } + + return result; + } + + /** + * Shows the usage information to the sender, if they have permission. + * + * @param sender The sender of the command + * @param command The command to send usage of. + */ + private void showUsage(CommandSender sender, Command command) { + CommandInfo info = command.getClass().getAnnotation(CommandInfo.class); + if(!sender.hasPermission(info.permission())) return; + + sender.sendMessage(info.usage()); + } + + private void loadCommands() { + load(JailCreateCellCommand.class); + load(JailCheckCommand.class); + load(JailClearCommand.class); + load(JailCommand.class); + load(JailConfirmCommand.class); + load(JailCreateCommand.class); + load(JailDeleteCellCommand.class); + load(JailDeleteCellsCommand.class); + load(JailDeleteCommand.class); + load(JailListCellsCommand.class); + load(JailListCommand.class); + load(JailMuteCommand.class); + load(JailPayCommand.class); + load(JailRecordCommand.class); + load(JailReloadCommand.class); + load(JailStatusCommand.class); + load(JailStickCommand.class); + load(JailStopCommand.class); + load(JailTeleInCommand.class); + load(JailTeleOutCommand.class); + load(JailTimeCommand.class); + load(JailTransferAllCommand.class); + load(JailTransferCommand.class); + load(JailVersionCommand.class); + } + + private void load(Class c) { + CommandInfo info = c.getAnnotation(CommandInfo.class); + if(info == null) return; + + try { + commands.put(info.pattern(), c.newInstance()); + }catch(Exception e) { + e.printStackTrace(); + } + } } diff --git a/src/main/java/com/graywolf336/jail/command/commands/HandCuffCommand.java b/src/main/java/com/graywolf336/jail/command/commands/HandCuffCommand.java index 05450e4..8f5665e 100644 --- a/src/main/java/com/graywolf336/jail/command/commands/HandCuffCommand.java +++ b/src/main/java/com/graywolf336/jail/command/commands/HandCuffCommand.java @@ -9,33 +9,33 @@ import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Lang; @CommandInfo( - maxArgs = 1, - minimumArgs = 1, - needsPlayer = false, - pattern = "handcuff|hc", - permission = "jail.command.handcuff", - usage = "/handcuff [player]" - ) + maxArgs = 1, + minimumArgs = 1, + needsPlayer = false, + pattern = "handcuff|hc", + permission = "jail.command.handcuff", + usage = "/handcuff [player]" + ) public class HandCuffCommand implements Command { - public boolean execute(JailManager jm, CommandSender sender, String... args) { - Player player = jm.getPlugin().getServer().getPlayer(args[0]); - - if(player == null) { - sender.sendMessage(Lang.PLAYERNOTONLINE.get()); - }else if(player.hasPermission("jail.cantbehandcuffed")) { - sender.sendMessage(Lang.CANTBEHANDCUFFED.get(player.getName())); - }else if(jm.isPlayerJailed(player.getUniqueId())) { - sender.sendMessage(Lang.CURRENTLYJAILEDHANDCUFF.get(player.getName())); - }else if(jm.getPlugin().getHandCuffManager().isHandCuffed(player.getUniqueId())) { - sender.sendMessage(Lang.HANDCUFFSRELEASED.get(player.getName())); - jm.getPlugin().getHandCuffManager().removeHandCuffs(player.getUniqueId()); - player.sendMessage(Lang.UNHANDCUFFED.get()); - }else { - jm.getPlugin().getHandCuffManager().addHandCuffs(player.getUniqueId(), player.getLocation()); - sender.sendMessage(Lang.HANDCUFFSON.get(player.getName())); - player.sendMessage(Lang.HANDCUFFED.get()); - } - - return true; - } + public boolean execute(JailManager jm, CommandSender sender, String... args) { + Player player = jm.getPlugin().getServer().getPlayer(args[0]); + + if(player == null) { + sender.sendMessage(Lang.PLAYERNOTONLINE.get()); + }else if(player.hasPermission("jail.cantbehandcuffed")) { + sender.sendMessage(Lang.CANTBEHANDCUFFED.get(player.getName())); + }else if(jm.isPlayerJailed(player.getUniqueId())) { + sender.sendMessage(Lang.CURRENTLYJAILEDHANDCUFF.get(player.getName())); + }else if(jm.getPlugin().getHandCuffManager().isHandCuffed(player.getUniqueId())) { + sender.sendMessage(Lang.HANDCUFFSRELEASED.get(player.getName())); + jm.getPlugin().getHandCuffManager().removeHandCuffs(player.getUniqueId()); + player.sendMessage(Lang.UNHANDCUFFED.get()); + }else { + jm.getPlugin().getHandCuffManager().addHandCuffs(player.getUniqueId(), player.getLocation()); + sender.sendMessage(Lang.HANDCUFFSON.get(player.getName())); + player.sendMessage(Lang.HANDCUFFED.get()); + } + + return true; + } } diff --git a/src/main/java/com/graywolf336/jail/command/commands/ToggleJailDebugCommand.java b/src/main/java/com/graywolf336/jail/command/commands/ToggleJailDebugCommand.java index a0b6a35..65a77db 100644 --- a/src/main/java/com/graywolf336/jail/command/commands/ToggleJailDebugCommand.java +++ b/src/main/java/com/graywolf336/jail/command/commands/ToggleJailDebugCommand.java @@ -8,17 +8,17 @@ import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.CommandInfo; @CommandInfo( - maxArgs = 0, - minimumArgs = 0, - needsPlayer = false, - pattern = "togglejaildebug|tjd", - permission = "jail.command.toggledebug", - usage = "/togglejaildebug" - ) + maxArgs = 0, + minimumArgs = 0, + needsPlayer = false, + pattern = "togglejaildebug|tjd", + permission = "jail.command.toggledebug", + usage = "/togglejaildebug" + ) public class ToggleJailDebugCommand implements Command { - public boolean execute(JailManager jm, CommandSender sender, String... args) { - boolean debug = jm.getPlugin().setDebugging(!jm.getPlugin().inDebug()); - sender.sendMessage("Jail debugging is now: " + (debug ? ChatColor.GREEN + "enabled" : ChatColor.RED + "disabled")); - return true; - } + public boolean execute(JailManager jm, CommandSender sender, String... args) { + boolean debug = jm.getPlugin().setDebugging(!jm.getPlugin().inDebug()); + sender.sendMessage("Jail debugging is now: " + (debug ? ChatColor.GREEN + "enabled" : ChatColor.RED + "disabled")); + return true; + } } diff --git a/src/main/java/com/graywolf336/jail/command/commands/UnHandCuffCommand.java b/src/main/java/com/graywolf336/jail/command/commands/UnHandCuffCommand.java index d791b6b..88e1c59 100644 --- a/src/main/java/com/graywolf336/jail/command/commands/UnHandCuffCommand.java +++ b/src/main/java/com/graywolf336/jail/command/commands/UnHandCuffCommand.java @@ -9,27 +9,27 @@ import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Lang; @CommandInfo( - maxArgs = 1, - minimumArgs = 1, - needsPlayer = false, - pattern = "unhandcuff|uhc", - permission = "jail.command.handcuff", - usage = "/unhandcuff [player]" - ) + maxArgs = 1, + minimumArgs = 1, + needsPlayer = false, + pattern = "unhandcuff|uhc", + permission = "jail.command.handcuff", + usage = "/unhandcuff [player]" + ) public class UnHandCuffCommand implements Command { - public boolean execute(JailManager jm, CommandSender sender, String... args) { - Player player = jm.getPlugin().getServer().getPlayerExact(args[0]); - - if(player == null) { - sender.sendMessage(Lang.PLAYERNOTONLINE.get()); - }else if(jm.getPlugin().getHandCuffManager().isHandCuffed(player.getUniqueId())) { - sender.sendMessage(Lang.HANDCUFFSRELEASED.get(player.getName())); - jm.getPlugin().getHandCuffManager().removeHandCuffs(player.getUniqueId()); - player.sendMessage(Lang.UNHANDCUFFED.get()); - }else { - sender.sendMessage(Lang.NOTHANDCUFFED.get(player.getName())); - } - - return true; - } + public boolean execute(JailManager jm, CommandSender sender, String... args) { + Player player = jm.getPlugin().getServer().getPlayerExact(args[0]); + + if(player == null) { + sender.sendMessage(Lang.PLAYERNOTONLINE.get()); + }else if(jm.getPlugin().getHandCuffManager().isHandCuffed(player.getUniqueId())) { + sender.sendMessage(Lang.HANDCUFFSRELEASED.get(player.getName())); + jm.getPlugin().getHandCuffManager().removeHandCuffs(player.getUniqueId()); + player.sendMessage(Lang.UNHANDCUFFED.get()); + }else { + sender.sendMessage(Lang.NOTHANDCUFFED.get(player.getName())); + } + + return true; + } } diff --git a/src/main/java/com/graywolf336/jail/command/commands/UnJailCommand.java b/src/main/java/com/graywolf336/jail/command/commands/UnJailCommand.java index 58bf464..70129b2 100644 --- a/src/main/java/com/graywolf336/jail/command/commands/UnJailCommand.java +++ b/src/main/java/com/graywolf336/jail/command/commands/UnJailCommand.java @@ -13,51 +13,51 @@ import com.graywolf336.jail.enums.Lang; import com.graywolf336.jail.enums.Settings; @CommandInfo( - maxArgs = 1, - minimumArgs = 1, - needsPlayer = false, - pattern = "unjail|uj", - permission = "jail.command.unjail", - usage = "/unjail [player]" - ) + maxArgs = 1, + minimumArgs = 1, + needsPlayer = false, + pattern = "unjail|uj", + permission = "jail.command.unjail", + usage = "/unjail [player]" + ) public class UnJailCommand implements Command { - - public boolean execute(JailManager jm, CommandSender sender, String... args) { - //Check if the player is jailed - if(jm.isPlayerJailedByLastKnownUsername(args[0])) { - Jail j = jm.getJailPlayerIsInByLastKnownName(args[0]); - Prisoner pris = j.getPrisonerByLastKnownName(args[0]); - Player p = jm.getPlugin().getServer().getPlayer(pris.getUUID()); - - //Check if the player is on the server or not - if(p == null) { - //Check if the player has offline pending and their remaining time is above 0, if so then - //forceably unjail them - if(pris.isOfflinePending() && pris.getRemainingTime() != 0L) { - jm.getPlugin().getPrisonerManager().forceUnJail(j, j.getCellPrisonerIsIn(pris.getUUID()), p, pris, sender); - }else { - //The player is not, so we'll set the remaining time to zero and do it when they login next - pris.setRemainingTime(0L); - pris.setOfflinePending(true); - sender.sendMessage(Lang.WILLBEUNJAILED.get(args[0])); - } - }else { - //Player is online, so let's try unjailing them - try { - jm.getPlugin().getPrisonerManager().unJail(j, j.getCellPrisonerIsIn(pris.getUUID()), p, pris, sender); - } catch (Exception e) { - sender.sendMessage(ChatColor.RED + e.getMessage()); - } - } - - if(jm.getPlugin().getConfig().getBoolean(Settings.LOGJAILINGTOCONSOLE.getPath())) { - jm.getPlugin().getLogger().info(ChatColor.stripColor(Lang.BROADCASTUNJAILING.get(new String[] { args[0], sender.getName() }))); - } - }else { - //The player is not currently jailed - sender.sendMessage(Lang.NOTJAILED.get(args[0])); - } - - return true; - } + + public boolean execute(JailManager jm, CommandSender sender, String... args) { + //Check if the player is jailed + if(jm.isPlayerJailedByLastKnownUsername(args[0])) { + Jail j = jm.getJailPlayerIsInByLastKnownName(args[0]); + Prisoner pris = j.getPrisonerByLastKnownName(args[0]); + Player p = jm.getPlugin().getServer().getPlayer(pris.getUUID()); + + //Check if the player is on the server or not + if(p == null) { + //Check if the player has offline pending and their remaining time is above 0, if so then + //forceably unjail them + if(pris.isOfflinePending() && pris.getRemainingTime() != 0L) { + jm.getPlugin().getPrisonerManager().forceUnJail(j, j.getCellPrisonerIsIn(pris.getUUID()), p, pris, sender); + }else { + //The player is not, so we'll set the remaining time to zero and do it when they login next + pris.setRemainingTime(0L); + pris.setOfflinePending(true); + sender.sendMessage(Lang.WILLBEUNJAILED.get(args[0])); + } + }else { + //Player is online, so let's try unjailing them + try { + jm.getPlugin().getPrisonerManager().unJail(j, j.getCellPrisonerIsIn(pris.getUUID()), p, pris, sender); + } catch (Exception e) { + sender.sendMessage(ChatColor.RED + e.getMessage()); + } + } + + if(jm.getPlugin().getConfig().getBoolean(Settings.LOGJAILINGTOCONSOLE.getPath())) { + jm.getPlugin().getLogger().info(ChatColor.stripColor(Lang.BROADCASTUNJAILING.get(new String[] { args[0], sender.getName() }))); + } + }else { + //The player is not currently jailed + sender.sendMessage(Lang.NOTJAILED.get(args[0])); + } + + return true; + } } diff --git a/src/main/java/com/graywolf336/jail/command/commands/UnJailForceCommand.java b/src/main/java/com/graywolf336/jail/command/commands/UnJailForceCommand.java index 066915c..d280deb 100644 --- a/src/main/java/com/graywolf336/jail/command/commands/UnJailForceCommand.java +++ b/src/main/java/com/graywolf336/jail/command/commands/UnJailForceCommand.java @@ -10,28 +10,28 @@ import com.graywolf336.jail.enums.Lang; import com.graywolf336.jail.enums.Settings; @CommandInfo( - maxArgs = 1, - minimumArgs = 1, - needsPlayer = false, - pattern = "unjailforce|ujf", - permission = "jail.command.unjailforce", - usage = "/unjailforce [player]" - ) + maxArgs = 1, + minimumArgs = 1, + needsPlayer = false, + pattern = "unjailforce|ujf", + permission = "jail.command.unjailforce", + usage = "/unjailforce [player]" + ) public class UnJailForceCommand implements Command { - - public boolean execute(JailManager jm, CommandSender sender, String... args) { - //Check if the player is jailed - if(jm.isPlayerJailedByLastKnownUsername(args[0])) { - jm.getPlugin().getPrisonerManager().forceRelease(jm.getPrisonerByLastKnownName(args[0]), sender); - - if(jm.getPlugin().getConfig().getBoolean(Settings.LOGJAILINGTOCONSOLE.getPath())) { - jm.getPlugin().getLogger().info(ChatColor.stripColor(Lang.BROADCASTUNJAILING.get(new String[] { args[0], sender.getName() }))); - } - }else { - //The player is not currently jailed - sender.sendMessage(Lang.NOTJAILED.get(args[0])); - } - - return true; - } + + public boolean execute(JailManager jm, CommandSender sender, String... args) { + //Check if the player is jailed + if(jm.isPlayerJailedByLastKnownUsername(args[0])) { + jm.getPlugin().getPrisonerManager().forceRelease(jm.getPrisonerByLastKnownName(args[0]), sender); + + if(jm.getPlugin().getConfig().getBoolean(Settings.LOGJAILINGTOCONSOLE.getPath())) { + jm.getPlugin().getLogger().info(ChatColor.stripColor(Lang.BROADCASTUNJAILING.get(new String[] { args[0], sender.getName() }))); + } + }else { + //The player is not currently jailed + sender.sendMessage(Lang.NOTJAILED.get(args[0])); + } + + return true; + } } diff --git a/src/main/java/com/graywolf336/jail/command/commands/jewels/Jailing.java b/src/main/java/com/graywolf336/jail/command/commands/jewels/Jailing.java index c2cde86..e2afc8f 100644 --- a/src/main/java/com/graywolf336/jail/command/commands/jewels/Jailing.java +++ b/src/main/java/com/graywolf336/jail/command/commands/jewels/Jailing.java @@ -5,32 +5,32 @@ import java.util.List; import com.lexicalscope.jewel.cli.Option; public interface Jailing { - - @Option(longName={"player", "pl"}, shortName="p", description = "the player's name") - public String getPlayer(); - - @Option(longName={"time", "length"}, shortName="t", description = "the amount of time") - public String getTime(); - - @Option(longName={"jail", "prison"}, shortName="j", description = "the jail") - public String getJail(); - - @Option(longName={"cell"}, shortName="c", description = "the cell") - public String getCell(); - - @Option(longName={"anycell"}, shortName="a", description = "decides whether the plugin will pick any open cell") - public boolean getAnyCell(); - - @Option(longName={"muted", "canttalk"}, shortName="m", description = "whether the prisoner is muted or not") - public boolean getMuted(); - - @Option(longName={"reason"}, shortName="r", description = "the reason this player is being jailed") - public List getReason(); - - public boolean isTime(); - public boolean isJail(); - public boolean isCell(); - public boolean isAnyCell(); - public boolean isMuted(); - public boolean isReason(); + + @Option(longName={"player", "pl"}, shortName="p", description = "the player's name") + public String getPlayer(); + + @Option(longName={"time", "length"}, shortName="t", description = "the amount of time") + public String getTime(); + + @Option(longName={"jail", "prison"}, shortName="j", description = "the jail") + public String getJail(); + + @Option(longName={"cell"}, shortName="c", description = "the cell") + public String getCell(); + + @Option(longName={"anycell"}, shortName="a", description = "decides whether the plugin will pick any open cell") + public boolean getAnyCell(); + + @Option(longName={"muted", "canttalk"}, shortName="m", description = "whether the prisoner is muted or not") + public boolean getMuted(); + + @Option(longName={"reason"}, shortName="r", description = "the reason this player is being jailed") + public List getReason(); + + public boolean isTime(); + public boolean isJail(); + public boolean isCell(); + public boolean isAnyCell(); + public boolean isMuted(); + public boolean isReason(); } diff --git a/src/main/java/com/graywolf336/jail/command/commands/jewels/Transfer.java b/src/main/java/com/graywolf336/jail/command/commands/jewels/Transfer.java index 4f5b397..739e267 100644 --- a/src/main/java/com/graywolf336/jail/command/commands/jewels/Transfer.java +++ b/src/main/java/com/graywolf336/jail/command/commands/jewels/Transfer.java @@ -3,17 +3,17 @@ package com.graywolf336.jail.command.commands.jewels; import com.lexicalscope.jewel.cli.Option; public interface Transfer { - - @Option(longName={"player", "pl"}, shortName="p", description = "the player's name") - public String getPlayer(); - - @Option(longName={"jail", "prison"}, shortName="j", description = "the jail") - public String getJail(); - - @Option(longName={"cell"}, shortName="c", description = "the cell") - public String getCell(); - - public boolean isPlayer(); - public boolean isJail(); - public boolean isCell(); + + @Option(longName={"player", "pl"}, shortName="p", description = "the player's name") + public String getPlayer(); + + @Option(longName={"jail", "prison"}, shortName="j", description = "the jail") + public String getJail(); + + @Option(longName={"cell"}, shortName="c", description = "the cell") + public String getCell(); + + public boolean isPlayer(); + public boolean isJail(); + public boolean isCell(); } diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailCheckCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailCheckCommand.java index 49f350b..271f26b 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailCheckCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailCheckCommand.java @@ -10,29 +10,29 @@ import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Lang; @CommandInfo( - maxArgs = 1, - minimumArgs = 1, - needsPlayer = false, - pattern = "check", - permission = "jail.command.jailcheck", - usage = "/jail check [name]" - ) + maxArgs = 1, + minimumArgs = 1, + needsPlayer = false, + pattern = "check", + permission = "jail.command.jailcheck", + usage = "/jail check [name]" + ) public class JailCheckCommand implements Command{ - // Checks the status of the specified prisoner - public boolean execute(JailManager jm, CommandSender sender, String... args) { - //Otherwise let's check the first argument - if(jm.isPlayerJailedByLastKnownUsername(args[1])) { - Prisoner p = jm.getPrisonerByLastKnownName(args[1]); - - //graywolf663: Being gray's evil twin; CONSOLE (10) - //prisoner: reason; jailer (time in minutes) - sender.sendMessage(ChatColor.BLUE + " " + p.getLastKnownName() + ": " + p.getReason() + "; " + p.getJailer() + " (" + p.getRemainingTimeInMinutes() + " mins)"); - }else { - sender.sendMessage(Lang.NOTJAILED.get(args[1])); - } - - return true; - } + // Checks the status of the specified prisoner + public boolean execute(JailManager jm, CommandSender sender, String... args) { + //Otherwise let's check the first argument + if(jm.isPlayerJailedByLastKnownUsername(args[1])) { + Prisoner p = jm.getPrisonerByLastKnownName(args[1]); + + //graywolf663: Being gray's evil twin; CONSOLE (10) + //prisoner: reason; jailer (time in minutes) + sender.sendMessage(ChatColor.BLUE + " " + p.getLastKnownName() + ": " + p.getReason() + "; " + p.getJailer() + " (" + p.getRemainingTimeInMinutes() + " mins)"); + }else { + sender.sendMessage(Lang.NOTJAILED.get(args[1])); + } + + return true; + } } diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailClearCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailClearCommand.java index 34151a7..a840e33 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailClearCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailClearCommand.java @@ -10,32 +10,32 @@ import com.graywolf336.jail.enums.Confirmation; import com.graywolf336.jail.enums.Lang; @CommandInfo( - maxArgs = 2, - minimumArgs = 0, - needsPlayer = false, - pattern = "clear|clearforce", - permission = "jail.command.jailclear", - usage = "/jail clear (-f) (jail)" - ) + maxArgs = 2, + minimumArgs = 0, + needsPlayer = false, + pattern = "clear|clearforce", + permission = "jail.command.jailclear", + usage = "/jail clear (-f) (jail)" + ) public class JailClearCommand implements Command { - public boolean execute(JailManager jm, CommandSender sender, String... args) { - boolean force = false; - - //Check if we need to forcefully clear something - for(String s : args) - if(s.equalsIgnoreCase("-f") || s.equalsIgnoreCase("-force")) - force = true; - - if(jm.isConfirming(sender.getName())) { - sender.sendMessage(Lang.ALREADY.get()); - }else if(force && sender.hasPermission("jail.command.jailclearforce")) { - jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.CLEARFORCE)); + public boolean execute(JailManager jm, CommandSender sender, String... args) { + boolean force = false; + + //Check if we need to forcefully clear something + for(String s : args) + if(s.equalsIgnoreCase("-f") || s.equalsIgnoreCase("-force")) + force = true; + + if(jm.isConfirming(sender.getName())) { + sender.sendMessage(Lang.ALREADY.get()); + }else if(force && sender.hasPermission("jail.command.jailclearforce")) { + jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.CLEARFORCE)); sender.sendMessage(Lang.START.get()); - }else { - jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.CLEAR)); - sender.sendMessage(Lang.START.get()); - } - - return true; - } + }else { + jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.CLEAR)); + sender.sendMessage(Lang.START.get()); + } + + return true; + } } diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailCommand.java index a647e06..13ce5fb 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailCommand.java @@ -23,213 +23,213 @@ import com.lexicalscope.jewel.cli.ArgumentValidationException; import com.lexicalscope.jewel.cli.CliFactory; @CommandInfo( - maxArgs = -1, - minimumArgs = 0, - needsPlayer = false, - pattern = "jail|j", - permission = "jail.command.jail", - usage = "/jail [name] (-t time) (-j JailName) (-c CellName) (-a AnyCell) (-m Muted) (-r A reason for jailing)" - ) + maxArgs = -1, + minimumArgs = 0, + needsPlayer = false, + pattern = "jail|j", + permission = "jail.command.jail", + usage = "/jail [name] (-t time) (-j JailName) (-c CellName) (-a AnyCell) (-m Muted) (-r A reason for jailing)" + ) public class JailCommand implements Command { - - /* - * Executes the command. Checks the following: - * - * - If there are any jails. - * - If the command can be parsed correctly. - * - If the player is already jailed. - * - If the given time can be parsed correctly, defaults to what is defined in the config - * - If the jail is reasonable or not, else sets the one from the config - * - If the cell is not empty then checks to be sure that cell exists - * - If the prisoner is online or not. - */ - public boolean execute(JailManager jm, CommandSender sender, String... args) { - - if(jm.getJails().isEmpty()) { - sender.sendMessage(Lang.NOJAILS.get()); - return true; - } - - //This is just to add the -p param so CliFactory doesn't blow up - List arguments = new LinkedList(Arrays.asList(args)); - //Only add the "-p" if it doesn't already contain it, this way people can do `/jail -p check` in the event someone - //has a name which is one of our subcommands - if(!arguments.contains("-p")) arguments.add(0, "-p"); - - Jailing params = null; - - try { - params = CliFactory.parseArguments(Jailing.class, arguments.toArray(new String[arguments.size()])); - }catch(ArgumentValidationException e) { - sender.sendMessage(ChatColor.RED + e.getMessage()); - return true; - } - - //Check if they've actually given us a player to jail - if(params.getPlayer() == null) { - sender.sendMessage(Lang.PROVIDEAPLAYER.get(Lang.JAILING)); - return true; - }else { - jm.getPlugin().debug("We are getting ready to handle jailing: " + params.getPlayer()); - } - - //Check if the given player is already jailed or not - if(jm.isPlayerJailedByLastKnownUsername(params.getPlayer())) { - sender.sendMessage(Lang.ALREADYJAILED.get(params.getPlayer())); - return true; - } - - //Try to parse the time, if they give us nothing in the time parameter then we get the default time - //from the config and if that isn't there then we default to thirty minutes. - Long time = 10L; - try { - if(!params.isTime()) { - time = Util.getTime(jm.getPlugin().getConfig().getString(Settings.DEFAULTTIME.getPath(), "30m")); - }else if(params.getTime() == String.valueOf(-1)) { - time = -1L; - }else { - time = Util.getTime(params.getTime()); - } - }catch(Exception e) { - sender.sendMessage(Lang.NUMBERFORMATINCORRECT.get()); - return true; - } - - //Check the jail params. If it is empty, let's get the default jail - //from the config. If that is nearest, let's make a call to getting the nearest jail to - //the sender but otherwise if it isn't nearest then let's set it to the default jail - //which is defined in the config. - String jailName = ""; - if(!params.isJail()) { - String dJail = jm.getPlugin().getConfig().getString(Settings.DEFAULTJAIL.getPath()); - - if(dJail.equalsIgnoreCase("nearest")) { - jailName = jm.getNearestJail(sender).getName(); - }else { - jailName = dJail; - } - }else if(!jm.isValidJail(params.getJail())) { - sender.sendMessage(Lang.NOJAIL.get(params.getJail())); - return true; - }else { - jailName = params.getJail(); - } - - //Get the jail instance from the name of jail in the params. + + /* + * Executes the command. Checks the following: + * + * - If there are any jails. + * - If the command can be parsed correctly. + * - If the player is already jailed. + * - If the given time can be parsed correctly, defaults to what is defined in the config + * - If the jail is reasonable or not, else sets the one from the config + * - If the cell is not empty then checks to be sure that cell exists + * - If the prisoner is online or not. + */ + public boolean execute(JailManager jm, CommandSender sender, String... args) { + + if(jm.getJails().isEmpty()) { + sender.sendMessage(Lang.NOJAILS.get()); + return true; + } + + //This is just to add the -p param so CliFactory doesn't blow up + List arguments = new LinkedList(Arrays.asList(args)); + //Only add the "-p" if it doesn't already contain it, this way people can do `/jail -p check` in the event someone + //has a name which is one of our subcommands + if(!arguments.contains("-p")) arguments.add(0, "-p"); + + Jailing params = null; + + try { + params = CliFactory.parseArguments(Jailing.class, arguments.toArray(new String[arguments.size()])); + }catch(ArgumentValidationException e) { + sender.sendMessage(ChatColor.RED + e.getMessage()); + return true; + } + + //Check if they've actually given us a player to jail + if(params.getPlayer() == null) { + sender.sendMessage(Lang.PROVIDEAPLAYER.get(Lang.JAILING)); + return true; + }else { + jm.getPlugin().debug("We are getting ready to handle jailing: " + params.getPlayer()); + } + + //Check if the given player is already jailed or not + if(jm.isPlayerJailedByLastKnownUsername(params.getPlayer())) { + sender.sendMessage(Lang.ALREADYJAILED.get(params.getPlayer())); + return true; + } + + //Try to parse the time, if they give us nothing in the time parameter then we get the default time + //from the config and if that isn't there then we default to thirty minutes. + Long time = 10L; + try { + if(!params.isTime()) { + time = Util.getTime(jm.getPlugin().getConfig().getString(Settings.DEFAULTTIME.getPath(), "30m")); + }else if(params.getTime() == String.valueOf(-1)) { + time = -1L; + }else { + time = Util.getTime(params.getTime()); + } + }catch(Exception e) { + sender.sendMessage(Lang.NUMBERFORMATINCORRECT.get()); + return true; + } + + //Check the jail params. If it is empty, let's get the default jail + //from the config. If that is nearest, let's make a call to getting the nearest jail to + //the sender but otherwise if it isn't nearest then let's set it to the default jail + //which is defined in the config. + String jailName = ""; + if(!params.isJail()) { + String dJail = jm.getPlugin().getConfig().getString(Settings.DEFAULTJAIL.getPath()); + + if(dJail.equalsIgnoreCase("nearest")) { + jailName = jm.getNearestJail(sender).getName(); + }else { + jailName = dJail; + } + }else if(!jm.isValidJail(params.getJail())) { + sender.sendMessage(Lang.NOJAIL.get(params.getJail())); + return true; + }else { + jailName = params.getJail(); + } + + //Get the jail instance from the name of jail in the params. Jail j = jm.getJail(jailName); if(!j.isEnabled()) { sender.sendMessage(Lang.WORLDUNLOADED.get(j.getName())); return true; } - - Cell c = null; - //Check if the cell is defined - if(params.isCell()) { - //Check if it is a valid cell - if(!jm.getJail(jailName).isValidCell(params.getCell())) { - //There is no cell by that name - sender.sendMessage(Lang.NOCELL.get(new String[] { params.getCell(), jailName })); - return true; - }else if(jm.getJail(jailName).getCell(params.getCell()).hasPrisoner()) { - //If the cell has a prisoner, don't allow jailing them to that particular cell but suggest another one - sender.sendMessage(Lang.CELLNOTEMPTY.get(params.getCell())); - Cell suggestedCell = jm.getJail(jailName).getFirstEmptyCell(); - if(suggestedCell != null) { - sender.sendMessage(Lang.SUGGESTEDCELL.get(new String[] { jailName, suggestedCell.getName() })); - }else { - sender.sendMessage(Lang.NOEMPTYCELLS.get(jailName)); - } - - return true; - }else { - c = jm.getJail(jailName).getCell(params.getCell()); - } - } - - //If they want just any open cell, then let's find the first empty one - if(params.isAnyCell()) { - c = jm.getJail(jailName).getFirstEmptyCell(); - if(c == null) { - //If there wasn't an empty cell, then tell them so. - sender.sendMessage(Lang.NOEMPTYCELLS.get(jailName)); - return true; - } - } - - //If the jailer gave no reason, then let's get the default reason - String reason = ""; - if(!params.isReason()) { - reason = Lang.DEFAULTJAILEDREASON.get(); - }else { - StringBuilder sb = new StringBuilder(); - for(String s : params.getReason()) { - sb.append(s).append(' '); - } - - sb.deleteCharAt(sb.length() - 1); - reason = sb.toString(); - } - - //If the config has automatic muting, then let's set them as muted - boolean muted = params.getMuted(); - if(jm.getPlugin().getConfig().getBoolean(Settings.AUTOMATICMUTE.getPath())) { - muted = true; - } - - Player p = jm.getPlugin().getServer().getPlayer(params.getPlayer()); - - //If the player instance is not null and the player has the permission - //'jail.cantbejailed' then don't allow this to happen - if(p != null && p.hasPermission("jail.cantbejailed")) { - sender.sendMessage(Lang.CANTBEJAILED.get()); - return true; - } - - String uuid = ""; - if(p == null) { - //TODO: Make this whole jail command non-blocking - uuid = jm.getPlugin().getServer().getOfflinePlayer(params.getPlayer()).getUniqueId().toString(); - }else { - uuid = p.getUniqueId().toString(); - } - - Prisoner pris = new Prisoner(uuid, params.getPlayer(), muted, time, sender.getName(), reason); - - //call the event - PrePrisonerJailedEvent event = new PrePrisonerJailedEvent(j, c, pris, p, p == null, pris.getJailer()); - jm.getPlugin().getServer().getPluginManager().callEvent(event); - - //check if the event is cancelled - if(event.isCancelled()) { - if(event.getCancelledMessage().isEmpty()) - sender.sendMessage(Lang.CANCELLEDBYANOTHERPLUGIN.get(params.getPlayer())); - else - sender.sendMessage(event.getCancelledMessage()); - - return true; - } - - //recall data from the event - j = event.getJail(); - c = event.getCell(); - pris = event.getPrisoner(); - p = event.getPlayer(); - - //Player is not online - if(p == null) { - sender.sendMessage(Lang.OFFLINEJAIL.get(new String[] { pris.getLastKnownName(), String.valueOf(pris.getRemainingTimeInMinutes()) })); - }else { - //Player *is* online - sender.sendMessage(Lang.ONLINEJAIL.get(new String[] { pris.getLastKnownName(), String.valueOf(pris.getRemainingTimeInMinutes()) })); - } - - try { - jm.getPlugin().getPrisonerManager().prepareJail(j, c, p, pris); - } catch (Exception e) { - sender.sendMessage(ChatColor.RED + e.getMessage()); - return true; - } - - return true; - } + + Cell c = null; + //Check if the cell is defined + if(params.isCell()) { + //Check if it is a valid cell + if(!jm.getJail(jailName).isValidCell(params.getCell())) { + //There is no cell by that name + sender.sendMessage(Lang.NOCELL.get(new String[] { params.getCell(), jailName })); + return true; + }else if(jm.getJail(jailName).getCell(params.getCell()).hasPrisoner()) { + //If the cell has a prisoner, don't allow jailing them to that particular cell but suggest another one + sender.sendMessage(Lang.CELLNOTEMPTY.get(params.getCell())); + Cell suggestedCell = jm.getJail(jailName).getFirstEmptyCell(); + if(suggestedCell != null) { + sender.sendMessage(Lang.SUGGESTEDCELL.get(new String[] { jailName, suggestedCell.getName() })); + }else { + sender.sendMessage(Lang.NOEMPTYCELLS.get(jailName)); + } + + return true; + }else { + c = jm.getJail(jailName).getCell(params.getCell()); + } + } + + //If they want just any open cell, then let's find the first empty one + if(params.isAnyCell()) { + c = jm.getJail(jailName).getFirstEmptyCell(); + if(c == null) { + //If there wasn't an empty cell, then tell them so. + sender.sendMessage(Lang.NOEMPTYCELLS.get(jailName)); + return true; + } + } + + //If the jailer gave no reason, then let's get the default reason + String reason = ""; + if(!params.isReason()) { + reason = Lang.DEFAULTJAILEDREASON.get(); + }else { + StringBuilder sb = new StringBuilder(); + for(String s : params.getReason()) { + sb.append(s).append(' '); + } + + sb.deleteCharAt(sb.length() - 1); + reason = sb.toString(); + } + + //If the config has automatic muting, then let's set them as muted + boolean muted = params.getMuted(); + if(jm.getPlugin().getConfig().getBoolean(Settings.AUTOMATICMUTE.getPath())) { + muted = true; + } + + Player p = jm.getPlugin().getServer().getPlayer(params.getPlayer()); + + //If the player instance is not null and the player has the permission + //'jail.cantbejailed' then don't allow this to happen + if(p != null && p.hasPermission("jail.cantbejailed")) { + sender.sendMessage(Lang.CANTBEJAILED.get()); + return true; + } + + String uuid = ""; + if(p == null) { + //TODO: Make this whole jail command non-blocking + uuid = jm.getPlugin().getServer().getOfflinePlayer(params.getPlayer()).getUniqueId().toString(); + }else { + uuid = p.getUniqueId().toString(); + } + + Prisoner pris = new Prisoner(uuid, params.getPlayer(), muted, time, sender.getName(), reason); + + //call the event + PrePrisonerJailedEvent event = new PrePrisonerJailedEvent(j, c, pris, p, p == null, pris.getJailer()); + jm.getPlugin().getServer().getPluginManager().callEvent(event); + + //check if the event is cancelled + if(event.isCancelled()) { + if(event.getCancelledMessage().isEmpty()) + sender.sendMessage(Lang.CANCELLEDBYANOTHERPLUGIN.get(params.getPlayer())); + else + sender.sendMessage(event.getCancelledMessage()); + + return true; + } + + //recall data from the event + j = event.getJail(); + c = event.getCell(); + pris = event.getPrisoner(); + p = event.getPlayer(); + + //Player is not online + if(p == null) { + sender.sendMessage(Lang.OFFLINEJAIL.get(new String[] { pris.getLastKnownName(), String.valueOf(pris.getRemainingTimeInMinutes()) })); + }else { + //Player *is* online + sender.sendMessage(Lang.ONLINEJAIL.get(new String[] { pris.getLastKnownName(), String.valueOf(pris.getRemainingTimeInMinutes()) })); + } + + try { + jm.getPlugin().getPrisonerManager().prepareJail(j, c, p, pris); + } catch (Exception e) { + sender.sendMessage(ChatColor.RED + e.getMessage()); + return true; + } + + return true; + } } diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailConfirmCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailConfirmCommand.java index 7a7d041..214e000 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailConfirmCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailConfirmCommand.java @@ -8,84 +8,84 @@ import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Lang; @CommandInfo( - maxArgs = 0, - minimumArgs = 0, - needsPlayer = false, - pattern = "confirm|con", - permission = "", - usage = "/jail confirm" - ) + maxArgs = 0, + minimumArgs = 0, + needsPlayer = false, + pattern = "confirm|con", + permission = "", + usage = "/jail confirm" + ) public class JailConfirmCommand implements Command{ - - public boolean execute(JailManager jm, CommandSender sender, String... args) { - //Check if the sender is actually confirming something. - if(jm.isConfirming(sender.getName())) { - if(jm.confirmingHasExpired(sender.getName())) { - //Their confirmation time frame has closed - sender.sendMessage(Lang.EXPIRED.get()); - }else { - switch(jm.getWhatIsConfirming(sender.getName())) { - case CLEAR: - //Copy the original arguments for easy access - String[] cArgs = jm.getOriginalArgs(sender.getName()); - //Clear a jail if the args length is two, else send null - String msg = jm.clearJailOfPrisoners(cArgs.length == 2 ? cArgs[1] : null); - //Send the message we got back - sender.sendMessage(msg); - //Remove them from confirming so they can't do it again - jm.removeConfirming(sender.getName()); - break; - case CLEARFORCE: - //Copy the original arguments for easy access - String[] cArgs2 = jm.getOriginalArgs(sender.getName()); - //Forcefully clear a jail if the args length is two, else send null to clear all - String msg2 = jm.forcefullyClearJailOrJails(cArgs2.length == 2 ? cArgs2[1] : null); - //Send the message we got back - sender.sendMessage(msg2); - jm.removeConfirming(sender.getName()); - break; - case DELETECELL: - //Copy the original arguments for easy access - String[] cArgs3 = jm.getOriginalArgs(sender.getName()); - //delete a cell from a jail with the given arguments - String msg3 = jm.deleteJailCell(cArgs3[1], cArgs3[2]); - //Send the message we got back - sender.sendMessage(msg3); - jm.removeConfirming(sender.getName()); - break; - case DELETECELLS: - //Copy the original arguments for easy access - String[] cArgs4 = jm.getOriginalArgs(sender.getName()); - //delete a cell from a jail with the given arguments - String[] msgs4 = jm.deleteAllJailCells(cArgs4[1]); - //Send the messages we got back - for(String s : msgs4) { - sender.sendMessage(s); - } - - jm.removeConfirming(sender.getName()); - break; - case DELETE: - //Copy the original arguments for easy access - String[] cArgs5 = jm.getOriginalArgs(sender.getName()); - //delete a cell from a jail with the given arguments - String msg5 = jm.deleteJail(cArgs5[1]); - //Send the message we got back - sender.sendMessage(msg5); - jm.removeConfirming(sender.getName()); - break; - default: - sender.sendMessage(Lang.NOTHING.get()); - jm.removeConfirming(sender.getName()); - break; - } - } - }else { - //They aren't confirming anything right now. - sender.sendMessage(Lang.NOTHING.get()); - } - - return true; - } + + public boolean execute(JailManager jm, CommandSender sender, String... args) { + //Check if the sender is actually confirming something. + if(jm.isConfirming(sender.getName())) { + if(jm.confirmingHasExpired(sender.getName())) { + //Their confirmation time frame has closed + sender.sendMessage(Lang.EXPIRED.get()); + }else { + switch(jm.getWhatIsConfirming(sender.getName())) { + case CLEAR: + //Copy the original arguments for easy access + String[] cArgs = jm.getOriginalArgs(sender.getName()); + //Clear a jail if the args length is two, else send null + String msg = jm.clearJailOfPrisoners(cArgs.length == 2 ? cArgs[1] : null); + //Send the message we got back + sender.sendMessage(msg); + //Remove them from confirming so they can't do it again + jm.removeConfirming(sender.getName()); + break; + case CLEARFORCE: + //Copy the original arguments for easy access + String[] cArgs2 = jm.getOriginalArgs(sender.getName()); + //Forcefully clear a jail if the args length is two, else send null to clear all + String msg2 = jm.forcefullyClearJailOrJails(cArgs2.length == 2 ? cArgs2[1] : null); + //Send the message we got back + sender.sendMessage(msg2); + jm.removeConfirming(sender.getName()); + break; + case DELETECELL: + //Copy the original arguments for easy access + String[] cArgs3 = jm.getOriginalArgs(sender.getName()); + //delete a cell from a jail with the given arguments + String msg3 = jm.deleteJailCell(cArgs3[1], cArgs3[2]); + //Send the message we got back + sender.sendMessage(msg3); + jm.removeConfirming(sender.getName()); + break; + case DELETECELLS: + //Copy the original arguments for easy access + String[] cArgs4 = jm.getOriginalArgs(sender.getName()); + //delete a cell from a jail with the given arguments + String[] msgs4 = jm.deleteAllJailCells(cArgs4[1]); + //Send the messages we got back + for(String s : msgs4) { + sender.sendMessage(s); + } + + jm.removeConfirming(sender.getName()); + break; + case DELETE: + //Copy the original arguments for easy access + String[] cArgs5 = jm.getOriginalArgs(sender.getName()); + //delete a cell from a jail with the given arguments + String msg5 = jm.deleteJail(cArgs5[1]); + //Send the message we got back + sender.sendMessage(msg5); + jm.removeConfirming(sender.getName()); + break; + default: + sender.sendMessage(Lang.NOTHING.get()); + jm.removeConfirming(sender.getName()); + break; + } + } + }else { + //They aren't confirming anything right now. + sender.sendMessage(Lang.NOTHING.get()); + } + + return true; + } } diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailCreateCellCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailCreateCellCommand.java index 6e41ebb..2714c69 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailCreateCellCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailCreateCellCommand.java @@ -10,57 +10,57 @@ import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.CommandInfo; @CommandInfo( - maxArgs = 2, - minimumArgs = 1, - needsPlayer = true, - pattern = "createcell|createcells|cellcreate|cellscreate|cc", - permission = "jail.command.jailcreatecells", - usage = "/jail createcell [jail] (cellname)" - ) + maxArgs = 2, + minimumArgs = 1, + needsPlayer = true, + pattern = "createcell|createcells|cellcreate|cellscreate|cc", + permission = "jail.command.jailcreatecells", + usage = "/jail createcell [jail] (cellname)" + ) public class JailCreateCellCommand implements Command { - public boolean execute(JailManager jm, CommandSender sender, String... args) { - Player player = (Player) sender; - String name = player.getName(); - String jail = args[1].toLowerCase(); - String cell = ""; - - //Only get the cell name they provide if they provide it - if(args.length >= 3) { - cell = args[2]; - } - - //Check if the player is currently creating something else - if(jm.isCreatingSomething(name)) { - String message = jm.getStepMessage(name); - if(!message.isEmpty()) { - player.sendMessage(ChatColor.RED + message); - }else { - player.sendMessage(ChatColor.RED + "You're already creating something else, please finish it or cancel."); - } - }else { - //Not creating anything, so let them create some cells. - if(jm.isValidJail(jail)) { - Jail j = jm.getJail(jail); - - //If they didn't provide a cell name, let's provide one ourself. - if(cell.isEmpty()) cell = "cell_n" + (j.getCellCount() + 1); - - if(j.getCell(cell) == null) { - if(jm.addCreatingCell(name, jail, cell)) { - jm.getCellCreationSteps().startStepping(player); - }else { - player.sendMessage(ChatColor.RED + "Appears you're creating a cell or something went wrong on our side."); - } - }else { - player.sendMessage(ChatColor.RED + "There's already a cell with the name '" + cell + "', please pick a new one or remove that cell."); - } - }else { - player.sendMessage(ChatColor.RED + "No such jail found by the name of '" + jail + "'."); - } - } - - return true; - } + public boolean execute(JailManager jm, CommandSender sender, String... args) { + Player player = (Player) sender; + String name = player.getName(); + String jail = args[1].toLowerCase(); + String cell = ""; + + //Only get the cell name they provide if they provide it + if(args.length >= 3) { + cell = args[2]; + } + + //Check if the player is currently creating something else + if(jm.isCreatingSomething(name)) { + String message = jm.getStepMessage(name); + if(!message.isEmpty()) { + player.sendMessage(ChatColor.RED + message); + }else { + player.sendMessage(ChatColor.RED + "You're already creating something else, please finish it or cancel."); + } + }else { + //Not creating anything, so let them create some cells. + if(jm.isValidJail(jail)) { + Jail j = jm.getJail(jail); + + //If they didn't provide a cell name, let's provide one ourself. + if(cell.isEmpty()) cell = "cell_n" + (j.getCellCount() + 1); + + if(j.getCell(cell) == null) { + if(jm.addCreatingCell(name, jail, cell)) { + jm.getCellCreationSteps().startStepping(player); + }else { + player.sendMessage(ChatColor.RED + "Appears you're creating a cell or something went wrong on our side."); + } + }else { + player.sendMessage(ChatColor.RED + "There's already a cell with the name '" + cell + "', please pick a new one or remove that cell."); + } + }else { + player.sendMessage(ChatColor.RED + "No such jail found by the name of '" + jail + "'."); + } + } + + return true; + } } diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailCreateCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailCreateCommand.java index 5678a8c..8adfe30 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailCreateCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailCreateCommand.java @@ -9,40 +9,40 @@ import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.CommandInfo; @CommandInfo( - maxArgs = 1, - minimumArgs = 1, - needsPlayer = true, - pattern = "create", - permission = "jail.command.jailcreate", - usage = "/jail create [name]" - ) + maxArgs = 1, + minimumArgs = 1, + needsPlayer = true, + pattern = "create", + permission = "jail.command.jailcreate", + usage = "/jail create [name]" + ) public class JailCreateCommand implements Command { - public boolean execute(JailManager jm, CommandSender sender, String... args) { - Player player = (Player) sender; - String name = player.getName(); - String jail = args[1]; - - //Check if the player is currently creating something else - if(jm.isCreatingSomething(name)) { - String message = jm.getStepMessage(name); - if(!message.isEmpty()) { - player.sendMessage(ChatColor.RED + message); - }else { - player.sendMessage(ChatColor.RED + "You're already creating something else, please finish it or cancel."); - } - }else { - if(jm.isValidJail(jail)) { - player.sendMessage(ChatColor.RED + "Jail by the name of '" + jail + "' already exist!"); - }else { - if(jm.addCreatingJail(name, jail)) { - jm.getJailCreationSteps().startStepping(player); - }else { - player.sendMessage(ChatColor.RED + "Seems like you're already creating a Jail or something went wrong on our side."); - } - } - } - - return true; - } + public boolean execute(JailManager jm, CommandSender sender, String... args) { + Player player = (Player) sender; + String name = player.getName(); + String jail = args[1]; + + //Check if the player is currently creating something else + if(jm.isCreatingSomething(name)) { + String message = jm.getStepMessage(name); + if(!message.isEmpty()) { + player.sendMessage(ChatColor.RED + message); + }else { + player.sendMessage(ChatColor.RED + "You're already creating something else, please finish it or cancel."); + } + }else { + if(jm.isValidJail(jail)) { + player.sendMessage(ChatColor.RED + "Jail by the name of '" + jail + "' already exist!"); + }else { + if(jm.addCreatingJail(name, jail)) { + jm.getJailCreationSteps().startStepping(player); + }else { + player.sendMessage(ChatColor.RED + "Seems like you're already creating a Jail or something went wrong on our side."); + } + } + } + + return true; + } } diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailDeleteCellCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailDeleteCellCommand.java index 9e3b378..d0f99c5 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailDeleteCellCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailDeleteCellCommand.java @@ -10,22 +10,22 @@ import com.graywolf336.jail.enums.Confirmation; import com.graywolf336.jail.enums.Lang; @CommandInfo( - maxArgs = 2, - minimumArgs = 2, - needsPlayer = false, - pattern = "deletecell|dc", - permission = "jail.command.jaildeletecell", - usage = "/jail deletecell [jail] [cell]" - ) + maxArgs = 2, + minimumArgs = 2, + needsPlayer = false, + pattern = "deletecell|dc", + permission = "jail.command.jaildeletecell", + usage = "/jail deletecell [jail] [cell]" + ) public class JailDeleteCellCommand implements Command { - public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { - if(jm.isConfirming(sender.getName())) { - sender.sendMessage(Lang.ALREADY.get()); - }else { - jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.DELETECELL)); - sender.sendMessage(Lang.START.get()); - } - - return true; - } + public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { + if(jm.isConfirming(sender.getName())) { + sender.sendMessage(Lang.ALREADY.get()); + }else { + jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.DELETECELL)); + sender.sendMessage(Lang.START.get()); + } + + return true; + } } diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailDeleteCellsCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailDeleteCellsCommand.java index 7e71182..5f15cd8 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailDeleteCellsCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailDeleteCellsCommand.java @@ -10,22 +10,22 @@ import com.graywolf336.jail.enums.Confirmation; import com.graywolf336.jail.enums.Lang; @CommandInfo( - maxArgs = 1, - minimumArgs = 1, - needsPlayer = false, - pattern = "deletecells|dcs", - permission = "jail.command.jaildeletecell", - usage = "/jail deletecells [jail]" - ) + maxArgs = 1, + minimumArgs = 1, + needsPlayer = false, + pattern = "deletecells|dcs", + permission = "jail.command.jaildeletecell", + usage = "/jail deletecells [jail]" + ) public class JailDeleteCellsCommand implements Command { - public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { - if(jm.isConfirming(sender.getName())) { - sender.sendMessage(Lang.ALREADY.get()); - }else { - jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.DELETECELLS)); - sender.sendMessage(Lang.START.get()); - } - - return true; - } + public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { + if(jm.isConfirming(sender.getName())) { + sender.sendMessage(Lang.ALREADY.get()); + }else { + jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.DELETECELLS)); + sender.sendMessage(Lang.START.get()); + } + + return true; + } } diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailDeleteCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailDeleteCommand.java index ac751a7..09d35b3 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailDeleteCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailDeleteCommand.java @@ -10,22 +10,22 @@ import com.graywolf336.jail.enums.Confirmation; import com.graywolf336.jail.enums.Lang; @CommandInfo( - maxArgs = 1, - minimumArgs = 1, - needsPlayer = false, - pattern = "delete|d", - permission = "jail.command.jaildelete", - usage = "/jail delete [jail]" - ) + maxArgs = 1, + minimumArgs = 1, + needsPlayer = false, + pattern = "delete|d", + permission = "jail.command.jaildelete", + usage = "/jail delete [jail]" + ) public class JailDeleteCommand implements Command { - public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { - if(jm.isConfirming(sender.getName())) { - sender.sendMessage(Lang.ALREADY.get()); - }else { - jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.DELETE)); - sender.sendMessage(Lang.START.get()); - } - - return true; - } + public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { + if(jm.isConfirming(sender.getName())) { + sender.sendMessage(Lang.ALREADY.get()); + }else { + jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.DELETE)); + sender.sendMessage(Lang.START.get()); + } + + return true; + } } diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailListCellsCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailListCellsCommand.java index 5ef03c0..229c28a 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailListCellsCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailListCellsCommand.java @@ -11,44 +11,44 @@ import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Lang; @CommandInfo( - maxArgs = 1, - minimumArgs = 1, - needsPlayer = false, - pattern = "listcells|lc", - permission = "jail.command.jaillistcell", - usage = "/jail listcells [jail]" - ) + maxArgs = 1, + minimumArgs = 1, + needsPlayer = false, + pattern = "listcells|lc", + permission = "jail.command.jaillistcell", + usage = "/jail listcells [jail]" + ) public class JailListCellsCommand implements Command { - @Override - public boolean execute(JailManager jm, CommandSender sender, String... args) { - sender.sendMessage(ChatColor.AQUA + "----------Cells----------"); - - if(!jm.getJails().isEmpty()) { - if(jm.getJail(args[1]) != null) { - Jail j = jm.getJail(args[1]); - - String message = ""; - for(Cell c : j.getCells()) { - if(message.isEmpty()) { - message = c.getName() + (c.getPrisoner() == null ? "" : " (" + c.getPrisoner().getLastKnownName() + ")"); - }else { - message += ", " + c.getName() + (c.getPrisoner() == null ? "" : " (" + c.getPrisoner().getLastKnownName() + ")"); - } - } - - if(message.isEmpty()) { - sender.sendMessage(Lang.NOCELLS.get(j.getName())); - }else { - sender.sendMessage(ChatColor.GREEN + message); - } - }else { - sender.sendMessage(Lang.NOJAIL.get(args[1])); - } - }else { - sender.sendMessage(Lang.NOJAILS.get()); - } - - sender.sendMessage(ChatColor.AQUA + "-------------------------"); - return true; - } + @Override + public boolean execute(JailManager jm, CommandSender sender, String... args) { + sender.sendMessage(ChatColor.AQUA + "----------Cells----------"); + + if(!jm.getJails().isEmpty()) { + if(jm.getJail(args[1]) != null) { + Jail j = jm.getJail(args[1]); + + String message = ""; + for(Cell c : j.getCells()) { + if(message.isEmpty()) { + message = c.getName() + (c.getPrisoner() == null ? "" : " (" + c.getPrisoner().getLastKnownName() + ")"); + }else { + message += ", " + c.getName() + (c.getPrisoner() == null ? "" : " (" + c.getPrisoner().getLastKnownName() + ")"); + } + } + + if(message.isEmpty()) { + sender.sendMessage(Lang.NOCELLS.get(j.getName())); + }else { + sender.sendMessage(ChatColor.GREEN + message); + } + }else { + sender.sendMessage(Lang.NOJAIL.get(args[1])); + } + }else { + sender.sendMessage(Lang.NOJAILS.get()); + } + + sender.sendMessage(ChatColor.AQUA + "-------------------------"); + return true; + } } diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailListCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailListCommand.java index 006621f..e71e1d4 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailListCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailListCommand.java @@ -13,52 +13,52 @@ import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Lang; @CommandInfo( - maxArgs = 1, - minimumArgs = 0, - needsPlayer = false, - pattern = "list|l", - permission = "jail.command.jaillist", - usage = "/jail list (jail)" - ) + maxArgs = 1, + minimumArgs = 0, + needsPlayer = false, + pattern = "list|l", + permission = "jail.command.jaillist", + usage = "/jail list (jail)" + ) public class JailListCommand implements Command { - public boolean execute(JailManager jm, CommandSender sender, String... args) { - sender.sendMessage(ChatColor.AQUA + "----------" + (args.length == 1 ? "Jails" : "Prisoners") + "----------"); - - //Check if there are any jails - if(jm.getJails().isEmpty()) { - sender.sendMessage(" " + Lang.NOJAILS.get()); - }else { - //Check if they have provided a jail to list or not - if(args.length == 1) { - //No jail provided, so give them a list of the jails - for(Jail j : jm.getJails()) { - if(j.isEnabled()) sender.sendMessage(ChatColor.BLUE + " " + j.getName() + " (" + j.getAllPrisoners().size() + ")"); - else sender.sendMessage(ChatColor.RED + " " + j.getName() + " (" + j.getAllPrisoners().size() + ") - WORLD UNLOADED"); - } - }else { - Jail j = jm.getJail(args[1]); - - if(j == null) { - //No jail was found - sender.sendMessage(" " + Lang.NOJAIL.get(args[1])); - }else { - Collection pris = j.getAllPrisoners().values(); - - if(pris.isEmpty()) { - //If there are no prisoners, then send that message - sender.sendMessage(" " + Lang.NOPRISONERS.get(j.getName())); - }else { - for(Prisoner p : pris) { - //graywolf663: Being gray's evil twin; CONSOLE (10) - //prisoner: reason; jailer (time in minutes) - sender.sendMessage(ChatColor.BLUE + " " + p.getLastKnownName() + ": " + p.getReason() + "; " + p.getJailer() + " (" + p.getRemainingTimeInMinutes() + " mins)"); - } - } - } - } - } - - sender.sendMessage(ChatColor.AQUA + "-------------------------"); - return true; - } + public boolean execute(JailManager jm, CommandSender sender, String... args) { + sender.sendMessage(ChatColor.AQUA + "----------" + (args.length == 1 ? "Jails" : "Prisoners") + "----------"); + + //Check if there are any jails + if(jm.getJails().isEmpty()) { + sender.sendMessage(" " + Lang.NOJAILS.get()); + }else { + //Check if they have provided a jail to list or not + if(args.length == 1) { + //No jail provided, so give them a list of the jails + for(Jail j : jm.getJails()) { + if(j.isEnabled()) sender.sendMessage(ChatColor.BLUE + " " + j.getName() + " (" + j.getAllPrisoners().size() + ")"); + else sender.sendMessage(ChatColor.RED + " " + j.getName() + " (" + j.getAllPrisoners().size() + ") - WORLD UNLOADED"); + } + }else { + Jail j = jm.getJail(args[1]); + + if(j == null) { + //No jail was found + sender.sendMessage(" " + Lang.NOJAIL.get(args[1])); + }else { + Collection pris = j.getAllPrisoners().values(); + + if(pris.isEmpty()) { + //If there are no prisoners, then send that message + sender.sendMessage(" " + Lang.NOPRISONERS.get(j.getName())); + }else { + for(Prisoner p : pris) { + //graywolf663: Being gray's evil twin; CONSOLE (10) + //prisoner: reason; jailer (time in minutes) + sender.sendMessage(ChatColor.BLUE + " " + p.getLastKnownName() + ": " + p.getReason() + "; " + p.getJailer() + " (" + p.getRemainingTimeInMinutes() + " mins)"); + } + } + } + } + } + + sender.sendMessage(ChatColor.AQUA + "-------------------------"); + return true; + } } diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailMuteCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailMuteCommand.java index 49e9325..f33dd72 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailMuteCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailMuteCommand.java @@ -8,31 +8,31 @@ import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Lang; @CommandInfo( - maxArgs = 1, - minimumArgs = 1, - needsPlayer = false, - pattern = "mute|m", - permission = "jail.command.jailmute", - usage = "/jail mute [name]" - ) + maxArgs = 1, + minimumArgs = 1, + needsPlayer = false, + pattern = "mute|m", + permission = "jail.command.jailmute", + usage = "/jail mute [name]" + ) public class JailMuteCommand implements Command { - public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { - //Let's check if the player they're sending us is jailed - if(jm.isPlayerJailedByLastKnownUsername(args[1])) { - //They are, so let's toggle whether they are muted or not - boolean muted = !jm.getPrisonerByLastKnownName(args[1]).isMuted(); - jm.getPrisonerByLastKnownName(args[1]).setMuted(muted); - - //Send the message to the sender based upon whether they are muted or unmuted - if(muted) - sender.sendMessage(Lang.NOWMUTED.get(args[1])); - else - sender.sendMessage(Lang.NOWUNMUTED.get(args[1])); - }else { - //The player provided is not jailed, so let's tell the sender that - sender.sendMessage(Lang.NOTJAILED.get(args[1])); - } - - return true; - } + public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { + //Let's check if the player they're sending us is jailed + if(jm.isPlayerJailedByLastKnownUsername(args[1])) { + //They are, so let's toggle whether they are muted or not + boolean muted = !jm.getPrisonerByLastKnownName(args[1]).isMuted(); + jm.getPrisonerByLastKnownName(args[1]).setMuted(muted); + + //Send the message to the sender based upon whether they are muted or unmuted + if(muted) + sender.sendMessage(Lang.NOWMUTED.get(args[1])); + else + sender.sendMessage(Lang.NOWUNMUTED.get(args[1])); + }else { + //The player provided is not jailed, so let's tell the sender that + sender.sendMessage(Lang.NOTJAILED.get(args[1])); + } + + return true; + } } diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailPayCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailPayCommand.java index 6e24d70..d1292f5 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailPayCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailPayCommand.java @@ -15,195 +15,195 @@ import com.graywolf336.jail.enums.Lang; import com.graywolf336.jail.enums.Settings; @CommandInfo( - maxArgs = 2, - minimumArgs = 0, - needsPlayer = true, - pattern = "pay", - permission = "jail.usercmd.jailpay", - usage = "/jail pay (amount) (name)" - ) + maxArgs = 2, + minimumArgs = 0, + needsPlayer = true, + pattern = "pay", + permission = "jail.usercmd.jailpay", + usage = "/jail pay (amount) (name)" + ) public class JailPayCommand implements Command { - public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { - if(jm.getPlugin().getConfig().getBoolean(Settings.JAILPAYENABLED.getPath())) { - JailPayManager pm = jm.getPlugin().getJailPayManager(); - - switch(args.length) { - case 1: - // `/jail pay` - //send how much it costs to get out - if(jm.isPlayerJailedByLastKnownUsername(sender.getName())) { - Prisoner p = jm.getPrisonerByLastKnownName(sender.getName()); - String amt = ""; - - if(pm.usingItemsForPayment()) { - amt = String.valueOf((int) Math.ceil(pm.calculateBill(p))); - }else { - amt = String.valueOf(pm.calculateBill(p)); - } - - if(p.getRemainingTime() > 0) { - if(pm.isTimedEnabled()) { - sender.sendMessage(Lang.PAYCOST.get(new String[] { pm.getCostPerMinute(), pm.getCurrencyName(), amt })); - }else { - sender.sendMessage(Lang.PAYNOTENABLED.get()); - jm.getPlugin().debug("Jail pay 'timed' paying is not enabled (config has 0 as the cost)."); - } - }else { - if(pm.isInfiniteEnabled()) { - sender.sendMessage(Lang.PAYCOST.get(new String[] { amt, pm.getCurrencyName() })); - }else { - sender.sendMessage(Lang.PAYNOTENABLED.get()); - jm.getPlugin().debug("Jail pay 'infinite' paying is not enabled (config has 0 as the cost)."); - } - } - }else { - sender.sendMessage(Lang.YOUARENOTJAILED.get()); - } - - break; - case 2: - // `/jail pay ` - //They are trying to pay for their self - if(jm.isPlayerJailedByLastKnownUsername(sender.getName())) { - Prisoner p = jm.getPrisonerByLastKnownName(sender.getName()); - - if(p.getRemainingTime() > 0) { - if(!pm.isTimedEnabled()) { - sender.sendMessage(Lang.PAYNOTENABLED.get()); - return true; - } - }else { - if(!pm.isInfiniteEnabled()) { - sender.sendMessage(Lang.PAYNOTENABLED.get()); - return true; - } - } - - if(args[1].startsWith("-")) { - sender.sendMessage(Lang.PAYNONEGATIVEAMOUNTS.get()); - }else { - double amt = 0; - - try { - amt = Double.parseDouble(args[1]); - }catch(NumberFormatException e) { - sender.sendMessage(ChatColor.RED + " must be a number."); - throw e; - } - - if(pm.hasEnoughToPay((Player) sender, amt)) { - double bill = pm.calculateBill(p); - - if(p.getRemainingTime() > 0) { - //timed sentence - if(amt >= bill) { - pm.pay((Player) sender, bill); - sender.sendMessage(Lang.PAYPAIDRELEASED.get(String.valueOf(bill))); - jm.getPlugin().getPrisonerManager().schedulePrisonerRelease(p); - }else { - long minutes = pm.getMinutesPayingFor(amt); - pm.pay((Player) sender, amt); - long remain = p.subtractTime(TimeUnit.MILLISECONDS.convert(minutes, TimeUnit.MINUTES)); - sender.sendMessage(Lang.PAYPAIDLOWEREDTIME.get(new String[] { String.valueOf(amt), String.valueOf(TimeUnit.MINUTES.convert(remain, TimeUnit.MILLISECONDS)) })); - } - }else { - //infinite jailing - if(amt >= bill) { - pm.pay((Player) sender, bill); - sender.sendMessage(Lang.PAYPAIDRELEASED.get(String.valueOf(bill))); - jm.getPlugin().getPrisonerManager().schedulePrisonerRelease(p); - }else { - //You haven't provided enough money to get them out - sender.sendMessage(Lang.PAYNOTENOUGHMONEYPROVIDED.get()); - } - } - }else { - sender.sendMessage(Lang.PAYNOTENOUGHMONEY.get()); - } - } - }else { - sender.sendMessage(Lang.YOUARENOTJAILED.get()); - } - break; - case 3: - // `/jail pay - //they are trying to pay for someone else - if(jm.isPlayerJailedByLastKnownUsername(sender.getName())) { - //When they are jailed they can not pay for someone else - sender.sendMessage(Lang.PAYCANTPAYWHILEJAILED.get()); - }else { - if(jm.isPlayerJailedByLastKnownUsername(args[2])) { - Prisoner p = jm.getPrisonerByLastKnownName(args[2]); - - if(p.getRemainingTime() > 0) { - if(!pm.isTimedEnabled()) { - sender.sendMessage(Lang.PAYNOTENABLED.get()); - return true; - } - }else { - if(!pm.isInfiniteEnabled()) { - sender.sendMessage(Lang.PAYNOTENABLED.get()); - return true; - } - } - - if(args[1].startsWith("-")) { - sender.sendMessage(Lang.PAYNONEGATIVEAMOUNTS.get()); - }else { - double amt = 0; - - try { - amt = Double.parseDouble(args[1]); - }catch(NumberFormatException e) { - sender.sendMessage(ChatColor.RED + " must be a number."); - throw e; - } - - - if(pm.hasEnoughToPay((Player) sender, amt)) { - double bill = pm.calculateBill(p); - - if(p.getRemainingTime() > 0) { - //timed sentence - if(amt >= bill) { - pm.pay((Player) sender, bill); - sender.sendMessage(Lang.PAYPAIDRELEASEDELSE.get(new String[] { String.valueOf(bill), p.getLastKnownName() })); - jm.getPlugin().getPrisonerManager().schedulePrisonerRelease(p); - }else { - long minutes = pm.getMinutesPayingFor(amt); - pm.pay((Player) sender, amt); - long remain = p.subtractTime(TimeUnit.MILLISECONDS.convert(minutes, TimeUnit.MINUTES)); - sender.sendMessage(Lang.PAYPAIDLOWEREDTIMEELSE.get(new String[] { String.valueOf(amt), p.getLastKnownName(), String.valueOf(TimeUnit.MINUTES.convert(remain, TimeUnit.MILLISECONDS)) })); - } - }else { - //infinite jailing - if(amt >= bill) { - pm.pay((Player) sender, bill); - sender.sendMessage(Lang.PAYPAIDRELEASEDELSE.get(new String[] { String.valueOf(bill), p.getLastKnownName() })); - jm.getPlugin().getPrisonerManager().schedulePrisonerRelease(p); - }else { - //You haven't provided enough money to get them out - sender.sendMessage(Lang.PAYNOTENOUGHMONEYPROVIDED.get()); - } - } - }else { - sender.sendMessage(Lang.PAYNOTENOUGHMONEY.get()); - } - } - }else { - //Person they're trying to pay for is not jailed - sender.sendMessage(Lang.NOTJAILED.get(args[2])); - } - } - break; - default: - return false; - } - }else { - jm.getPlugin().debug("Jail pay not enabled."); - sender.sendMessage(Lang.PAYNOTENABLED.get()); - } - - return true; - } + public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { + if(jm.getPlugin().getConfig().getBoolean(Settings.JAILPAYENABLED.getPath())) { + JailPayManager pm = jm.getPlugin().getJailPayManager(); + + switch(args.length) { + case 1: + // `/jail pay` + //send how much it costs to get out + if(jm.isPlayerJailedByLastKnownUsername(sender.getName())) { + Prisoner p = jm.getPrisonerByLastKnownName(sender.getName()); + String amt = ""; + + if(pm.usingItemsForPayment()) { + amt = String.valueOf((int) Math.ceil(pm.calculateBill(p))); + }else { + amt = String.valueOf(pm.calculateBill(p)); + } + + if(p.getRemainingTime() > 0) { + if(pm.isTimedEnabled()) { + sender.sendMessage(Lang.PAYCOST.get(new String[] { pm.getCostPerMinute(), pm.getCurrencyName(), amt })); + }else { + sender.sendMessage(Lang.PAYNOTENABLED.get()); + jm.getPlugin().debug("Jail pay 'timed' paying is not enabled (config has 0 as the cost)."); + } + }else { + if(pm.isInfiniteEnabled()) { + sender.sendMessage(Lang.PAYCOST.get(new String[] { amt, pm.getCurrencyName() })); + }else { + sender.sendMessage(Lang.PAYNOTENABLED.get()); + jm.getPlugin().debug("Jail pay 'infinite' paying is not enabled (config has 0 as the cost)."); + } + } + }else { + sender.sendMessage(Lang.YOUARENOTJAILED.get()); + } + + break; + case 2: + // `/jail pay ` + //They are trying to pay for their self + if(jm.isPlayerJailedByLastKnownUsername(sender.getName())) { + Prisoner p = jm.getPrisonerByLastKnownName(sender.getName()); + + if(p.getRemainingTime() > 0) { + if(!pm.isTimedEnabled()) { + sender.sendMessage(Lang.PAYNOTENABLED.get()); + return true; + } + }else { + if(!pm.isInfiniteEnabled()) { + sender.sendMessage(Lang.PAYNOTENABLED.get()); + return true; + } + } + + if(args[1].startsWith("-")) { + sender.sendMessage(Lang.PAYNONEGATIVEAMOUNTS.get()); + }else { + double amt = 0; + + try { + amt = Double.parseDouble(args[1]); + }catch(NumberFormatException e) { + sender.sendMessage(ChatColor.RED + " must be a number."); + throw e; + } + + if(pm.hasEnoughToPay((Player) sender, amt)) { + double bill = pm.calculateBill(p); + + if(p.getRemainingTime() > 0) { + //timed sentence + if(amt >= bill) { + pm.pay((Player) sender, bill); + sender.sendMessage(Lang.PAYPAIDRELEASED.get(String.valueOf(bill))); + jm.getPlugin().getPrisonerManager().schedulePrisonerRelease(p); + }else { + long minutes = pm.getMinutesPayingFor(amt); + pm.pay((Player) sender, amt); + long remain = p.subtractTime(TimeUnit.MILLISECONDS.convert(minutes, TimeUnit.MINUTES)); + sender.sendMessage(Lang.PAYPAIDLOWEREDTIME.get(new String[] { String.valueOf(amt), String.valueOf(TimeUnit.MINUTES.convert(remain, TimeUnit.MILLISECONDS)) })); + } + }else { + //infinite jailing + if(amt >= bill) { + pm.pay((Player) sender, bill); + sender.sendMessage(Lang.PAYPAIDRELEASED.get(String.valueOf(bill))); + jm.getPlugin().getPrisonerManager().schedulePrisonerRelease(p); + }else { + //You haven't provided enough money to get them out + sender.sendMessage(Lang.PAYNOTENOUGHMONEYPROVIDED.get()); + } + } + }else { + sender.sendMessage(Lang.PAYNOTENOUGHMONEY.get()); + } + } + }else { + sender.sendMessage(Lang.YOUARENOTJAILED.get()); + } + break; + case 3: + // `/jail pay + //they are trying to pay for someone else + if(jm.isPlayerJailedByLastKnownUsername(sender.getName())) { + //When they are jailed they can not pay for someone else + sender.sendMessage(Lang.PAYCANTPAYWHILEJAILED.get()); + }else { + if(jm.isPlayerJailedByLastKnownUsername(args[2])) { + Prisoner p = jm.getPrisonerByLastKnownName(args[2]); + + if(p.getRemainingTime() > 0) { + if(!pm.isTimedEnabled()) { + sender.sendMessage(Lang.PAYNOTENABLED.get()); + return true; + } + }else { + if(!pm.isInfiniteEnabled()) { + sender.sendMessage(Lang.PAYNOTENABLED.get()); + return true; + } + } + + if(args[1].startsWith("-")) { + sender.sendMessage(Lang.PAYNONEGATIVEAMOUNTS.get()); + }else { + double amt = 0; + + try { + amt = Double.parseDouble(args[1]); + }catch(NumberFormatException e) { + sender.sendMessage(ChatColor.RED + " must be a number."); + throw e; + } + + + if(pm.hasEnoughToPay((Player) sender, amt)) { + double bill = pm.calculateBill(p); + + if(p.getRemainingTime() > 0) { + //timed sentence + if(amt >= bill) { + pm.pay((Player) sender, bill); + sender.sendMessage(Lang.PAYPAIDRELEASEDELSE.get(new String[] { String.valueOf(bill), p.getLastKnownName() })); + jm.getPlugin().getPrisonerManager().schedulePrisonerRelease(p); + }else { + long minutes = pm.getMinutesPayingFor(amt); + pm.pay((Player) sender, amt); + long remain = p.subtractTime(TimeUnit.MILLISECONDS.convert(minutes, TimeUnit.MINUTES)); + sender.sendMessage(Lang.PAYPAIDLOWEREDTIMEELSE.get(new String[] { String.valueOf(amt), p.getLastKnownName(), String.valueOf(TimeUnit.MINUTES.convert(remain, TimeUnit.MILLISECONDS)) })); + } + }else { + //infinite jailing + if(amt >= bill) { + pm.pay((Player) sender, bill); + sender.sendMessage(Lang.PAYPAIDRELEASEDELSE.get(new String[] { String.valueOf(bill), p.getLastKnownName() })); + jm.getPlugin().getPrisonerManager().schedulePrisonerRelease(p); + }else { + //You haven't provided enough money to get them out + sender.sendMessage(Lang.PAYNOTENOUGHMONEYPROVIDED.get()); + } + } + }else { + sender.sendMessage(Lang.PAYNOTENOUGHMONEY.get()); + } + } + }else { + //Person they're trying to pay for is not jailed + sender.sendMessage(Lang.NOTJAILED.get(args[2])); + } + } + break; + default: + return false; + } + }else { + jm.getPlugin().debug("Jail pay not enabled."); + sender.sendMessage(Lang.PAYNOTENABLED.get()); + } + + return true; + } } diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailRecordCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailRecordCommand.java index f7ea3ec..7621d6e 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailRecordCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailRecordCommand.java @@ -10,36 +10,36 @@ import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Lang; @CommandInfo( - maxArgs = 2, - minimumArgs = 1, - needsPlayer = false, - pattern = "record|r", - permission = "jail.command.jailrecord", - usage = "/jail record [name] (display)" - ) + maxArgs = 2, + minimumArgs = 1, + needsPlayer = false, + pattern = "record|r", + permission = "jail.command.jailrecord", + usage = "/jail record [name] (display)" + ) public class JailRecordCommand implements Command { - public boolean execute(JailManager jm, CommandSender sender, String... args) { - if(args.length == 2) { - // /jail record - List entries = jm.getPlugin().getJailIO().getRecordEntries(args[1]); - - sender.sendMessage(Lang.RECORDTIMESJAILED.get(new String[] { args[1], String.valueOf(entries.size()) })); - }else if(args.length == 3) { - // /jail record something - List entries = jm.getPlugin().getJailIO().getRecordEntries(args[1]); - - //Send all the record entries - for(String s : entries) { - sender.sendMessage(s); - } - - sender.sendMessage(Lang.RECORDTIMESJAILED.get(new String[] { args[1], String.valueOf(entries.size()) })); - }else { - //They didn't do the command right - //send them back to get the usage - return false; - } - - return true; - } + public boolean execute(JailManager jm, CommandSender sender, String... args) { + if(args.length == 2) { + // /jail record + List entries = jm.getPlugin().getJailIO().getRecordEntries(args[1]); + + sender.sendMessage(Lang.RECORDTIMESJAILED.get(new String[] { args[1], String.valueOf(entries.size()) })); + }else if(args.length == 3) { + // /jail record something + List entries = jm.getPlugin().getJailIO().getRecordEntries(args[1]); + + //Send all the record entries + for(String s : entries) { + sender.sendMessage(s); + } + + sender.sendMessage(Lang.RECORDTIMESJAILED.get(new String[] { args[1], String.valueOf(entries.size()) })); + }else { + //They didn't do the command right + //send them back to get the usage + return false; + } + + return true; + } } diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailReloadCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailReloadCommand.java index 76b8582..06e5cc0 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailReloadCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailReloadCommand.java @@ -9,29 +9,29 @@ import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Lang; @CommandInfo( - maxArgs = 0, - minimumArgs = 0, - needsPlayer = false, - pattern = "reload", - permission = "jail.command.jailreload", - usage = "/jail reload" - ) + maxArgs = 0, + minimumArgs = 0, + needsPlayer = false, + pattern = "reload", + permission = "jail.command.jailreload", + usage = "/jail reload" + ) public class JailReloadCommand implements Command { - public boolean execute(JailManager jm, CommandSender sender, String... args) { - try { - jm.getPlugin().reloadConfig(); - jm.getPlugin().getJailIO().loadLanguage(); - jm.getPlugin().getJailIO().loadJails(); - jm.getPlugin().reloadScoreBoardManager(); - jm.getPlugin().reloadJailSticks(); - jm.getPlugin().reloadJailPayManager(); - jm.getPlugin().reloadUpdateCheck(); - - sender.sendMessage(Lang.PLUGINRELOADED.get()); - }catch (Exception e) { - sender.sendMessage(ChatColor.RED + "Failed to reload due to: " + e.getMessage()); - } - - return true; - } + public boolean execute(JailManager jm, CommandSender sender, String... args) { + try { + jm.getPlugin().reloadConfig(); + jm.getPlugin().getJailIO().loadLanguage(); + jm.getPlugin().getJailIO().loadJails(); + jm.getPlugin().reloadScoreBoardManager(); + jm.getPlugin().reloadJailSticks(); + jm.getPlugin().reloadJailPayManager(); + jm.getPlugin().reloadUpdateCheck(); + + sender.sendMessage(Lang.PLUGINRELOADED.get()); + }catch (Exception e) { + sender.sendMessage(ChatColor.RED + "Failed to reload due to: " + e.getMessage()); + } + + return true; + } } diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailStatusCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailStatusCommand.java index 65ceb9d..5e41742 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailStatusCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailStatusCommand.java @@ -10,28 +10,28 @@ import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Lang; @CommandInfo( - maxArgs = 0, - minimumArgs = 0, - needsPlayer = true, - pattern = "status|s", - permission = "jail.usercmd.jailstatus", - usage = "/jail status" - ) + maxArgs = 0, + minimumArgs = 0, + needsPlayer = true, + pattern = "status|s", + permission = "jail.usercmd.jailstatus", + usage = "/jail status" + ) public class JailStatusCommand implements Command{ - - public boolean execute(JailManager jm, CommandSender sender, String... args) { - Player pl = (Player) sender; - - if(jm.isPlayerJailed(pl.getUniqueId())) { - Prisoner p = jm.getPrisoner(pl.getUniqueId()); - //They are jailed, so let's tell them some information - sender.sendMessage(Lang.STATUS.get(new String[] { p.getReason(), p.getJailer(), String.valueOf(p.getRemainingTimeInMinutes()) })); - }else { - //the sender of the command is not jailed, tell them that - sender.sendMessage(Lang.YOUARENOTJAILED.get()); - } - - return true; - } + + public boolean execute(JailManager jm, CommandSender sender, String... args) { + Player pl = (Player) sender; + + if(jm.isPlayerJailed(pl.getUniqueId())) { + Prisoner p = jm.getPrisoner(pl.getUniqueId()); + //They are jailed, so let's tell them some information + sender.sendMessage(Lang.STATUS.get(new String[] { p.getReason(), p.getJailer(), String.valueOf(p.getRemainingTimeInMinutes()) })); + }else { + //the sender of the command is not jailed, tell them that + sender.sendMessage(Lang.YOUARENOTJAILED.get()); + } + + return true; + } } diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailStickCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailStickCommand.java index 797adb8..6699151 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailStickCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailStickCommand.java @@ -10,27 +10,27 @@ import com.graywolf336.jail.enums.Lang; import com.graywolf336.jail.enums.Settings; @CommandInfo( - maxArgs = 0, - minimumArgs = 0, - needsPlayer = true, - pattern = "stick", - permission = "jail.usercmd.jailstick", - usage = "/jail stick" - ) + maxArgs = 0, + minimumArgs = 0, + needsPlayer = true, + pattern = "stick", + permission = "jail.usercmd.jailstick", + usage = "/jail stick" + ) public class JailStickCommand implements Command { - public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { - if(jm.getPlugin().getConfig().getBoolean(Settings.JAILSTICKENABLED.getPath())) { - boolean using = jm.getPlugin().getJailStickManager().toggleUsingStick(((Player) sender).getUniqueId()); - - if(using) { - sender.sendMessage(Lang.JAILSTICKENABLED.get()); - }else { - sender.sendMessage(Lang.JAILSTICKDISABLED.get()); - } - }else { - sender.sendMessage(Lang.JAILSTICKUSAGEDISABLED.get()); - } - - return true; - } + public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { + if(jm.getPlugin().getConfig().getBoolean(Settings.JAILSTICKENABLED.getPath())) { + boolean using = jm.getPlugin().getJailStickManager().toggleUsingStick(((Player) sender).getUniqueId()); + + if(using) { + sender.sendMessage(Lang.JAILSTICKENABLED.get()); + }else { + sender.sendMessage(Lang.JAILSTICKDISABLED.get()); + } + }else { + sender.sendMessage(Lang.JAILSTICKUSAGEDISABLED.get()); + } + + return true; + } } diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailStopCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailStopCommand.java index 1dbbe56..9a9fa71 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailStopCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailStopCommand.java @@ -8,33 +8,33 @@ import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.CommandInfo; @CommandInfo( - maxArgs = 0, - minimumArgs = 0, - needsPlayer = true, - pattern = "stop", - permission = "jail.command.jailstop", - usage = "/jail stop" - ) + maxArgs = 0, + minimumArgs = 0, + needsPlayer = true, + pattern = "stop", + permission = "jail.command.jailstop", + usage = "/jail stop" + ) public class JailStopCommand implements Command { - public boolean execute(JailManager jm, CommandSender sender, String... args) { - boolean nothing = true; - - if(jm.isCreatingACell(sender.getName())) { - jm.removeCellCreationPlayer(sender.getName()); - sender.sendMessage(ChatColor.RED + "You have stopped creating cells."); - nothing = false; - } - - if(jm.isCreatingAJail(sender.getName())) { - jm.removeJailCreationPlayer(sender.getName()); - sender.sendMessage(ChatColor.RED + "You have stopped creating a jail."); - nothing = false; - } - - if(nothing) { - sender.sendMessage(ChatColor.RED + "You've stopped creating....nothing."); - } - - return true; - } + public boolean execute(JailManager jm, CommandSender sender, String... args) { + boolean nothing = true; + + if(jm.isCreatingACell(sender.getName())) { + jm.removeCellCreationPlayer(sender.getName()); + sender.sendMessage(ChatColor.RED + "You have stopped creating cells."); + nothing = false; + } + + if(jm.isCreatingAJail(sender.getName())) { + jm.removeJailCreationPlayer(sender.getName()); + sender.sendMessage(ChatColor.RED + "You have stopped creating a jail."); + nothing = false; + } + + if(nothing) { + sender.sendMessage(ChatColor.RED + "You've stopped creating....nothing."); + } + + return true; + } } \ No newline at end of file diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailTeleInCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailTeleInCommand.java index a207cca..d50adc5 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailTeleInCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailTeleInCommand.java @@ -10,45 +10,45 @@ import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Lang; @CommandInfo( - maxArgs = 2, - minimumArgs = 1, - needsPlayer = false, - pattern = "telein|teleportin", - permission = "jail.command.jailtelein", - usage = "/jail telein [jail] (name)" - ) + maxArgs = 2, + minimumArgs = 1, + needsPlayer = false, + pattern = "telein|teleportin", + permission = "jail.command.jailtelein", + usage = "/jail telein [jail] (name)" + ) public class JailTeleInCommand implements Command { - public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { - Jail j = jm.getJail(args[1]); - - //The jail doesn't exist - if(j == null) { - sender.sendMessage(Lang.NOJAIL.get(args[1])); - }else { - //The jail does exist - //now let's check the size of the command - //if it has two args then someone is sending someone else in - //otherwise it is just the sender going in - if(args.length == 3) { - Player p = jm.getPlugin().getServer().getPlayer(args[2]); - - //If the player they're trying to send is offline, don't do anything - if(p == null) { - sender.sendMessage(Lang.PLAYERNOTONLINE.get(args[2])); - }else { - p.teleport(j.getTeleportIn()); - sender.sendMessage(Lang.TELEIN.get(new String[] { args[2], args[1] })); - } - }else { - if(sender instanceof Player) { - ((Player) sender).teleport(j.getTeleportIn()); - sender.sendMessage(Lang.TELEIN.get(new String[] { sender.getName(), args[1] })); - }else { - sender.sendMessage(Lang.PLAYERCONTEXTREQUIRED.get()); - } - } - } - - return true; - } + public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { + Jail j = jm.getJail(args[1]); + + //The jail doesn't exist + if(j == null) { + sender.sendMessage(Lang.NOJAIL.get(args[1])); + }else { + //The jail does exist + //now let's check the size of the command + //if it has two args then someone is sending someone else in + //otherwise it is just the sender going in + if(args.length == 3) { + Player p = jm.getPlugin().getServer().getPlayer(args[2]); + + //If the player they're trying to send is offline, don't do anything + if(p == null) { + sender.sendMessage(Lang.PLAYERNOTONLINE.get(args[2])); + }else { + p.teleport(j.getTeleportIn()); + sender.sendMessage(Lang.TELEIN.get(new String[] { args[2], args[1] })); + } + }else { + if(sender instanceof Player) { + ((Player) sender).teleport(j.getTeleportIn()); + sender.sendMessage(Lang.TELEIN.get(new String[] { sender.getName(), args[1] })); + }else { + sender.sendMessage(Lang.PLAYERCONTEXTREQUIRED.get()); + } + } + } + + return true; + } } diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailTeleOutCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailTeleOutCommand.java index 76cb65f..846680d 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailTeleOutCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailTeleOutCommand.java @@ -10,45 +10,45 @@ import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Lang; @CommandInfo( - maxArgs = 2, - minimumArgs = 1, - needsPlayer = false, - pattern = "teleout|teleportout", - permission = "jail.command.jailteleout", - usage = "/jail teleout [jail] (name)" - ) + maxArgs = 2, + minimumArgs = 1, + needsPlayer = false, + pattern = "teleout|teleportout", + permission = "jail.command.jailteleout", + usage = "/jail teleout [jail] (name)" + ) public class JailTeleOutCommand implements Command { - public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { - Jail j = jm.getJail(args[1]); - - //The jail doesn't exist - if(j == null) { - sender.sendMessage(Lang.NOJAIL.get(args[1])); - }else { - //The jail does exist - //now let's check the size of the command - //if it has two args then someone is sending someone else in - //otherwise it is just the sender going in - if(args.length == 3) { - Player p = jm.getPlugin().getServer().getPlayer(args[2]); - - //If the player they're trying to send is offline, don't do anything - if(p == null) { - sender.sendMessage(Lang.PLAYERNOTONLINE.get(args[2])); - }else { - p.teleport(j.getTeleportFree()); - sender.sendMessage(Lang.TELEOUT.get(new String[] { args[2], args[1] })); - } - }else { - if(sender instanceof Player) { - ((Player) sender).teleport(j.getTeleportFree()); - sender.sendMessage(Lang.TELEOUT.get(new String[] { sender.getName(), args[1] })); - }else { - sender.sendMessage(Lang.PLAYERCONTEXTREQUIRED.get()); - } - } - } - - return true; - } + public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { + Jail j = jm.getJail(args[1]); + + //The jail doesn't exist + if(j == null) { + sender.sendMessage(Lang.NOJAIL.get(args[1])); + }else { + //The jail does exist + //now let's check the size of the command + //if it has two args then someone is sending someone else in + //otherwise it is just the sender going in + if(args.length == 3) { + Player p = jm.getPlugin().getServer().getPlayer(args[2]); + + //If the player they're trying to send is offline, don't do anything + if(p == null) { + sender.sendMessage(Lang.PLAYERNOTONLINE.get(args[2])); + }else { + p.teleport(j.getTeleportFree()); + sender.sendMessage(Lang.TELEOUT.get(new String[] { args[2], args[1] })); + } + }else { + if(sender instanceof Player) { + ((Player) sender).teleport(j.getTeleportFree()); + sender.sendMessage(Lang.TELEOUT.get(new String[] { sender.getName(), args[1] })); + }else { + sender.sendMessage(Lang.PLAYERCONTEXTREQUIRED.get()); + } + } + } + + return true; + } } diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailTimeCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailTimeCommand.java index d8c00e1..cd644cf 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailTimeCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailTimeCommand.java @@ -10,44 +10,44 @@ import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Lang; @CommandInfo( - maxArgs = 3, - minimumArgs = 2, - needsPlayer = false, - pattern = "time|t", - permission = "jail.command.jailtime", - usage = "/jail time [add|remove|show] [name]