From d5296c43148d5a622f7ec8ceb00f550ddc9204eb Mon Sep 17 00:00:00 2001 From: EpicKnarvik97 Date: Thu, 21 Oct 2021 15:13:55 +0200 Subject: [PATCH] Improves formatting, removes broken comments and updates version to 1.17 --- pom.xml | 141 +---- .../com/graywolf336/jail/HandCuffManager.java | 40 +- .../java/com/graywolf336/jail/JailIO.java | 293 +++++----- .../java/com/graywolf336/jail/JailMain.java | 177 +++--- .../com/graywolf336/jail/JailManager.java | 347 ++++++------ .../com/graywolf336/jail/JailPayManager.java | 60 +- .../graywolf336/jail/JailStickManager.java | 51 +- .../java/com/graywolf336/jail/JailTimer.java | 100 ++-- .../com/graywolf336/jail/JailVoteManager.java | 150 ++--- .../java/com/graywolf336/jail/JailsAPI.java | 10 +- .../com/graywolf336/jail/PrisonerManager.java | 440 +++++++-------- .../graywolf336/jail/ScoreBoardManager.java | 63 +-- .../java/com/graywolf336/jail/Update.java | 49 +- src/main/java/com/graywolf336/jail/Util.java | 184 +++--- .../com/graywolf336/jail/beans/AnyCell.java | 40 +- .../graywolf336/jail/beans/CachePrisoner.java | 12 +- .../java/com/graywolf336/jail/beans/Cell.java | 102 ++-- .../graywolf336/jail/beans/ConfirmPlayer.java | 18 +- .../jail/beans/CreationPlayer.java | 105 ++-- .../java/com/graywolf336/jail/beans/Jail.java | 258 +++++---- .../com/graywolf336/jail/beans/JailVote.java | 65 ++- .../com/graywolf336/jail/beans/NoCell.java | 14 +- .../com/graywolf336/jail/beans/Prisoner.java | 232 +++++--- .../jail/beans/SimpleLocation.java | 56 +- .../com/graywolf336/jail/beans/Stick.java | 28 +- .../com/graywolf336/jail/command/Command.java | 27 +- .../jail/command/CommandHandler.java | 108 ++-- .../graywolf336/jail/command/CommandInfo.java | 39 +- .../graywolf336/jail/command/JailHandler.java | 152 +++-- .../command/commands/HandCuffCommand.java | 46 +- .../commands/ToggleJailDebugCommand.java | 15 +- .../command/commands/UnHandCuffCommand.java | 40 +- .../jail/command/commands/UnJailCommand.java | 49 +- .../command/commands/UnJailForceCommand.java | 39 +- .../jail/command/commands/jewels/Jailing.java | 67 ++- .../command/commands/jewels/Transfer.java | 20 +- .../command/subcommands/JailCheckCommand.java | 51 +- .../command/subcommands/JailClearCommand.java | 43 +- .../jail/command/subcommands/JailCommand.java | 217 ++++--- .../subcommands/JailConfirmCommand.java | 27 +- .../subcommands/JailCreateCellCommand.java | 45 +- .../subcommands/JailCreateCommand.java | 33 +- .../subcommands/JailDeleteCellCommand.java | 41 +- .../subcommands/JailDeleteCellsCommand.java | 17 +- .../subcommands/JailDeleteCommand.java | 17 +- .../command/subcommands/JailHelpCommand.java | 17 +- .../subcommands/JailListCellsCommand.java | 35 +- .../command/subcommands/JailListCommand.java | 41 +- .../command/subcommands/JailMuteCommand.java | 47 +- .../command/subcommands/JailPayCommand.java | 170 +++--- .../subcommands/JailRecordCommand.java | 25 +- .../subcommands/JailReloadCommand.java | 17 +- .../command/subcommands/JailSignsCommand.java | 87 ++- .../subcommands/JailStatusCommand.java | 23 +- .../command/subcommands/JailStickCommand.java | 25 +- .../command/subcommands/JailStopCommand.java | 21 +- .../subcommands/JailTeleInCommand.java | 56 +- .../subcommands/JailTeleOutCommand.java | 56 +- .../command/subcommands/JailTimeCommand.java | 61 +- .../subcommands/JailTransferAllCommand.java | 47 +- .../subcommands/JailTransferCommand.java | 138 ++--- .../subcommands/JailVersionCommand.java | 13 +- .../command/subcommands/JailVoteCommand.java | 106 ++-- .../graywolf336/jail/enums/Confirmation.java | 22 +- .../jail/enums/JailVoteResult.java | 36 +- .../java/com/graywolf336/jail/enums/Lang.java | 528 +++++++++++++----- .../com/graywolf336/jail/enums/Settings.java | 19 +- .../jail/events/JailPluginReloadedEvent.java | 19 +- .../events/OfflinePrisonerJailedEvent.java | 53 +- .../PrePrisonerJailedByJailStickEvent.java | 91 +-- .../jail/events/PrePrisonerJailedEvent.java | 101 ++-- .../jail/events/PrePrisonerReleasedEvent.java | 55 +- .../events/PrePrisonerTransferredEvent.java | 102 ++-- .../jail/events/PrisonerDeathEvent.java | 59 +- .../jail/events/PrisonerJailedEvent.java | 65 ++- .../jail/events/PrisonerReleasedEvent.java | 55 +- .../jail/events/PrisonerTimeChangeEvent.java | 104 ++-- .../jail/events/PrisonerTransferredEvent.java | 82 +-- .../AsyncUnJailingNotSupportedException.java | 6 +- .../exceptions/CellRequiredException.java | 9 +- .../exceptions/JailRequiredException.java | 9 +- .../PrisonerAlreadyJailedException.java | 12 +- .../exceptions/PrisonerRequiredException.java | 9 +- .../graywolf336/jail/interfaces/ICell.java | 99 ++-- .../jail/interfaces/IJailPayManager.java | 78 ++- .../jail/interfaces/IJailStickManager.java | 56 +- .../jail/listeners/CacheListener.java | 38 +- .../jail/listeners/CellSignListener.java | 45 +- .../jail/listeners/EntityListener.java | 21 +- .../jail/listeners/HandCuffListener.java | 43 +- .../jail/listeners/JailingListener.java | 167 +++--- .../listeners/MoveProtectionListener.java | 43 +- .../jail/listeners/PlayerListener.java | 191 +++---- .../jail/listeners/ProtectionListener.java | 161 +++--- .../jail/listeners/WorldListener.java | 19 +- .../jail/steps/CellCreationSteps.java | 74 +-- .../jail/steps/JailCreationSteps.java | 53 +- src/main/resources/plugin.yml | 4 +- .../com/graywolf336/jail/BenchmarkTest.java | 90 --- .../com/graywolf336/jail/TestJailAPI.java | 99 ---- .../graywolf336/jail/TestJailCommandInfo.java | 211 ------- .../graywolf336/jail/TestJailCommands.java | 85 --- .../jail/TestJailDefaultConfig.java | 174 ------ .../graywolf336/jail/TestJailLanguage.java | 186 ------ .../com/graywolf336/jail/TestJailVote.java | 213 ------- .../com/graywolf336/jail/TestUtilClass.java | 176 ------ .../jail/util/MockWorldFactory.java | 215 ------- .../jail/util/TestInstanceCreator.java | 426 -------------- .../jail/util/TestLogFormatter.java | 32 -- .../java/com/graywolf336/jail/util/Util.java | 52 -- 110 files changed, 4038 insertions(+), 5562 deletions(-) delete mode 100644 src/test/java/test/java/com/graywolf336/jail/BenchmarkTest.java delete mode 100644 src/test/java/test/java/com/graywolf336/jail/TestJailAPI.java delete mode 100644 src/test/java/test/java/com/graywolf336/jail/TestJailCommandInfo.java delete mode 100644 src/test/java/test/java/com/graywolf336/jail/TestJailCommands.java delete mode 100644 src/test/java/test/java/com/graywolf336/jail/TestJailDefaultConfig.java delete mode 100644 src/test/java/test/java/com/graywolf336/jail/TestJailLanguage.java delete mode 100644 src/test/java/test/java/com/graywolf336/jail/TestJailVote.java delete mode 100644 src/test/java/test/java/com/graywolf336/jail/TestUtilClass.java delete mode 100644 src/test/java/test/java/com/graywolf336/jail/util/MockWorldFactory.java delete mode 100644 src/test/java/test/java/com/graywolf336/jail/util/TestInstanceCreator.java delete mode 100644 src/test/java/test/java/com/graywolf336/jail/util/TestLogFormatter.java delete mode 100644 src/test/java/test/java/com/graywolf336/jail/util/Util.java diff --git a/pom.xml b/pom.xml index ede47c9..0d8e20d 100644 --- a/pom.xml +++ b/pom.xml @@ -10,22 +10,6 @@ Ban too harsh? Mute too weak? Kicking not enough? Jail them! http://dev.bukkit.org/bukkit-plugins/jail/ - - https://ci.craftyn.com/job/Jail/ - jenkins - - - - https://github.com/graywolf336/Jail/issues - GitHub - - - - https://github.com/graywolf336/Jail - scm:git:git://github.com/graywolf336/Jail.git - scm:git:git:@github.com/graywolf336/Jail.git - - 0 UTF-8 @@ -48,40 +32,31 @@ - gray-snapshot - https://repo.craftyn.com/repository/graywolf336-snapshots/ + jitpack.io + https://jitpack.io - org.bukkit - bukkit - 1.13.2-R0.1-SNAPSHOT - jar - - - - org.bukkit - craftbukkit - 1.13.2-R0.1-SNAPSHOT - jar + org.spigotmc + spigot-api + 1.17.1-R0.1-SNAPSHOT provided com.sk89q.worldedit worldedit-bukkit - 7.0.0-SNAPSHOT + 7.2.6 provided true - net.milkbowl.vault - Vault - 1.5.6 - jar + com.github.MilkBowl + VaultAPI + 1.7 provided true @@ -96,31 +71,7 @@ junit junit - 4.13.1 - - - org.powermock - powermock-module-junit4 - 1.5.5 - test - - - org.powermock - powermock-api-easymock - 1.5.5 - test - - - org.powermock - powermock-api-mockito - 1.5.5 - test - - - org.easymock - easymock - 3.2 - test + 4.13.2 com.carrotsearch @@ -128,6 +79,12 @@ 0.7.2 test + + org.spigotmc + spigot + 1.17.1-R0.1-SNAPSHOT + test + @@ -143,26 +100,6 @@ ${env.BUILD_NUMBER} - - - doclint-java8-disable - - [1.8,) - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.10.3 - - -Xdoclint:none - - - - - @@ -201,10 +138,10 @@ org.apache.maven.plugins maven-compiler-plugin - 2.3.2 + 3.8.1 - 1.8 - 1.8 + 16 + 16 @@ -236,7 +173,7 @@ org.apache.maven.plugins maven-jar-plugin - 2.3.1 + 3.2.0 @@ -247,7 +184,7 @@ org.apache.maven.plugins maven-shade-plugin - 2.2 + 3.2.4 package @@ -294,42 +231,6 @@ - - - org.apache.maven.plugins - maven-surefire-plugin - 2.11 - - - ${surefireArgLine} - methods - 10 - - **/TestCommandSender.java - **/TestInstanceCreator.java - - - - - org.apache.maven.surefire - surefire-junit47 - 2.11 - - - - - - - repo-release - Jail Releases - https://repo.craftyn.com/repository/internal/ - - - repo-snapshot - Jail Snapshots - https://repo.craftyn.com/repository/snapshots/ - - \ No newline at end of file diff --git a/src/main/java/com/graywolf336/jail/HandCuffManager.java b/src/main/java/com/graywolf336/jail/HandCuffManager.java index 39b50c8..c32fd02 100644 --- a/src/main/java/com/graywolf336/jail/HandCuffManager.java +++ b/src/main/java/com/graywolf336/jail/HandCuffManager.java @@ -1,44 +1,46 @@ package com.graywolf336.jail; +import org.bukkit.Location; + import java.util.HashMap; import java.util.UUID; -import org.bukkit.Location; - /** * Manages the handcuffing of players. - * + * *

 

- * + *

* Provides easy to use methods for adding, * removing, and checking if someone has * handcuffs. - * + * *

- * + * * @author graywolf336 - * @since 2.6.3 * @version 1.0.2 + * @since 2.6.3 */ public class HandCuffManager { - private HashMap handcuffed; - private HashMap locs; + private final HashMap handcuffed; + private final HashMap locs; - /** Constructs a new HandCuff Manager, for handling all the handcuffing. */ + /** + * Constructs a new HandCuff Manager, for handling all the handcuffing. + */ protected HandCuffManager() { - this.handcuffed = new HashMap(); - this.locs = new HashMap(); + this.handcuffed = new HashMap<>(); + this.locs = new HashMap<>(); } /** * Adds handcuffs to a player. - * - * @param uuid of the 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) { @@ -48,7 +50,7 @@ public class HandCuffManager { /** * Removes the handcuffs from the given player. - * + * * @param uuid of the person to remove the handcuffs from */ public void removeHandCuffs(UUID uuid) { @@ -58,7 +60,7 @@ public class HandCuffManager { /** * Gets if the player is handcuffed or not. - * + * * @param uuid of the player to check * @return true if they are handcuffed, false if not */ @@ -68,7 +70,7 @@ public class HandCuffManager { /** * 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 */ @@ -78,7 +80,7 @@ public class HandCuffManager { /** * 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) { @@ -87,7 +89,7 @@ public class HandCuffManager { /** * 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 */ diff --git a/src/main/java/com/graywolf336/jail/JailIO.java b/src/main/java/com/graywolf336/jail/JailIO.java index bdea4fd..dc9a6be 100644 --- a/src/main/java/com/graywolf336/jail/JailIO.java +++ b/src/main/java/com/graywolf336/jail/JailIO.java @@ -1,8 +1,18 @@ package com.graywolf336.jail; +import com.graywolf336.jail.beans.Cell; +import com.graywolf336.jail.beans.Jail; +import com.graywolf336.jail.beans.Prisoner; +import com.graywolf336.jail.beans.SimpleLocation; +import com.graywolf336.jail.enums.Lang; +import com.graywolf336.jail.enums.Settings; +import org.bukkit.Location; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + import java.io.File; -import java.io.InputStreamReader; import java.io.IOException; +import java.io.InputStreamReader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; @@ -15,27 +25,15 @@ import java.util.List; import java.util.Set; import java.util.UUID; -import org.bukkit.Location; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; - -import com.graywolf336.jail.beans.Cell; -import com.graywolf336.jail.beans.Jail; -import com.graywolf336.jail.beans.Prisoner; -import com.graywolf336.jail.beans.SimpleLocation; -import com.graywolf336.jail.enums.Lang; -import com.graywolf336.jail.enums.Settings; - /** * Handles all the saving and loading of the plugin's data. * * @author graywolf336 - * @since 2.x.x * @version 3.0.0 - * + * @since 2.x.x */ public class JailIO { - private JailMain pl; + private final JailMain pl; private FileConfiguration flat, records; private Connection con; private int storage = -1; //0 = flatfile, 1 = sqlite, 2 = mysql @@ -46,24 +44,26 @@ public class JailIO { this.pl = plugin; } - /** Loads the language file from disk, if there is none then we save the default one. */ + /** + * Loads the language file from disk, if there is none then we save the default one. + */ protected void loadLanguage() { String language = pl.getConfig().getString(Settings.LANGUAGE.getPath()); boolean save = false; File langFile = new File(pl.getDataFolder() + File.separator + "locales", language + ".yml"); //File or folder already exists, let's check - if(langFile.exists()) { - if(langFile.isFile()) { + if (langFile.exists()) { + if (langFile.isFile()) { Lang.setFile(YamlConfiguration.loadConfiguration(langFile)); pl.getLogger().info("Loaded the language: " + language); - }else { + } 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(new InputStreamReader(pl.getResource("locales/en.yml")))); save = true; } - }else { + } 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(new InputStreamReader(pl.getResource("locales/en.yml")))); @@ -71,10 +71,11 @@ public class JailIO { } //Make sure we have all the new language settings loaded - if(!save) save = Lang.writeNewLanguage(YamlConfiguration.loadConfiguration(new InputStreamReader(pl.getResource("locales/en.yml")))); + if (!save) + save = Lang.writeNewLanguage(YamlConfiguration.loadConfiguration(new InputStreamReader(pl.getResource("locales/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) { + if (save) { try { Lang.getFile().save(new File(pl.getDataFolder() + File.separator + "locales", "en.yml")); } catch (IOException e) { @@ -85,7 +86,7 @@ public class JailIO { /** * Prepares the storage engine to be used, returns true if everything went good. - * + * * @param doInitialCreations whether to do the initial creations (database tables or files) * @return Whether it was successful or not */ @@ -93,38 +94,38 @@ public class JailIO { int inital = storage == -1 ? -1 : storage; String st = pl.getConfig().getString("storage.type", "flatfile"); - if(st.equalsIgnoreCase("sqlite")) { + if (st.equalsIgnoreCase("sqlite")) { storage = 1; prefix = pl.getConfig().getString("storage.mysql.prefix"); - }else if(st.equalsIgnoreCase("mysql")) { + } else if (st.equalsIgnoreCase("mysql")) { storage = 2; prefix = pl.getConfig().getString("storage.mysql.prefix"); - }else { + } else { storage = 0; } //Determine if we changed storage types midstream //this way we can know whether to save EVERYTHING //or not afterwards - if(inital != -1 && inital != storage) { + if (inital != -1 && inital != storage) { pl.debug("We changed storage types! We used to be " + inital + " and changed to " + storage + "."); changed = true; } pl.debug("The storage type " + st + " with the type being " + storage + "."); - if(!pl.inDebug()) pl.getLogger().info("Storage type selected: " + st); + if (!pl.inDebug()) pl.getLogger().info("Storage type selected: " + st); - switch(storage) { + 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()); + 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."); - if(doInitialCreations) createTables(); + if (doInitialCreations) createTables(); } catch (ClassNotFoundException e) { e.printStackTrace(); pl.getLogger().severe("---------- Jail Error!!! ----------"); @@ -149,8 +150,8 @@ public class JailIO { this.con = mysqlConnection; pl.debug("Connection created for MySQL."); - if(doInitialCreations) createTables(); - } catch(ClassNotFoundException e) { + if (doInitialCreations) createTables(); + } catch (ClassNotFoundException e) { e.printStackTrace(); pl.getLogger().severe("---------- Jail Error!!! ----------"); pl.getLogger().severe("MySQL driver not found, disabling the plugin."); @@ -169,7 +170,7 @@ public class JailIO { break; } - if(changed) { + if (changed) { changed = false; this.saveEverything(); } @@ -183,11 +184,11 @@ public class JailIO { * @return The connection for the sql database. */ private Connection getConnection() { - switch(storage) { + switch (storage) { case 1: - if(con == null) this.prepareStorage(false); + if (con == null) this.prepareStorage(false); try { - if(con.isClosed()) this.prepareStorage(false); + if (con.isClosed()) this.prepareStorage(false); } catch (SQLException e) { e.printStackTrace(); pl.getLogger().severe("---------- Jail Error!!! ----------"); @@ -196,9 +197,9 @@ public class JailIO { } return con; case 2: - if(con == null) this.prepareStorage(false); + if (con == null) this.prepareStorage(false); try { - if(con.isClosed() || !con.isValid(10)) this.prepareStorage(false); + if (con.isClosed() || !con.isValid(10)) this.prepareStorage(false); } catch (SQLException e) { e.printStackTrace(); pl.getLogger().severe("---------- Jail Error!!! ----------"); @@ -211,13 +212,15 @@ public class JailIO { } } - /** Closes the sql connection. */ + /** + * Closes the sql connection. + */ protected void closeConnection() { - switch(storage) { + switch (storage) { case 1: case 2: try { - if(con != null) { + if (con != null) { con.close(); con = null; @@ -236,14 +239,14 @@ public class JailIO { } private void createTables() { - if(getConnection() == null) { + if (getConnection() == null) { pl.debug("The connection was null when we tried to create a table."); return; } try { Statement st = getConnection().createStatement(); - switch(storage){ + switch (storage) { case 1: String sqlJailCreateCmd = "CREATE TABLE IF NOT EXISTS `" + prefix + "jails` (" + "`name` VARCHAR PRIMARY KEY NOT NULL," @@ -418,7 +421,7 @@ public class JailIO { * Loads the jails, this should only be called after {@link #prepareStorage(boolean)}. */ protected void loadJails() { - switch(storage) { + switch (storage) { case 1: case 2: //load the jails from mysql and sqlite @@ -428,12 +431,12 @@ public class JailIO { PreparedStatement ps = getConnection().prepareStatement("SELECT * FROM " + prefix + "jails"); ResultSet set = ps.executeQuery(); - while(set.next()) { + 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.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"))); @@ -455,27 +458,27 @@ public class JailIO { //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(); + List cellsToRemove = new LinkedList<>(); try { PreparedStatement ps = getConnection().prepareStatement("SELECT * FROM " + prefix + "cells"); ResultSet set = ps.executeQuery(); - while(set.next()) { + while (set.next()) { Jail j = pl.getJailManager().getJail(set.getString("jail")); - if(j != null) { - if(j.getWorld() != null) { + if (j != null) { + if (j.getWorld() != null) { Cell c = new Cell(set.getInt("cellid"), set.getString("name")); - c.setTeleport(new SimpleLocation(j.getWorldName(), set.getDouble("tp.x"), set.getDouble("tp.y"), set.getDouble("tp.z"), + 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 SimpleLocation(j.getWorldName(), set.getInt("chest.x"), set.getInt("chest.y"), set.getInt("chest.z"))); String cSigns = set.getString("signs"); - if(!cSigns.isEmpty()) { + if (!cSigns.isEmpty()) { String[] signs = cSigns.split(";"); - for(String s : signs) { + for (String s : signs) { String[] co = s.split(","); c.addSign(new SimpleLocation(co[0], co[1], co[2], co[3])); } @@ -488,15 +491,15 @@ public class JailIO { //if this method returns false then //the cell already exists and needs //to be removed from the database - if(!j.addCell(c, false)) { + if (!j.addCell(c, false)) { int id = set.getInt("cellid"); cellsToRemove.add(id); pl.debug("The cell, " + c.getName() + " (" + id + "), is already in jail " + j.getName() + " so we're removing it."); } - }else { + } else { pl.getLogger().warning("The cell, " + set.getString("name") + ", in " + j.getName() + " is located in a world that is not loaded."); } - }else { + } else { cellsToRemove.add(set.getInt("cellid")); } } @@ -512,17 +515,17 @@ public class JailIO { } //Remove the invalid prisoners - if(!cellsToRemove.isEmpty()) { + if (!cellsToRemove.isEmpty()) { StringBuilder ids = new StringBuilder(); - for(int c : cellsToRemove) { - if(ids.length() == 0) ids.append("'" + c + "'"); - else ids.append("," + "'" + c + "'"); + for (int c : cellsToRemove) { + if (ids.length() == 0) ids.append("'").append(c).append("'"); + else ids.append("," + "'").append(c).append("'"); } try { - PreparedStatement cds = getConnection().prepareStatement("delete from " + prefix + "cells where cellid in (" + ids.toString() + ");"); + PreparedStatement cds = getConnection().prepareStatement("delete from " + prefix + "cells where cellid in (" + ids + ");"); - pl.debug("Deleting old cells: `delete from " + prefix + "cells where cellid in (" + ids.toString() + ");`"); + pl.debug("Deleting old cells: `delete from " + prefix + "cells where cellid in (" + ids + ");`"); int count = cds.executeUpdate(); pl.getLogger().info("Deleted " + count + " cells which were invalid, they either referenced a jail which are no longer valid or were duplicates."); @@ -537,16 +540,16 @@ public class JailIO { //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(); + List prisonersToRemove = new LinkedList<>(); try { PreparedStatement ps = getConnection().prepareStatement("SELECT * FROM " + prefix + "prisoners"); ResultSet set = ps.executeQuery(); - while(set.next()) { + while (set.next()) { Jail j = pl.getJailManager().getJail(set.getString("jail")); - if(j != null) { + if (j != null) { String cellname = set.getString("cell"); Cell c = j.getCell(cellname); @@ -559,12 +562,12 @@ public class JailIO { 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()) { + if (cellname == null || cellname.isEmpty()) { j.addPrisoner(p); - }else if(c != null) { + } else if (c != null) { c.setPrisoner(p); c.setChanged(false); - }else { + } else { //the prisoner is assigned to a cell which doesn't exist, so just put them into the jail j.addPrisoner(p); } @@ -585,11 +588,11 @@ public class JailIO { } //Remove the invalid prisoners - if(!prisonersToRemove.isEmpty()) { - String names = ""; - for(String s : prisonersToRemove) { - if(names.isEmpty()) names = "'" + s + "'"; - else names += "," + "'" + s + "'"; + if (!prisonersToRemove.isEmpty()) { + StringBuilder names = new StringBuilder(); + for (String s : prisonersToRemove) { + if (names.length() == 0) names = new StringBuilder("'" + s + "'"); + else names.append("," + "'").append(s).append("'"); } try { @@ -611,10 +614,10 @@ public class JailIO { break; default: //load the jails from flatfile - if(flat.isConfigurationSection("jails")) { + if (flat.isConfigurationSection("jails")) { Set jails = flat.getConfigurationSection("jails").getKeys(false); - if(!jails.isEmpty()) { - for(String name : jails) { + if (!jails.isEmpty()) { + for (String name : jails) { loadJailFromFlatFile(name); } } @@ -638,14 +641,14 @@ public class JailIO { pl.debug("Loading the jail " + name + "; " + node + "; " + cNode); Jail j = new Jail(pl, name); - if(flat.getString(node + "world") == null || flat.getString(node + "world").isEmpty()) { + if (flat.getString(node + "world") == null || flat.getString(node + "world").isEmpty()) { pl.getLogger().severe("Failed to load the jail, " + name + ", because the world is not set."); return; } 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.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(j.getWorldName()), @@ -662,10 +665,10 @@ public class JailIO { (float) flat.getDouble(node + "tps.free.yaw"), (float) flat.getDouble(node + "tps.free.pitch"))); - if(flat.isConfigurationSection(node + "cells")) { + if (flat.isConfigurationSection(node + "cells")) { Set cells = flat.getConfigurationSection(node + "cells").getKeys(false); - if(!cells.isEmpty()) { - for(String cell : cells) { + if (!cells.isEmpty()) { + for (String cell : cells) { Cell c = new Cell(cell); String cellNode = cNode + cell + "."; @@ -680,17 +683,17 @@ public class JailIO { flat.getInt(cellNode + "chest.y"), flat.getInt(cellNode + "chest.z"))); - for(String sign : flat.getStringList(cellNode + "signs")) { + 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]))); + Double.parseDouble(arr[1]), + Double.parseDouble(arr[2]), + Double.parseDouble(arr[3]), + Float.parseFloat(arr[4]), + Float.parseFloat(arr[5]))); } - if(flat.contains(cellNode + "prisoner")) { + if (flat.contains(cellNode + "prisoner")) { Prisoner p = new Prisoner(flat.getString(cellNode + "prisoner.uuid"), flat.getString(cellNode + "prisoner.name"), flat.getBoolean(cellNode + "prisoner.muted"), @@ -713,10 +716,10 @@ public class JailIO { } } - if(flat.isConfigurationSection(node + "prisoners")) { + if (flat.isConfigurationSection(node + "prisoners")) { Set prisoners = flat.getConfigurationSection(node + "prisoners").getKeys(false); - if(!prisoners.isEmpty()) { - for(String uuid : prisoners) { + if (!prisoners.isEmpty()) { + for (String uuid : prisoners) { String pNode = node + "prisoners." + uuid + "."; Prisoner pris = new Prisoner(uuid, flat.getString(pNode + "name"), @@ -741,17 +744,19 @@ public class JailIO { pl.getLogger().info("Loaded jail " + j.getName() + " with " + j.getAllPrisoners().size() + " prisoners and " + j.getCellCount() + " cells" + (j.isEnabled() ? "." : " but the jail is disabled as the world doesn't exist or isn't loaded.")); } - /** Saves everything about a jail, don't usually call this. */ + /** + * Saves everything about a jail, don't usually call this. + */ protected void saveEverything() { long st = System.currentTimeMillis(); - for(Jail j : pl.getJailManager().getJails()) { + for (Jail j : pl.getJailManager().getJails()) { saveJail(j); //Only save the cells individually //when we are not using the flatfile storage - if(storage != 0) { - for(Cell c : j.getCells()) { + if (storage != 0) { + for (Cell c : j.getCells()) { saveCell(j, c, true); } } @@ -766,8 +771,8 @@ public class JailIO { * @param j The jail to save. */ protected void saveJail(Jail j) { - if(j.isEnabled()) { - switch(storage) { + if (j.isEnabled()) { + switch (storage) { case 1: case 2: long st = System.currentTimeMillis(); @@ -808,11 +813,11 @@ public class JailIO { } try { - for(Cell c : j.getCells()) { - if(c.getDatabaseID() != -1) + for (Cell c : j.getCells()) { + if (c.getDatabaseID() != -1) saveCell(j, c, false); - if(c.hasPrisoner() && c.getPrisoner().wasChanged()) { + if (c.hasPrisoner() && c.getPrisoner().wasChanged()) { Prisoner p = c.getPrisoner(); PreparedStatement pPS = getConnection().prepareStatement("REPLACE INTO `" + prefix + "prisoners` (`uuid`, `name`, `jail`, `cell`, `muted`, `time`," + "`offlinePending`, `toBeTransferred`, `jailer`, `reason`, `inventory`, `armor`, `previousLocation`, `previousGameMode`)" @@ -845,8 +850,8 @@ public class JailIO { } try { - for(Prisoner p : j.getPrisonersNotInCells().values()) { - if(p.wasChanged()) { + for (Prisoner p : j.getPrisonersNotInCells().values()) { + if (p.wasChanged()) { PreparedStatement pPS = getConnection().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()); @@ -878,7 +883,7 @@ public class JailIO { pl.debug("Took " + (System.currentTimeMillis() - st) + " millis to save the jail " + j.getName() + "."); break; default: - if(flat != null) { + if (flat != null) { String node = "jails." + j.getName() + "."; //Corners @@ -907,10 +912,10 @@ public class JailIO { //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()) { + for (Cell c : j.getCells()) { String cNode = node + "cells." + c.getName() + "."; - if(c.getTeleport() != null) { + 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()); @@ -918,7 +923,7 @@ public class JailIO { flat.set(cNode + "tp.pitch", c.getTeleport().getPitch()); } - if(c.getChestLocation() != null) { + 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()); @@ -926,14 +931,14 @@ public class JailIO { String[] signs = new String[c.getSigns().size()]; int count = 0; - for(SimpleLocation loc : c.getSigns()) { + for (SimpleLocation loc : c.getSigns()) { signs[count] = loc.toString(); count++; } flat.set(cNode + "signs", signs); - if(c.getPrisoner() != null) { + if (c.getPrisoner() != null) { Prisoner p = c.getPrisoner(); flat.set(cNode + "prisoner.uuid", p.getUUID().toString()); flat.set(cNode + "prisoner.name", p.getLastKnownName()); @@ -945,9 +950,9 @@ public class JailIO { 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) + if (p.getPreviousLocationString() != null) flat.set(cNode + "prisoner.previousLocation", p.getPreviousLocationString()); - if(p.getPreviousGameMode() != null) + if (p.getPreviousGameMode() != null) flat.set(cNode + "prisoner.previousGameMode", p.getPreviousGameMode().toString()); } @@ -956,7 +961,7 @@ public class JailIO { //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()) { + 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()); @@ -967,9 +972,9 @@ public class JailIO { flat.set(pNode + "reason", p.getReason()); flat.set(pNode + "inventory", p.getInventory()); flat.set(pNode + "armor", p.getArmor()); - if(p.getPreviousLocationString() != null) + if (p.getPreviousLocationString() != null) flat.set(pNode + "previousLocation", p.getPreviousLocationString()); - if(p.getPreviousGameMode() != null) + if (p.getPreviousGameMode() != null) flat.set(pNode + "previousGameMode", p.getPreviousGameMode().toString()); } @@ -978,7 +983,7 @@ public class JailIO { } catch (IOException e) { pl.getLogger().severe("Unable to save the Jail data: " + e.getMessage()); } - }else { + } else { pl.getLogger().severe("Storage not enabled, could not save the jail " + j.getName()); } break; @@ -989,9 +994,9 @@ public class JailIO { public void saveCell(Jail j, Cell c, boolean force) { //if the cell hasn't changed, no need to save it again //unless they're forcing the save - if(!c.hasChanged() && !force) return; + if (!c.hasChanged() && !force) return; - switch(storage) { + switch (storage) { case 1: case 2: try { @@ -1017,11 +1022,11 @@ public class JailIO { cPS.setDouble(6, c.getTeleport().getYaw()); cPS.setDouble(7, c.getTeleport().getPitch()); - if(c.useChest()) { + if (c.useChest()) { cPS.setInt(8, c.getChestLocation().getBlockX()); cPS.setInt(9, c.getChestLocation().getBlockY()); cPS.setInt(10, c.getChestLocation().getBlockZ()); - }else { + } else { cPS.setNull(8, java.sql.Types.INTEGER); cPS.setNull(9, java.sql.Types.INTEGER); cPS.setNull(10, java.sql.Types.INTEGER); @@ -1032,7 +1037,7 @@ public class JailIO { cPS.executeUpdate(); cPS.close(); - if(c.hasPrisoner()) { + 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 (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); @@ -1087,7 +1092,7 @@ public class JailIO { * @param p the prisoner data */ protected void removePrisoner(Jail j, Cell c, Prisoner p) { - switch(storage) { + switch (storage) { case 1: case 2: try { @@ -1110,7 +1115,7 @@ public class JailIO { } break; default: - if(c == null) + if (c == null) flat.set("jails." + j.getName() + ".prisoners." + p.getUUID().toString(), null); else flat.set("jails." + j.getName() + ".cells." + c.getName() + ".prisoner", null); @@ -1132,15 +1137,15 @@ public class JailIO { */ public void removeCell(Jail j, Cell c) { //Clear the inventory before we delete it - if(c.hasChest()) c.getChest().getInventory().clear(); + if (c.hasChest()) c.getChest().getInventory().clear(); //transfer the prisoner if it has one - if(c.hasPrisoner()) { + 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) { + switch (storage) { case 1: try { Connection con = getConnection(); @@ -1180,7 +1185,7 @@ public class JailIO { } break; default: - if(flat != null) { + if (flat != null) { flat.set("jails." + j.getName() + ".cells." + c.getName(), null); try { @@ -1203,10 +1208,10 @@ public class JailIO { protected void removeJail(Jail j) { String name = j.getName(); - switch(storage) { + switch (storage) { case 1: case 2: - for(Cell c : j.getCells()) { + for (Cell c : j.getCells()) { removeCell(j, c); } @@ -1244,15 +1249,15 @@ public class JailIO { /** * Adds an entry to the database/file for the user, logging when they was jailed. * - * @param uuid of the player + * @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 + * @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) { + switch (storage) { case 1: break; case 2: @@ -1279,10 +1284,11 @@ public class JailIO { } break; default: - if(records == null) records = YamlConfiguration.loadConfiguration(new File(pl.getDataFolder(), "records.yml")); + 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 })); + previous.add(Lang.RECORDENTRY.get(date, username, jailer, String.valueOf(time), reason, uuid)); records.set(uuid, previous); @@ -1306,9 +1312,9 @@ public class JailIO { */ public List getRecordEntries(String username) { UUID uuid = pl.getServer().getOfflinePlayer(username).getUniqueId(); - List entries = new ArrayList(); + List entries = new ArrayList<>(); - switch(storage) { + switch (storage) { case 1: break; case 2: @@ -1322,8 +1328,8 @@ public class JailIO { 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.getString("uuid") })); + while (set.next()) { + entries.add(Lang.RECORDENTRY.get(set.getString("date"), set.getString("username"), set.getString("jailer"), String.valueOf(set.getLong("time")), set.getString("reason"), set.getString("uuid"))); } set.close(); @@ -1335,7 +1341,8 @@ public class JailIO { } break; default: - if(records == null) records = YamlConfiguration.loadConfiguration(new File(pl.getDataFolder(), "records.yml")); + if (records == null) + records = YamlConfiguration.loadConfiguration(new File(pl.getDataFolder(), "records.yml")); entries = records.getStringList(uuid.toString()); break; diff --git a/src/main/java/com/graywolf336/jail/JailMain.java b/src/main/java/com/graywolf336/jail/JailMain.java index d266a03..c64d840 100644 --- a/src/main/java/com/graywolf336/jail/JailMain.java +++ b/src/main/java/com/graywolf336/jail/JailMain.java @@ -1,15 +1,5 @@ package com.graywolf336.jail; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.event.HandlerList; -import org.bukkit.plugin.PluginManager; -import org.bukkit.plugin.java.JavaPlugin; - import com.graywolf336.jail.beans.Jail; import com.graywolf336.jail.beans.Prisoner; import com.graywolf336.jail.command.CommandHandler; @@ -28,13 +18,22 @@ import com.graywolf336.jail.listeners.MoveProtectionListener; import com.graywolf336.jail.listeners.PlayerListener; import com.graywolf336.jail.listeners.ProtectionListener; import com.graywolf336.jail.listeners.WorldListener; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.event.HandlerList; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.Collections; +import java.util.List; +import java.util.concurrent.TimeUnit; /** * The main class for this Jail plugin, holds instances of vital classes. - * + * * @author graywolf336 - * @since 1.x.x * @version 3.0.0 + * @since 1.x.x */ public class JailMain extends JavaPlugin { private CommandHandler cmdHand; @@ -58,7 +57,7 @@ public class JailMain extends JavaPlugin { loadConfig(); debug = getConfig().getBoolean(Settings.DEBUG.getPath()); - if(debug) getLogger().info("Debugging enabled."); + if (debug) getLogger().info("Debugging enabled."); hcm = new HandCuffManager(); jm = new JailManager(this); @@ -66,7 +65,7 @@ public class JailMain extends JavaPlugin { io.loadLanguage(); //If the prepareStorage returns false, we need to disable the plugin - if(!io.prepareStorage(true)) { + 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; @@ -77,10 +76,10 @@ public class JailMain extends JavaPlugin { cmdHand = new CommandHandler(this); jh = new JailHandler(this); pm = new PrisonerManager(this); - + try { jvm = new JailVoteManager(this); - }catch(Exception e) { + } catch (Exception e) { e.printStackTrace(); getLogger().severe("Failed to load the Jail Vote system, please see the stacktrace above (you probably misconfigured the time)."); } @@ -115,15 +114,15 @@ public class JailMain extends JavaPlugin { } public void onDisable() { - if(jm != null) - for(Jail j : jm.getJails()) + if (jm != null) + for (Jail j : jm.getJails()) io.saveJail(j); - if(jt != null) - if(jt.getTimer() != null) + if (jt != null) + if (jt.getTimer() != null) jt.getTimer().stop(); - if(io != null) + if (io != null) io.closeConnection(); getServer().getScheduler().cancelTasks(this); @@ -168,44 +167,44 @@ public class JailMain extends JavaPlugin { * 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(jh == null || cmdHand == null) { - sender.sendMessage(Lang.PLUGINNOTLOADED.get()); - getServer().getConsoleSender().sendMessage(Lang.PLUGINNOTLOADED.get()); - }else { - if(commandLabel.equalsIgnoreCase("jail") || commandLabel.equalsIgnoreCase("j")) { - jh.parseCommand(jm, sender, args); - }else { + if (jh == null || cmdHand == null) { + sender.sendMessage(Lang.PLUGINNOTLOADED.get()); + getServer().getConsoleSender().sendMessage(Lang.PLUGINNOTLOADED.get()); + } else { + 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. } - + public List onTabComplete(CommandSender sender, Command command, String commandLabel, String[] args) { - if(jh == null || cmdHand == null) { + if (jh == null || cmdHand == null) { sender.sendMessage(Lang.PLUGINNOTLOADED.get()); getServer().getConsoleSender().sendMessage(Lang.PLUGINNOTLOADED.get()); - }else { + } else { debug("Tab Complete Args (" + args.length + ") for '" + commandLabel + "': " + Util.getStringFromArray(", ", args)); try { - if(commandLabel.equalsIgnoreCase("jail") || commandLabel.equalsIgnoreCase("j")) { + if (commandLabel.equalsIgnoreCase("jail") || commandLabel.equalsIgnoreCase("j")) { return jh.parseTabComplete(jm, sender, args); - }else { + } else { return cmdHand.parseTabComplete(jm, sender, command.getName().toLowerCase(), args); } - }catch(Exception e) { - if(this.debug) + } catch (Exception e) { + if (this.debug) e.printStackTrace(); - + debug(e.getClass().getSimpleName() + " occured while providing tab complete: " + e.getMessage()); return Collections.emptyList(); } } - + return Collections.emptyList(); } - + public void reloadEverything() throws Exception { //Reload the configuration file reloadConfig(); @@ -230,37 +229,41 @@ public class JailMain extends JavaPlugin { //if they rely on any of the configuration settings (such as signs) getServer().getPluginManager().callEvent(new JailPluginReloadedEvent(this)); } - - /** Reloads/Loads the move protection listener based upon it's previous status and the config. */ + + /** + * Reloads/Loads the move protection listener based upon it's previous status and the config. + */ private void reloadMoveProtection() { boolean moveProtection = getConfig().getBoolean(Settings.MOVEPROTECTION.getPath()); - + //If move protection is not enabled and it used to be, //unregister it. - if(!moveProtection && this.mpl != null) { + if (!moveProtection && this.mpl != null) { HandlerList.unregisterAll(this.mpl); this.mpl = null; this.debug("The move protection listener is now disabled."); } - + //If it is enabled and it used to not be, then enable it. - if(moveProtection && this.mpl == null) { + if (moveProtection && this.mpl == null) { this.mpl = new MoveProtectionListener(this); getServer().getPluginManager().registerEvents(mpl, this); this.debug("The move protection listener is now enabled."); } } - /** Reloads the scoreboard manager class, useful when something is changed in the config about it. */ + /** + * Reloads the scoreboard manager class, useful when something is changed in the config about it. + */ private 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) { + 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); } } @@ -268,10 +271,12 @@ public class JailMain extends JavaPlugin { } } - /** Reloads the Jail Sticks, so the new ones can be loaded from the config. */ + /** + * Reloads the Jail Sticks, so the new ones can be loaded from the config. + */ private void reloadJailSticks() { - if(getConfig().getBoolean(Settings.JAILSTICKENABLED.getPath())) { - if(this.jsm != null) { + if (getConfig().getBoolean(Settings.JAILSTICKENABLED.getPath())) { + if (this.jsm != null) { this.jsm.removeAllStickUsers(); this.jsm = null; } @@ -280,46 +285,48 @@ public class JailMain extends JavaPlugin { } } - /** Reloads the {@link JailPayManager}. */ + /** + * Reloads the {@link JailPayManager}. + */ private void reloadJailPayManager() { this.jpm = null; - if(getConfig().getBoolean(Settings.JAILPAYENABLED.getPath())) { - if(getServer().getPluginManager().isPluginEnabled("Vault")) { + if (getConfig().getBoolean(Settings.JAILPAYENABLED.getPath())) { + if (getServer().getPluginManager().isPluginEnabled("Vault")) { this.jpm = new JailPayManager(this); - }else { + } else { getConfig().set(Settings.JAILPAYENABLED.getPath(), false); getLogger().severe("Jail Pay couldn't find an economy, disabling Jail Pay."); } } } - - /** Reloads the {@link JailVoteManager}. */ + + /** + * Reloads the {@link JailVoteManager}. + */ private void reloadJailVoteManager() throws Exception { - if(this.jvm != null) { - for(Integer i : this.jvm.getRunningTasks().values()) { + if (this.jvm != null) { + for (Integer i : this.jvm.getRunningTasks().values()) { this.getServer().getScheduler().cancelTask(i); } - + this.jvm.getRunningTasks().clear(); this.jvm.getVotes().clear(); } - + this.jvm = null; this.jvm = new JailVoteManager(this); } - /** Reloads the update checker, in case they changed a setting about it. */ + /** + * Reloads the update checker, in case they changed a setting about it. + */ private void reloadUpdateCheck() { getServer().getScheduler().cancelTask(updateCheckTask); update = new Update(this); - if(getConfig().getBoolean(Settings.UPDATENOTIFICATIONS.getPath())) { + 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(); + updateCheckTask = getServer().getScheduler().runTaskTimerAsynchronously(this, () -> 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."); @@ -329,7 +336,7 @@ public class JailMain extends JavaPlugin { /** * Gets the {@link HandCuffManager} instance. - * + * * @return {@link HandCuffManager} instance */ public HandCuffManager getHandCuffManager() { @@ -338,7 +345,7 @@ public class JailMain extends JavaPlugin { /** * Gets the {@link JailIO} instance. - * + * * @return {@link JailIO} instance */ public JailIO getJailIO() { @@ -347,7 +354,7 @@ public class JailMain extends JavaPlugin { /** * Gets the {@link JailManager} instance. - * + * * @return {@link JailManager} instance */ public JailManager getJailManager() { @@ -356,7 +363,7 @@ public class JailMain extends JavaPlugin { /** * Gets an instance of the {@link IJailPayManager}. - * + * * @return {@link IJailPayManager} */ public IJailPayManager getJailPayManager() { @@ -365,7 +372,7 @@ public class JailMain extends JavaPlugin { /** * Gets the {@link PrisonerManager} instance. - * + * * @return {@link PrisonerManager} instance */ public PrisonerManager getPrisonerManager() { @@ -374,7 +381,7 @@ public class JailMain extends JavaPlugin { /** * Gets an instance of the {@link JailStickManager}. - * + * * @return {@link JailStickManager} */ public IJailStickManager getJailStickManager() { @@ -383,16 +390,16 @@ public class JailMain extends JavaPlugin { /** * Gets the {@link ScoreBoardManager} instance. - * + * * @return {@link ScoreBoardManager} instance */ public ScoreBoardManager getScoreBoardManager() { return this.sbm; } - + /** * Gets the {@link JailVoteManager} instance. - * + * * @return {@link JailVoteManager} instance */ public JailVoteManager getJailVoteManager() { @@ -401,7 +408,7 @@ public class JailMain extends JavaPlugin { /** * Gets the {@link Update} instance. - * + * * @return {@link Update} instance */ public Update getUpdate() { @@ -410,7 +417,7 @@ public class JailMain extends JavaPlugin { /** * Sets whether the plugin is in debugging or not. - * + * * @param debug whether to be in debuggin or not * @return Whether we we debugging or not. */ @@ -426,7 +433,7 @@ public class JailMain extends JavaPlugin { /** * Returns if the plugin is in debug state or not. - * + * * @return Whether we are debugging or not. */ public boolean inDebug() { @@ -435,16 +442,16 @@ public class JailMain extends JavaPlugin { /** * Logs a debugging message to the console if debugging is enabled. - * + * * @param message the item to log as debugging */ public void debug(String message) { - if(inDebug()) getLogger().info("[Debug]: " + 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 */ diff --git a/src/main/java/com/graywolf336/jail/JailManager.java b/src/main/java/com/graywolf336/jail/JailManager.java index 7816ede..9df972f 100644 --- a/src/main/java/com/graywolf336/jail/JailManager.java +++ b/src/main/java/com/graywolf336/jail/JailManager.java @@ -1,18 +1,5 @@ package com.graywolf336.jail; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.UUID; - -import org.bukkit.Location; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.util.StringUtil; - import com.graywolf336.jail.beans.CachePrisoner; import com.graywolf336.jail.beans.Cell; import com.graywolf336.jail.beans.ConfirmPlayer; @@ -23,12 +10,24 @@ import com.graywolf336.jail.enums.Confirmation; import com.graywolf336.jail.enums.Lang; import com.graywolf336.jail.steps.CellCreationSteps; import com.graywolf336.jail.steps.JailCreationSteps; +import org.bukkit.Location; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.UUID; /** * Handles all things related to jails. - * + * + *

*

- * * Stores the following: *

    *
  • The {@link Jail jails}, which contains the prisoners and cells.
  • @@ -36,35 +35,35 @@ import com.graywolf336.jail.steps.JailCreationSteps; *
  • Players creating jail cells, see {@link CreationPlayer}.
  • *
  • An instance of {@link JailCreationSteps} for stepping players through the Jail creation process.
  • *
- * + * * @author graywolf336 - * @since 3.0.0 * @version 1.1.0 + * @since 3.0.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; + private final JailMain plugin; + private final HashMap jails; + private final HashMap jailCreators; + private final HashMap cellCreators; + private final HashMap confirms; + private final HashMap cache; + private final JailCreationSteps jcs; + private final CellCreationSteps ccs; protected 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.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. - * + * * @return {@link JailMain} instance */ public JailMain getPlugin() { @@ -73,66 +72,66 @@ public class JailManager { /** * Returns a HashSet of all the jails. - * + * * @return HashSet of all the jail instances. */ public HashSet getJails() { - return new HashSet(jails.values()); + return new HashSet<>(jails.values()); } /** * Returns an array of all the names of the jails. - * + * * @return Array of the jail names */ public String[] getJailNames() { String[] toReturn = new String[jails.size()]; - + int count = 0; - for(Jail j : this.jails.values()) { + for (Jail j : this.jails.values()) { toReturn[count] = j.getName(); count++; } - + return toReturn; } - + /** * Gets a list of Jail names that start with the provided prefix. - * + * + *

*

- * * If the provided prefix is empty, then we add all of the jails. - * + * * @param prefix The start of the jails to get * @return List of jails that matched the prefix */ public List getJailsByPrefix(String prefix) { - List results = new ArrayList(); - - for(Jail j : this.jails.values()) - if(prefix.isEmpty() || StringUtil.startsWithIgnoreCase(j.getName(), prefix)) + List results = new ArrayList<>(); + + for (Jail j : this.jails.values()) + if (prefix.isEmpty() || StringUtil.startsWithIgnoreCase(j.getName(), prefix)) results.add(j.getName()); - + Collections.sort(results); - + return results; } /** * 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. + * @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().toLowerCase(), jail); - if(n) plugin.getJailIO().saveJail(jail); + if (n) plugin.getJailIO().saveJail(jail); } /** * Removes a {@link Jail}. - * + * * @param name of the jail to remove */ public void removeJail(String name) { @@ -142,12 +141,12 @@ public class JailManager { /** * 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) { - if(name.isEmpty() && jails.isEmpty()) + if (name.isEmpty() && jails.isEmpty()) return null; else return name.isEmpty() ? this.jails.values().iterator().next() : this.jails.get(name.toLowerCase()); @@ -155,20 +154,20 @@ public class JailManager { /** * 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(jails.isEmpty()) return null; - - if(sender instanceof Player) { + if (jails.isEmpty()) return null; + + if (sender instanceof Player) { Location loc = ((Player) sender).getLocation(); Jail j = null; double len = -1; - for(Jail jail : jails.values()) { + for (Jail jail : jails.values()) { double clen = jail.getDistance(loc); if (clen < len || len == -1) { @@ -178,20 +177,20 @@ public class JailManager { } return (j == null ? jails.values().iterator().next() : j); - }else { + } 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())) { + for (Jail j : jails.values()) { + if (Util.isInsideAB(loc.toVector(), j.getMinPoint().toVector(), j.getMaxPoint().toVector())) { return j; } } @@ -201,13 +200,13 @@ public class JailManager { /** * Gets whether the location is inside of a Jail. - * + * * @param l to determine if is in a jail * @return whether it is inside a jail or not */ public boolean isLocationAJail(Location l) { - for(Jail j : jails.values()) { - if(Util.isInsideAB(l.toVector(), j.getMinPoint().toVector(), j.getMaxPoint().toVector())) { + for (Jail j : jails.values()) { + if (Util.isInsideAB(l.toVector(), j.getMinPoint().toVector(), j.getMaxPoint().toVector())) { return true; } } @@ -217,7 +216,7 @@ public class JailManager { /** * 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. */ @@ -227,13 +226,13 @@ public class JailManager { /** * 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(); + HashSet cells = new HashSet<>(); - for(Jail j : jails.values()) + for (Jail j : jails.values()) cells.addAll(j.getCells()); return cells; @@ -241,7 +240,7 @@ public class JailManager { /** * Adds a prisoner to the cache. - * + * * @param cache object to store * @return The same object given */ @@ -253,7 +252,7 @@ public class JailManager { /** * Checks if the given uuid is in the cache. - * + * * @param uuid of the player * @return true if in cache, false if not */ @@ -263,7 +262,7 @@ public class JailManager { /** * 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 */ @@ -273,7 +272,7 @@ public class JailManager { /** * Removes the cache object stored for this uuid. - * + * * @param uuid of the prisoner to remove */ public void removeCacheObject(UUID uuid) { @@ -283,13 +282,13 @@ public class JailManager { /** * 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(); + HashMap prisoners = new HashMap<>(); - for(Jail j : jails.values()) + for (Jail j : jails.values()) prisoners.putAll(j.getAllPrisoners()); return prisoners; @@ -297,33 +296,33 @@ public class JailManager { /** * 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; + 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)) { + 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)) + for (Jail j : jails.values()) + if (j.isPlayerJailed(uuid)) return j; return null; @@ -331,7 +330,7 @@ public class JailManager { /** * 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. */ @@ -341,7 +340,7 @@ public class JailManager { /** * 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. */ @@ -353,14 +352,14 @@ public class JailManager { /** * 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)) + for (Jail j : jails.values()) + for (Prisoner p : j.getAllPrisoners().values()) + if (p.getLastKnownName().equalsIgnoreCase(username)) return j; return null; @@ -368,13 +367,13 @@ public class JailManager { /** * 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)) + for (Prisoner p : this.getAllPrisoners().values()) + if (p.getLastKnownName().equalsIgnoreCase(username)) return p; return null; @@ -382,7 +381,7 @@ public class JailManager { /** * 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 */ @@ -392,41 +391,41 @@ public class JailManager { /** * 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) { + if (jail != null) { Jail j = getJail(jail); - if(j != null) { - for(Prisoner p : j.getAllPrisoners().values()) { + if (j != null) { + for (Prisoner p : j.getAllPrisoners().values()) { getPlugin().getPrisonerManager().schedulePrisonerRelease(p); } return Lang.PRISONERSCLEARED.get(j.getName()); - }else { + } else { return Lang.NOJAIL.get(jail); } - }else { + } 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) { + if (getJails().size() == 0) { return Lang.NOJAILS.get(); - }else { - for(Jail j : getJails()) { - for(Prisoner p : j.getAllPrisoners().values()) { + } else { + for (Jail j : getJails()) { + for (Prisoner p : j.getAllPrisoners().values()) { getPlugin().getPrisonerManager().schedulePrisonerRelease(p); } } @@ -437,32 +436,32 @@ public class JailManager { /** * 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) { + if (name == null) { + if (getJails().size() == 0) { return Lang.NOJAILS.get(); - }else { - for(Jail j : getJails()) { + } else { + for (Jail j : getJails()) { j.clearPrisoners(); } return Lang.PRISONERSCLEARED.get(Lang.ALLJAILS); } - }else { + } else { Jail j = getJail(name); - if(j != null) { + if (j != null) { j.clearPrisoners(); return Lang.PRISONERSCLEARED.get(j.getName()); - }else { + } else { return Lang.NOJAIL.get(name); } } @@ -470,31 +469,31 @@ public class JailManager { /** * 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)) { + if (isValidJail(jail)) { Jail j = getJail(jail); //check if the cell is a valid cell - if(j.isValidCell(cell)) { - if(j.getCell(cell).hasPrisoner()) { + 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 { + return Lang.CELLREMOVALUNSUCCESSFUL.get(cell, jail); + } else { j.removeCell(cell); - return Lang.CELLREMOVED.get(new String[] { cell, jail }); + return Lang.CELLREMOVED.get(cell, jail); } - }else { + } else { //No cell found by the provided name in the stated jail - return Lang.NOCELL.get(new String[] { cell, jail }); + return Lang.NOCELL.get(cell, jail); } - }else { + } else { //No jail found by the provided name return Lang.NOJAIL.get(jail); } @@ -502,62 +501,62 @@ public class JailManager { /** * 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(); + LinkedList msgs = new LinkedList<>(); //Check if the jail name provided is a valid jail - if(isValidJail(jail)) { + if (isValidJail(jail)) { Jail j = getJail(jail); - if(j.getCellCount() == 0) { + 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 { + } else { //Keep a local copy of the hashset so that we don't get any CMEs. - HashSet cells = new HashSet(j.getCells()); + HashSet cells = new HashSet<>(j.getCells()); - for(Cell c : cells) { - if(c.hasPrisoner()) { + 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 { + msgs.add(Lang.CELLREMOVALUNSUCCESSFUL.get(c.getName(), j.getName())); + } else { j.removeCell(c.getName()); - msgs.add(Lang.CELLREMOVED.get(new String[] { c.getName(), j.getName() })); + msgs.add(Lang.CELLREMOVED.get(c.getName(), j.getName())); } } } - }else { + } else { //No jail found by the provided name msgs.add(Lang.NOJAIL.get(jail)); } - return msgs.toArray(new String[msgs.size()]); + return msgs.toArray(new String[0]); } /** * 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)) { + if (isValidJail(jail)) { //check if the jail doesn't contain prisoners - if(getJail(jail).getAllPrisoners().size() == 0) { + if (getJail(jail).getAllPrisoners().size() == 0) { //There are no prisoners, so we can delete it removeJail(jail); return Lang.JAILREMOVED.get(jail); - }else { + } else { //The jail has prisoners, they need to release them first return Lang.JAILREMOVALUNSUCCESSFUL.get(jail); } - }else { + } else { //No jail found by the provided name return Lang.NOJAIL.get(jail); } @@ -565,11 +564,11 @@ public class JailManager { /** * 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. */ @@ -579,18 +578,18 @@ public class JailManager { /** * Returns a message used for telling them what they're creating and what step they're on. - * + * * @param player the name of the player to check * @return The details for the step they're on */ public String getStepMessage(String player) { String message = ""; - if(isCreatingACell(player)) {//Check whether it is a jail cell + 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()) { + switch (cp.getStep()) { case 1: message += "set the teleport in location."; break; @@ -602,11 +601,11 @@ public class JailManager { break; } - }else if(isCreatingAJail(player)) {//If not a cell, then check if a jail. + } 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()) { + switch (cp.getStep()) { case 1: message += "select the first point."; break; @@ -627,7 +626,7 @@ public class JailManager { /** * Returns whether or not someone is creating a Jail. - * + * * @param name the player's name to check * @return Whether they are creating a jail or not. */ @@ -637,15 +636,15 @@ public class JailManager { /** * 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 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)) { + if (isCreatingAJail(player)) { return false; - }else { + } else { this.jailCreators.put(player.toLowerCase(), new CreationPlayer(jailName)); return true; } @@ -653,7 +652,7 @@ public class JailManager { /** * Returns the instance of the CreationPlayer for this player, null if there was none found. - * + * * @param name the player's name * @return gets the player's {@link CreationPlayer} instance */ @@ -663,7 +662,7 @@ public class JailManager { /** * Removes a CreationPlayer with the given name from the jail creators. - * + * * @param name player's name to remove */ public void removeJailCreationPlayer(String name) { @@ -672,7 +671,7 @@ public class JailManager { /** * Returns whether or not someone is creating a Cell. - * + * * @param name the player's name to check * @return Whether they are creating a jail cell or not. */ @@ -682,16 +681,16 @@ public class JailManager { /** * 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 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)) { + if (isCreatingACell(player)) { return false; - }else { + } else { this.cellCreators.put(player.toLowerCase(), new CreationPlayer(jailName, cellName)); return true; } @@ -699,7 +698,7 @@ public class JailManager { /** * Returns the instance of the CreationPlayer for this player, null if there was none found. - * + * * @param name the player's name to get * @return The player's {@link CreationPlayer} instance. */ @@ -709,7 +708,7 @@ public class JailManager { /** * Removes a CreationPlayer with the given name from the cell creators. - * + * * @param name player's name to remove */ public void removeCellCreationPlayer(String name) { @@ -718,7 +717,7 @@ public class JailManager { /** * Gets the instance of the {@link JailCreationSteps}. - * + * * @return {@link JailCreationSteps} instance */ public JailCreationSteps getJailCreationSteps() { @@ -727,7 +726,7 @@ public class JailManager { /** * Gets the instance of the {@link CellCreationSteps}. - * + * * @return the {@link CellCreationSteps} instance */ public CellCreationSteps getCellCreationSteps() { @@ -736,8 +735,8 @@ public class JailManager { /** * Adds something to the confirming list. - * - * @param name who to add + * + * @param name who to add * @param confirmer {@link ConfirmPlayer} of what they're confirming */ public void addConfirming(String name, ConfirmPlayer confirmer) { @@ -747,7 +746,7 @@ public class JailManager { /** * Removes a name from the confirming list. - * + * * @param name who to remove */ public void removeConfirming(String name) { @@ -756,7 +755,7 @@ public class JailManager { /** * Checks if the given name is confirming something. - * + * * @param name the player's name * @return Whether they are confirming something or not */ @@ -766,7 +765,7 @@ public class JailManager { /** * Returns true if the confirmation has expired, false if it is still valid. - * + * * @param name the player's name * @return Whether their confirmation has expired or not. */ @@ -777,7 +776,7 @@ public class JailManager { /** * Returns the original arguments for what we are confirming. - * + * * @param name the player's name * @return an array of strings which is their original arguments */ @@ -787,7 +786,7 @@ public class JailManager { /** * Returns what the given name is confirming. - * + * * @param name the player's name * @return What they are confirming */ diff --git a/src/main/java/com/graywolf336/jail/JailPayManager.java b/src/main/java/com/graywolf336/jail/JailPayManager.java index 01cb57d..e72a31d 100644 --- a/src/main/java/com/graywolf336/jail/JailPayManager.java +++ b/src/main/java/com/graywolf336/jail/JailPayManager.java @@ -1,34 +1,34 @@ package com.graywolf336.jail; +import com.graywolf336.jail.beans.Prisoner; +import com.graywolf336.jail.enums.Settings; +import com.graywolf336.jail.interfaces.IJailPayManager; import net.milkbowl.vault.economy.Economy; - import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.RegisteredServiceProvider; -import com.graywolf336.jail.beans.Prisoner; -import com.graywolf336.jail.enums.Settings; -import com.graywolf336.jail.interfaces.IJailPayManager; - public class JailPayManager implements IJailPayManager { private Economy economy = null; - private double minteCost, infiniteCost; + private final double minteCost; + private double infiniteCost; private Material item; - private boolean infinite, timed; + private final boolean infinite; + private final boolean timed; protected JailPayManager(JailMain plugin) { this.item = Material.getMaterial(plugin.getConfig().getString(Settings.JAILPAYITEM.getPath()).toUpperCase()); - - if(this.item == null) { - plugin.getLogger().warning("Pay item is null, setting to air"); - this.item = Material.AIR; + + if (this.item == null) { + plugin.getLogger().warning("Pay item is null, setting to air"); + this.item = Material.AIR; } this.minteCost = plugin.getConfig().getDouble(Settings.JAILPAYPRICEPERMINUTE.getPath()); - if(!this.usingItemsForPayment()) { - if(!this.setupEconomy(plugin)) { + if (!this.usingItemsForPayment()) { + if (!this.setupEconomy(plugin)) { plugin.getConfig().set(Settings.JAILPAYENABLED.getPath(), false); } } @@ -66,22 +66,22 @@ public class JailPayManager implements IJailPayManager { } public boolean hasEnoughToPay(Player p, double amt) { - if(this.usingItemsForPayment()) { + if (this.usingItemsForPayment()) { return p.getInventory().contains(this.item, (int) Math.ceil(amt)); - }else { + } else { return this.economy.has(p, amt); } } public void pay(Player p, double amt) { - if(this.usingItemsForPayment()) { + 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 (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 @@ -97,33 +97,33 @@ public class JailPayManager implements IJailPayManager { if (amtNeeded == 0) break; } - }else { + } else { this.economy.withdrawPlayer(p, amt); } } public String getCurrencyName() { - if(this.usingItemsForPayment()) { - String name = item.toString().replaceAll("_", " "); + if (this.usingItemsForPayment()) { + StringBuilder name = new StringBuilder(item.toString().replaceAll("_", " ")); - if(name.contains(" ")){ - String[] split = name.split(" "); - for(int i=0; i < split.length; i++){ + if (name.toString().contains(" ")) { + String[] split = name.toString().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 = new StringBuilder(); + for (String s : split) { + name.append(" ").append(s); } - name = name.substring(1); + name = new StringBuilder(name.substring(1)); } else { - name = name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase(); + name = new StringBuilder(name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase()); } - return name; - }else { + return name.toString(); + } else { return this.economy.currencyNamePlural(); } } diff --git a/src/main/java/com/graywolf336/jail/JailStickManager.java b/src/main/java/com/graywolf336/jail/JailStickManager.java index a57c232..2c4e94f 100644 --- a/src/main/java/com/graywolf336/jail/JailStickManager.java +++ b/src/main/java/com/graywolf336/jail/JailStickManager.java @@ -1,49 +1,47 @@ package com.graywolf336.jail; +import com.graywolf336.jail.beans.Stick; +import com.graywolf336.jail.enums.Settings; +import com.graywolf336.jail.interfaces.IJailStickManager; +import org.bukkit.Material; + import java.util.ArrayList; import java.util.HashMap; import java.util.UUID; -import org.bukkit.Material; - -import com.graywolf336.jail.beans.Stick; -import com.graywolf336.jail.enums.Settings; -import com.graywolf336.jail.interfaces.IJailStickManager; - /** * Manages the jail stick users. - * + * * @author graywolf336 * @version 1.0.2 * @since 3.0.0 - * */ public class JailStickManager implements IJailStickManager { - private ArrayList stickers; - private HashMap sticks; + private final ArrayList stickers; + private final HashMap sticks; protected JailStickManager(JailMain plugin) { - this.stickers = new ArrayList(); - this.sticks = new HashMap(); + 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) { + 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())) { + } 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()) { + if (jail.isEmpty()) { jail = pl.getJailManager().getJail("").getName(); - }else { - if(!pl.getJailManager().isValidJail(jail)) { + } 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; @@ -51,13 +49,13 @@ public class JailStickManager implements IJailStickManager { } Material m = Material.getMaterial(a[0].toUpperCase()); - if(this.sticks.containsKey(m)) { + 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; + long time; try { time = Util.getTime(a[1]); } catch (Exception e) { @@ -67,12 +65,11 @@ public class JailStickManager implements IJailStickManager { } try { - this.sticks.put(m, new Stick(jail, a[3], time, a.length >= 5 ? Double.valueOf(a[4]) : -1)); - }catch (Exception e) { + this.sticks.put(m, new Stick(jail, a[3], time, a.length >= 5 ? Double.parseDouble(a[4]) : -1)); + } 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; } } } @@ -80,7 +77,7 @@ public class JailStickManager implements IJailStickManager { int c = sticks.size(); pl.getLogger().info("Loaded " + c + " jail stick" + (c == 1 ? "" : "s") + "."); } - + public Stick getStick(Material mat) { return this.sticks.get(mat); } @@ -102,17 +99,17 @@ public class JailStickManager implements IJailStickManager { } public boolean toggleUsingStick(UUID id) { - if(this.stickers.contains(id)) { + if (this.stickers.contains(id)) { this.stickers.remove(id); return false; - }else { + } else { this.stickers.add(id); return true; } } public void removeAllStickUsers() { - for(UUID id : stickers) { + 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 48815fc..7275bed 100644 --- a/src/main/java/com/graywolf336/jail/JailTimer.java +++ b/src/main/java/com/graywolf336/jail/JailTimer.java @@ -1,27 +1,23 @@ package com.graywolf336.jail; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.Timer; - -import org.bukkit.entity.Player; - import com.graywolf336.jail.beans.Jail; import com.graywolf336.jail.beans.Prisoner; import com.graywolf336.jail.enums.Lang; import com.graywolf336.jail.enums.Settings; import com.graywolf336.jail.events.PrisonerTimeChangeEvent; +import org.bukkit.entity.Player; + +import javax.swing.*; /** * Contains all the logic for counting down the time of the prisoners time. - * + * * @author graywolf336 - * @since 2.x.x * @version 3.0.0 + * @since 2.x.x */ public class JailTimer { - private JailMain pl; + private final JailMain pl; private Timer timer; private Long lastTime; private Long afkTime = 0L; @@ -35,33 +31,27 @@ public class JailTimer { } this.lastTime = System.currentTimeMillis(); - if(pl.getConfig().getBoolean(Settings.USEBUKKITTIMER.getPath())) { + if (pl.getConfig().getBoolean(Settings.USEBUKKITTIMER.getPath())) { pl.getLogger().info("Using the Bukkit Scheduler."); pl.getServer().getScheduler().runTaskTimerAsynchronously(pl, new TimeEvent(), 200, 200); - }else { + } 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 = new Timer(10000, 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); - } + pl.getServer().getScheduler().runTaskTimerAsynchronously(pl, () -> { + for (Jail j : pl.getJailManager().getJails()) { + pl.getJailIO().saveJail(j); } }, 1200L, 1200L); } /** * Returns the instance of this timer. - * + * * @return the {@link Timer} instance */ public Timer getTimer() { @@ -73,60 +63,56 @@ public class JailTimer { long timePassed = System.currentTimeMillis() - lastTime; lastTime = System.currentTimeMillis(); - for(Jail j : pl.getJailManager().getJails()) { - for(Prisoner p : j.getAllPrisoners().values()) { + 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()) { + if (p.getRemainingTime() > 0 && !p.isOfflinePending()) { final Player player = pl.getServer().getPlayer(p.getUUID()); //Check if the player is offline - if(player == null) { + 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())) { + if (pl.getConfig().getBoolean(Settings.COUNTDOWNTIMEOFFLINE.getPath())) { //Set their remaining time but if it is less than zero, set it to zero - long before = p.getRemainingTime(); - long after = Math.max(0, p.getRemainingTime() - timePassed); - - PrisonerTimeChangeEvent event = new PrisonerTimeChangeEvent(j, j.getCellPrisonerIsIn(p.getUUID()), p, player, before, after); - pl.getServer().getPluginManager().callEvent(event); - - if(!event.isCancelled()) { - after = event.getTimeAfterChange(); - p.setRemainingTime(after); - if(p.getRemainingTime() == 0) pl.getPrisonerManager().schedulePrisonerRelease(p); - } + long before = p.getRemainingTime(); + long after = Math.max(0, p.getRemainingTime() - timePassed); + + PrisonerTimeChangeEvent event = new PrisonerTimeChangeEvent(j, j.getCellPrisonerIsIn(p.getUUID()), p, player, before, after); + pl.getServer().getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + after = event.getTimeAfterChange(); + p.setRemainingTime(after); + if (p.getRemainingTime() == 0) pl.getPrisonerManager().schedulePrisonerRelease(p); + } } - }else { - if(afkTime > 0) { + } else { + if (afkTime > 0) { p.setAFKTime(p.getAFKTime() + timePassed); - if(p.getAFKTime() > afkTime) { + if (p.getAFKTime() > afkTime) { p.setAFKTime(0); //This is so we kick players on the main thread //instead of on the async thread(s), as spigot //has a protection against this enabled. - pl.getServer().getScheduler().scheduleSyncDelayedTask(pl, new Runnable() { - public void run() { - player.kickPlayer(Lang.AFKKICKMESSAGE.get()); - } - }); + pl.getServer().getScheduler().scheduleSyncDelayedTask(pl, () -> 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 long before = p.getRemainingTime(); - long after = Math.max(0, p.getRemainingTime() - timePassed); - - PrisonerTimeChangeEvent event = new PrisonerTimeChangeEvent(j, j.getCellPrisonerIsIn(p.getUUID()), p, player, before, after); - pl.getServer().getPluginManager().callEvent(event); - - if(!event.isCancelled()) { - after = event.getTimeAfterChange(); - p.setRemainingTime(after); - if(p.getRemainingTime() == 0) pl.getPrisonerManager().schedulePrisonerRelease(p); - } + long after = Math.max(0, p.getRemainingTime() - timePassed); + + PrisonerTimeChangeEvent event = new PrisonerTimeChangeEvent(j, j.getCellPrisonerIsIn(p.getUUID()), p, player, before, after); + pl.getServer().getPluginManager().callEvent(event); + + if (!event.isCancelled()) { + after = event.getTimeAfterChange(); + p.setRemainingTime(after); + if (p.getRemainingTime() == 0) pl.getPrisonerManager().schedulePrisonerRelease(p); + } } } } diff --git a/src/main/java/com/graywolf336/jail/JailVoteManager.java b/src/main/java/com/graywolf336/jail/JailVoteManager.java index 9e1265d..40703c0 100644 --- a/src/main/java/com/graywolf336/jail/JailVoteManager.java +++ b/src/main/java/com/graywolf336/jail/JailVoteManager.java @@ -1,9 +1,5 @@ package com.graywolf336.jail; -import java.util.HashMap; -import java.util.UUID; -import java.util.concurrent.TimeUnit; - import com.graywolf336.jail.beans.Jail; import com.graywolf336.jail.beans.JailVote; import com.graywolf336.jail.beans.Prisoner; @@ -12,207 +8,211 @@ import com.graywolf336.jail.enums.Lang; import com.graywolf336.jail.enums.Settings; import com.graywolf336.jail.events.PrePrisonerJailedEvent; +import java.util.HashMap; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + /** * Manages all the votes to jail players. - * + * * @author graywolf336 - * @since 3.0.0 * @version 1.0.0 + * @since 3.0.0 */ public class JailVoteManager { - private JailMain pl; - private HashMap votes; - private HashMap tasks; - private String timerDesc, reason; - private long timerTicks, jailTime; - private int minYes; - + private final JailMain pl; + private final HashMap votes; + private final HashMap tasks; + private final String timerDesc; + private final String reason; + private final long timerTicks; + private final long jailTime; + private final int minYes; + /** * Creates a new instance of this Jail Vote manager. - * + * * @param plugin the {@link JailMain} instance * @throws Exception When it can't load the time correctly */ protected JailVoteManager(JailMain plugin) throws Exception { this.pl = plugin; - this.votes = new HashMap(); - this.tasks = new HashMap(); + this.votes = new HashMap<>(); + this.tasks = new HashMap<>(); this.reason = plugin.getConfig().getString(Settings.JAILVOTEREASON.getPath()); - + String timer = plugin.getConfig().getString(Settings.JAILVOTETIMER.getPath()); this.timerDesc = Util.getDurationBreakdown(Util.getTime(timer)); this.timerTicks = Util.getTime(timer, TimeUnit.SECONDS) * 20; this.jailTime = Util.getTime(plugin.getConfig().getString(Settings.JAILVOTETIME.getPath())); this.minYes = plugin.getConfig().getInt(Settings.JAILMINYESVOTES.getPath()); } - + /** * Gets all the votes to jail someone. - * + * * @return HashMap of all the votes */ public HashMap getVotes() { return this.votes; } - + /** * Gets the jail vote for the given player name, returning null if it doesn't exist. - * + * * @param name of the player to get the jail vote for * @return {@link JailVote} for the player */ public JailVote getVoteForPlayer(String name) { return this.votes.get(name); } - + /** * Adds a vote to jail someone. - * + * * @param v the {@link JailVote} to add. * @return true if the vote was added, false if a vote already exists for that player name. */ public boolean addVote(JailVote v) { - if(this.votes.containsKey(v.getPlayerName())) { + if (this.votes.containsKey(v.getPlayerName())) { return false; - }else { + } else { this.votes.put(v.getPlayerName(), v); return true; } } - + /** * Adds a vote for the given player's name. - * - * @param name the name of the player the vote is for. - * @param id the uuid of the player voting. + * + * @param name the name of the player the vote is for. + * @param id the uuid of the player voting. * @param which whether they are voting yes or no, true if yes false if no. * @return True if the vote was successful, false if it was unsuccessful. */ public boolean addVote(String name, UUID id, boolean which) { - if(this.votes.containsKey(name)) { + if (this.votes.containsKey(name)) { pl.debug(id.toString() + " voted " + (which ? "yes" : "no") + " to jail " + name); - if(which) { + if (which) { return this.votes.get(name).voteYes(id); - }else { + } else { return this.votes.get(name).voteNo(id); } - }else { + } else { return false; } } - + /** * Checks if the uuid provided has voted for the player name provided. - * + * * @param name of the vote for to check against - * @param id of the player voting + * @param id of the player voting * @return whether the player has voted for the username provided. */ public boolean hasVotedAlready(String name, UUID id) { - if(this.votes.containsKey(name)) { + if (this.votes.containsKey(name)) { return this.votes.get(name).hasVoted(id); - }else { + } else { return false; } } - + /** * Checks if a player is voted for or not. - * + * * @param name of the player to check for. * @return true if they were voted for, false if not. */ public boolean isVotedFor(String name) { return this.votes.containsKey(name); } - + /** * Returns the nice formatted time of how long a vote is open. - * + * * @return The vote length description */ public String getTimerLengthDescription() { return this.timerDesc; } - + /** * Returns the minimum amount of yes votes required to jail someone. - * + * * @return Minimum amount of votes required. */ public int getMinimumYesVotes() { return this.minYes; } - + /** * Gets the current running tasks ids. - * + * * @return HashMap of all the current current tasks */ public HashMap getRunningTasks() { return this.tasks; } - + /** * Schedules the calculation of whether a jail vote should jail or not jail. - * + * * @param name the name of the person who is being voted to be jailed */ public void scheduleCalculating(final String name) { - int taskId = pl.getServer().getScheduler().runTaskLater(pl, new Runnable() { - public void run() { - doTheVoteCalculation(votes.get(name)); - tasks.remove(name); - } + int taskId = pl.getServer().getScheduler().runTaskLater(pl, () -> { + doTheVoteCalculation(votes.get(name)); + tasks.remove(name); }, timerTicks).getTaskId(); - + this.tasks.put(name, taskId); } - + /** * Calculates the votes, determining whether there are enough votes to jail the person or not. - * + * * @param v the {@link JailVote} to do the calculation of. * @return the {@link JailVoteResult} of the vote. */ public JailVoteResult doTheVoteCalculation(JailVote v) { JailVoteResult result; - - if(v.getPlayer() == null) { + + if (v.getPlayer() == null) { pl.getServer().broadcastMessage(Lang.VOTEPLAYERNOLONGERONLINE.get(v.getPlayerName())); result = JailVoteResult.NOTONLINE; - }else { - if(v.getYesVotes() > v.getNoVotes()) { - if(v.getYesVotes() >= getMinimumYesVotes()) { + } else { + if (v.getYesVotes() > v.getNoVotes()) { + if (v.getYesVotes() >= getMinimumYesVotes()) { Prisoner p = new Prisoner(v.getPlayer().getUniqueId().toString(), v.getPlayerName(), pl.getConfig().getBoolean(Settings.AUTOMATICMUTE.getPath()), jailTime, "[JailVote]", reason); - + //Get the jail name, check for the nearest one String jailName = pl.getConfig().getString(Settings.DEFAULTJAIL.getPath()); - if(jailName.equalsIgnoreCase("nearest")) { + if (jailName.equalsIgnoreCase("nearest")) { Jail j = pl.getJailManager().getNearestJail(v.getPlayer()); - if(j != null) { + if (j != null) { jailName = j.getName(); } } - + //Get the jail instance from the name of jail in the params. Jail j = pl.getJailManager().getJail(jailName); - if(j == null) { + if (j == null) { pl.getLogger().warning("Jail Vote Failed: no jail was found?"); result = JailVoteResult.NOJAIL; - }else if(!j.isEnabled()) { + } else if (!j.isEnabled()) { pl.getLogger().warning("Jail Vote Failed: " + Lang.WORLDUNLOADED.get(j.getName())); result = JailVoteResult.JAILNOTENABLED; - }else { + } else { //call the event PrePrisonerJailedEvent event = new PrePrisonerJailedEvent(j, null, p, v.getPlayer(), v.getPlayer() == null, p.getJailer()); pl.getServer().getPluginManager().callEvent(event); //check if the event is cancelled - if(event.isCancelled()) { + if (event.isCancelled()) { pl.getLogger().warning("Jail Vote Failed: The PrePrisonerJailedEvent was cancelled for some reason."); result = JailVoteResult.EVENTCANCELLED; - }else { + } else { try { pl.getPrisonerManager().prepareJail(j, null, v.getPlayer(), p); result = JailVoteResult.YES; @@ -223,19 +223,19 @@ public class JailVoteManager { } } } - }else { - pl.getServer().broadcastMessage(Lang.VOTESNOTENOUGHYES.get(new String[] { v.getPlayerName(), String.valueOf(v.getYesVotes()), String.valueOf(minYes) })); + } else { + pl.getServer().broadcastMessage(Lang.VOTESNOTENOUGHYES.get(v.getPlayerName(), String.valueOf(v.getYesVotes()), String.valueOf(minYes))); result = JailVoteResult.NOTENOUGHYESVOTES; } - }else if(v.getYesVotes() == v.getNoVotes()) { + } else if (v.getYesVotes() == v.getNoVotes()) { pl.getServer().broadcastMessage(Lang.VOTESTIED.get(v.getPlayerName())); result = JailVoteResult.TIED; - }else { + } else { pl.getServer().broadcastMessage(Lang.VOTESSAIDNO.get(v.getPlayerName())); result = JailVoteResult.NO; } } - + votes.remove(v.getPlayerName()); return result; } diff --git a/src/main/java/com/graywolf336/jail/JailsAPI.java b/src/main/java/com/graywolf336/jail/JailsAPI.java index d0de71a..1ba290f 100644 --- a/src/main/java/com/graywolf336/jail/JailsAPI.java +++ b/src/main/java/com/graywolf336/jail/JailsAPI.java @@ -6,7 +6,7 @@ import com.graywolf336.jail.interfaces.IJailStickManager; * The static api interface for Jail plugin. * *

- * + *

* If you're looking for non-static methods, please see the * {@link JailMain} interface. * @@ -20,19 +20,19 @@ public class JailsAPI { protected JailsAPI(JailMain plugin) { pl = plugin; } - + /** * Returns the build number, it will return -1 if an errors occurs. - * + * * @return the build number of jail or -1 if an error occurred. */ public static int getBuildNumber() { String v = pl.getDescription().getVersion(); String[] split = v.split("-"); - + try { return Integer.parseInt(split[split.length - 1].replace("b", "")); - }catch(NumberFormatException e) { + } catch (NumberFormatException e) { return -1; } } diff --git a/src/main/java/com/graywolf336/jail/PrisonerManager.java b/src/main/java/com/graywolf336/jail/PrisonerManager.java index 786b07d..98b56bc 100644 --- a/src/main/java/com/graywolf336/jail/PrisonerManager.java +++ b/src/main/java/com/graywolf336/jail/PrisonerManager.java @@ -1,16 +1,5 @@ package com.graywolf336.jail; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -import org.bukkit.GameMode; -import org.bukkit.Material; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; - import com.graywolf336.jail.beans.AnyCell; import com.graywolf336.jail.beans.Cell; import com.graywolf336.jail.beans.Jail; @@ -28,6 +17,16 @@ import com.graywolf336.jail.exceptions.JailRequiredException; import com.graywolf336.jail.exceptions.PrisonerAlreadyJailedException; import com.graywolf336.jail.exceptions.PrisonerRequiredException; import com.graywolf336.jail.interfaces.ICell; +import org.bukkit.GameMode; +import org.bukkit.Material; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; /** * Provides methods, non-statically, that do the preparing of jails, jailing, etc. @@ -44,30 +43,26 @@ import com.graywolf336.jail.interfaces.ICell; * * * @author graywolf336 - * @since 2.x.x * @version 3.0.0 + * @since 2.x.x */ public class PrisonerManager { - private JailMain pl; - private ArrayList releases; + private final JailMain pl; + private final ArrayList releases; protected PrisonerManager(JailMain plugin) { this.pl = plugin; - this.releases = new ArrayList(); + this.releases = new ArrayList<>(); // Schedule the releasing of prisoners - plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() { - public void run() { - releaseScheduledPrisoners(); - } - }, 100L, 20L); + plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, this::releaseScheduledPrisoners, 100L, 20L); } /** * Does everything preparing for the jailing of the provided prisoner, if they are online it forwards it to {@link #jailPrisoner(Jail, ICell, Player, Prisoner)}. * *

- * + *

* In this we do the following: *

    *
  1. Checks if the jail is null, if so it throws an Exception
  2. @@ -81,75 +76,71 @@ public class PrisonerManager { *
  3. If we log the jailing to console and we haven't broadcasted it, then we log it to the console.
  4. *
* - * @param jail The {@link Jail jail instance} we are sending this prisoner to - * @param cell The name of the {@link ICell cell} we are sending this prisoner to - * @param player The {@link Player player} we are preparing the jail for. + * @param jail The {@link Jail jail instance} we are sending this prisoner to + * @param cell The name of the {@link ICell 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 JailRequiredException if the jail provided is null. + * @throws JailRequiredException if the jail provided is null. * @throws PrisonerAlreadyJailedException if the prisoner is already jailed. - * @throws PrisonerRequiredException if the prisoner's data provided is null. + * @throws PrisonerRequiredException if the prisoner's data provided is null. */ public void prepareJail(final Jail jail, ICell cell, final Player player, final Prisoner prisoner) throws JailRequiredException, PrisonerAlreadyJailedException, PrisonerRequiredException { //Do some checks of whether the passed params are null. - if(jail == null) + if (jail == null) throw new JailRequiredException("jailing a prisoner"); - if(cell == null) + if (cell == null) cell = new NoCell(); - if(prisoner == null) + if (prisoner == null) throw new PrisonerRequiredException("jailing a prisoner"); - if(this.pl.getJailManager().isPlayerJailed(prisoner.getUUID())) + if (this.pl.getJailManager().isPlayerJailed(prisoner.getUUID())) throw new PrisonerAlreadyJailedException(prisoner.getLastKnownName(), prisoner.getUUID().toString()); //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 instanceof NoCell) { + if (cell instanceof NoCell) { jail.addPrisoner(prisoner); cell = null; - }else if(cell instanceof AnyCell) { + } else if (cell instanceof AnyCell) { cell = jail.getFirstEmptyCell(); - if(cell == null) + if (cell == null) jail.addPrisoner(prisoner); else cell.setPrisoner(prisoner); - }else { + } else { cell.setPrisoner(prisoner); } //If they are are offline then throw the event otherwise jail them - if(prisoner.isOfflinePending()) { + if (prisoner.isOfflinePending()) { pl.getServer().getPluginManager().callEvent(new OfflinePrisonerJailedEvent(jail, cell, prisoner)); - }else { + } else { final ICell c = cell; - pl.getServer().getScheduler().runTask(pl, new Runnable() { - public void run() { - jailPrisoner(jail, c, player, prisoner); - } - }); + pl.getServer().getScheduler().runTask(pl, () -> jailPrisoner(jail, c, player, prisoner)); } //Get a message ready for broadcasting or logging. - String msg = ""; + String msg; - if(prisoner.getRemainingTime() < 0L) - msg = Lang.BROADCASTMESSAGEFOREVER.get(new String[] { prisoner.getLastKnownName(), prisoner.getReason(), jail.getName(), cell == null ? "" : cell.getName() }); + if (prisoner.getRemainingTime() < 0L) + msg = Lang.BROADCASTMESSAGEFOREVER.get(prisoner.getLastKnownName(), prisoner.getReason(), jail.getName(), cell == null ? "" : cell.getName()); else - msg = Lang.BROADCASTMESSAGEFORMINUTES.get(new String[] { prisoner.getLastKnownName(), String.valueOf(prisoner.getRemainingTimeInMinutes()), prisoner.getReason(), jail.getName(), cell == null ? "" : cell.getName() }); + msg = Lang.BROADCASTMESSAGEFORMINUTES.get(prisoner.getLastKnownName(), String.valueOf(prisoner.getRemainingTimeInMinutes()), prisoner.getReason(), jail.getName(), cell == null ? "" : cell.getName()); boolean broadcasted = false; //Broadcast the message, if it is enabled - if(pl.getConfig().getBoolean(Settings.BROADCASTJAILING.getPath(), false)) { + if (pl.getConfig().getBoolean(Settings.BROADCASTJAILING.getPath(), false)) { pl.getServer().broadcast(msg, "jail.see.broadcast"); broadcasted = true; } //Log the message, if it is enabled - if(pl.getConfig().getBoolean(Settings.LOGJAILINGTOCONSOLE.getPath(), true) && !broadcasted) { + if (pl.getConfig().getBoolean(Settings.LOGJAILINGTOCONSOLE.getPath(), true) && !broadcasted) { pl.getServer().getConsoleSender().sendMessage(msg); } } @@ -167,20 +158,20 @@ public class PrisonerManager { /** * 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 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 */ protected void jailPrisoner(final Jail jail, ICell cell, final Player player, final Prisoner prisoner) { - if(cell instanceof NoCell) + if (cell instanceof NoCell) cell = null; - else if(cell instanceof AnyCell) + else if (cell instanceof AnyCell) cell = null; //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())) { + if (pl.getHandCuffManager().isHandCuffed(player.getUniqueId())) { pl.getHandCuffManager().removeHandCuffs(player.getUniqueId()); } @@ -192,21 +183,21 @@ public class PrisonerManager { prisoner.setTeleporting(true); //If their reason is empty send proper message, else send other proper message - if(prisoner.getReason().isEmpty()) { + if (prisoner.getReason().isEmpty()) { player.sendMessage(Lang.JAILED.get()); - }else { + } 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)) { + 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)) { + if (pl.getConfig().getBoolean(Settings.RESTOREPREVIOUSGAMEMODE.getPath(), false)) { prisoner.setPreviousGameMode(player.getGameMode()); } @@ -214,10 +205,10 @@ public class PrisonerManager { //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) { + } catch (Exception e) { StringBuilder gamemodes = new StringBuilder(); - for(GameMode m : GameMode.values()) { - if(gamemodes.length() != 0) + for (GameMode m : GameMode.values()) { + if (gamemodes.length() != 0) gamemodes.append(", "); gamemodes.append(m.toString().toLowerCase()); @@ -225,19 +216,19 @@ public class PrisonerManager { pl.getLogger().warning("Your jailed gamemode setting is problematic. It is currently '" + pl.getConfig().getString(Settings.JAILEDGAMEMODE.getPath()) - + "' and should be one of the following: " + gamemodes.toString()); + + "' and should be one of the following: " + gamemodes); 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()) { + if (player.isInsideVehicle()) { player.getVehicle().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)) { + if (pl.getConfig().getBoolean(Settings.IGNORESLEEPINGSTATE.getPath(), true)) { player.setSleepingIgnored(true); } @@ -247,92 +238,88 @@ public class PrisonerManager { //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) { + 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) { + if (cell != null) { //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()); - + //check if we store the inventory - if(pl.getConfig().getBoolean(Settings.JAILEDSTOREINVENTORY.getPath(), true)) { + if (pl.getConfig().getBoolean(Settings.JAILEDSTOREINVENTORY.getPath(), true)) { final ICell theCell = cell; - pl.getServer().getScheduler().runTaskLater(pl, new Runnable() { - public void run() { - 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(theCell.hasChest()) { - //Get the chest's inventory and then clear it - Inventory chest = theCell.getChest().getInventory(); - chest.clear(); + pl.getServer().getScheduler().runTaskLater(pl, () -> { + 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 (theCell.hasChest()) { + //Get the chest's inventory and then clear it + Inventory chest = theCell.getChest().getInventory(); + chest.clear(); - //Get the separate inventory, so we can iterate of them - ItemStack[] inventory = player.getInventory().getContents(); + //Get the separate inventory, so we can iterate of them + ItemStack[] inventory = player.getInventory().getContents(); - for(ItemStack item : inventory) { - if(item != null) { - if(!Util.isStringInsideList(item.getType().toString(), blacklist)) { - 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 : inventory) { + if (item != null) { + if (!Util.isStringInsideList(item.getType().toString(), blacklist)) { + 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().clear(); - }else { - for(ItemStack item : player.getInventory().getContents()) - if(item != null) - if(Util.isStringInsideList(item.getType().toString(), blacklist)) - player.getInventory().remove(item); - - for(ItemStack item : player.getInventory().getArmorContents()) - if(item != null) - if(Util.isStringInsideList(item.getType().toString(), blacklist)) - player.getInventory().remove(item); - - prisoner.setInventory(Util.toBase64(player.getInventory())); - - player.getInventory().setArmorContents(null); - player.getInventory().clear(); } - }; - }, 10); - } - }else { - //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()); - - //There is no cell we're jailing them to, so stick them in the jail - if(pl.getConfig().getBoolean(Settings.JAILEDSTOREINVENTORY.getPath(), true)) { - pl.getServer().getScheduler().runTaskLater(pl, new Runnable() { - public void run() { - List blacklist = pl.getConfig().getStringList(Settings.JAILEDINVENTORYBLACKLIST.getPath()); - for(ItemStack item : player.getInventory().getContents()) - if(item != null) - if(Util.isStringInsideList(item.getType().toString(), blacklist)) + player.getInventory().clear(); + } else { + for (ItemStack item : player.getInventory().getContents()) + if (item != null) + if (Util.isStringInsideList(item.getType().toString(), blacklist)) player.getInventory().remove(item); - for(ItemStack item : player.getInventory().getArmorContents()) - if(item != null) - if(Util.isStringInsideList(item.getType().toString(), blacklist)) + for (ItemStack item : player.getInventory().getArmorContents()) + if (item != null) + if (Util.isStringInsideList(item.getType().toString(), blacklist)) player.getInventory().remove(item); prisoner.setInventory(Util.toBase64(player.getInventory())); player.getInventory().setArmorContents(null); player.getInventory().clear(); - }; + } + }, 10); + } + } else { + //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()); + + //There is no cell we're jailing them to, so stick them in the jail + if (pl.getConfig().getBoolean(Settings.JAILEDSTOREINVENTORY.getPath(), true)) { + pl.getServer().getScheduler().runTaskLater(pl, () -> { + List blacklist = pl.getConfig().getStringList(Settings.JAILEDINVENTORYBLACKLIST.getPath()); + + for (ItemStack item : player.getInventory().getContents()) + if (item != null) + if (Util.isStringInsideList(item.getType().toString(), blacklist)) + player.getInventory().remove(item); + + for (ItemStack item : player.getInventory().getArmorContents()) + if (item != null) + if (Util.isStringInsideList(item.getType().toString(), blacklist)) + player.getInventory().remove(item); + + prisoner.setInventory(Util.toBase64(player.getInventory())); + + player.getInventory().setArmorContents(null); + player.getInventory().clear(); }, 10); } } @@ -343,7 +330,7 @@ public class PrisonerManager { //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())) { + for (String command : pl.getConfig().getStringList(Settings.COMMANDSONJAIL.getPath())) { command = command.replaceAll("%p%", player.getName()); command = command.replaceAll("%player%", player.getName()); command = command.replaceAll("%uuid%", player.getUniqueId().toString()); @@ -352,7 +339,7 @@ public class PrisonerManager { } //Add the scoreboard to them if it is enabled - if(pl.getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) { + if (pl.getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) { pl.getScoreBoardManager().addScoreBoard(player, prisoner); } @@ -360,15 +347,15 @@ public class PrisonerManager { pl.getJailIO().saveJail(jail); //Call our custom event for when a prisoner is actually jailed. - PrisonerJailedEvent event = new PrisonerJailedEvent(jail, cell == null ? null : (Cell)cell, prisoner, player); + PrisonerJailedEvent event = new PrisonerJailedEvent(jail, cell == null ? null : (Cell) cell, prisoner, player); pl.getServer().getPluginManager().callEvent(event); } /** * Schedules a prisoner to be released, this method is to be used async. - * + * + *

*

- * * If you're wanting to unjail a prisoner, see the {@link #unJail(Jail, ICell, Player, Prisoner, CommandSender)} method. * * @param prisoner to be released. @@ -378,8 +365,8 @@ public class PrisonerManager { } private void releaseScheduledPrisoners() { - ArrayList lettingGo = new ArrayList(releases); - for(Prisoner p : lettingGo) { + ArrayList lettingGo = new ArrayList<>(releases); + for (Prisoner p : lettingGo) { releases.remove(p); releasePrisoner(pl.getServer().getPlayer(p.getUUID()), p); } @@ -388,20 +375,20 @@ public class PrisonerManager { /** * 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 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) { + if (player == null) { prisoner.setOfflinePending(true); prisoner.setRemainingTime(0); - }else { + } else { Jail j = pl.getJailManager().getJailPlayerIsIn(player.getUniqueId()); try { unJail(j, j.getCellPrisonerIsIn(player.getUniqueId()), player, prisoner, null); - }catch(Exception e) { - if(pl.inDebug()) { + } catch (Exception e) { + if (pl.inDebug()) { e.printStackTrace(); } @@ -415,32 +402,31 @@ public class PrisonerManager { * Unjails a prisoner, sync, 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 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. + * @param sender The {@link CommandSender} who unjailed this player, can be null. * @throws AsyncUnJailingNotSupportedException when this method is called via a thread that is not the primary thread. - * @throws JailRequiredException when the jail provided is null. - * @throws PrisonerRequiredException when the provided prisoner data is null. - * + * @throws JailRequiredException when the jail provided is null. + * @throws PrisonerRequiredException when the provided prisoner data is null. */ - public void unJail(final Jail jail, ICell cell, final Player player, final Prisoner prisoner, final CommandSender sender) throws AsyncUnJailingNotSupportedException, JailRequiredException, PrisonerRequiredException { - if(!pl.getServer().isPrimaryThread()) throw new AsyncUnJailingNotSupportedException(); + public void unJail(final Jail jail, ICell cell, final Player player, final Prisoner prisoner, final CommandSender sender) throws AsyncUnJailingNotSupportedException, JailRequiredException, PrisonerRequiredException { + if (!pl.getServer().isPrimaryThread()) throw new AsyncUnJailingNotSupportedException(); //Do some checks of whether the passed params are null. - if(jail == null) + if (jail == null) throw new JailRequiredException("unjailing a prisoner"); - if(cell instanceof NoCell) + if (cell instanceof NoCell) cell = null; - else if(cell instanceof AnyCell) + else if (cell instanceof AnyCell) cell = null; - if(prisoner == null) + if (prisoner == null) throw new PrisonerRequiredException("unjailing a prisoner"); //Throw the custom event which is called before we start releasing them @@ -453,37 +439,37 @@ public class PrisonerManager { //In case they have somehow got in a vehicle, let's unmount //them so we can possibly teleport them - if(player.isInsideVehicle()) { + if (player.isInsideVehicle()) { player.getVehicle().eject(); player.eject(); } - + //Now, let's restore their inventory if we can store it but //first up is clearing their inventory...if we can store it boolean store = pl.getConfig().getBoolean(Settings.JAILEDSTOREINVENTORY.getPath(), true); - if(store) { + if (store) { 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(store) { - if(cell.hasChest()) { + if (cell != null) { + if (store) { + 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)) { + 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)) { + } 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)) { + } 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)) { + } 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); @@ -493,19 +479,19 @@ public class PrisonerManager { } chest.clear(); - }else { + } else { Util.restoreInventory(player, prisoner); } - }else { + } else { //Clear out the cell's chest just in case //they decided to store something there - if(cell.hasChest()) cell.getChest().getInventory().clear(); + if (cell.hasChest()) cell.getChest().getInventory().clear(); } - pl.getJailIO().removePrisoner(jail, (Cell)cell, prisoner); + pl.getJailIO().removePrisoner(jail, (Cell) cell, prisoner); cell.removePrisoner(); - }else { - if(store) Util.restoreInventory(player, prisoner); + } else { + if (store) Util.restoreInventory(player, prisoner); pl.getJailIO().removePrisoner(jail, prisoner); jail.removePrisoner(prisoner); @@ -514,34 +500,32 @@ public class PrisonerManager { //In case we had set their sleeping state to be ignored //let's enable their sleeping state taking place again player.setSleepingIgnored(false); - - pl.getServer().getScheduler().runTaskLater(pl, new Runnable() { - public void run() { - //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()); - } + pl.getServer().getScheduler().runTaskLater(pl, () -> { + //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 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()); - } - }; + //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()); + } }, 5); //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())) { + for (String command : pl.getConfig().getStringList(Settings.COMMANDSONRELEASE.getPath())) { command = command.replaceAll("%p%", player.getName()); command = command.replaceAll("%player%", player.getName()); command = command.replaceAll("%uuid%", player.getUniqueId().toString()); @@ -550,23 +534,23 @@ public class PrisonerManager { } //Remove the scoreboard to them if it is enabled - if(pl.getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) { + 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 == null ? null : (Cell)cell, prisoner, player); + PrisonerReleasedEvent event = new PrisonerReleasedEvent(jail, cell == null ? null : (Cell) cell, prisoner, player); pl.getServer().getPluginManager().callEvent(event); player.sendMessage(Lang.UNJAILED.get()); - if(sender != null) sender.sendMessage(Lang.UNJAILSUCCESS.get(player.getName())); + 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: *

    @@ -574,15 +558,15 @@ public class PrisonerManager { *
  • 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 + * @param sender who is releasing the prisoner, can be null * @throws PrisonerRequiredException when the prisoner data doesn't exist. - * @throws JailRequiredException when the prisoner isn't jailed + * @throws JailRequiredException when the prisoner isn't jailed */ public void forceRelease(Prisoner prisoner, CommandSender sender) throws JailRequiredException, PrisonerRequiredException { Jail j = pl.getJailManager().getJailPrisonerIsIn(prisoner); @@ -594,7 +578,7 @@ public class PrisonerManager { * * *

- * + *

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

    @@ -602,33 +586,33 @@ public class PrisonerManager { *
  • 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 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 - * @throws JailRequiredException when the provided jail is null. + * @param sender who is releasing the prisoner, can be null + * @throws JailRequiredException when the provided jail is null. * @throws PrisonerRequiredException when the provided prisoner data is null. */ public void forceUnJail(Jail jail, Cell cell, Player player, Prisoner prisoner, CommandSender sender) throws JailRequiredException, PrisonerRequiredException { - if(jail == null) + if (jail == null) throw new JailRequiredException("jailing a prisoner"); - if(prisoner == null) + if (prisoner == null) throw new PrisonerRequiredException("jailing a prisoner"); - if(player == null) { + if (player == null) { //Player is offline, we just forcefully remove them from the database pl.getJailIO().removePrisoner(jail, cell, prisoner); - if(cell == null) { + if (cell == null) { jail.removePrisoner(prisoner); - }else { + } else { cell.removePrisoner(); } @@ -636,8 +620,8 @@ public class PrisonerManager { PrisonerReleasedEvent event = new PrisonerReleasedEvent(jail, cell, prisoner, player); pl.getServer().getPluginManager().callEvent(event); - if(sender != null) sender.sendMessage(Lang.FORCEUNJAILED.get(prisoner.getLastKnownName())); - }else { + if (sender != null) sender.sendMessage(Lang.FORCEUNJAILED.get(prisoner.getLastKnownName())); + } else { try { unJail(jail, cell, player, prisoner, sender); } catch (Exception e) { @@ -653,15 +637,15 @@ public class PrisonerManager { * @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. + * @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) { + if (originCell == null) { //But first thing is first, let's check if there is a targetCell we're putting them in - if(targetCell == null) { + 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); @@ -670,41 +654,41 @@ public class PrisonerManager { //If the player is not online, trigger them to be teleported when they //come online again - if(player == null) { + 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 { + } else { prisoner.setTeleporting(true); player.teleport(targetJail.getTeleportIn()); prisoner.setTeleporting(false); player.sendMessage(Lang.TRANSFERRED.get(targetJail.getName())); } - }else { + } 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) { + 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 { + } else { prisoner.setTeleporting(true); player.teleport(targetCell.getTeleport()); prisoner.setTeleporting(false); player.sendMessage(Lang.TRANSFERRED.get(targetJail.getName())); } } - }else { + } 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) { + if (targetCell == null) { //Add them to the target jail targetJail.addPrisoner(prisoner); //Next, remove them from the cell @@ -712,13 +696,13 @@ public class PrisonerManager { //If the cell they came from has any items from their inventory, //let's get it all and store it - if(originCell.hasChest()) { + 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 { + } 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. @@ -729,17 +713,17 @@ public class PrisonerManager { originCell.removePrisoner(); //Check if the origin cell has a chest, put all the player's inventory into it - if(originCell.hasChest()) { + if (originCell.hasChest()) { //If the targetCell has a chest - if(targetCell.hasChest()) { + 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()) - if(i != null) + for (ItemStack i : originCell.getChest().getInventory().getContents()) + if (i != null) targetCell.getChest().getInventory().addItem(i); //Clear the origin cell's chest as it is clear now originCell.getChest().getInventory().clear(); - }else { + } 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 @@ -750,11 +734,11 @@ public class PrisonerManager { } } } - + //Update the signs of both cells - if(originCell != null) + if (originCell != null) originCell.updateSigns(); - if(targetCell != null) + if (targetCell != null) targetCell.updateSigns(); //Throw our custom event PrisonerTransferredEvent to say it was successful diff --git a/src/main/java/com/graywolf336/jail/ScoreBoardManager.java b/src/main/java/com/graywolf336/jail/ScoreBoardManager.java index 44014ff..20e3692 100644 --- a/src/main/java/com/graywolf336/jail/ScoreBoardManager.java +++ b/src/main/java/com/graywolf336/jail/ScoreBoardManager.java @@ -1,8 +1,8 @@ package com.graywolf336.jail; -import java.util.HashMap; -import java.util.UUID; - +import com.graywolf336.jail.beans.Jail; +import com.graywolf336.jail.beans.Prisoner; +import com.graywolf336.jail.enums.Settings; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.bukkit.scoreboard.DisplaySlot; @@ -10,56 +10,51 @@ import org.bukkit.scoreboard.Objective; import org.bukkit.scoreboard.Scoreboard; import org.bukkit.scoreboard.ScoreboardManager; -import com.graywolf336.jail.beans.Jail; -import com.graywolf336.jail.beans.Prisoner; -import com.graywolf336.jail.enums.Settings; +import java.util.HashMap; +import java.util.UUID; public class ScoreBoardManager { - private JailMain pl; - private ScoreboardManager man; - private HashMap boards; - private OfflinePlayer time; + private final JailMain pl; + private final ScoreboardManager man; + private final HashMap boards; + private final OfflinePlayer time; @SuppressWarnings("deprecation") protected ScoreBoardManager(JailMain plugin) { this.pl = plugin; this.man = plugin.getServer().getScoreboardManager(); - this.boards = new HashMap(); + 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); + if (plugin.getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) { + plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, this::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 + * @param pris data for the provided prisoner */ @SuppressWarnings("deprecation") public void addScoreBoard(Player player, Prisoner pris) { - if(!boards.containsKey(player.getUniqueId())) { + 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 { + } 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) { @@ -68,14 +63,16 @@ public class ScoreBoardManager { player.setScoreboard(man.getMainScoreboard()); } - /** Removes all of the scoreboards from the prisoners. */ + /** + * Removes all of the scoreboards from the prisoners. + */ public void removeAllScoreboards() { - HashMap temp = new HashMap(boards); + HashMap temp = new HashMap<>(boards); - for(UUID id : temp.keySet()) { + for (UUID id : temp.keySet()) { Player p = pl.getServer().getPlayer(id); - if(p != null) { + if (p != null) { p.setScoreboard(man.getMainScoreboard()); } @@ -83,11 +80,13 @@ public class ScoreBoardManager { } } - /** Updates the prisoners time on their scoreboard. */ + /** + * 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) { + 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); } } @@ -96,9 +95,9 @@ public class ScoreBoardManager { /** * Updates a player's time in the scoreboard. - * + * * @param player of whom to update the scoreboard for. - * @param pris data for the player + * @param pris data for the player */ @SuppressWarnings("deprecation") private void updatePrisonersBoard(Player player, Prisoner pris) { diff --git a/src/main/java/com/graywolf336/jail/Update.java b/src/main/java/com/graywolf336/jail/Update.java index 390e2bf..f594fad 100644 --- a/src/main/java/com/graywolf336/jail/Update.java +++ b/src/main/java/com/graywolf336/jail/Update.java @@ -1,5 +1,10 @@ package com.graywolf336.jail; +import com.graywolf336.jail.enums.Settings; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; @@ -7,14 +12,8 @@ import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.JSONValue; - -import com.graywolf336.jail.enums.Settings; - public class Update { - private JailMain plugin; + private final JailMain plugin; // The project's unique ID private static final int projectID = 31139; @@ -34,14 +33,14 @@ public class Update { public void query() { String channel = plugin.getConfig().getString(Settings.UPDATECHANNEL.getPath(), "bukkit"); - URL url = null; + URL url; try { - if(channel.equalsIgnoreCase("stable-dev")) { + if (channel.equalsIgnoreCase("stable-dev")) { url = new URL(CI_STABLEDEV_API_QUERY); - }else if(channel.equalsIgnoreCase("dev")) { + } else if (channel.equalsIgnoreCase("dev")) { url = new URL(CI_DEV_API_QUERY); - }else { + } else { url = new URL(BUKKIT_API_QUERY); } } catch (MalformedURLException e) { @@ -61,7 +60,7 @@ public class Update { final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String response = reader.readLine(); - if(channel.equalsIgnoreCase("stable-dev") || channel.equalsIgnoreCase("dev")) { + 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 @@ -69,7 +68,7 @@ public class Update { // 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")) { + if (ver[ver.length - 1].equalsIgnoreCase("0")) { plugin.getLogger().info("You are using a custom version, you can disable update checking."); } @@ -80,13 +79,13 @@ public class Update { needed = number > curr; // Alert the console that an update is needed, if it is needed - if(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 { + } else { // Parse the array of files from the query's response JSONArray array = (JSONArray) JSONValue.parse(response); @@ -104,7 +103,7 @@ public class Update { plugin.debug(remoteVer + " verus " + currentVer); this.needed = this.versionCompare(remoteVer, currentVer) > 0; - if(needed) { + 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); @@ -116,23 +115,21 @@ public class Update { // There was an error reading the query e.printStackTrace(); plugin.getLogger().severe("There was an error checking for an update, please see the above stacktrace for details before reporting."); - return; } } /** * Compares two version strings. - * + *

* 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 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. - * The result is zero if the strings are _numerically_ equal. + * The result is a positive integer if str1 is _numerically_ greater than str2. + * The result is zero if the strings are _numerically_ equal. + * @note It does not work if "1.10" is supposed to be equal to "1.10.0". */ private Integer versionCompare(String str1, String str2) { String[] vals1 = str1.split("\\."); @@ -157,7 +154,7 @@ public class Update { /** * Returns true if there is an update needed, false if not. - * + * * @return Whether an update is available */ public boolean isAvailable() { @@ -166,7 +163,7 @@ public class Update { /** * Returns the new version. - * + * * @return The string name of the new version */ public String getNewVersion() { @@ -175,7 +172,7 @@ public class Update { /** * Returns the new file url. - * + * * @return New file's url */ public String getFileUrl() { diff --git a/src/main/java/com/graywolf336/jail/Util.java b/src/main/java/com/graywolf336/jail/Util.java index 44509d0..23407ef 100644 --- a/src/main/java/com/graywolf336/jail/Util.java +++ b/src/main/java/com/graywolf336/jail/Util.java @@ -1,16 +1,7 @@ package com.graywolf336.jail; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - +import com.graywolf336.jail.beans.Prisoner; +import com.graywolf336.jail.enums.Lang; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; @@ -23,26 +14,34 @@ import org.bukkit.util.io.BukkitObjectInputStream; import org.bukkit.util.io.BukkitObjectOutputStream; import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; -import com.graywolf336.jail.beans.Prisoner; -import com.graywolf336.jail.enums.Lang; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** * Provides a variety of methods, static, that are used throughout the plugin. * * @author graywolf336 - * @since 2.x.x * @version 3.1.0 + * @since 2.x.x */ 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); - private static String[] signLines = new String[] { "", "", "", "" }; + private static String[] signLines = new String[]{"", "", "", ""}; private final static int inventoryMultipule = 9; /** * Checks if the first {@link Vector} is inside this region. * - * @param point The point to check - * @param first point of the 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. */ @@ -59,14 +58,14 @@ public class Util { * *

* - * @param loc The location. - * @param first The first point + * @param loc The location. + * @param first The first point * @param second The second point * @return true if they are inside, false if not. */ private static boolean isInside(int loc, int first, int second) { - int point1 = 0; - int point2 = 0; + int point1; + int point2; if (first < second) { point1 = first; point2 = second; @@ -80,16 +79,16 @@ public class Util { /** * Checks if the given string is inside the array, ignoring the casing. - * - *

+ *

+ *

* * @param value to check * @param array of strings to check * @return true if the array contains the provided value, false if it doesn't */ public static boolean isStringInsideArray(String value, String... array) { - for(String s : array) - if(s.equalsIgnoreCase(value)) + for (String s : array) + if (s.equalsIgnoreCase(value)) return true; return false; @@ -97,16 +96,16 @@ public class Util { /** * Checks if the given string is inside the list, ignoring the casing. - * - *

+ *

+ *

* * @param value to check - * @param list of strings to check + * @param list of strings to check * @return true if the list contains the provided value, false if it doesn't */ public static boolean isStringInsideList(String value, List list) { - for(String s : list) - if(s.equalsIgnoreCase(value)) + for (String s : list) + if (s.equalsIgnoreCase(value)) return true; return false; @@ -116,14 +115,14 @@ public class Util { * Gets a single string from an array of strings, separated by the separator. * * @param separator The item to separate the items - * @param array The array of strings to combine + * @param array The array of strings to combine * @return the resulting combined string */ public static String getStringFromArray(String separator, String... array) { StringBuilder result = new StringBuilder(); - for(String s : array) { - if(result.length() != 0) result.append(separator); + for (String s : array) { + if (result.length() != 0) result.append(separator); result.append(s); } @@ -134,14 +133,14 @@ public class Util { * Gets a single string from a list of strings, separated by the separator. * * @param separator The item to separate the items - * @param list The list of strings to combine + * @param list The list of strings to combine * @return the resulting combined string */ public static String getStringFromList(String separator, List list) { StringBuilder result = new StringBuilder(); - for(String s : list) { - if(result.length() != 0) result.append(separator); + for (String s : list) { + if (result.length() != 0) result.append(separator); result.append(s); } @@ -150,7 +149,7 @@ public class Util { /** * Returns a colorful message from the color codes. - * + * * @param message the message to colorize * @return the colorized message */ @@ -160,8 +159,8 @@ public class Util { /** * Returns a message with all the possible variables replaced. - * - * @param p the {@link Prisoner} data + * + * @param p the {@link Prisoner} data * @param msg the message to replace everything in * @return The message with everything replaced and colorized. */ @@ -172,10 +171,10 @@ public class Util { .replace("%jailer%", p.getJailer()) .replace("%afktime%", Util.getDurationBreakdown(p.getAFKTime())); - if(p.getRemainingTime() >= 0) { + if (p.getRemainingTime() >= 0) { msg = msg.replace("%timeinminutes%", String.valueOf(p.getRemainingTimeInMinutes())); msg = msg.replace("%prettytime%", Util.getDurationBreakdown(p.getRemainingTime())); - }else { + } else { msg = msg.replace("%timeinminutes%", String.valueOf(-1)); msg = msg.replace("%prettytime%", Lang.JAILEDFOREVERSIGN.get()); } @@ -185,15 +184,15 @@ public class Util { /** * Replaces all the variables in the messages with their possible values. - * - * @param p the {@link Prisoner} data. + * + * @param p the {@link Prisoner} data. * @param msgs the messages * @return the messages but variables replaced and colorized */ public static String[] replaceAllVariables(Prisoner p, String... msgs) { String[] results = new String[msgs.length]; - - for(int i = 0; i < msgs.length; i++) + + for (int i = 0; i < msgs.length; i++) results[i] = replaceAllVariables(p, msgs[i]); return results; @@ -201,14 +200,14 @@ public class Util { /** * Returns the wand used throughout the different creation steps. - * + * * @return The {@link ItemStack} to use for creation */ public static ItemStack getWand() { ItemStack wand = new ItemStack(Material.BRICK); ItemMeta meta = wand.getItemMeta(); meta.setDisplayName(ChatColor.AQUA + "Jail Wand"); - LinkedList lore = new LinkedList(); + LinkedList lore = new LinkedList<>(); lore.add(ChatColor.BLUE + "The wand for creating"); lore.add(ChatColor.BLUE + "a jail or cell."); meta.setLore(lore); @@ -237,29 +236,29 @@ public class Util { * @throws Exception if there are no matches */ public static Long getTime(String time) throws Exception { - if(time.equalsIgnoreCase("-1")) return -1L; + if (time.equalsIgnoreCase("-1")) return -1L; - Long t = 10L; + long t; 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); + t = TimeUnit.MILLISECONDS.convert(Long.parseLong(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); + t = TimeUnit.MILLISECONDS.convert(Long.parseLong(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.parseLong(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.parseLong(match.group(1)), TimeUnit.DAYS); else { try { t = TimeUnit.MILLISECONDS.convert(Long.parseLong(time), TimeUnit.MINUTES); - }catch(NumberFormatException e) { + } catch (NumberFormatException e) { throw new Exception("Invalid format."); } } - }else { + } else { throw new Exception("Invalid format."); } @@ -273,7 +272,7 @@ public class Util { * @return A string of the form "XdYhZAs". */ public static String getDurationBreakdown(long millis) { - if(millis < 0) { + if (millis < 0) { return Lang.JAILEDFOREVERSIGN.get(); } @@ -286,17 +285,17 @@ public class Util { long seconds = TimeUnit.MILLISECONDS.toSeconds(millis); StringBuilder sb = new StringBuilder(64); - if(days > 0) { + if (days > 0) { sb.append(days); sb.append("d"); } - if(days > 0 || hours > 0) { + if (days > 0 || hours > 0) { sb.append(hours); sb.append("h"); } - if(days > 0 || hours > 0 || minutes > 0) { + if (days > 0 || hours > 0 || minutes > 0) { sb.append(minutes); sb.append("m"); } @@ -314,42 +313,41 @@ public class Util { * @throws Exception Throws an exception if there aren't exactly four lines. */ public static void updateSignLinesCache(String[] lines) throws Exception { - if(lines.length != 4) throw new Exception("Exactly four lines are required for the signs."); + if (lines.length != 4) throw new Exception("Exactly four lines are required for the signs."); signLines = lines; } /** * Gets all the lines which go on the cell signs. - * + * * @return the strings for the signs */ public static String[] getSignLines() { return signLines; } - + public static List getUnusedItems(List items, String[] args, boolean useP) { - List used = new ArrayList(); - for(String s : args) - if(s.contains("-")) + List used = new ArrayList<>(); + for (String s : args) + if (s.contains("-")) used.add(s.replace("-", "")); - - List unused = new ArrayList(); - for(String t : items) - if(!used.contains(t)) //don't add it if it is already used - if(!t.equalsIgnoreCase("p") || (useP && t.equalsIgnoreCase("p")))//don't add -p unless otherwise stated - unused.add("-" + t); - + + List unused = new ArrayList<>(); + for (String t : items) + if (!used.contains(t)) //don't add it if it is already used + if (!t.equalsIgnoreCase("p") || (useP && t.equalsIgnoreCase("p")))//don't add -p unless otherwise stated + unused.add("-" + t); + Collections.sort(unused); - + return unused; } /** - * * A method to serialize an {@link ItemStack} array to Base64 String. * *

- * + *

* Based off of {@link #toBase64(Inventory)}. * * @param items to turn into a Base64 String. @@ -381,7 +379,7 @@ public class Util { * A method to serialize an inventory to Base64 string. * *

- * + *

* Special thanks to Comphenix in the Bukkit forums or also known * as aadnk on GitHub. Original Source * @@ -411,11 +409,10 @@ public class Util { } /** - * * A method to get an {@link Inventory} from an encoded, Base64, string. * *

- * + *

* Special thanks to Comphenix in the Bukkit forums or also known * as aadnk on GitHub. * @@ -426,13 +423,13 @@ public class Util { * @throws IOException if we were unable to parse the base64 string */ 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); int size = dataInput.readInt(); - Inventory inventory = Bukkit.getServer().createInventory(null, (int)Math.ceil((double)size / inventoryMultipule) * inventoryMultipule); + Inventory inventory = Bukkit.getServer().createInventory(null, (int) Math.ceil((double) size / inventoryMultipule) * inventoryMultipule); // Read the serialized inventory for (int i = 0; i < size; i++) { @@ -451,7 +448,7 @@ public class Util { * Gets an array of ItemStacks from Base64 string. * *

- * + *

* Base off of {@link #fromBase64(String)}. * * @param data Base64 string to convert to ItemStack array. @@ -459,7 +456,7 @@ public class Util { * @throws IOException if we was unable to parse the base64 string */ public static ItemStack[] itemStackArrayFromBase64(String data) throws IOException { - if(data.isEmpty()) return new ItemStack[] {}; + if (data.isEmpty()) return new ItemStack[]{}; try { ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); @@ -483,16 +480,16 @@ public class Util { 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")) + for (ItemStack item : armor) { + if (item == null) { + } + else if (item.getType().toString().toLowerCase().contains("helmet")) player.getInventory().setHelmet(item); - else if(item.getType().toString().toLowerCase().contains("chestplate")) + else if (item.getType().toString().toLowerCase().contains("chestplate")) player.getInventory().setChestplate(item); - else if(item.getType().toString().toLowerCase().contains("leg")) + else if (item.getType().toString().toLowerCase().contains("leg")) player.getInventory().setLeggings(item); - else if(item.getType().toString().toLowerCase().contains("boots")) + else if (item.getType().toString().toLowerCase().contains("boots")) player.getInventory().setBoots(item); else if (player.getInventory().firstEmpty() == -1) player.getWorld().dropItem(player.getLocation(), item); @@ -500,9 +497,10 @@ public class Util { player.getInventory().addItem(item); } - for(ItemStack item : content.getContents()) { - if(item == null) continue; - else if(player.getInventory().firstEmpty() == -1) + for (ItemStack item : content.getContents()) { + if (item == null) { + } + else if (player.getInventory().firstEmpty() == -1) player.getWorld().dropItem(player.getLocation(), item); else player.getInventory().addItem(item); @@ -516,7 +514,7 @@ public class Util { /** * Checks if the provided class has the provided method. * - * @param c The {@link Class} to check on. + * @param c The {@link Class} to check on. * @param method The name of the method to check for * @return whether the method exists or not. */ diff --git a/src/main/java/com/graywolf336/jail/beans/AnyCell.java b/src/main/java/com/graywolf336/jail/beans/AnyCell.java index 87895c4..3881ac0 100644 --- a/src/main/java/com/graywolf336/jail/beans/AnyCell.java +++ b/src/main/java/com/graywolf336/jail/beans/AnyCell.java @@ -1,111 +1,133 @@ package com.graywolf336.jail.beans; +import com.graywolf336.jail.interfaces.ICell; +import org.bukkit.Location; +import org.bukkit.block.Chest; + import java.util.HashMap; import java.util.HashSet; import java.util.List; -import org.bukkit.Location; -import org.bukkit.block.Chest; - -import com.graywolf336.jail.interfaces.ICell; - /** - * Pass this an instance of this class into the jailing of a player and they go to any open cell. + * Pass this an instance of this class into the jailing of a player, and they go to any open cell. * * @author graywolf336 - * @since 3.0.0 * @version 1.0.0 - * + * @since 3.0.0 */ public class AnyCell implements ICell { + + @Override public int getDatabaseID() { throw new UnsupportedOperationException(); } + @Override public String getName() { throw new UnsupportedOperationException(); } + @Override public void setPrisoner(Prisoner prisoner) { throw new UnsupportedOperationException(); } + @Override public Prisoner getPrisoner() { throw new UnsupportedOperationException(); } + @Override public void removePrisoner() { throw new UnsupportedOperationException(); } + @Override public boolean hasPrisoner() { throw new UnsupportedOperationException(); } + @Override public void addAllSigns(HashSet signs) { throw new UnsupportedOperationException(); } + @Override public void addSign(SimpleLocation sign) { throw new UnsupportedOperationException(); } + @Override public HashSet getSigns() { throw new UnsupportedOperationException(); } + @Override public boolean hasSigns() { throw new UnsupportedOperationException(); } + @Override public String getSignString() { throw new UnsupportedOperationException(); } + @Override public List getInvalidSigns() { throw new UnsupportedOperationException(); } + @Override public List cleanSigns() { throw new UnsupportedOperationException(); } + @Override public HashMap> updateSigns() { throw new UnsupportedOperationException(); } + @Override public void setTeleport(SimpleLocation location) { throw new UnsupportedOperationException(); } + @Override public Location getTeleport() { throw new UnsupportedOperationException(); } + @Override public void setChestLocation(SimpleLocation simpleLocation) { throw new UnsupportedOperationException(); } + @Override public Location getChestLocation() { throw new UnsupportedOperationException(); } + @Override public Chest getChest() { throw new UnsupportedOperationException(); } + @Override public boolean hasChest() { throw new UnsupportedOperationException(); } - + + @Override public boolean useChest() { throw new UnsupportedOperationException(); } + @Override public boolean setChanged(boolean changed) { throw new UnsupportedOperationException(); } + @Override public boolean hasChanged() { throw new UnsupportedOperationException(); } diff --git a/src/main/java/com/graywolf336/jail/beans/CachePrisoner.java b/src/main/java/com/graywolf336/jail/beans/CachePrisoner.java index 815e482..0baf1c7 100644 --- a/src/main/java/com/graywolf336/jail/beans/CachePrisoner.java +++ b/src/main/java/com/graywolf336/jail/beans/CachePrisoner.java @@ -2,14 +2,14 @@ package com.graywolf336.jail.beans; /** * An object for storing online cached prisoners. - * + * * @author graywolf336 - * @since 3.0.0 * @version 1.0.0 + * @since 3.0.0 */ public class CachePrisoner { - private Jail jail; - private Prisoner p; + private final Jail jail; + private final Prisoner p; public CachePrisoner(Jail jail, Prisoner prisoner) { this.jail = jail; @@ -18,7 +18,7 @@ public class CachePrisoner { /** * Gets the {@link Jail} this cache is in. - * + * * @return the {@link Jail} instance */ public Jail getJail() { @@ -27,7 +27,7 @@ public class CachePrisoner { /** * Gets the {@link Prisoner} in this cache. - * + * * @return the {@link Prisoner} instance */ public Prisoner getPrisoner() { diff --git a/src/main/java/com/graywolf336/jail/beans/Cell.java b/src/main/java/com/graywolf336/jail/beans/Cell.java index 490331f..790d41f 100644 --- a/src/main/java/com/graywolf336/jail/beans/Cell.java +++ b/src/main/java/com/graywolf336/jail/beans/Cell.java @@ -1,10 +1,8 @@ package com.graywolf336.jail.beans; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; - +import com.graywolf336.jail.Util; +import com.graywolf336.jail.enums.Lang; +import com.graywolf336.jail.interfaces.ICell; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; @@ -12,48 +10,51 @@ import org.bukkit.block.BlockState; import org.bukkit.block.Chest; import org.bukkit.block.Sign; -import com.graywolf336.jail.Util; -import com.graywolf336.jail.enums.Lang; -import com.graywolf336.jail.interfaces.ICell; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; -/** Represents a Cell inside of a {@link Jail}. +/** + * Represents a Cell inside of a {@link Jail}. * * @author graywolf336 - * @since 3.0.0 * @version 1.2.0 + * @since 3.0.0 */ public class Cell implements ICell { - private int databaseid; - private String name; + private final int databaseid; + private final String name; private Prisoner p; - private HashSet signs; + private final HashSet signs; private SimpleLocation teleport, chest; private boolean changed; - /** Creates a new Cell with the given name + /** + * Creates a new Cell with the given name * * @param name The name of the cell. */ public Cell(String name) { this.databaseid = -1; this.name = name; - this.signs = new HashSet(); + this.signs = new HashSet<>(); this.changed = false; } - + /** * Creates a new Cell with the id in the database and the name. - * - * @param id The id of the cell in the database. + * + * @param id The id of the cell in the database. * @param name The name of the cell. */ public Cell(int id, String name) { this.databaseid = id; this.name = name; - this.signs = new HashSet(); + this.signs = new HashSet<>(); this.changed = false; } - + public int getDatabaseID() { return this.databaseid; } @@ -99,38 +100,37 @@ public class Cell implements ICell { } public String getSignString() { - String r = ""; + StringBuilder r = new StringBuilder(); - for(SimpleLocation s : signs) { - if(r.isEmpty()) { - r = s.toString(); - }else { - r += ";" + s.toString(); + for (SimpleLocation s : signs) { + if (r.length() == 0) { + r = new StringBuilder(s.toString()); + } else { + r.append(";").append(s.toString()); } } - return r; + return r.toString(); } - - public List getInvalidSigns() { - List invalid = new ArrayList(); - for(SimpleLocation s : new HashSet(signs)) - if (s.getLocation().getBlock().getState() instanceof Sign) - continue; - else + public List getInvalidSigns() { + List invalid = new ArrayList<>(); + + for (SimpleLocation s : new HashSet<>(signs)) + if (s.getLocation().getBlock().getState() instanceof Sign) { + } + else invalid.add(s.toString()); return invalid; } public List cleanSigns() { - List cleaned = new ArrayList(); + List cleaned = new ArrayList<>(); - for(SimpleLocation s : new HashSet(signs)) { + for (SimpleLocation s : new HashSet<>(signs)) { if (s.getLocation().getBlock().getState() instanceof Sign) { - continue; - }else { + } else { changed = true; signs.remove(s); cleaned.add(s.toString()); @@ -141,16 +141,16 @@ public class Cell implements ICell { } public HashMap> updateSigns() { - List removed = new ArrayList(); - List updated = new ArrayList(); + List removed = new ArrayList<>(); + List updated = new ArrayList<>(); - for(SimpleLocation s : new HashSet(signs)) { + for (SimpleLocation s : new HashSet<>(signs)) { BlockState bs = s.getLocation().getBlock().getState(); if (bs instanceof Sign) { Sign sign = (Sign) bs; - if(hasPrisoner()) { + if (hasPrisoner()) { String[] lines = Util.replaceAllVariables(p, Util.getSignLines()); sign.setLine(0, lines[0]); @@ -158,7 +158,7 @@ public class Cell implements ICell { sign.setLine(2, lines[2]); sign.setLine(3, lines[3]); sign.update(true, false); - }else { + } else { sign.setLine(0, ""); sign.setLine(1, Lang.CELLEMPTYSIGN.get()); sign.setLine(2, ""); @@ -167,14 +167,14 @@ public class Cell implements ICell { } updated.add(s.toString()); - }else { + } else { changed = true; signs.remove(s); removed.add(s.toString()); } } - HashMap> results = new HashMap>(); + HashMap> results = new HashMap<>(); results.put("removed", removed); results.put("updated", updated); @@ -200,8 +200,8 @@ public class Cell implements ICell { } public Chest getChest() { - if(this.chest == null) return null; - if(this.chest.getLocation().getBlock() == null + if (this.chest == null) return null; + if (this.chest.getLocation().getBlock() == null || (this.chest.getLocation().getBlock().getType() != Material.CHEST && this.chest.getLocation().getBlock().getType() != Material.TRAPPED_CHEST)) return null; @@ -210,17 +210,17 @@ public class Cell implements ICell { public boolean hasChest() { Chest c = getChest(); - if(c != null) { - if(c.getInventory().getSize() >= 40) + 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 + } else return false; } - + public boolean useChest() { return this.chest != null; } diff --git a/src/main/java/com/graywolf336/jail/beans/ConfirmPlayer.java b/src/main/java/com/graywolf336/jail/beans/ConfirmPlayer.java index 6686b6e..b894a8f 100644 --- a/src/main/java/com/graywolf336/jail/beans/ConfirmPlayer.java +++ b/src/main/java/com/graywolf336/jail/beans/ConfirmPlayer.java @@ -4,16 +4,16 @@ import com.graywolf336.jail.enums.Confirmation; /** * Holds data for when a player is confirming a command. - * + * * @author graywolf336 * @version 1.0.0 * @since 3.0.0 */ public class ConfirmPlayer { - private String name; - private String[] args; - private Confirmation confirm; - private Long expires; + private final String name; + private final String[] args; + private final Confirmation confirm; + private final Long expires; public ConfirmPlayer(String name, String[] args, Confirmation confirm) { this.name = name; @@ -24,7 +24,7 @@ public class ConfirmPlayer { /** * Returns the name of the thing needing to confirm. - * + * * @return the name of what is being confirmed */ public String getName() { @@ -33,7 +33,7 @@ public class ConfirmPlayer { /** * Returns the initial arguments they sent with their command. - * + * * @return the initial arguments of the original command */ public String[] getArguments() { @@ -42,7 +42,7 @@ public class ConfirmPlayer { /** * Returns what they are {@link Confirmation confirming}. - * + * * @return the {@link Confirmation} of what they're confirming */ public Confirmation getConfirming() { @@ -51,7 +51,7 @@ public class ConfirmPlayer { /** * Returns the time in milliseconds their confirmation time frame expires. - * + * * @return the time their confirming expires */ public Long getExpiryTime() { diff --git a/src/main/java/com/graywolf336/jail/beans/CreationPlayer.java b/src/main/java/com/graywolf336/jail/beans/CreationPlayer.java index b63c341..ea86d59 100644 --- a/src/main/java/com/graywolf336/jail/beans/CreationPlayer.java +++ b/src/main/java/com/graywolf336/jail/beans/CreationPlayer.java @@ -1,20 +1,20 @@ package com.graywolf336.jail.beans; -import java.util.HashSet; - import org.bukkit.Bukkit; import org.bukkit.Location; +import java.util.HashSet; + /** * 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 * + * @author graywolf336 + * @version 1.1.0 + * @since 3.0.0 */ public class CreationPlayer { - private String jailName, cellName; + private final String jailName; + private String cellName; private int step; private int x1, y1, z1, x2, y2, z2; private String inWorld, freeWorld; @@ -25,7 +25,7 @@ public class CreationPlayer { /** * Create a new instance of a CreationPlayer, given the name of the jail. - * + * * @param jailName The name of the jail. */ public CreationPlayer(String jailName) { @@ -35,20 +35,20 @@ public class CreationPlayer { /** * 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.signs = new HashSet<>(); this.step = 1; } /** * Gets the name of the jail. - * + * * @return the name of the jail the player is creating */ public String getJailName() { @@ -57,7 +57,7 @@ public class CreationPlayer { /** * Gets the name of the cell. - * + * * @return the name of the cell the player is creating */ public String getCellName() { @@ -66,9 +66,9 @@ public class CreationPlayer { /** * 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. @@ -76,14 +76,14 @@ public class CreationPlayer { *
  3. Creating the teleport in location.
  4. *
  5. Creating the teleport out location.
  6. *
- * + *

* 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() { @@ -92,7 +92,7 @@ public class CreationPlayer { /** * 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) { @@ -101,13 +101,12 @@ public class CreationPlayer { /** * 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++; @@ -115,7 +114,7 @@ public class CreationPlayer { /** * Sets the first corner with the given location. - * + * * @param loc the location of the first corner */ public void setCornerOne(Location loc) { @@ -126,7 +125,7 @@ public class CreationPlayer { /** * Sets the first corner with the given x, y, and z. - * + * * @param x coordinate of the first corner's x * @param y coordinate of the first corner's x * @param z coordinate of the first corner's x @@ -139,16 +138,16 @@ public class CreationPlayer { /** * Returns the first corner coords an array of int. 0 = x, 1 = y, 2 = z - * + * * @return the first corner coords */ public int[] getCornerOne() { - return new int[] {x1, y1, z1}; + return new int[]{x1, y1, z1}; } /** * Sets the second corner with the given location. - * + * * @param loc The second corner's location */ public void setCornerTwo(Location loc) { @@ -157,29 +156,31 @@ public class CreationPlayer { this.z2 = loc.getBlockZ(); } - /** Sets the second corner with the given x, y, and z. - * + /** + * Sets the second corner with the given x, y, and z. + * * @param x coordinate of the second corner's x * @param y coordinate of the second corner's x * @param z coordinate of the second corner's x - */ + */ 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 - * + /** + * Returns the second corner coords an array of int. 0 = x, 1 = y, 2 = z + * * @return the first corner coords */ public int[] getCornerTwo() { - return new int[] {x2, y2, z2}; + return new int[]{x2, y2, z2}; } /** * Sets the teleport in coords from the given location. - * + * * @param location the in location */ public void setTeleportIn(Location location) { @@ -193,12 +194,12 @@ public class CreationPlayer { /** * Sets the teleport in coords from the given params. - * + * * @param world the name of the world - * @param x the coordinate for x - * @param y the coordinate for y - * @param z the coordinate for z - * @param yaw the yaw of the teleport in + * @param x the coordinate for x + * @param y the coordinate for y + * @param z the coordinate for z + * @param yaw the yaw of the teleport in * @param pitch the pitch of the teleport in */ public void setTeleportIn(String world, double x, double y, double z, float yaw, float pitch) { @@ -212,7 +213,7 @@ public class CreationPlayer { /** * Gets the teleport in location in a {@link Location}. - * + * * @return the teleport in {@link Location} */ public Location getTeleportIn() { @@ -221,7 +222,7 @@ public class CreationPlayer { /** * Gets the teleport in location in a {@link SimpleLocation}. - * + * * @return the {@link SimpleLocation} for the teleportin */ public SimpleLocation getTeleportInSL() { @@ -230,7 +231,7 @@ public class CreationPlayer { /** * Sets the teleport free coords from the given location. - * + * * @param location Sets the teleport free {@link Location} */ public void setTeleportFree(Location location) { @@ -244,12 +245,12 @@ public class CreationPlayer { /** * Sets the teleport free coords from the given params. - * + * * @param world the name of the world - * @param x the coordinate for x - * @param y the coordinate for y - * @param z the coordinate for z - * @param yaw the yaw of the teleport free + * @param x the coordinate for x + * @param y the coordinate for y + * @param z the coordinate for z + * @param yaw the yaw of the teleport free * @param pitch the pitch of the teleport free */ public void setTeleportFree(String world, double x, double y, double z, float yaw, float pitch) { @@ -263,7 +264,7 @@ public class CreationPlayer { /** * Gets the teleport free location in a {@link Location}. - * + * * @return the teleport free {@link Location} */ public Location getTeleportFree() { @@ -272,7 +273,7 @@ public class CreationPlayer { /** * Gets the teleport free location in a {@link SimpleLocation}. - * + * * @return the teleport free {@link SimpleLocation} */ public SimpleLocation getTeleportFreeSL() { @@ -281,7 +282,7 @@ public class CreationPlayer { /** * Adds a sign to this cell. - * + * * @param sign the {@link SimpleLocation} of the sign to add */ public void addSign(SimpleLocation sign) { @@ -290,16 +291,16 @@ public class CreationPlayer { /** * Returns all the signs, null if none (usually null when a jail is being created). - * + * * @return all of the signs, null if none. */ public HashSet getSigns() { - return this.signs == null ? null : new HashSet(this.signs); + return this.signs == null ? null : new HashSet<>(this.signs); } /** * Sets the chest's location, used mainly for cells. - * + * * @param loc the {@link SimpleLocation} of the cheset */ public void setChestLocation(SimpleLocation loc) { @@ -308,7 +309,7 @@ public class CreationPlayer { /** * Gets the chest's location. - * + * * @return the {@link SimpleLocation} of the cheset */ public SimpleLocation getChestLocation() { diff --git a/src/main/java/com/graywolf336/jail/beans/Jail.java b/src/main/java/com/graywolf336/jail/beans/Jail.java index 4112a06..3dbaa82 100644 --- a/src/main/java/com/graywolf336/jail/beans/Jail.java +++ b/src/main/java/com/graywolf336/jail/beans/Jail.java @@ -1,30 +1,30 @@ package com.graywolf336.jail.beans; -import java.util.HashMap; -import java.util.HashSet; -import java.util.UUID; - +import com.graywolf336.jail.JailMain; +import com.graywolf336.jail.Util; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Sign; import org.bukkit.entity.Player; import org.bukkit.util.Vector; -import com.graywolf336.jail.JailMain; -import com.graywolf336.jail.Util; +import java.util.HashMap; +import java.util.HashSet; +import java.util.UUID; -/** Represents a Jail, contains the prisoners and the cells. - * +/** + * Represents a Jail, contains the prisoners and the cells. + * * @author graywolf336 - * @since 3.0.0 * @version 1.0.3 + * @since 3.0.0 */ public class Jail { - private JailMain plugin; + private final JailMain plugin; private boolean enabled; - private HashMap cells; + private final HashMap cells; private HashMap nocellPrisoners;//prisoners who aren't in a cell - private String name = "", world = ""; + private String name, world = ""; private int minX, minY, minZ, maxX, maxY, maxZ; private Location in, free; @@ -32,13 +32,13 @@ public class Jail { this.plugin = plugin; this.enabled = true; this.name = name; - cells = new HashMap(); - nocellPrisoners = new HashMap(); + cells = new HashMap<>(); + nocellPrisoners = new HashMap<>(); } /** * Gets the instance of the plugin's main class. - * + * * @return the {@link JailMain} instance */ public JailMain getPlugin() { @@ -47,7 +47,7 @@ public class Jail { /** * Sets whether this jail can be used or not. - * + * * @param enabled Whether to set if this Jail is enabled or not */ public void setEnabled(boolean enabled) { @@ -56,7 +56,7 @@ public class Jail { /** * Gets whether this jail is enabled or not. - * + * * @return Whether the Jail is enabled or not */ public boolean isEnabled() { @@ -65,7 +65,7 @@ public class Jail { /** * Sets the name of the jail. - * + * * @param name the name of the jail to set */ public void setName(String name) { @@ -74,7 +74,7 @@ public class Jail { /** * Gets the name of the jail. - * + * * @return the name of the jail */ public String getName() { @@ -83,11 +83,11 @@ public class Jail { /** * Sets the location of the minimum point to the given location's coordinates. - * + * * @param location the {@link Location} of the lowest point */ public void setMinPoint(Location location) { - if(this.world.isEmpty()) this.world = location.getWorld().getName(); + if (this.world.isEmpty()) this.world = location.getWorld().getName(); this.minX = location.getBlockX(); this.minY = location.getBlockY(); @@ -96,11 +96,11 @@ public class Jail { /** * Accepts an array of ints as the coord, where 0 = x, 1 = y, 2 = z. - * + * * @param coords the coordinates of the minimum point */ public void setMinPoint(int[] coords) { - if(coords.length != 3) return; + if (coords.length != 3) return; this.minX = coords[0]; this.minY = coords[1]; @@ -109,7 +109,7 @@ public class Jail { /** * Gets the minimum point as a Bukkit Location class. - * + * * @return the {@link Location} of the minimum point. */ public Location getMinPoint() { @@ -118,11 +118,11 @@ public class Jail { /** * Sets the location of the maximum point to the given location's coordinates. - * + * * @param location the {@link Location} of the maximum point */ public void setMaxPoint(Location location) { - if(this.world.isEmpty()) this.world = location.getWorld().getName(); + if (this.world.isEmpty()) this.world = location.getWorld().getName(); this.maxX = location.getBlockX(); this.maxY = location.getBlockY(); @@ -131,107 +131,137 @@ public class Jail { /** * Gets the minimum point as a Bukkit Location class. - * + * * @return the {@link Location} of the maximum point */ 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. */ + /** + * 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; + 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. */ + /** + * 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. */ + /** + * 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. */ + /** + * 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. */ + /** + * Sets the {@link Location location} of the teleport in. + */ public void setTeleportIn(Location location) { - if(this.world.isEmpty()) this.world = location.getWorld().getName(); + if (this.world.isEmpty()) this.world = location.getWorld().getName(); this.in = location; } - /** Gets the {@link Location location} of the teleport in. */ + /** + * 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. */ + /** + * 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.*/ + /** + * Gets the {@link Location location} of the teleport free spot. + */ public Location getTeleportFree() { return this.free; } - /** Add a prisoner to this jail. */ + /** + * 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. */ + /** + * Removes a prisoner from this jail, doesn't remove it from the cell. + */ public void removePrisoner(Prisoner p) { this.nocellPrisoners.remove(p.getUUID()); } - - /** Returns if there are any cells or not. */ + + /** + * Returns if there are any cells or not. + */ public boolean hasCells() { return !this.cells.isEmpty(); } - /** Adds a cell to the Jail. */ + /** + * Adds a cell to the Jail. + */ public boolean addCell(Cell cell, boolean save) { - if(save) plugin.getJailIO().saveCell(this, cell, false); - + if (save) plugin.getJailIO().saveCell(this, cell, false); + //Check if it already exists or not - if(this.cells.containsKey(cell.getName())) return false; + if (this.cells.containsKey(cell.getName())) return false; else this.cells.put(cell.getName(), cell); return true; } - /** Gets the cell with the given name. */ + /** + * 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. */ + /** + * 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. */ + /** + * 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()) { + 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) { + for (SimpleLocation s : c.getSigns()) { + if (s.getLocation().getBlock() instanceof Sign) { Sign sign = (Sign) s.getLocation().getBlock(); - for(int i = 0; i < 4; i++) { + for (int i = 0; i < 4; i++) { sign.setLine(i, ""); } } @@ -243,61 +273,73 @@ public class Jail { this.cells.remove(name); } - /** Returns the cell which the given player name is jailed in, null if not. */ + /** + * 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)) + 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. */ + /** + * 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; + for (Cell c : getCells()) + if (c.hasPrisoner()) { + } else return c; return null; } - - /** Checks if there is an empty cell in this Jail. */ + + /** + * Checks if there is an empty cell in this Jail. + */ public boolean hasEmptyCell() { - for(Cell c : getCells()) - if(!c.hasPrisoner()) + for (Cell c : getCells()) + if (!c.hasPrisoner()) return true; - + return false; } - /** Gets the amount of cells the jail. */ + /** + * Gets the amount of cells the jail. + */ public int getCellCount() { return this.cells.size(); } - /** Gets all the cells in the jail. */ + /** + * Gets all the cells in the jail. + */ public HashSet getCells() { - return new HashSet(this.cells.values()); + return new HashSet<>(this.cells.values()); } - /** Gets the closest cell to the provided location, via the teleport in location of the cells. */ + /** + * 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()) { + 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())) { + 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 { + } else { //If they aren't, return the first cell found. return c; } @@ -306,48 +348,56 @@ public class Jail { return cell; } - /** Clears all the prisoners from this Jail. */ + /** + * Clears all the prisoners from this Jail. + */ public void clearPrisoners() { //Remove the prisoners from all the cells - for(Cell c : getCells()) { + for (Cell c : getCells()) { c.removePrisoner(); } //Replace all the current no cell prisoners with //a new hashset of prisoners. - this.nocellPrisoners = new HashMap(); + this.nocellPrisoners = new HashMap<>(); } - /** Gets a HashMap of all the prisoners, the ones in cells and ones who aren't. */ + /** + * 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 + 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()) + 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. */ + /** + * Gets a HashSet of the prisoners in cells. + */ public HashSet getPrisonersInCells() { - HashSet all = new HashSet(); + HashSet all = new HashSet<>(); - for(Cell c : getCells()) - if(c.hasPrisoner()) + for (Cell c : getCells()) + if (c.hasPrisoner()) all.add(c.getPrisoner()); return all; } - /** Gets a HashSet of the prisoners not in cells.*/ + /** + * 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. */ @@ -357,7 +407,7 @@ public class Jail { /** * 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. */ @@ -367,7 +417,7 @@ public class Jail { /** * 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. */ @@ -377,16 +427,16 @@ public class Jail { /** * 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; + if (this.nocellPrisoners.containsKey(uuid)) return false; - for(Cell c : cells.values()) - if(c.getPrisoner() != null) - if(c.getPrisoner().getUUID().equals(uuid)) + for (Cell c : cells.values()) + if (c.getPrisoner() != null) + if (c.getPrisoner().getUUID().equals(uuid)) return true; return false; @@ -394,13 +444,13 @@ public class Jail { /** * 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)) + for (Prisoner p : this.getAllPrisoners().values()) + if (p.getLastKnownName().equalsIgnoreCase(name)) return p; return null; @@ -408,16 +458,16 @@ public class Jail { /** * 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); + if (this.nocellPrisoners.containsKey(uuid)) return this.nocellPrisoners.get(uuid); - for(Cell c : cells.values()) - if(c.hasPrisoner()) - if(c.getPrisoner().getUUID().equals(uuid)) + for (Cell c : cells.values()) + if (c.hasPrisoner()) + if (c.getPrisoner().getUUID().equals(uuid)) return c.getPrisoner(); return null; @@ -427,7 +477,7 @@ public class Jail { * 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. */ @@ -438,14 +488,14 @@ public class Jail { /** * 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)) { + if (loc.getWorld().getName().equalsIgnoreCase(world)) { return Util.isInsideAB(loc.toVector(), new Vector(minX, minY, minZ), new Vector(maxX, maxY, maxZ)); - }else { + } else { return false; } } diff --git a/src/main/java/com/graywolf336/jail/beans/JailVote.java b/src/main/java/com/graywolf336/jail/beans/JailVote.java index 7d24716..30f585e 100644 --- a/src/main/java/com/graywolf336/jail/beans/JailVote.java +++ b/src/main/java/com/graywolf336/jail/beans/JailVote.java @@ -1,93 +1,100 @@ package com.graywolf336.jail.beans; -import java.util.ArrayList; -import java.util.UUID; - import org.bukkit.Bukkit; import org.bukkit.entity.Player; +import java.util.ArrayList; +import java.util.UUID; + /** * Represents a vote to jail someone. - * + * * @author graywolf336 - * @since 3.0.0 * @version 1.0.0 + * @since 3.0.0 */ public class JailVote { - private String name; - private ArrayList voters; + private final String name; + private final ArrayList voters; private int yes, no; - + /** * Initiates a vote to jail someone, with the vote being for the given player. - * + * * @param player the name of the player the vote is for */ public JailVote(String player) { this.name = player; - this.voters = new ArrayList(); + this.voters = new ArrayList<>(); this.yes = 0; this.no = 0; } - - /** The name of the player the vote is for. */ + + /** + * The name of the player the vote is for. + */ public String getPlayerName() { return this.name; } - + /** * Gets the player who the vote is for, from the player name. - * + * * @return the player who the vote is for to jail */ - @SuppressWarnings("deprecation") public Player getPlayer() { return Bukkit.getPlayer(name); } - - /** Checks if the player with the given id has voted already. */ + + /** + * Checks if the player with the given id has voted already. + */ public boolean hasVoted(UUID id) { return this.voters.contains(id); } - + /** * Method to vote yes, providing the uuid of the person doing the voting. - * + * * @param id the uuid of the voter * @return true if it was success, false if they already voted */ public boolean voteYes(UUID id) { - if(this.voters.contains(id)) { + if (this.voters.contains(id)) { return false; - }else { + } else { this.voters.add(id); this.yes++; return true; } } - + /** * Method to vote no, providing the uuid of the person doing the voting. - * + * * @param id the uuid of the voter * @return true if it was success, false if they already voted */ public boolean voteNo(UUID id) { - if(this.voters.contains(id)) { + if (this.voters.contains(id)) { return false; - }else { + } else { this.voters.add(id); this.no++; return true; } } - - /** Get the amount of yes votes. */ + + /** + * Get the amount of yes votes. + */ public int getYesVotes() { return this.yes; } - - /** Get the amount of no votes. */ + + /** + * Get the amount of no votes. + */ public int getNoVotes() { return this.no; } diff --git a/src/main/java/com/graywolf336/jail/beans/NoCell.java b/src/main/java/com/graywolf336/jail/beans/NoCell.java index 5cab844..8610247 100644 --- a/src/main/java/com/graywolf336/jail/beans/NoCell.java +++ b/src/main/java/com/graywolf336/jail/beans/NoCell.java @@ -1,21 +1,19 @@ package com.graywolf336.jail.beans; +import com.graywolf336.jail.interfaces.ICell; +import org.bukkit.Location; +import org.bukkit.block.Chest; + import java.util.HashMap; import java.util.HashSet; import java.util.List; -import org.bukkit.Location; -import org.bukkit.block.Chest; - -import com.graywolf336.jail.interfaces.ICell; - /** * Pass this an instance of this class into the jailing of a player and they won't go into a cell. * * @author graywolf336 - * @since 3.0.0 * @version 1.0.0 - * + * @since 3.0.0 */ public class NoCell implements ICell { public int getDatabaseID() { @@ -97,7 +95,7 @@ public class NoCell implements ICell { public boolean hasChest() { throw new UnsupportedOperationException(); } - + public boolean useChest() { throw new UnsupportedOperationException(); } diff --git a/src/main/java/com/graywolf336/jail/beans/Prisoner.java b/src/main/java/com/graywolf336/jail/beans/Prisoner.java index d44a714..c5c8ec0 100644 --- a/src/main/java/com/graywolf336/jail/beans/Prisoner.java +++ b/src/main/java/com/graywolf336/jail/beans/Prisoner.java @@ -1,36 +1,40 @@ package com.graywolf336.jail.beans; -import java.util.UUID; -import java.util.concurrent.TimeUnit; - +import com.graywolf336.jail.enums.Lang; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.entity.Player; -import com.graywolf336.jail.enums.Lang; +import java.util.UUID; +import java.util.concurrent.TimeUnit; /** * Represents a Prisoner, player who is jailed, and contains all the information about him/her. * * @author graywolf336 - * @since 2.x.x * @version 3.1.1 + * @since 2.x.x */ public class Prisoner { - private String uuid, name, jailer, reason, inventory, armor; + private final String uuid; + private String name; + private String jailer; + private String reason; + private String inventory; + private String armor; private boolean muted = true, offlinePending = false, teleporting = false, toBeTransferred = false, changed = false; - private long time = -1L, afk = 0L; + private long time, afk = 0L; private Location previousPosition; private GameMode previousGameMode; /** * Creates the prisoner instance with the lot of data provided. * - * @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 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 */ @@ -47,9 +51,9 @@ public class Prisoner { /** * Creates the prisoner instance with the lot of data provided. * - * @param uuid The uuid of the prisoner - * @param name The name of the prisoner - * @param time The amount of remaining time the prisoner has + * @param uuid The uuid of the prisoner + * @param name The name of the prisoner + * @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 */ @@ -65,9 +69,9 @@ public class Prisoner { /** * Creates the prisoner instance with the lot of data provided. * - * @param uuid The uuid of the prisoner - * @param name The name of the prisoner - * @param time The amount of remaining time the prisoner has + * @param uuid The uuid of the prisoner + * @param name The name of the prisoner + * @param time The amount of remaining time the prisoner has * @param reason The reason why this prisoner is in jail */ public Prisoner(String uuid, String name, long time, String reason) { @@ -96,8 +100,8 @@ public class Prisoner { * Creates the prisoner instance with the data provided. * * @param player The instance of the player who is to be jailed - * @param muted Whether the prisoner is muted or not - * @param time The amount of remaining time the prisoner has + * @param muted Whether the prisoner is muted or not + * @param time The amount of remaining time the prisoner has * @param jailer The jailer who jailed the prisoner * @param reason The reason why this prisoner is in jail */ @@ -115,7 +119,7 @@ public class Prisoner { * Creates the prisoner instance with the data provided. * * @param player The instance of the player who is to be jailed - * @param time The amount of remaining time the prisoner has + * @param time The amount of remaining time the prisoner has * @param jailer The jailer who jailed the prisoner * @param reason The reason why this prisoner is in jail */ @@ -132,7 +136,7 @@ public class Prisoner { * The most basic prisoner instance creation via providing the player, time, and reason. * * @param player The instance of the player who is to be jailed - * @param time The amount of remaining time the prisoner has + * @param time The amount of remaining time the prisoner has * @param reason The reason why this prisoner is in jail */ public Prisoner(Player player, long time, String reason) { @@ -147,7 +151,7 @@ public class Prisoner { * The most basic prisoner instance creation via providing the player and time. * * @param player The instance of the player who is to be jailed - * @param time The amount of remaining time the prisoner has + * @param time The amount of remaining time the prisoner has */ public Prisoner(Player player, long time) { this.uuid = player.getUniqueId().toString(); @@ -156,39 +160,49 @@ public class Prisoner { finishSetup(); } - /** Finishes the setup of the prisoner data, set to defaults. */ + /** + * Finishes the setup of the prisoner data, set to defaults. + */ private void finishSetup() { - if(jailer == null) + if (jailer == null) jailer = Lang.DEFAULTJAILER.get(); - if(reason == null) + if (reason == null) Lang.DEFAULTJAILEDREASON.get(); - if(inventory == null) + if (inventory == null) inventory = ""; - if(armor == null) + if (armor == null) armor = ""; - if(previousGameMode == null) + if (previousGameMode == null) previousGameMode = GameMode.SURVIVAL; previousPosition = null; } - /** Returns the UUID of the prisoner. */ + /** + * Returns the UUID of the prisoner. + */ public UUID getUUID() { return UUID.fromString(this.uuid); } - /** Gets the name of this prisoner. */ + /** + * Gets the name of this prisoner. + */ public String getLastKnownName() { return this.name; } - /** Sets the name of this prisoner. */ + /** + * 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. */ + /** + * Gets the reason this player was jailed for. + */ public String getReason() { return this.reason; } @@ -205,44 +219,60 @@ public class Prisoner { return this.reason; } - /** Gets the person who jailed this prisoner. */ + /** + * Gets the person who jailed this prisoner. + */ public String getJailer() { return this.jailer; } - /** Sets the person who jailed this prisoner. */ + /** + * 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. */ + /** + * Gets whether the prisoner is muted or not. + */ public boolean isMuted() { return this.muted; } - /** Sets whether the prisoner is muted or not. */ + /** + * Sets whether the prisoner is muted or not. + */ public void setMuted(boolean muted) { this.muted = muted; this.changed = true; } - - /** Gets whether the prisoner is jailed forever or not. */ + + /** + * Gets whether the prisoner is jailed forever or not. + */ public boolean isJailedForever() { return this.time == -1; } - /** Gets the remaining time the prisoner has. */ + /** + * Gets the remaining time the prisoner has. + */ public long getRemainingTime() { return this.time; } - /** Gets the remaining time the prisoner has in minutes. */ + /** + * 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. */ + /** + * Gets the remaining time the prison has in minutes except only in int format. + */ public int getRemainingTimeInMinutesInt() { return (int) this.getRemainingTimeInMinutes(); } @@ -264,7 +294,7 @@ public class Prisoner { * @return the new remaining time the prisoner has */ public long addTime(long time) { - if(this.time != -1L) { + if (this.time != -1L) { this.time += time; this.changed = true; } @@ -279,7 +309,7 @@ public class Prisoner { * @return the new remaining time the prisoner has */ public long subtractTime(long time) { - if(this.time != -1L) { + if (this.time != -1L) { this.time -= time; this.changed = true; } @@ -287,132 +317,174 @@ public class Prisoner { return this.time; } - /** Gets whether the player is offline or not. */ + /** + * Gets whether the player is offline or not. + */ public boolean isOfflinePending() { return this.offlinePending; } - /** Sets whether the player is offline or not. */ + /** + * 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. */ + /** + * Gets whether the player is being teleported or not. + */ public boolean isTeleporting() { return this.teleporting; } - /** Sets whether the player is being teleported or not. */ + /** + * 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. */ + /** + * 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. */ + /** + * 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. */ + /** + * 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. */ + /** + * Gets the previous location of this player, separated by a comma. + */ public String getPreviousLocationString() { - if(previousPosition == null) return ""; - else if(previousPosition.getWorld() == null) return ""; + 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(); + previousPosition.getX() + "," + + previousPosition.getY() + "," + + previousPosition.getZ() + "," + + previousPosition.getYaw() + "," + + previousPosition.getPitch(); } - /** Sets the previous location of this player. */ + /** + * 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. */ + /** + * 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; + 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])); + Double.parseDouble(s[1]), + Double.parseDouble(s[2]), + Double.parseDouble(s[3]), + Float.parseFloat(s[4]), + Float.parseFloat(s[5])); } - /** Gets the previous gamemode of this player. */ + /** + * Gets the previous gamemode of this player. + */ public GameMode getPreviousGameMode() { return this.previousGameMode; } - /** Sets the previous gamemode of this player. */ + /** + * 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. */ + /** + * 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; + 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. */ + /** + * Gets the inventory string for this player, it is encoded in Base64 string. + */ public String getInventory() { return this.inventory; } - /** Sets the inventory Base64 string. */ + /** + * Sets the inventory Base64 string. + */ public void setInventory(String inventory) { this.inventory = inventory; this.changed = true; } - /** Gets the armor content, encoded in Base64 string. */ + /** + * Gets the armor content, encoded in Base64 string. + */ public String getArmor() { return this.armor; } - /** Sets the armor inventory Base64 string. */ + /** + * 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. */ + /** + * 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. */ + /** + * 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. */ + /** + * Checks if the prisoner was changed or not. + */ public boolean wasChanged() { return this.changed; } - /** Sets whether the prisoner was changed or not. */ + /** + * 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 2125989..0f884db 100644 --- a/src/main/java/com/graywolf336/jail/beans/SimpleLocation.java +++ b/src/main/java/com/graywolf336/jail/beans/SimpleLocation.java @@ -6,24 +6,26 @@ import org.bukkit.World; /** * Simple location class which doesn't store any instances of {@link World worlds} or {@link org.bukkit.block.Block blocks}, just uses strings, floats, and doubles. - * + * * @author graywolf336 - * @since 3.0.0 * @version 1.1.1 + * @since 3.0.0 */ public class SimpleLocation { - private String world; - private double x, y, z; + private final String world; + private final double x; + private final double y; + private final double 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 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) { @@ -37,7 +39,7 @@ public class SimpleLocation { /** * Creates a new SimpleLocation with all the detail provided from {@link Location}. - * + * * @param location to convert to a SimpleLocation */ public SimpleLocation(Location location) { @@ -51,28 +53,28 @@ public class SimpleLocation { /** * 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 + * @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.x = Double.parseDouble(x); + this.y = Double.parseDouble(y); + this.z = Double.parseDouble(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 + * @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; @@ -81,17 +83,23 @@ public class SimpleLocation { this.z = z; } - /** Returns the instance from Bukkit of the world this location is in. */ + /** + * 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. */ + /** + * Returns the name of the world this location is in. + */ public String getWorldName() { return this.world; } - /** Returns a new {@link Location} from this SimpleLocation. */ + /** + * Returns a new {@link Location} from this SimpleLocation. + */ public Location getLocation() { return new Location(Bukkit.getWorld(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 1bfe17e..6090d33 100644 --- a/src/main/java/com/graywolf336/jail/beans/Stick.java +++ b/src/main/java/com/graywolf336/jail/beans/Stick.java @@ -2,22 +2,23 @@ package com.graywolf336.jail.beans; /** * Represents a Jail Stick, contains all the information. - * + * * @author graywolf336 * @version 1.0.1 * @since 3.0.0 */ public class Stick { - private String jail, reason; - private long time; - private double health; + private final String jail; + private final String reason; + private final long time; + private final double health; /** * Creates a new Jail Stick instance. - * - * @param jail the player will be jailed in. + * + * @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 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) { @@ -29,7 +30,7 @@ public class Stick { /** * Gets the name of the jail a player will be sent when jailed via this jail stick. - * + * * @return the name of the jail this stick puts people in */ public String getJail() { @@ -38,7 +39,7 @@ public class Stick { /** * Gets the reason a player will be jailed for when jailed via this stick. - * + * * @return the reason of jailing used by this stick */ public String getReason() { @@ -47,17 +48,18 @@ public class Stick { /** * Gets the amount of time a player has to serve when they are jailed via this stick. - * + * * @return the amount of time someone is 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. - * + /** + * 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() { diff --git a/src/main/java/com/graywolf336/jail/command/Command.java b/src/main/java/com/graywolf336/jail/command/Command.java index c9021da..1bb701a 100644 --- a/src/main/java/com/graywolf336/jail/command/Command.java +++ b/src/main/java/com/graywolf336/jail/command/Command.java @@ -1,35 +1,34 @@ package com.graywolf336.jail.command; +import com.graywolf336.jail.JailManager; +import org.bukkit.command.CommandSender; + import java.util.List; -import org.bukkit.command.CommandSender; - -import com.graywolf336.jail.JailManager; - /** * The base of all the commands. - * + * * @author graywolf336 - * @since 3.0.0 * @version 1.1.0 + * @since 3.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 jm An instance of the {@link JailManager} * @param sender The {@link CommandSender sender} of the command - * @param args The args, in an array + * @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; - - public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception; + boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception; + + List provideTabCompletions(JailManager jm, CommandSender sender, String... args); } diff --git a/src/main/java/com/graywolf336/jail/command/CommandHandler.java b/src/main/java/com/graywolf336/jail/command/CommandHandler.java index 46ff95c..216951d 100644 --- a/src/main/java/com/graywolf336/jail/command/CommandHandler.java +++ b/src/main/java/com/graywolf336/jail/command/CommandHandler.java @@ -1,14 +1,5 @@ package com.graywolf336.jail.command; -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map.Entry; - -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - import com.graywolf336.jail.JailMain; import com.graywolf336.jail.JailManager; import com.graywolf336.jail.command.commands.HandCuffCommand; @@ -17,42 +8,50 @@ import com.graywolf336.jail.command.commands.UnHandCuffCommand; import com.graywolf336.jail.command.commands.UnJailCommand; import com.graywolf336.jail.command.commands.UnJailForceCommand; import com.graywolf336.jail.enums.Lang; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map.Entry; /** * Where all the commands are registered, handled, and processed. - * - * @author graywolf336 - * @since 3.0.0 - * @version 1.0.2 * + * @author graywolf336 + * @version 1.0.2 + * @since 3.0.0 */ public class CommandHandler { - private LinkedHashMap commands; + private final LinkedHashMap commands; public CommandHandler(JailMain plugin) { - commands = new LinkedHashMap(); + commands = new LinkedHashMap<>(); loadCommands(); plugin.debug("Loaded " + commands.size() + " commands."); } - - public List parseTabComplete(JailManager jm, CommandSender sender, String commandLine, String[] args) throws Exception { + + public List parseTabComplete(JailManager jm, CommandSender sender, String commandLine, String[] args) { List matches = getMatches(commandLine); - - if(matches.isEmpty() || matches.size() > 1) return Collections.emptyList(); + + if (matches.size() != 1) return Collections.emptyList(); else { CommandInfo i = matches.get(0).getClass().getAnnotation(CommandInfo.class); - + //Sender provided too many arguments which means there //is nothing to tab complete - if(i.maxArgs() != -1 && i.maxArgs() < args.length) return Collections.emptyList(); - + if (i.maxArgs() != -1 && i.maxArgs() < args.length) return Collections.emptyList(); + //Don't return anything if a player is required and they're not a player - if(i.needsPlayer() && !(sender instanceof Player)) return Collections.emptyList(); - + if (i.needsPlayer() && !(sender instanceof Player)) return Collections.emptyList(); + //Don't return anything if they don't have permission - if(!sender.hasPermission(i.permission())) return Collections.emptyList(); - + if (!sender.hasPermission(i.permission())) return Collections.emptyList(); + //Let the command handle the rest of it return matches.get(0).provideTabCompletions(jm, sender, args); } @@ -60,9 +59,9 @@ public class CommandHandler { /** * 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. @@ -73,27 +72,25 @@ public class CommandHandler { *
  3. If the required maximum arguments have been passed (if there is a max, -1 if no max), if not sends the usage.
  4. *
  5. Then executes, upon failed execution it sends the usage command.
  6. *
- * + * * @param jailmanager The instance of {@link JailManager}. - * @param sender The sender of the command. + * @param sender The sender of the command. * @param commandLine The name of the command. - * @param args The arguments passed to 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.isEmpty()) { - if(commandLine.startsWith("jail")) { + if (matches.isEmpty()) { + if (commandLine.startsWith("jail")) { String j = commandLine.substring(0, 4); - String a0 = commandLine.substring(4, commandLine.length()); + String a0 = commandLine.substring(4); - ArrayList args2 = new ArrayList(); - for(String s : args) - args2.add(s); + ArrayList args2 = new ArrayList<>(Arrays.asList(args)); args2.add(a0); - if(jailmanager.getPlugin().onCommand(sender, null, j, args2.toArray(new String[args2.size()]))) + if (jailmanager.getPlugin().onCommand(sender, null, j, args2.toArray(new String[0]))) return; } @@ -102,8 +99,8 @@ public class CommandHandler { } //If more than one command was found, send them each command's help message. - if(matches.size() > 1) { - for(Command c : matches) + if (matches.size() > 1) { + for (Command c : matches) showUsage(sender, c); return; } @@ -112,25 +109,25 @@ public class CommandHandler { CommandInfo i = c.getClass().getAnnotation(CommandInfo.class); // First, let's check if the sender has permission for the command. - if(!sender.hasPermission(i.permission())) { + 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)) { + 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()) { + 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) { + if (i.maxArgs() != -1 && i.maxArgs() < args.length) { showUsage(sender, c); return; } @@ -138,9 +135,8 @@ public class CommandHandler { // 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)) { + if (!c.execute(jailmanager, sender, args)) { showUsage(sender, c); - return; } } catch (Exception e) { e.printStackTrace(); @@ -150,10 +146,10 @@ public class CommandHandler { } private List getMatches(String command) { - List result = new ArrayList(); + List result = new ArrayList<>(); - for(Entry entry : commands.entrySet()) { - if(command.matches(entry.getKey())) { + for (Entry entry : commands.entrySet()) { + if (command.matches(entry.getKey())) { result.add(entry.getValue()); } } @@ -163,18 +159,20 @@ public class CommandHandler { /** * Shows the usage information to the sender, if they have permission. - * - * @param sender The sender of the command + * + * @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; + if (!sender.hasPermission(info.permission())) return; sender.sendMessage(info.usage()); } - /** Loads all the commands into the hashmap. */ + /** + * Loads all the commands into the hashmap. + */ private void loadCommands() { load(HandCuffCommand.class); load(ToggleJailDebugCommand.class); @@ -185,11 +183,11 @@ public class CommandHandler { private void load(Class c) { CommandInfo info = c.getAnnotation(CommandInfo.class); - if(info == null) return; + if (info == null) return; try { commands.put(info.pattern(), c.newInstance()); - }catch(Exception e) { + } 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 b6265ba..88f1aef 100644 --- a/src/main/java/com/graywolf336/jail/command/CommandInfo.java +++ b/src/main/java/com/graywolf336/jail/command/CommandInfo.java @@ -5,9 +5,9 @@ import java.lang.annotation.RetentionPolicy; /** * Contains a definition of all the annotations {@link Command commands} should have, if a {@link Command command} doesn't have any then it isn't registered. - * + * + *

*

- * * This helps make loading and registering and verifying commands a lot * easier, makes sure that before we really process a command that it * is structured correctly and all the right information is passed. If @@ -23,56 +23,55 @@ 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 * + * @author graywolf336 + * @version 1.0.0 + * @since 3.0.0 */ -@Retention (RetentionPolicy.RUNTIME) +@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(); + int maxArgs(); /** * Gets the minimum amount of arguments required. - * + * * @return The minimum number of arguments required. */ - public int minimumArgs(); + int minimumArgs(); /** * Whether the command needs a player context or not. - * + * * @return True if requires a player, false if not. */ - public boolean needsPlayer(); + 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(); + String pattern(); /** * Gets the permission required to execute this command. - * + * * @return The permission required. */ - public String permission(); + String permission(); /** * Gets the usage message for this command. - * + * * @return The usage message. */ - public String usage(); - + String usage(); + // /** // * Gets the help messages for this command, color codes enabled. // * diff --git a/src/main/java/com/graywolf336/jail/command/JailHandler.java b/src/main/java/com/graywolf336/jail/command/JailHandler.java index 2be3e4d..8e0d48b 100644 --- a/src/main/java/com/graywolf336/jail/command/JailHandler.java +++ b/src/main/java/com/graywolf336/jail/command/JailHandler.java @@ -1,14 +1,5 @@ package com.graywolf336.jail.command; -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map.Entry; - -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - import com.graywolf336.jail.JailMain; import com.graywolf336.jail.JailManager; import com.graywolf336.jail.command.subcommands.JailCheckCommand; @@ -39,104 +30,111 @@ import com.graywolf336.jail.command.subcommands.JailTransferCommand; import com.graywolf336.jail.command.subcommands.JailVersionCommand; import com.graywolf336.jail.command.subcommands.JailVoteCommand; import com.graywolf336.jail.enums.Lang; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map.Entry; /** * Where all the jail commands are registered, handled, and processed at. - * - * @author graywolf336 - * @since 3.0.0 - * @version 1.1.0 * + * @author graywolf336 + * @version 1.1.0 + * @since 3.0.0 */ public class JailHandler { - private LinkedHashMap commands; + private final LinkedHashMap commands; public JailHandler(JailMain plugin) { - commands = new LinkedHashMap(); + commands = new LinkedHashMap<>(); loadCommands(); plugin.debug("Loaded " + commands.size() + " sub-commands of /jail."); } - - public List parseTabComplete(JailManager jm, CommandSender sender, String[] args) throws Exception { - if(args[0].isEmpty() || args.length == 1) { - List results = new ArrayList(); + + public List parseTabComplete(JailManager jm, CommandSender sender, String[] args) { + if (args[0].isEmpty() || args.length == 1) { + List results = new ArrayList<>(); String arg0 = args[0].toLowerCase(); boolean hasJailPermission = false; - - for(Command c : commands.values()) { + + for (Command c : commands.values()) { CommandInfo i = c.getClass().getAnnotation(CommandInfo.class); //Skip the jail subcommand instance, since it is unique - if(i.pattern().equalsIgnoreCase("jail|j")) { + if (i.pattern().equalsIgnoreCase("jail|j")) { hasJailPermission = sender.hasPermission(i.permission()); continue; } - + //Skip if the command requires a player and the sender isn't a player - if(i.needsPlayer() && !(sender instanceof Player)) continue; - + if (i.needsPlayer() && !(sender instanceof Player)) continue; + //If the sender has permission to the command //and the first argument (sub command) is empty OR //the first argument matches the command or starts with the string - if(sender.hasPermission(i.permission()) && (arg0.isEmpty() || (arg0.toLowerCase().matches(i.pattern()) || i.pattern().startsWith(arg0)))) { + if (sender.hasPermission(i.permission()) && (arg0.isEmpty() || (arg0.toLowerCase().matches(i.pattern()) || i.pattern().startsWith(arg0)))) { results.add(i.pattern().split("\\|")[0]); } } - + //Sort the results before adding the player names Collections.sort(results); - + //If the results doesn't contain anything and they have permission to jail someone //then send let the jail command provide the tab completion - if(results.isEmpty() && hasJailPermission) + if (results.isEmpty() && hasJailPermission) return getMatches("jail").get(0).provideTabCompletions(jm, sender, args); else return results; - }else { + } else { String arg0 = args[0].toLowerCase(); boolean hasJailPermission = false; - - for(Command c : commands.values()) { + + for (Command c : commands.values()) { CommandInfo i = c.getClass().getAnnotation(CommandInfo.class); - + //since the pattern won't ever match the jail plugin //we can skip it but first we need to see if they have //permission to do the jailing - if(i.pattern().equalsIgnoreCase("jail|j")) { + if (i.pattern().equalsIgnoreCase("jail|j")) { hasJailPermission = sender.hasPermission(i.permission()); continue; } - - if(!arg0.toLowerCase().matches(i.pattern())) continue; - + + if (!arg0.toLowerCase().matches(i.pattern())) continue; + //Sender provided too many arguments which means there //is nothing to tab complete - if(i.maxArgs() != -1 && i.maxArgs() < args.length - 1) continue; - + if (i.maxArgs() != -1 && i.maxArgs() < args.length - 1) continue; + //Skip if the command requires a player and the sender isn't a player - if(i.needsPlayer() && !(sender instanceof Player)) continue; - + if (i.needsPlayer() && !(sender instanceof Player)) continue; + //If the sender doesn't have permission, we won't send them further - if(!sender.hasPermission(i.permission())) continue; - + if (!sender.hasPermission(i.permission())) continue; + return c.provideTabCompletions(jm, sender, args); } - + //By the time it has reached here no other command matched //which means they are probably jailing someone, or trying to //so let's check permission first and go from there. - if(hasJailPermission) + if (hasJailPermission) return getMatches("jail").get(0).provideTabCompletions(jm, sender, args); } - + return Collections.emptyList(); } /** * 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. @@ -145,35 +143,35 @@ public class JailHandler { *
  3. If the required maximum arguments have been passed (if there is a max, -1 if no max), if not sends the usage.
  4. *
  5. Then executes, upon failed execution it sends the usage command.
  6. *
- * + * * @param jailmanager The instance of {@link JailManager}. - * @param sender The sender of the command. - * @param args The arguments passed to the command. + * @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; + Command c; //If they didn't provide any arguments (aka just: /jail) then we will need to send them some help - if(args.length == 0) { + if (args.length == 0) { //TODO: Create the help page(s) c = getMatches("jail").get(0); - }else { + } else { //Get the matches from the first argument passed List matches = getMatches(args[0].toLowerCase()); - if(matches.isEmpty()) { + if (matches.isEmpty()) { //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) { + } 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) + for (Command cmd : matches) showUsage(sender, cmd); return true; - }else { + } else { //Only one match was found, so let's continue c = matches.get(0); } @@ -182,14 +180,14 @@ public class JailHandler { CommandInfo i = c.getClass().getAnnotation(CommandInfo.class); // First, let's check if the sender has permission for the command. - if(!i.permission().isEmpty() && !sender.hasPermission(i.permission())) { - jailmanager.getPlugin().debug("Sender has no permission: " + i.permission()); + if (!i.permission().isEmpty() && !sender.hasPermission(i.permission())) { + jailmanager.getPlugin().debug("Sender has no permission: " + i.permission()); sender.sendMessage(Lang.NOPERMISSION.get() + (jailmanager.getPlugin().inDebug() ? " (" + i.permission() + ")" : "")); 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)) { + if (i.needsPlayer() && !(sender instanceof Player)) { jailmanager.getPlugin().debug("Sender is not a player."); sender.sendMessage(Lang.PLAYERCONTEXTREQUIRED.get()); return true; @@ -197,7 +195,7 @@ public class JailHandler { // 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()) { + if (args.length - 1 < i.minimumArgs()) { jailmanager.getPlugin().debug("Sender didn't provide enough arguments."); showUsage(sender, c); return true; @@ -205,7 +203,7 @@ public class JailHandler { // 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) { + if (i.maxArgs() != -1 && i.maxArgs() < args.length - 1) { jailmanager.getPlugin().debug("Sender provided too many arguments."); showUsage(sender, c); return true; @@ -214,14 +212,14 @@ public class JailHandler { // 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)) { + if (!c.execute(jailmanager, sender, args)) { showUsage(sender, c); return true; - }else { + } else { return true; } } catch (Exception e) { - if(jailmanager.getPlugin().inDebug()) { + if (jailmanager.getPlugin().inDebug()) { e.printStackTrace(); } @@ -232,10 +230,10 @@ public class JailHandler { } private List getMatches(String command) { - List result = new ArrayList(); + List result = new ArrayList<>(); - for(Entry entry : commands.entrySet()) { - if(command.matches(entry.getKey())) { + for (Entry entry : commands.entrySet()) { + if (command.matches(entry.getKey())) { result.add(entry.getValue()); } } @@ -245,13 +243,13 @@ public class JailHandler { /** * Shows the usage information to the sender, if they have permission. - * - * @param sender The sender of the command + * + * @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; + if (!sender.hasPermission(info.permission())) return; sender.sendMessage(info.usage()); } @@ -286,13 +284,13 @@ public class JailHandler { load(JailVoteCommand.class); } - private void load(Class c) { - CommandInfo info = c.getAnnotation(CommandInfo.class); - if(info == null) return; + private void load(Class command) { + CommandInfo info = command.getAnnotation(CommandInfo.class); + if (info == null) return; try { - commands.put(info.pattern(), c.newInstance()); - }catch(Exception e) { + commands.put(info.pattern(), command.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 3475f39..b512e3e 100644 --- a/src/main/java/com/graywolf336/jail/command/commands/HandCuffCommand.java +++ b/src/main/java/com/graywolf336/jail/command/commands/HandCuffCommand.java @@ -1,17 +1,16 @@ package com.graywolf336.jail.command.commands; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.util.StringUtil; - import com.graywolf336.jail.JailManager; import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Lang; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; @CommandInfo( maxArgs = 1, @@ -20,23 +19,22 @@ import com.graywolf336.jail.enums.Lang; pattern = "handcuff|hc", permission = "jail.command.handcuff", usage = "/handcuff [player]" - ) +) public class HandCuffCommand implements Command { - @SuppressWarnings("deprecation") public boolean execute(JailManager jm, CommandSender sender, String... args) { Player player = jm.getPlugin().getServer().getPlayer(args[0]); - if(player == null) { + if (player == null) { sender.sendMessage(Lang.PLAYERNOTONLINE.get()); - }else if(player.hasPermission("jail.cantbehandcuffed")) { + } else if (player.hasPermission("jail.cantbehandcuffed")) { sender.sendMessage(Lang.CANTBEHANDCUFFED.get(player.getName())); - }else if(jm.isPlayerJailed(player.getUniqueId())) { + } else if (jm.isPlayerJailed(player.getUniqueId())) { sender.sendMessage(Lang.CURRENTLYJAILEDHANDCUFF.get(player.getName())); - }else if(jm.getPlugin().getHandCuffManager().isHandCuffed(player.getUniqueId())) { + } 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 { + } else { jm.getPlugin().getHandCuffManager().addHandCuffs(player.getUniqueId(), player.getLocation()); sender.sendMessage(Lang.HANDCUFFSON.get(player.getName())); player.sendMessage(Lang.HANDCUFFED.get()); @@ -45,17 +43,17 @@ public class HandCuffCommand implements Command { return true; } - public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception { - List results = new ArrayList(); - - for(Player p : jm.getPlugin().getServer().getOnlinePlayers()) - if(!jm.getPlugin().getHandCuffManager().isHandCuffed(p.getUniqueId())) //don't send someone who is already handcuffed - if(!p.hasPermission("jail.cantbehandcuffed")) //don't send someone who can't be handcuffed - if(args[0].isEmpty() || StringUtil.startsWithIgnoreCase(p.getName(), args[0])) + public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) { + List results = new ArrayList<>(); + + for (Player p : jm.getPlugin().getServer().getOnlinePlayers()) + if (!jm.getPlugin().getHandCuffManager().isHandCuffed(p.getUniqueId())) //don't send someone who is already handcuffed + if (!p.hasPermission("jail.cantbehandcuffed")) //don't send someone who can't be handcuffed + if (args[0].isEmpty() || StringUtil.startsWithIgnoreCase(p.getName(), args[0])) results.add(p.getName()); - + Collections.sort(results); - + return results; } } 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 b9723d7..9716c06 100644 --- a/src/main/java/com/graywolf336/jail/command/commands/ToggleJailDebugCommand.java +++ b/src/main/java/com/graywolf336/jail/command/commands/ToggleJailDebugCommand.java @@ -1,14 +1,13 @@ package com.graywolf336.jail.command.commands; -import java.util.Collections; -import java.util.List; - -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; - import com.graywolf336.jail.JailManager; import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.CommandInfo; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; + +import java.util.Collections; +import java.util.List; @CommandInfo( maxArgs = 0, @@ -17,7 +16,7 @@ import com.graywolf336.jail.command.CommandInfo; 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()); @@ -25,7 +24,7 @@ public class ToggleJailDebugCommand implements Command { return true; } - public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception { + public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) { //No tab completion required for toggling debug command return Collections.emptyList(); } 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 6d9844e..e303df5 100644 --- a/src/main/java/com/graywolf336/jail/command/commands/UnHandCuffCommand.java +++ b/src/main/java/com/graywolf336/jail/command/commands/UnHandCuffCommand.java @@ -1,17 +1,16 @@ package com.graywolf336.jail.command.commands; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.util.StringUtil; - import com.graywolf336.jail.JailManager; import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Lang; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; @CommandInfo( maxArgs = 1, @@ -20,35 +19,34 @@ import com.graywolf336.jail.enums.Lang; pattern = "unhandcuff|uhc", permission = "jail.command.handcuff", usage = "/unhandcuff [player]" - ) +) public class UnHandCuffCommand implements Command { - @SuppressWarnings("deprecation") public boolean execute(JailManager jm, CommandSender sender, String... args) { Player player = jm.getPlugin().getServer().getPlayerExact(args[0]); - if(player == null) { + if (player == null) { sender.sendMessage(Lang.PLAYERNOTONLINE.get()); - }else if(jm.getPlugin().getHandCuffManager().isHandCuffed(player.getUniqueId())) { + } 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 { + } else { sender.sendMessage(Lang.NOTHANDCUFFED.get(player.getName())); } return true; } - public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception { - List results = new ArrayList(); - - for(Player p : jm.getPlugin().getServer().getOnlinePlayers()) - if(jm.getPlugin().getHandCuffManager().isHandCuffed(p.getUniqueId())) //don't send someone who isn't already handcuffed - if(args[0].isEmpty() || StringUtil.startsWithIgnoreCase(p.getName(), args[0])) + public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) { + List results = new ArrayList<>(); + + for (Player p : jm.getPlugin().getServer().getOnlinePlayers()) + if (jm.getPlugin().getHandCuffManager().isHandCuffed(p.getUniqueId())) //don't send someone who isn't already handcuffed + if (args[0].isEmpty() || StringUtil.startsWithIgnoreCase(p.getName(), args[0])) results.add(p.getName()); - + Collections.sort(results); - + return results; } } 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 8c598b9..61a226b 100644 --- a/src/main/java/com/graywolf336/jail/command/commands/UnJailCommand.java +++ b/src/main/java/com/graywolf336/jail/command/commands/UnJailCommand.java @@ -1,14 +1,5 @@ package com.graywolf336.jail.command.commands; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.util.StringUtil; - import com.graywolf336.jail.JailManager; import com.graywolf336.jail.beans.Jail; import com.graywolf336.jail.beans.Prisoner; @@ -18,6 +9,14 @@ import com.graywolf336.jail.enums.Lang; import com.graywolf336.jail.enums.Settings; import com.graywolf336.jail.exceptions.JailRequiredException; import com.graywolf336.jail.exceptions.PrisonerRequiredException; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; @CommandInfo( maxArgs = 1, @@ -26,29 +25,29 @@ import com.graywolf336.jail.exceptions.PrisonerRequiredException; pattern = "unjail|uj", permission = "jail.command.unjail", usage = "/unjail [player]" - ) +) public class UnJailCommand implements Command { public boolean execute(JailManager jm, CommandSender sender, String... args) throws JailRequiredException, PrisonerRequiredException { //Check if the player is jailed - if(jm.isPlayerJailedByLastKnownUsername(args[0])) { + 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) { + 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) { + if (pris.isOfflinePending() && pris.getRemainingTime() != 0L) { jm.getPlugin().getPrisonerManager().forceUnJail(j, j.getCellPrisonerIsIn(pris.getUUID()), p, pris, sender); - }else { + } 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 { + } else { //Player is online, so let's try unjailing them try { jm.getPlugin().getPrisonerManager().unJail(j, j.getCellPrisonerIsIn(pris.getUUID()), p, pris, sender); @@ -57,10 +56,10 @@ public class UnJailCommand implements Command { } } - if(jm.getPlugin().getConfig().getBoolean(Settings.LOGJAILINGTOCONSOLE.getPath())) { - jm.getPlugin().getLogger().info(ChatColor.stripColor(Lang.BROADCASTUNJAILING.get(new String[] { args[0], sender.getName() }))); + if (jm.getPlugin().getConfig().getBoolean(Settings.LOGJAILINGTOCONSOLE.getPath())) { + jm.getPlugin().getLogger().info(ChatColor.stripColor(Lang.BROADCASTUNJAILING.get(args[0], sender.getName()))); } - }else { + } else { //The player is not currently jailed sender.sendMessage(Lang.NOTJAILED.get(args[0])); } @@ -68,15 +67,15 @@ public class UnJailCommand implements Command { return true; } - public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception { - List results = new ArrayList(); - - for(Prisoner p : jm.getAllPrisoners().values()) - if(args[0].isEmpty() || StringUtil.startsWithIgnoreCase(p.getLastKnownName(), args[0])) + public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) { + List results = new ArrayList<>(); + + for (Prisoner p : jm.getAllPrisoners().values()) + if (args[0].isEmpty() || StringUtil.startsWithIgnoreCase(p.getLastKnownName(), args[0])) results.add(p.getLastKnownName()); - + Collections.sort(results); - + return results; } } 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 463e296..31a13c5 100644 --- a/src/main/java/com/graywolf336/jail/command/commands/UnJailForceCommand.java +++ b/src/main/java/com/graywolf336/jail/command/commands/UnJailForceCommand.java @@ -1,13 +1,5 @@ package com.graywolf336.jail.command.commands; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; -import org.bukkit.util.StringUtil; - import com.graywolf336.jail.JailManager; import com.graywolf336.jail.beans.Prisoner; import com.graywolf336.jail.command.Command; @@ -16,6 +8,13 @@ import com.graywolf336.jail.enums.Lang; import com.graywolf336.jail.enums.Settings; import com.graywolf336.jail.exceptions.JailRequiredException; import com.graywolf336.jail.exceptions.PrisonerRequiredException; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; @CommandInfo( maxArgs = 1, @@ -24,18 +23,18 @@ import com.graywolf336.jail.exceptions.PrisonerRequiredException; pattern = "unjailforce|ujf", permission = "jail.command.unjailforce", usage = "/unjailforce [player]" - ) +) public class UnJailForceCommand implements Command { public boolean execute(JailManager jm, CommandSender sender, String... args) throws JailRequiredException, PrisonerRequiredException { //Check if the player is jailed - if(jm.isPlayerJailedByLastKnownUsername(args[0])) { + 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() }))); + if (jm.getPlugin().getConfig().getBoolean(Settings.LOGJAILINGTOCONSOLE.getPath())) { + jm.getPlugin().getLogger().info(ChatColor.stripColor(Lang.BROADCASTUNJAILING.get(args[0], sender.getName()))); } - }else { + } else { //The player is not currently jailed sender.sendMessage(Lang.NOTJAILED.get(args[0])); } @@ -43,15 +42,15 @@ public class UnJailForceCommand implements Command { return true; } - public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception { - List results = new ArrayList(); - - for(Prisoner p : jm.getAllPrisoners().values()) - if(args[0].isEmpty() || StringUtil.startsWithIgnoreCase(p.getLastKnownName(), args[0])) + public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) { + List results = new ArrayList<>(); + + for (Prisoner p : jm.getAllPrisoners().values()) + if (args[0].isEmpty() || StringUtil.startsWithIgnoreCase(p.getLastKnownName(), args[0])) results.add(p.getLastKnownName()); - + Collections.sort(results); - + return results; } } 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 27472d1..6842ac9 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 @@ -1,44 +1,51 @@ package com.graywolf336.jail.command.commands.jewels; -import java.util.List; - import com.lexicalscope.jewel.cli.Option; +import java.util.List; + public interface Jailing { - @Option(longName={"player", "pl"}, shortName="p", description = "the player's name") - public String getPlayer(); - - @Option(longName={"force"}, shortName="f", description = "force jailing someone who has never been online") - public boolean getForce(); + @Option(longName = {"player", "pl"}, shortName = "p", description = "the player's name") + String getPlayer(); - @Option(longName={"time", "length"}, shortName="t", description = "the amount of time") - public String getTime(); - - @Option(longName={"forever", "eternity", "infinite"}, shortName="i", description = "jail the player for eternity") - public boolean getInfinite(); + @Option(longName = {"force"}, shortName = "f", description = "force jailing someone who has never been online") + boolean getForce(); - @Option(longName={"jail", "prison"}, shortName="j", description = "the jail") - public String getJail(); + @Option(longName = {"time", "length"}, shortName = "t", description = "the amount of time") + String getTime(); - @Option(longName={"cell"}, shortName="c", description = "the cell") - public String getCell(); + @Option(longName = {"forever", "eternity", "infinite"}, shortName = "i", description = "jail the player for eternity") + boolean getInfinite(); - @Option(longName={"anycell"}, shortName="a", description = "decides whether the plugin will pick any open cell") - public boolean getAnyCell(); + @Option(longName = {"jail", "prison"}, shortName = "j", description = "the jail") + String getJail(); - @Option(longName={"muted", "canttalk"}, shortName="m", description = "whether the prisoner is muted or not") - public boolean getMuted(); + @Option(longName = {"cell"}, shortName = "c", description = "the cell") + String getCell(); - @Option(longName={"reason"}, shortName="r", description = "the reason this player is being jailed") - public List getReason(); + @Option(longName = {"anycell"}, shortName = "a", description = "decides whether the plugin will pick any open cell") + boolean getAnyCell(); - public boolean isForce(); - public boolean isInfinite(); - public boolean isTime(); - public boolean isJail(); - public boolean isCell(); - public boolean isAnyCell(); - public boolean isMuted(); - public boolean isReason(); + @Option(longName = {"muted", "canttalk"}, shortName = "m", description = "whether the prisoner is muted or not") + boolean getMuted(); + + @Option(longName = {"reason"}, shortName = "r", description = "the reason this player is being jailed") + List getReason(); + + boolean isForce(); + + boolean isInfinite(); + + boolean isTime(); + + boolean isJail(); + + boolean isCell(); + + boolean isAnyCell(); + + boolean isMuted(); + + 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 739e267..09e315b 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 @@ -4,16 +4,18 @@ 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 = {"player", "pl"}, shortName = "p", description = "the player's name") + String getPlayer(); - @Option(longName={"jail", "prison"}, shortName="j", description = "the jail") - public String getJail(); + @Option(longName = {"jail", "prison"}, shortName = "j", description = "the jail") + String getJail(); - @Option(longName={"cell"}, shortName="c", description = "the cell") - public String getCell(); + @Option(longName = {"cell"}, shortName = "c", description = "the cell") + String getCell(); - public boolean isPlayer(); - public boolean isJail(); - public boolean isCell(); + boolean isPlayer(); + + boolean isJail(); + + 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 2af27f6..60ab579 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailCheckCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailCheckCommand.java @@ -1,20 +1,19 @@ package com.graywolf336.jail.command.subcommands; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - +import com.graywolf336.jail.JailManager; +import com.graywolf336.jail.Util; +import com.graywolf336.jail.beans.Prisoner; +import com.graywolf336.jail.command.Command; +import com.graywolf336.jail.command.CommandInfo; +import com.graywolf336.jail.enums.Lang; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.util.StringUtil; -import com.graywolf336.jail.JailManager; -import com.graywolf336.jail.beans.Prisoner; -import com.graywolf336.jail.command.Command; -import com.graywolf336.jail.command.CommandInfo; -import com.graywolf336.jail.Util; -import com.graywolf336.jail.enums.Lang; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; @CommandInfo( maxArgs = 1, @@ -23,44 +22,44 @@ import com.graywolf336.jail.enums.Lang; 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])) { + 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() + " (" + Util.getDurationBreakdown(p.getRemainingTime()) + " )"); - }else { + } else { sender.sendMessage(Lang.NOTJAILED.get(args[1])); } return true; } - public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception { - List results = new ArrayList(); - - for(Prisoner p : jm.getAllPrisoners().values()) { - if(args.length == 2 && StringUtil.startsWithIgnoreCase(p.getLastKnownName(), args[1].toLowerCase())) { + public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) { + List results = new ArrayList<>(); + + for (Prisoner p : jm.getAllPrisoners().values()) { + if (args.length == 2 && StringUtil.startsWithIgnoreCase(p.getLastKnownName(), args[1].toLowerCase())) { results.add(p.getLastKnownName()); - }else { + } else { results.add(p.getLastKnownName()); } } - + Collections.sort(results); - - if(args.length == 2) - for(Player p : jm.getPlugin().getServer().getOnlinePlayers()) - if(args[1].isEmpty() || StringUtil.startsWithIgnoreCase(p.getName(), args[1])) - if(!results.contains(p.getName())) + + if (args.length == 2) + for (Player p : jm.getPlugin().getServer().getOnlinePlayers()) + if (args[1].isEmpty() || StringUtil.startsWithIgnoreCase(p.getName(), args[1])) + if (!results.contains(p.getName())) results.add(p.getName()); - + return results; } } 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 4da2e1a..c4284d3 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailClearCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailClearCommand.java @@ -1,12 +1,5 @@ package com.graywolf336.jail.command.subcommands; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.bukkit.command.CommandSender; -import org.bukkit.util.StringUtil; - import com.graywolf336.jail.JailManager; import com.graywolf336.jail.beans.ConfirmPlayer; import com.graywolf336.jail.beans.Jail; @@ -14,6 +7,12 @@ import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Confirmation; import com.graywolf336.jail.enums.Lang; +import org.bukkit.command.CommandSender; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; @CommandInfo( maxArgs = 2, @@ -22,22 +21,24 @@ import com.graywolf336.jail.enums.Lang; 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")) + for (String s : args) + if (s.equalsIgnoreCase("-f") || s.equalsIgnoreCase("-force")) { force = true; + break; + } - if(jm.isConfirming(sender.getName())) { + if (jm.isConfirming(sender.getName())) { sender.sendMessage(Lang.ALREADY.get()); - }else if(force && sender.hasPermission("jail.command.jailclearforce")) { + } 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 { + } else { jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.CLEAR)); sender.sendMessage(Lang.START.get()); } @@ -45,20 +46,20 @@ public class JailClearCommand implements Command { return true; } - public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception { - List results = new ArrayList(); - - for(Jail j : jm.getJails()) { - if((args.length == 2 && StringUtil.startsWithIgnoreCase(j.getName(), args[1])) + public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) { + List results = new ArrayList<>(); + + for (Jail j : jm.getJails()) { + if ((args.length == 2 && StringUtil.startsWithIgnoreCase(j.getName(), args[1])) || (args.length == 3 && StringUtil.startsWithIgnoreCase(j.getName(), args[2]))) { results.add(j.getName()); - }else { + } else { results.add(j.getName()); } } - + Collections.sort(results); - + return results; } } 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 bcd3279..c36c750 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailCommand.java @@ -1,19 +1,5 @@ package com.graywolf336.jail.command.subcommands; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; - -import org.apache.commons.lang3.ArrayUtils; - -import org.bukkit.ChatColor; -import org.bukkit.OfflinePlayer; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.util.StringUtil; - import com.graywolf336.jail.JailManager; import com.graywolf336.jail.Util; import com.graywolf336.jail.beans.Cell; @@ -28,6 +14,18 @@ import com.graywolf336.jail.events.PrePrisonerJailedEvent; import com.graywolf336.jail.interfaces.ICell; import com.lexicalscope.jewel.cli.ArgumentValidationException; import com.lexicalscope.jewel.cli.CliFactory; +import org.apache.commons.lang.ArrayUtils; +import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; @CommandInfo( maxArgs = -1, @@ -36,14 +34,14 @@ import com.lexicalscope.jewel.cli.CliFactory; 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 { private static final String noJailPermission = "jail.cantbejailed"; - private List commands = Arrays.asList(new String[] { "p", "t", "i", "j", "c", "a", "m", "r", "f" }); + private final List commands = Arrays.asList("p", "t", "i", "j", "c", "a", "m", "r", "f"); /* * Executes the command. Checks the following: - * + * * - If there are any jails. * - If the command can be parsed correctly. * - If the player is already jailed. @@ -54,51 +52,51 @@ public class JailCommand implements Command { */ @SuppressWarnings("deprecation") public boolean execute(JailManager jm, CommandSender sender, String... args) { - if(jm.getJails().isEmpty()) { + 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)); + 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"); + if (!arguments.contains("-p")) arguments.add(0, "-p"); - Jailing params = null; + Jailing params; try { - params = CliFactory.parseArguments(Jailing.class, arguments.toArray(new String[arguments.size()])); - }catch(ArgumentValidationException e) { + params = CliFactory.parseArguments(Jailing.class, arguments.toArray(new String[0])); + } 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) { + if (params.getPlayer() == null) { sender.sendMessage(Lang.PROVIDEAPLAYER.get(Lang.JAILING)); return true; - }else { + } 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())) { + if (jm.isPlayerJailedByLastKnownUsername(params.getPlayer())) { sender.sendMessage(Lang.ALREADYJAILED.get(params.getPlayer())); return 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(noJailPermission)) { + if (p != null && p.hasPermission(noJailPermission)) { sender.sendMessage(Lang.CANTBEJAILED.get()); return true; } - - String uuid = ""; - if(p == null) { + + String uuid; + if (p == null) { if (!jm.getPlugin().getConfig().getBoolean(Settings.ALLOWJAILINGOFFLINEPLAYERS.getPath())) { sender.sendMessage(Lang.PLAYERHASNEVERPLAYEDBEFORE.get()); return true; @@ -106,34 +104,34 @@ public class JailCommand implements Command { //TODO: Make this whole jail command non-blocking OfflinePlayer of = jm.getPlugin().getServer().getOfflinePlayer(params.getPlayer()); - - if(!of.hasPlayedBefore() && !jm.getPlugin().getConfig().getBoolean(Settings.ALLOWJAILINGNEVERPLAYEDBEFOREPLAYERS.getPath()) && !params.isForce()) { + + if (!of.hasPlayedBefore() && !jm.getPlugin().getConfig().getBoolean(Settings.ALLOWJAILINGNEVERPLAYEDBEFOREPLAYERS.getPath()) && !params.isForce()) { sender.sendMessage(Lang.PLAYERHASNEVERPLAYEDBEFORE.get(params.getPlayer())); return true; - }else { + } else { uuid = of.getUniqueId().toString(); } - }else { + } else { uuid = p.getUniqueId().toString(); } //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; + Long time; try { - if(params.isTime()) { + if (params.isTime()) { time = Util.getTime(params.getTime()); - }else { + } else { time = Util.getTime(jm.getPlugin().getConfig().getString(Settings.DEFAULTTIME.getPath(), "30m")); } - }catch(Exception e) { + } catch (Exception e) { sender.sendMessage(Lang.NUMBERFORMATINCORRECT.get()); return true; } - + //Check if they provided the infinite argument //if so, then set the time jailed forever - if(params.isInfinite()) { + if (params.isInfinite()) { time = -1L; } @@ -141,65 +139,65 @@ public class JailCommand implements Command { //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 jailName; + if (!params.isJail()) { String dJail = jm.getPlugin().getConfig().getString(Settings.DEFAULTJAIL.getPath()); - if(dJail.equalsIgnoreCase("nearest")) { + if (dJail.equalsIgnoreCase("nearest")) { jailName = jm.getNearestJail(sender).getName(); - }else { + } else { jailName = dJail; } - }else if(!jm.isValidJail(params.getJail())) { + } else if (!jm.isValidJail(params.getJail())) { sender.sendMessage(Lang.NOJAIL.get(params.getJail())); return true; - }else { + } else { jailName = params.getJail(); } //Get the jail instance from the name of jail in the params. Jail j = jm.getJail(jailName); - if(!j.isEnabled()) { + if (!j.isEnabled()) { sender.sendMessage(Lang.WORLDUNLOADED.get(j.getName())); return true; } ICell c = null; //Check if the cell is defined - if(params.isCell()) { + if (params.isCell()) { //Check if it is a valid cell - if(!jm.getJail(jailName).isValidCell(params.getCell())) { + if (!jm.getJail(jailName).isValidCell(params.getCell())) { //There is no cell by that name - sender.sendMessage(Lang.NOCELL.get(new String[] { params.getCell(), jailName })); + sender.sendMessage(Lang.NOCELL.get(params.getCell(), jailName)); return true; - }else if(jm.getJail(jailName).getCell(params.getCell()).hasPrisoner()) { + } 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 { + if (suggestedCell != null) { + sender.sendMessage(Lang.SUGGESTEDCELL.get(jailName, suggestedCell.getName())); + } else { sender.sendMessage(Lang.NOEMPTYCELLS.get(jailName)); } return true; - }else { + } else { c = jm.getJail(jailName).getCell(params.getCell()); } } //If they want just any open cell or automatic jailing in cells is turned on //and a cell wasn't already found, then find try to find a cell - if(params.isAnyCell() && c == null) { + if (params.isAnyCell() && c == null) { c = jm.getJail(jailName).getFirstEmptyCell(); - if(c == null) { + if (c == null) { //If there wasn't an empty cell, then tell them so. sender.sendMessage(Lang.NOEMPTYCELLS.get(jailName)); return true; } - }else if(jm.getPlugin().getConfig().getBoolean(Settings.AUTOMATICCELL.getPath(), true) && j.hasCells() && c == null) { + } else if (jm.getPlugin().getConfig().getBoolean(Settings.AUTOMATICCELL.getPath(), true) && j.hasCells() && c == null) { c = jm.getJail(jailName).getFirstEmptyCell(); - if(c == null) { + if (c == null) { //If there wasn't an empty cell, then tell them so. sender.sendMessage(Lang.NOEMPTYCELLS.get(jailName)); return true; @@ -207,23 +205,23 @@ public class JailCommand implements Command { } //If the jailer gave no reason, then let's get the default reason - String reason = ""; - if(params.isReason()) { + String reason; + if (params.isReason()) { StringBuilder sb = new StringBuilder(); - for(String s : params.getReason()) { + for (String s : params.getReason()) { sb.append(s).append(' '); } sb.deleteCharAt(sb.length() - 1); reason = sb.toString(); - - }else { - reason = Lang.DEFAULTJAILEDREASON.get(); + + } else { + reason = Lang.DEFAULTJAILEDREASON.get(); } //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())) { + if (jm.getPlugin().getConfig().getBoolean(Settings.AUTOMATICMUTE.getPath())) { muted = true; } @@ -234,8 +232,8 @@ public class JailCommand implements Command { jm.getPlugin().getServer().getPluginManager().callEvent(event); //check if the event is cancelled - if(event.isCancelled()) { - if(event.getCancelledMessage().isEmpty()) + if (event.isCancelled()) { + if (event.getCancelledMessage().isEmpty()) sender.sendMessage(Lang.CANCELLEDBYANOTHERPLUGIN.get(params.getPlayer())); else sender.sendMessage(event.getCancelledMessage()); @@ -250,11 +248,11 @@ public class JailCommand implements Command { p = event.getPlayer(); //Player is not online - if(p == null) { - sender.sendMessage(Lang.OFFLINEJAIL.get(new String[] { pris.getLastKnownName(), String.valueOf(pris.getRemainingTimeInMinutes()) })); - }else { + if (p == null) { + sender.sendMessage(Lang.OFFLINEJAIL.get(pris.getLastKnownName(), String.valueOf(pris.getRemainingTimeInMinutes()))); + } else { //Player *is* online - sender.sendMessage(Lang.ONLINEJAIL.get(new String[] { pris.getLastKnownName(), String.valueOf(pris.getRemainingTimeInMinutes()) })); + sender.sendMessage(Lang.ONLINEJAIL.get(pris.getLastKnownName(), String.valueOf(pris.getRemainingTimeInMinutes()))); } try { @@ -267,71 +265,72 @@ public class JailCommand implements Command { return true; } - public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception { + public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) { //by the time it gets to this command it'll have at least two arguments String last = args[args.length - 1]; - + jm.getPlugin().debug("The last item is: " + last); - - if(last.isEmpty() || !commands.contains(last.replace("-", ""))) { + + if (last.isEmpty() || !commands.contains(last.replace("-", ""))) { //the current part is empty. Need to look at their previous //item and if it is a valid option, then provide them a valid tab complete option - if(args.length - 2 > -1) { + if (args.length - 2 > -1) { String previous = args[args.length - 2]; jm.getPlugin().debug("args[args.length - 2]: " + previous); - - if(previous.equalsIgnoreCase("-p")) return getPlayers(jm, last); - else if(previous.equalsIgnoreCase("-j")) return jm.getJailsByPrefix(last); - else if(previous.equalsIgnoreCase("-c")) { + + if (previous.equalsIgnoreCase("-p")) return getPlayers(jm, last); + else if (previous.equalsIgnoreCase("-j")) return jm.getJailsByPrefix(last); + else if (previous.equalsIgnoreCase("-c")) { //Since we need to give them a list of the cells in a jail //we need to get the jail they're giving int jailIndex = ArrayUtils.indexOf(args, "-j"); - if(jailIndex != -1) { + if (jailIndex != -1) { String jail = args[jailIndex + 1]; jm.getPlugin().debug("The jail is: " + jail); - if(jm.isValidJail(jail)) return getCells(jm, jail, last); + if (jm.isValidJail(jail)) return getCells(jm, jail, last); } - }else if(previous.endsWith("r")) return Collections.emptyList(); - else if(!commands.contains(args[args.length - 2].replace("-", ""))) return Util.getUnusedItems(commands, args, false); - }else { - return getPlayers(jm, last); + } else if (previous.endsWith("r")) return Collections.emptyList(); + else if (!commands.contains(args[args.length - 2].replace("-", ""))) + return Util.getUnusedItems(commands, args, false); + } else { + return getPlayers(jm, last); } - }else if(last.equalsIgnoreCase("-")) { + } else if (last.equalsIgnoreCase("-")) { //add some smart checking so that it only returns a list of what isn't already //in the command :) return Util.getUnusedItems(commands, args, false); - }else { - jm.getPlugin().debug("Getting the list of online players."); + } else { + jm.getPlugin().debug("Getting the list of online players."); return getPlayers(jm, last); } - + jm.getPlugin().debug("Returning an empty list."); return Collections.emptyList(); } - + private List getPlayers(JailManager jm, String first) { - List results = new ArrayList(); - - for(Player p : jm.getPlugin().getServer().getOnlinePlayers()) - if(first.isEmpty() || StringUtil.startsWithIgnoreCase(p.getName(), first)) - if(!jm.isPlayerJailed(p.getUniqueId()) && !p.hasPermission(noJailPermission)) //don't send back them if they're already jailed or can't be jailed + List results = new ArrayList<>(); + + for (Player p : jm.getPlugin().getServer().getOnlinePlayers()) + if (first.isEmpty() || StringUtil.startsWithIgnoreCase(p.getName(), first)) + if (!jm.isPlayerJailed(p.getUniqueId()) && !p.hasPermission(noJailPermission)) //don't send back them if they're already jailed or can't be jailed results.add(p.getName()); - + Collections.sort(results); jm.getPlugin().debug("The list we're returning is: " + Util.getStringFromList(", ", results)); - + return results; } - + private List getCells(JailManager jm, String jail, String cell) { - List results = new ArrayList(); - - for(Cell c : jm.getJail(jail).getCells()) - if(!c.hasPrisoner() && (cell.isEmpty() || StringUtil.startsWithIgnoreCase(c.getName(), cell))) - results.add(c.getName()); - + List results = new ArrayList<>(); + + for (Cell c : jm.getJail(jail).getCells()) + if (!c.hasPrisoner() && (cell.isEmpty() || StringUtil.startsWithIgnoreCase(c.getName(), cell))) + results.add(c.getName()); + Collections.sort(results); - + return results; } } 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 956f17f..81b9ea9 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailConfirmCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailConfirmCommand.java @@ -1,14 +1,13 @@ package com.graywolf336.jail.command.subcommands; -import java.util.Collections; -import java.util.List; - -import org.bukkit.command.CommandSender; - import com.graywolf336.jail.JailManager; import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Lang; +import org.bukkit.command.CommandSender; + +import java.util.Collections; +import java.util.List; @CommandInfo( maxArgs = 0, @@ -17,18 +16,18 @@ import com.graywolf336.jail.enums.Lang; pattern = "confirm|con", permission = "", usage = "/jail confirm" - ) -public class JailConfirmCommand implements Command{ +) +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())) { + if (jm.isConfirming(sender.getName())) { + if (jm.confirmingHasExpired(sender.getName())) { //Their confirmation time frame has closed sender.sendMessage(Lang.EXPIRED.get()); jm.removeConfirming(sender.getName()); - }else { - switch(jm.getWhatIsConfirming(sender.getName())) { + } else { + switch (jm.getWhatIsConfirming(sender.getName())) { case CLEAR: //Copy the original arguments for easy access String[] cArgs = jm.getOriginalArgs(sender.getName()); @@ -63,7 +62,7 @@ public class JailConfirmCommand implements Command{ //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) { + for (String s : msgs4) { sender.sendMessage(s); } @@ -84,7 +83,7 @@ public class JailConfirmCommand implements Command{ break; } } - }else { + } else { //They aren't confirming anything right now. sender.sendMessage(Lang.NOTHING.get()); } @@ -92,7 +91,7 @@ public class JailConfirmCommand implements Command{ return true; } - public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception { + public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) { //confirming doesn't require any tab completing return Collections.emptyList(); } 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 60ce243..c969ff9 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailCreateCellCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailCreateCellCommand.java @@ -1,16 +1,15 @@ package com.graywolf336.jail.command.subcommands; -import java.util.Collections; -import java.util.List; - -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - import com.graywolf336.jail.JailManager; import com.graywolf336.jail.beans.Jail; import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.CommandInfo; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.Collections; +import java.util.List; @CommandInfo( maxArgs = 2, @@ -19,7 +18,7 @@ import com.graywolf336.jail.command.CommandInfo; pattern = "createcells|createcell|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) { @@ -29,36 +28,36 @@ public class JailCreateCellCommand implements Command { String cell = ""; //Only get the cell name they provide if they provide it - if(args.length >= 3) { + if (args.length >= 3) { cell = args[2]; } //Check if the player is currently creating something else - if(jm.isCreatingSomething(name)) { + if (jm.isCreatingSomething(name)) { String message = jm.getStepMessage(name); - if(!message.isEmpty()) { + if (!message.isEmpty()) { player.sendMessage(ChatColor.RED + message); - }else { + } else { player.sendMessage(ChatColor.RED + "You're already creating something else, please finish it or cancel."); } - }else { + } else { //Not creating anything, so let them create some cells. - if(jm.isValidJail(jail)) { + 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 (cell.isEmpty()) cell = "cell_n" + (j.getCellCount() + 1); - if(j.getCell(cell) == null) { - if(jm.addCreatingCell(name, jail, cell)) { + if (j.getCell(cell) == null) { + if (jm.addCreatingCell(name, jail, cell)) { jm.getCellCreationSteps().startStepping(player); - }else { + } else { player.sendMessage(ChatColor.RED + "Appears you're creating a cell or something went wrong on our side."); } - }else { + } else { player.sendMessage(ChatColor.RED + "There's already a cell with the name '" + cell + "', please pick a new one or remove that cell."); } - }else { + } else { player.sendMessage(ChatColor.RED + "No such jail found by the name of '" + jail + "'."); } } @@ -66,10 +65,10 @@ public class JailCreateCellCommand implements Command { return true; } - public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception { + public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) { //We shouldn't provide when they want a cell name - if(args.length >= 3) return Collections.emptyList(); - + if (args.length >= 3) return Collections.emptyList(); + return jm.getJailsByPrefix(args.length == 2 ? args[1] : ""); } } 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 46e2ca9..205af4e 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailCreateCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailCreateCommand.java @@ -1,15 +1,14 @@ package com.graywolf336.jail.command.subcommands; -import java.util.Collections; -import java.util.List; - -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - import com.graywolf336.jail.JailManager; import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.CommandInfo; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.Collections; +import java.util.List; @CommandInfo( maxArgs = 1, @@ -18,7 +17,7 @@ import com.graywolf336.jail.command.CommandInfo; pattern = "create", permission = "jail.command.jailcreate", usage = "/jail create [name]" - ) +) public class JailCreateCommand implements Command { public boolean execute(JailManager jm, CommandSender sender, String... args) { @@ -27,20 +26,20 @@ public class JailCreateCommand implements Command { String jail = args[1]; //Check if the player is currently creating something else - if(jm.isCreatingSomething(name)) { + if (jm.isCreatingSomething(name)) { String message = jm.getStepMessage(name); - if(!message.isEmpty()) { + if (!message.isEmpty()) { player.sendMessage(ChatColor.RED + message); - }else { + } else { player.sendMessage(ChatColor.RED + "You're already creating something else, please finish it or cancel."); } - }else { - if(jm.isValidJail(jail)) { + } else { + if (jm.isValidJail(jail)) { player.sendMessage(ChatColor.RED + "Jail by the name of '" + jail + "' already exist!"); - }else { - if(jm.addCreatingJail(name, jail)) { + } else { + if (jm.addCreatingJail(name, jail)) { jm.getJailCreationSteps().startStepping(player); - }else { + } else { player.sendMessage(ChatColor.RED + "Seems like you're already creating a Jail or something went wrong on our side."); } } @@ -49,7 +48,7 @@ public class JailCreateCommand implements Command { return true; } - public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception { + public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) { //Creating a jail shouldn't provide tab completion return Collections.emptyList(); } 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 18c7110..6af3a5a 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailDeleteCellCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailDeleteCellCommand.java @@ -1,12 +1,5 @@ package com.graywolf336.jail.command.subcommands; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.bukkit.command.CommandSender; -import org.bukkit.util.StringUtil; - import com.graywolf336.jail.JailManager; import com.graywolf336.jail.beans.Cell; import com.graywolf336.jail.beans.ConfirmPlayer; @@ -15,6 +8,12 @@ import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Confirmation; import com.graywolf336.jail.enums.Lang; +import org.bukkit.command.CommandSender; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; @CommandInfo( maxArgs = 2, @@ -23,12 +22,12 @@ import com.graywolf336.jail.enums.Lang; 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())) { + public boolean execute(JailManager jm, CommandSender sender, String... args) { + if (jm.isConfirming(sender.getName())) { sender.sendMessage(Lang.ALREADY.get()); - }else { + } else { jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.DELETECELL)); sender.sendMessage(Lang.START.get()); } @@ -36,10 +35,10 @@ public class JailDeleteCellCommand implements Command { return true; } - public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception { - List results = new ArrayList(); - - switch(args.length) { + public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) { + List results = new ArrayList<>(); + + switch (args.length) { case 1: results.addAll(jm.getJailsByPrefix("")); break; @@ -47,18 +46,18 @@ public class JailDeleteCellCommand implements Command { results = jm.getJailsByPrefix(args[1]); break; case 3: - if(jm.isValidJail(args[1])) { + if (jm.isValidJail(args[1])) { Jail j = jm.getJail(args[1]); - - for(Cell c : j.getCells()) - if(args[2].isEmpty() || StringUtil.startsWithIgnoreCase(c.getName(), args[2])) + + for (Cell c : j.getCells()) + if (args[2].isEmpty() || StringUtil.startsWithIgnoreCase(c.getName(), args[2])) results.add(c.getName()); } break; } - + Collections.sort(results); - + return results; } } 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 cab8c21..6e5b4fb 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailDeleteCellsCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailDeleteCellsCommand.java @@ -1,15 +1,14 @@ package com.graywolf336.jail.command.subcommands; -import java.util.List; - -import org.bukkit.command.CommandSender; - import com.graywolf336.jail.JailManager; import com.graywolf336.jail.beans.ConfirmPlayer; import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Confirmation; import com.graywolf336.jail.enums.Lang; +import org.bukkit.command.CommandSender; + +import java.util.List; @CommandInfo( maxArgs = 1, @@ -18,12 +17,12 @@ import com.graywolf336.jail.enums.Lang; pattern = "deletecells|dcs", permission = "jail.command.jaildeletecells", 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())) { + public boolean execute(JailManager jm, CommandSender sender, String... args) { + if (jm.isConfirming(sender.getName())) { sender.sendMessage(Lang.ALREADY.get()); - }else { + } else { jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.DELETECELLS)); sender.sendMessage(Lang.START.get()); } @@ -31,7 +30,7 @@ public class JailDeleteCellsCommand implements Command { return true; } - public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception { + public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) { return jm.getJailsByPrefix(args.length == 2 ? args[1] : ""); } } 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 446e22f..7b88727 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailDeleteCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailDeleteCommand.java @@ -1,15 +1,14 @@ package com.graywolf336.jail.command.subcommands; -import java.util.List; - -import org.bukkit.command.CommandSender; - import com.graywolf336.jail.JailManager; import com.graywolf336.jail.beans.ConfirmPlayer; import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Confirmation; import com.graywolf336.jail.enums.Lang; +import org.bukkit.command.CommandSender; + +import java.util.List; @CommandInfo( maxArgs = 1, @@ -18,12 +17,12 @@ import com.graywolf336.jail.enums.Lang; 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())) { + public boolean execute(JailManager jm, CommandSender sender, String... args) { + if (jm.isConfirming(sender.getName())) { sender.sendMessage(Lang.ALREADY.get()); - }else { + } else { jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.DELETE)); sender.sendMessage(Lang.START.get()); } @@ -31,7 +30,7 @@ public class JailDeleteCommand implements Command { return true; } - public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception { + public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) { return jm.getJailsByPrefix(args.length == 2 ? args[1] : ""); } } diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailHelpCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailHelpCommand.java index 50811a1..e6872ac 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailHelpCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailHelpCommand.java @@ -1,14 +1,13 @@ package com.graywolf336.jail.command.subcommands; -import java.util.Collections; -import java.util.List; - -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; - import com.graywolf336.jail.JailManager; import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.CommandInfo; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; + +import java.util.Collections; +import java.util.List; @CommandInfo( maxArgs = 1, @@ -17,15 +16,15 @@ import com.graywolf336.jail.command.CommandInfo; pattern = "help|h", permission = "jail.command.jailhelp", usage = "/jail help [page]" - ) +) public class JailHelpCommand implements Command { - public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { + public boolean execute(JailManager jm, CommandSender sender, String... args) { sender.sendMessage(ChatColor.GREEN + "This command will be filled out shortly, use this link for now:"); sender.sendMessage(ChatColor.GREEN + "https://github.com/graywolf336/Jail/wiki/Commands"); return true; } - public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception { + public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) { //TODO implement return Collections.emptyList(); } 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 b1c7c79..d3889d1 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailListCellsCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailListCellsCommand.java @@ -1,12 +1,5 @@ package com.graywolf336.jail.command.subcommands; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; - import com.graywolf336.jail.JailManager; import com.graywolf336.jail.Util; import com.graywolf336.jail.beans.Cell; @@ -14,6 +7,12 @@ import com.graywolf336.jail.beans.Jail; import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Lang; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; @CommandInfo( maxArgs = 1, @@ -22,28 +21,28 @@ import com.graywolf336.jail.enums.Lang; pattern = "listcells|lc", permission = "jail.command.jaillistcells", usage = "/jail listcells [jail]" - ) +) public class JailListCellsCommand implements Command { public boolean execute(JailManager jm, CommandSender sender, String... args) { sender.sendMessage(ChatColor.AQUA + "----------Cells----------"); - if(!jm.getJails().isEmpty()) { - if(jm.getJail(args[1]) != null) { + if (!jm.getJails().isEmpty()) { + if (jm.getJail(args[1]) != null) { Jail j = jm.getJail(args[1]); - List cells = new ArrayList(); - - for(Cell c : j.getCells()) { + List cells = new ArrayList<>(); + + for (Cell c : j.getCells()) { cells.add(c.getName() + (c.getPrisoner() == null ? "" : " (" + c.getPrisoner().getLastKnownName() + ")")); } - + Collections.sort(cells); - + sender.sendMessage(cells.isEmpty() ? Lang.NOCELLS.get(j.getName()) : ChatColor.GREEN + Util.getStringFromList(", ", cells)); - }else { + } else { sender.sendMessage(Lang.NOJAIL.get(args[1])); } - }else { + } else { sender.sendMessage(Lang.NOJAILS.get()); } @@ -51,7 +50,7 @@ public class JailListCellsCommand implements Command { return true; } - public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception { + public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) { return jm.getJailsByPrefix(args.length == 2 ? args[1] : ""); } } 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 d22f17c..732e711 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailListCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailListCommand.java @@ -1,17 +1,16 @@ package com.graywolf336.jail.command.subcommands; -import java.util.Collection; -import java.util.List; - -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; - import com.graywolf336.jail.JailManager; import com.graywolf336.jail.beans.Jail; import com.graywolf336.jail.beans.Prisoner; import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Lang; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; + +import java.util.Collection; +import java.util.List; @CommandInfo( maxArgs = 1, @@ -20,36 +19,38 @@ import com.graywolf336.jail.enums.Lang; 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()) { + if (jm.getJails().isEmpty()) { sender.sendMessage(" " + Lang.NOJAILS.get()); - }else { + } else { //Check if they have provided a jail to list or not - if(args.length == 1) { + 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"); + 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 { + } else { Jail j = jm.getJail(args[1]); - if(j == null) { + if (j == null) { //No jail was found sender.sendMessage(" " + Lang.NOJAIL.get(args[1])); - }else { + } else { Collection pris = j.getAllPrisoners().values(); - if(pris.isEmpty()) { + if (pris.isEmpty()) { //If there are no prisoners, then send that message sender.sendMessage(" " + Lang.NOPRISONERS.get(j.getName())); - }else { - for(Prisoner p : pris) { + } 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)"); @@ -63,7 +64,7 @@ public class JailListCommand implements Command { return true; } - public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception { + public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) { return jm.getJailsByPrefix(args.length == 2 ? args[1] : ""); } } 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 e67c027..1c3099e 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailMuteCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailMuteCommand.java @@ -1,17 +1,16 @@ package com.graywolf336.jail.command.subcommands; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.util.StringUtil; - import com.graywolf336.jail.JailManager; import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Lang; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; @CommandInfo( maxArgs = 1, @@ -20,21 +19,21 @@ import com.graywolf336.jail.enums.Lang; 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 { + public boolean execute(JailManager jm, CommandSender sender, String... args) { //Let's check if the player they're sending us is jailed - if(jm.isPlayerJailedByLastKnownUsername(args[1])) { + 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) + if (muted) sender.sendMessage(Lang.NOWMUTED.get(args[1])); else sender.sendMessage(Lang.NOWUNMUTED.get(args[1])); - }else { + } else { //The player provided is not jailed, so let's tell the sender that sender.sendMessage(Lang.NOTJAILED.get(args[1])); } @@ -42,18 +41,16 @@ public class JailMuteCommand implements Command { return true; } - public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception { - switch(args.length) { - case 2: - List results = new ArrayList(); - for(Player p : jm.getPlugin().getServer().getOnlinePlayers()) - if(StringUtil.startsWithIgnoreCase(p.getName(), args[1].toLowerCase())) - results.add(p.getName()); - - Collections.sort(results); - return results; - default: - return Collections.emptyList(); + public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) { + if (args.length == 2) { + List results = new ArrayList<>(); + for (Player p : jm.getPlugin().getServer().getOnlinePlayers()) + if (StringUtil.startsWithIgnoreCase(p.getName(), args[1].toLowerCase())) + results.add(p.getName()); + + Collections.sort(results); + return results; } + return Collections.emptyList(); } } 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 91509de..a11208c 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailPayCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailPayCommand.java @@ -1,15 +1,5 @@ package com.graywolf336.jail.command.subcommands; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.util.StringUtil; - import com.graywolf336.jail.JailManager; import com.graywolf336.jail.beans.Prisoner; import com.graywolf336.jail.command.Command; @@ -17,6 +7,15 @@ import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Lang; import com.graywolf336.jail.enums.Settings; import com.graywolf336.jail.interfaces.IJailPayManager; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.TimeUnit; @CommandInfo( maxArgs = 2, @@ -25,42 +24,42 @@ import com.graywolf336.jail.interfaces.IJailPayManager; 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())) { + public boolean execute(JailManager jm, CommandSender sender, String... args) { + if (jm.getPlugin().getConfig().getBoolean(Settings.JAILPAYENABLED.getPath())) { IJailPayManager pm = jm.getPlugin().getJailPayManager(); - switch(args.length) { + switch (args.length) { case 1: // `/jail pay` //send how much it costs to get out - if(jm.isPlayerJailedByLastKnownUsername(sender.getName())) { + if (jm.isPlayerJailedByLastKnownUsername(sender.getName())) { Prisoner p = jm.getPrisonerByLastKnownName(sender.getName()); - String amt = ""; + String amt; - if(pm.usingItemsForPayment()) { + if (pm.usingItemsForPayment()) { amt = String.valueOf((int) Math.ceil(pm.calculateBill(p))); - }else { + } 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 { + if (p.getRemainingTime() > 0) { + if (pm.isTimedEnabled()) { + sender.sendMessage(Lang.PAYCOST.get(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 { + } else { + if (pm.isInfiniteEnabled()) { + sender.sendMessage(Lang.PAYCOST.get(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 { + } else { sender.sendMessage(Lang.YOUARENOTJAILED.get()); } @@ -68,133 +67,133 @@ public class JailPayCommand implements Command { case 2: // `/jail pay ` //They are trying to pay for their self - if(jm.isPlayerJailedByLastKnownUsername(sender.getName())) { + if (jm.isPlayerJailedByLastKnownUsername(sender.getName())) { Prisoner p = jm.getPrisonerByLastKnownName(sender.getName()); - if(p.getRemainingTime() > 0) { - if(!pm.isTimedEnabled()) { + if (p.getRemainingTime() > 0) { + if (!pm.isTimedEnabled()) { sender.sendMessage(Lang.PAYNOTENABLED.get()); return true; } - }else { - if(!pm.isInfiniteEnabled()) { + } else { + if (!pm.isInfiniteEnabled()) { sender.sendMessage(Lang.PAYNOTENABLED.get()); return true; } } - if(args[1].startsWith("-")) { + if (args[1].startsWith("-")) { sender.sendMessage(Lang.PAYNONEGATIVEAMOUNTS.get()); - }else { - double amt = 0; + } else { + double amt; try { amt = Double.parseDouble(args[1]); - }catch(NumberFormatException e) { + } catch (NumberFormatException e) { sender.sendMessage(ChatColor.RED + " must be a number."); throw e; } - if(pm.hasEnoughToPay((Player) sender, amt)) { + if (pm.hasEnoughToPay((Player) sender, amt)) { double bill = pm.calculateBill(p); - if(p.getRemainingTime() > 0) { + if (p.getRemainingTime() > 0) { //timed sentence - if(amt >= bill) { + if (amt >= bill) { pm.pay((Player) sender, bill); sender.sendMessage(Lang.PAYPAIDRELEASED.get(String.valueOf(bill))); jm.getPlugin().getPrisonerManager().schedulePrisonerRelease(p); - }else { + } 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)) })); + sender.sendMessage(Lang.PAYPAIDLOWEREDTIME.get(String.valueOf(amt), String.valueOf(TimeUnit.MINUTES.convert(remain, TimeUnit.MILLISECONDS)))); } - }else { + } else { //infinite jailing - if(amt >= bill) { + if (amt >= bill) { pm.pay((Player) sender, bill); sender.sendMessage(Lang.PAYPAIDRELEASED.get(String.valueOf(bill))); jm.getPlugin().getPrisonerManager().schedulePrisonerRelease(p); - }else { + } else { //You haven't provided enough money to get them out sender.sendMessage(Lang.PAYNOTENOUGHMONEYPROVIDED.get()); } } - }else { + } else { sender.sendMessage(Lang.PAYNOTENOUGHMONEY.get()); } } - }else { + } else { sender.sendMessage(Lang.YOUARENOTJAILED.get()); } break; case 3: // `/jail pay //they are trying to pay for someone else - if(jm.isPlayerJailedByLastKnownUsername(sender.getName())) { + 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])) { + } else { + if (jm.isPlayerJailedByLastKnownUsername(args[2])) { Prisoner p = jm.getPrisonerByLastKnownName(args[2]); - if(p.isJailedForever()) { - if(!pm.isInfiniteEnabled()) { + if (p.isJailedForever()) { + if (!pm.isInfiniteEnabled()) { sender.sendMessage(Lang.PAYNOTENABLED.get()); return true; } - }else { - if(!pm.isTimedEnabled()) { + } else { + if (!pm.isTimedEnabled()) { sender.sendMessage(Lang.PAYNOTENABLED.get()); return true; } } - if(args[1].startsWith("-")) { + if (args[1].startsWith("-")) { sender.sendMessage(Lang.PAYNONEGATIVEAMOUNTS.get()); - }else { - double amt = 0; + } else { + double amt; try { amt = Double.parseDouble(args[1]); - }catch(NumberFormatException e) { + } catch (NumberFormatException e) { sender.sendMessage(ChatColor.RED + " must be a number."); throw e; } - if(pm.hasEnoughToPay((Player) sender, amt)) { + if (pm.hasEnoughToPay((Player) sender, amt)) { double bill = pm.calculateBill(p); - if(p.getRemainingTime() > 0) { + if (p.getRemainingTime() > 0) { //timed sentence - if(amt >= bill) { + if (amt >= bill) { pm.pay((Player) sender, bill); - sender.sendMessage(Lang.PAYPAIDRELEASEDELSE.get(new String[] { String.valueOf(bill), p.getLastKnownName() })); + sender.sendMessage(Lang.PAYPAIDRELEASEDELSE.get(String.valueOf(bill), p.getLastKnownName())); jm.getPlugin().getPrisonerManager().schedulePrisonerRelease(p); - }else { + } 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)) })); + sender.sendMessage(Lang.PAYPAIDLOWEREDTIMEELSE.get(String.valueOf(amt), p.getLastKnownName(), String.valueOf(TimeUnit.MINUTES.convert(remain, TimeUnit.MILLISECONDS)))); } - }else { + } else { //infinite jailing - if(amt >= bill) { + if (amt >= bill) { pm.pay((Player) sender, bill); - sender.sendMessage(Lang.PAYPAIDRELEASEDELSE.get(new String[] { String.valueOf(bill), p.getLastKnownName() })); + sender.sendMessage(Lang.PAYPAIDRELEASEDELSE.get(String.valueOf(bill), p.getLastKnownName())); jm.getPlugin().getPrisonerManager().schedulePrisonerRelease(p); - }else { + } else { //You haven't provided enough money to get them out sender.sendMessage(Lang.PAYNOTENOUGHMONEYPROVIDED.get()); } } - }else { + } else { sender.sendMessage(Lang.PAYNOTENOUGHMONEY.get()); } } - }else { + } else { //Person they're trying to pay for is not jailed sender.sendMessage(Lang.NOTJAILED.get(args[2])); } @@ -203,7 +202,7 @@ public class JailPayCommand implements Command { default: return false; } - }else { + } else { jm.getPlugin().debug("Jail pay not enabled."); sender.sendMessage(Lang.PAYNOTENABLED.get()); } @@ -211,25 +210,22 @@ public class JailPayCommand implements Command { return true; } - public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception { - if(jm.getPlugin().getConfig().getBoolean(Settings.JAILPAYENABLED.getPath())) { - switch(args.length) { - case 3: - List results = new ArrayList(); - for(Prisoner p : jm.getAllPrisoners().values()) - if(!p.isOfflinePending()) //Don't list if they're offline pending - if(p.getRemainingTime() != -1) //Don't list if they're jailed forever - if(StringUtil.startsWithIgnoreCase(p.getLastKnownName(), args[2])) - results.add(p.getLastKnownName()); - - Collections.sort(results); - - return results; - default: - break; + public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) { + if (jm.getPlugin().getConfig().getBoolean(Settings.JAILPAYENABLED.getPath())) { + if (args.length == 3) { + List results = new ArrayList<>(); + for (Prisoner p : jm.getAllPrisoners().values()) + if (!p.isOfflinePending()) //Don't list if they're offline pending + if (p.getRemainingTime() != -1) //Don't list if they're jailed forever + if (StringUtil.startsWithIgnoreCase(p.getLastKnownName(), args[2])) + results.add(p.getLastKnownName()); + + Collections.sort(results); + + return results; } } - + return Collections.emptyList(); } } 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 3228c12..4bebd34 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailRecordCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailRecordCommand.java @@ -1,14 +1,13 @@ package com.graywolf336.jail.command.subcommands; -import java.util.Collections; -import java.util.List; - -import org.bukkit.command.CommandSender; - import com.graywolf336.jail.JailManager; import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Lang; +import org.bukkit.command.CommandSender; + +import java.util.Collections; +import java.util.List; @CommandInfo( maxArgs = 2, @@ -17,26 +16,26 @@ import com.graywolf336.jail.enums.Lang; pattern = "record|r", permission = "jail.command.jailrecord", usage = "/jail record [name] (display)" - ) +) public class JailRecordCommand implements Command { @SuppressWarnings("deprecation") public boolean execute(JailManager jm, CommandSender sender, String... args) { - if(args.length == 2) { + 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) { + sender.sendMessage(Lang.RECORDTIMESJAILED.get(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) { + for (String s : entries) { sender.sendMessage(s); } - sender.sendMessage(Lang.RECORDTIMESJAILED.get(new String[] { args[1], String.valueOf(entries.size()) })); - }else { + sender.sendMessage(Lang.RECORDTIMESJAILED.get(args[1], String.valueOf(entries.size()))); + } else { //They didn't do the command right //send them back to get the usage return false; @@ -45,7 +44,7 @@ public class JailRecordCommand implements Command { return true; } - public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception { + public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) { //We won't be implementing tab complete on this for now (unless requested) return Collections.emptyList(); } 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 60f4f4d..64e4315 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailReloadCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailReloadCommand.java @@ -1,15 +1,14 @@ package com.graywolf336.jail.command.subcommands; -import java.util.Collections; -import java.util.List; - -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; - import com.graywolf336.jail.JailManager; import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Lang; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; + +import java.util.Collections; +import java.util.List; @CommandInfo( maxArgs = 0, @@ -18,13 +17,13 @@ import com.graywolf336.jail.enums.Lang; 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().reloadEverything(); sender.sendMessage(Lang.PLUGINRELOADED.get()); - }catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); sender.sendMessage(ChatColor.RED + "Failed to reload due to (see the console): " + e.getMessage()); } @@ -32,7 +31,7 @@ public class JailReloadCommand implements Command { return true; } - public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception { + public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) { //Reloading the plugin doesn't require tab completions return Collections.emptyList(); } diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailSignsCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailSignsCommand.java index 8f6d951..2d154e7 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailSignsCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailSignsCommand.java @@ -1,14 +1,5 @@ package com.graywolf336.jail.command.subcommands; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map.Entry; - -import org.bukkit.command.CommandSender; -import org.bukkit.util.StringUtil; - import com.graywolf336.jail.JailManager; import com.graywolf336.jail.Util; import com.graywolf336.jail.beans.Cell; @@ -16,6 +7,14 @@ import com.graywolf336.jail.beans.Jail; import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Lang; +import org.bukkit.command.CommandSender; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map.Entry; @CommandInfo( maxArgs = -1, @@ -24,48 +23,48 @@ import com.graywolf336.jail.enums.Lang; pattern = "signs", permission = "jail.command.jailsigns", usage = "/jail signs [clean|refresh|update|verify] [jail] (cell)..." - ) +) public class JailSignsCommand implements Command { - private static final String[] options = new String[] { "clean", "refresh", "update", "verify" }; + private static final String[] options = new String[]{"clean", "refresh", "update", "verify"}; - public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { - if(!jm.isValidJail(args[2])) { + public boolean execute(JailManager jm, CommandSender sender, String... args) { + if (!jm.isValidJail(args[2])) { sender.sendMessage(" " + Lang.NOJAIL.get(args[1])); return true; } Jail j = jm.getJail(args[2]); - HashMap> items = new HashMap>(); + HashMap> items = new HashMap<>(); - if(args[1].equalsIgnoreCase("clean")) { + if (args[1].equalsIgnoreCase("clean")) { //if they type clean, we can remove all signs which are no longer signs //then provide them a list of signs which got cleaned up - for(Cell c : j.getCells()) { - if(Util.isStringInsideArray(c.getName(), args) || args.length == 3) { - if(c.hasSigns()) { + for (Cell c : j.getCells()) { + if (Util.isStringInsideArray(c.getName(), args) || args.length == 3) { + if (c.hasSigns()) { List cleaned = c.cleanSigns(); - if(!cleaned.isEmpty()) { + if (!cleaned.isEmpty()) { items.put(c.getName(), cleaned); } } } } - if(items.isEmpty()) { + if (items.isEmpty()) { sender.sendMessage(Lang.NOINVALIDSIGNS.get()); - }else { + } else { sender.sendMessage(Lang.CLEANEDSIGNS.get()); - for(Entry> e : items.entrySet()) { + for (Entry> e : items.entrySet()) { sender.sendMessage(" " + e.getKey()); - for(String s : e.getValue()) + for (String s : e.getValue()) sender.sendMessage(" Sign: " + s); } } return true; - }else if(args[1].equalsIgnoreCase("refresh") || args[1].equalsIgnoreCase("update")) { + } else if (args[1].equalsIgnoreCase("refresh") || args[1].equalsIgnoreCase("update")) { //if they type refresh, we will go through all the signs and update them to //display the correct message on the sign whether empty or time @@ -73,8 +72,8 @@ public class JailSignsCommand implements Command { int updated = 0; int removed = 0; - for(Cell c : j.getCells()) { - if(Util.isStringInsideArray(c.getName(), args) || args.length == 3) { + for (Cell c : j.getCells()) { + if (Util.isStringInsideArray(c.getName(), args) || args.length == 3) { HashMap> results = c.updateSigns(); updated += results.get("updated").size(); removed += results.get("removed").size(); @@ -82,53 +81,53 @@ public class JailSignsCommand implements Command { } } - sender.sendMessage(Lang.SIGNSREFRESHED.get(new String[] { String.valueOf(updated), String.valueOf(removed), String.valueOf(cells) })); + sender.sendMessage(Lang.SIGNSREFRESHED.get(String.valueOf(updated), String.valueOf(removed), String.valueOf(cells))); return true; - }else if(args[1].equalsIgnoreCase("verify")) { + } else if (args[1].equalsIgnoreCase("verify")) { //if they type verify, we will go through all the signs and then provide them //as a list of cells which have signs that aren't actually signs and provide //the location where the signs are - for(Cell c : j.getCells()) { - if(Util.isStringInsideArray(c.getName(), args) || args.length == 3) { + for (Cell c : j.getCells()) { + if (Util.isStringInsideArray(c.getName(), args) || args.length == 3) { List invalids = c.getInvalidSigns(); - if(!invalids.isEmpty()) { + if (!invalids.isEmpty()) { items.put(c.getName(), invalids); } } } - if(items.isEmpty()) { + if (items.isEmpty()) { sender.sendMessage(Lang.NOINVALIDSIGNS.get()); - }else { + } else { sender.sendMessage(Lang.INVALIDSIGNS.get()); - for(Entry> e : items.entrySet()) { + for (Entry> e : items.entrySet()) { sender.sendMessage(" " + e.getKey()); - for(String s : e.getValue()) + for (String s : e.getValue()) sender.sendMessage(" " + Lang.SIGN.get() + ": " + s); } } return true; - }else + } else return false; } - public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception { - List results = new ArrayList(); + public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) { + List results = new ArrayList<>(); - switch(args.length) { + switch (args.length) { case 2: - for(String s : options) - if(args[1].isEmpty() || StringUtil.startsWithIgnoreCase(s, args[1])) + for (String s : options) + if (args[1].isEmpty() || StringUtil.startsWithIgnoreCase(s, args[1])) results.add(s); break; case 3: results.addAll(jm.getJailsByPrefix(args[2])); break; default: - if(jm.isValidJail(args[2])) - for(Cell c : jm.getJail(args[2]).getCells()) - if(!Util.isStringInsideArray(c.getName(), args)) + if (jm.isValidJail(args[2])) + for (Cell c : jm.getJail(args[2]).getCells()) + if (!Util.isStringInsideArray(c.getName(), args)) results.add(c.getName()); break; } 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 58b7181..4792ee9 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailStatusCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailStatusCommand.java @@ -1,17 +1,16 @@ package com.graywolf336.jail.command.subcommands; -import java.util.Collections; -import java.util.List; - -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - import com.graywolf336.jail.JailManager; import com.graywolf336.jail.Util; import com.graywolf336.jail.beans.Prisoner; import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Lang; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.Collections; +import java.util.List; @CommandInfo( maxArgs = 0, @@ -20,17 +19,17 @@ import com.graywolf336.jail.enums.Lang; pattern = "status|s", permission = "jail.usercmd.jailstatus", usage = "/jail status" - ) -public class JailStatusCommand implements Command{ +) +public class JailStatusCommand implements Command { public boolean execute(JailManager jm, CommandSender sender, String... args) { Player pl = (Player) sender; - if(jm.isPlayerJailed(pl.getUniqueId())) { + 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()), Util.getDurationBreakdown(p.getRemainingTime()) })); - }else { + sender.sendMessage(Lang.STATUS.get(p.getReason(), p.getJailer(), String.valueOf(p.getRemainingTimeInMinutes()), Util.getDurationBreakdown(p.getRemainingTime()))); + } else { //the sender of the command is not jailed, tell them that sender.sendMessage(Lang.YOUARENOTJAILED.get()); } @@ -38,7 +37,7 @@ public class JailStatusCommand implements Command{ return true; } - public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception { + public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) { //Checking your jail status doesn't require tab completion return Collections.emptyList(); } 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 e5cdf69..9e08bf5 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailStickCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailStickCommand.java @@ -1,16 +1,15 @@ package com.graywolf336.jail.command.subcommands; -import java.util.Collections; -import java.util.List; - -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - import com.graywolf336.jail.JailManager; import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Lang; import com.graywolf336.jail.enums.Settings; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.Collections; +import java.util.List; @CommandInfo( maxArgs = 0, @@ -19,25 +18,25 @@ import com.graywolf336.jail.enums.Settings; 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())) { + public boolean execute(JailManager jm, CommandSender sender, String... args) { + if (jm.getPlugin().getConfig().getBoolean(Settings.JAILSTICKENABLED.getPath())) { boolean using = jm.getPlugin().getJailStickManager().toggleUsingStick(((Player) sender).getUniqueId()); - if(using) { + if (using) { sender.sendMessage(Lang.JAILSTICKENABLED.get()); - }else { + } else { sender.sendMessage(Lang.JAILSTICKDISABLED.get()); } - }else { + } else { sender.sendMessage(Lang.JAILSTICKUSAGEDISABLED.get()); } return true; } - public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception { + public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) { //Nothing to tab complete on jail stick return Collections.emptyList(); } 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 9e6282b..5c5e09e 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailStopCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailStopCommand.java @@ -1,14 +1,13 @@ package com.graywolf336.jail.command.subcommands; -import java.util.Collections; -import java.util.List; - -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; - import com.graywolf336.jail.JailManager; import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.CommandInfo; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; + +import java.util.Collections; +import java.util.List; @CommandInfo( maxArgs = 0, @@ -17,31 +16,31 @@ import com.graywolf336.jail.command.CommandInfo; 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())) { + 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())) { + if (jm.isCreatingAJail(sender.getName())) { jm.removeJailCreationPlayer(sender.getName()); sender.sendMessage(ChatColor.RED + "You have stopped creating a jail."); nothing = false; } - if(nothing) { + if (nothing) { sender.sendMessage(ChatColor.RED + "You've stopped creating....nothing."); } return true; } - public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception { + public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) { //no tab completion required for stop command return Collections.emptyList(); } 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 5acde7b..e278ab1 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailTeleInCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailTeleInCommand.java @@ -1,18 +1,17 @@ package com.graywolf336.jail.command.subcommands; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.util.StringUtil; - import com.graywolf336.jail.JailManager; import com.graywolf336.jail.beans.Jail; import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Lang; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; @CommandInfo( maxArgs = 2, @@ -21,35 +20,34 @@ import com.graywolf336.jail.enums.Lang; pattern = "teleportin|telein", permission = "jail.command.jailtelein", usage = "/jail telein [jail] (name)" - ) +) public class JailTeleInCommand implements Command { - @SuppressWarnings("deprecation") - public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { + public boolean execute(JailManager jm, CommandSender sender, String... args) { Jail j = jm.getJail(args[1]); //The jail doesn't exist - if(j == null) { + if (j == null) { sender.sendMessage(Lang.NOJAIL.get(args[1])); - }else { + } 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) { + 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) { + if (p == null) { sender.sendMessage(Lang.PLAYERNOTONLINE.get(args[2])); - }else { + } else { p.teleport(j.getTeleportIn()); - sender.sendMessage(Lang.TELEIN.get(new String[] { args[2], args[1] })); + sender.sendMessage(Lang.TELEIN.get(args[2], args[1])); } - }else { - if(sender instanceof Player) { + } 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.TELEIN.get(sender.getName(), args[1])); + } else { sender.sendMessage(Lang.PLAYERCONTEXTREQUIRED.get()); } } @@ -58,19 +56,19 @@ public class JailTeleInCommand implements Command { return true; } - public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception { - switch(args.length) { + public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) { + switch (args.length) { case 2: return jm.getJailsByPrefix(args[1]); case 3: - List results = new ArrayList(); - - for(Player p : jm.getPlugin().getServer().getOnlinePlayers()) - if(args[2].isEmpty() || StringUtil.startsWithIgnoreCase(p.getName(), args[2])) + List results = new ArrayList<>(); + + for (Player p : jm.getPlugin().getServer().getOnlinePlayers()) + if (args[2].isEmpty() || StringUtil.startsWithIgnoreCase(p.getName(), args[2])) results.add(p.getName()); - + Collections.sort(results); - + return results; default: return Collections.emptyList(); 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 fbf0c80..b33709d 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailTeleOutCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailTeleOutCommand.java @@ -1,18 +1,17 @@ package com.graywolf336.jail.command.subcommands; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.util.StringUtil; - import com.graywolf336.jail.JailManager; import com.graywolf336.jail.beans.Jail; import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Lang; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; @CommandInfo( maxArgs = 2, @@ -21,35 +20,34 @@ import com.graywolf336.jail.enums.Lang; pattern = "teleportout|teleout", permission = "jail.command.jailteleout", usage = "/jail teleout [jail] (name)" - ) +) public class JailTeleOutCommand implements Command { - @SuppressWarnings("deprecation") - public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { + public boolean execute(JailManager jm, CommandSender sender, String... args) { Jail j = jm.getJail(args[1]); //The jail doesn't exist - if(j == null) { + if (j == null) { sender.sendMessage(Lang.NOJAIL.get(args[1])); - }else { + } 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) { + 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) { + if (p == null) { sender.sendMessage(Lang.PLAYERNOTONLINE.get(args[2])); - }else { + } else { p.teleport(j.getTeleportFree()); - sender.sendMessage(Lang.TELEOUT.get(new String[] { args[2], args[1] })); + sender.sendMessage(Lang.TELEOUT.get(args[2], args[1])); } - }else { - if(sender instanceof Player) { + } 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.TELEOUT.get(sender.getName(), args[1])); + } else { sender.sendMessage(Lang.PLAYERCONTEXTREQUIRED.get()); } } @@ -58,19 +56,19 @@ public class JailTeleOutCommand implements Command { return true; } - public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception { - switch(args.length) { + public List provideTabCompletions(JailManager jm, CommandSender sender, String... args) { + switch (args.length) { case 2: return jm.getJailsByPrefix(args[1]); case 3: - List results = new ArrayList(); - - for(Player p : jm.getPlugin().getServer().getOnlinePlayers()) - if(args[2].isEmpty() || StringUtil.startsWithIgnoreCase(p.getName(), args[2])) + List results = new ArrayList<>(); + + for (Player p : jm.getPlugin().getServer().getOnlinePlayers()) + if (args[2].isEmpty() || StringUtil.startsWithIgnoreCase(p.getName(), args[2])) results.add(p.getName()); - + Collections.sort(results); - + return results; default: return Collections.emptyList(); 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 b0e9948..86ce334 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailTimeCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailTimeCommand.java @@ -1,18 +1,17 @@ package com.graywolf336.jail.command.subcommands; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.bukkit.command.CommandSender; -import org.bukkit.util.StringUtil; - import com.graywolf336.jail.JailManager; import com.graywolf336.jail.Util; import com.graywolf336.jail.beans.Prisoner; import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.enums.Lang; +import org.bukkit.command.CommandSender; +import org.bukkit.util.StringUtil; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; @CommandInfo( maxArgs = 3, @@ -21,65 +20,65 @@ import com.graywolf336.jail.enums.Lang; pattern = "time|t", permission = "jail.command.jailtime", usage = "/jail time [add|remove|set|show] [name]